Diffinery

homeflare/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.

63 lines · 2.6 KBRaw History
1import { DurableObject } from "cloudflare:workers";
2import type { Env } from "../env.js";
3import type { RunnerSize } from "../runner/sizes.js";
4import { GitHubAppClient, githubApp } from "./github.js";
5import { GitHubRunners, containerHost, type JobEvent, type QueuedJob } from "./service.js";
6
7/**
8 * One per Diffinery account that pays for GitHub jobs on Diffinery runners (named by the account id).
9 * Webhooks and container stops only record what happened and set the alarm; the alarm starts runners
10 * and stops idle ones (GitHubRunners.pump), one pass at a time, so a webhook never waits on a container
11 * start and GitHub's 10-second delivery timeout is never at risk.
12 */
13export class GitHubRunnersDO extends DurableObject<Env> {
14 private client: GitHubAppClient | null = null;
15
16 private runners(): GitHubRunners | null {
17 const app = githubApp(this.env);
18 if (!app) return null;
19 this.client ??= new GitHubAppClient(app);
20 return new GitHubRunners(this.env, this.client, containerHost(this.env));
21 }
22
23 /** Sets the alarm `ms` from now unless it is already due sooner. */
24 private async wake(accountId: string, ms: number): Promise<void> {
25 await this.ctx.storage.put("account", accountId);
26 const at = Date.now() + ms;
27 const cur = await this.ctx.storage.getAlarm();
28 if (cur === null || cur > at) await this.ctx.storage.setAlarm(at);
29 }
30
31 async queued(accountId: string, job: QueuedJob, size: RunnerSize): Promise<void> {
32 const r = this.runners();
33 if (r && (await r.queued(accountId, job, size))) await this.wake(accountId, 0);
34 }
35
36 async jobEvent(accountId: string, ev: JobEvent): Promise<void> {
37 const r = this.runners();
38 if (!r) return;
39 await r.jobEvent(ev);
40 await this.wake(accountId, 0);
41 }
42
43 /** A runner's container stopped (runner/containers.ts onStop); containers started before it said which don't. */
44 async stopped(accountId: string, runnerId: string, exitCode: number | null, container?: string): Promise<void> {
45 const r = this.runners();
46 if (!r) return;
47 await r.stopped(runnerId, exitCode, container);
48 await this.wake(accountId, 0);
49 }
50
51 /** A kill switch (lib/killswitch.ts stopGitHubRunners). */
52 async stopAll(accountId: string, message: string): Promise<number> {
53 return (await this.runners()?.stopAll(accountId, message)) ?? 0;
54 }
55
56 override async alarm(): Promise<void> {
57 const accountId = await this.ctx.storage.get<string>("account");
58 const r = this.runners();
59 if (!accountId || !r) return;
60 const { next } = await r.pump(accountId);
61 if (next !== null) await this.wake(accountId, next);
62 }
63}