Public: anyone can read this; the crew can change it.
Scheduled work on any app is done only when the app confirms the work finishe… #16112
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16099-scheduled-work-on-any-app-is-done-only-w → main 0 commits fork
16 files
changed +528
−35
docs/APPS.md +1
| @@ -1375,6 +1375,7 @@ Declare schedules in `forge.json`: | ||
| 1375 | 1375 | - **Where.** Production only, unless an entry says `"env": "preview"`: a preview never fires production's jobs. |
| 1376 | 1376 | - **Firing.** The forge wakes the app, then `POST`s `path` with `x-forge-schedule`, `x-forge-scheduled-at`, `x-forge-attempt` and `idempotency-key` (`<app>:<name>:<scheduled time>`), signed with the app's identity key as the identity headers are (`x-forge-identity` is `forge-timer|<key>|timer|<expiry>`). 2xx is done. Anything else, or no answer in `timeout` seconds (default 300, at most 3600), is retried after 30 s, 2 min, 10 min, 30 min, then hourly, up to `retries` (default 3), and then the run is failed. |
| 1377 | 1377 | - **Once.** The template's `src/once.ts` gives `fromForge(request, key)` (did the forge send this?) and `once(db, key, handler)`, which runs the handler once per idempotency key and answers 200 for a repeat. The key is the same on every attempt, so a retry or a second delivery never does the work twice. |
| 1378 | - **Done means confirmed (#16099).** A run is `ok` only when the app says its work finished. An app that finishes inside the call answers 2xx as before. An app that only *took* the work answers `202`, or 2xx with JSON `{"status": "running" | "printing" | "pending" | "accepted" | "in_progress"}`: the run is then **running**, never ok, and the app is **not put to sleep** while it is (the run's deadline, `timeout` seconds after the answer, ends the hold). The app confirms with `POST /api/v1/timers/finish` under its own token: `{ "run": "<the idempotency-key it was sent>", "status": "ok" | "failed" | "device_asleep", "error": "why" }`. No confirmation by the deadline, `failed`, and `device_asleep` (also what a 2xx `{"status":"device_asleep"}` means: the device the app drives did not answer, so nothing happened) are unfinished attempts: retried with the backoff above and the **same idempotency key and run id**, so an app that does its effect once per key never repeats it; when attempts are spent the run is failed (or `device_asleep`) and the owner is asked. One occurrence is one row in the history with its attempts, start, finish, status and error, and the sleep and a forge restart in the middle change none of it (the state is the timer's row). | |
| 1378 | 1379 | - **Missed.** Timers are rows read at boot, so a release never drops one. A run due while the forge was away fires as soon as it is back if it is inside `catchUp` (default `"1h"`; `"none"`, or `"30m"`, `"2d"` up to 7 d) and the history says it ran late; past it, the run is recorded as missed and skipped. |
| 1379 | 1380 | - **Seen and steered.** The app's page has a Schedules row per schedule: next run, last run and how it went, in the schedule's timezone, with **Run now** (once, apart from the clock) and **Pause**. `GET /api/v1/repos/{owner}/{name}/schedules` (`?runs=N` adds the history: attempts, duration, status, the first 2 KB of the response) and the `app_deploy` MCP tool (`action: "schedules" | "run_schedule" | "pause_schedule" | "resume_schedule"`) answer the same. |
| 1380 | 1381 | - **When it fails.** A failed or missed run asks the app's owner once, with the reason in plain words (and on their phone when a notify URL is set); the ask is the schedule, not the run, so a schedule that keeps failing does not ask again. A schedule that fails five days running pauses itself and says so; Resume waits for the next occurrence. |
docs/features/scheduled-run-confirmation.md added +37
| @@ -0,0 +1,37 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Scheduled runs: done only when the app confirms | |
| 4 | --- | |
| 5 | # Scheduled runs: done only when the app confirms | |
| 6 | ||
| 7 | This page is for app authors. A scheduled or timer run is `ok` only when your app says its work finished. A 2xx answer alone does not mean that when the work is still going. | |
| 8 | ||
| 9 | ## What your app answers | |
| 10 | ||
| 11 | - **Finished inside the call:** answer 2xx with any body. The run is `ok`, as before. | |
| 12 | - **Took the work, not done:** answer `202`, or 2xx with JSON `{"status": "running"}` (also `printing`, `pending`, `accepted`, `in_progress`). The run reads **running**. The app is not put to sleep while it runs. The deadline is the schedule's `timeout` seconds after the answer. | |
| 13 | - **The device it drives is asleep:** answer 2xx with `{"status": "device_asleep"}`. Nothing happened, so the attempt is retried. | |
| 14 | ||
| 15 | ## Confirm | |
| 16 | ||
| 17 | When the work ends, call `POST /api/v1/timers/finish` with the app's own token: | |
| 18 | ||
| 19 | json | |
| 20 | { "run": "<the idempotency-key header it was sent>", "status": "ok", "error": "why, for failed" } | |
| 21 | ||
| 22 | ||
| 23 | `status` is `ok`, `failed` or `device_asleep`. `error` is optional text of at most 2000 characters. A person's token gets 401, bad input gets 422. | |
| 24 | ||
| 25 | ## Retries | |
| 26 | ||
| 27 | `failed`, `device_asleep` and no confirmation by the deadline are unfinished attempts. They retry with the usual backoff while `retries` remain, with the **same idempotency key and run id**, so an app that does its effect once per key never repeats it. When the attempts are spent the run ends as `failed` (or `device_asleep`) and the owner is asked. | |
| 28 | ||
| 29 | A schedule that fails or finds its device asleep on five days running pauses itself and asks the owner. A device asleep counts as a failed day. | |
| 30 | ||
| 31 | ## A late confirmation | |
| 32 | ||
| 33 | Once the deadline has passed and the run has been retried, the earlier attempt is over. A confirmation for it gets **404** (`No run of this app is waiting for confirmation`). Confirm the attempt in flight with the same run id. The same 404 answers a second confirmation of the same run. | |
| 34 | ||
| 35 | ## Reading it | |
| 36 | ||
| 37 | The app's Schedules row on the page and the terminal's Schedules screen (`src/tui/screens/schedules.ts`) read the same rows: `running`, `device_asleep` and the retry text (`attempt 1: …; trying again …`) show the same in both. |
src/actions/timers.ts +26
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | |
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | 12 | import { isJobPath } from "../apps/schedule_spec.ts"; |
| 13 | import { confirmRun } from "../apps/timer_fire.ts"; | |
| 14 | import { getAppById } from "../core/apps.ts"; | |
| 13 | 15 | import { sha256 } from "../kernel/hash.ts"; |
| 14 | 16 | import { appOfToken } from "../core/device_grants.ts"; |
| 15 | 17 | import { armTimer, cancelTimer, ONCE_BODY_MAX, ONCE_KEY, pendingOnce, type Arm } from "../core/timers.ts"; |
| @@ -87,3 +89,27 @@ export function cancelFor(app: App, secret: string, key: string): Result<true, { | ||
| 87 | 89 | if (caller === undefined) return err({ kind: "unauthorized", message: TIMER_WORDS.unauthorized }); |
| 88 | 90 | return cancelTimer(app.db, caller.id, caller.env, key) ? ok(true) : err({ kind: "not_found", message: TIMER_WORDS.not_found }); |
| 89 | 91 | } |
| 92 | ||
| 93 | const FINISH_STATUS = ["ok", "failed", "device_asleep"] as const; | |
| 94 | ||
| 95 | /** | |
| 96 | * An app says how a scheduled run it took ended: `{ run, status: "ok" | "failed" | "device_asleep", | |
| 97 | * error? }`, `run` being the `idempotency-key` it was sent. Only now is the run done; the rest retry | |
| 98 | * with backoff while attempts remain, and ask the owner when they are spent (`apps/timer_fire.ts`). | |
| 99 | */ | |
| 100 | export async function finishFor(app: App, secret: string, input: unknown): Promise<Result<true, { kind: TimerError; message: string }>> { | |
| 101 | const caller = callerOf(app, secret); | |
| 102 | if (caller === undefined) return err({ kind: "unauthorized", message: TIMER_WORDS.unauthorized }); | |
| 103 | const bad = (message: string) => err({ kind: "invalid" as const, message }); | |
| 104 | if (typeof input !== "object" || input === null || Array.isArray(input)) return bad("The body is a JSON object."); | |
| 105 | const o = input as Record<string, unknown>; | |
| 106 | if (Object.keys(o).some((k) => !["run", "status", "error"].includes(k))) return bad("Unknown field. The fields are run, status and error."); | |
| 107 | if (typeof o["run"] !== "string" || o["run"] === "" || o["run"].length > 300) return bad("`run` is the idempotency-key the run was sent with."); | |
| 108 | const status = FINISH_STATUS.find((x) => x === o["status"]); | |
| 109 | if (status === undefined) return bad("`status` is ok, failed or device_asleep."); | |
| 110 | const said = o["error"]; | |
| 111 | if (said !== undefined && (typeof said !== "string" || said.length > 2000)) return bad("`error` is text of at most 2000 characters."); | |
| 112 | const record = getAppById(app.db, caller.id); | |
| 113 | const settled = record === undefined ? false : await confirmRun(app.db, record, caller.env, o["run"], { status, error: said }); | |
| 114 | return settled ? ok(true) : err({ kind: "not_found", message: "No run of this app is waiting for confirmation under that run id." }); | |
| 115 | } |
src/apps/busy.ts +2 −1
| @@ -14,13 +14,14 @@ | ||
| 14 | 14 | |
| 15 | 15 | import { readdirSync, readFileSync } from "node:fs"; |
| 16 | 16 | |
| 17 | export type BusyReason = "children" | "stream" | "request"; | |
| 17 | export type BusyReason = "children" | "stream" | "request" | "run"; | |
| 18 | 18 | |
| 19 | 19 | /** Busy, in the words a page says it with. */ |
| 20 | 20 | export const BUSY_WORDS: Record<BusyReason, string> = { |
| 21 | 21 | children: "busy — its child processes are still working", |
| 22 | 22 | stream: "busy — a stream to it is still open", |
| 23 | 23 | request: "busy — a request is still waiting on its answer", |
| 24 | run: "busy — a scheduled run it took has not been confirmed finished", | |
| 24 | 25 | }; |
| 25 | 26 | |
| 26 | 27 | /** |
src/apps/runtime_sleep.ts +8
| @@ -23,6 +23,7 @@ import { appendRunLog } from "../runs/log.ts"; | ||
| 23 | 23 | import { beatAwake } from "../core/meter.ts"; |
| 24 | 24 | import { dropPreviewBuildCache } from "./build_cache.ts"; |
| 25 | 25 | import { BUSY_WORDS, busyReason } from "./busy.ts"; |
| 26 | import { awaitingRun } from "../core/timers.ts"; | |
| 26 | 27 | import { envBuild, envVariant, envDataDir, envDir, envPull, type EnvName } from "./data.ts"; |
| 27 | 28 | import { parseManifest } from "./manifest.ts"; |
| 28 | 29 | import { heldManifest } from "../core/starts.ts"; |
| @@ -455,6 +456,13 @@ export async function sweep(rt: AppsRuntime): Promise<void> { | ||
| 455 | 456 | : null); |
| 456 | 457 | if (limit === null) continue; |
| 457 | 458 | if (now - last < limit) continue; |
| 459 | // A scheduled run the app took and has not confirmed finished is work in flight: sleep never | |
| 460 | // cuts it. Not subject to the grace; the run's own deadline (`core/timers.ts`) ends it. | |
| 461 | if (awaitingRun(rt.app.db, state.app.id, state.env)) { | |
| 462 | if (spared !== "run" && live.runId !== "") appendRunLog(rt.app.config.dataDir, live.runId, `kept awake: ${BUSY_WORDS.run}`); | |
| 463 | state.keptAwake = "run"; | |
| 464 | continue; | |
| 465 | } | |
| 458 | 466 | // Idle by the clock; asked whether it is mid-work, and spared while |
| 459 | 467 | // it is — but only for one grace past the window, never forever. |
| 460 | 468 | const busy = busyReason( |
src/apps/timer_fire.ts +111 −25
| @@ -22,7 +22,7 @@ import { createHmac } from "node:crypto"; | ||
| 22 | 22 | import type { Database } from "bun:sqlite"; |
| 23 | 23 | import { getAppById, type AppRecord } from "../core/apps.ts"; |
| 24 | 24 | import { |
| 25 | dueTimers, finishTimer, recordRun, retryTimer, runsOf, setPaused, RESPONSE_KEPT, type Timer, type TimerRun, | |
| 25 | awaitingTimers, awaitTimer, dueTimers, finishTimer, recordRun, retryTimer, runsOf, setPaused, updateRun, RESPONSE_KEPT, type Timer, type TimerRun, | |
| 26 | 26 | } from "../core/timers.ts"; |
| 27 | 27 | import { nextRun, parseCron } from "./cron.ts"; |
| 28 | 28 | |
| @@ -118,7 +118,31 @@ async function readHead(res: Response): Promise<string> { | ||
| 118 | 118 | return new TextDecoder().decode(Buffer.concat(chunks)).slice(0, RESPONSE_KEPT).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "?"); |
| 119 | 119 | } |
| 120 | 120 | |
| 121 | interface Attempt { readonly final?: boolean; readonly ok: boolean; readonly status: number | null; readonly response: string | null; readonly error: string | null } | |
| 121 | /** What an app answers 2xx to say it took the work and has not finished it (never "done"). */ | |
| 122 | const WORKING = new Set(["accepted", "pending", "queued", "started", "running", "working", "printing", "in_progress", "in-progress"]); | |
| 123 | /** What it answers to say the device it drives did not answer: nothing happened. */ | |
| 124 | const DEVICE_ASLEEP = new Set(["device_asleep", "device-asleep", "asleep", "unreachable", "device_unreachable"]); | |
| 125 | ||
| 126 | /** | |
| 127 | * What a 2xx answer says about the work: finished (the default, for an app that answers when it is | |
| 128 | * done), working or the device asleep. | |
| 129 | */ | |
| 130 | function stateOf(status: number, head: string): "done" | "working" | "device_asleep" { | |
| 131 | if (status === 202) return "working"; | |
| 132 | try { | |
| 133 | const v = (JSON.parse(head) as { status?: unknown }).status; | |
| 134 | if (typeof v === "string") { | |
| 135 | const w = v.toLowerCase(); | |
| 136 | if (WORKING.has(w)) return "working"; | |
| 137 | if (DEVICE_ASLEEP.has(w)) return "device_asleep"; | |
| 138 | } | |
| 139 | } catch { | |
| 140 | // Not JSON: an answer in words is the app saying it is done. | |
| 141 | } | |
| 142 | return "done"; | |
| 143 | } | |
| 144 | ||
| 145 | interface Attempt { readonly pending?: boolean; readonly deviceAsleep?: boolean; readonly final?: boolean; readonly ok: boolean; readonly status: number | null; readonly response: string | null; readonly error: string | null } | |
| 122 | 146 | |
| 123 | 147 | async function attemptOnce(reach: Reach, app: AppRecord, t: Timer, attempt: number, now: () => number): Promise<Attempt> { |
| 124 | 148 | const port = await reach.ensure(app, t.env).catch(() => undefined); |
| @@ -133,7 +157,12 @@ async function attemptOnce(reach: Reach, app: AppRecord, t: Timer, attempt: numb | ||
| 133 | 157 | signal: AbortSignal.timeout(t.timeoutMs), |
| 134 | 158 | }); |
| 135 | 159 | const head = await readHead(res); |
| 136 | if (res.status >= 200 && res.status < 300) return { ok: true, status: res.status, response: head, error: null }; | |
| 160 | if (res.status >= 200 && res.status < 300) { | |
| 161 | const state = stateOf(res.status, head); | |
| 162 | if (state === "working") return { ok: false, pending: true, status: res.status, response: head, error: null }; | |
| 163 | if (state === "device_asleep") return { ok: false, deviceAsleep: true, status: res.status, response: head, error: failureText(head) ?? "the app says the device it drives is asleep or unreachable" }; | |
| 164 | return { ok: true, status: res.status, response: head, error: null }; | |
| 165 | } | |
| 137 | 166 | // An app that says `x-forge-no-retry` has decided: delivering again would only repeat it (a |
| 138 | 167 | // durable job that failed, #11596). |
| 139 | 168 | if (res.headers.get("x-forge-no-retry") === "1") return { ok: false, final: true, status: res.status, response: head, error: failureText(head) ?? `the app answered ${res.status}` }; |
| @@ -155,13 +184,14 @@ function nextOf(t: Timer, after: number): number | undefined { | ||
| 155 | 184 | |
| 156 | 185 | /** |
| 157 | 186 | * Whether the schedule has failed on each of the last five days with no success between (the newest |
| 158 | * runs first). | |
| 187 | * runs first). A device asleep counts as a failed day: the work did not happen, so a schedule | |
| 188 | * whose device sleeps every day pauses itself and asks the owner, not retries for ever. | |
| 159 | 189 | */ |
| 160 | 190 | export function failingDays(runs: readonly TimerRun[]): number { |
| 161 | 191 | const days = new Set<string>(); |
| 162 | 192 | for (const r of runs) { |
| 163 | 193 | if (r.status === "ok") break; |
| 164 | if (r.status === "failed" || r.status === "missed") days.add(iso(r.scheduledAt).slice(0, 10)); | |
| 194 | if (r.status === "failed" || r.status === "missed" || r.status === "device_asleep") days.add(iso(r.scheduledAt).slice(0, 10)); | |
| 165 | 195 | if (r.status === "paused") break; |
| 166 | 196 | } |
| 167 | 197 | return days.size; |
| @@ -193,34 +223,90 @@ export async function fireTimer(db: Database, reach: Reach, t: Timer, now: () => | ||
| 193 | 223 | finishTimer(db, t, nextOf(t, Math.max(t.scheduledAt, started - t.catchUpMs - 1))); |
| 194 | 224 | return; |
| 195 | 225 | } |
| 196 | const attempt = t.attempt + 1; | |
| 197 | const result = await attemptOnce(reach, app, t, attempt, now); | |
| 226 | const attempt = t.awaiting ? t.attempt : t.attempt + 1; | |
| 227 | // The deadline of a run the app took came with no confirmation: an unfinished attempt, however | |
| 228 | // the call answered. | |
| 229 | const result: Attempt = t.awaiting | |
| 230 | ? { ok: false, status: null, response: null, error: `the app did not confirm the work finished within ${Math.round(t.timeoutMs / 1000)} s` } | |
| 231 | : await attemptOnce(reach, app, t, attempt, now); | |
| 198 | 232 | const finished = now(); |
| 199 | 233 | const late = lateMs > LATE_AFTER_MS && t.attempt === 0 ? { lateMs, lateReason: "the forge was down or restarting at the scheduled time; it ran as soon as it was back" } : { lateMs: t.attempt === 0 ? 0 : lateMs, lateReason: t.attempt === 0 ? null : "retried after a failed attempt" }; |
| 200 | const next = t.kind === "schedule" ? nextOf(t, t.scheduledAt) : undefined; | |
| 201 | if (result.ok) { | |
| 202 | recordRun(db, { ...base, startedAt: started, finishedAt: finished, attempts: attempt, status: "ok", httpStatus: result.status, response: result.response, error: null, ...late, durationMs: finished - started }); | |
| 203 | finishTimer(db, t, next); | |
| 204 | return; | |
| 205 | } | |
| 206 | if (result.final !== true && attempt <= t.retries) return retryTimer(db, t.id, finished + backoffFor(t.attempt), attempt); | |
| 207 | recordRun(db, { | |
| 208 | ...base, startedAt: started, finishedAt: finished, attempts: attempt, status: "failed", httpStatus: result.status, response: result.response, | |
| 209 | error: result.final === true ? (result.error ?? "failed") : `${result.error ?? "failed"}, after ${attempt} ${attempt === 1 ? "attempt" : "attempts"}`, ...late, durationMs: finished - started, | |
| 210 | }); | |
| 211 | finishTimer(db, t, next); | |
| 212 | if (t.kind === "schedule" && failingDays(runsOf(db, t.appId, t.name, 30).filter((r) => r.env === t.env)) >= PAUSE_AFTER_DAYS) { | |
| 213 | setPaused(db, t.id, true, finished); | |
| 214 | recordRun(db, { | |
| 215 | ...base, startedAt: finished, finishedAt: finished, attempts: 0, status: "paused", httpStatus: null, response: null, durationMs: 0, | |
| 216 | error: `Paused itself: it failed ${PAUSE_AFTER_DAYS} days running. Resume it once the app is fixed.`, lateMs: 0, lateReason: null, | |
| 217 | }); | |
| 234 | const row = { ...base, startedAt: started, finishedAt: finished, attempts: attempt, httpStatus: result.status, response: result.response, ...late, durationMs: finished - started }; | |
| 235 | if (result.pending === true) { | |
| 236 | // The app took the work: it is running, not done. It stays awake and the next look is the | |
| 237 | // deadline. | |
| 238 | const runId = t.runId === null ? recordRun(db, { ...row, status: "running", error: null }) : (updateRun(db, t.runId, { ...row, status: "running", error: null }), t.runId); | |
| 239 | return awaitTimer(db, t.id, finished + t.timeoutMs, attempt, runId); | |
| 218 | 240 | } |
| 241 | await conclude(db, t, base, row, result); | |
| 219 | 242 | } finally { |
| 220 | 243 | inFlight.delete(t.id); |
| 221 | 244 | } |
| 222 | 245 | } |
| 223 | 246 | |
| 247 | /** | |
| 248 | * An attempt ended, by the app's answer or its confirmation: done, or retried with backoff, or | |
| 249 | * failed for good (and the owner asked). The occurrence's one row is updated in place when an | |
| 250 | * earlier attempt made it. | |
| 251 | */ | |
| 252 | async function conclude(db: Database, t: Timer, base: Pick<TimerRun, "appId" | "env" | "name" | "idemKey" | "scheduledAt">, row: Omit<TimerRun, "id" | "status" | "error">, result: Attempt): Promise<void> { | |
| 253 | const attempt = row.attempts; | |
| 254 | const finished = row.finishedAt; | |
| 255 | const next = t.kind === "schedule" ? nextOf(t, t.scheduledAt) : undefined; | |
| 256 | const put = (status: TimerRun["status"], error: string | null): number => | |
| 257 | t.runId === null ? recordRun(db, { ...row, status, error }) : (updateRun(db, t.runId, { ...row, status, error }), t.runId); | |
| 258 | if (result.ok) { | |
| 259 | put("ok", null); | |
| 260 | return finishTimer(db, t, next); | |
| 261 | } | |
| 262 | const state: TimerRun["status"] = result.deviceAsleep === true ? "device_asleep" : "failed"; | |
| 263 | if (result.final !== true && attempt <= t.retries) { | |
| 264 | const at = finished + backoffFor(attempt - 1); | |
| 265 | // An earlier attempt left a row: it says what is happening now. A first plain failure leaves | |
| 266 | // none, as it always did. | |
| 267 | let runId = t.runId; | |
| 268 | if (runId !== null || result.deviceAsleep === true) | |
| 269 | runId = put(result.deviceAsleep === true ? "device_asleep" : "running", `attempt ${attempt}: ${result.error ?? "failed"}; trying again ${new Date(at).toISOString()}`); | |
| 270 | retryTimer(db, t.id, at, attempt); | |
| 271 | if (runId !== null && runId !== t.runId) db.query("UPDATE timer SET run_id = ?2 WHERE id = ?1").run(t.id, runId); | |
| 272 | return; | |
| 273 | } | |
| 274 | put(state, result.final === true ? (result.error ?? "failed") : `${result.error ?? "failed"}, after ${attempt} ${attempt === 1 ? "attempt" : "attempts"}`); | |
| 275 | finishTimer(db, t, next); | |
| 276 | if (t.kind === "schedule" && failingDays(runsOf(db, t.appId, t.name, 30).filter((r) => r.env === t.env)) >= PAUSE_AFTER_DAYS) { | |
| 277 | setPaused(db, t.id, true, finished); | |
| 278 | recordRun(db, { | |
| 279 | ...base, startedAt: finished, finishedAt: finished, attempts: 0, status: "paused", httpStatus: null, response: null, durationMs: 0, | |
| 280 | error: `Paused itself: it failed ${PAUSE_AFTER_DAYS} days running. Resume it once the app is fixed.`, lateMs: 0, lateReason: null, | |
| 281 | }); | |
| 282 | } | |
| 283 | } | |
| 284 | ||
| 285 | /** | |
| 286 | * What an app tells the forge about a run it took: the work is `ok`, `failed`, or its device was | |
| 287 | * `device_asleep`. | |
| 288 | */ | |
| 289 | export interface Confirmation { readonly status: "ok" | "failed" | "device_asleep"; readonly error?: string | undefined } | |
| 290 | ||
| 291 | /** | |
| 292 | * The app confirms a run it took (`POST /api/v1/timers/finish`): the run is done only now. A | |
| 293 | * failure or a sleeping device is an unfinished attempt, retried with backoff while attempts remain | |
| 294 | * (the idempotency key is the same, so the app does the effect once). False when no run of the app | |
| 295 | * is waiting under that key. | |
| 296 | */ | |
| 297 | export async function confirmRun(db: Database, app: AppRecord, env: Timer["env"], run: string, c: Confirmation, now: () => number = Date.now): Promise<boolean> { | |
| 298 | const t = awaitingTimers(db, app.id, env).find((x) => idempotencyKey(app.slug, x) === run); | |
| 299 | if (t === undefined || inFlight.has(t.id)) return false; | |
| 300 | const finished = now(); | |
| 301 | const base = { appId: t.appId, env: t.env, name: t.name === "" ? t.key : t.name, idemKey: run, scheduledAt: t.scheduledAt }; | |
| 302 | const result: Attempt = c.status === "ok" | |
| 303 | ? { ok: true, status: null, response: null, error: null } | |
| 304 | : { ok: false, deviceAsleep: c.status === "device_asleep", status: null, response: null, error: (c.error ?? "").slice(0, 500) || (c.status === "device_asleep" ? "the device it drives is asleep or unreachable" : "the app reported the work failed") }; | |
| 305 | const row = { ...base, startedAt: finished, finishedAt: finished, attempts: t.attempt, httpStatus: null, response: null, lateMs: 0, lateReason: null, durationMs: 0 }; | |
| 306 | await conclude(db, t, base, row, result); | |
| 307 | return true; | |
| 308 | } | |
| 309 | ||
| 224 | 310 | /** Fire every timer due at `now()`; the count fired. A slow app delays only its own timer. */ |
| 225 | 311 | export async function fireDueTimers(db: Database, reach: Reach, now: () => number = Date.now): Promise<number> { |
| 226 | 312 | const due = dueTimers(db, now()); |
src/contract/openapi/routes/index.ts +1
| @@ -438,6 +438,7 @@ export { route as postApiV1Share } from "./postApiV1Share.ts"; | ||
| 438 | 438 | export { route as postApiV1Start } from "./postApiV1Start.ts"; |
| 439 | 439 | export { route as postApiV1Thoughts } from "./postApiV1Thoughts.ts"; |
| 440 | 440 | export { route as postApiV1Timers } from "./postApiV1Timers.ts"; |
| 441 | export { route as postApiV1TimersFinish } from "./postApiV1TimersFinish.ts"; | |
| 441 | 442 | export { route as postApiV1Tokens } from "./postApiV1Tokens.ts"; |
| 442 | 443 | export { route as postApiV1UserEmailVerify } from "./postApiV1UserEmailVerify.ts"; |
| 443 | 444 | export { route as postApiV1UserKeys } from "./postApiV1UserKeys.ts"; |
src/contract/openapi/routes/postApiV1TimersFinish.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/timers/finish", | |
| 6 | summary: "An app confirms how a scheduled run it took ended, with its own token", | |
| 7 | detail: "An app confirms how a scheduled run it took ended, with its own token: a run is done only now, not when its HTTP call returns; `run` is the idempotency-key it was sent; a failure or a sleeping device is retried with backoff and asks the owner when attempts are spent; answers 200", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | body: { run: "the idempotency-key the run was delivered with", status: "ok, failed or device_asleep", error: "optional: why it did not finish, up to 2000 characters" }, | |
| 11 | refusals: { | |
| 12 | invalid: "422: a field is wrong; the sentence names it", | |
| 13 | not_found: "404: no run of this app is waiting for confirmation under that run id", | |
| 14 | unauthorized: "401: not an app's own token", | |
| 15 | }, | |
| 16 | refuses: [401], | |
| 17 | }; |
src/core/migration-pins/20261123130000-timer-awaiting.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d0696df5df197ed0222cad324c325b0d7ff9ac769e58e626a0c7a62e17afbbab |
src/core/migrations/20261123130000-timer-awaiting.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // A run the app has not yet confirmed finished (#16099): `awaiting` is 1 while the forge waits for | |
| 2 | // the app to say the work is done (`due_at` is then its deadline, not a retry), and `run_id` is the | |
| 3 | // `timer_run` row that shows it as running. Both are cleared when the run settles. Additive. | |
| 4 | export default ` | |
| 5 | ALTER TABLE timer ADD COLUMN awaiting INTEGER NOT NULL DEFAULT 0; | |
| 6 | ALTER TABLE timer ADD COLUMN run_id INTEGER; | |
| 7 | `; |
src/core/timers.ts +45 −7
| @@ -36,9 +36,17 @@ export interface Timer { | ||
| 36 | 36 | readonly dueAt: number; |
| 37 | 37 | readonly attempt: number; |
| 38 | 38 | readonly paused: boolean; |
| 39 | /** The forge is waiting for the app to confirm the work finished; `dueAt` is the deadline. */ | |
| 40 | readonly awaiting: boolean; | |
| 41 | /** The `timer_run` row showing this occurrence as running or between attempts. */ | |
| 42 | readonly runId: number | null; | |
| 39 | 43 | } |
| 40 | 44 | |
| 41 | export type RunStatus = "ok" | "failed" | "missed" | "paused"; | |
| 45 | /** | |
| 46 | * `running`: the app took the work and has not said it finished (never ok); `device_asleep`: the | |
| 47 | * app says the device it drives did not answer, so nothing happened. | |
| 48 | */ | |
| 49 | export type RunStatus = "ok" | "failed" | "missed" | "paused" | "running" | "device_asleep"; | |
| 42 | 50 | |
| 43 | 51 | export interface TimerRun { |
| 44 | 52 | readonly id: number; |
| @@ -81,6 +89,8 @@ const toTimer = (r: Row): Timer => ({ | ||
| 81 | 89 | dueAt: r["due_at"] as number, |
| 82 | 90 | attempt: r["attempt"] as number, |
| 83 | 91 | paused: r["paused"] === 1, |
| 92 | awaiting: r["awaiting"] === 1, | |
| 93 | runId: (r["run_id"] as number | null) ?? null, | |
| 84 | 94 | }); |
| 85 | 95 | const toRun = (r: Row): TimerRun => ({ |
| 86 | 96 | id: r["id"] as number, |
| @@ -264,23 +274,51 @@ export function setPaused(db: Database, id: number, paused: boolean, now: number | ||
| 264 | 274 | /** A one-shot is done; a schedule re-arms for `next` with a fresh attempt count. */ |
| 265 | 275 | export function finishTimer(db: Database, t: Timer, next: number | undefined): void { |
| 266 | 276 | if (t.kind === "once" || next === undefined) db.query("DELETE FROM timer WHERE id = ?1").run(t.id); |
| 267 | else db.query("UPDATE timer SET scheduled_at = ?2, due_at = ?2, attempt = 0 WHERE id = ?1").run(t.id, next); | |
| 277 | else db.query("UPDATE timer SET scheduled_at = ?2, due_at = ?2, attempt = 0, awaiting = 0, run_id = NULL WHERE id = ?1").run(t.id, next); | |
| 268 | 278 | } |
| 269 | 279 | |
| 270 | 280 | /** Try again at `dueAt`: the occurrence keeps its scheduled time and key. */ |
| 271 | 281 | export function retryTimer(db: Database, id: number, dueAt: number, attempt: number): void { |
| 272 | db.query("UPDATE timer SET due_at = ?2, attempt = ?3 WHERE id = ?1").run(id, dueAt, attempt); | |
| 282 | db.query("UPDATE timer SET due_at = ?2, attempt = ?3, awaiting = 0 WHERE id = ?1").run(id, dueAt, attempt); | |
| 283 | } | |
| 284 | ||
| 285 | /** The app took the work: wait for its confirmation until `deadline`, shown by run row `runId`. */ | |
| 286 | export function awaitTimer(db: Database, id: number, deadline: number, attempt: number, runId: number): void { | |
| 287 | db.query("UPDATE timer SET due_at = ?2, attempt = ?3, awaiting = 1, run_id = ?4 WHERE id = ?1").run(id, deadline, attempt, runId); | |
| 288 | } | |
| 289 | ||
| 290 | /** | |
| 291 | * Whether an environment of the app has a run the app has not confirmed finished: it is not put to | |
| 292 | * sleep. | |
| 293 | */ | |
| 294 | export function awaitingRun(db: Database, appId: string, env: TimerEnv): boolean { | |
| 295 | return db.query("SELECT 1 FROM timer WHERE app_id = ?1 AND env = ?2 AND awaiting = 1 LIMIT 1").get(appId, env) !== null; | |
| 296 | } | |
| 297 | ||
| 298 | /** The timers of an app's environment still waiting on the app's confirmation. */ | |
| 299 | export function awaitingTimers(db: Database, appId: string, env: TimerEnv): Timer[] { | |
| 300 | return db.query<Row, [string, string]>("SELECT * FROM timer WHERE app_id = ?1 AND env = ?2 AND awaiting = 1").all(appId, env).map(toTimer); | |
| 273 | 301 | } |
| 274 | 302 | |
| 275 | 303 | export const RESPONSE_KEPT = 2048; |
| 276 | 304 | |
| 277 | export function recordRun(db: Database, r: Omit<TimerRun, "id">): void { | |
| 278 | db.query( | |
| 305 | export function recordRun(db: Database, r: Omit<TimerRun, "id">): number { | |
| 306 | const id = Number(db.query( | |
| 279 | 307 | `INSERT INTO timer_run (app_id, env, name, idem_key, scheduled_at, started_at, finished_at, attempts, status, http_status, response, error, late_ms, late_reason, duration_ms) |
| 280 | 308 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)`, |
| 281 | ).run(r.appId, r.env, r.name, r.idemKey, r.scheduledAt, r.startedAt, r.finishedAt, r.attempts, r.status, r.httpStatus, r.response?.slice(0, RESPONSE_KEPT) ?? null, r.error, r.lateMs, r.lateReason, r.durationMs); | |
| 309 | ).run(r.appId, r.env, r.name, r.idemKey, r.scheduledAt, r.startedAt, r.finishedAt, r.attempts, r.status, r.httpStatus, r.response?.slice(0, RESPONSE_KEPT) ?? null, r.error, r.lateMs, r.lateReason, r.durationMs).lastInsertRowid); | |
| 282 | 310 | // A history, not a log: the newest 200 runs of an app are kept. |
| 283 | 311 | db.query("DELETE FROM timer_run WHERE app_id = ?1 AND id <= (SELECT id FROM timer_run WHERE app_id = ?1 ORDER BY id DESC LIMIT 1 OFFSET 200)").run(r.appId); |
| 312 | return id; | |
| 313 | } | |
| 314 | ||
| 315 | /** | |
| 316 | * Settle or update a run's row in place: one occurrence is one row, however many attempts. Its | |
| 317 | * start and lateness stay as the first attempt wrote them; the answer is kept when none is given. | |
| 318 | */ | |
| 319 | export function updateRun(db: Database, id: number, r: Pick<TimerRun, "finishedAt" | "attempts" | "status" | "httpStatus" | "response" | "error">): void { | |
| 320 | db.query("UPDATE timer_run SET finished_at = ?2, duration_ms = ?2 - started_at, attempts = ?3, status = ?4, http_status = COALESCE(?5, http_status), response = COALESCE(?6, response), error = ?7 WHERE id = ?1") | |
| 321 | .run(id, r.finishedAt, r.attempts, r.status, r.httpStatus, r.response?.slice(0, RESPONSE_KEPT) ?? null, r.error); | |
| 284 | 322 | } |
| 285 | 323 | |
| 286 | 324 | /** Runs of the app, newest first; of one schedule when `name` is given. */ |
| @@ -299,7 +337,7 @@ export function failingNow(db: Database, appId: string): TimerRun[] { | ||
| 299 | 337 | const out: TimerRun[] = []; |
| 300 | 338 | for (const t of scheduleTimers(db, appId)) { |
| 301 | 339 | const r = db.query<Row, [string, string, string]>("SELECT * FROM timer_run WHERE app_id = ?1 AND name = ?2 AND env = ?3 ORDER BY id DESC LIMIT 1").get(appId, t.name, t.env); |
| 302 | if (r !== null && r["status"] !== "ok") out.push(toRun(r)); | |
| 340 | if (r !== null && r["status"] !== "ok" && r["status"] !== "running") out.push(toRun(r)); | |
| 303 | 341 | } |
| 304 | 342 | return out; |
| 305 | 343 | } |
src/http/api/timers.ts +17 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | * and cancels its own timers with its own token (`actions/timers.ts`). |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import { armFor, cancelFor, type TimerError } from "../../actions/timers.ts"; | |
| 6 | import { armFor, cancelFor, finishFor, type TimerError } from "../../actions/timers.ts"; | |
| 7 | 7 | import type { Handler } from "../context.ts"; |
| 8 | 8 | import { BODY_CAPS, readBounded } from "../limits.ts"; |
| 9 | 9 | import { refuseDirtyJson } from "../parseable_request.ts"; |
| @@ -31,6 +31,22 @@ export function timersRoutes(router: Router<Handler>): void { | ||
| 31 | 31 | if (!armed.ok) return apiError(armed.error.kind, STATUS[armed.error.kind], armed.error.message); |
| 32 | 32 | return json({ timer: armed.value }, 201); |
| 33 | 33 | }); |
| 34 | router.add("POST", "/api/v1/timers/finish", async (ctx) => { | |
| 35 | const secret = tokenSecret(ctx.request.headers.get("authorization") ?? ""); | |
| 36 | if (secret === null) return unauthorized(); | |
| 37 | const raw = await readBounded(ctx.request, BODY_CAPS.timerArm.bytes); | |
| 38 | if (raw === "too_large") return apiError("invalid", 422, "The body is small JSON."); | |
| 39 | let input: unknown; | |
| 40 | try { | |
| 41 | input = JSON.parse(new TextDecoder().decode(raw)); | |
| 42 | } catch { | |
| 43 | return apiError("invalid", 422, "The body is JSON."); | |
| 44 | } | |
| 45 | refuseDirtyJson(input); | |
| 46 | const done = await finishFor(ctx.app, secret, input); | |
| 47 | if (!done.ok) return apiError(done.error.kind, STATUS[done.error.kind], done.error.message); | |
| 48 | return json({}, 200); | |
| 49 | }); | |
| 34 | 50 | router.add("DELETE", "/api/v1/timers/:key", (ctx) => { |
| 35 | 51 | const secret = tokenSecret(ctx.request.headers.get("authorization") ?? ""); |
| 36 | 52 | if (secret === null) return unauthorized(); |
test/apps-sleep.test.ts +19
| @@ -14,6 +14,7 @@ import { commitToBranch } from "../src/actions/repos.ts"; | ||
| 14 | 14 | import type { AppRecord } from "../src/core/apps.ts"; |
| 15 | 15 | import type { Repo } from "../src/core/repos.ts"; |
| 16 | 16 | import { listRuns, type Run } from "../src/core/runs.ts"; |
| 17 | import { armTimer } from "../src/core/timers.ts"; | |
| 17 | 18 | import { createUser, type User } from "../src/core/users.ts"; |
| 18 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 19 | 20 | import { readRunLog } from "../src/runs/log.ts"; |
| @@ -167,6 +168,24 @@ describe("apps that sleep", () => { | ||
| 167 | 168 | expect(stateOf("production")).toBe("running"); |
| 168 | 169 | }, 15_000); |
| 169 | 170 | |
| 171 | test("past its window an app still holds a run it has not confirmed finished, and sleeps once it is", async () => { | |
| 172 | expect(stateOf("production")).toBe("running"); | |
| 173 | armTimer(app.db, { appId: record.id, env: "production", key: "run-1", path: "/jobs/x", at: Date.now(), timeoutMs: 300_000, retries: 1 }, Date.now()); | |
| 174 | app.db.query("UPDATE timer SET awaiting = 1, due_at = ?1 WHERE app_id = ?2").run(Date.now() + 3 * HOUR, record.id); | |
| 175 | ahead = 2 * HOUR; | |
| 176 | try { | |
| 177 | await runtime.sweep(); | |
| 178 | await runtime.sweep(); | |
| 179 | expect(stateOf("production")).toBe("running"); | |
| 180 | expect(runtime.status(record).find((e) => e.env === "production")!.busy).toContain("scheduled run"); | |
| 181 | app.db.query("DELETE FROM timer WHERE app_id = ?1").run(record.id); | |
| 182 | await until(() => (stateOf("production") === "asleep" ? true : undefined), 5_000); | |
| 183 | } finally { | |
| 184 | ahead = 0; | |
| 185 | } | |
| 186 | expect((await viaHost(`hello.${DOMAIN}`)).status).toBe(200); | |
| 187 | }, 15_000); | |
| 188 | ||
| 170 | 189 | test("the forge coming back starts production warm and leaves previews asleep", async () => { |
| 171 | 190 | const branch = await commitToBranch(app, alice, repo, { |
| 172 | 191 | branch: "feature/greeting", |
test/schedules-doors.test.ts +26 −1
| @@ -13,7 +13,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 13 | 13 | import { createRepo } from "../src/actions/repos.ts"; |
| 14 | 14 | import { scheduleRows, scheduleRuns } from "../src/actions/schedules.ts"; |
| 15 | 15 | import { parseSchedules } from "../src/apps/schedule_spec.ts"; |
| 16 | import { createApp as insertApp } from "../src/core/apps.ts"; | |
| 16 | import { createApp as insertApp, getAppByRepo } from "../src/core/apps.ts"; | |
| 17 | 17 | import type { Repo } from "../src/core/repos.ts"; |
| 18 | 18 | import { recordRun, syncSchedules } from "../src/core/timers.ts"; |
| 19 | 19 | import { createUser, type User } from "../src/core/users.ts"; |
| @@ -99,6 +99,31 @@ describe("a run's answer and error are a writer's", () => { | ||
| 99 | 99 | }); |
| 100 | 100 | |
| 101 | 101 | describe("the terminal screen", () => { |
| 102 | test("running and device_asleep read in the terminal's rows as on the page, retry text with them", () => { | |
| 103 | const specs = parseSchedules([{ name: "print", cron: "30 6 * * *", timezone: "UTC", path: "/jobs/print" }, { name: "zink", cron: "30 6 * * *", timezone: "UTC", path: "/jobs/zink" }]); | |
| 104 | if (!specs.ok) throw new Error(specs.error); | |
| 105 | const rec = getAppByRepo(app.db, pub.id)!; | |
| 106 | syncSchedules(app.db, rec.id, "production", specs.value, "c1", Date.parse("2026-11-12T00:00:00Z")); | |
| 107 | const note = "attempt 1: the device is asleep; trying again 2026-11-23T13:16:00.000Z"; | |
| 108 | for (const status of ["running", "device_asleep"] as const) | |
| 109 | recordRun(app.db, { appId: rec.id, env: "production", name: "zink", idemKey: `zink:${status}`, scheduledAt: 9, startedAt: 9, finishedAt: 9, attempts: 1, status, httpStatus: null, response: null, error: note, lateMs: 0, lateReason: null, durationMs: 0 }); | |
| 110 | const lines = (): string[] => { | |
| 111 | const rows = scheduleRows(app, cy, pub); | |
| 112 | return rows.ok ? rows.value.filter((r) => r.name === "zink").map((r) => `${r.line}|${r.last?.error ?? ""}`) : []; | |
| 113 | }; | |
| 114 | // The terminal's screen draws these same rows (`line`, and the error as the note). | |
| 115 | expect(lines()[0]).toContain("last device_asleep"); | |
| 116 | expect(lines()[0]).toContain(note); | |
| 117 | expect(schedulesScreen(session(cy), ctxWith(), pub).title).toContain("Schedules"); | |
| 118 | app.db.query("DELETE FROM timer_run WHERE name = 'zink' AND idem_key = 'zink:device_asleep'").run(); | |
| 119 | expect(lines()[0]).toContain("last running"); | |
| 120 | expect(lines()[0]).toContain(note); | |
| 121 | const only = parseSchedules([{ name: "print", cron: "30 6 * * *", timezone: "UTC", path: "/jobs/print" }]); | |
| 122 | if (!only.ok) throw new Error(only.error); | |
| 123 | syncSchedules(app.db, rec.id, "production", only.value, "c2", Date.parse("2026-11-12T00:00:00Z")); | |
| 124 | app.db.query("DELETE FROM timer_run WHERE name = 'zink'").run(); | |
| 125 | }); | |
| 126 | ||
| 102 | 127 | test("a reader sees the rows and is refused writes; a guest cannot steer", () => { |
| 103 | 128 | expect(schedulesCommands(session(dee), ctxWith(), pub)).toHaveLength(1); |
| 104 | 129 | expect(schedulesCommands(session(cy), ctxWith(), undefined)).toEqual([]); |
test/timers-api.test.ts +26
| @@ -17,6 +17,7 @@ import { createApp as insertApp } from "../src/core/apps.ts"; | ||
| 17 | 17 | import { createToken } from "../src/core/tokens.ts"; |
| 18 | 18 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 19 | 19 | import { dueTimers, recordRun, syncSchedules } from "../src/core/timers.ts"; |
| 20 | import { fireTimer, type Reach } from "../src/apps/timer_fire.ts"; | |
| 20 | 21 | import { serve, type Servers } from "../src/http/server.ts"; |
| 21 | 22 | import { promote } from "./helpers/members.ts"; |
| 22 | 23 | |
| @@ -91,6 +92,31 @@ describe("timers over the API and the page", () => { | ||
| 91 | 92 | expect((await call("POST", "/api/v1/timers", appToken, bad)).status).toBe(422); |
| 92 | 93 | }); |
| 93 | 94 | |
| 95 | test("an app confirms a run it took with its own token; a person's token, bad input and an unknown run do not", async () => { | |
| 96 | // The real fire path: the timer comes due, the app's answer is "printing", the run is running. | |
| 97 | let run = ""; | |
| 98 | const reach: Reach = { | |
| 99 | ensure: async () => 4321, | |
| 100 | identityKey: (id) => `key-of-${id}`, | |
| 101 | fetch: (async (_url: string, init: RequestInit) => { | |
| 102 | run = (init.headers as Record<string, string>)["idempotency-key"]!; | |
| 103 | return Response.json({ status: "printing" }); | |
| 104 | }) as unknown as typeof fetch, | |
| 105 | }; | |
| 106 | expect((await call("POST", "/api/v1/timers", appToken, { in: 5, path: "/a", key: "conf-1" })).status).toBe(201); | |
| 107 | const soon = () => Date.now() + 60_000; | |
| 108 | const armed = dueTimers(app.db, soon()).find((t) => t.key === "conf-1")!; | |
| 109 | await fireTimer(app.db, reach, armed, soon); | |
| 110 | expect(run).toContain("conf-1"); | |
| 111 | expect((await call("POST", "/api/v1/timers/finish", ownerRw, { run, status: "ok" })).status).toBe(401); | |
| 112 | expect((await call("POST", "/api/v1/timers/finish", appToken, { run, status: "done" })).status).toBe(422); | |
| 113 | expect((await call("POST", "/api/v1/timers/finish", appToken, { run: "nope", status: "ok" })).status).toBe(404); | |
| 114 | expect((await call("POST", "/api/v1/timers/finish", appToken, { run, status: "ok" })).status).toBe(200); | |
| 115 | expect(app.db.query("SELECT COUNT(*) AS n FROM timer WHERE key = 'conf-1'").get()).toEqual({ n: 0 }); | |
| 116 | expect((await call("POST", "/api/v1/timers/finish", appToken, { run, status: "ok" })).status).toBe(404); | |
| 117 | app.db.query("DELETE FROM timer_run").run(); | |
| 118 | }); | |
| 119 | ||
| 94 | 120 | test("the per-app limit is a setting", async () => { |
| 95 | 121 | process.env["FORGE_TIMERS_PER_APP"] = "2"; |
| 96 | 122 | try { |
test/timers-confirmed.test.ts added +184
| @@ -0,0 +1,184 @@ | ||
| 1 | /** | |
| 2 | * A scheduled run is done only when the app says so (#16099): "still printing" is running, never | |
| 3 | * ok; the same run id comes with every retry so the effect happens once; a device that is asleep | |
| 4 | * is retried and asked about; an app put to sleep, or the forge restarted, mid-run loses nothing. | |
| 5 | */ | |
| 6 | import { Database } from "bun:sqlite"; | |
| 7 | import { describe, expect, test } from "bun:test"; | |
| 8 | import { confirmRun, failingDays, fireDueTimers, type Reach } from "../src/apps/timer_fire.ts"; | |
| 9 | import { createApp } from "../src/core/apps.ts"; | |
| 10 | import { migrationFiles } from "../src/core/schema.ts"; | |
| 11 | import { migrate } from "../src/kernel/migrate.ts"; | |
| 12 | import { awaitingRun, failingNow, runsOf, type TimerRun, syncSchedules, scheduleTimer } from "../src/core/timers.ts"; | |
| 13 | import { parseSchedules } from "../src/apps/schedule_spec.ts"; | |
| 14 | ||
| 15 | const at = (s: string): number => Date.parse(s); | |
| 16 | const template = (() => { | |
| 17 | const db = new Database(":memory:"); | |
| 18 | migrate(db, migrationFiles); | |
| 19 | const bytes = db.serialize(); | |
| 20 | db.close(); | |
| 21 | return bytes; | |
| 22 | })(); | |
| 23 | ||
| 24 | /** An app that prints once per run id, and a printer that may be asleep. */ | |
| 25 | function world() { | |
| 26 | let db = Database.deserialize(template); | |
| 27 | const made = createApp(db, { repoId: "r1", slug: "paper", access: "private" }); | |
| 28 | if (!made.ok) throw new Error(made.error); | |
| 29 | const app = made.value; | |
| 30 | const w = { asleep: false, deviceAsleep: true, printed: new Set<string>(), keys: [] as string[] }; | |
| 31 | const reach: Reach = { | |
| 32 | async ensure() { | |
| 33 | w.asleep = false; | |
| 34 | return 4321; | |
| 35 | }, | |
| 36 | identityKey: (id) => `key-of-${id}`, | |
| 37 | fetch: (async (_url: string, init: RequestInit) => { | |
| 38 | const key = (init.headers as Record<string, string>)["idempotency-key"]!; | |
| 39 | w.keys.push(key); | |
| 40 | if (w.deviceAsleep) return Response.json({ status: "device_asleep" }); | |
| 41 | w.printed.add(key); | |
| 42 | return Response.json({ status: "printing", why: "still printing" }); | |
| 43 | }) as unknown as typeof fetch, | |
| 44 | }; | |
| 45 | let clock = at("2026-11-23T13:15:00Z"); | |
| 46 | const parsed = parseSchedules([{ name: "print", cron: "15 7 * * *", timezone: "America/Chicago", path: "/jobs/print", retries: 2 }]); | |
| 47 | if (!parsed.ok) throw new Error(parsed.error); | |
| 48 | syncSchedules(db, app.id, "production", parsed.value, "c1", clock - 60_000); | |
| 49 | return { | |
| 50 | get db() { return db; }, app, w, reach, now: () => clock, advance: (ms: number) => void (clock += ms), | |
| 51 | /** The forge restarts: only the database file survives. */ | |
| 52 | restart() { db = Database.deserialize(db.serialize()); }, | |
| 53 | }; | |
| 54 | } | |
| 55 | const status = (x: ReturnType<typeof world>): string[] => runsOf(x.db, x.app.id).map((r) => r.status); | |
| 56 | ||
| 57 | describe("a scheduled run is done when the app confirms it", () => { | |
| 58 | test("a 200 'printing' is running, not ok; the app stays awake; confirmation makes it ok", async () => { | |
| 59 | const x = world(); | |
| 60 | x.w.deviceAsleep = false; | |
| 61 | await fireDueTimers(x.db, x.reach, x.now); | |
| 62 | expect(status(x)).toEqual(["running"]); | |
| 63 | expect(awaitingRun(x.db, x.app.id, "production")).toBe(true); | |
| 64 | expect(failingNow(x.db, x.app.id)).toHaveLength(0); | |
| 65 | const run = "paper:print:2026-11-23T13:15:00.000Z"; | |
| 66 | expect(await confirmRun(x.db, x.app, "production", "paper:print:other", { status: "ok" }, x.now)).toBe(false); | |
| 67 | x.advance(20_000); | |
| 68 | expect(await confirmRun(x.db, x.app, "production", run, { status: "ok" }, x.now)).toBe(true); | |
| 69 | const [r] = runsOf(x.db, x.app.id); | |
| 70 | expect([r!.status, r!.attempts, r!.durationMs]).toEqual(["ok", 1, 20_000]); | |
| 71 | expect(awaitingRun(x.db, x.app.id, "production")).toBe(false); | |
| 72 | // Re-armed for tomorrow; confirming twice is refused. | |
| 73 | expect(new Date(scheduleTimer(x.db, x.app.id, "print", "production")!.dueAt).toISOString()).toBe("2026-11-24T13:15:00.000Z"); | |
| 74 | expect(await confirmRun(x.db, x.app, "production", run, { status: "ok" }, x.now)).toBe(false); | |
| 75 | }); | |
| 76 | ||
| 77 | test("a device that starts asleep is retried with the same run id, then done once it wakes", async () => { | |
| 78 | const x = world(); | |
| 79 | await fireDueTimers(x.db, x.reach, x.now); | |
| 80 | expect(status(x)).toEqual(["device_asleep"]); | |
| 81 | expect(failingNow(x.db, x.app.id)).toHaveLength(1); // the owner is told, not "ok" | |
| 82 | x.advance(31_000); | |
| 83 | x.w.deviceAsleep = false; | |
| 84 | await fireDueTimers(x.db, x.reach, x.now); | |
| 85 | expect(status(x)).toEqual(["running"]); | |
| 86 | expect(x.w.keys).toEqual(Array(2).fill("paper:print:2026-11-23T13:15:00.000Z")); | |
| 87 | await confirmRun(x.db, x.app, "production", x.w.keys[0]!, { status: "ok" }, x.now); | |
| 88 | const [r] = runsOf(x.db, x.app.id); | |
| 89 | expect([r!.status, r!.attempts, x.w.printed.size]).toEqual(["ok", 2, 1]); | |
| 90 | }); | |
| 91 | ||
| 92 | test("sleep and a forge restart mid-run lose nothing: no confirmation by the deadline retries, the same id", async () => { | |
| 93 | const x = world(); | |
| 94 | x.w.deviceAsleep = false; | |
| 95 | await fireDueTimers(x.db, x.reach, x.now); | |
| 96 | x.w.asleep = true; // the app was put to sleep mid-run | |
| 97 | x.restart(); // and the forge restarted | |
| 98 | expect(awaitingRun(x.db, x.app.id, "production")).toBe(true); | |
| 99 | x.advance(299_000); | |
| 100 | expect(await fireDueTimers(x.db, x.reach, x.now)).toBe(0); // still inside its deadline | |
| 101 | x.advance(2_000); | |
| 102 | await fireDueTimers(x.db, x.reach, x.now); // deadline: unconfirmed, retried after backoff | |
| 103 | expect(status(x)).toEqual(["running"]); | |
| 104 | expect(runsOf(x.db, x.app.id)[0]!.error).toContain("did not confirm"); | |
| 105 | expect(awaitingRun(x.db, x.app.id, "production")).toBe(false); | |
| 106 | x.advance(31_000); | |
| 107 | await fireDueTimers(x.db, x.reach, x.now); | |
| 108 | expect(x.w.keys).toHaveLength(2); | |
| 109 | expect(new Set(x.w.keys).size).toBe(1); | |
| 110 | expect(runsOf(x.db, x.app.id)[0]!.attempts).toBe(2); | |
| 111 | x.restart(); | |
| 112 | expect(await confirmRun(x.db, x.app, "production", x.w.keys[0]!, { status: "ok" }, x.now)).toBe(true); | |
| 113 | expect(status(x)).toEqual(["ok"]); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a run never confirmed fails after its attempts and asks the owner; a reported failure retries first", async () => { | |
| 117 | const x = world(); | |
| 118 | x.w.deviceAsleep = false; | |
| 119 | await fireDueTimers(x.db, x.reach, x.now); | |
| 120 | await confirmRun(x.db, x.app, "production", x.w.keys[0]!, { status: "failed", error: "paper jam" }, x.now); | |
| 121 | expect(status(x)).toEqual(["running"]); | |
| 122 | expect(runsOf(x.db, x.app.id)[0]!.error).toContain("paper jam"); | |
| 123 | for (let i = 0; i < 6; i++) { | |
| 124 | x.advance(3_700_000); | |
| 125 | await fireDueTimers(x.db, x.reach, x.now); | |
| 126 | } | |
| 127 | const [r] = runsOf(x.db, x.app.id); | |
| 128 | expect([r!.status, r!.attempts]).toEqual(["failed", 3]); | |
| 129 | expect(r!.error).toContain("did not confirm"); | |
| 130 | expect(failingNow(x.db, x.app.id).map((f) => f.status)).toEqual(["failed"]); | |
| 131 | }); | |
| 132 | ||
| 133 | test("an app that answers 200 with a finished body is done at once, as before", async () => { | |
| 134 | const x = world(); | |
| 135 | const done: Reach = { ...x.reach, fetch: (async () => new Response("printed 3 pages")) as unknown as typeof fetch }; | |
| 136 | await fireDueTimers(x.db, done, x.now); | |
| 137 | expect(status(x)).toEqual(["ok"]); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a 2xx device_asleep that spends its retries ends device_asleep and asks the owner", async () => { | |
| 141 | const x = world(); // the device answers asleep every time | |
| 142 | for (let i = 0; i < 6; i++) { | |
| 143 | await fireDueTimers(x.db, x.reach, x.now); | |
| 144 | x.advance(3_700_000); | |
| 145 | } | |
| 146 | expect(x.w.keys).toHaveLength(3); | |
| 147 | const [r] = runsOf(x.db, x.app.id); | |
| 148 | expect([r!.status, r!.attempts]).toEqual(["device_asleep", 3]); | |
| 149 | expect(r!.error).toContain("after 3 attempts"); | |
| 150 | expect(failingNow(x.db, x.app.id).map((f) => f.status)).toEqual(["device_asleep"]); | |
| 151 | }); | |
| 152 | ||
| 153 | test("a confirmation after the deadline has retried is refused; so is a second one", async () => { | |
| 154 | const x = world(); | |
| 155 | x.w.deviceAsleep = false; | |
| 156 | await fireDueTimers(x.db, x.reach, x.now); | |
| 157 | const run = x.w.keys[0]!; | |
| 158 | x.advance(301_000); | |
| 159 | await fireDueTimers(x.db, x.reach, x.now); // deadline: retried | |
| 160 | expect(await confirmRun(x.db, x.app, "production", run, { status: "ok" }, x.now)).toBe(false); | |
| 161 | expect(status(x)).toEqual(["running"]); | |
| 162 | }); | |
| 163 | }); | |
| 164 | ||
| 165 | describe("a device asleep is a failed day", () => { | |
| 166 | const run = (day: number, status: TimerRun["status"]): TimerRun => | |
| 167 | ({ id: day, appId: "a", env: "production", name: "n", idemKey: "k", scheduledAt: Date.UTC(2026, 10, day), startedAt: 0, finishedAt: 0, attempts: 1, status, httpStatus: null, response: null, error: null, lateMs: 0, lateReason: null, durationMs: 0 }) as TimerRun; | |
| 168 | test("failingDays counts device_asleep days, and an ok ends the count", () => { | |
| 169 | expect(failingDays([20, 19, 18, 17, 16].map((d) => run(d, "device_asleep")))).toBe(5); | |
| 170 | expect(failingDays([run(20, "device_asleep"), run(19, "failed"), run(18, "ok"), run(17, "failed")])).toBe(2); | |
| 171 | }); | |
| 172 | ||
| 173 | test("a schedule whose device sleeps five days running pauses itself", async () => { | |
| 174 | const x = world(); | |
| 175 | for (let day = 0; day < 6; day++) { | |
| 176 | for (let i = 0; i < 4; i++) { | |
| 177 | await fireDueTimers(x.db, x.reach, x.now); | |
| 178 | x.advance(3_700_000); | |
| 179 | } | |
| 180 | x.advance(86_400_000 - 4 * 3_700_000); | |
| 181 | } | |
| 182 | expect(runsOf(x.db, x.app.id, undefined, 100).some((r) => r.status === "paused")).toBe(true); | |
| 183 | }); | |
| 184 | }); |
new above
offline