| 1 | import type { JobCompletion, JobSpec } from "@diffinery/shared"; |
| 2 | import { LogBatcher, RunnerApi } from "./api.js"; |
| 3 | import { JobRunner, errMsg } from "./job.js"; |
| 4 | import { UsageSampler, describeUsage } from "./usage.js"; |
| 5 | |
| 6 | export interface AgentOptions { |
| 7 | /** `${apiUrl}/runner/jobs/${jobId}`, or null for offline mode (logs to stdout, no reports). */ |
| 8 | apiBase: string | null; |
| 9 | workRoot: string; |
| 10 | toolCache?: string; |
| 11 | echoLogs?: boolean; |
| 12 | /** Install a SIGTERM/SIGINT handler that cancels the job. */ |
| 13 | handleSignals?: boolean; |
| 14 | /** |
| 15 | * Hosted runners: on SIGTERM (a platform rollout replacing this container), keep |
| 16 | * running the job for up to this long before cancelling it. SIGINT or a second |
| 17 | * SIGTERM still cancels at once. |
| 18 | */ |
| 19 | drainOnSigtermMs?: number; |
| 20 | /** Exposes the runner (e.g. so tests can cancel). */ |
| 21 | onRunner?: (r: JobRunner) => void; |
| 22 | logIntervalMs?: number; |
| 23 | baseEnv?: NodeJS.ProcessEnv; |
| 24 | /** |
| 25 | * Measure what the job uses of the machine and report it with the result (hosted runners, where the |
| 26 | * container is the job's own machine; on a shared self-hosted machine the numbers would be the host's). |
| 27 | */ |
| 28 | measureUsage?: boolean | UsageSampler; |
| 29 | } |
| 30 | |
| 31 | export function apiBaseFor(apiUrl: string | undefined | null, jobId: string): string | null { |
| 32 | if (!apiUrl) return null; |
| 33 | return `${apiUrl.replace(/\/$/, "")}/runner/jobs/${encodeURIComponent(jobId)}`; |
| 34 | } |
| 35 | |
| 36 | /** Runs one job end-to-end: execute steps, ship logs, POST completion. */ |
| 37 | export async function runAgentJob(spec: JobSpec, o: AgentOptions): Promise<JobCompletion> { |
| 38 | const api = new RunnerApi(o.apiBase, spec.token); |
| 39 | const batcher = api.online |
| 40 | ? new LogBatcher((lines) => api.postLogs(lines), { |
| 41 | intervalMs: o.logIntervalMs ?? 500, |
| 42 | onError: (e) => process.stderr.write(`[diffinery-runner] log upload failed: ${errMsg(e)}\n`), |
| 43 | }) |
| 44 | : null; |
| 45 | const runner = new JobRunner(spec, api, null, { workRoot: o.workRoot, toolCache: o.toolCache, echoLogs: o.echoLogs ?? !api.online, baseEnv: o.baseEnv }, batcher); |
| 46 | o.onRunner?.(runner); |
| 47 | const onSignal = (sig: string) => { |
| 48 | runner.logger.line(-1, `##[error]Received ${sig}; cancelling the job.`); |
| 49 | runner.cancel("cancelled"); |
| 50 | }; |
| 51 | let draining: NodeJS.Timeout | null = null; |
| 52 | const sigterm = () => { |
| 53 | if (!o.drainOnSigtermMs || draining) return onSignal("SIGTERM"); |
| 54 | const minutes = Math.round(o.drainOnSigtermMs / 60_000); |
| 55 | runner.replacing = true; |
| 56 | runner.logger.line(-1, `##[warning]The platform is stopping this runner (a rollout replacing it with a new version, or the platform moving it). The job keeps running for up to ${minutes} minutes; if the platform stops a step or the time runs out, the job ends, and Diffinery starts it again on a new runner when doing so can't repeat anything outside the run.`); |
| 57 | draining = setTimeout(() => onSignal("SIGTERM"), o.drainOnSigtermMs); |
| 58 | draining.unref(); |
| 59 | }; |
| 60 | const sigint = () => onSignal("SIGINT"); |
| 61 | if (o.handleSignals) { |
| 62 | process.on("SIGTERM", sigterm); |
| 63 | process.on("SIGINT", sigint); |
| 64 | } |
| 65 | const sampler = o.measureUsage instanceof UsageSampler ? o.measureUsage : o.measureUsage ? new UsageSampler() : null; |
| 66 | sampler?.start(); |
| 67 | let completion: JobCompletion; |
| 68 | try { |
| 69 | completion = await runner.run(); |
| 70 | } catch (e) { |
| 71 | completion = { conclusion: "failure", outputs: {}, failure: { message: `Runner error: ${errMsg(e)}` } }; |
| 72 | } |
| 73 | const usage = sampler?.stop(); |
| 74 | if (usage) { |
| 75 | completion.usage = usage; |
| 76 | runner.logger.line(-1, describeUsage(usage)); |
| 77 | } |
| 78 | if (batcher) { |
| 79 | // After a SIGTERM the platform kills the container soon, so the result must not wait long on logs. |
| 80 | const ok = await batcher.close(draining ? 30_000 : 120_000); |
| 81 | if (!ok) process.stderr.write(`[diffinery-runner] gave up shipping ${batcher.pending} log lines\n`); |
| 82 | } |
| 83 | try { |
| 84 | await api.complete(completion); |
| 85 | } catch (e) { |
| 86 | process.stderr.write(`[diffinery-runner] failed to report completion: ${errMsg(e)}\n`); |
| 87 | } |
| 88 | if (draining) clearTimeout(draining); |
| 89 | if (o.handleSignals) { |
| 90 | process.off("SIGTERM", sigterm); |
| 91 | process.off("SIGINT", sigint); |
| 92 | } |
| 93 | return completion; |
| 94 | } |