| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | import type { Env } from "../env.js"; |
| 3 | import type { RunnerSize } from "../runner/sizes.js"; |
| 4 | import { GitHubAppClient, githubApp } from "./github.js"; |
| 5 | import { 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 | */ |
| 13 | export 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). */ |
| 44 | async stopped(accountId: string, runnerId: string, exitCode: number | null): Promise<void> { |
| 45 | const r = this.runners(); |
| 46 | if (!r) return; |
| 47 | await r.stopped(runnerId, exitCode); |
| 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 | } |