38 lines · 1.7 KBRaw
| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | import type { CiEnv } from "./ci-env.ts"; |
| 3 | |
| 4 | /** The most job containers refs runs at once, across every namespace. It matches `max_instances` of the container app. */ |
| 5 | export const MAX_JOBS = 2; |
| 6 | |
| 7 | /** ponytail: one queue for all of refs; add a limit per namespace when one namespace can starve the others. */ |
| 8 | export const SLOTS = "all"; |
| 9 | |
| 10 | /** |
| 11 | * The running-job limit of refs. A job holds a lease while its container runs. A lease ends when the job |
| 12 | * releases it, or at its expiry, so a job whose release was lost cannot hold its slot for good. |
| 13 | */ |
| 14 | export class JobSlots extends DurableObject<CiEnv> { |
| 15 | constructor(ctx: DurableObjectState, env: CiEnv) { |
| 16 | super(ctx, env); |
| 17 | ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS leases (job TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)"); |
| 18 | } |
| 19 | |
| 20 | /** Takes a slot for `job`, or returns false when refs already runs its limit. Taking it again renews it. */ |
| 21 | acquire(job: string, leaseMs: number, limit = MAX_JOBS): boolean { |
| 22 | const sql = this.ctx.storage.sql; |
| 23 | const at = Date.now(); |
| 24 | sql.exec("DELETE FROM leases WHERE expires_at <= ?", at); |
| 25 | const held = sql.exec<{ n: number }>("SELECT count(*) AS n FROM leases WHERE job != ?", job).one().n; |
| 26 | if (held >= limit) return false; |
| 27 | sql.exec("INSERT INTO leases (job, expires_at) VALUES (?, ?) ON CONFLICT (job) DO UPDATE SET expires_at = excluded.expires_at", job, at + leaseMs); |
| 28 | return true; |
| 29 | } |
| 30 | |
| 31 | release(job: string): void { |
| 32 | this.ctx.storage.sql.exec("DELETE FROM leases WHERE job = ?", job); |
| 33 | } |
| 34 | |
| 35 | running(): number { |
| 36 | return this.ctx.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM leases WHERE expires_at > ?", Date.now()).one().n; |
| 37 | } |
| 38 | } |