Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x | /**
* BuildHive API Client
*
* HTTP client for communicating with the BuildHive platform REST API.
* Handles agent registration, authentication, and heartbeat updates.
*
* Requirements: MVP.4.1.2
*/
import axios, { AxiosInstance } from 'axios';
import { createLogger } from '../utils/logger.js';
import {
RegistrationRequest,
RegistrationResponse,
AuthenticationRequest,
AuthenticationResponse,
} from './types.js';
const logger = createLogger('apiClient');
export interface HeartbeatRequest {
agentId: string;
status: 'ONLINE' | 'OFFLINE' | 'BUSY' | 'MAINTENANCE';
currentLoad: number;
activeJobs: number;
cpuUsage?: number;
memoryUsage?: number;
diskUsage?: number;
}
export class BuildHiveApiClient {
private client: AxiosInstance;
private platformUrl: string;
constructor(platformUrl: string) {
this.platformUrl = platformUrl;
this.client = axios.create({
baseURL: platformUrl,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'BuildHive-Agent/1.0.0',
},
});
// Add request interceptor for logging
this.client.interceptors.request.use(
(config) => {
logger.debug(`API Request: ${config.method?.toUpperCase()} ${config.url}`);
return config;
},
(error) => {
logger.error('API Request Error:', error);
return Promise.reject(error);
}
);
// Add response interceptor for logging
this.client.interceptors.response.use(
(response) => {
logger.debug(`API Response: ${response.status} ${response.config.url}`);
return response;
},
(error) => {
if (axios.isAxiosError(error)) {
logger.error(
`API Error: ${error.response?.status} ${error.config?.url} - ${
error.response?.data?.message || error.message
}`
);
}
return Promise.reject(error);
}
);
}
/**
* Register agent with the BuildHive platform
*/
async register(request: RegistrationRequest): Promise<RegistrationResponse> {
logger.info('Registering agent with BuildHive platform');
try {
const response = await this.client.post<RegistrationResponse>(
'/api/agents/register',
request
);
logger.info('Agent registered successfully', {
agentId: response.data.agentId,
expiresAt: response.data.expiresAt,
});
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
const message = error.response?.data?.message || error.message;
const statusCode = error.response?.status;
logger.error(`Registration failed [${statusCode}]: ${message}`);
if (statusCode === 409) {
throw new Error('Agent already registered with this machine ID');
} else if (statusCode === 400) {
throw new Error(`Invalid registration data: ${message}`);
} else if (statusCode === 401 || statusCode === 403) {
throw new Error('Authentication failed - check your API credentials');
} else if (statusCode && statusCode >= 500) {
throw new Error('Server error during registration - please try again later');
}
throw new Error(`Registration failed: ${message}`);
}
throw error;
}
}
/**
* Authenticate agent and get JWT token
*/
async authenticate(request: AuthenticationRequest): Promise<AuthenticationResponse> {
logger.info('Authenticating agent');
try {
const response = await this.client.post<AuthenticationResponse>(
'/api/agents/auth',
request
);
logger.info('Agent authenticated successfully', {
expiresAt: response.data.expiresAt,
});
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
const message = error.response?.data?.message || error.message;
const statusCode = error.response?.status;
logger.error(`Authentication failed [${statusCode}]: ${message}`);
if (statusCode === 401) {
throw new Error('Invalid agent ID or API key');
} else if (statusCode === 404) {
throw new Error('Agent not found - please register first');
}
throw new Error(`Authentication failed: ${message}`);
}
throw error;
}
}
/**
* Send heartbeat to platform
*/
async sendHeartbeat(request: HeartbeatRequest, apiKey: string): Promise<void> {
logger.debug('Sending heartbeat to platform');
try {
await this.client.put('/api/agents/heartbeat', request, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
logger.debug('Heartbeat sent successfully');
} catch (error) {
if (axios.isAxiosError(error)) {
const message = error.response?.data?.message || error.message;
logger.error(`Heartbeat failed: ${message}`);
// Don't throw - heartbeat failures should be handled gracefully
}
}
}
/**
* Test connection to platform
*/
async testConnection(): Promise<boolean> {
try {
await this.client.get('/health');
logger.info('Platform connection test successful');
return true;
} catch (error) {
logger.error('Platform connection test failed:', error);
return false;
}
}
/**
* Get platform URL
*/
getPlatformUrl(): string {
return this.platformUrl;
}
}
|