/** * A STEP JOB'S RUN (JOBS OUT M1, assets/design/shared/JOBS-OUT.md (d), "How the rest move: step jobs"): work with no * outside socket, moved off the account object's alarm. The queue message names one account object, one kind of job * and carries the credential the object minted for it (src/jobs/token.ts). The run calls the object's door, * `POST /v1/jobs/step/`, again and again; each call is one bounded step the object runs in an ordinary request * and answers `{ more }`. The object ends a run itself once it has had its time, and puts the next on the queue. * * Handed only the door (the front Worker, as a phone's request goes): no binding, no key, nothing the object keeps. */ import { JOB_SCHEME } from "./token.ts"; /** The kinds of step job (each with its own per-account switch on the object, `jobs: { : "on" }`). */ export const STEP_KINDS = ["media_drop", "artwork", "book_files", "calendar_sync", "changes", "acts", "prompts", "sweeps", "storage_count", "order_shadow", "send"] as const; export type StepKind = (typeof STEP_KINDS)[number]; export interface StepJobMessage { kind: "step"; job: StepKind; slug: string; token: string; } export interface StepJobDeps { /** The account object's door: `path` on `/b/`. */ door(slug: string, path: string, init: RequestInit): Promise; /** A run stops calling after this long (the object ends it sooner; a queue consumer has 15 minutes). */ runForMs?: number; } export function isStepJob(body: unknown): body is StepJobMessage { const m = body as Partial | null; return !!m && m.kind === "step" && typeof m.slug === "string" && typeof m.token === "string" && (STEP_KINDS as readonly string[]).includes(String(m.job)); } /** * One run: steps until the object says there is no more. "gone" when the object no longer wants this run (the * credential, the switch, the generation or the account went: 401, 404, 410), "busy" when another run holds the job * (409). Anything else the object could not answer throws, and the queue tries the message again. */ export async function runStepJob(deps: StepJobDeps, job: StepJobMessage): Promise<"ran" | "busy" | "gone"> { const until = Date.now() + (deps.runForMs ?? 12 * 60_000); for (;;) { const r = await deps.door(job.slug, `/v1/jobs/step/${job.job}`, { method: "POST", headers: { authorization: `${JOB_SCHEME}${job.token}` } }); if (r.status === 409) return "busy"; if (r.status === 401 || r.status === 404 || r.status === 410) return "gone"; if (!r.ok) throw new Error(`the door answered ${r.status}`); const answer = (await r.json()) as { more?: unknown }; if (answer.more !== true || Date.now() >= until) return "ran"; } }