|
| 1 | +import { ChildProcess, spawn } from "child_process"; |
| 2 | + |
| 3 | +import { logger } from "../util/logger.js"; |
| 4 | + |
| 5 | +export type BackgroundJobStatus = |
| 6 | + | "pending" |
| 7 | + | "running" |
| 8 | + | "completed" |
| 9 | + | "failed" |
| 10 | + | "cancelled"; |
| 11 | + |
| 12 | +export interface BackgroundJob { |
| 13 | + id: string; |
| 14 | + status: BackgroundJobStatus; |
| 15 | + command: string; |
| 16 | + output: string; |
| 17 | + exitCode: number | null; |
| 18 | + startTime: Date; |
| 19 | + endTime: Date | null; |
| 20 | + error?: string; |
| 21 | +} |
| 22 | + |
| 23 | +const MAX_CONCURRENT_JOBS = 5; |
| 24 | +const MAX_OUTPUT_LINES = 1000; |
| 25 | + |
| 26 | +/** |
| 27 | + * Service for managing background job execution and lifecycle |
| 28 | + * Handles spawning, tracking, and cleanup of background processes |
| 29 | + */ |
| 30 | +export class BackgroundJobService { |
| 31 | + private jobs: Map<string, BackgroundJob> = new Map(); |
| 32 | + private processes: Map<string, ChildProcess> = new Map(); |
| 33 | + private jobCounter = 0; |
| 34 | + |
| 35 | + createJob(command: string): BackgroundJob | null { |
| 36 | + const runningCount = this.getRunningJobCount(); |
| 37 | + if (runningCount >= MAX_CONCURRENT_JOBS) { |
| 38 | + logger.warn( |
| 39 | + `Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`, |
| 40 | + ); |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + const id = `bg-${++this.jobCounter}-${Date.now()}`; |
| 45 | + const job: BackgroundJob = { |
| 46 | + id, |
| 47 | + status: "pending", |
| 48 | + command, |
| 49 | + output: "", |
| 50 | + exitCode: null, |
| 51 | + startTime: new Date(), |
| 52 | + endTime: null, |
| 53 | + }; |
| 54 | + |
| 55 | + this.jobs.set(id, job); |
| 56 | + return job; |
| 57 | + } |
| 58 | + |
| 59 | + startJob(jobId: string, shell: string, args: string[]): ChildProcess | null { |
| 60 | + const job = this.jobs.get(jobId); |
| 61 | + if (!job) { |
| 62 | + logger.error(`Cannot start job ${jobId}: job not found`); |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + job.status = "running"; |
| 67 | + |
| 68 | + const child = spawn(shell, args, { stdio: "pipe" }); |
| 69 | + this.processes.set(jobId, child); |
| 70 | + |
| 71 | + child.stdout?.setEncoding("utf8"); |
| 72 | + child.stderr?.setEncoding("utf8"); |
| 73 | + |
| 74 | + child.stdout?.on("data", (data: string) => { |
| 75 | + this.appendOutput(jobId, data); |
| 76 | + }); |
| 77 | + |
| 78 | + child.stderr?.on("data", (data: string) => { |
| 79 | + this.appendOutput(jobId, data); |
| 80 | + }); |
| 81 | + |
| 82 | + child.on("close", (code: number | null) => { |
| 83 | + this.completeJob(jobId, code ?? 0); |
| 84 | + }); |
| 85 | + |
| 86 | + child.on("error", (error: Error) => { |
| 87 | + this.failJob(jobId, error.message); |
| 88 | + }); |
| 89 | + |
| 90 | + return child; |
| 91 | + } |
| 92 | + |
| 93 | + createJobWithProcess( |
| 94 | + command: string, |
| 95 | + child: ChildProcess, |
| 96 | + existingOutput: string = "", |
| 97 | + ): BackgroundJob | null { |
| 98 | + const runningCount = this.getRunningJobCount(); |
| 99 | + if (runningCount >= MAX_CONCURRENT_JOBS) { |
| 100 | + logger.warn( |
| 101 | + `Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`, |
| 102 | + ); |
| 103 | + return null; |
| 104 | + } |
| 105 | + |
| 106 | + const id = `bg-${++this.jobCounter}-${Date.now()}`; |
| 107 | + const job: BackgroundJob = { |
| 108 | + id, |
| 109 | + status: "running", |
| 110 | + command, |
| 111 | + output: existingOutput, |
| 112 | + exitCode: null, |
| 113 | + startTime: new Date(), |
| 114 | + endTime: null, |
| 115 | + }; |
| 116 | + |
| 117 | + this.jobs.set(id, job); |
| 118 | + this.processes.set(id, child); |
| 119 | + |
| 120 | + child.stdout?.setEncoding("utf8"); |
| 121 | + child.stderr?.setEncoding("utf8"); |
| 122 | + |
| 123 | + child.stdout?.on("data", (data: string) => { |
| 124 | + this.appendOutput(id, data); |
| 125 | + }); |
| 126 | + |
| 127 | + child.stderr?.on("data", (data: string) => { |
| 128 | + this.appendOutput(id, data); |
| 129 | + }); |
| 130 | + |
| 131 | + child.on("close", (code: number | null) => { |
| 132 | + this.completeJob(id, code ?? 0); |
| 133 | + }); |
| 134 | + |
| 135 | + child.on("error", (error: Error) => { |
| 136 | + this.failJob(id, error.message); |
| 137 | + }); |
| 138 | + |
| 139 | + return job; |
| 140 | + } |
| 141 | + |
| 142 | + // todo: improve write efficiency with ring buffer or similar |
| 143 | + appendOutput(jobId: string, data: string): void { |
| 144 | + const job = this.jobs.get(jobId); |
| 145 | + if (job) { |
| 146 | + job.output += data; |
| 147 | + const lines = job.output.split("\n"); |
| 148 | + if (lines.length > MAX_OUTPUT_LINES) { |
| 149 | + job.output = lines.slice(-MAX_OUTPUT_LINES).join("\n"); |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + completeJob(jobId: string, exitCode: number): void { |
| 155 | + const job = this.jobs.get(jobId); |
| 156 | + if (job) { |
| 157 | + if (job.status === "cancelled") { |
| 158 | + return; |
| 159 | + } |
| 160 | + job.status = exitCode === 0 ? "completed" : "failed"; |
| 161 | + job.exitCode = exitCode; |
| 162 | + job.endTime = new Date(); |
| 163 | + this.processes.delete(jobId); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + failJob(jobId: string, error: string): void { |
| 168 | + const job = this.jobs.get(jobId); |
| 169 | + if (job) { |
| 170 | + job.status = "failed"; |
| 171 | + job.error = error; |
| 172 | + job.endTime = new Date(); |
| 173 | + this.processes.delete(jobId); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + cancelJob(jobId: string): boolean { |
| 178 | + const job = this.jobs.get(jobId); |
| 179 | + const process = this.processes.get(jobId); |
| 180 | + |
| 181 | + if (!job) return false; |
| 182 | + |
| 183 | + if (process) { |
| 184 | + process.kill(); |
| 185 | + this.processes.delete(jobId); |
| 186 | + } |
| 187 | + |
| 188 | + job.status = "cancelled"; |
| 189 | + job.endTime = new Date(); |
| 190 | + return true; |
| 191 | + } |
| 192 | + |
| 193 | + getJob(jobId: string): BackgroundJob | undefined { |
| 194 | + return this.jobs.get(jobId); |
| 195 | + } |
| 196 | + |
| 197 | + getRunningJobs(): BackgroundJob[] { |
| 198 | + return Array.from(this.jobs.values()).filter( |
| 199 | + (job) => job.status === "running" || job.status === "pending", |
| 200 | + ); |
| 201 | + } |
| 202 | + |
| 203 | + getAllJobs(): BackgroundJob[] { |
| 204 | + return Array.from(this.jobs.values()); |
| 205 | + } |
| 206 | + |
| 207 | + getRunningJobCount(): number { |
| 208 | + return this.getRunningJobs().length; |
| 209 | + } |
| 210 | + |
| 211 | + killAllJobs(): void { |
| 212 | + for (const [jobId, process] of this.processes) { |
| 213 | + process.kill(); |
| 214 | + const job = this.jobs.get(jobId); |
| 215 | + if (job) { |
| 216 | + job.status = "cancelled"; |
| 217 | + job.endTime = new Date(); |
| 218 | + } |
| 219 | + } |
| 220 | + this.processes.clear(); |
| 221 | + } |
| 222 | +} |
| 223 | + |
| 224 | +export const backgroundJobService = new BackgroundJobService(); |
0 commit comments