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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | /** * Job Status API Client - REST API integration for job status updates * * Provides methods for updating job status, streaming logs, and reporting * job completion to the BuildHive server via REST API. * * Requirements: MVP.4.2.2 - Job status updates */ import axios, { AxiosInstance, AxiosError } from 'axios'; import { createLogger } from '../utils/logger.js'; const logger = createLogger('jobStatusApi'); export interface JobStatusUpdate { status?: 'QUEUED' | 'ASSIGNED' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'FALLBACK'; agentId?: string; startedAt?: Date; completedAt?: Date; exitCode?: number; logs?: string; errorMessage?: string; artifactUrls?: string[]; actualDuration?: number; } export interface JobCompletionResult { exitCode: number; logs: string; artifactUrls?: string[]; actualDuration: number; errorMessage?: string; } export class JobStatusApi { private client: AxiosInstance; private serverUrl: string; private apiKey: string; private logBuffer: Map<string, string> = new Map(); constructor(serverUrl: string, apiKey: string) { this.serverUrl = serverUrl; this.apiKey = apiKey; // Create axios instance with default config this.client = axios.create({ baseURL: serverUrl, timeout: 30000, // 30 second timeout headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }); // Add request interceptor for logging this.client.interceptors.request.use( (config) => { logger.debug('API request', { method: config.method, url: config.url, dataSize: JSON.stringify(config.data || {}).length }); return config; }, (error) => { logger.error('Request interceptor error', error); return Promise.reject(error); } ); // Add response interceptor for error handling this.client.interceptors.response.use( (response) => { logger.debug('API response', { status: response.status, url: response.config.url }); return response; }, (error: AxiosError) => { this.handleApiError(error); return Promise.reject(error); } ); logger.info('JobStatusApi initialized', { serverUrl }); } /** * Update job status with any combination of fields */ async updateJobStatus(jobId: string, update: JobStatusUpdate): Promise<void> { try { logger.info('Updating job status', { jobId, status: update.status, hasLogs: !!update.logs, logsSize: update.logs?.length || 0 }); await this.client.put(`/api/jobs/${jobId}/status`, update); logger.info('Job status updated successfully', { jobId, status: update.status }); } catch (error) { logger.error(`Failed to update job status for ${jobId}`, error); throw error; } } /** * Mark job as RUNNING with start timestamp */ async markJobRunning(jobId: string): Promise<void> { logger.info(`Marking job ${jobId} as RUNNING`); await this.updateJobStatus(jobId, { status: 'RUNNING', startedAt: new Date() }); } /** * Update job logs (accumulative - replaces all logs) */ async updateJobLogs(jobId: string, logs: string): Promise<void> { try { // Store logs in buffer for this job this.logBuffer.set(jobId, logs); logger.debug('Updating job logs', { jobId, logsSize: logs.length, logLines: logs.split('\n').length }); await this.updateJobStatus(jobId, { logs }); logger.debug('Job logs updated', { jobId }); } catch (error) { logger.error(`Failed to update logs for job ${jobId}`, error); throw error; } } /** * Append logs to existing buffer and send update */ async appendJobLogs(jobId: string, newLogs: string): Promise<void> { const existingLogs = this.logBuffer.get(jobId) || ''; const updatedLogs = existingLogs + newLogs; await this.updateJobLogs(jobId, updatedLogs); } /** * Mark job as COMPLETED with results */ async markJobCompleted(jobId: string, result: JobCompletionResult): Promise<void> { logger.info(`Marking job ${jobId} as ${result.exitCode === 0 ? 'COMPLETED' : 'FAILED'}`, { exitCode: result.exitCode, duration: result.actualDuration, hasArtifacts: !!result.artifactUrls?.length }); const status: JobStatusUpdate = { status: result.exitCode === 0 ? 'COMPLETED' : 'FAILED', completedAt: new Date(), exitCode: result.exitCode, logs: result.logs, actualDuration: result.actualDuration }; if (result.artifactUrls && result.artifactUrls.length > 0) { status.artifactUrls = result.artifactUrls; } if (result.errorMessage) { status.errorMessage = result.errorMessage; } await this.updateJobStatus(jobId, status); // Clean up log buffer this.logBuffer.delete(jobId); logger.info('Job completion reported', { jobId, status: status.status, exitCode: result.exitCode }); } /** * Mark job as FAILED with error details */ async markJobFailed(jobId: string, errorMessage: string, logs?: string): Promise<void> { logger.error(`Marking job ${jobId} as FAILED`, { errorMessage }); await this.updateJobStatus(jobId, { status: 'FAILED', completedAt: new Date(), errorMessage, logs: logs || this.logBuffer.get(jobId) }); // Clean up log buffer this.logBuffer.delete(jobId); } /** * Update job progress (sends status update without changing status) */ async updateJobProgress(jobId: string, progress: { percentage: number; currentStep: string }): Promise<void> { // Progress updates can be sent via logs const progressLog = `[PROGRESS] ${progress.percentage}% - ${progress.currentStep}\n`; await this.appendJobLogs(jobId, progressLog); } /** * Get current logs from buffer */ getCurrentLogs(jobId: string): string { return this.logBuffer.get(jobId) || ''; } /** * Clear log buffer for a job */ clearLogBuffer(jobId: string): void { this.logBuffer.delete(jobId); } /** * Handle API errors with detailed logging */ private handleApiError(error: AxiosError): void { if (error.response) { // Server responded with error status logger.error('API error response', { status: error.response.status, statusText: error.response.statusText, data: error.response.data, url: error.config?.url }); } else if (error.request) { // Request made but no response logger.error('API no response', { url: error.config?.url, message: error.message }); } else { // Error setting up request logger.error('API request setup error', { message: error.message }); } } /** * Cleanup resources */ cleanup(): void { this.logBuffer.clear(); logger.info('JobStatusApi cleaned up'); } } |