Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

98 lines · 4.4 KBRaw History
1import type { JobCompletion, JobSpec } from "@diffinery/shared";
2import { LogBatcher, RunnerApi } from "./api.js";
3import { JobRunner, errMsg } from "./job.js";
4import { UsageSampler, describeUsage } from "./usage.js";
5
6export 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 /** Hosted runners: start the Docker daemon as the job begins when the job will use Docker (docker.ts prewarm). */
30 prewarmDocker?: boolean;
31 /** Hosted runners: start installing the job's Go or Java toolchain as the job begins (prefetch.ts). */
32 prefetchTools?: boolean;
33}
34
35export function apiBaseFor(apiUrl: string | undefined | null, jobId: string): string | null {
36 if (!apiUrl) return null;
37 return `${apiUrl.replace(/\/$/, "")}/runner/jobs/${encodeURIComponent(jobId)}`;
38}
39
40/** Runs one job end-to-end: execute steps, ship logs, POST completion. */
41export async function runAgentJob(spec: JobSpec, o: AgentOptions): Promise<JobCompletion> {
42 const api = new RunnerApi(o.apiBase, spec.token);
43 const batcher = api.online
44 ? new LogBatcher((lines) => api.postLogs(lines), {
45 intervalMs: o.logIntervalMs ?? 500,
46 onError: (e) => process.stderr.write(`[diffinery-runner] log upload failed: ${errMsg(e)}\n`),
47 })
48 : null;
49 const runner = new JobRunner(spec, api, null, { workRoot: o.workRoot, toolCache: o.toolCache, echoLogs: o.echoLogs ?? !api.online, baseEnv: o.baseEnv, prewarmDocker: o.prewarmDocker, prefetchTools: o.prefetchTools }, batcher);
50 o.onRunner?.(runner);
51 const onSignal = (sig: string) => {
52 runner.logger.line(-1, `##[error]Received ${sig}; cancelling the job.`);
53 runner.cancel("cancelled");
54 };
55 let draining: NodeJS.Timeout | null = null;
56 const sigterm = () => {
57 if (!o.drainOnSigtermMs || draining) return onSignal("SIGTERM");
58 const minutes = Math.round(o.drainOnSigtermMs / 60_000);
59 runner.replacing = true;
60 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.`);
61 draining = setTimeout(() => onSignal("SIGTERM"), o.drainOnSigtermMs);
62 draining.unref();
63 };
64 const sigint = () => onSignal("SIGINT");
65 if (o.handleSignals) {
66 process.on("SIGTERM", sigterm);
67 process.on("SIGINT", sigint);
68 }
69 const sampler = o.measureUsage instanceof UsageSampler ? o.measureUsage : o.measureUsage ? new UsageSampler() : null;
70 sampler?.start();
71 let completion: JobCompletion;
72 try {
73 completion = await runner.run();
74 } catch (e) {
75 completion = { conclusion: "failure", outputs: {}, failure: { message: `Runner error: ${errMsg(e)}` } };
76 }
77 const usage = sampler?.stop();
78 if (usage) {
79 completion.usage = usage;
80 runner.logger.line(-1, describeUsage(usage));
81 }
82 if (batcher) {
83 // After a SIGTERM the platform kills the container soon, so the result must not wait long on logs.
84 const ok = await batcher.close(draining ? 30_000 : 120_000);
85 if (!ok) process.stderr.write(`[diffinery-runner] gave up shipping ${batcher.pending} log lines\n`);
86 }
87 try {
88 await api.complete(completion);
89 } catch (e) {
90 process.stderr.write(`[diffinery-runner] failed to report completion: ${errMsg(e)}\n`);
91 }
92 if (draining) clearTimeout(draining);
93 if (o.handleSignals) {
94 process.off("SIGTERM", sigterm);
95 process.off("SIGINT", sigint);
96 }
97 return completion;
98}