Public: anyone can read this; the crew can change it.
An outside runner (a Mac) registers, claims a repository's labelled checks, and reports them as the pull's real check #18073
Merged 10h 4m ago, live in production
scout/forge:scout/18037-an-outside-runner-a-mac-registers-claims → main 0 commits fork 2 threads · 2 unresolved
24 files
changed +820
−55
- docs/features/outside-runner.md
- src/actions/runners.ts
- src/apps/manifest.ts
- src/checks/lane_state.ts
- src/checks/runner_jobs.ts
- src/checks/runner_step.ts
- src/checks/tier_runner.ts
- src/contract/openapi/routes/getApiV1AdminRunners.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1AdminRunners.ts
- src/contract/openapi/routes/postApiV1AdminRunnersIdPause.ts
- src/contract/openapi/routes/postApiV1RunnerHeartbeat.ts
- src/core/migration-pins/20261204054000-runner-labels.pin
- src/core/migrations/20261204054000-runner-labels.ts
- src/http/api/runners.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/tui/screens/runners.ts
- src/web/pages/runners.ts
- test/openapi-errors.test.ts
- test/outside-runner.test.ts
- test/settings-runners.test.ts
- test/tui-runners.test.ts
docs/features/outside-runner.md added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Outside runner: a Mac that registers, claims a labelled check and reports it as the pull's check | |
| 4 | --- | |
| 5 | # An outside runner (#18037) | |
| 6 | ||
| 7 | A machine the forge cannot reach (a Mac behind a router) takes checks by asking. The forge never | |
| 8 | connects to it. It is the [](runners.md) with four additions: labels, repositories, | |
| 9 | a heartbeat and a pause. Nothing else is new: claim, log, report, give back and the job's git door | |
| 10 | are the ones every runner uses. | |
| 11 | ||
| 12 | ## What a repository says | |
| 13 | ||
| 14 | json | |
| 15 | { "check": { "run": "bun test", "label": "macos" } } | |
| 16 | ||
| 17 | ||
| 18 | `check.label` is one lower-case label. A check that names it goes only to a runner holding that | |
| 19 | label and **never runs on the forge's own machine**, whatever `FORGE_CHECKS_PLACEMENT` says. With | |
| 20 | no label, a repository behaves exactly as before. Only a pull's check and the default branch's push | |
| 21 | check are offered. A step the forge cannot offer to a runner (the full tier on landing, a bisection | |
| 22 | step) **fails in words** for a labelled check, naming the label; it is never run here, so a verdict | |
| 23 | that was not the labelled machine's never lands code through `require_checks`. | |
| 24 | ||
| 25 | ## The loop, as curl lines | |
| 26 | ||
| 27 | An admin registers it once; the token is shown this once (`labels` and at least one `repos`, as | |
| 28 | `owner/name`). It is the only credential the machine holds: | |
| 29 | ||
| 30 | sh | |
| 31 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' \ | |
| 32 | -d '{"name":"mac","labels":["macos","arm64","container"],"repos":["alice/lib"]}' /api/v1/admin/runners | |
| 33 | ||
| 34 | ||
| 35 | Each loop, with `RT` the runner token: | |
| 36 | ||
| 37 | sh | |
| 38 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' -d '{"state":"idle"}' /api/v1/runner/heartbeat | |
| 39 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' -d '{"wait":25,"cells":true}' /api/v1/runner/claim | |
| 40 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' -d '{"step":"check","lines":["ran 3 tests"]}' /api/v1/runner/jobs/ | |
| 41 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' -d '{"done":{"steps":[{"name":"check","ok":true,"ms":900}],"contained":true,"note":"container VM"}}' /api/v1/runner/jobs/ | |
| 42 | curl -X POST -H "Authorization: Bearer " -H 'content-type: application/json' -d '{"interrupted":"the Mac went on battery"}' /api/v1/runner/jobs/ | |
| 43 | ||
| 44 | ||
| 45 | - **Heartbeat** `{state: idle|busy|paused}` answers 204 and takes no labels: only the registration holds them. `paused` claims nothing until it | |
| 46 | says otherwise; silence for 60 seconds reads as away. | |
| 47 | - **Claim** answers 204 when nothing is queued for it, or `{job, token, lease}`: `job.id` is the run's | |
| 48 | job, `job.commit` the commit, `job.steps` the commands, `job.env`, `job.timeoutS`, `job.label`. | |
| 49 | `token` is the **fetch credential**: it fetches `job.commit` from | |
| 50 | `$FORGE_URL/api/v1/runner/jobs/$JOB/git` by `git-upload-pack` (put it in git's environment, as | |
| 51 | `http.extraHeader`, never argv), is read-only, serves that one repository's one commit, and | |
| 52 | lasts 30 seconds, renewed by every report; any report, even `{}`, renews. It is no credential | |
| 53 | anywhere else: no push, no account, no API. | |
| 54 | - **Log and result** are the one report route. `done` with a step per command (`ok`, `error`) is | |
| 55 | the pull's real check: it shows on the pull and the run page, and `require_checks` counts it. A | |
| 56 | red stays red as the runner said it; a label has no machine of the forge's to re-run it on. | |
| 57 | `contained` is what the runner says of its sandbox, shown as said, never proven by the forge. | |
| 58 | - **Give back** is `{"interrupted": why}`: queued again, not a try. A claim whose runner goes | |
| 59 | silent is queued again once; the second time the check fails with the reason in words. | |
| 60 | - **No holder**: while no runner that is here, not paused, holds the label for the repository, | |
| 61 | the check's log says so (`waiting: no runner holding the label "macos" …`), and after 15 minutes | |
| 62 | the check fails and says that. It never sits queued without a word. | |
| 63 | ||
| 64 | `POST /api/v1/admin/runners/{id}/pause` (`{reason?}`) and `/resume` stop and start a runner; `/revoke` | |
| 65 | ends its token. Settings → Runners (Register, Pause, Resume, Revoke) and the terminal's Runners screen (`n` registers, | |
| 66 | `p` pauses, `u` resumes, `x` revokes) register an outside runner with its labels and repositories, and list each with its labels, repositories and what its last heartbeat said. | |
| 67 | ||
| 68 | Code: `src/checks/runner_jobs.ts` (labels in the claim), `src/checks/runner_step.ts` (the wait), | |
| 69 | `src/http/api/runners.ts`, `src/tui/screens/runners.ts`. Test: `test/outside-runner.test.ts`. |
src/actions/runners.ts +41 −6
| @@ -12,6 +12,9 @@ import { | ||
| 12 | 12 | deskOf, |
| 13 | 13 | dropJob, |
| 14 | 14 | enrolRunner, |
| 15 | LABEL_RE, | |
| 16 | MAX_LABELS, | |
| 17 | MAX_REPOS, | |
| 15 | 18 | lentFacts, |
| 16 | 19 | listRunners, |
| 17 | 20 | pauseRunner, |
| @@ -25,24 +28,55 @@ import { | ||
| 25 | 28 | type RunnerResult, |
| 26 | 29 | } from "../checks/runner_jobs.ts"; |
| 27 | 30 | import { isLocal } from "../checks/runner_pool.ts"; |
| 31 | import { getRepo } from "../core/repos.ts"; | |
| 28 | 32 | import type { User } from "../core/users.ts"; |
| 29 | 33 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 30 | 34 | |
| 31 | 35 | const admin = (actor: User | undefined): actor is User => |
| 32 | 36 | actor !== undefined && actor.isAdmin && actor.kind === "user"; |
| 33 | 37 | |
| 38 | /** | |
| 39 | * An outside runner's enrolment (#18037): the labels it holds and the repositories (`owner/name`) | |
| 40 | * it serves. | |
| 41 | */ | |
| 42 | export interface OutsideInput { | |
| 43 | readonly labels: readonly string[]; | |
| 44 | readonly repos: readonly string[]; | |
| 45 | } | |
| 46 | ||
| 47 | /** | |
| 48 | * Enrol a runner. With `outside` it holds labels and serves only the repositories it names, each | |
| 49 | * of which must exist; `invalid` says what is wrong in words. | |
| 50 | */ | |
| 34 | 51 | export function enrol( |
| 35 | 52 | app: App, |
| 36 | 53 | actor: User | undefined, |
| 37 | 54 | name: string, |
| 38 | 55 | lend?: LendInput, |
| 39 | ): Result<{ runner: Enrolled; token: string }, "not_found"> { | |
| 56 | outside?: OutsideInput, | |
| 57 | ): Result<{ runner: Enrolled; token: string }, "not_found" | { invalid: string }> { | |
| 40 | 58 | if (!admin(actor)) return err("not_found"); |
| 41 | const made = enrolRunner(app.db, name, actor.id, lend); | |
| 59 | let held: { labels: string[]; repos: string[] } | undefined; | |
| 60 | if (outside !== undefined && (outside.labels.length > 0 || outside.repos.length > 0)) { | |
| 61 | if (lend !== undefined) return err({ invalid: "a lent runner takes no labels or repositories" }); | |
| 62 | if (outside.labels.length > MAX_LABELS || outside.labels.some((l) => !LABEL_RE.test(l))) | |
| 63 | return err({ invalid: `labels: at most ${MAX_LABELS}, each lower-case letters, digits, . _ - (up to 32)` }); | |
| 64 | if (outside.repos.length === 0 || outside.repos.length > MAX_REPOS) | |
| 65 | return err({ invalid: `repos: name 1 to ${MAX_REPOS} repositories as owner/name` }); | |
| 66 | const ids: string[] = []; | |
| 67 | for (const full of outside.repos) { | |
| 68 | const [owner, repoName, extra] = full.split("/"); | |
| 69 | const repo = owner === undefined || repoName === undefined || extra !== undefined ? undefined : getRepo(app.db, owner, repoName); | |
| 70 | if (repo === undefined) return err({ invalid: `repos: ${full.slice(0, 80)} is not a repository here` }); | |
| 71 | ids.push(repo.id); | |
| 72 | } | |
| 73 | held = { labels: [...new Set(outside.labels)], repos: [...new Set(ids)] }; | |
| 74 | } | |
| 75 | const made = enrolRunner(app.db, name, actor.id, lend, Date.now(), held); | |
| 42 | 76 | app.bus.append({ |
| 43 | 77 | kind: "runner.enrolled", |
| 44 | 78 | actorId: actor.id, |
| 45 | payload: { id: made.runner.id, name: made.runner.name, ...(made.runner.scope === undefined ? {} : { scope: made.runner.scope }) }, | |
| 79 | payload: { id: made.runner.id, name: made.runner.name, ...(held === undefined ? {} : { labels: held.labels, repos: held.repos }), ...(made.runner.scope === undefined ? {} : { scope: made.runner.scope }) }, | |
| 46 | 80 | }); |
| 47 | 81 | return ok(made); |
| 48 | 82 | } |
| @@ -74,15 +108,16 @@ export function resume(app: App, actor: User | undefined, runnerId: string): Res | ||
| 74 | 108 | } |
| 75 | 109 | |
| 76 | 110 | /** |
| 77 | * An admin holds a runner: it claims nothing until resumed. The forge's own `local-N` is refused. | |
| 111 | * An admin holds a runner: it claims nothing until resumed; a job it holds keeps its lease. The | |
| 112 | * forge's own `local-N` is refused. `reason` is optional; the default names who held it. | |
| 78 | 113 | */ |
| 79 | export function pause(app: App, actor: User | undefined, runnerId: string): Result<Enrolled, "not_found" | "local" | "revoked" | "paused"> { | |
| 114 | export function pause(app: App, actor: User | undefined, runnerId: string, reason = ""): Result<Enrolled, "not_found" | "local" | "revoked" | "paused"> { | |
| 80 | 115 | const runner = enrolled(app, actor, runnerId); |
| 81 | 116 | if (runner === undefined || !admin(actor)) return err("not_found"); |
| 82 | 117 | if (isLocal(runner)) return err("local"); |
| 83 | 118 | if (runner.revokedAt !== 0) return err("revoked"); |
| 84 | 119 | if (runner.paused !== "") return err("paused"); |
| 85 | const why = `paused by ${actor.username}`; | |
| 120 | const why = reason.trim().slice(0, 200) || `paused by ${actor.username}`; | |
| 86 | 121 | if (!pauseRunner(app.db, runnerId, why)) return err("not_found"); |
| 87 | 122 | app.bus.append({ kind: "runner.paused", actorId: actor.id, payload: { id: runnerId, name: runner.name, why } }); |
| 88 | 123 | return ok({ ...runner, paused: why }); |
src/apps/manifest.ts +11
| @@ -543,8 +543,15 @@ export interface CheckManifest { | ||
| 543 | 543 | readonly egress: readonly string[]; |
| 544 | 544 | /** `check.limits`: memory, CPU and disk, within the machine's maximum. */ |
| 545 | 545 | readonly limits: DeclaredLimits; |
| 546 | /** | |
| 547 | * `check.label` (#18037): the one label of an outside runner (`macos`) the check needs. Only a | |
| 548 | * runner holding it takes the check, and it never runs on the forge's own machine. Absent: as | |
| 549 | * ever. | |
| 550 | */ | |
| 551 | readonly label?: string | undefined; | |
| 546 | 552 | } |
| 547 | 553 | |
| 554 | const CHECK_LABEL = /^[a-z0-9][a-z0-9._-]{0,31}$/; | |
| 548 | 555 | const CHECK_TIMEOUT_DEFAULT = 20 * 60; |
| 549 | 556 | export const CHECK_TIMEOUT_MAX = 2 * 60 * 60; |
| 550 | 557 | |
| @@ -592,7 +599,11 @@ export function parseCheck( | ||
| 592 | 599 | if (!egress.ok) return egress; |
| 593 | 600 | const limits = limitsField(check, "check"); |
| 594 | 601 | if (!limits.ok) return limits; |
| 602 | const label = check["label"]; | |
| 603 | if (label !== undefined && (typeof label !== "string" || !CHECK_LABEL.test(label))) | |
| 604 | return invalid("forge.json: check.label must be a lower-case label such as macos (letters, digits, . _ -, at most 32)"); | |
| 595 | 605 | return ok({ |
| 606 | ...(label === undefined ? {} : { label }), | |
| 596 | 607 | run: run.value, |
| 597 | 608 | fast: fast.value || null, |
| 598 | 609 | full: full.value || run.value, |
src/checks/lane_state.ts +2
| @@ -69,6 +69,8 @@ export interface ChecksOptions { | ||
| 69 | 69 | readonly checkStep?: typeof runStep | undefined; |
| 70 | 70 | /** Test seam: what hands a check to a runner and waits on its answer (`runner_step.ts`). */ |
| 71 | 71 | readonly runnerStep?: typeof runRunnerStep | undefined; |
| 72 | /** How long a check naming a runner label waits for a holder of it. @default LABEL_WAIT_MS */ | |
| 73 | readonly labelWaitMs?: number | undefined; | |
| 72 | 74 | /** Test seam: what deepsec's review runs and installs with (`checks/deepsec_step.ts`). */ |
| 73 | 75 | readonly deepsec?: DeepsecDeps | undefined; |
| 74 | 76 | /** |
src/checks/runner_jobs.ts +100 −11
| @@ -92,6 +92,8 @@ export interface RunnerJob { | ||
| 92 | 92 | * verification names any, so its impact map, kept results and times reach the forge's stores. |
| 93 | 93 | */ |
| 94 | 94 | readonly hands?: readonly string[]; |
| 95 | /** The label `forge.json`'s check names: only a runner that holds it takes this job (#18037). */ | |
| 96 | readonly label?: string; | |
| 95 | 97 | } |
| 96 | 98 | |
| 97 | 99 | /** |
| @@ -148,6 +150,12 @@ export interface Enrolled { | ||
| 148 | 150 | readonly cpus: number; |
| 149 | 151 | readonly memoryMiB: number; |
| 150 | 152 | readonly hostCpus: number; |
| 153 | /** What an outside runner holds (`macos`, `arm64`): a job naming one goes only to a holder. */ | |
| 154 | readonly labels: readonly string[]; | |
| 155 | /** The repositories (ids) it serves; none listed is every one, as a runner always did. */ | |
| 156 | readonly repos: readonly string[]; | |
| 157 | /** What it last said in its heartbeat: `idle`, `busy` or `paused`; "" before one. */ | |
| 158 | readonly state: string; | |
| 151 | 159 | } |
| 152 | 160 | |
| 153 | 161 | type RunnerRow = { |
| @@ -165,8 +173,21 @@ type RunnerRow = { | ||
| 165 | 173 | cpus: number; |
| 166 | 174 | memory_mib: number; |
| 167 | 175 | host_cpus: number; |
| 176 | labels: string; | |
| 177 | repos: string; | |
| 178 | state: string; | |
| 179 | }; | |
| 180 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state"; | |
| 181 | ||
| 182 | /** A JSON array of strings as kept in a column; anything else is none. */ | |
| 183 | const stringList = (raw: string): string[] => { | |
| 184 | try { | |
| 185 | const v: unknown = JSON.parse(raw); | |
| 186 | return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; | |
| 187 | } catch { | |
| 188 | return []; | |
| 189 | } | |
| 168 | 190 | }; |
| 169 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus"; | |
| 170 | 191 | const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { |
| 171 | 192 | const scope = readScope(r.name, r.scope, r.created_at); |
| 172 | 193 | return { |
| @@ -183,9 +204,25 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { | ||
| 183 | 204 | cpus: r.cpus, |
| 184 | 205 | memoryMiB: r.memory_mib, |
| 185 | 206 | hostCpus: r.host_cpus, |
| 207 | labels: stringList(r.labels), | |
| 208 | repos: stringList(r.repos), | |
| 209 | state: r.state, | |
| 186 | 210 | }; |
| 187 | 211 | }; |
| 188 | 212 | |
| 213 | /** | |
| 214 | * What an outside runner holds and says, in words for the page and the terminal; "" for any other. | |
| 215 | */ | |
| 216 | export const outsideWords = (r: Pick<Enrolled, "labels" | "repos" | "state">): string => | |
| 217 | r.labels.length === 0 | |
| 218 | ? "" | |
| 219 | : `labels ${r.labels.join(", ")} · serves ${r.repos.length} repositor${r.repos.length === 1 ? "y" : "ies"}${r.state === "" ? "" : ` · said ${r.state}`}`; | |
| 220 | ||
| 221 | /** A label as `forge.json` and a runner write it: lower-case, at most 32 characters. */ | |
| 222 | export const LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/; | |
| 223 | export const MAX_LABELS = 8; | |
| 224 | export const MAX_REPOS = 50; | |
| 225 | ||
| 189 | 226 | /** A name as it is kept: printable, at most 40 characters, "runner" when nothing is left. */ |
| 190 | 227 | export const runnerName = (raw: string): string => |
| 191 | 228 | raw.replace(/[^\x21-\x7e]/g, "").slice(0, 40) || "runner"; |
| @@ -201,14 +238,24 @@ export function enrolRunner( | ||
| 201 | 238 | createdBy: string, |
| 202 | 239 | lend?: LendInput, |
| 203 | 240 | now: number = Date.now(), |
| 241 | outside?: { readonly labels: readonly string[]; readonly repos: readonly string[] }, | |
| 204 | 242 | ): { runner: Enrolled; token: string } { |
| 205 | 243 | const runnerId = id(); |
| 206 | 244 | const token = `${RUNNER_TOKEN_PREFIX}${secret()}`; |
| 207 | 245 | const kept = runnerName(lend === undefined ? name : lentName(runnerName(name))); |
| 208 | 246 | const scope = readScope(kept, null, "") === undefined ? null : JSON.stringify(scopeFrom(lend ?? {}, now)); |
| 209 | 247 | db.query( |
| 210 | "INSERT INTO check_runner (id, name, token_hash, created_by, scope, salt) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 211 | ).run(runnerId, kept, sha256(token), createdBy, scope, scope === null ? "" : secret()); | |
| 248 | "INSERT INTO check_runner (id, name, token_hash, created_by, scope, salt, labels, repos) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | |
| 249 | ).run( | |
| 250 | runnerId, | |
| 251 | kept, | |
| 252 | sha256(token), | |
| 253 | createdBy, | |
| 254 | scope, | |
| 255 | scope === null ? "" : secret(), | |
| 256 | JSON.stringify(outside?.labels ?? []), | |
| 257 | JSON.stringify(outside?.repos ?? []), | |
| 258 | ); | |
| 212 | 259 | return { runner: getRunner(db, runnerId)!, token }; |
| 213 | 260 | } |
| 214 | 261 | |
| @@ -276,6 +323,33 @@ export function pauseRunner(db: Database, runnerId: string, why: string): boolea | ||
| 276 | 323 | ); |
| 277 | 324 | } |
| 278 | 325 | |
| 326 | /** | |
| 327 | * A runner's heartbeat (#18037): it is here, and says its state. The instant it asked is noted by | |
| 328 | * its token's lookup. Labels are never taken from it: the admin's registration is their only | |
| 329 | * source. | |
| 330 | */ | |
| 331 | export function noteHeartbeat(db: Database, runnerId: string, said: { state: string }): void { | |
| 332 | db.query("UPDATE check_runner SET state = ?2 WHERE id = ?1").run(runnerId, said.state); | |
| 333 | } | |
| 334 | ||
| 335 | /** | |
| 336 | * Whether a runner that can take a job of this repository with this label is here now: asked | |
| 337 | * within `SEEN_FRESH_MS`, not revoked, not paused, holding the label and serving the repository. | |
| 338 | */ | |
| 339 | export function labelServed(db: Database, repoId: string, label: string, now: number): boolean { | |
| 340 | return ( | |
| 341 | db | |
| 342 | .query<{ n: number }, [number, string, string]>( | |
| 343 | `SELECT COUNT(*) AS n FROM check_runner | |
| 344 | WHERE seen_at > ?1 - ${SEEN_FRESH_MS} AND revoked_at = 0 AND paused = '' AND state != 'paused' | |
| 345 | AND EXISTS (SELECT 1 FROM json_each(labels) WHERE value = ?3) | |
| 346 | AND (repos = '[]' OR EXISTS (SELECT 1 FROM json_each(repos) WHERE value = ?2)) | |
| 347 | AND (scope IS NULL OR EXISTS (SELECT 1 FROM repo r WHERE r.id = ?2 AND r.visibility = 'public'))`, | |
| 348 | ) | |
| 349 | .get(now, repoId, label)!.n > 0 | |
| 350 | ); | |
| 351 | } | |
| 352 | ||
| 279 | 353 | /** Let a paused runner claim again. False when it was not paused. */ |
| 280 | 354 | export function resumeRunner(db: Database, runnerId: string): boolean { |
| 281 | 355 | return db.query("UPDATE check_runner SET paused = '' WHERE id = ?1 AND paused != ''").run(runnerId).changes > 0; |
| @@ -408,7 +482,7 @@ export function offerJob( | ||
| 408 | 482 | ): RunnerJob { |
| 409 | 483 | const job: RunnerJob = { ...input.job, id: id() }; |
| 410 | 484 | db.query( |
| 411 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 485 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author, label) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | |
| 412 | 486 | ).run( |
| 413 | 487 | job.id, |
| 414 | 488 | input.runId, |
| @@ -417,6 +491,7 @@ export function offerJob( | ||
| 417 | 491 | JSON.stringify(job), |
| 418 | 492 | job.cell === "required" ? 1 : 0, |
| 419 | 493 | (input.author ?? "").toLowerCase(), |
| 494 | job.label ?? "", | |
| 420 | 495 | ); |
| 421 | 496 | return job; |
| 422 | 497 | } |
| @@ -443,6 +518,9 @@ type ClaimRow = { | ||
| 443 | 518 | ran: number; |
| 444 | 519 | canary_at: number; |
| 445 | 520 | box_id: string; |
| 521 | labels: string; | |
| 522 | repos: string; | |
| 523 | state: string; | |
| 446 | 524 | }; |
| 447 | 525 | |
| 448 | 526 | /** |
| @@ -457,10 +535,12 @@ export function claimJob( | ||
| 457 | 535 | ): Claim | undefined { |
| 458 | 536 | const me = db |
| 459 | 537 | .query<ClaimRow, [string]>( |
| 460 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id FROM check_runner WHERE id = ?1", | |
| 538 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state FROM check_runner WHERE id = ?1", | |
| 461 | 539 | ) |
| 462 | 540 | .get(runner.id); |
| 463 | if (me === null || me.revoked_at !== 0 || me.paused !== "") return undefined; | |
| 541 | // A runner that said `paused` in its heartbeat (a Mac on battery) takes nothing until it says | |
| 542 | // otherwise. | |
| 543 | if (me === null || me.revoked_at !== 0 || me.paused !== "" || me.state === "paused") return undefined; | |
| 464 | 544 | const kept = readScope(me.name, me.scope, me.created_at); |
| 465 | 545 | // A game box's runner serves the box's repository's writers as they are now, not as they were |
| 466 | 546 | // when it was enrolled. |
| @@ -472,26 +552,35 @@ export function claimJob( | ||
| 472 | 552 | // own canaries; a runner this forge owns sees every job but a canary. |
| 473 | 553 | // A runner enrolled for a game box (`games/lend.ts`) is held to that box's spare memory now, |
| 474 | 554 | // which is 0 while a server wakes (`games/lend_fit.ts`); -1 for one that is not. |
| 555 | // A job naming a label goes only to a runner holding it, and a runner that lists repositories | |
| 556 | // serves only those (#18037); both are `[]` for a runner as it always was. | |
| 557 | const labels = me.labels; | |
| 558 | const repos = me.repos; | |
| 475 | 559 | const spareMiB = me.box_id === "" ? -1 : boxSpareMiB(db, me.box_id, now); |
| 476 | 560 | const queued = |
| 477 | 561 | scope === undefined |
| 478 | 562 | ? db |
| 479 | .query<{ id: string }, [number]>( | |
| 480 | "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", | |
| 563 | .query<{ id: string }, [number, string, string]>( | |
| 564 | `SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1) | |
| 565 | AND (label = '' OR label IN (SELECT value FROM json_each(?2))) | |
| 566 | AND (?3 = '[]' OR repo_id IN (SELECT value FROM json_each(?3))) | |
| 567 | ORDER BY id LIMIT 8`, | |
| 481 | 568 | ) |
| 482 | .all(runner.cells ? 1 : 0) | |
| 569 | .all(runner.cells ? 1 : 0, labels, repos) | |
| 483 | 570 | : db |
| 484 | .query<{ id: string }, [string, string, number, number]>( | |
| 571 | .query<{ id: string }, [string, string, number, number, string, string]>( | |
| 485 | 572 | `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id |
| 486 | 573 | WHERE j.state = 'queued' AND r.visibility = 'public' AND (j.canary_for IS NULL OR j.canary_for = ?1) |
| 487 | 574 | AND (?3 = 0 OR j.author IN (SELECT value FROM json_each(?2))) |
| 488 | 575 | -- A job that hands files back is this forge's own verification: never a lent runner's. |
| 489 | 576 | AND json_extract(j.spec, '$.hands') IS NULL |
| 577 | AND (j.label = '' OR j.label IN (SELECT value FROM json_each(?5))) | |
| 578 | AND (?6 = '[]' OR j.repo_id IN (SELECT value FROM json_each(?6))) | |
| 490 | 579 | -- A game box's runner (?4 >= 0, its spare memory now) takes only a job that declares memory and fits. |
| 491 | 580 | AND (?4 < 0 OR COALESCE(json_extract(j.spec, '$.limits.memoryMiB'), 0) BETWEEN 1 AND ?4) |
| 492 | 581 | ORDER BY j.id LIMIT 8`, |
| 493 | 582 | ) |
| 494 | .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB); | |
| 583 | .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB, labels, repos); | |
| 495 | 584 | if (scope !== undefined && queued.length > 0 && canaryDue(saltOf(me), me.canary_at, me.ran)) { |
| 496 | 585 | const canary = offerCanary(db, runner.id, queued[0]!.id, now, leaseMs); |
| 497 | 586 | if (canary !== undefined) return canary; |
src/checks/runner_step.ts +50 −8
| @@ -24,6 +24,7 @@ import { | ||
| 24 | 24 | deskOf, |
| 25 | 25 | dropJob, |
| 26 | 26 | handOverJob, |
| 27 | labelServed, | |
| 27 | 28 | jobSpec, |
| 28 | 29 | lapseJobs, |
| 29 | 30 | offerJob, |
| @@ -42,6 +43,8 @@ import { summariseCheckFailure } from "./summary.ts"; | ||
| 42 | 43 | export const RUNNER_WAIT_MS = 5_000; |
| 43 | 44 | /** A job whose runner went silent this many times is not offered again. */ |
| 44 | 45 | export const MAX_CLAIMS = 2; |
| 46 | /** How long a check naming a label waits for a runner holding it before it fails, in words. */ | |
| 47 | export const LABEL_WAIT_MS = 15 * 60_000; | |
| 45 | 48 | /** How often a waiting check looks at its job when nothing woke it. */ |
| 46 | 49 | const LOOK_MS = 1_000; |
| 47 | 50 | |
| @@ -77,7 +80,11 @@ export type RunnerStepEnd = | ||
| 77 | 80 | readonly start?: "warm" | "cold"; |
| 78 | 81 | readonly setupMs?: number; |
| 79 | 82 | } |
| 80 | | { readonly taken: false; readonly why: string }; | |
| 83 | /** | |
| 84 | * `final`: the check names a label, so the forge's own machine cannot stand in: `why` is its | |
| 85 | * failure (#18037), not a reason to run here. | |
| 86 | */ | |
| 87 | | { readonly taken: false; readonly why: string; readonly final?: true }; | |
| 81 | 88 | |
| 82 | 89 | export interface RunnerStepInput { |
| 83 | 90 | readonly runId: string; |
| @@ -93,6 +100,8 @@ export interface RunnerStepInput { | ||
| 93 | 100 | readonly author?: string | undefined; |
| 94 | 101 | /** @default RUNNER_WAIT_MS */ |
| 95 | 102 | readonly waitMs?: number | undefined; |
| 103 | /** How long a check naming a label waits for a runner holding it. @default LABEL_WAIT_MS */ | |
| 104 | readonly labelWaitMs?: number | undefined; | |
| 96 | 105 | /** Tests stand a clock in. @default Date.now */ |
| 97 | 106 | readonly now?: (() => number) | undefined; |
| 98 | 107 | /** |
| @@ -150,8 +159,13 @@ export async function runRunnerStep( | ||
| 150 | 159 | const adopted = desk.adopt.get(input.runId); |
| 151 | 160 | if (adopted !== undefined) desk.adopt.delete(input.runId); |
| 152 | 161 | const sent = adopted === undefined ? undefined : jobSpec(app.db, adopted); |
| 162 | // A check naming a label (#18037) cannot run on this machine: it waits for a runner that holds | |
| 163 | // it, says so, and fails in words instead of running here. | |
| 164 | const label = sent?.label ?? input.job.label ?? ""; | |
| 165 | const labelWaitMs = input.labelWaitMs ?? LABEL_WAIT_MS; | |
| 166 | const fail = (why: string): RunnerStepEnd => (label === "" ? { taken: false, why } : { taken: false, why, final: true }); | |
| 153 | 167 | // Nobody to offer it to: not a second is spent waiting. |
| 154 | if (sent === undefined && desk.claimers.size === 0 && !runnersAround(app.db, now())) | |
| 168 | if (label === "" && sent === undefined && desk.claimers.size === 0 && !runnersAround(app.db, now())) | |
| 155 | 169 | return { taken: false, why: "no runner is connected" }; |
| 156 | 170 | const job = |
| 157 | 171 | sent ?? |
| @@ -194,6 +208,8 @@ export async function runRunnerStep( | ||
| 194 | 208 | }); |
| 195 | 209 | let offeredAt = now(); |
| 196 | 210 | let holder = ""; |
| 211 | let waitingSaid = false; | |
| 212 | let seenClaims = 0; | |
| 197 | 213 | try { |
| 198 | 214 | wakeClaimers(app); |
| 199 | 215 | for (;;) { |
| @@ -215,7 +231,7 @@ export async function runRunnerStep( | ||
| 215 | 231 | for (const lapsed of lapseJobs(app.db, now())) desk.held.delete(lapsed); |
| 216 | 232 | const view = viewJob(app.db, job.id); |
| 217 | 233 | if (view === undefined) |
| 218 | return { taken: false, why: "the job left the desk" }; | |
| 234 | return fail("the job left the desk"); | |
| 219 | 235 | if (view.state === "queued" && holder !== "") { |
| 220 | 236 | input.log( |
| 221 | 237 | view.result?.startsWith("interrupted: ") === true |
| @@ -237,7 +253,7 @@ export async function runRunnerStep( | ||
| 237 | 253 | const result = parseResult(view.result); |
| 238 | 254 | const read = result === undefined ? undefined : readSteps(steps, result.steps); |
| 239 | 255 | if (result === undefined || read === undefined) |
| 240 | return { taken: false, why: `runner ${holder} sent a result that does not match the job's steps` }; | |
| 256 | return fail(`runner ${holder} sent a result that does not match the job's steps`); | |
| 241 | 257 | return { |
| 242 | 258 | taken: true, |
| 243 | 259 | ...read, |
| @@ -253,10 +269,36 @@ export async function runRunnerStep( | ||
| 253 | 269 | }; |
| 254 | 270 | } |
| 255 | 271 | if (view.state === "returned") |
| 256 | return { | |
| 257 | taken: false, | |
| 258 | why: `runner ${holder} handed it back: ${view.result ?? ""}`, | |
| 259 | }; | |
| 272 | return fail(`runner ${holder} handed it back: ${view.result ?? ""}`); | |
| 273 | // Time a runner held the job is not time spent waiting for one. | |
| 274 | if (view.claims !== seenClaims) { | |
| 275 | seenClaims = view.claims; | |
| 276 | offeredAt = now(); | |
| 277 | } | |
| 278 | if (label !== "" && view.state === "queued") { | |
| 279 | // Said on the check's log, and so on its pull, while no runner that could take it is here. | |
| 280 | const served = labelServed(app.db, input.repoId, label, now()); | |
| 281 | if (!served && !waitingSaid) { | |
| 282 | waitingSaid = true; | |
| 283 | input.log(`waiting: no runner holding the label "${label}" is available for this repository; it waits up to ${Math.round(labelWaitMs / 60_000)} minutes`); | |
| 284 | } | |
| 285 | if (served && waitingSaid) { | |
| 286 | waitingSaid = false; | |
| 287 | input.log(`a runner holding the label "${label}" is available`); | |
| 288 | } | |
| 289 | const why = | |
| 290 | view.claims >= MAX_CLAIMS | |
| 291 | ? `runners holding the label "${label}" went silent ${view.claims} times while running it: the check failed, and was not run on this machine` | |
| 292 | : now() - offeredAt >= labelWaitMs | |
| 293 | ? `no runner holding the label "${label}" took it in ${Math.round(labelWaitMs / 60_000)} minutes: the check failed, and was not run on this machine` | |
| 294 | : ""; | |
| 295 | if (why !== "") { | |
| 296 | if (withdrawJob(app.db, job.id)) return fail(why); | |
| 297 | continue; | |
| 298 | } | |
| 299 | await rest(LOOK_MS); | |
| 300 | continue; | |
| 301 | } | |
| 260 | 302 | if ( |
| 261 | 303 | view.state === "queued" && |
| 262 | 304 | (view.claims >= MAX_CLAIMS || now() - offeredAt >= waitMs) |
src/checks/tier_runner.ts +28 −6
| @@ -80,7 +80,17 @@ export async function tryRunner( | ||
| 80 | 80 | // A runner that joined takes the steps (`runner_step.ts`, #13652): only a check that hands |
| 81 | 81 | // back nothing but its log and its verdict, and only while a runner is connected. Not taken, |
| 82 | 82 | // or an answer that is not the check's own verdict, and it runs here as it always has. |
| 83 | if (lane.placement.mode === "runner" && x.runId !== undefined && runnerTakes(x)) { | |
| 83 | // A check naming a label (#18037) goes to a runner holding it whatever the placement, and is | |
| 84 | // never run here. | |
| 85 | const label = manifest.label ?? ""; | |
| 86 | if (label !== "" && !(x.runId !== undefined && runnerTakes(x))) { | |
| 87 | // Offered to no runner, and never run here: the label is the owner's word that this machine | |
| 88 | // cannot be the one that says whether the code is good. | |
| 89 | const error = `this check names the label "${label}" and cannot be offered to a runner here (${x.tier === "verify" || x.tier === "full" ? `the ${x.tier} tier runs on this machine only` : "a re-run of part of a check"}), so it was not run`; | |
| 90 | write(error); | |
| 91 | return { ok: false, error }; | |
| 92 | } | |
| 93 | if ((lane.placement.mode === "runner" || label !== "") && x.runId !== undefined && runnerTakes(x)) { | |
| 84 | 94 | // The base's gate runs first there as here (#15291): the job carries the base commit and the |
| 85 | 95 | // gate's blob id, and the check step writes the file from them (`withBaseGateFrom`). |
| 86 | 96 | const baseGate = base === undefined ? undefined : await readFileAt(bare, base, "scripts/gate.ts", 1 << 20); |
| @@ -88,7 +98,7 @@ export async function tryRunner( | ||
| 88 | 98 | const step = withBaseGateFrom(command, baseGate, base, blob?.ok ? blob.value.trim() : undefined); |
| 89 | 99 | if (runsAsBaseGate(baseGate) && step === command) { |
| 90 | 100 | write("placement: runner; the base's gate could not be named for it; running here"); |
| 91 | return undefined; | |
| 101 | return label === "" ? undefined : { ok: false, error: `the base's gate could not be named for the runner holding "${label}", and this check cannot run here` }; | |
| 92 | 102 | } |
| 93 | 103 | if (step !== command) write(`gate list: read from ${base!.slice(0, 7)}'s scripts/gate.ts, on the runner`); |
| 94 | 104 | // Install scripts run only once the repository's review has passed (#3970), on a runner too: |
| @@ -97,7 +107,7 @@ export async function tryRunner( | ||
| 97 | 107 | const install = installCommand(manifest.install, isQuarantined(app.db, repo.id)); |
| 98 | 108 | if (install === undefined) { |
| 99 | 109 | write("placement: runner; the install command cannot be run without its scripts; running here"); |
| 100 | return undefined; | |
| 110 | return label === "" ? undefined : { ok: false, error: `the install command cannot be run without its scripts, and a check naming "${label}" cannot run here` }; | |
| 101 | 111 | } |
| 102 | 112 | const lines: string[] = []; |
| 103 | 113 | // The shard count an admin set reaches a runner's check as it does one run here (#14844); the |
| @@ -159,11 +169,13 @@ export async function tryRunner( | ||
| 159 | 169 | ...(seeds.length === 0 ? {} : { seeds }), |
| 160 | 170 | // Main's whole verification hands back what it measured (`runner_hands.ts`). |
| 161 | 171 | ...(handsTimesBack(x) ? { hands: HAND_FILES } : {}), |
| 172 | ...(label === "" ? {} : { label }), | |
| 162 | 173 | }, |
| 163 | 174 | log: write, |
| 164 | 175 | output: lines, |
| 165 | 176 | signal, |
| 166 | waitMs: lane.placement.waitMs, | |
| 177 | waitMs: lane.placement.mode === "runner" ? lane.placement.waitMs : undefined, | |
| 178 | ...(lane.options.labelWaitMs === undefined ? {} : { labelWaitMs: lane.options.labelWaitMs }), | |
| 167 | 179 | // A release stopping this forge leaves the job with its runner (`adoptRunnerJobs`). |
| 168 | 180 | handingOver: () => lane.stopped, |
| 169 | 181 | }); |
| @@ -177,7 +189,7 @@ export async function tryRunner( | ||
| 177 | 189 | if (sent !== undefined && sent.taken && !signal.aborted && handsTimesBack(x)) keepHands(app.config.dataDir, repo.id, run.id, write); |
| 178 | 190 | if (sent === undefined || sent.taken || sent.why !== HANDED_OVER) dropHands(app.config.dataDir, run.id); |
| 179 | 191 | const verify = x.tier === "verify"; |
| 180 | if (sent === undefined) return undefined; | |
| 192 | if (sent === undefined) return label === "" ? undefined : { ok: false, error: `no runner holding "${label}" gave a verdict, and a check naming it is not run on this machine` }; | |
| 181 | 193 | // Handed over: no verdict here, and not run here either; the forge that comes up waits on it. |
| 182 | 194 | if (!sent.taken && sent.why === HANDED_OVER) { |
| 183 | 195 | write(HANDED_OVER); |
| @@ -185,7 +197,17 @@ export async function tryRunner( | ||
| 185 | 197 | } |
| 186 | 198 | // A verification's red is its own verdict, named by file for the bisection: never one or two |
| 187 | 199 | // tests re-run here alone. |
| 188 | const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted, !verify) : sent.why; | |
| 200 | // A check naming a label has no machine of the forge's to fall back on: the runner's answer | |
| 201 | // stands as it said it, and one it could not give fails the check with its reason. | |
| 202 | if (label !== "" && !sent.taken && sent.final === true) { | |
| 203 | write(sent.why); | |
| 204 | return { ok: false, error: sent.why }; | |
| 205 | } | |
| 206 | const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted, !verify && label === "") : sent.why; | |
| 207 | if (typeof verdict === "string" && label !== "") { | |
| 208 | write(`placement: runner ${sent.taken ? sent.runner : ""}; ${verdict}`); | |
| 209 | return { ok: false, error: verdict }; | |
| 210 | } | |
| 189 | 211 | if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`); |
| 190 | 212 | else if ("alone" in verdict) { |
| 191 | 213 | write(`placement: runner; one or two tests failed on runner ${verdict.runner}: only they are re-run here, alone, never the whole check`); |
src/contract/openapi/routes/getApiV1AdminRunners.ts +1 −1
| @@ -6,7 +6,7 @@ export const route: Route = { | ||
| 6 | 6 | summary: |
| 7 | 7 | "The enrolled runners, each with when it last asked for work", |
| 8 | 8 | detail: |
| 9 | "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never); answers { items, next_cursor }", | |
| 9 | "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never); state (idle, busy or paused: what its heartbeat last said), labels and repos (ids; none listed is every repository); answers { items, next_cursor }", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | 12 | refuses: [404], |
src/contract/openapi/routes/index.ts +1
| @@ -499,6 +499,7 @@ export { route as postApiV1ReposOwnerNameSync } from "./postApiV1ReposOwnerNameS | ||
| 499 | 499 | export { route as postApiV1ReposOwnerNameTransfer } from "./postApiV1ReposOwnerNameTransfer.ts"; |
| 500 | 500 | export { route as postApiV1ReposOwnerNameUpstreamCheck } from "./postApiV1ReposOwnerNameUpstreamCheck.ts"; |
| 501 | 501 | export { route as postApiV1RunnerClaim } from "./postApiV1RunnerClaim.ts"; |
| 502 | export { route as postApiV1RunnerHeartbeat } from "./postApiV1RunnerHeartbeat.ts"; | |
| 502 | 503 | export { route as postApiV1RunnerJobsId } from "./postApiV1RunnerJobsId.ts"; |
| 503 | 504 | export { route as postApiV1RunnerJobsIdGitGitUploadPack } from "./postApiV1RunnerJobsIdGitGitUploadPack.ts"; |
| 504 | 505 | export { route as postApiV1RunnerJobsIdHand } from "./postApiV1RunnerJobsIdHand.ts"; |
src/contract/openapi/routes/postApiV1AdminRunners.ts +4 −2
| @@ -6,11 +6,13 @@ 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. 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)", | |
| 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). With labels (e.g. [\"macos\",\"arm64\"]) and repos (owner/name, at least one) it is an outside runner: it takes only a check whose forge.json check.label it holds, and only for those repositories (docs/features/outside-runner.md); 422 invalid_runner says what is wrong", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | body: { name: "string", lend: "object" }, | |
| 12 | body: { name: "string", lend: "object", labels: "array", repos: "array" }, | |
| 13 | 13 | status: 201, |
| 14 | 14 | reply: { id: "string", name: "string", createdAt: "string", seenAt: "integer", token: "string" }, |
| 15 | 15 | refuses: [404], |
| 16 | errorStatus: { 422: "labels or repos are not well-formed, or name a repository that is not here (invalid_runner)" }, | |
| 17 | refusals: { invalid_runner: "what is wrong with the labels or repos" }, | |
| 16 | 18 | }; |
src/contract/openapi/routes/postApiV1AdminRunnersIdPause.ts +2 −1
| @@ -5,9 +5,10 @@ export const route: Route = { | ||
| 5 | 5 | path: "/api/v1/admin/runners/{id}/pause", |
| 6 | 6 | summary: "Pause a runner: it claims no more work until resumed", |
| 7 | 7 | detail: |
| 8 | "Hold a runner (admin scope): its claim is refused and a job it holds finishes; POST …/resume lets it claim again. The paused text names who held it. 422 local for the forge's own local-N runner, revoked for a revoked one, paused when it is paused already; 404 when there is none", | |
| 8 | "Hold a runner (admin scope; takes an optional reason): its claim is refused and a job it holds finishes; POST …/resume lets it claim again. The paused text names who held it. 422 local for the forge's own local-N runner, revoked for a revoked one, paused when it is paused already; 404 when there is none", | |
| 9 | 9 | auth: true, |
| 10 | 10 | role: "admin", |
| 11 | body: { reason: "string" }, | |
| 11 | 12 | status: 200, |
| 12 | 13 | reply: { id: "string", name: "string", paused: "string" }, |
| 13 | 14 | refuses: [404], |
src/contract/openapi/routes/postApiV1RunnerHeartbeat.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/runner/heartbeat", | |
| 6 | summary: "A runner says it is here, its state. Takes a runner token as the bearer", | |
| 7 | detail: | |
| 8 | "A runner says it is available (runner token as the bearer, never an account's): state is idle, busy or paused (paused: it takes no job until it says otherwise, as a Mac on battery); labels are never taken from a runner: the admin's registration holds them. A runner silent for 60 seconds reads as away, and a check naming a label no available runner holds says so on its pull. Answers 204", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | body: { state: "string" }, | |
| 12 | alsoStatus: [204], | |
| 13 | refusals: { unauthorized: "401: not a runner token this forge enrolled", invalid_heartbeat: "422: state is idle, busy or paused" }, | |
| 14 | errorStatus: { 401: "`unauthorized`: not a runner token this forge enrolled", 422: "`invalid_heartbeat`: the state is not what is asked" }, | |
| 15 | }; |
src/core/migration-pins/20261204054000-runner-labels.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 3f73178f741a60cb770c151fed9479850a03a106575960c59d5742b8b25b1c66 |
src/core/migrations/20261204054000-runner-labels.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | // An outside runner (#18037): labels it holds and the repositories it serves, both JSON arrays on | |
| 2 | // `check_runner` ('[]' is today's runner: no labels, every repository), and the state it last said | |
| 3 | // in its heartbeat. On `check_job`, the label its repository's `forge.json` check names ('' for | |
| 4 | // none: a job any runner may take, as before). Additive. | |
| 5 | export default ` | |
| 6 | ALTER TABLE check_runner ADD COLUMN labels TEXT NOT NULL DEFAULT '[]'; | |
| 7 | ALTER TABLE check_runner ADD COLUMN repos TEXT NOT NULL DEFAULT '[]'; | |
| 8 | ALTER TABLE check_runner ADD COLUMN state TEXT NOT NULL DEFAULT ''; | |
| 9 | ALTER TABLE check_job ADD COLUMN label TEXT NOT NULL DEFAULT ''; | |
| 10 | `; |
src/http/api/runners.ts +26 −4
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | jobByToken, |
| 27 | 27 | nextOffer, |
| 28 | 28 | interruptJob, |
| 29 | noteHeartbeat, | |
| 29 | 30 | noteHeldReport, |
| 30 | 31 | noteRunnerJobs, |
| 31 | 32 | noteRunnerMachine, |
| @@ -126,8 +127,13 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 126 | 127 | const denied = accountAdmin(ctx, "admin"); |
| 127 | 128 | if (denied) return denied; |
| 128 | 129 | const input = await body(ctx.request); |
| 129 | const made = enrol(ctx.app, ctx.auth.user, str(input.name), readLend(input.lend)); | |
| 130 | if (!made.ok) return notFound(); | |
| 130 | const strings = (v: unknown): string[] | undefined => | |
| 131 | v === undefined ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; | |
| 132 | const labels = strings(input.labels); | |
| 133 | const repos = strings(input.repos); | |
| 134 | if (labels === undefined || repos === undefined) return apiError("invalid_runner", 422, "labels and repos are arrays of strings"); | |
| 135 | const made = enrol(ctx.app, ctx.auth.user, str(input.name), readLend(input.lend), { labels, repos }); | |
| 136 | if (!made.ok) return made.error === "not_found" ? notFound() : apiError("invalid_runner", 422, made.error.invalid); | |
| 131 | 137 | return json({ ...made.value.runner, token: made.value.token }, 201); |
| 132 | 138 | }); |
| 133 | 139 | |
| @@ -143,10 +149,11 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 143 | 149 | }); |
| 144 | 150 | |
| 145 | 151 | // Beside resume: an admin holds a runner; its running job finishes, it claims no more. |
| 146 | router.add("POST", "/api/v1/admin/runners/:id/pause", (ctx) => { | |
| 152 | router.add("POST", "/api/v1/admin/runners/:id/pause", async (ctx) => { | |
| 147 | 153 | const denied = accountAdmin(ctx, "admin"); |
| 148 | 154 | if (denied) return denied; |
| 149 | const done = pause(ctx.app, ctx.auth.user, ctx.params.id!); | |
| 155 | const input = await body(ctx.request); | |
| 156 | const done = pause(ctx.app, ctx.auth.user, ctx.params.id!, str(input.reason)); | |
| 150 | 157 | if (done.ok) return json({ id: done.value.id, name: done.value.name, paused: done.value.paused }); |
| 151 | 158 | if (done.error === "local") return apiError("local", 422, "a local-N runner is the forge's own; it cannot be paused"); |
| 152 | 159 | if (done.error === "revoked") return apiError("revoked", 422, "that runner is revoked"); |
| @@ -224,6 +231,21 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 224 | 231 | return gone.ok ? new Response(null, { status: 204 }) : notFound(); |
| 225 | 232 | }); |
| 226 | 233 | |
| 234 | // A runner says it is here, in what state, and which labels it holds (#18037). Silence past | |
| 235 | // `SEEN_FRESH_MS` reads as away. Its claim and its reports say the same without the state. | |
| 236 | router.add("POST", "/api/v1/runner/heartbeat", async (ctx) => { | |
| 237 | const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now()); | |
| 238 | if (runner === undefined) return unauthorized(); | |
| 239 | const input = await boundedBody(ctx.request, STRANGER_MAX); | |
| 240 | if (input === "too_large") return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); | |
| 241 | const state = str(input.state); | |
| 242 | if (state !== "idle" && state !== "busy" && state !== "paused") | |
| 243 | return apiError("invalid_heartbeat", 422, "state is idle, busy or paused"); | |
HIGH: |
||
| 244 | noteHeartbeat(ctx.app.db, runner.id, { state }); | |
| 245 | wakeClaimers(ctx.app); | |
| 246 | return new Response(null, { status: 204 }); | |
| 247 | }); | |
| 248 | ||
| 227 | 249 | // A runner asks for work. Held open until a job is offered or `wait` seconds pass (204). |
| 228 | 250 | router.add("POST", "/api/v1/runner/claim", async (ctx) => { |
| 229 | 251 | const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now()); |
src/http/lazy_lists.ts +3
| @@ -30,6 +30,8 @@ export const SETTINGS_ROUTES = [ | ||
| 30 | 30 | ["POST", "/settings/runners/:id/remove"], |
| 31 | 31 | ["POST", "/settings/runners/:id/revoke"], |
| 32 | 32 | ["POST", "/settings/runners/:id/resume"], |
| 33 | ["POST", "/settings/runners/:id/pause"], | |
| 34 | ["POST", "/settings/runners/register"], | |
| 33 | 35 | ["GET", "/settings/runners/lending/live"], |
| 34 | 36 | ["POST", "/settings/runners/lending"], |
| 35 | 37 | ["POST", "/settings/runners/lending/:id/stop"], |
| @@ -1302,6 +1304,7 @@ export const API_ROUTES = [ | ||
| 1302 | 1304 | ["POST", "/api/v1/admin/lending/:id/resume"], |
| 1303 | 1305 | ["GET", "/api/v1/admin/runners"], |
| 1304 | 1306 | ["DELETE", "/api/v1/admin/runners/:id"], |
| 1307 | ["POST", "/api/v1/runner/heartbeat"], | |
| 1305 | 1308 | ["POST", "/api/v1/runner/claim"], |
| 1306 | 1309 | ["POST", "/api/v1/runner/jobs/:id"], |
| 1307 | 1310 | ["GET", "/api/v1/runner/jobs/:id/seed"], |
src/http/marks/settings.json +2
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | "/settings/runners/:id/remove": "open", |
| 11 | 11 | "/settings/runners/:id/revoke": "open", |
| 12 | 12 | "/settings/runners/:id/resume": "open", |
| 13 | "/settings/runners/:id/pause": "open", | |
| 14 | "/settings/runners/register": "open", | |
| 13 | 15 | "/settings/runners/lending/live": "open", |
| 14 | 16 | "/settings/runners/lending": "open", |
| 15 | 17 | "/settings/runners/lending/:id/stop": "open", |
src/http/settings_routes.ts +3 −1
| @@ -24,7 +24,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 24 | 24 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 25 | 25 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 26 | 26 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 27 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts"; | |
| 27 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts"; | |
| 28 | 28 | import { usagePage } from "../web/pages/usage.ts"; |
| 29 | 29 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| 30 | 30 | import { securityControlsPage } from "../web/pages/security_controls.ts"; |
| @@ -174,6 +174,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 174 | 174 | router.add("POST", "/settings/runners/:id/remove", runnerRemove); |
| 175 | 175 | router.add("POST", "/settings/runners/:id/revoke", runnerRevoke); |
| 176 | 176 | router.add("POST", "/settings/runners/:id/resume", runnerResume); |
| 177 | router.add("POST", "/settings/runners/:id/pause", runnerPause); | |
| 178 | router.add("POST", "/settings/runners/register", runnerRegister); | |
| 177 | 179 | router.add("GET", "/settings/runners/lending/live", lendingLive); |
| 178 | 180 | router.add("POST", "/settings/runners/lending", lendingOffer); |
| 179 | 181 | router.add("POST", "/settings/runners/lending/:id/stop", lendingStop); |
src/tui/screens/runners.ts +43 −7
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | * offered it. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 9 | import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 10 | 10 | import { isLocal } from "../../checks/runner_pool.ts"; |
| 11 | 11 | import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts"; |
| 12 | 12 | import { proofByRunner, proofWords } from "../../games/lent_proof.ts"; |
| @@ -14,7 +14,7 @@ import { cannotByRunner } from "../../games/lend_why.ts"; | ||
| 14 | 14 | import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts"; |
| 15 | 15 | import { lentLine, scopeLine } from "../../checks/lent_scope.ts"; |
| 16 | 16 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 17 | import { heldByRunner, lentIn, workByRunner, type Enrolled, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 17 | import { heldByRunner, lentIn, workByRunner, type Enrolled, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 18 | 18 | import type { Ctx, Screen } from "../app/app.ts"; |
| 19 | 19 | import { binding } from "../app/keys.ts"; |
| 20 | 20 | import { style } from "../term/style.ts"; |
| @@ -35,7 +35,7 @@ function lendingLine(f: Session): string { | ||
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | /** A lent runner that still works: `x` revokes it rather than removing its ledger. */ |
| 38 | const revocable = (r: Enrolled): boolean => r.scope !== undefined && r.revokedAt === 0; | |
| 38 | const revocable = (r: Enrolled): boolean => (r.scope !== undefined || r.labels.length > 0) && r.revokedAt === 0; | |
| 39 | 39 | |
| 40 | 40 | const stateWords = (r: Enrolled, now: number): string => |
| 41 | 41 | r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now)]; |
| @@ -78,7 +78,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 78 | 78 | const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`; |
| 79 | 79 | return { |
| 80 | 80 | title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`, |
| 81 | meta: `${asked}${machine === "" ? "" : ` · ${machine}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`, | |
| 81 | meta: `${asked}${machine === "" ? "" : ` · ${machine}`}${outsideWords(r) === "" ? "" : ` · ${outsideWords(r)}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`, | |
| 82 | 82 | // Under the row, where a narrow screen never gives it up as it does the meta's pieces. |
| 83 | 83 | ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}), |
| 84 | 84 | }; |
| @@ -118,6 +118,37 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 118 | 118 | ); |
| 119 | 119 | }; |
| 120 | 120 | |
| 121 | /** Register an outside runner: name, labels and repositories; its token is shown once. */ | |
| 122 | const register = (): void => { | |
| 123 | ctx.push( | |
| 124 | promptScreen(ctx, screen, { | |
| 125 | title: "Register an outside runner", | |
| 126 | label: "Name, labels (comma-separated), repositories (owner/name, comma-separated)", | |
| 127 | placeholder: "mac macos,arm64 alice/lib", | |
| 128 | hint: "The labels you give here are the only ones it can ever hold.", | |
| 129 | onSubmit: (value) => { | |
| 130 | const [name, labels, repos] = value.trim().split(/\s+/); | |
| 131 | if (name === undefined || name === "" || labels === undefined || repos === undefined) return "Three words: a name, its labels and its repositories"; | |
| 132 | const split = (w: string): string[] => w.split(",").filter((x) => x !== ""); | |
| 133 | const made = enrol(f.app, f.user, name, undefined, { labels: split(labels), repos: split(repos) }); | |
| 134 | if (!made.ok) return made.error === "not_found" ? "Only a forge admin registers runners." : `Not registered: ${made.error.invalid}.`; | |
| 135 | ctx.invalidate(); | |
| 136 | return Promise.resolve().then(() => | |
| 137 | ctx.push( | |
| 138 | confirmScreen(ctx, screen, { | |
| 139 | title: `Runner ${made.value.runner.name} registered`, | |
| 140 | body: ["Its token, shown this once:", made.value.token], | |
| 141 | actions: [{ label: "Done" }], | |
| 142 | onChoose: () => {}, | |
| 143 | width: 80, | |
| 144 | }), | |
| 145 | ), | |
| 146 | ); | |
| 147 | }, | |
| 148 | }), | |
| 149 | ); | |
| 150 | }; | |
| 151 | ||
| 121 | 152 | /** s, S and u on an offer: stop once its jobs finish, stop now, lend again. */ |
| 122 | 153 | const onOffer = (o: LendView, key: string): boolean => { |
| 123 | 154 | if (key === "u") { |
| @@ -145,8 +176,9 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 145 | 176 | keys: [ |
| 146 | 177 | binding(["j", "k"], "move cursor"), |
| 147 | 178 | binding(["x"], "revoke or remove a runner"), |
| 148 | binding(["p"], "pause a runner"), | |
| 179 | binding(["p"], "pause"), | |
| 149 | 180 | binding(["u"], "resume"), |
| 181 | binding(["n"], "register an outside runner"), | |
| 150 | 182 | binding(["c"], "lend runners to a forge"), |
| 151 | 183 | binding(["s"], "stop lending"), |
| 152 | 184 | binding(["S"], "stop lending now"), |
| @@ -158,7 +190,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 158 | 190 | ? "Only a forge admin sees the runners." |
| 159 | 191 | : entries().length === 0 |
| 160 | 192 | ? "No runner is enrolled; checks run on the forge's own machine. c lends runners to another forge." |
| 161 | : "The machines that take this forge's checks; x revokes a lent one or removes a hand-made one, p pauses, u resumes. c lends runners to another forge; on an offer s stops, S stops now."; | |
| 193 | : "The machines that take this forge's checks; x revokes a lent or outside one or removes a hand-made one, p pauses, u resumes. c lends runners to another forge; on an offer s stops, S stops now."; | |
| 162 | 194 | const waiting = mayRunners(f) ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : ""; |
| 163 | 195 | s.text(head!.x, head!.y, truncate(waiting === "" ? text : waiting, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 164 | 196 | const lent = mayRunners(f) ? [lentLine(lentIn(f.db, Date.now())), lendingLine(f)].filter((l) => l !== "").join(" · ") : ""; |
| @@ -173,12 +205,16 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 173 | 205 | offer(); |
| 174 | 206 | return true; |
| 175 | 207 | } |
| 208 | if (e.key === "n") { | |
| 209 | register(); | |
| 210 | return true; | |
| 211 | } | |
| 176 | 212 | const picked = all[state.index]; |
| 177 | 213 | if (picked?.kind === "offer") return e.key === "s" || e.key === "S" || e.key === "u" ? onOffer(picked.o, e.key) : false; |
| 178 | 214 | const at = picked?.r; |
| 179 | 215 | if (at === undefined || (e.key !== "x" && e.key !== "u" && e.key !== "p")) return false; |
| 180 | 216 | if (e.key === "p") { |
| 181 | const held = pause(f.app, f.user, at.id); | |
| 217 | const held = pause(f.app, f.user, at.id, "paused in the terminal"); | |
| 182 | 218 | const why = { local: `${at.name} is the forge's own; it cannot be paused.`, revoked: "That runner is revoked.", paused: "That runner is paused already.", not_found: "That runner is not enrolled." }; |
| 183 | 219 | ctx.toast(held.ok ? `Runner ${at.name} is paused: u resumes it.` : why[held.error], held.ok ? "success" : "danger"); |
| 184 | 220 | ctx.invalidate(); |
src/web/pages/runners.ts +71 −7
| @@ -9,14 +9,14 @@ | ||
| 9 | 9 | * check answers rather than the admin gate's 403. |
| 10 | 10 | */ |
| 11 | 11 | import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts"; |
| 12 | import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 12 | import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 13 | 13 | import { isLocal } from "../../checks/runner_pool.ts"; |
| 14 | 14 | import { proofByRunner, proofWords } from "../../games/lent_proof.ts"; |
| 15 | 15 | import { cannotByRunner } from "../../games/lend_why.ts"; |
| 16 | 16 | import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts"; |
| 17 | 17 | import { lentLine, scopeFacts } from "../../checks/lent_scope.ts"; |
| 18 | 18 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 19 | import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 19 | import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 20 | 20 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 21 | 21 | import type { Ctx } from "../../http/context.ts"; |
| 22 | 22 | import { sshOn } from "../../settings/ssh.ts"; |
| @@ -45,8 +45,8 @@ function runnerTrail(r: Enrolled) { | ||
| 45 | 45 | html`<form class="row-fields" method="post" action="${HERE}/${r.id}/${verb}"> |
| 46 | 46 | ${btn(label, { size: "sm", variant: "outline", label: `${label} runner ${r.name}` })} |
| 47 | 47 | </form>`; |
| 48 | if (r.scope === undefined || r.revokedAt !== 0) return form("remove", "Remove"); | |
| 49 | return html`${r.paused === "" ? "" : form("resume", "Resume")}${form("revoke", "Revoke")}`; | |
| 48 | if ((r.scope === undefined && r.labels.length === 0) || r.revokedAt !== 0) return form("remove", "Remove"); | |
| 49 | return html`${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`; | |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string) { |
| @@ -67,7 +67,7 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, can | ||
| 67 | 67 | : badge("Never asked", { variant: "outline", icon: "ban" })}`, |
| 68 | 68 | meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`} |
| 69 | 69 | · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`, |
| 70 | facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)], | |
| 70 | facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)], | |
| 71 | 71 | trail: runnerTrail(r), |
| 72 | 72 | }); |
| 73 | 73 | } |
| @@ -155,6 +155,70 @@ function lendingBlock(ctx: Ctx) { | ||
| 155 | 155 | </section>`; |
| 156 | 156 | } |
| 157 | 157 | |
| 158 | /** | |
| 159 | * Register an outside runner (#18037), a Mac say: its name, the labels it holds and the | |
| 160 | * repositories it serves. The owner's word here is the only source of its labels. Posts without | |
| 161 | * script, through the same `enrol` the API calls. | |
| 162 | */ | |
| 163 | function registerBlock() { | |
| 164 | return html`<section class="settings-block" id="register"> | |
| 165 | <h2>Register an outside runner</h2> | |
| 166 | <form method="post" action="${HERE}/register" id="register-runner"> | |
| 167 | <div class="field"> | |
| 168 | <label for="reg-name">Name</label> | |
| 169 | <input class="input" id="reg-name" name="name" required maxlength="64" placeholder="mac" autocomplete="off" /> | |
| 170 | </div> | |
| 171 | <div class="field"> | |
| 172 | <label for="reg-labels">Labels, separated by commas</label> | |
| 173 | <input class="input mono" id="reg-labels" name="labels" placeholder="macos, arm64" autocomplete="off" /> | |
| 174 | </div> | |
| 175 | <div class="field"> | |
| 176 | <label for="reg-repos">Repositories it serves, as owner/name, separated by commas</label> | |
| 177 | <input class="input mono" id="reg-repos" name="repos" required placeholder="alice/lib" autocomplete="off" /> | |
| 178 | </div> | |
| 179 | ${btn("Register runner", { label: "Register this outside runner" })} | |
| 180 | </form> | |
| 181 | </section>`; | |
| 182 | } | |
| 183 | ||
| 184 | // POST /settings/runners/register | |
| 185 | export async function runnerRegister(ctx: Ctx): Promise<Response> { | |
| 186 | const denied = admin(ctx); | |
| 187 | if (denied) return denied; | |
| 188 | const form = await readForm(ctx, "admin"); | |
| 189 | if (form instanceof Response) return form; | |
| 190 | const words = (name: string): string[] => String(form.get(name) ?? "").split(",").map((w) => w.trim()).filter((w) => w !== ""); | |
| 191 | const made = enrol(ctx.app, ctx.auth.user, String(form.get("name") ?? ""), undefined, { labels: words("labels"), repos: words("repos") }); | |
| 192 | if (!made.ok) | |
| 193 | return flashTo(ctx, `${HERE}`, { tone: "danger", message: made.error === "not_found" ? "Only a forge admin registers runners." : `Not registered: ${made.error.invalid}.` }); | |
| 194 | // Shown once, here, never kept in a flash or a URL. | |
| 195 | const res = page({ | |
| 196 | ctx, | |
| 197 | title: "Runner registered", | |
| 198 | body: html`${pageHead("Runner registered", { sub: `${made.value.runner.name}: copy its token now; it is not shown again.` })} | |
| 199 | <section class="settings-block"><p><code class="mono" id="runner-token">${made.value.token}</code></p> | |
| 200 | <p class="muted small">Give it to the runner as its bearer token. <a href="${HERE}">Back to runners</a></p></section>`, | |
| 201 | }); | |
| 202 | res.headers.set("cache-control", "no-store"); | |
| 203 | return res; | |
| 204 | } | |
| 205 | ||
| 206 | // POST /settings/runners/:id/pause | |
| 207 | export async function runnerPause(ctx: Ctx): Promise<Response> { | |
| 208 | const denied = admin(ctx); | |
| 209 | if (denied) return denied; | |
| 210 | const form = await readForm(ctx, "admin"); | |
| 211 | if (form instanceof Response) return form; | |
| 212 | const done = pause(ctx.app, ctx.auth.user, ctx.params.id ?? "", "paused on the page"); | |
| 213 | return flashTo( | |
| 214 | ctx, | |
| 215 | HERE, | |
| 216 | done.ok | |
| 217 | ? { message: `Runner ${done.value.name} claims nothing until it is resumed.` } | |
| 218 | : { tone: "danger", message: done.error === "not_found" ? "That runner is not enrolled." : "That runner is paused or revoked already." }, | |
| 219 | ); | |
| 220 | } | |
| 221 | ||
| 158 | 222 | // GET /settings/runners/lending/live |
| 159 | 223 | export function lendingLive(ctx: Ctx): Response { |
| 160 | 224 | if (!ctx.auth.user?.isAdmin || ctx.auth.user.kind !== "user") return fragment(html``, { status: 404 }); |
| @@ -205,13 +269,13 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 205 | 269 | const body = html`<section class="settings-block"> |
| 206 | 270 | ${waiting === "" ? "" : html`<p class="muted small" id="lent-waiting">${waiting}</p>`} |
| 207 | 271 | ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`} |
| 208 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>.</p> | |
| 272 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>, or register a machine below.</p> | |
| 209 | 273 | ${seen.value.length === 0 |
| 210 | 274 | ? emptyList("runners") |
| 211 | 275 | : html`<ul class="list setting-list" id="runner-list"> |
| 212 | 276 | ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? "", proofWords(proofs.get(r.id))))} |
| 213 | 277 | </ul>`} |
| 214 | </section>${lendingBlock(ctx)}`; | |
| 278 | </section>${registerBlock()}${lendingBlock(ctx)}`; | |
| 215 | 279 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 216 | 280 | return page({ |
| 217 | 281 | ctx, |
test/openapi-errors.test.ts +1 −1
| @@ -27,7 +27,7 @@ type Doc = { | ||
| 27 | 27 | |
| 28 | 28 | const BASE = "http://localhost"; |
| 29 | 29 | /** Not called: these would end the session, stop the forge or reach beyond the test's own data. */ |
| 30 | const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/; | |
| 30 | const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|(?<!runner\/)heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/; | |
| 31 | 31 | /** How many routes NOT_CALLED leaves out; a change to it changes this on purpose. */ |
| 32 | 32 | const SKIPPED = 57; |
| 33 | 33 |
test/outside-runner.test.ts added +288
| @@ -0,0 +1,288 @@ | ||
| 1 | /** | |
| 2 | * #18037: an outside runner (a Mac) is registered for chosen repositories with labels, says it is | |
| 3 | * here, claims a check whose forge.json names one of its labels, fetches the commit with the job's | |
| 4 | * short-lived credential, streams its log and reports: that is the pull's real check. The forge | |
| 5 | * never runs a labelled check itself. | |
| 6 | */ | |
| 7 | import { beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdirSync } from "node:fs"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { openPull } from "../src/actions/pulls.ts"; | |
| 11 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 12 | import { LEASE_MS, deskOf, lapseJobs, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 13 | import type { LaneState } from "../src/checks/lane_state.ts"; | |
| 14 | import type { Execution } from "../src/checks/local_runner.ts"; | |
| 15 | import { tryRunner, type RunnerCheck } from "../src/checks/tier_runner.ts"; | |
| 16 | import { startChecks } from "../src/checks/service.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { parseCheck } from "../src/apps/manifest.ts"; | |
| 19 | import { readRunLog } from "../src/runs/log.ts"; | |
| 20 | import { checkJson, checksForge } from "./helpers/checks-forge.ts"; | |
| 21 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | const f = checksForge("forge-outside-runner-"); | |
| 26 | let adminToken = ""; | |
| 27 | ||
| 28 | const api = (path: string, token: string, body?: unknown, raw?: string): Promise<Response> => | |
| 29 | fetch(`${f.servers.url}${path}`, { | |
| 30 | method: body === undefined && raw === undefined ? "GET" : "POST", | |
| 31 | headers: { authorization: `Bearer ${token}`, "content-type": raw === undefined ? "application/json" : "text/plain" }, | |
| 32 | ...(body === undefined && raw === undefined ? {} : { body: raw ?? JSON.stringify(body) }), | |
| 33 | }); | |
| 34 | ||
| 35 | /** A pull whose head declares `label` on the check (and nothing else): its head commit. */ | |
| 36 | async function labelledPull(branch: string, label: string): Promise<string> { | |
| 37 | const made = await commitToBranch(f.app, f.alice, f.repo, { | |
| 38 | branch, | |
| 39 | message: `Label the check ${label}`, | |
| 40 | files: [{ path: "forge.json", content: checkJson(`echo on-the-mac ${branch}`, `, "label": "${label}"`) }], | |
| 41 | }); | |
| 42 | if (!made.ok) throw new Error(JSON.stringify(made.error)); | |
| 43 | const opened = await openPull(f.app, f.alice, f.repo, { title: branch, body: "", baseBranch: "main", headBranch: branch }); | |
| 44 | if (!opened.ok) throw new Error(JSON.stringify(opened.error)); | |
| 45 | return made.value.commitOid; | |
| 46 | } | |
| 47 | ||
| 48 | const logOf = (runId: string): string => readRunLog(f.dataDir, runId).lines.join("\n"); | |
| 49 | ||
| 50 | async function register(name: string, labels: string[], repos: string[]): Promise<{ id: string; token: string }> { | |
| 51 | const r = await api("/api/v1/admin/runners", adminToken, { name, labels, repos }); | |
| 52 | expect(r.status).toBe(201); | |
| 53 | return (await r.json()) as { id: string; token: string }; | |
| 54 | } | |
| 55 | ||
| 56 | type Claim = { job: RunnerJob; token: string; lease: { seconds: number } }; | |
| 57 | ||
| 58 | const claimWith = async (token: string): Promise<Claim> => { | |
| 59 | const asked = api("/api/v1/runner/claim", token, { wait: 20, cells: true }); | |
| 60 | const r = await asked; | |
| 61 | expect(r.status).toBe(200); | |
| 62 | return (await r.json()) as Claim; | |
| 63 | }; | |
| 64 | ||
| 65 | beforeAll(async () => { | |
| 66 | // Placement stays `process`: a label alone sends a check to a runner. A label no runner holds | |
| 67 | // fails after a second and a half. | |
| 68 | await f.checks.stop(); | |
| 69 | f.checks = startChecks(f.app, { forgeUrl: f.servers.url, concurrency: 1, labelWaitMs: 1_500 }); | |
| 70 | adminToken = createToken(f.app.db, f.alice.id, "admin", "admin").token; | |
| 71 | }); | |
| 72 | ||
| 73 | describe("forge.json's label", () => { | |
| 74 | test("is one lower-case label; anything else is refused with the reason", () => { | |
| 75 | const ok = parseCheck(checkJson("true", `, "label": "macos"`), undefined); | |
| 76 | expect(ok.ok && ok.value?.label).toBe("macos"); | |
| 77 | const none = parseCheck(checkJson("true"), undefined); | |
| 78 | expect(none.ok && none.value?.label).toBeUndefined(); | |
| 79 | for (const bad of ['"Mac OS"', "3", '""', `"${"a".repeat(33)}"`]) { | |
| 80 | const r = parseCheck(checkJson("true", `, "label": ${bad}`), undefined); | |
| 81 | expect(r.ok).toBe(false); | |
| 82 | } | |
| 83 | }); | |
| 84 | }); | |
| 85 | ||
| 86 | describe("registering", () => { | |
| 87 | test("an owner registers a runner for chosen repositories; the token is shown once and listed rows carry labels and state", async () => { | |
| 88 | const made = await register("mac", ["macos", "arm64"], ["alice/lib"]); | |
| 89 | expect(made.token.startsWith("forge_runner_")).toBe(true); | |
| 90 | const listed = (await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; labels: string[]; repos: string[]; state: string }[] }; | |
| 91 | const row = listed.items.find((r) => r.id === made.id)!; | |
| 92 | expect(row.labels).toEqual(["macos", "arm64"]); | |
| 93 | expect(row.repos).toEqual([f.repo.id]); | |
| 94 | expect(JSON.stringify(listed)).not.toContain(made.token); | |
| 95 | }); | |
| 96 | ||
| 97 | test("not anonymous, not a member, and only well-formed labels for repositories that exist", async () => { | |
| 98 | const body = { name: "x", labels: ["macos"], repos: ["alice/lib"] }; | |
| 99 | expect((await fetch(`${f.servers.url}/api/v1/admin/runners`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })).status).not.toBe(201); | |
| 100 | const bobToken = createToken(f.app.db, f.bob.id, "bob", "admin").token; | |
| 101 | expect((await api("/api/v1/admin/runners", bobToken, body)).status).toBe(403); | |
| 102 | for (const bad of [{ labels: ["Mac OS"], repos: ["alice/lib"] }, { labels: ["macos"], repos: [] }, { labels: ["macos"], repos: ["alice/nope"] }, { labels: "macos", repos: ["alice/lib"] }]) { | |
| 103 | const r = await api("/api/v1/admin/runners", adminToken, { name: "x", ...bad }); | |
| 104 | expect(r.status).toBe(422); | |
| 105 | } | |
| 106 | }); | |
| 107 | ||
| 108 | test("a heartbeat names a state; a bad one is refused; a paused runner claims nothing", async () => { | |
| 109 | const r = await register("beat", ["macos"], ["alice/lib"]); | |
| 110 | expect((await api("/api/v1/runner/heartbeat", r.token, { state: "busy" })).status).toBe(204); | |
| 111 | expect((await api("/api/v1/runner/heartbeat", r.token, { state: "asleep" })).status).toBe(422); | |
| 112 | expect((await api("/api/v1/runner/heartbeat", "forge_runner_nope", { state: "idle" })).status).toBe(401); | |
| 113 | expect((await api("/api/v1/runner/heartbeat", r.token, { state: "paused" })).status).toBe(204); | |
| 114 | expect((await api("/api/v1/runner/claim", r.token, { wait: 0 })).status).toBe(204); | |
| 115 | const row = ((await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; state: string; seenAt: number }[] }).items.find((x) => x.id === r.id)!; | |
| 116 | expect(row.state).toBe("paused"); | |
| 117 | expect(row.seenAt).toBeGreaterThan(0); | |
| 118 | // An admin's pause, beside resume. | |
| 119 | expect((await api(`/api/v1/admin/runners/${r.id}/pause`, adminToken, { reason: "away" })).status).toBe(200); | |
| 120 | expect((await api(`/api/v1/admin/runners/${r.id}/pause`, adminToken, {})).status).toBe(422); | |
| 121 | expect((await api(`/api/v1/admin/runners/${r.id}/resume`, adminToken, {})).status).toBe(200); | |
| 122 | expect((await api(`/api/v1/admin/runners/${r.id}/revoke`, adminToken, {})).status).toBe(200); | |
| 123 | expect((await api("/api/v1/runner/heartbeat", r.token, { state: "idle" })).status).toBe(401); | |
| 124 | }); | |
| 125 | }); | |
| 126 | ||
| 127 | describe("who holds a label", () => { | |
| 128 | test("a heartbeat cannot give a runner labels: a legacy runner that sends some still claims no labelled job", async () => { | |
| 129 | const legacy = await api("/api/v1/admin/runners", adminToken, { name: "legacy" }); | |
| 130 | expect(legacy.status).toBe(201); | |
| 131 | const { id, token } = (await legacy.json()) as { id: string; token: string }; | |
| 132 | expect((await api("/api/v1/runner/heartbeat", token, { state: "idle", labels: ["macos"] })).status).toBe(204); | |
| 133 | const row = ((await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; labels: string[] }[] }).items.find((x) => x.id === id)!; | |
| 134 | expect(row.labels).toEqual([]); | |
| 135 | const oid = await labelledPull("self-labelled", "macos"); | |
| 136 | await f.until(() => f.app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM check_job WHERE state = 'queued' AND label = 'macos'").get()!.n > 0, "the labelled job queued"); | |
| 137 | expect((await api("/api/v1/runner/claim", token, { wait: 0 })).status).toBe(204); | |
| 138 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 139 | expect(run.state).toBe("failed"); | |
| 140 | }, 30_000); | |
| 141 | ||
| 142 | test("the heartbeat's refusals have the API's shape: 401, 413 and 422", async () => { | |
| 143 | const r = await register("shape", ["macos"], ["alice/lib"]); | |
| 144 | const none = await api("/api/v1/runner/heartbeat", "forge_runner_nope", { state: "idle" }); | |
| 145 | expect(none.status).toBe(401); | |
| 146 | expect(((await none.json()) as { error: string }).error).toBe("unauthorized"); | |
| 147 | const big = await api("/api/v1/runner/heartbeat", r.token, undefined, "x".repeat(1 << 20)); | |
| 148 | expect(big.status).toBe(413); | |
| 149 | expect(((await big.json()) as { error: string }).error).toBe("too_large"); | |
| 150 | const bad = await api("/api/v1/runner/heartbeat", r.token, { state: "asleep" }); | |
| 151 | expect(bad.status).toBe(422); | |
| 152 | expect(((await bad.json()) as { error: string }).error).toBe("invalid_heartbeat"); | |
| 153 | }); | |
| 154 | }); | |
| 155 | ||
| 156 | describe("a labelled check that no runner may be offered", () => { | |
| 157 | test("fails in words and is never run here: the full tier, or no run to hang a job on", async () => { | |
| 158 | const lane = { app: f.app, options: {}, placement: { mode: "process" } } as unknown as LaneState; | |
| 159 | const made = async (x: { tier?: Execution["tier"]; runId?: string | undefined }): Promise<{ out: unknown; log: string[] }> => { | |
| 160 | const log: string[] = []; | |
| 161 | const out = await tryRunner( | |
| 162 | lane, | |
| 163 | { runId: "run-1", tier: "full", ...x } as Execution, | |
| 164 | { manifest: { label: "macos" }, write: (l: string) => log.push(l), signal: new AbortController().signal } as unknown as RunnerCheck, | |
| 165 | () => Promise.reject(new Error("offered to a runner")), | |
| 166 | ); | |
| 167 | return { out, log }; | |
| 168 | }; | |
| 169 | for (const x of [{ tier: "full" as const }, { tier: "fast" as const, runId: undefined }]) { | |
| 170 | const { out, log } = await made(x); | |
| 171 | expect(out).toMatchObject({ ok: false }); | |
| 172 | expect((out as { error: string }).error).toContain('names the label "macos"'); | |
| 173 | expect(log.join("\n")).toContain("so it was not run"); | |
| 174 | } | |
| 175 | }); | |
| 176 | }); | |
| 177 | ||
| 178 | describe("a labelled check", () => { | |
| 179 | test("is claimed with the runner token, fetched with the job's credential, logged and reported: the pull's real check is green", async () => { | |
| 180 | const mac = await register("mac-flow", ["macos", "arm64"], ["alice/lib"]); | |
| 181 | expect((await api("/api/v1/runner/heartbeat", mac.token, { state: "idle", labels: ["macos", "arm64"] })).status).toBe(204); | |
| 182 | const asked = claimWith(mac.token); | |
| 183 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 184 | const oid = await labelledPull("mac-flow", "macos"); | |
| 185 | const claim = await asked; | |
| 186 | expect(claim.job.label).toBe("macos"); | |
| 187 | expect(claim.job.repo).toBe("alice/lib"); | |
| 188 | expect(claim.job.steps.at(-1)!.command).toContain("on-the-mac"); | |
| 189 | expect(claim.lease.seconds).toBe(LEASE_MS / 1000); | |
| 190 | expect(claim.token.startsWith("forge_job_")).toBe(true); | |
| 191 | // The commit, fetched by git with the short-lived credential in git's environment. | |
| 192 | const dir = join(f.dataDir, "mac-fetch"); | |
| 193 | mkdirSync(dir); | |
| 194 | const env = gitClientEnv({ GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: `Authorization: Bearer ${claim.token}` }); | |
| 195 | await Bun.spawn(["git", "init", "--quiet", "--bare", dir], { env, stdout: "ignore", stderr: "ignore" }).exited; | |
| 196 | const fetched = Bun.spawn(["git", "fetch", "--quiet", "--no-tags", "--depth=1", `${f.servers.url}/api/v1/runner/jobs/${claim.job.id}/git`, claim.job.commit], { cwd: dir, env, stdout: "ignore", stderr: "pipe" }); | |
| 197 | expect(await fetched.exited).toBe(0); | |
| 198 | // Two log lines, then ok. | |
| 199 | const door = `/api/v1/runner/jobs/${claim.job.id}`; | |
| 200 | expect((await api(door, claim.token, { step: "check", lines: ["$ on-the-mac", "mac line one"] })).status).toBe(200); | |
| 201 | expect((await api(door, claim.token, { step: "check", lines: ["mac line two"] })).status).toBe(200); | |
| 202 | const done = await api(door, claim.token, { done: { steps: claim.job.steps.map((s) => ({ name: s.name, ok: true, ms: 5 })), contained: true, note: "container VM" } }); | |
| 203 | expect(done.status).toBe(200); | |
| 204 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 205 | expect(run.state).toBe("ok"); | |
| 206 | expect(run.placement).toBe("runner"); | |
| 207 | const log = logOf(run.id); | |
| 208 | expect(log).toContain("mac line one"); | |
| 209 | expect(log).toContain("mac line two"); | |
| 210 | expect(log).toContain("placement: runner mac-flow"); | |
| 211 | // After it, the credential is nothing. | |
| 212 | expect((await api(door, claim.token, { lines: ["late"] })).status).toBe(404); | |
| 213 | }, 30_000); | |
| 214 | ||
| 215 | test("the runner token is refused a push and every route that is not a runner's; a runner serves only the repositories it was made for", async () => { | |
| 216 | const mac = await register("mac-scope", ["macos"], ["alice/lib"]); | |
| 217 | for (const path of ["/api/v1/user", "/api/v1/admin/runners"]) { | |
| 218 | expect((await api(path, mac.token)).status).toBeGreaterThanOrEqual(401); | |
| 219 | } | |
| 220 | expect((await api("/api/v1/repos/alice/lib/issues", mac.token, { title: "x" })).status).toBeGreaterThanOrEqual(401); | |
| 221 | const push = await fetch(`${f.servers.url}/alice/lib.git/info/refs?service=git-receive-pack`, { headers: { authorization: `Bearer ${mac.token}` } }); | |
| 222 | expect(push.status).toBeGreaterThanOrEqual(401); | |
| 223 | const elsewhere = await register("mac-else", ["windows"], ["alice/lib"]); | |
| 224 | // A label it does not hold is never offered to it: nothing to claim for a different label. | |
| 225 | expect((await api("/api/v1/runner/claim", elsewhere.token, { wait: 0 })).status).toBe(204); | |
| 226 | }); | |
| 227 | ||
| 228 | test("a claim whose runner goes silent is queued again once, then fails with the reason in words", async () => { | |
| 229 | const mac = await register("mac-silent", ["macos"], ["alice/lib"]); | |
| 230 | await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" }); | |
| 231 | const asked = claimWith(mac.token); | |
| 232 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 233 | const oid = await labelledPull("mac-silent", "macos"); | |
| 234 | const first = await asked; | |
| 235 | expect(lapseJobs(f.app.db, Date.now() + LEASE_MS + 1)).toEqual([first.job.id]); | |
| 236 | deskOf(f.app).ears.get(first.job.id)?.wake(); | |
| 237 | expect((await api(`/api/v1/runner/jobs/${first.job.id}`, first.token, { lines: ["late"] })).status).toBe(404); | |
| 238 | const second = await claimWith(mac.token); | |
| 239 | expect(second.job.id).toBe(first.job.id); | |
| 240 | expect(lapseJobs(f.app.db, Date.now() + LEASE_MS + 1)).toEqual([second.job.id]); | |
| 241 | deskOf(f.app).ears.get(second.job.id)?.wake(); | |
| 242 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 243 | expect(run.state).toBe("failed"); | |
| 244 | const log = logOf(run.id); | |
| 245 | expect(log).toContain("went silent: the job is queued again, and that is not a try"); | |
| 246 | expect(log).toContain('runners holding the label "macos" went silent 2 times while running it'); | |
| 247 | expect(log).toContain("not run on this machine"); | |
| 248 | }, 30_000); | |
| 249 | ||
| 250 | test("a runner may give a claim back: it is queued again, and another claim takes it", async () => { | |
| 251 | const mac = await register("mac-release", ["macos"], ["alice/lib"]); | |
| 252 | await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" }); | |
| 253 | const asked = claimWith(mac.token); | |
| 254 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 255 | const oid = await labelledPull("mac-release", "macos"); | |
| 256 | const first = await asked; | |
| 257 | expect((await api(`/api/v1/runner/jobs/${first.job.id}`, first.token, { interrupted: "the Mac slept" })).status).toBe(200); | |
| 258 | const again = await claimWith(mac.token); | |
| 259 | expect(again.job.id).toBe(first.job.id); | |
| 260 | await api(`/api/v1/runner/jobs/${again.job.id}`, again.token, { done: { steps: again.job.steps.map((s) => ({ name: s.name, ok: true, ms: 1 })), contained: true, note: "" } }); | |
| 261 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 262 | expect(run.state).toBe("ok"); | |
| 263 | }, 30_000); | |
| 264 | ||
| 265 | test("a red from the runner stays red, however it ended, and is never run on the forge's machine", async () => { | |
| 266 | const mac = await register("mac-red", ["macos"], ["alice/lib"]); | |
| 267 | await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" }); | |
| 268 | const asked = claimWith(mac.token); | |
| 269 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 270 | const oid = await labelledPull("mac-red", "macos"); | |
| 271 | const claim = await asked; | |
| 272 | await api(`/api/v1/runner/jobs/${claim.job.id}`, claim.token, { | |
| 273 | done: { steps: [{ name: "check", ok: false, error: "check exited with code 1", ms: 3 }], contained: true, note: "" }, | |
| 274 | }); | |
| 275 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 276 | expect(run.state).toBe("failed"); | |
| 277 | expect(run.placement).not.toBe("process"); | |
| 278 | }, 30_000); | |
| 279 | ||
| 280 | test("a label no available runner holds is said on the check, which then fails; it never sits queued without a word", async () => { | |
| 281 | const oid = await labelledPull("no-holder", "plan9"); | |
| 282 | const run = await f.settled((r) => r.commitOid === oid, 30_000); | |
| 283 | expect(run.state).toBe("failed"); | |
| 284 | const log = logOf(run.id); | |
| 285 | expect(log).toContain('waiting: no runner holding the label "plan9" is available for this repository'); | |
| 286 | expect(log).toContain('no runner holding the label "plan9" took it'); | |
| 287 | }, 30_000); | |
| 288 | }); |
test/settings-runners.test.ts +33
| @@ -3,6 +3,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | ||
| 3 | 3 | import { mkdtemp, rm } from "node:fs/promises"; |
| 4 | 4 | import { tmpdir } from "node:os"; |
| 5 | 5 | import { join } from "node:path"; |
| 6 | import { createRepo } from "../src/actions/repos.ts"; | |
| 6 | 7 | import { list } from "../src/actions/runners.ts"; |
| 7 | 8 | import { createApp, type App } from "../src/app.ts"; |
| 8 | 9 | import { setLoadSource } from "../src/checks/lent_yield.ts"; |
| @@ -251,3 +252,35 @@ describe("the runners page", () => { | ||
| 251 | 252 | expect(state()).toMatchObject({ stoppedAt: "", stopNow: false }); |
| 252 | 253 | }); |
| 253 | 254 | }); |
| 255 | ||
| 256 | describe("an outside runner, from the page", () => { | |
| 257 | const form = (who: User, path: string, body: string, origin = servers.url) => | |
| 258 | fetch(`${servers.url}${path}`, { | |
| 259 | method: "POST", | |
| 260 | redirect: "manual", | |
| 261 | headers: { cookie: cookie(who), origin, "content-type": "application/x-www-form-urlencoded" }, | |
| 262 | body, | |
| 263 | }); | |
| 264 | ||
| 265 | test("the admin registers one with labels and repositories, sees its token once, and may pause and resume it", async () => { | |
| 266 | const bad = await form(alice, "/settings/runners/register", "name=mac&labels=macos&repos=nobody%2Fnone"); | |
| 267 | expect(bad.status).toBe(303); | |
| 268 | expect((list(app, alice) as unknown as { value: { name: string }[] }).value.some((r) => r.name === "mac")).toBe(false); | |
| 269 | expect((await form(bob, "/settings/runners/register", "name=mac&labels=macos&repos=x%2Fy")).status).toBeGreaterThanOrEqual(403); | |
| 270 | expect((await form(alice, "/settings/runners/register", "name=mac&labels=macos&repos=x%2Fy", "http://elsewhere.test")).status).toBe(403); | |
| 271 | const repo = await createRepo(app, alice, { name: "mac-lib", visibility: "public" }); | |
| 272 | expect(repo.ok).toBe(true); | |
| 273 | const ok = await form(alice, "/settings/runners/register", "name=mac&labels=macos%2C+arm64&repos=alice%2Fmac-lib"); | |
| 274 | expect(ok.status).toBe(200); | |
| 275 | expect(ok.headers.get("cache-control")).toBe("no-store"); | |
| 276 | expect(await ok.text()).toContain("forge_runner_"); | |
| 277 | const row = ((list(app, alice) as unknown as { value: { name: string; labels: string[] }[] }).value.find((r) => r.name === "mac"))!; | |
| 278 | expect(row.labels).toEqual(["macos", "arm64"]); | |
| 279 | const made = enrolRunner(app.db, "pausable", alice.id, undefined, Date.now(), { labels: ["macos"], repos: [] }).runner; | |
| 280 | expect(await (await get(alice)).text()).toContain(`/settings/runners/${made.id}/pause`); | |
| 281 | expect((await form(alice, `/settings/runners/${made.id}/pause`, "")).status).toBe(303); | |
| 282 | const page = await (await get(alice)).text(); | |
| 283 | expect(page).toContain(`/settings/runners/${made.id}/resume`); | |
| 284 | expect(page).not.toContain(`/settings/runners/${made.id}/pause`); | |
| 285 | }); | |
| 286 | }); |
test/tui-runners.test.ts +15
| @@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | ||
| 8 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 13 | import { setLoadSource } from "../src/checks/lent_yield.ts"; |
| 13 | 14 | import { enrolRunner, listRunners } from "../src/checks/runner_jobs.ts"; |
| @@ -175,3 +176,17 @@ describe("runners in the terminal", () => { | ||
| 175 | 176 | expect(state().stoppedAt).toBe(""); |
| 176 | 177 | }); |
| 177 | 178 | }); |
| 179 | ||
| 180 | describe("registering an outside runner in the terminal", () => { | |
| 181 | test("n takes a name, labels and repositories; a repository that is not here is refused; the token is shown once; a non-admin registers nothing", async () => { | |
| 182 | const made = await createRepo(app, ada, { name: "termlib", visibility: "public" }); | |
| 183 | expect(made.ok).toBe(true); | |
| 184 | await drive(ada, ["n", "termbad macos ada/nope", ENTER]); | |
| 185 | expect(names()).not.toContain("termbad"); | |
| 186 | const { text } = await drive(ada, ["n", "termmac macos,arm64 ada/termlib", ENTER]); | |
| 187 | expect(text).toContain("forge_runner_"); | |
| 188 | expect(listRunners(app.db).find((r) => r.name === "termmac")).toMatchObject({ labels: ["macos", "arm64"] }); | |
| 189 | await drive(bob, ["n", "termbob macos ada/termlib", ENTER]); | |
| 190 | expect(names()).not.toContain("termbob"); | |
| 191 | }); | |
| 192 | }); |
new above
offline
HIGH: this branch needs
runnerTakes(x). A labelled check that fails that test, or has no runId, falls through and runs on the forge's machine, against the label. Fail it in words here instead.