Public: anyone can read this; the crew can change it.
Lent runners: a peer forge can lend check compute, scoped to public pulls, budgeted, sampled and revocable #16836
Check · Review · Land · Live done — Landed and live in production.
lend-runners → main 0 commits 3 threads · 3 unresolved
24 files
changed +1225
−83
- docs/features/lent-runners.md
- docs/features/runners.md
- docs/features/settings-runners.md
- src/actions/runners.ts
- src/checks/lent_scope.ts
- src/checks/run_tier.ts
- src/checks/runner_jobs.ts
- src/checks/runner_step.ts
- src/checks/tier_runner.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1AdminRunners.ts
- src/contract/openapi/routes/postApiV1AdminRunnersIdResume.ts
- src/contract/openapi/routes/postApiV1AdminRunnersIdRevoke.ts
- src/core/account_purge.ts
- src/core/migration-pins/20261130140000-lent-runner-scope.pin
- src/core/migrations/20261130140000-lent-runner-scope.ts
- src/http/api/runners.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/kernel/destroy_reach.ts
- src/tui/screens/runners.ts
- src/web/pages/capacity.ts
- src/web/pages/runners.ts
- test/lent-runners.test.ts
docs/features/lent-runners.md added +112
| @@ -0,0 +1,112 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Lent runners: another forge runs your public checks, scoped, sampled and revocable | |
| 4 | --- | |
| 5 | # Lent runners: one forge runs another's checks | |
| 6 | ||
| 7 | Two forges that know each other can share check compute. Say forge **A** borrows and forge **B** | |
| 8 | lends. A enrols a runner for B and holds it to a scope. B runs that runner on B's machine, | |
| 9 | pointed at A. Nothing dials into B: the runner long-polls A's `POST /api/v1/runner/claim` with | |
| 10 | a token A issued, as any runner does ([](runners.md)). | |
| 11 | ||
| 12 | ## What B's machine is sent | |
| 13 | ||
| 14 | A job is a public repository's commit, its history back to the base the check compares | |
| 15 | against (only through a git door that serves those commits), the recipe from `forge.json`, and | |
| 16 | plain variables: `CI`, `FORGE_URL`, the run id, the commit, the shard count and file names. It | |
| 17 | also carries its own job token, which fetches that one job and reports on it while its lease | |
| 18 | lives. A job carries no secret, no account token and none of A's environment. B sees nothing it | |
| 19 | could not clone itself. | |
| 20 | ||
| 21 | ## What a lent runner may claim | |
| 22 | ||
| 23 | A runner whose name starts `lent-` is held to a scope, and the claim enforces it | |
| 24 | (`src/checks/lent_scope.ts`, `claimJob` in `src/checks/runner_jobs.ts`). It is never left to | |
| 25 | trust: | |
| 26 | ||
| 27 | - **Public repositories only.** This is a hard rule in v1, checked against the repository as it | |
| 28 | stands at the claim, so a repository made private while its job waits is out of scope. | |
| 29 | - **Authors**, optional: only pulls by these logins (a pull mirrored from an origin is matched by | |
| 30 | the origin's login). This is the guest case, where B's compute runs only B's people's pulls. | |
| 31 | - **An expiry**: 30 days by default, at most 365. | |
| 32 | - **A budget** of core-minutes per UTC day: 240 by default. A core-minute is wall time from claim | |
| 33 | to answer × the job's declared `limits.cpus` (1 when none). The budget is checked at each | |
| 34 | claim, so a job that starts under it runs to its end. | |
| 35 | - **A cell, always.** It claims nothing unless it says it has cells, and every job it is sent says | |
| 36 | `cell: required`. A's code runs in a cell on B's machine (bubblewrap, so on Linux). | |
| 37 | ||
| 38 | A runner A owns has no scope and claims as before. A `lent-` runner enrolled before scopes takes | |
| 39 | the defaults from the day it was enrolled. | |
| 40 | ||
| 41 | ## How A trusts the answer | |
| 42 | ||
| 43 | A lent runner's answer stands only as green, the check's own exit code or its timeout, as for any | |
| 44 | runner. On top of that: | |
| 45 | ||
| 46 | - **Sample re-runs.** Every green from a lent runner's first 5 jobs is run again on A's own | |
| 47 | machine, then about 15% of its greens. The share is picked by a hash of the job id under a salt | |
| 48 | that never leaves A, so B cannot tell which ones. A's own verdict is the one that stands. If | |
| 49 | A's run is red, the runner is **paused**, with the commit named. A run here that was cancelled, | |
| 50 | or that failed on the machine's account, proves nothing either way. | |
| 51 | - **Canaries.** A lent runner's first claim, and about 1 in 20 after it, is a canary: a real | |
| 52 | queued job's repository and commit with a check that must fail. A green back means the runner | |
| 53 | did not run it, and the runner is paused. A canary is only ever claimed by its own runner, and | |
| 54 | it leaves the desk once answered. | |
| 55 | ||
| 56 | A paused runner claims nothing until an admin resumes it. Each pause is a `runner.paused` event. | |
| 57 | ||
| 58 | ## The recipe | |
| 59 | ||
| 60 | **A, the borrower** (a forge admin): | |
| 61 | ||
| 62 | 1. Make sure checks are offered to runners: `FORGE_CHECKS_PLACEMENT=runner` ([](runners.md)). | |
| 63 | 2. Enrol the lent runner and copy the token, which is shown once: | |
| 64 | ||
| 65 | sh | |
| 66 | curl -s -X POST https://a.forge/api/v1/admin/runners \ | |
| 67 | -H "authorization: Bearer " -H 'content-type: application/json' \ | |
| 68 | -d '{"name": "benjiver", "lend": {"days": 30, "coreMinPerDay": 240, "authors": []}}' | |
| 69 | ||
| 70 | ||
| 71 | The answer is the row (`lent-benjiver`, its `scope`) and its `token`. Every `lend` field is | |
| 72 | optional; `"lend": {}` takes the defaults. | |
| 73 | ||
| 74 | 3. Send B the forge URL and the token over a private channel. | |
| 75 | ||
| 76 | **B, the lender**, on a Linux machine with bubblewrap and a checkout of the forge: | |
| 77 | ||
| 78 | sh | |
| 79 | FORGE_URL=https://a.forge FORGE_RUNNER_TOKEN=forge_runner_… FORGE_RUNNER_JOBS=2 bun src/runner/main.ts | |
| 80 | ||
| 81 | ||
| 82 | `FORGE_RUNNER_JOBS` caps how many of A's jobs run at once, and each job is held to the cpus, | |
| 83 | memory and disk its `forge.json` declares. B stops lending by stopping the process. | |
| 84 | ||
| 85 | ## Seeing it and stopping it | |
| 86 | ||
| 87 | **Settings → Runners** (`/settings/runners`) and **Runners** in the terminal | |
| 88 | (`src/tui/screens/runners.ts`) show each lent runner's scope, today's core-minutes against its | |
| 89 | budget, its total, its expiry and why it is paused, if it is: as rows under the runner on the web, | |
| 90 | on its one line in the terminal. While a runner is lent to the forge, both open with the lent-in | |
| 91 | numbers (runners, core-minutes in all and today), and **Settings → Capacity** shows the same line, | |
| 92 | linked to Runners. | |
| 93 | ||
| 94 | - **Revoke**: the **Revoke** button on the web, or `x` in the terminal after a confirm, or | |
| 95 | `POST /api/v1/admin/runners/<id>/revoke`. The runner's next request is refused (401) and a job | |
| 96 | it held is queued again. Its row stays, so its core-minutes stay counted. A revoked runner then | |
| 97 | offers **Remove**. | |
| 98 | - **Resume**: the **Resume** button, `u` in the terminal, or | |
| 99 | `POST /api/v1/admin/runners/<id>/resume`, for a paused runner an admin has looked at. | |
| 100 | ||
| 101 | ## Limits in v1 | |
| 102 | ||
| 103 | - **Lent out is not counted on B.** B's runner is a process that answers to A, not a row on B's | |
| 104 | forge. A's Runners page is the ledger for both sides. | |
| 105 | - **The owner-yield rule (#16479) measures A's load.** A `lent-` runner's claim still waits while | |
| 106 | A's one-minute load per core is above `FORGE_LEND_YIELD_LOAD`. That load is the borrowing | |
| 107 | forge's machine, not B's, so B's own protection is `FORGE_RUNNER_JOBS`, the cell and the | |
| 108 | declared limits. | |
| 109 | - **Only pull checks.** The default branch's own runs and verifications stay on A, as they do for | |
| 110 | every runner. | |
| 111 | - **No handshake yet.** A enrols and B starts the process by hand. A redeem link and a "Lend to A" | |
| 112 | screen on B are the next step (f2f design, v1.5). |
docs/features/runners.md +1 −1
| @@ -147,4 +147,4 @@ Tests: `test/checks-runner-placement.test.ts`, `test/checks-runner-pool.test.ts` | ||
| 147 | 147 | |
| 148 | 148 | A runner enrolled with a name starting `lent-` is machine time the owner shares. When this machine's one-minute load per core is above `FORGE_LEND_YIELD_LOAD` (default 0.75, `0` never yields), its claim answers 204: it finishes the job it holds and takes no new one. Other runners are never held. `src/checks/lent_yield.ts`. |
| 149 | 149 | |
| 150 | The owner sees it too: while lent runners wait, the runners screen in the terminal and Settings → Runners say so, with the load and the line. Nothing lends a runner yet (part 1 of #16479 is separate), so this rule is dormant until a `lent-` runner is enrolled. | |
| 150 | The owner sees it too: while lent runners wait, the runners screen in the terminal and Settings → Runners say so, with the load and the line. A `lent-` runner is also held to a scope (public pulls only, in a cell, an expiry and a daily core-minute budget), sampled and sent canaries: [](lent-runners.md). |
docs/features/settings-runners.md +6
| @@ -17,6 +17,12 @@ same `remove` as `DELETE /api/v1/admin/runners/<id>`, and the same `runner.remov | ||
| 17 | 17 | `local-N` runner is the forge's own, started again at each boot, so it has no button and is |
| 18 | 18 | refused if asked anyway. |
| 19 | 19 | |
| 20 | A **lent** runner (`lent-…`, [](lent-runners.md)) also shows its scope, today's | |
| 21 | core-minutes against its budget, its total and its expiry, as rows under it, and has **Revoke** | |
| 22 | instead of Remove: its next request is refused and its row stays with its core-minutes (then | |
| 23 | Remove clears it). A paused one has **Resume**. Any other runner that has run something shows its | |
| 24 | core-minutes, and while a runner is lent to the forge the page opens with the lent-in numbers. | |
| 25 | ||
| 20 | 26 | **Both doors.** `/settings/runners` on the web (under This forge in the settings menu), and |
| 21 | 27 | **Runners** in the terminal's command palette (`src/tui/screens/runners.ts`, a forge admin's): |
| 22 | 28 | `j`/`k` move, `x` removes the hand-made runner under the cursor after a confirm. Both go through |
src/actions/runners.ts +108 −4
| @@ -6,13 +6,23 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import type { App } from "../app.ts"; |
| 9 | import { sampled, type LendInput } from "../checks/lent_scope.ts"; | |
| 10 | import type { CheckOutcome } from "../checks/runner.ts"; | |
| 9 | 11 | import { |
| 12 | deskOf, | |
| 13 | dropJob, | |
| 10 | 14 | enrolRunner, |
| 15 | lentFacts, | |
| 11 | 16 | listRunners, |
| 17 | pauseRunner, | |
| 12 | 18 | removeRunner, |
| 19 | resumeRunner, | |
| 20 | revokeRunner, | |
| 13 | 21 | SEEN_FRESH_MS, |
| 22 | viewJob, | |
| 14 | 23 | wakeClaimers, |
| 15 | 24 | type Enrolled, |
| 25 | type RunnerResult, | |
| 16 | 26 | } from "../checks/runner_jobs.ts"; |
| 17 | 27 | import { LOCAL_PREFIX } from "../checks/runner_pool.ts"; |
| 18 | 28 | import type { User } from "../core/users.ts"; |
| @@ -25,17 +35,106 @@ export function enrol( | ||
| 25 | 35 | app: App, |
| 26 | 36 | actor: User | undefined, |
| 27 | 37 | name: string, |
| 38 | lend?: LendInput, | |
| 28 | 39 | ): Result<{ runner: Enrolled; token: string }, "not_found"> { |
| 29 | 40 | if (!admin(actor)) return err("not_found"); |
| 30 | const made = enrolRunner(app.db, name, actor.id); | |
| 41 | const made = enrolRunner(app.db, name, actor.id, lend); | |
| 31 | 42 | app.bus.append({ |
| 32 | 43 | kind: "runner.enrolled", |
| 33 | 44 | actorId: actor.id, |
| 34 | payload: { id: made.runner.id, name: made.runner.name }, | |
| 45 | payload: { id: made.runner.id, name: made.runner.name, ...(made.runner.scope === undefined ? {} : { scope: made.runner.scope }) }, | |
| 35 | 46 | }); |
| 36 | 47 | return ok(made); |
| 37 | 48 | } |
| 38 | 49 | |
| 50 | /** | |
| 51 | * Revoke a runner (Settings → Runners, the terminal screen, | |
| 52 | * `POST /api/v1/admin/runners/:id/revoke`): | |
| 53 | * its token is refused from its next request, a job it holds is queued again, and its row stays | |
| 54 | * with its core-minutes. A `local-N` runner is the forge's own and is refused. | |
| 55 | */ | |
| 56 | export function revoke(app: App, actor: User | undefined, runnerId: string): Result<Enrolled, "not_found" | "local" | "revoked"> { | |
| 57 | const runner = enrolled(app, actor, runnerId); | |
| 58 | if (runner === undefined || !admin(actor)) return err("not_found"); | |
| 59 | if (isLocal(runner)) return err("local"); | |
| 60 | if (!revokeRunner(app.db, runnerId, Date.now())) return err("revoked"); | |
| 61 | // A claim it holds open ends now, refused; a check waiting on its job looks again. | |
| 62 | wakeClaimers(app); | |
| 63 | app.bus.append({ kind: "runner.revoked", actorId: actor.id, payload: { id: runnerId, name: runner.name } }); | |
| 64 | return ok(runner); | |
| 65 | } | |
| 66 | ||
| 67 | /** Let a paused runner claim again: an admin who looked at why it was paused and disagrees. */ | |
| 68 | export function resume(app: App, actor: User | undefined, runnerId: string): Result<Enrolled, "not_found" | "not_paused"> { | |
| 69 | const runner = enrolled(app, actor, runnerId); | |
| 70 | if (runner === undefined || !admin(actor)) return err("not_found"); | |
| 71 | if (runner.revokedAt !== 0 || !resumeRunner(app.db, runnerId)) return err("not_paused"); | |
| 72 | app.bus.append({ kind: "runner.resumed", actorId: actor.id, payload: { id: runnerId, name: runner.name, was: runner.paused } }); | |
| 73 | return ok(runner); | |
| 74 | } | |
| 75 | ||
| 76 | /** The forge pauses a lent runner whose answer it caught out; the event is the record. */ | |
| 77 | function pauseLent(app: App, runnerId: string, why: string): void { | |
| 78 | if (!pauseRunner(app.db, runnerId, why)) return; | |
| 79 | app.bus.append({ kind: "runner.paused", payload: { id: runnerId, why } }); | |
| 80 | } | |
| 81 | ||
| 82 | /** A lent runner's green that this forge runs again itself (`lent_scope.ts` `sampled`). */ | |
| 83 | export interface LentGreen { | |
| 84 | readonly runnerId: string; | |
| 85 | readonly runner: string; | |
| 86 | readonly commit: string; | |
| 87 | } | |
| 88 | ||
| 89 | /** Whether this runner's green on this job is one this forge runs again: lent, and drawn. */ | |
| 90 | export function sampleLentGreen(app: App, runnerId: string | undefined, jobId: string | undefined): boolean { | |
| 91 | if (runnerId === undefined || runnerId === "" || jobId === undefined) return false; | |
| 92 | const facts = lentFacts(app.db, runnerId); | |
| 93 | return facts !== undefined && facts.lent && sampled(facts.salt, jobId, facts.ran); | |
| 94 | } | |
| 95 | ||
| 96 | /** | |
| 97 | * What this forge's own run says of a lent runner's green: agreed, or red here and the runner | |
| 98 | * paused. A run that was cancelled or failed on this machine's account proves nothing either way. | |
| 99 | */ | |
| 100 | export function judgeLentGreen(app: App, green: LentGreen, outcome: CheckOutcome, write: (line: string) => void): void { | |
| 101 | if (outcome.ok) { | |
| 102 | write(`lent runner ${green.runner}'s green agrees with this forge's own run`); | |
| 103 | return; | |
| 104 | } | |
| 105 | if (outcome.infrastructure === true || outcome.error === "check cancelled") return; | |
| 106 | const why = `said green on ${green.commit.slice(0, 7)}; this forge's own run of it was red`; | |
| 107 | pauseLent(app, green.runnerId, why); | |
| 108 | write(`lent runner ${green.runner} is paused: it ${why}`); | |
| 109 | } | |
| 110 | ||
| 111 | /** | |
| 112 | * Hear a canary's answer (`runner_jobs.ts` `offerCanary`): its check must fail, so a green is a | |
| 113 | * runner that did not run it, and it is paused. The row goes once it is answered. | |
| 114 | */ | |
| 115 | export function hearCanary(app: App, jobId: string): void { | |
| 116 | const desk = deskOf(app); | |
| 117 | desk.ears.set(jobId, { | |
| 118 | lines: () => {}, | |
| 119 | wake: () => { | |
| 120 | const view = viewJob(app.db, jobId); | |
| 121 | if (view === undefined || view.state === "claimed" || view.state === "queued") return; | |
| 122 | if (view.state === "done") { | |
| 123 | let result: RunnerResult | undefined; | |
| 124 | try { | |
| 125 | result = JSON.parse(view.result ?? "") as RunnerResult; | |
| 126 | } catch { | |
| 127 | result = undefined; | |
| 128 | } | |
| 129 | if (result?.steps?.some((s) => s.name === "check" && s.ok) === true && view.runnerId !== "") | |
| 130 | pauseLent(app, view.runnerId, "said green on a canary, a job that must fail"); | |
| 131 | } | |
| 132 | desk.ears.delete(jobId); | |
| 133 | dropJob(app.db, jobId); | |
| 134 | }, | |
| 135 | }); | |
| 136 | } | |
| 137 | ||
| 39 | 138 | export function list( |
| 40 | 139 | app: App, |
| 41 | 140 | actor: User | undefined, |
| @@ -67,6 +166,12 @@ export function remove( | ||
| 67 | 166 | export const isLocal = (r: Pick<Enrolled, "name">): boolean => |
| 68 | 167 | r.name.startsWith(LOCAL_PREFIX) && /^\d+$/.test(r.name.slice(LOCAL_PREFIX.length)); |
| 69 | 168 | |
| 169 | /** The runner by id, as an admin sees it in the list; undefined for anyone else, or none. */ | |
| 170 | function enrolled(app: App, actor: User | undefined, runnerId: string): Enrolled | undefined { | |
| 171 | const seen = list(app, actor); | |
| 172 | return seen.ok ? seen.value.find((r) => r.id === runnerId) : undefined; | |
| 173 | } | |
| 174 | ||
| 70 | 175 | /** A runner's state from when it last asked for work. */ |
| 71 | 176 | export function runnerState(seenAt: number, now: number): "connected" | "quiet" | "never" { |
| 72 | 177 | if (seenAt === 0) return "never"; |
| @@ -82,8 +187,7 @@ export function removeHandMade( | ||
| 82 | 187 | actor: User | undefined, |
| 83 | 188 | runnerId: string, |
| 84 | 189 | ): Result<Enrolled, "not_found" | "local"> { |
| 85 | const seen = list(app, actor); | |
| 86 | const runner = seen.ok ? seen.value.find((r) => r.id === runnerId) : undefined; | |
| 190 | const runner = enrolled(app, actor, runnerId); | |
| 87 | 191 | if (runner === undefined) return err("not_found"); |
| 88 | 192 | if (isLocal(runner)) return err("local"); |
| 89 | 193 | const gone = remove(app, actor, runnerId); |
src/checks/lent_scope.ts added +161
| @@ -0,0 +1,161 @@ | ||
| 1 | /** | |
| 2 | * Lent runners (f2f v1, docs/features/lent-runners.md): a runner another forge's owner runs for | |
| 3 | * this one, named `lent-…`. Its token is this forge's, and what it may claim is held to a scope | |
| 4 | * the claim enforces (`runner_jobs.ts` `claimJob`), never to trust: | |
| 5 | * | |
| 6 | * - public repositories only (a hard rule in v1: nothing it is sent is anything its owner could | |
| 7 | * not clone); | |
| 8 | * - optionally, only pulls by the named authors (a guest forge running its own people's pulls); | |
| 9 | * - until an expiry, and within a budget of core-minutes per UTC day (wall time from claim to | |
| 10 | * answer × the job's declared `limits.cpus`, 1 when none); | |
| 11 | * - in a cell, always: it claims nothing unless it says it has cells, and every job it is sent | |
| 12 | * says `cell: required`. | |
| 13 | * | |
| 14 | * Its answer is checked as well as bounded. A share of its greens, picked by a hash of the job id | |
| 15 | * under a salt that never leaves this forge, is run again here (every green while it is new); a | |
| 16 | * red here pauses it. Now and then it is sent a canary, a job that must fail; a green back pauses | |
| 17 | * it too. A runner this forge owns has no scope, and nothing here touches it. | |
| 18 | */ | |
| 19 | ||
| 20 | import { sha256 } from "../kernel/hash.ts"; | |
| 21 | import { isLent, LENT_PREFIX } from "./lent_yield.ts"; | |
| 22 | ||
| 23 | export interface LentScope { | |
| 24 | /** Logins whose pulls it may run; empty for any author. Lower case. */ | |
| 25 | readonly authors: readonly string[]; | |
| 26 | /** Milliseconds since the epoch after which it claims nothing. */ | |
| 27 | readonly expiresAt: number; | |
| 28 | /** Core-minutes it may run in one UTC day. */ | |
| 29 | readonly coreMinPerDay: number; | |
| 30 | } | |
| 31 | ||
| 32 | /** What an admin may say when lending; anything left out takes the default. */ | |
| 33 | export interface LendInput { | |
| 34 | readonly authors?: readonly string[] | undefined; | |
| 35 | readonly days?: number | undefined; | |
| 36 | readonly coreMinPerDay?: number | undefined; | |
| 37 | } | |
| 38 | ||
| 39 | export const LEND_DAYS = 30; | |
| 40 | export const LEND_DAYS_MAX = 365; | |
| 41 | export const LEND_CORE_MIN = 240; | |
| 42 | export const LEND_CORE_MIN_MAX = 100_000; | |
| 43 | const DAY_MS = 86_400_000; | |
| 44 | ||
| 45 | /** Every green of a runner that has run fewer jobs than this is run again here. */ | |
| 46 | export const SAMPLE_ALL_UNTIL = 5; | |
| 47 | /** After that, the share of its greens run again here. */ | |
| 48 | export const SAMPLE_RATE = 0.15; | |
| 49 | /** The share of its claims that are a canary, besides its very first. */ | |
| 50 | export const CANARY_RATE = 0.05; | |
| 51 | ||
| 52 | const login = (raw: string): string => raw.trim().toLowerCase().replace(/[^a-z0-9._-]/g, "").slice(0, 64); | |
| 53 | const whole = (raw: unknown, min: number, max: number, fallback: number): number => | |
| 54 | typeof raw === "number" && Number.isFinite(raw) ? Math.min(Math.max(Math.round(raw), min), max) : fallback; | |
| 55 | ||
| 56 | /** A scope from what an admin said, every field held to its range. */ | |
| 57 | export function scopeFrom(input: LendInput, now: number): LentScope { | |
| 58 | const authors = [...new Set((input.authors ?? []).filter((a) => typeof a === "string").map(login))].filter((a) => a !== "").slice(0, 50); | |
| 59 | return { | |
| 60 | authors, | |
| 61 | expiresAt: now + whole(input.days, 1, LEND_DAYS_MAX, LEND_DAYS) * DAY_MS, | |
| 62 | coreMinPerDay: whole(input.coreMinPerDay, 1, LEND_CORE_MIN_MAX, LEND_CORE_MIN), | |
| 63 | }; | |
| 64 | } | |
| 65 | ||
| 66 | /** | |
| 67 | * The scope a runner row is held to. A `lent-` runner always has one: a row enrolled before | |
| 68 | * scopes (or one whose column cannot be read) takes the defaults from its enrolment, so no lent | |
| 69 | * runner ever claims as an owned one does. | |
| 70 | */ | |
| 71 | export function readScope(name: string, raw: string | null, createdAt: string): LentScope | undefined { | |
| 72 | if (raw === null && !isLent(name)) return undefined; | |
| 73 | try { | |
| 74 | const v = JSON.parse(raw ?? "") as Partial<LentScope>; | |
| 75 | if (Array.isArray(v.authors) && typeof v.expiresAt === "number" && typeof v.coreMinPerDay === "number") | |
| 76 | return { authors: v.authors.filter((a) => typeof a === "string"), expiresAt: v.expiresAt, coreMinPerDay: v.coreMinPerDay }; | |
| 77 | } catch { | |
| 78 | // Falls through to the defaults. | |
| 79 | } | |
| 80 | return scopeFrom({}, Date.parse(createdAt) || 0); | |
| 81 | } | |
| 82 | ||
| 83 | /** A lent runner's name: `lent-` in front, once. */ | |
| 84 | export const lentName = (name: string): string => (isLent(name) ? name : `${LENT_PREFIX}${name}`); | |
| 85 | ||
| 86 | /** The UTC day a millisecond falls on, as the budget counts it. */ | |
| 87 | export const utcDay = (now: number): string => new Date(now).toISOString().slice(0, 10); | |
| 88 | ||
| 89 | /** Core-milliseconds: wall time × the cpus the job declared (1 when none, never below 1). */ | |
| 90 | export const coreMs = (wallMs: number, cpus: number | undefined): number => | |
| 91 | Math.round(Math.max(0, wallMs) * Math.max(1, cpus ?? 1)); | |
| 92 | ||
| 93 | /** Why a lent runner takes nothing now; "" when it may claim. */ | |
| 94 | export function outOfScope(scope: LentScope, x: { now: number; todayCoreMs: number; cells: boolean }): string { | |
| 95 | if (x.now >= scope.expiresAt) return "expired"; | |
| 96 | if (x.todayCoreMs >= scope.coreMinPerDay * 60_000) return "over today's budget"; | |
| 97 | if (!x.cells) return "has no cells"; | |
| 98 | return ""; | |
| 99 | } | |
| 100 | ||
| 101 | /** A draw in [0, 1) from `salt` and `key`: the same each time, unknowable without the salt. */ | |
| 102 | const draw = (salt: string, key: string): number => Number.parseInt(sha256(`${salt}:${key}`).slice(0, 8), 16) / 0x1_0000_0000; | |
| 103 | ||
| 104 | /** Whether a lent runner's green on this job is run again here. */ | |
| 105 | export const sampled = (salt: string, jobId: string, ran: number): boolean => | |
| 106 | ran < SAMPLE_ALL_UNTIL || draw(salt, `sample:${jobId}`) < SAMPLE_RATE; | |
| 107 | ||
| 108 | /** Whether its next claim is a canary: its first ever, then a draw per job it has run. */ | |
| 109 | export const canaryDue = (salt: string, canaryAt: number, ran: number): boolean => | |
| 110 | canaryAt === 0 || draw(salt, `canary:${ran}`) < CANARY_RATE; | |
| 111 | ||
| 112 | /** | |
| 113 | * A canary's check: a test for a file no tree holds, under a name drawn per canary. It must exit | |
| 114 | * 1; a runner that answers green never ran it. | |
| 115 | */ | |
| 116 | export const canaryCommand = (nonce: string): string => `test -e .forge-check-${nonce.slice(0, 12)}`; | |
| 117 | ||
| 118 | /** Core-minutes, whole, as the pages say them. */ | |
| 119 | export const coreMinutes = (ms: number): number => Math.round(ms / 60_000); | |
| 120 | ||
| 121 | /** | |
| 122 | * What a runner row says of its scope and core-minutes, on Settings → Runners and the terminal, as | |
| 123 | * " · …"; nothing for an owned runner that has run nothing yet. | |
| 124 | */ | |
| 125 | export function scopeLine( | |
| 126 | r: { readonly scope?: LentScope | undefined; readonly coreMs: number; readonly todayCoreMs: number; readonly paused: string }, | |
| 127 | now: number, | |
| 128 | ): string { | |
| 129 | const run = `${coreMinutes(r.coreMs)} core-min run`; | |
| 130 | const paused = r.paused === "" ? "" : ` · paused: ${r.paused}`; | |
| 131 | if (r.scope === undefined) return r.coreMs === 0 && paused === "" ? "" : ` · ${run}${paused}`; | |
| 132 | const s = r.scope; | |
| 133 | const who = s.authors.length === 0 ? "" : ` by ${s.authors.join(", ")}`; | |
| 134 | const until = `${now >= s.expiresAt ? "expired" : "expires"} ${new Date(s.expiresAt).toISOString().slice(0, 10)}`; | |
| 135 | return ` · lent: public pulls${who}, in a cell · ${coreMinutes(r.todayCoreMs)} of ${s.coreMinPerDay} core-min today · ${run} · ${until}${paused}`; | |
| 136 | } | |
| 137 | ||
| 138 | /** | |
| 139 | * A lent runner's scope as rows (label, value), for the `dl` under its row on Settings → Runners. | |
| 140 | */ | |
| 141 | export function scopeFacts( | |
| 142 | r: { readonly scope?: LentScope | undefined; readonly coreMs: number; readonly todayCoreMs: number; readonly paused: string }, | |
| 143 | now: number, | |
| 144 | ): { label: string; value: string }[] { | |
| 145 | const paused = r.paused === "" ? [] : [{ label: "Paused", value: r.paused }]; | |
| 146 | if (r.scope === undefined) return r.coreMs === 0 ? paused : [{ label: "Core-minutes", value: String(coreMinutes(r.coreMs)) }, ...paused]; | |
| 147 | const s = r.scope; | |
| 148 | return [ | |
| 149 | { label: "Scope", value: `public pulls${s.authors.length === 0 ? "" : ` by ${s.authors.join(", ")}`}, in a cell` }, | |
| 150 | { label: "Today", value: `${coreMinutes(r.todayCoreMs)} of ${s.coreMinPerDay} core-min` }, | |
| 151 | { label: "Total", value: `${coreMinutes(r.coreMs)} core-min` }, | |
| 152 | { label: now >= s.expiresAt ? "Expired" : "Expires", value: new Date(s.expiresAt).toISOString().slice(0, 10) }, | |
| 153 | ...paused, | |
| 154 | ]; | |
| 155 | } | |
| 156 | ||
| 157 | /** What lent runners have run for this forge, in numbers; "" while none is lent to it. */ | |
| 158 | export function lentLine(lent: { readonly runners: number; readonly coreMs: number; readonly todayCoreMs: number }): string { | |
| 159 | if (lent.runners === 0) return ""; | |
| 160 | return `Lent in: ${lent.runners} lent runner${lent.runners === 1 ? "" : "s"}, ${coreMinutes(lent.coreMs)} core-min in all, ${coreMinutes(lent.todayCoreMs)} today.`; | |
| 161 | } |
src/checks/run_tier.ts +13 −1
| @@ -40,6 +40,7 @@ import type { Execution } from "./local_runner.ts"; | ||
| 40 | 40 | import { resolveSource } from "./tier_source.ts"; |
| 41 | 41 | import { resolveManifest } from "./tier_manifest.ts"; |
| 42 | 42 | import { tryRunner } from "./tier_runner.ts"; |
| 43 | import { judgeLentGreen, type LentGreen } from "../actions/runners.ts"; | |
| 43 | 44 | import { runInstall } from "./tier_install.ts"; |
| 44 | 45 | import { settleFlakes } from "./tier_flake.ts"; |
| 45 | 46 | import { deepsecStep } from "./deepsec_step.ts"; |
| @@ -58,9 +59,19 @@ const lostCheckout = (dir: string, outcome: CheckOutcome): CheckOutcome => | ||
| 58 | 59 | |
| 59 | 60 | /** |
| 60 | 61 | * Run one tier of one check: resolve the commit and the manifest it runs by, give it to a runner |
| 61 | * or run it here in a cell, and answer the verdict. The steps it is made of are `tier_*.ts`. | |
| 62 | * or run it here in a cell, and answer the verdict. The steps it is made of are `tier_*.ts`. A lent | |
| 63 | * runner's green in the sample is run here too, and this run's verdict judges it. | |
| 62 | 64 | */ |
| 63 | 65 | export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutcome> { |
| 66 | let green: LentGreen | undefined; | |
| 67 | const outcome = await runTierOnce(lane, x, (g) => { | |
| 68 | green = g; | |
| 69 | }); | |
| 70 | if (green !== undefined) judgeLentGreen(lane.app, green, outcome, x.write); | |
| 71 | return outcome; | |
| 72 | } | |
| 73 | ||
| 74 | async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGreen) => void): Promise<CheckOutcome> { | |
| 64 | 75 | const { app, options } = lane; |
| 65 | 76 | const { bare, repo, write, signal } = x; |
| 66 | 77 | const sourced = await resolveSource(lane, x); |
| @@ -123,6 +134,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco | ||
| 123 | 134 | outside, |
| 124 | 135 | write, |
| 125 | 136 | signal, |
| 137 | sample, | |
| 126 | 138 | }); |
| 127 | 139 | if (sent !== undefined) return sent; |
| 128 | 140 | if (await reclaimIfFull(app)) write("disk under its free floor: swept unused checkouts"); |
src/checks/runner_jobs.ts +224 −47
| @@ -22,6 +22,7 @@ import type { App } from "../app.ts"; | ||
| 22 | 22 | import { sha256 } from "../kernel/hash.ts"; |
| 23 | 23 | import { id, secret } from "../kernel/id.ts"; |
| 24 | 24 | import { during } from "../perf/jobs.ts"; |
| 25 | import { canaryCommand, canaryDue, coreMs, lentName, outOfScope, readScope, scopeFrom, utcDay, type LendInput, type LentScope } from "./lent_scope.ts"; | |
| 25 | 26 | |
| 26 | 27 | export const RUNNER_TOKEN_PREFIX = "forge_runner_"; |
| 27 | 28 | export const JOB_TOKEN_PREFIX = "forge_job_"; |
| @@ -104,6 +105,15 @@ export interface Enrolled { | ||
| 104 | 105 | readonly createdAt: string; |
| 105 | 106 | /** When it last asked for work, in milliseconds; 0 for never. */ |
| 106 | 107 | readonly seenAt: number; |
| 108 | /** What a lent runner may claim (`lent_scope.ts`); undefined for one this forge owns. */ | |
| 109 | readonly scope?: LentScope; | |
| 110 | /** Every core-millisecond it has run, and today's (UTC) share. */ | |
| 111 | readonly coreMs: number; | |
| 112 | readonly todayCoreMs: number; | |
| 113 | /** Why it takes nothing now; "" when it may. */ | |
| 114 | readonly paused: string; | |
| 115 | /** When its token was revoked; 0 while it works. */ | |
| 116 | readonly revokedAt: number; | |
| 107 | 117 | } |
| 108 | 118 | |
| 109 | 119 | type RunnerRow = { |
| @@ -111,29 +121,52 @@ type RunnerRow = { | ||
| 111 | 121 | name: string; |
| 112 | 122 | created_at: string; |
| 113 | 123 | seen_at: number; |
| 124 | scope: string | null; | |
| 125 | core_ms: number; | |
| 126 | day: string; | |
| 127 | day_core_ms: number; | |
| 128 | paused: string; | |
| 129 | revoked_at: number; | |
| 130 | }; | |
| 131 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at"; | |
| 132 | const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { | |
| 133 | const scope = readScope(r.name, r.scope, r.created_at); | |
| 134 | return { | |
| 135 | id: r.id, | |
| 136 | name: r.name, | |
| 137 | createdAt: r.created_at, | |
| 138 | seenAt: r.seen_at, | |
| 139 | ...(scope === undefined ? {} : { scope }), | |
| 140 | coreMs: r.core_ms, | |
| 141 | todayCoreMs: r.day === utcDay(now) ? r.day_core_ms : 0, | |
| 142 | paused: r.paused, | |
| 143 | revokedAt: r.revoked_at, | |
| 144 | }; | |
| 114 | 145 | }; |
| 115 | const toEnrolled = (r: RunnerRow): Enrolled => ({ | |
| 116 | id: r.id, | |
| 117 | name: r.name, | |
| 118 | createdAt: r.created_at, | |
| 119 | seenAt: r.seen_at, | |
| 120 | }); | |
| 121 | 146 | |
| 122 | 147 | /** A name as it is kept: printable, at most 40 characters, "runner" when nothing is left. */ |
| 123 | 148 | export const runnerName = (raw: string): string => |
| 124 | 149 | raw.replace(/[^\x21-\x7e]/g, "").slice(0, 40) || "runner"; |
| 125 | 150 | |
| 126 | /** Enrol a runner. The token is returned once; the row keeps its hash. */ | |
| 151 | /** | |
| 152 | * Enrol a runner. The token is returned once; the row keeps its hash. With `lend`, or a name | |
| 153 | * that is already `lent-…`, it is a lent runner: named `lent-…` and held to a scope | |
| 154 | * (`lent_scope.ts`). | |
| 155 | */ | |
| 127 | 156 | export function enrolRunner( |
| 128 | 157 | db: Database, |
| 129 | 158 | name: string, |
| 130 | 159 | createdBy: string, |
| 160 | lend?: LendInput, | |
| 161 | now: number = Date.now(), | |
| 131 | 162 | ): { runner: Enrolled; token: string } { |
| 132 | 163 | const runnerId = id(); |
| 133 | 164 | const token = `${RUNNER_TOKEN_PREFIX}${secret()}`; |
| 165 | const kept = runnerName(lend === undefined ? name : lentName(runnerName(name))); | |
| 166 | const scope = readScope(kept, null, "") === undefined ? null : JSON.stringify(scopeFrom(lend ?? {}, now)); | |
| 134 | 167 | db.query( |
| 135 | "INSERT INTO check_runner (id, name, token_hash, created_by) VALUES (?1, ?2, ?3, ?4)", | |
| 136 | ).run(runnerId, runnerName(name), sha256(token), createdBy); | |
| 168 | "INSERT INTO check_runner (id, name, token_hash, created_by, scope, salt) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 169 | ).run(runnerId, kept, sha256(token), createdBy, scope, scope === null ? "" : secret()); | |
| 137 | 170 | return { runner: getRunner(db, runnerId)!, token }; |
| 138 | 171 | } |
| 139 | 172 | |
| @@ -142,22 +175,16 @@ export function getRunner( | ||
| 142 | 175 | runnerId: string, |
| 143 | 176 | ): Enrolled | undefined { |
| 144 | 177 | const row = db |
| 145 | .query< | |
| 146 | RunnerRow, | |
| 147 | [string] | |
| 148 | >("SELECT id, name, created_at, seen_at FROM check_runner WHERE id = ?1") | |
| 178 | .query<RunnerRow, [string]>(`SELECT ${RUNNER_COLUMNS} FROM check_runner WHERE id = ?1`) | |
| 149 | 179 | .get(runnerId); |
| 150 | 180 | return row === null ? undefined : toEnrolled(row); |
| 151 | 181 | } |
| 152 | 182 | |
| 153 | 183 | export function listRunners(db: Database): Enrolled[] { |
| 154 | 184 | return db |
| 155 | .query< | |
| 156 | RunnerRow, | |
| 157 | [] | |
| 158 | >("SELECT id, name, created_at, seen_at FROM check_runner ORDER BY id LIMIT 200") | |
| 185 | .query<RunnerRow, []>(`SELECT ${RUNNER_COLUMNS} FROM check_runner ORDER BY id LIMIT 200`) | |
| 159 | 186 | .all() |
| 160 | .map(toEnrolled); | |
| 187 | .map((r) => toEnrolled(r)); | |
| 161 | 188 | } |
| 162 | 189 | |
| 163 | 190 | /** |
| @@ -169,14 +196,78 @@ export function removeRunner(db: Database, runnerId: string): boolean { | ||
| 169 | 196 | const gone = |
| 170 | 197 | db.query("DELETE FROM check_runner WHERE id = ?1").run(runnerId).changes > |
| 171 | 198 | 0; |
| 172 | if (gone) | |
| 173 | db.query( | |
| 174 | "UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0 WHERE runner_id = ?1 AND state = 'claimed'", | |
| 175 | ).run(runnerId); | |
| 199 | if (gone) requeueHeld(db, runnerId); | |
| 176 | 200 | return gone; |
| 177 | 201 | })(); |
| 178 | 202 | } |
| 179 | 203 | |
| 204 | /** What a runner held goes back to queued; a canary meant for it goes. */ | |
| 205 | function requeueHeld(db: Database, runnerId: string): void { | |
| 206 | db.query("DELETE FROM check_job WHERE canary_for = ?1").run(runnerId); | |
| 207 | db.query( | |
| 208 | "UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0 WHERE runner_id = ?1 AND state = 'claimed'", | |
| 209 | ).run(runnerId); | |
| 210 | } | |
| 211 | ||
| 212 | /** | |
| 213 | * Revoke a runner: its token is dead from the next request (its hash is replaced by one no token | |
| 214 | * has), what it held is queued again, and the row stays, so its core-minutes are still counted. | |
| 215 | * False when there is no such runner, or it is revoked already. | |
| 216 | */ | |
| 217 | export function revokeRunner(db: Database, runnerId: string, now: number): boolean { | |
| 218 | return db.transaction(() => { | |
| 219 | const done = | |
| 220 | db | |
| 221 | .query("UPDATE check_runner SET token_hash = 'revoked:' || id, revoked_at = ?2 WHERE id = ?1 AND revoked_at = 0") | |
| 222 | .run(runnerId, Math.max(1, now)).changes > 0; | |
| 223 | if (done) requeueHeld(db, runnerId); | |
| 224 | return done; | |
| 225 | })(); | |
| 226 | } | |
| 227 | ||
| 228 | /** Pause a runner: it claims nothing until resumed. The first reason is kept. False if none. */ | |
| 229 | export function pauseRunner(db: Database, runnerId: string, why: string): boolean { | |
| 230 | return ( | |
| 231 | db | |
| 232 | .query("UPDATE check_runner SET paused = CASE WHEN paused = '' THEN ?2 ELSE paused END WHERE id = ?1") | |
| 233 | .run(runnerId, why.slice(0, 200) || "paused").changes > 0 | |
| 234 | ); | |
| 235 | } | |
| 236 | ||
| 237 | /** Let a paused runner claim again. False when it was not paused. */ | |
| 238 | export function resumeRunner(db: Database, runnerId: string): boolean { | |
| 239 | return db.query("UPDATE check_runner SET paused = '' WHERE id = ?1 AND paused != ''").run(runnerId).changes > 0; | |
| 240 | } | |
| 241 | ||
| 242 | /** What lent runners have run for this forge: the line Capacity and Runners show. */ | |
| 243 | export function lentIn(db: Database, now: number): { runners: number; coreMs: number; todayCoreMs: number } { | |
| 244 | const row = db | |
| 245 | .query<{ n: number; total: number | null; today: number | null }, [string]>( | |
| 246 | `SELECT COUNT(*) AS n, SUM(core_ms) AS total, SUM(CASE WHEN day = ?1 THEN day_core_ms ELSE 0 END) AS today | |
| 247 | FROM check_runner WHERE scope IS NOT NULL OR name LIKE 'lent-%'`, | |
| 248 | ) | |
| 249 | .get(utcDay(now))!; | |
| 250 | return { runners: row.n, coreMs: row.total ?? 0, todayCoreMs: row.today ?? 0 }; | |
| 251 | } | |
| 252 | ||
| 253 | /** What a lent runner's greens are sampled by: its salt and how many jobs it has run. */ | |
| 254 | export function lentFacts(db: Database, runnerId: string): { name: string; salt: string; ran: number; lent: boolean } | undefined { | |
| 255 | const row = db | |
| 256 | .query<{ id: string; name: string; salt: string; ran: number; scope: string | null; created_at: string }, [string]>( | |
| 257 | "SELECT id, name, salt, ran, scope, created_at FROM check_runner WHERE id = ?1", | |
| 258 | ) | |
| 259 | .get(runnerId); | |
| 260 | if (row === null) return undefined; | |
| 261 | const lent = readScope(row.name, row.scope, row.created_at) !== undefined; | |
| 262 | return { name: row.name, salt: saltOf(row), ran: row.ran, lent }; | |
| 263 | } | |
| 264 | ||
| 265 | /** | |
| 266 | * A runner's salt. One enrolled `lent-` before scopes has none: its id and enrolment instant, which | |
| 267 | * its token never told anyone, stand in. | |
| 268 | */ | |
| 269 | const saltOf = (r: { id: string; salt: string; created_at: string }): string => r.salt || sha256(`${r.id}:${r.created_at}`); | |
| 270 | ||
| 180 | 271 | /** The runner a presented token is, noting that it asked; undefined for anything else. */ |
| 181 | 272 | export function runnerByToken( |
| 182 | 273 | db: Database, |
| @@ -185,20 +276,17 @@ export function runnerByToken( | ||
| 185 | 276 | ): Enrolled | undefined { |
| 186 | 277 | if (!presented.startsWith(RUNNER_TOKEN_PREFIX)) return undefined; |
| 187 | 278 | const row = db |
| 188 | .query< | |
| 189 | RunnerRow, | |
| 190 | [string] | |
| 191 | >("SELECT id, name, created_at, seen_at FROM check_runner WHERE token_hash = ?1") | |
| 279 | .query<RunnerRow, [string]>(`SELECT ${RUNNER_COLUMNS} FROM check_runner WHERE token_hash = ?1`) | |
| 192 | 280 | .get(sha256(presented)); |
| 193 | 281 | if (row === null) return undefined; |
| 194 | 282 | // One write is a commit: a runner polling every few seconds is noted at most once per |
| 195 | 283 | // `SEEN_WRITE_MS`, which is well inside `SEEN_FRESH_MS`. |
| 196 | if (now - row.seen_at < SEEN_WRITE_MS && row.seen_at <= now) return toEnrolled(row); | |
| 284 | if (now - row.seen_at < SEEN_WRITE_MS && row.seen_at <= now) return toEnrolled(row, now); | |
| 197 | 285 | db.query("UPDATE check_runner SET seen_at = ?2 WHERE id = ?1").run( |
| 198 | 286 | row.id, |
| 199 | 287 | now, |
| 200 | 288 | ); |
| 201 | return toEnrolled({ ...row, seen_at: now }); | |
| 289 | return toEnrolled({ ...row, seen_at: now }, now); | |
| 202 | 290 | } |
| 203 | 291 | |
| 204 | 292 | /** Whether any runner asked for work within `SEEN_FRESH_MS`. */ |
| @@ -235,11 +323,13 @@ export function offerJob( | ||
| 235 | 323 | repoId: string; |
| 236 | 324 | dir: string; |
| 237 | 325 | job: Omit<RunnerJob, "id">; |
| 326 | /** The pull's author, as a lent runner's `authors` scope matches it; "" for none. */ | |
| 327 | author?: string; | |
| 238 | 328 | }, |
| 239 | 329 | ): RunnerJob { |
| 240 | 330 | const job: RunnerJob = { ...input.job, id: id() }; |
| 241 | 331 | db.query( |
| 242 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 332 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 243 | 333 | ).run( |
| 244 | 334 | job.id, |
| 245 | 335 | input.runId, |
| @@ -247,6 +337,7 @@ export function offerJob( | ||
| 247 | 337 | input.dir, |
| 248 | 338 | JSON.stringify(job), |
| 249 | 339 | job.cell === "required" ? 1 : 0, |
| 340 | (input.author ?? "").toLowerCase(), | |
| 250 | 341 | ); |
| 251 | 342 | return job; |
| 252 | 343 | } |
| @@ -256,8 +347,24 @@ export interface Claim { | ||
| 256 | 347 | /** The job's own credential: shown once, here. */ |
| 257 | 348 | readonly token: string; |
| 258 | 349 | readonly leaseMs: number; |
| 350 | /** A canary (`lent_scope.ts`): no check waits on it, and it must come back red. Never sent. */ | |
| 351 | readonly canary?: true; | |
| 259 | 352 | } |
| 260 | 353 | |
| 354 | type ClaimRow = { | |
| 355 | id: string; | |
| 356 | name: string; | |
| 357 | created_at: string; | |
| 358 | scope: string | null; | |
| 359 | day: string; | |
| 360 | day_core_ms: number; | |
| 361 | paused: string; | |
| 362 | revoked_at: number; | |
| 363 | salt: string; | |
| 364 | ran: number; | |
| 365 | canary_at: number; | |
| 366 | }; | |
| 367 | ||
| 261 | 368 | /** |
| 262 | 369 | * Take the oldest queued job this runner can run. The UPDATE's WHERE is the claim: of two |
| 263 | 370 | * runners asking at once, one changes the row and the other moves on to the next. |
| @@ -268,32 +375,88 @@ export function claimJob( | ||
| 268 | 375 | now: number, |
| 269 | 376 | leaseMs: number = LEASE_MS, |
| 270 | 377 | ): Claim | undefined { |
| 271 | // Ids only: the spec (a job's whole build) is read for the one row this runner takes. | |
| 272 | const queued = db | |
| 273 | .query< | |
| 274 | { id: string }, | |
| 275 | [number] | |
| 276 | >("SELECT id FROM check_job WHERE state = 'queued' AND (needs_cell = 0 OR ?1 = 1) ORDER BY id LIMIT 8") | |
| 277 | .all(runner.cells ? 1 : 0); | |
| 378 | const me = db | |
| 379 | .query<ClaimRow, [string]>( | |
| 380 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at FROM check_runner WHERE id = ?1", | |
| 381 | ) | |
| 382 | .get(runner.id); | |
| 383 | if (me === null || me.revoked_at !== 0 || me.paused !== "") return undefined; | |
| 384 | const scope = readScope(me.name, me.scope, me.created_at); | |
| 385 | const todayCoreMs = me.day === utcDay(now) ? me.day_core_ms : 0; | |
| 386 | if (scope !== undefined && outOfScope(scope, { now, todayCoreMs, cells: runner.cells }) !== "") return undefined; | |
| 387 | // Ids only: the spec (a job's whole build) is read for the one row this runner takes. A lent | |
| 388 | // runner sees only public repositories' jobs, only its authors' when it names some, and its | |
| 389 | // own canaries; a runner this forge owns sees every job but a canary. | |
| 390 | const queued = | |
| 391 | scope === undefined | |
| 392 | ? db | |
| 393 | .query<{ id: string }, [number]>( | |
| 394 | "SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1) ORDER BY id LIMIT 8", | |
| 395 | ) | |
| 396 | .all(runner.cells ? 1 : 0) | |
| 397 | : db | |
| 398 | .query<{ id: string }, [string, string, number]>( | |
| 399 | `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id | |
| 400 | WHERE j.state = 'queued' AND r.visibility = 'public' AND (j.canary_for IS NULL OR j.canary_for = ?1) | |
| 401 | AND (?3 = 0 OR j.author IN (SELECT value FROM json_each(?2))) | |
| 402 | ORDER BY j.id LIMIT 8`, | |
| 403 | ) | |
| 404 | .all(runner.id, JSON.stringify(scope.authors), scope.authors.length); | |
| 405 | if (scope !== undefined && queued.length > 0 && canaryDue(saltOf(me), me.canary_at, me.ran)) { | |
| 406 | const canary = offerCanary(db, runner.id, queued[0]!.id, now, leaseMs); | |
| 407 | if (canary !== undefined) return canary; | |
| 408 | } | |
| 278 | 409 | for (const row of queued) { |
| 279 | 410 | const token = `${JOB_TOKEN_PREFIX}${secret()}`; |
| 280 | 411 | const taken = |
| 281 | 412 | db |
| 282 | 413 | .query( |
| 283 | 414 | `UPDATE check_job SET state = 'claimed', runner_id = ?2, token_hash = ?3, lease_until = ?4, |
| 284 | claims = claims + 1 WHERE id = ?1 AND state = 'queued'`, | |
| 415 | claims = claims + 1, claimed_at = ?5 WHERE id = ?1 AND state = 'queued'`, | |
| 285 | 416 | ) |
| 286 | .run(row.id, runner.id, sha256(token), now + leaseMs).changes > 0; | |
| 417 | .run(row.id, runner.id, sha256(token), now + leaseMs, now).changes > 0; | |
| 287 | 418 | if (taken) { |
| 288 | const spec = db | |
| 289 | .query<{ spec: string }, [string]>("SELECT spec FROM check_job WHERE id = ?1") | |
| 290 | .get(row.id)!.spec; | |
| 291 | return { job: JSON.parse(spec) as RunnerJob, token, leaseMs }; | |
| 419 | const got = db | |
| 420 | .query<{ spec: string; canary_for: string | null }, [string]>("SELECT spec, canary_for FROM check_job WHERE id = ?1") | |
| 421 | .get(row.id)!; | |
| 422 | const job = JSON.parse(got.spec) as RunnerJob; | |
| 423 | // A lent runner runs every job in a cell: one without hands it back. | |
| 424 | return { | |
| 425 | job: scope === undefined ? job : { ...job, cell: "required" }, | |
| 426 | token, | |
| 427 | leaseMs, | |
| 428 | ...(got.canary_for === null ? {} : { canary: true as const }), | |
| 429 | }; | |
| 292 | 430 | } |
| 293 | 431 | } |
| 294 | 432 | return undefined; |
| 295 | 433 | } |
| 296 | 434 | |
| 435 | /** | |
| 436 | * A canary for a lent runner, made from a queued job it could take (the same repository, commit | |
| 437 | * and limits, so it looks like any other) with a check that must fail, and claimed for it at once. | |
| 438 | * The job it was made from stays queued for whoever asks next. | |
| 439 | */ | |
| 440 | function offerCanary(db: Database, runnerId: string, fromId: string, now: number, leaseMs: number): Claim | undefined { | |
| 441 | const from = db | |
| 442 | .query<{ run_id: string; repo_id: string; dir: string; spec: string }, [string]>( | |
| 443 | "SELECT run_id, repo_id, dir, spec FROM check_job WHERE id = ?1 AND canary_for IS NULL", | |
| 444 | ) | |
| 445 | .get(fromId); | |
| 446 | if (from === null) return undefined; | |
| 447 | const real = JSON.parse(from.spec) as RunnerJob; | |
| 448 | const job: RunnerJob = { ...real, id: id(), steps: [{ name: "check", command: canaryCommand(sha256(secret())) }], cell: "required" }; | |
| 449 | const token = `${JOB_TOKEN_PREFIX}${secret()}`; | |
| 450 | db.transaction(() => { | |
| 451 | db.query( | |
| 452 | `INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, state, runner_id, token_hash, lease_until, claims, claimed_at, canary_for) | |
| 453 | VALUES (?1, ?2, ?3, ?4, ?5, 1, 'claimed', ?6, ?7, ?8, 1, ?9, ?6)`, | |
| 454 | ).run(job.id, from.run_id, from.repo_id, from.dir, JSON.stringify(job), runnerId, sha256(token), now + leaseMs, now); | |
| 455 | db.query("UPDATE check_runner SET canary_at = ?2 WHERE id = ?1").run(runnerId, Math.max(1, now)); | |
| 456 | })(); | |
| 457 | return { job, token, leaseMs, canary: true }; | |
| 458 | } | |
| 459 | ||
| 297 | 460 | export interface HeldJob { |
| 298 | 461 | readonly id: string; |
| 299 | 462 | readonly runId: string; |
| @@ -374,13 +537,14 @@ export function settleJob( | ||
| 374 | 537 | jobId: string, |
| 375 | 538 | presented: string, |
| 376 | 539 | end: { done: RunnerResult } | { returned: string }, |
| 540 | now: number = Date.now(), | |
| 377 | 541 | ): boolean { |
| 378 | 542 | const done = "done" in end; |
| 379 | 543 | return db.transaction(() => { |
| 380 | 544 | const settled = db |
| 381 | .query<{ runner_id: string | null }, [string, string, string, string]>( | |
| 545 | .query<{ runner_id: string | null; claimed_at: number; spec: string }, [string, string, string, string]>( | |
| 382 | 546 | `UPDATE check_job SET state = ?2, result = ?3, token_hash = NULL |
| 383 | WHERE id = ?1 AND token_hash = ?4 AND state = 'claimed' RETURNING runner_id`, | |
| 547 | WHERE id = ?1 AND token_hash = ?4 AND state = 'claimed' RETURNING runner_id, claimed_at, spec`, | |
| 384 | 548 | ) |
| 385 | 549 | .get( |
| 386 | 550 | jobId, |
| @@ -388,8 +552,17 @@ export function settleJob( | ||
| 388 | 552 | done ? JSON.stringify(end.done) : end.returned.slice(0, 400), |
| 389 | 553 | sha256(presented), |
| 390 | 554 | ); |
| 391 | // A job done is one more the runner has run (#15252); a returned one is not. | |
| 392 | if (done && settled?.runner_id) db.query("UPDATE check_runner SET ran = ran + 1 WHERE id = ?1").run(settled.runner_id); | |
| 555 | // A job done is one more the runner has run (#15252); a returned one is not. Either way its | |
| 556 | // machine spent the time: wall time from the claim × the job's declared cpus, today's and in | |
| 557 | // all. | |
| 558 | if (settled?.runner_id) { | |
| 559 | const cpus = (JSON.parse(settled.spec) as RunnerJob).limits?.cpus; | |
| 560 | const spent = settled.claimed_at === 0 ? 0 : coreMs(now - settled.claimed_at, cpus); | |
| 561 | db.query( | |
| 562 | `UPDATE check_runner SET ran = ran + ?2, core_ms = core_ms + ?3, | |
| 563 | day_core_ms = CASE WHEN day = ?4 THEN day_core_ms + ?3 ELSE ?3 END, day = ?4 WHERE id = ?1`, | |
| 564 | ).run(settled.runner_id, done ? 1 : 0, spent, utcDay(now)); | |
| 565 | } | |
| 393 | 566 | return settled !== null; |
| 394 | 567 | })(); |
| 395 | 568 | } |
| @@ -436,6 +609,8 @@ export interface JobView { | ||
| 436 | 609 | readonly claims: number; |
| 437 | 610 | /** The runner holding it, by name; "" when none does. */ |
| 438 | 611 | readonly runner: string; |
| 612 | /** Its id; "" when none does. */ | |
| 613 | readonly runnerId: string; | |
| 439 | 614 | readonly result: string | null; |
| 440 | 615 | } |
| 441 | 616 | |
| @@ -446,11 +621,12 @@ export function viewJob(db: Database, jobId: string): JobView | undefined { | ||
| 446 | 621 | state: JobView["state"]; |
| 447 | 622 | claims: number; |
| 448 | 623 | runner: string | null; |
| 624 | runner_id: string | null; | |
| 449 | 625 | result: string | null; |
| 450 | 626 | }, |
| 451 | 627 | [string] |
| 452 | 628 | >( |
| 453 | `SELECT j.state, j.claims, r.name AS runner, j.result | |
| 629 | `SELECT j.state, j.claims, r.name AS runner, r.id AS runner_id, j.result | |
| 454 | 630 | FROM check_job j LEFT JOIN check_runner r ON r.id = j.runner_id WHERE j.id = ?1`, |
| 455 | 631 | ) |
| 456 | 632 | .get(jobId); |
| @@ -460,6 +636,7 @@ export function viewJob(db: Database, jobId: string): JobView | undefined { | ||
| 460 | 636 | state: row.state, |
| 461 | 637 | claims: row.claims, |
| 462 | 638 | runner: row.runner ?? "", |
| 639 | runnerId: row.runner_id ?? "", | |
| 463 | 640 | result: row.result, |
| 464 | 641 | }; |
| 465 | 642 | } |
src/checks/runner_step.ts +11
| @@ -72,6 +72,12 @@ export type RunnerStepEnd = | ||
| 72 | 72 | /** The step that did not end ok. */ |
| 73 | 73 | readonly failed?: string; |
| 74 | 74 | readonly runner: string; |
| 75 | /** | |
| 76 | * The runner's id and the job's, when a runner answered: what a lent runner's green is | |
| 77 | * sampled by. | |
| 78 | */ | |
| 79 | readonly runnerId?: string; | |
| 80 | readonly jobId?: string; | |
| 75 | 81 | readonly contained: boolean; |
| 76 | 82 | readonly note: string; |
| 77 | 83 | readonly start?: "warm" | "cold"; |
| @@ -89,6 +95,8 @@ export interface RunnerStepInput { | ||
| 89 | 95 | /** The check step's own output, apart from the echoed command. */ |
| 90 | 96 | readonly output: string[]; |
| 91 | 97 | readonly signal: AbortSignal; |
| 98 | /** The pull's author, as a lent runner's authors scope reads it. */ | |
| 99 | readonly author?: string | undefined; | |
| 92 | 100 | /** @default RUNNER_WAIT_MS */ |
| 93 | 101 | readonly waitMs?: number | undefined; |
| 94 | 102 | /** Tests stand a clock in. @default Date.now */ |
| @@ -140,6 +148,7 @@ export async function runRunnerStep( | ||
| 140 | 148 | repoId: input.repoId, |
| 141 | 149 | dir: input.dir, |
| 142 | 150 | job: input.job, |
| 151 | author: input.author ?? "", | |
| 143 | 152 | }); |
| 144 | 153 | let wake: () => void = () => {}; |
| 145 | 154 | let sawEcho = false; |
| @@ -210,6 +219,8 @@ export async function runRunnerStep( | ||
| 210 | 219 | taken: true, |
| 211 | 220 | ...read, |
| 212 | 221 | runner: holder, |
| 222 | runnerId: view.runnerId, | |
| 223 | jobId: job.id, | |
| 213 | 224 | contained: result.contained === true, |
| 214 | 225 | note: |
| 215 | 226 | typeof result.note === "string" ? result.note.slice(0, 200) : "", |
src/checks/tier_runner.ts +12 −1
| @@ -16,6 +16,7 @@ import type { LaneState } from "./lane_state.ts"; | ||
| 16 | 16 | import type { Execution } from "./local_runner.ts"; |
| 17 | 17 | import type { CheckManifest } from "../apps/manifest.ts"; |
| 18 | 18 | import { readFileAt } from "../apps/checkout.ts"; |
| 19 | import { sampleLentGreen, type LentGreen } from "../actions/runners.ts"; | |
| 19 | 20 | import { runsAsBaseGate, withBaseGateFrom } from "./base_gate.ts"; |
| 20 | 21 | |
| 21 | 22 | /** What a check handed to a runner is made of. */ |
| @@ -38,6 +39,8 @@ export interface RunnerCheck { | ||
| 38 | 39 | readonly outside: boolean; |
| 39 | 40 | readonly write: (line: string) => void; |
| 40 | 41 | readonly signal: AbortSignal; |
| 42 | /** Told of a lent runner's green this forge runs again itself, before it does. */ | |
| 43 | readonly sample?: ((green: LentGreen) => void) | undefined; | |
| 41 | 44 | } |
| 42 | 45 | |
| 43 | 46 | /** |
| @@ -76,6 +79,9 @@ export async function tryRunner( | ||
| 76 | 79 | runId: x.runId, |
| 77 | 80 | repoId: repo.id, |
| 78 | 81 | dir: bare, |
| 82 | // Whose pull it is, as a lent runner's authors scope reads it: the origin's login for one | |
| 83 | // mirrored from there. | |
| 84 | author: x.pull === undefined ? "" : (x.pull.originAuthor ?? x.pull.authorName), | |
| 79 | 85 | job: { |
| 80 | 86 | run: x.runId, |
| 81 | 87 | repo: `${repo.ownerName}/${repo.name}`, |
| @@ -116,7 +122,12 @@ export async function tryRunner( | ||
| 116 | 122 | }); |
| 117 | 123 | const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted) : sent.why; |
| 118 | 124 | if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`); |
| 119 | else { | |
| 125 | else if (verdict.ok && sent.taken && sampleLentGreen(app, sent.runnerId, sent.jobId)) { | |
| 126 | // A share of a lent runner's greens is run here as well (`lent_scope.ts`): this forge's | |
| 127 | // own verdict is the one that stands, and a red pauses the runner (`judgeLentGreen`). | |
| 128 | write(`lent runner ${sent.runner} said green; this check is in the share run here too`); | |
| 129 | c.sample?.({ runnerId: sent.runnerId!, runner: sent.runner, commit: run.commitOid }); | |
| 130 | } else { | |
| 120 | 131 | if (sent.taken && sent.runner !== "") |
| 121 | 132 | noteRunProgress(app.db, x.runId, { |
| 122 | 133 | placement: "runner", |
src/contract/openapi/routes/index.ts +2
| @@ -325,6 +325,8 @@ export { route as postApiV1AdminReleasesShaRollback } from "./postApiV1AdminRele | ||
| 325 | 325 | export { route as postApiV1AdminRequestsUsernameAllow } from "./postApiV1AdminRequestsUsernameAllow.ts"; |
| 326 | 326 | export { route as postApiV1AdminRequestsUsernameDecline } from "./postApiV1AdminRequestsUsernameDecline.ts"; |
| 327 | 327 | export { route as postApiV1AdminRunners } from "./postApiV1AdminRunners.ts"; |
| 328 | export { route as postApiV1AdminRunnersIdResume } from "./postApiV1AdminRunnersIdResume.ts"; | |
| 329 | export { route as postApiV1AdminRunnersIdRevoke } from "./postApiV1AdminRunnersIdRevoke.ts"; | |
| 328 | 330 | export { route as postApiV1Agents } from "./postApiV1Agents.ts"; |
| 329 | 331 | export { route as postApiV1Apps } from "./postApiV1Apps.ts"; |
| 330 | 332 | export { route as postApiV1AsksAdmin } from "./postApiV1AsksAdmin.ts"; |
src/contract/openapi/routes/postApiV1AdminRunners.ts +2 −2
| @@ -6,10 +6,10 @@ export const route: Route = { | ||
| 6 | 6 | summary: |
| 7 | 7 | "Enrol a runner: a machine that takes checks off this forge", |
| 8 | 8 | detail: |
| 9 | "Enrol a runner: a machine that takes checks off this forge when FORGE_CHECKS_PLACEMENT=runner (admin scope); answers its row and its token, shown this once", | |
| 9 | "Enrol a runner: a machine that takes checks off this forge when FORGE_CHECKS_PLACEMENT=runner (admin scope); answers its row and its token, shown this once. With lend ({ authors?, days?, coreMinPerDay? }) it is a lent runner another forge runs: named lent-…, public pulls only, in a cell, until it expires and within its core-minutes per day (docs/features/lent-runners.md)", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | body: { name: "string" }, | |
| 12 | body: { name: "string", lend: "object" }, | |
| 13 | 13 | status: 201, |
| 14 | 14 | reply: { id: "string", name: "string", createdAt: "string", seenAt: "integer", token: "string" }, |
| 15 | 15 | refuses: [404], |
src/contract/openapi/routes/postApiV1AdminRunnersIdResume.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/admin/runners/{id}/resume", | |
| 6 | summary: "Resume a paused runner: it may claim again", | |
| 7 | detail: | |
| 8 | "Resume a runner the forge paused (a lent runner whose green this forge's own run found red, or that said green on a canary) (admin scope); 422 not_paused when it is not paused; 404 when there is none", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | status: 200, | |
| 12 | reply: { id: "string", name: "string", paused: "string" }, | |
| 13 | refuses: [404], | |
| 14 | errorStatus: { 422: "the runner is not paused (not_paused)" }, | |
| 15 | refusals: { not_paused: "that runner is not paused" }, | |
| 16 | }; |
src/contract/openapi/routes/postApiV1AdminRunnersIdRevoke.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/admin/runners/{id}/revoke", | |
| 6 | summary: "Revoke a runner: its next request is refused, and its row and core-minutes stay", | |
| 7 | detail: | |
| 8 | "Revoke a runner by id (admin scope): its token is refused from its next request, a job it held is queued again, and its row stays with the core-minutes it ran; 422 local for a local-N runner, 422 revoked when it is already; 404 when there is none", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | status: 200, | |
| 12 | reply: { id: "string", name: "string", revoked: "boolean" }, | |
| 13 | refuses: [404], | |
| 14 | errorStatus: { 422: "the runner is the forge's own (local) or revoked already (revoked)" }, | |
| 15 | refusals: { local: "a local-N runner is the forge's own", revoked: "that runner is revoked already" }, | |
| 16 | }; |
src/core/account_purge.ts +1
| @@ -68,6 +68,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 68 | 68 | "bet.backed_by": FORMER, |
| 69 | 69 | "check_proven.proven_by": FORMER, |
| 70 | 70 | "check_runner.created_by": FORMER, |
| 71 | "check_job.author": { do: "none", why: "the login a lent runner's authors scope matches, copied from the pull while its check is in flight" }, | |
| 71 | 72 | "child_reach_ask.asked_by": FORMER, |
| 72 | 73 | "child_reach_ask.answered_by": FORMER, |
| 73 | 74 | "child_reach_grant.granted_by": FORMER, |
src/core/migration-pins/20261130140000-lent-runner-scope.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 05a2d4a653a531c56f4fe7a6d78bce333f96dab70ee9149245e6ee2f90c0f45a |
src/core/migrations/20261130140000-lent-runner-scope.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | // Lent runners (f2f v1): a runner another forge runs for this one is held to a scope that the | |
| 2 | // claim enforces (`checks/lent_scope.ts`). On `check_runner`: `scope` is the grant as JSON (NULL | |
| 3 | // for a runner this forge owns), `core_ms` every core-millisecond it ran, `day`/`day_core_ms` the | |
| 4 | // UTC day's share the budget is held to, `paused` why it takes nothing now ('' when it may), | |
| 5 | // `revoked_at` when its token was killed (0 for never; the row stays for the ledger), `salt` the | |
| 6 | // secret that picks which of its greens are run again here and when a canary is due, `canary_at` | |
| 7 | // when it was last given one. On `check_job`: `author` is the pull's author as the claim filters | |
| 8 | // it, `claimed_at` when its claim began (what a core-minute is measured from), `canary_for` the | |
| 9 | // runner a canary is for (NULL for a real job). | |
| 10 | // Additive: columns only. | |
| 11 | export default ` | |
| 12 | ALTER TABLE check_runner ADD COLUMN scope TEXT; | |
| 13 | ALTER TABLE check_runner ADD COLUMN core_ms INTEGER NOT NULL DEFAULT 0; | |
| 14 | ALTER TABLE check_runner ADD COLUMN day TEXT NOT NULL DEFAULT ''; | |
| 15 | ALTER TABLE check_runner ADD COLUMN day_core_ms INTEGER NOT NULL DEFAULT 0; | |
| 16 | ALTER TABLE check_runner ADD COLUMN paused TEXT NOT NULL DEFAULT ''; | |
| 17 | ALTER TABLE check_runner ADD COLUMN revoked_at INTEGER NOT NULL DEFAULT 0; | |
| 18 | ALTER TABLE check_runner ADD COLUMN salt TEXT NOT NULL DEFAULT ''; | |
| 19 | ALTER TABLE check_runner ADD COLUMN canary_at INTEGER NOT NULL DEFAULT 0; | |
| 20 | ALTER TABLE check_job ADD COLUMN author TEXT NOT NULL DEFAULT ''; | |
| 21 | ALTER TABLE check_job ADD COLUMN claimed_at INTEGER NOT NULL DEFAULT 0; | |
| 22 | ALTER TABLE check_job ADD COLUMN canary_for TEXT; | |
| 23 | `; |
src/http/api/runners.ts +37 −4
| @@ -9,7 +9,8 @@ | ||
| 9 | 9 | * stranger's header: no page, no API route and no git door knows them. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { enrol, list, remove } from "../../actions/runners.ts"; | |
| 12 | import { enrol, hearCanary, list, remove, resume, revoke } from "../../actions/runners.ts"; | |
| 13 | import type { LendInput } from "../../checks/lent_scope.ts"; | |
| 13 | 14 | import { machineLoad, mayTakeJob, yieldThreshold } from "../../checks/lent_yield.ts"; |
| 14 | 15 | import { |
| 15 | 16 | LEASE_MS, |
| @@ -86,16 +87,46 @@ function readResult(raw: unknown): RunnerResult | undefined { | ||
| 86 | 87 | }; |
| 87 | 88 | } |
| 88 | 89 | |
| 90 | /** What an enrolment's `lend` says, field by field; undefined when it says nothing. */ | |
| 91 | function readLend(raw: unknown): LendInput | undefined { | |
| 92 | if (typeof raw !== "object" || raw === null) return undefined; | |
| 93 | const from = raw as Record<string, unknown>; | |
| 94 | return { | |
| 95 | ...(Array.isArray(from.authors) ? { authors: from.authors.filter((a): a is string => typeof a === "string") } : {}), | |
| 96 | ...(typeof from.days === "number" ? { days: from.days } : {}), | |
| 97 | ...(typeof from.coreMinPerDay === "number" ? { coreMinPerDay: from.coreMinPerDay } : {}), | |
| 98 | }; | |
| 99 | } | |
| 100 | ||
| 89 | 101 | export function runnerRoutes(router: Router<Handler>): void { |
| 90 | 102 | router.add("POST", "/api/v1/admin/runners", async (ctx) => { |
| 91 | 103 | const denied = accountAdmin(ctx, "admin"); |
| 92 | 104 | if (denied) return denied; |
| 93 | 105 | const input = await body(ctx.request); |
| 94 | const made = enrol(ctx.app, ctx.auth.user, str(input.name)); | |
| 106 | const made = enrol(ctx.app, ctx.auth.user, str(input.name), readLend(input.lend)); | |
| 95 | 107 | if (!made.ok) return notFound(); |
| 96 | 108 | return json({ ...made.value.runner, token: made.value.token }, 201); |
| 97 | 109 | }); |
| 98 | 110 | |
| 111 | // A lent runner's token stops at its next request; its row and core-minutes stay. | |
| 112 | router.add("POST", "/api/v1/admin/runners/:id/revoke", (ctx) => { | |
| 113 | const denied = accountAdmin(ctx, "admin"); | |
| 114 | if (denied) return denied; | |
| 115 | const done = revoke(ctx.app, ctx.auth.user, ctx.params.id!); | |
| 116 | if (done.ok) return json({ ...done.value, revoked: true }); | |
| 117 | if (done.error === "local") return apiError("local", 422, "a local-N runner is the forge's own; it is started again at each boot"); | |
| 118 | if (done.error === "revoked") return apiError("revoked", 422, "that runner is revoked already"); | |
| 119 | return notFound(); | |
| 120 | }); | |
| 121 | ||
| 122 | router.add("POST", "/api/v1/admin/runners/:id/resume", (ctx) => { | |
| 123 | const denied = accountAdmin(ctx, "admin"); | |
| 124 | if (denied) return denied; | |
| 125 | const done = resume(ctx.app, ctx.auth.user, ctx.params.id!); | |
| 126 | if (done.ok) return json({ ...done.value, paused: "" }); | |
| 127 | return done.error === "not_paused" ? apiError("not_paused", 422, "that runner is not paused") : notFound(); | |
| 128 | }); | |
| 129 | ||
| 99 | 130 | router.add("GET", "/api/v1/admin/runners", (ctx) => { |
| 100 | 131 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 101 | 132 | const denied = accountAdmin(ctx, "ro"); |
| @@ -127,8 +158,9 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 127 | 158 | const stop = AbortSignal.any([ctx.request.signal, ctx.app.closing.signal]); |
| 128 | 159 | const threshold = yieldThreshold(process.env["FORGE_LEND_YIELD_LOAD"]); |
| 129 | 160 | for (;;) { |
| 130 | // Removed while it waited: its token is no longer one. | |
| 131 | if (getRunner(ctx.app.db, runner.id) === undefined) return unauthorized(); | |
| 161 | // Removed or revoked while it waited: its token is no longer one. | |
| 162 | const now = getRunner(ctx.app.db, runner.id); | |
| 163 | if (now === undefined || now.revokedAt !== 0) return unauthorized(); | |
| 132 | 164 | const claim = !mayTakeJob(runner.name, machineLoad(), threshold) |
| 133 | 165 | ? undefined |
| 134 | 166 | : claimJob( |
| @@ -137,6 +169,7 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 137 | 169 | Date.now(), |
| 138 | 170 | ); |
| 139 | 171 | if (claim !== undefined) { |
| 172 | if (claim.canary === true) hearCanary(ctx.app, claim.job.id); | |
| 140 | 173 | deskOf(ctx.app).ears.get(claim.job.id)?.wake(); |
| 141 | 174 | return json({ job: claim.job, token: claim.token, lease }); |
| 142 | 175 | } |
src/http/marks/settings.json +2
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | "/settings/trusted/:id/remove": "admin", |
| 9 | 9 | "/settings/runners": "open", |
| 10 | 10 | "/settings/runners/:id/remove": "open", |
| 11 | "/settings/runners/:id/revoke": "open", | |
| 12 | "/settings/runners/:id/resume": "open", | |
| 11 | 13 | "/settings/telemetry": "admin", |
| 12 | 14 | "/settings": "open", |
| 13 | 15 | "/settings/notify": "open", |
src/http/settings_routes.ts +3 −1
| @@ -23,7 +23,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 23 | 23 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 24 | 24 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 25 | 25 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 26 | import { runnerRemove, runnersPage } from "../web/pages/runners.ts"; | |
| 26 | import { runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts"; | |
| 27 | 27 | import { usagePage } from "../web/pages/usage.ts"; |
| 28 | 28 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| 29 | 29 | import { securityControlsPage } from "../web/pages/security_controls.ts"; |
| @@ -170,6 +170,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 170 | 170 | router.add("POST", "/settings/trusted/:id/remove", trustedRemove); |
| 171 | 171 | router.add("GET", "/settings/runners", runnersPage); |
| 172 | 172 | router.add("POST", "/settings/runners/:id/remove", runnerRemove); |
| 173 | router.add("POST", "/settings/runners/:id/revoke", runnerRevoke); | |
| 174 | router.add("POST", "/settings/runners/:id/resume", runnerResume); | |
| 173 | 175 | router.add("GET", "/settings/telemetry", telemetryPage); |
| 174 | 176 | router.add("POST", "/settings/telemetry", telemetrySet); |
| 175 | 177 | router.add("GET", "/settings", accountPage); |
src/kernel/destroy_reach.ts +1 −1
| @@ -68,7 +68,7 @@ export const ALLOWED_REMOVALS: readonly { unit: string; why: string }[] = [ | ||
| 68 | 68 | "src/git/seed_history.ts:prune", |
| 69 | 69 | ]), |
| 70 | 70 | ...unitsOn("scratch under the checks root, per run or commit (checkouts, caches, locks, the install cache): never a forge's or an app's directory", [ |
| 71 | "src/checks/run_tier.ts:runTier", | |
| 71 | "src/checks/run_tier.ts:runTierOnce", | |
| 72 | 72 | "src/checks/sweep.ts:removeRunDir", |
| 73 | 73 | "src/checks/cache.ts:restoreCache", |
| 74 | 74 | "src/checks/cache.ts:keepCache", |
src/tui/screens/runners.ts +39 −8
| @@ -6,9 +6,10 @@ | ||
| 6 | 6 | * offered it. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts"; | |
| 9 | import { isLocal, list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 10 | import { lentLine, scopeLine } from "../../checks/lent_scope.ts"; | |
| 10 | 11 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 11 | import { heldByRunner, workByRunner } from "../../checks/runner_jobs.ts"; | |
| 12 | import { heldByRunner, lentIn, workByRunner, type Enrolled } from "../../checks/runner_jobs.ts"; | |
| 12 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 13 | 14 | import { binding } from "../app/keys.ts"; |
| 14 | 15 | import { style } from "../term/style.ts"; |
| @@ -22,6 +23,12 @@ export const mayRunners = (f: Session): boolean => f.user !== undefined && f.use | ||
| 22 | 23 | |
| 23 | 24 | const STATE_WORDS = { connected: "connected", quiet: "quiet", never: "never asked" } as const; |
| 24 | 25 | |
| 26 | /** A lent runner that still works: `x` revokes it rather than removing its ledger. */ | |
| 27 | const revocable = (r: Enrolled): boolean => r.scope !== undefined && r.revokedAt === 0; | |
| 28 | ||
| 29 | const stateWords = (r: Enrolled, now: number): string => | |
| 30 | r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now)]; | |
| 31 | ||
| 25 | 32 | export function runnersScreen(f: Session, ctx: Ctx): Screen { |
| 26 | 33 | const state = new ListState(); |
| 27 | 34 | const entries = () => { |
| @@ -38,25 +45,27 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 38 | 45 | const w = work.get(r.id) ?? { jobs: 1, ran: 0 }; |
| 39 | 46 | const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`; |
| 40 | 47 | return { |
| 41 | title: `${r.name} ${STATE_WORDS[runnerState(r.seenAt, now)]}${isLocal(r) ? " (the forge's own)" : ""}`, | |
| 42 | meta: `${asked} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run`, | |
| 48 | title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`, | |
| 49 | meta: `${asked} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}`, | |
| 43 | 50 | }; |
| 44 | 51 | }); |
| 45 | 52 | }; |
| 46 | 53 | |
| 47 | 54 | const screen: Screen = { |
| 48 | 55 | title: "Runners", |
| 49 | keys: [binding(["j", "k"], "move cursor"), binding(["x"], "remove")], | |
| 56 | keys: [binding(["j", "k"], "move cursor"), binding(["x"], "revoke or remove"), binding(["u"], "resume")], | |
| 50 | 57 | render(area, s) { |
| 51 | 58 | const c = ctx.theme.c; |
| 52 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 59 | const [head, lentRow, body] = split(area, "v", [len(1), len(1), fill(1)]); | |
| 53 | 60 | const text = !mayRunners(f) |
| 54 | 61 | ? "Only a forge admin sees the runners." |
| 55 | 62 | : entries().length === 0 |
| 56 | 63 | ? "No runner is enrolled; checks run on the forge's own machine." |
| 57 | : "The machines that take this forge's checks; x removes a hand-made one."; | |
| 64 | : "The machines that take this forge's checks; x revokes a lent one or removes a hand-made one, u resumes a paused one."; | |
| 58 | 65 | const waiting = mayRunners(f) ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : ""; |
| 59 | 66 | s.text(head!.x, head!.y, truncate(waiting === "" ? text : waiting, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 67 | const lent = mayRunners(f) ? lentLine(lentIn(f.db, Date.now())) : ""; | |
| 68 | if (lent !== "") s.text(lentRow!.x, lentRow!.y, truncate(lent, lentRow!.w), style(c.mutedFg, c.bg), lentRow!.x + lentRow!.w); | |
| 60 | 69 | drawList(s, body!, c, state, rows()); |
| 61 | 70 | }, |
| 62 | 71 | key(e) { |
| @@ -64,11 +73,33 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 64 | 73 | const all = entries(); |
| 65 | 74 | if (state.key(e, all.length)) return true; |
| 66 | 75 | const at = all[state.index]; |
| 67 | if (at === undefined || e.key !== "x") return false; | |
| 76 | if (at === undefined || (e.key !== "x" && e.key !== "u")) return false; | |
| 77 | if (e.key === "u") { | |
| 78 | const done = resume(f.app, f.user, at.id); | |
| 79 | ctx.toast(done.ok ? `Runner ${at.name} may claim again.` : "That runner is not paused.", done.ok ? "success" : "danger"); | |
| 80 | ctx.invalidate(); | |
| 81 | return true; | |
| 82 | } | |
| 68 | 83 | if (isLocal(at)) { |
| 69 | 84 | ctx.toast(`${at.name} is the forge's own; it is started again at each boot.`, "danger"); |
| 70 | 85 | return true; |
| 71 | 86 | } |
| 87 | if (revocable(at)) { | |
| 88 | ctx.push( | |
| 89 | confirmScreen(ctx, screen, { | |
| 90 | title: "Revoke lent runner", | |
| 91 | body: [`${at.name}'s next request is refused and any job it holds is queued again; its core-minutes stay counted.`], | |
| 92 | actions: [{ label: "Keep", variant: "ghost" }, { label: "Revoke", variant: "default" }], | |
| 93 | onChoose: (i) => { | |
| 94 | if (i !== 1) return; | |
| 95 | const done = revoke(f.app, f.user, at.id); | |
| 96 | ctx.toast(done.ok ? `Runner ${at.name} is revoked.` : "That runner is not enrolled.", done.ok ? "success" : "danger"); | |
| 97 | ctx.invalidate(); | |
| 98 | }, | |
| 99 | }), | |
| 100 | ); | |
| 101 | return true; | |
| 102 | } | |
| 72 | 103 | ctx.push( |
| 73 | 104 | confirmScreen(ctx, screen, { |
| 74 | 105 | title: "Remove runner", |
src/web/pages/capacity.ts +4
| @@ -22,6 +22,8 @@ import { badge, btn, row, time } from "../ui.ts"; | ||
| 22 | 22 | import { emptyLine } from "../empty_words.ts"; |
| 23 | 23 | import { usageShell } from "./usage-tabs.ts"; |
| 24 | 24 | import { REACH_SETTINGS } from "../../actions/child_reach.ts"; |
| 25 | import { lentLine } from "../../checks/lent_scope.ts"; | |
| 26 | import { lentIn } from "../../checks/runner_jobs.ts"; | |
| 25 | 27 | |
| 26 | 28 | function requireAdmin(ctx: Ctx): Response | undefined { |
| 27 | 29 | if (!ctx.auth.user) return signInFirst(ctx); |
| @@ -75,6 +77,7 @@ export function capacityPage(ctx: Ctx): Response { | ||
| 75 | 77 | ctx.app.signals.refused.recent(), |
| 76 | 78 | ); |
| 77 | 79 | const rendering = performance.now(); |
| 80 | const lent = lentLine(lentIn(ctx.app.db, Date.now())); | |
| 78 | 81 | const byKey = new Map(settings.map((s) => [s.key, s])); |
| 79 | 82 | const effects = timePhase(ctx.request, "effects", () => |
| 80 | 83 | new Map(settings.map((s) => [s.key, effectOf(ctx.app, s.key, s.value)])), |
| @@ -200,6 +203,7 @@ export function capacityPage(ctx: Ctx): Response { | ||
| 200 | 203 | () => html`<p class="muted small mb" id="egress-reported">${EGRESS_REPORTED}</p>`, |
| 201 | 204 | )} |
| 202 | 205 | <p class="small" id="load">${loadLine(ctx.app)}</p> |
| 206 | ${lent === "" ? "" : html`<p class="small" id="lent-line"><a href="/settings/runners">${lent}</a></p>`} | |
| 203 | 207 | ${table} |
| 204 | 208 | ${block("Changes", history.length === 0 ? emptyLine("changes") : html`<ul class="list">${history}</ul>`, "changes")} |
| 205 | 209 | ${happened}${connections}${swap}`; |
src/web/pages/runners.ts +67 −13
| @@ -8,9 +8,10 @@ | ||
| 8 | 8 | * routes are marked `open` in `http/marks/settings.json`, as `/admin/flows` is, so this page's own |
| 9 | 9 | * check answers rather than the admin gate's 403. |
| 10 | 10 | */ |
| 11 | import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts"; | |
| 11 | import { isLocal, list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 12 | import { lentLine, scopeFacts } from "../../checks/lent_scope.ts"; | |
| 12 | 13 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 13 | import { heldByRunner, workByRunner, type Enrolled, type RunnerWork } from "../../checks/runner_jobs.ts"; | |
| 14 | import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork } from "../../checks/runner_jobs.ts"; | |
| 14 | 15 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 15 | 16 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 17 | import { sshOn } from "../../settings/ssh.ts"; |
| @@ -29,24 +30,39 @@ function admin(ctx: Ctx): Response | undefined { | ||
| 29 | 30 | return ctx.auth.user.isAdmin && ctx.auth.user.kind === "user" ? undefined : notFoundPage(ctx); |
| 30 | 31 | } |
| 31 | 32 | |
| 33 | /** | |
| 34 | * A row's buttons: a lent runner is revoked (its ledger stays) and resumed; any other hand-made one | |
| 35 | * removed. | |
| 36 | */ | |
| 37 | function runnerTrail(r: Enrolled) { | |
| 38 | if (isLocal(r)) return html`<span class="muted small">The forge's own: started again at each boot, so not removed here.</span>`; | |
| 39 | const form = (verb: string, label: string) => | |
| 40 | html`<form class="row-fields" method="post" action="${HERE}/${r.id}/${verb}"> | |
| 41 | ${btn(label, { size: "sm", variant: "outline", label: `${label} runner ${r.name}` })} | |
| 42 | </form>`; | |
| 43 | if (r.scope === undefined || r.revokedAt !== 0) return form("remove", "Remove"); | |
| 44 | return html`${r.paused === "" ? "" : form("resume", "Resume")}${form("revoke", "Revoke")}`; | |
| 45 | } | |
| 46 | ||
| 32 | 47 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) { |
| 33 | 48 | const state = runnerState(r.seenAt, now); |
| 34 | 49 | return row({ |
| 35 | 50 | lead: icon("activity"), |
| 36 | state: state === "connected" ? "open" : "draft", | |
| 51 | state: state === "connected" && r.revokedAt === 0 ? "open" : "draft", | |
| 37 | 52 | title: html`${r.name} <span class="muted small mono">${r.id}</span> |
| 38 | ${state === "connected" | |
| 39 | ? badge("Connected", { variant: "secondary", icon: "check" }) | |
| 40 | : state === "quiet" | |
| 41 | ? badge("Quiet", { variant: "outline", icon: "clock" }) | |
| 42 | : badge("Never asked", { variant: "outline", icon: "ban" })}`, | |
| 53 | ${r.revokedAt !== 0 | |
| 54 | ? badge("Revoked", { variant: "outline", icon: "ban" }) | |
| 55 | : r.paused !== "" | |
| 56 | ? badge("Paused", { tone: "attn" }) | |
| 57 | : state === "connected" | |
| 58 | ? badge("Connected", { variant: "secondary", icon: "check" }) | |
| 59 | : state === "quiet" | |
| 60 | ? badge("Quiet", { variant: "outline", icon: "clock" }) | |
| 61 | : badge("Never asked", { variant: "outline", icon: "ban" })}`, | |
| 43 | 62 | meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`} |
| 44 | 63 | · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`, |
| 45 | trail: isLocal(r) | |
| 46 | ? html`<span class="muted small">The forge's own: started again at each boot, so not removed here.</span>` | |
| 47 | : html`<form class="row-fields" method="post" action="${HERE}/${r.id}/remove"> | |
| 48 | ${btn("Remove", { size: "sm", variant: "outline", label: `Remove runner ${r.name}` })} | |
| 49 | </form>`, | |
| 64 | facts: scopeFacts(r, now), | |
| 65 | trail: runnerTrail(r), | |
| 50 | 66 | }); |
| 51 | 67 | } |
| 52 | 68 | |
| @@ -62,8 +78,10 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 62 | 78 | const held = heldByRunner(ctx.app.db); |
| 63 | 79 | const work = workByRunner(ctx.app.db); |
| 64 | 80 | const waiting = yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])); |
| 81 | const lent = lentLine(lentIn(ctx.app.db, now)); | |
| 65 | 82 | const body = html`<section class="settings-block"> |
| 66 | 83 | ${waiting === "" ? "" : html`<p class="muted small" id="lent-waiting">${waiting}</p>`} |
| 84 | ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`} | |
| 67 | 85 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>.</p> |
| 68 | 86 | ${seen.value.length === 0 |
| 69 | 87 | ? emptyList("runners") |
| @@ -80,6 +98,42 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 80 | 98 | }); |
| 81 | 99 | } |
| 82 | 100 | |
| 101 | // POST /settings/runners/:id/revoke | |
| 102 | export async function runnerRevoke(ctx: Ctx): Promise<Response> { | |
| 103 | const denied = admin(ctx); | |
| 104 | if (denied) return denied; | |
| 105 | const form = await readForm(ctx, "admin"); | |
| 106 | if (form instanceof Response) return form; | |
| 107 | const done = revoke(ctx.app, ctx.auth.user, ctx.params.id ?? ""); | |
| 108 | return flashTo( | |
| 109 | ctx, | |
| 110 | HERE, | |
| 111 | done.ok | |
| 112 | ? { message: `Runner ${done.value.name} is revoked: its next request is refused, and its core-minutes stay counted.` } | |
| 113 | : done.error === "local" | |
| 114 | ? { tone: "danger", message: "That runner is the forge's own; it is started again at each boot." } | |
| 115 | : done.error === "revoked" | |
| 116 | ? { tone: "danger", message: "That runner is revoked already." } | |
| 117 | : { tone: "danger", message: "That runner is not enrolled." }, | |
| 118 | ); | |
| 119 | } | |
| 120 | ||
| 121 | // POST /settings/runners/:id/resume | |
| 122 | export async function runnerResume(ctx: Ctx): Promise<Response> { | |
| 123 | const denied = admin(ctx); | |
| 124 | if (denied) return denied; | |
| 125 | const form = await readForm(ctx, "admin"); | |
| 126 | if (form instanceof Response) return form; | |
| 127 | const done = resume(ctx.app, ctx.auth.user, ctx.params.id ?? ""); | |
| 128 | return flashTo( | |
| 129 | ctx, | |
| 130 | HERE, | |
| 131 | done.ok | |
| 132 | ? { message: `Runner ${done.value.name} may claim again.` } | |
| 133 | : { tone: "danger", message: done.error === "not_paused" ? "That runner is not paused." : "That runner is not enrolled." }, | |
| 134 | ); | |
| 135 | } | |
| 136 | ||
| 83 | 137 | // POST /settings/runners/:id/remove |
| 84 | 138 | export async function runnerRemove(ctx: Ctx): Promise<Response> { |
| 85 | 139 | const denied = admin(ctx); |
test/lent-runners.test.ts added +363
| @@ -0,0 +1,363 @@ | ||
| 1 | // Lent runners (f2f v1, docs/features/lent-runners.md): a runner another forge runs for this one | |
| 2 | // claims only public pulls in a cell, within its expiry and its core-minutes per day; a share of | |
| 3 | // its greens is run here and a canary must come back red, either catch pausing it; an admin | |
| 4 | // revokes it from the web or the API, and its next claim is refused while its ledger stays. | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { judgeLentGreen, sampleLentGreen } from "../src/actions/runners.ts"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { setLoadSource } from "../src/checks/lent_yield.ts"; | |
| 13 | import { canaryDue, coreMs, LEND_CORE_MIN, LEND_DAYS, sampled, SAMPLE_ALL_UNTIL, scopeFrom } from "../src/checks/lent_scope.ts"; | |
| 14 | import { claimJob, enrolRunner, getRunner, lentIn, offerJob, settleJob, type Claim, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 15 | import type { Repo } from "../src/core/repos.ts"; | |
| 16 | import { createSession } from "../src/core/sessions.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import type { User } from "../src/core/users.ts"; | |
| 19 | import { serve } from "../src/http/server.ts"; | |
| 20 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | const DAY = 86_400_000; | |
| 26 | const T0 = Date.parse("2026-12-01T09:00:00Z"); | |
| 27 | ||
| 28 | let dataDir = ""; | |
| 29 | let app: App; | |
| 30 | let alice: User; | |
| 31 | let pub: Repo; | |
| 32 | let priv: Repo; | |
| 33 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 34 | ||
| 35 | beforeAll(async () => { | |
| 36 | dataDir = await mkdtemp(join(tmpdir(), "forge-lent-runners-")); | |
| 37 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 38 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 39 | if (!a.ok) throw new Error(a.error); | |
| 40 | alice = a.value; | |
| 41 | const p = await createRepo(app, alice, { name: "open", visibility: "public" }); | |
| 42 | const q = await createRepo(app, alice, { name: "secret", visibility: "private" }); | |
| 43 | if (!p.ok || !q.ok) throw new Error("repos"); | |
| 44 | pub = p.value; | |
| 45 | priv = q.value; | |
| 46 | servers = await serve(app); | |
| 47 | // A lent runner's claim waits while this machine is loaded (#16479): the tests' machine is idle. | |
| 48 | setLoadSource(() => 0); | |
| 49 | }); | |
| 50 | ||
| 51 | afterAll(async () => { | |
| 52 | setLoadSource(); | |
| 53 | servers.stop(); | |
| 54 | app.close(); | |
| 55 | await rm(dataDir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | const spec = (run: string, cpus?: number): Omit<RunnerJob, "id"> => ({ | |
| 59 | run, | |
| 60 | repo: "alice/x", | |
| 61 | commit: "a".repeat(40), | |
| 62 | depth: 1, | |
| 63 | steps: [{ name: "check", command: "bun test" }], | |
| 64 | env: { CI: "1" }, | |
| 65 | limits: cpus === undefined ? {} : { cpus }, | |
| 66 | timeoutS: 60, | |
| 67 | egress: [], | |
| 68 | egressMode: "enforce", | |
| 69 | cell: "preferred", | |
| 70 | cache: { repo: "r", tree: "", base: "" }, | |
| 71 | }); | |
| 72 | ||
| 73 | /** Every job off the desk, so each test starts from an empty one. */ | |
| 74 | const clearDesk = () => app.db.query("DELETE FROM check_job").run(); | |
| 75 | const offer = (repo: Repo, run: string, author = "", cpus?: number) => | |
| 76 | offerJob(app.db, { runId: run, repoId: repo.id, dir: "/nowhere", job: spec(run, cpus), author }); | |
| 77 | /** A lent runner past its canary and its every-green sample, so a claim is a real job. */ | |
| 78 | const seasoned = (name: string, lend = {}, now = T0) => { | |
| 79 | const made = enrolRunner(app.db, name, alice.id, lend, now); | |
| 80 | noCanary(made.runner.id); | |
| 81 | return made; | |
| 82 | }; | |
| 83 | /** | |
| 84 | * Past its first canary, at a job count whose canary draw is not one: its next claim is a real job. | |
| 85 | */ | |
| 86 | const noCanary = (runnerId: string) => { | |
| 87 | const salt = app.db.query<{ salt: string }, [string]>("SELECT salt FROM check_runner WHERE id = ?1").get(runnerId)!.salt; | |
| 88 | let ran = 100; | |
| 89 | while (canaryDue(salt, 1, ran)) ran++; | |
| 90 | app.db.query("UPDATE check_runner SET canary_at = 1, ran = ?2 WHERE id = ?1").run(runnerId, ran); | |
| 91 | }; | |
| 92 | const done = (claim: Claim, green: boolean, now: number) => | |
| 93 | settleJob(app.db, claim.job.id, claim.token, { done: { steps: [{ name: "check", ok: green, ms: 1 }], contained: true, note: "" } }, now); | |
| 94 | ||
| 95 | describe("scope", () => { | |
| 96 | test("a lent runner claims only public pulls, in a cell; an owned one claims anything", () => { | |
| 97 | clearDesk(); | |
| 98 | const lent = seasoned("benji"); | |
| 99 | const owned = enrolRunner(app.db, "mac", alice.id); | |
| 100 | expect(lent.runner.name).toBe("lent-benji"); | |
| 101 | expect(lent.runner.scope).toEqual({ authors: [], expiresAt: T0 + LEND_DAYS * DAY, coreMinPerDay: LEND_CORE_MIN }); | |
| 102 | expect(owned.runner.scope).toBeUndefined(); | |
| 103 | const secret = offer(priv, "s1"); | |
| 104 | // Only the private job is queued: the lent runner gets nothing, with or without cells. | |
| 105 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0)).toBeUndefined(); | |
| 106 | const open = offer(pub, "p1"); | |
| 107 | // Without cells it takes nothing at all, though a public job is there. | |
| 108 | expect(claimJob(app.db, { id: lent.runner.id, cells: false }, T0)).toBeUndefined(); | |
| 109 | const got = claimJob(app.db, { id: lent.runner.id, cells: true }, T0)!; | |
| 110 | expect(got.job.id).toBe(open.id); | |
| 111 | expect(got.job.cell).toBe("required"); | |
| 112 | expect(got.canary).toBeUndefined(); | |
| 113 | // The private job is still there for the forge's own runner. | |
| 114 | expect(claimJob(app.db, { id: owned.runner.id, cells: false }, T0)!.job.id).toBe(secret.id); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a repository made private after the offer is out of scope at the claim", () => { | |
| 118 | clearDesk(); | |
| 119 | const lent = seasoned("flip"); | |
| 120 | offer(pub, "f1"); | |
| 121 | app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(pub.id); | |
| 122 | try { | |
| 123 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0)).toBeUndefined(); | |
| 124 | } finally { | |
| 125 | app.db.query("UPDATE repo SET visibility = 'public' WHERE id = ?1").run(pub.id); | |
| 126 | } | |
| 127 | }); | |
| 128 | ||
| 129 | test("an authors scope takes only those authors' pulls, whatever the case", () => { | |
| 130 | clearDesk(); | |
| 131 | const lent = seasoned("guest", { authors: ["Benjiver", " omato "] }); | |
| 132 | expect(lent.runner.scope?.authors).toEqual(["benjiver", "omato"]); | |
| 133 | offer(pub, "a1", "alice"); | |
| 134 | const theirs = offer(pub, "a2", "BenJiver"); | |
| 135 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0)!.job.id).toBe(theirs.id); | |
| 136 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0)).toBeUndefined(); | |
| 137 | }); | |
| 138 | ||
| 139 | test("an expired lent runner claims nothing", () => { | |
| 140 | clearDesk(); | |
| 141 | const lent = seasoned("brief", { days: 2 }); | |
| 142 | offer(pub, "e1"); | |
| 143 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0 + 2 * DAY)).toBeUndefined(); | |
| 144 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0 + 2 * DAY - 1)).toBeDefined(); | |
| 145 | }); | |
| 146 | ||
| 147 | test("a lent- runner enrolled before scopes is held to the defaults, never claims as owned", () => { | |
| 148 | clearDesk(); | |
| 149 | const old = enrolRunner(app.db, "legacy", alice.id); | |
| 150 | app.db.query("UPDATE check_runner SET name = 'lent-legacy', scope = NULL, canary_at = 1, ran = 100 WHERE id = ?1").run(old.runner.id); | |
| 151 | expect(getRunner(app.db, old.runner.id)!.scope?.coreMinPerDay).toBe(LEND_CORE_MIN); | |
| 152 | offer(priv, "l1"); | |
| 153 | expect(claimJob(app.db, { id: old.runner.id, cells: true }, Date.now())).toBeUndefined(); | |
| 154 | }); | |
| 155 | ||
| 156 | test("an admin's numbers are held to their ranges", () => { | |
| 157 | expect(scopeFrom({ days: 10_000, coreMinPerDay: -5 }, 0)).toEqual({ authors: [], expiresAt: 365 * DAY, coreMinPerDay: 1 }); | |
| 158 | expect(scopeFrom({ authors: ["a b;c", ""] }, 0).authors).toEqual(["abc"]); | |
| 159 | }); | |
| 160 | }); | |
| 161 | ||
| 162 | describe("accounting", () => { | |
| 163 | test("core-minutes are wall time × declared cpus, per runner, and the day's budget stops claims", () => { | |
| 164 | clearDesk(); | |
| 165 | const lent = seasoned("budget", { coreMinPerDay: 10 }); | |
| 166 | expect(coreMs(60_000, undefined)).toBe(60_000); | |
| 167 | expect(coreMs(60_000, 0.5)).toBe(60_000); | |
| 168 | // Four cpus for two minutes: 8 core-minutes, under 10. | |
| 169 | offer(pub, "b1", "", 4); | |
| 170 | const first = claimJob(app.db, { id: lent.runner.id, cells: true }, T0)!; | |
| 171 | expect(done(first, true, T0 + 120_000)).toBe(true); | |
| 172 | expect(getRunner(app.db, lent.runner.id)!.coreMs).toBe(8 * 60_000); | |
| 173 | // One more minute on 2 cpus: 10, the budget, and nothing more today. | |
| 174 | offer(pub, "b2", "", 2); | |
| 175 | noCanary(lent.runner.id); | |
| 176 | const second = claimJob(app.db, { id: lent.runner.id, cells: true }, T0 + 130_000)!; | |
| 177 | // A job handed back still spent the time. | |
| 178 | expect(settleJob(app.db, second.job.id, second.token, { returned: "no cell" }, T0 + 190_000)).toBe(true); | |
| 179 | offer(pub, "b3"); | |
| 180 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0 + 200_000)).toBeUndefined(); | |
| 181 | // The next UTC day starts a new budget; the total keeps counting. | |
| 182 | const tomorrow = T0 + DAY; | |
| 183 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, tomorrow)).toBeDefined(); | |
| 184 | const row = app.db | |
| 185 | .query<{ core_ms: number; day: string }, [string]>("SELECT core_ms, day FROM check_runner WHERE id = ?1") | |
| 186 | .get(lent.runner.id)!; | |
| 187 | expect(row).toEqual({ core_ms: 10 * 60_000, day: "2026-12-01" }); | |
| 188 | expect(lentIn(app.db, T0).coreMs).toBeGreaterThanOrEqual(10 * 60_000); | |
| 189 | }); | |
| 190 | }); | |
| 191 | ||
| 192 | describe("trust in results", () => { | |
| 193 | test("a new lent runner's every green is sampled, then a share by a salted hash; an owned one never", () => { | |
| 194 | const lent = enrolRunner(app.db, "fresh", alice.id, {}); | |
| 195 | const owned = enrolRunner(app.db, "own", alice.id); | |
| 196 | expect(sampleLentGreen(app, lent.runner.id, "job-1")).toBe(true); | |
| 197 | expect(sampleLentGreen(app, owned.runner.id, "job-1")).toBe(false); | |
| 198 | const share = Array.from({ length: 2_000 }, (_, i) => sampled("salt", `j${i}`, SAMPLE_ALL_UNTIL)).filter(Boolean).length / 2_000; | |
| 199 | expect(share).toBeGreaterThan(0.1); | |
| 200 | expect(share).toBeLessThan(0.2); | |
| 201 | // A different salt draws a different set: the runner cannot tell from the id alone. | |
| 202 | const a = Array.from({ length: 200 }, (_, i) => sampled("one", `j${i}`, 99)); | |
| 203 | const b = Array.from({ length: 200 }, (_, i) => sampled("two", `j${i}`, 99)); | |
| 204 | expect(a).not.toEqual(b); | |
| 205 | }); | |
| 206 | ||
| 207 | test("a sampled green found red here pauses the runner, and it claims nothing until resumed", () => { | |
| 208 | clearDesk(); | |
| 209 | const lent = seasoned("liar"); | |
| 210 | const lines: string[] = []; | |
| 211 | const green = { runnerId: lent.runner.id, runner: lent.runner.name, commit: "b".repeat(40) }; | |
| 212 | judgeLentGreen(app, green, { ok: true }, (l) => lines.push(l)); | |
| 213 | expect(getRunner(app.db, lent.runner.id)!.paused).toBe(""); | |
| 214 | // A cancelled or infrastructure run here proves nothing. | |
| 215 | judgeLentGreen(app, green, { ok: false, error: "check cancelled" }, (l) => lines.push(l)); | |
| 216 | judgeLentGreen(app, green, { ok: false, error: "disk", infrastructure: true }, (l) => lines.push(l)); | |
| 217 | expect(getRunner(app.db, lent.runner.id)!.paused).toBe(""); | |
| 218 | judgeLentGreen(app, green, { ok: false, error: "1 test failed" }, (l) => lines.push(l)); | |
| 219 | expect(getRunner(app.db, lent.runner.id)!.paused).toContain("said green on bbbbbbb"); | |
| 220 | expect(lines.at(-1)).toContain("is paused"); | |
| 221 | offer(pub, "x1"); | |
| 222 | expect(claimJob(app.db, { id: lent.runner.id, cells: true }, T0)).toBeUndefined(); | |
| 223 | }); | |
| 224 | ||
| 225 | test("a fresh lent runner's first claim is a canary; a green on it pauses the runner (over HTTP)", async () => { | |
| 226 | clearDesk(); | |
| 227 | const { runner, token } = enrolRunner(app.db, "canary", alice.id, {}); | |
| 228 | const real = offer(pub, "c1"); | |
| 229 | const claim = await fetch(`${servers.url}/api/v1/runner/claim`, { | |
| 230 | method: "POST", | |
| 231 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 232 | body: JSON.stringify({ wait: 0, cells: true }), | |
| 233 | }); | |
| 234 | expect(claim.status).toBe(200); | |
| 235 | const got = (await claim.json()) as { job: RunnerJob; token: string }; | |
| 236 | expect(got.job.id).not.toBe(real.id); | |
| 237 | expect(got.job.commit).toBe(real.commit); | |
| 238 | expect(got.job.steps).toHaveLength(1); | |
| 239 | expect(got.job.steps[0]!.command).toMatch(/^test -e \.forge-check-[0-9a-f]{12}$/); | |
| 240 | expect("canary" in got).toBe(false); | |
| 241 | // The job it was made from is still queued for anyone. | |
| 242 | expect(app.db.query<{ state: string }, [string]>("SELECT state FROM check_job WHERE id = ?1").get(real.id)!.state).toBe("queued"); | |
| 243 | const report = await fetch(`${servers.url}/api/v1/runner/jobs/${got.job.id}`, { | |
| 244 | method: "POST", | |
| 245 | headers: { authorization: `Bearer ${got.token}`, "content-type": "application/json" }, | |
| 246 | body: JSON.stringify({ done: { steps: [{ name: "check", ok: true, ms: 5 }], contained: true, note: "" } }), | |
| 247 | }); | |
| 248 | expect(report.status).toBe(200); | |
| 249 | await report.body?.cancel(); | |
| 250 | expect(getRunner(app.db, runner.id)!.paused).toBe("said green on a canary, a job that must fail"); | |
| 251 | // Answered, the canary is gone from the desk. | |
| 252 | expect(app.db.query("SELECT 1 FROM check_job WHERE id = ?1").get(got.job.id)).toBeNull(); | |
| 253 | }); | |
| 254 | ||
| 255 | test("an honest red on a canary leaves the runner working, and the next claim is the real job", async () => { | |
| 256 | clearDesk(); | |
| 257 | const { runner, token } = enrolRunner(app.db, "honest", alice.id, {}); | |
| 258 | const real = offer(pub, "h1"); | |
| 259 | const claim = (): Promise<Response> => | |
| 260 | fetch(`${servers.url}/api/v1/runner/claim`, { | |
| 261 | method: "POST", | |
| 262 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 263 | body: JSON.stringify({ wait: 0, cells: true }), | |
| 264 | }); | |
| 265 | const got = (await (await claim()).json()) as { job: RunnerJob; token: string }; | |
| 266 | const report = await fetch(`${servers.url}/api/v1/runner/jobs/${got.job.id}`, { | |
| 267 | method: "POST", | |
| 268 | headers: { authorization: `Bearer ${got.token}`, "content-type": "application/json" }, | |
| 269 | body: JSON.stringify({ | |
| 270 | done: { steps: [{ name: "check", ok: false, error: "check exited with code 1", ms: 5 }], contained: true, note: "" }, | |
| 271 | }), | |
| 272 | }); | |
| 273 | await report.body?.cancel(); | |
| 274 | expect(getRunner(app.db, runner.id)!.paused).toBe(""); | |
| 275 | expect(getRunner(app.db, runner.id)!.coreMs).toBeGreaterThanOrEqual(0); | |
| 276 | noCanary(runner.id); | |
| 277 | const next = (await (await claim()).json()) as { job: RunnerJob }; | |
| 278 | expect(next.job.id).toBe(real.id); | |
| 279 | }); | |
| 280 | ||
| 281 | test("a canary is never offered to another runner", () => { | |
| 282 | clearDesk(); | |
| 283 | const lent = enrolRunner(app.db, "only", alice.id, {}); | |
| 284 | offer(pub, "o1"); | |
| 285 | const canary = claimJob(app.db, { id: lent.runner.id, cells: true }, T0)!; | |
| 286 | expect(canary.canary).toBe(true); | |
| 287 | // Its lease lapses: it is queued again, but only for its own runner. | |
| 288 | app.db.query("UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL WHERE id = ?1").run(canary.job.id); | |
| 289 | const owned = enrolRunner(app.db, "other", alice.id); | |
| 290 | const taken = claimJob(app.db, { id: owned.runner.id, cells: true }, T0)!; | |
| 291 | expect(taken.job.id).not.toBe(canary.job.id); | |
| 292 | expect(claimJob(app.db, { id: owned.runner.id, cells: true }, T0)).toBeUndefined(); | |
| 293 | }); | |
| 294 | }); | |
| 295 | ||
| 296 | describe("revocation", () => { | |
| 297 | const cookie = () => `forge_session=${createSession(app.db, alice.id).token}`; | |
| 298 | const claim = (token: string) => | |
| 299 | fetch(`${servers.url}/api/v1/runner/claim`, { | |
| 300 | method: "POST", | |
| 301 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 302 | body: JSON.stringify({ wait: 0, cells: true }), | |
| 303 | }); | |
| 304 | ||
| 305 | test("Settings → Runners revokes a lent runner: its next claim is refused, its held job queued again, its ledger kept", async () => { | |
| 306 | clearDesk(); | |
| 307 | const lent = seasoned("gone"); | |
| 308 | const job = offer(pub, "r1"); | |
| 309 | const held = claimJob(app.db, { id: lent.runner.id, cells: true }, Date.now())!; | |
| 310 | expect(held.job.id).toBe(job.id); | |
| 311 | app.db.query("UPDATE check_runner SET core_ms = 120000 WHERE id = ?1").run(lent.runner.id); | |
| 312 | const page = await (await fetch(`${servers.url}/settings/runners`, { headers: { cookie: cookie() } })).text(); | |
| 313 | expect(page).toContain(`/settings/runners/${lent.runner.id}/revoke`); | |
| 314 | expect(page).not.toContain(`/settings/runners/${lent.runner.id}/remove`); | |
| 315 | expect(page).toContain('id="lent-line"'); | |
| 316 | expect(page).not.toContain("Lent out"); | |
| 317 | // Its scope, today, total and expiry are rows under it, not one joined line. | |
| 318 | expect(page).toContain('<dl class="row-facts">'); | |
| 319 | expect(page).toContain("<dt>Today</dt><dd>0 of 240 core-min</dd>"); | |
| 320 | expect(page).toContain("<dt>Total</dt><dd>2 core-min</dd>"); | |
| 321 | const r = await fetch(`${servers.url}/settings/runners/${lent.runner.id}/revoke`, { | |
| 322 | method: "POST", | |
| 323 | redirect: "manual", | |
| 324 | headers: { cookie: cookie(), origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 325 | body: "", | |
| 326 | }); | |
| 327 | expect(r.status).toBe(303); | |
| 328 | expect((await claim(lent.token)).status).toBe(401); | |
| 329 | const after = getRunner(app.db, lent.runner.id)!; | |
| 330 | expect(after.revokedAt).toBeGreaterThan(0); | |
| 331 | expect(after.coreMs).toBe(120_000); | |
| 332 | expect(app.db.query<{ state: string }, [string]>("SELECT state FROM check_job WHERE id = ?1").get(job.id)!.state).toBe("queued"); | |
| 333 | // Revoked, its row offers Remove instead. | |
| 334 | const again = await (await fetch(`${servers.url}/settings/runners`, { headers: { cookie: cookie() } })).text(); | |
| 335 | expect(again).toContain(`/settings/runners/${lent.runner.id}/remove`); | |
| 336 | }); | |
| 337 | ||
| 338 | test("the API revokes and resumes; a second revoke and a resume of a working runner are refused", async () => { | |
| 339 | const { token: admin } = createToken(app.db, alice.id, "lend", "admin"); | |
| 340 | const call = (path: string) => | |
| 341 | fetch(`${servers.url}/api/v1/admin/runners/${path}`, { method: "POST", headers: { authorization: `Bearer ${admin}` } }); | |
| 342 | const made = await fetch(`${servers.url}/api/v1/admin/runners`, { | |
| 343 | method: "POST", | |
| 344 | headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" }, | |
| 345 | body: JSON.stringify({ name: "api", lend: { days: 3, coreMinPerDay: 60, authors: ["benjiver"] } }), | |
| 346 | }); | |
| 347 | expect(made.status).toBe(201); | |
| 348 | const row = (await made.json()) as { id: string; name: string; token: string; scope: { coreMinPerDay: number; authors: string[] } }; | |
| 349 | expect(row.name).toBe("lent-api"); | |
| 350 | expect(row.scope.coreMinPerDay).toBe(60); | |
| 351 | expect(row.scope.authors).toEqual(["benjiver"]); | |
| 352 | const notPaused = await call(`${row.id}/resume`); | |
| 353 | expect(notPaused.status).toBe(422); | |
| 354 | await notPaused.body?.cancel(); | |
| 355 | const ok = await call(`${row.id}/revoke`); | |
| 356 | expect(ok.status).toBe(200); | |
| 357 | await ok.body?.cancel(); | |
| 358 | const twice = await call(`${row.id}/revoke`); | |
| 359 | expect(twice.status).toBe(422); | |
| 360 | await twice.body?.cancel(); | |
| 361 | expect((await claim(row.token)).status).toBe(401); | |
| 362 | }); | |
| 363 | }); |
new above
offline
Principle 7: a fact is a
dlrow, not a run-on meta string. Scope, today's budget, total and expiry belong indlrows beneath the runner row. A row with 8 facts joined by middots is hard to read on a phone.