/** * STEP JOBS, the object's half (JOBS OUT M1, assets/design/shared/JOBS-OUT.md (d), "How the rest move: step jobs"; * the run's half is src/jobs/step_job.ts). Work with no outside socket, moved off the alarm: each kind behind its * own per-account switch (`PUT /v1/admin/business { "jobs": { "<kind>": "on" | null } }`, admin token, off by * default). On, neither the alarm nor a request runs the work; this object puts a run on the JOBS queue and answers * the run's calls at `POST /v1/jobs/step/<kind>`, one bounded step a call, in an ordinary request. Off, the object * runs the work exactly as before. * * THE JOB ROW (`step_job`, one a kind): `gen`, new each time the switch is thrown on (a credential names it, so one * from before opens nothing); `nonce`, the one scheduled message a run may begin with (used up by its first call); * `run` and `lease_until`, the one run that may call now; `begun_at`, when it began (a run is ended by this object * once it has had RUN_MS); `due_at`, when the next run was asked for (null: nothing asked); `sent_at`, when it went on * the queue. * * WHO SCHEDULES. Only this object: when work appears (`kick`, after a request or a write that made some), when a run * ends with work still left, and the alarm's watchdog (a message the queue lost, a run that died). */importtype { Env } from"./env.ts";import { refuse } from"./http.ts";import { STEP_KINDS, typeStepJobMessage, typeStepKind } from"./jobs/step_job.ts";import { JOB_SCHEME, mintJobToken, openJobToken, usableKey } from"./jobs/token.ts";exportconst SCHEMA = "CREATE TABLE IF NOT EXISTS step_job (kind TEXT PRIMARY KEY, gen TEXT NOT NULL, nonce TEXT, run TEXT, lease_until INTEGER, begun_at INTEGER, due_at INTEGER, sent_at INTEGER, rest_until INTEGER);";/** A run holds its job this long at most (a queue consumer runs 15 minutes). */exportconst LEASE_MS = 16 * 60_000;/** A run this old is ended by the object at its next step, and the next run put on the queue at once. */exportconst RUN_MS = 9 * 60_000;/** A run asked for and not begun this long after its time is asked for again by the watchdog. */exportconst OVERDUE_MS = 10 * 60_000;/** The watchdog's alarm comes at least this often while a kind is on and has work. */exportconst WATCH_EVERY_MS = 15 * 60_000;/** A credential lives this long past the run's time. */const TOKEN_SLACK_MS = 20 * 60_000;/** A step call carries no body; one that says it carries more than this is refused unread. */const BODY_MOST = 1024;exportinterfaceStepHost { sql: SqlStorage; env: Env; slug: string; now(): number;/** Whether this kind's switch is on for the account. */ on(kind: StepKind): boolean;/** One bounded step of the kind's work (at most its cap of rows or keys): whether more is left that a step can do now. */ step(kind: StepKind): Promise<boolean>;/** Whether the kind has work a step can do now (read cheaply: never a whole table). */ owes(kind: StepKind): boolean;/** * A kind with no cheap "is there work" (a trim: only its step knows): once a run finds nothing left it rests this * long (ms) before it owes again. 0 for a kind whose `owes` says it. */ restMs?(kind: StepKind): number;/** Work that cannot wait out a rest (a window past its end): owed now whatever the rest says. */ urgent?(kind: StepKind): boolean;}/** The columns a later build added to a table an earlier build made, the additive way. */exportfunction ensureColumns(sql: SqlStorage): void {const have = newSet(sql.exec<{ name: string }>("PRAGMA table_info(step_job)").toArray().map((c) => c.name));if (!have.has("rest_until")) sql.exec("ALTER TABLE step_job ADD COLUMN rest_until INTEGER");}/** Whether the kind owes a run now: its work, and no rest standing (or work that cannot wait). */function owing(host: StepHost, kind: StepKind, r: Row | null): boolean {if (!host.owes(kind)) returnfalse;return host.now() >= (r?.rest_until ?? 0) || !!host.urgent?.(kind);}interfaceRow { kind: string; gen: string; nonce: string | null; run: string | null; lease_until: number | null; begun_at: number | null; due_at: number | null; sent_at: number | null; rest_until: number | null;}exportfunction isKind(kind: string): kind is StepKind {return (STEP_KINDS asreadonly string[]).includes(kind);}/** The meta key a kind's switch is kept under. */exportfunction switchKey(kind: StepKind): string {return`jobs_${kind}`;}function row(sql: SqlStorage, kind: string): Row | null {const r = sql.exec<Record<string, SqlStorageValue>>("SELECT kind, gen, nonce, run, lease_until, begun_at, due_at, sent_at, rest_until FROM step_job WHERE kind = ?", kind).toArray()[0];if (!r) returnnull;const n = (v: SqlStorageValue | undefined) => (v === null || v === undefined ? null : Number(v));const t = (v: SqlStorageValue | undefined) => (v === null || v === undefined ? null : String(v));return { kind: String(r.kind), gen: String(r.gen), nonce: t(r.nonce), run: t(r.run), lease_until: n(r.lease_until), begun_at: n(r.begun_at), due_at: n(r.due_at), sent_at: n(r.sent_at), rest_until: n(r.rest_until) };}/** What a switch needs to be thrown on: the queue and the key that signs a job's credential. */exportfunction ready(env: Env): string | null {if (!env.JOBS) return"this Worker has no JOBS queue bound";if (!usableKey(env.JOB_TOKEN_KEY)) return"this Worker holds no JOB_TOKEN_KEY";returnnull;}/** The switch thrown on: a new generation, so every credential from before opens nothing. */exportfunction renew(sql: SqlStorage, kind: StepKind): void { sql.exec("INSERT INTO step_job (kind, gen) VALUES (?, ?) ON CONFLICT (kind) DO UPDATE SET gen = excluded.gen, nonce = NULL, run = NULL, lease_until = NULL, begun_at = NULL, due_at = NULL, sent_at = NULL, rest_until = NULL", kind, crypto.randomUUID());}/** The switch thrown off: the row goes, and with it every credential for the kind. */exportfunction drop(sql: SqlStorage, kind: StepKind): void { sql.exec("DELETE FROM step_job WHERE kind = ?", kind);}/** The message a run is scheduled with, its credential minted here for this generation; `fresh` mints a new nonce. */exportasyncfunction message(host: StepHost, kind: StepKind, delayMs: number, fresh = false): Promise<StepJobMessage> {if (!row(host.sql, kind)) renew(host.sql, kind);const r = row(host.sql, kind)!;const nonce = !fresh && r.nonce ? r.nonce : crypto.randomUUID();if (nonce !== r.nonce) host.sql.exec("UPDATE step_job SET nonce = ? WHERE kind = ?", nonce, kind);const token = await mintJobToken(host.env.JOB_TOKEN_KEY, { v: 1, slug: host.slug, kind: `step:${kind}`, account: kind, gen: r.gen, nonce, exp: host.now() + delayMs + TOKEN_SLACK_MS });return { kind: "step", job: kind, slug: host.slug, token };}/** Put the kind's next run on the queue, `delayMs` from now. A queue that refuses is logged; the watchdog asks again. */exportasyncfunction schedule(host: StepHost, kind: StepKind, delayMs: number, fresh = false): Promise<boolean> {if (!row(host.sql, kind)) renew(host.sql, kind); host.sql.exec("UPDATE step_job SET due_at = ? WHERE kind = ?", host.now() + delayMs, kind);try {const queue = host.env.JOBS ?? refuse(503, "jobs_unavailable", "no JOBS queue");await queue.send(await message(host, kind, delayMs, fresh), { delaySeconds: Math.min(Math.ceil(Math.max(0, delayMs) / 1000), 86_400) }); host.sql.exec("UPDATE step_job SET sent_at = ? WHERE kind = ?", host.now(), kind);returntrue; } catch (error) { console.log(`cottondb: job ${kind} ${host.slug} not sent: ${error instanceof Error ? error.message : String(error)}`);returnfalse; }}function live(host: StepHost, r: Row | null): boolean {return !!r?.run && (r.lease_until ?? 0) > host.now();}/** * Work appeared (after a request, a write): with the kind on, a run is put on the queue unless one runs or is asked * for already. Cheap when nothing is owed: one meta read and no queue call. */exportasyncfunction kick(host: StepHost, kind: StepKind): Promise<void> {if (!host.on(kind)) return;const r = row(host.sql, kind);if (!owing(host, kind, r)) return;if (live(host, r) || (r?.due_at != null && r.sent_at != null && host.now() <= r.due_at + OVERDUE_MS)) return;await schedule(host, kind, 0);}/** * The alarm's watchdog: every kind switched on that has work and no live run and no run asked for in time is put on * the queue now. Answers when it wants to look again (ms), or null with nothing owed. */exportasyncfunction watchdog(host: StepHost): Promise<number | null> {let look: number | null = null;for (const kind of STEP_KINDS) {if (!host.on(kind)) continue;const r = row(host.sql, kind);if (!owing(host, kind, r)) continue;const overdue = !r || r.due_at === null || r.sent_at === null || host.now() > r.due_at + OVERDUE_MS;if (!live(host, r) && overdue) await schedule(host, kind, 0); look = WATCH_EVERY_MS; }return look;}/** * What the door answers on an object with no personal database: gone, nothing read. The credential is opened first * (AUDIT F, F2): one that is not genuine is refused as a real door refuses it, so the answer never says whether a * personal database stands at this slug. */exportasyncfunction shut(env: Env, request: Request, kind: string): Promise<never> {await cancel(request); precheck(request, kind);if (!(await openJobToken(env.JOB_TOKEN_KEY, (request.headers.get("authorization") ?? "").slice(JOB_SCHEME.length), Date.now()))) refuse(401, "job_credential", "this credential opens nothing here"); refuse(410, "job_gone", "this account runs this work on its own object");}asyncfunction cancel(request: Request): Promise<void> {try {if (request.body && !request.bodyUsed) await request.body.cancel(); } catch {// already gone }}function precheck(request: Request, kind: string): void {if (request.method !== "POST") refuse(405, "method_not_allowed", "a job's call is a POST");if (!isKind(kind)) refuse(404, "not_found", "no such job");if (!(request.headers.get("authorization") ?? "").startsWith(JOB_SCHEME)) refuse(401, "job_credential", "a job's call carries its credential");}/** * `POST /v1/jobs/step/<kind>`: one step. The call carries no body (one is refused unread). Its credential must name * this object, this kind and its generation. The first call of a run uses up the message's nonce and takes the lease; * the run's later calls carry the same nonce; any other is told busy (409) while a run holds the job, gone (410) * otherwise. Answers `{ more }`: false once nothing is left, or once the run has had RUN_MS (the next is then on the * queue already). */exportasyncfunction door(host: StepHost, request: Request, kind: string): Promise<{ more: boolean }> {await cancel(request); precheck(request, kind);const k = kind asStepKind;const said = request.headers.get("content-length");if (said !== null && !(Number(said) <= BODY_MOST)) refuse(413, "too_large", "a step call carries no body");// The credential first (AUDIT F, F1): only a genuine one for this object and kind learns whether the kind is on.const claim = await openJobToken(host.env.JOB_TOKEN_KEY, (request.headers.get("authorization") ?? "").slice(JOB_SCHEME.length), host.now());if (!claim || claim.slug !== host.slug || claim.kind !== `step:${k}`) refuse(401, "job_credential", "this credential opens nothing here");if (!host.on(k)) refuse(410, "job_gone", "this account runs this work on its own object");const r = row(host.sql, k);if (!r || r.gen !== claim.gen) refuse(410, "job_gone", "this job was switched off or on again");const now = host.now();if (r.run !== claim.nonce) {if (live(host, r)) refuse(409, "job_busy", "another run holds this job");if (r.nonce !== claim.nonce) refuse(410, "job_gone", "this message began its run already, or a later one replaced it"); host.sql.exec("UPDATE step_job SET run = ?, lease_until = ?, begun_at = ?, nonce = NULL, due_at = NULL WHERE kind = ?", claim.nonce, now + LEASE_MS, now, k); } elseif ((r.lease_until ?? 0) <= now) { refuse(410, "job_gone", "this run no longer holds the job"); }let more: boolean;try { more = await host.step(k); } catch (error) {// The step is tried again by the next run, in a minute; this one ends. console.log(`cottondb: job ${k} ${host.slug} step failed: ${error instanceof Error ? error.message : String(error)}`); end(host, k);await schedule(host, k, 60_000, true);return { more: false }; }const begun = row(host.sql, k)?.begun_at ?? now;if (more && host.now() - begun < RUN_MS) return { more: true }; end(host, k);if (more) await schedule(host, k, 0, true);else {// Nothing left: a kind with no cheap "is there work" rests before it is asked for again.const rest = host.restMs?.(k) ?? 0;if (rest > 0) host.sql.exec("UPDATE step_job SET rest_until = ? WHERE kind = ?", host.now() + rest, k); }return { more: false };}function end(host: StepHost, kind: StepKind): void { host.sql.exec("UPDATE step_job SET run = NULL, lease_until = NULL, begun_at = NULL WHERE kind = ?", kind);}/** What the kind stands at, for an admin's look: the switch, the next run's time, a run's lease. */exportfunction stateOf(sql: SqlStorage, kind: StepKind): { due_at: string | null; run_until: string | null } | null {const r = row(sql, kind);if (!r) returnnull;const iso = (n: number | null) => (n === null ? null : newDate(n).toISOString());return { due_at: iso(r.due_at), run_until: r.run ? iso(r.lease_until) : null };}