Public: anyone can read this; the crew can change it.
Moving a forge to another machine is copy, start, flip the router — and a test kills a machine #16989
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16859-moving-a-forge-to-another-machine-is-cop → main 0 commits fork 3 threads · 3 unresolved
21 files
changed +1243
−28
- AGENTS.md
- docs/features/move-machine.md
- scripts/unused-exports-allow.json
- src/core/event_audience.ts
- src/http/forges_routes.ts
- src/http/lazy_lists.ts
- src/http/marks/forges.json
- src/http/mcp/tools/forges.ts
- src/spawn/archive.ts
- src/spawn/host.ts
- src/spawn/machines.ts
- src/spawn/manage.ts
- src/spawn/move_machine.ts
- src/spawn/routes.ts
- src/tui/screens/forges.ts
- src/web/pages/forge_machine.ts
- src/web/pages/forges.ts
- test/helpers/machine-forge.ts
- test/move-machine-doors.test.ts
- test/move-machine.test.ts
- test/spawn-sites.test.ts
AGENTS.md +1
| @@ -104,3 +104,4 @@ A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools | ||
| 104 | 104 | `bun scripts/gate.ts --explain` (#16325) lists every gate rule (`GATE_RULES`, `scripts/gate.ts`) and every fast tree-reading guard test (`GUARDS`, `scripts/gate_explain.ts`) against your diff, satisfied or not, each with the line that satisfies it and where the rule lives; a refusing gate ends with one line naming all the rules that refused. No network, no socket, about fifteen seconds. In a sandboxed session `bun x tsc --noEmit` without installed dependencies, tests that bind a port or unix socket, and the full suite cannot run: report them as not run. A rule added to `GATE_RULES` is judged and explained at once; a new tree-reading guard goes in `GUARDS`. |
| 105 | 105 | |
| 106 | 106 | `src/crew/runner.ts`'s `work()` is the order of one agent run, and each step of it is a module that takes its state as a plain object and returns plain data (#16789): `run_spend.ts` (`settleSpend`: the account, ceilings and budget, or the refusal), `run_prompt.ts` (`promptFor`, `reviewInputs`), `run_retry.ts` (`retryNetwork`, `outagePause`), `run_limits.ts` (`limitEnding`: a provider's refusal as a pause), `run_verdict.ts` (`verdictOf`, `settleReview`: a decline or a review's verdict), `run_prepare.ts` (`prepareAgent`: the environment, sandbox, devices, model and the metered `invoke` closure, with what the `finally` must free in a `Held`), `run_wrapup.ts` (`wrapUp`: the reserve turn), `run_settle.ts` (`settleRun`: a cancel, a refused token, a verdict, or the landing, as the outcome), with `meter.ts` holding the `Outcome` and `Meter` records they share. A step imports nothing of `runner.ts` but the `CrewOptions` type; `runner.ts` re-exports the names it was imported by. Tests: `test/run-steps.test.ts`. |
| 107 | `src/spawn/routes.ts`: `tables`, per data directory, the router's table of forges moved to another machine (#16859), read once from `routes.json` and kept by `setRoute`, the only writer (a rename of the whole file); at most one entry per moved forge, gone on restart (the file is the state). `src/spawn/machines.ts`: `registered`, the machines declared by `FORGE_MACHINES` (or put by a test), made on first read, and each process machine's `running` process groups by forge name; at most one per forge, gone on restart. `src/spawn/move_machine.ts`: `busy`, the forges being moved now, so a second ask is refused; gone when the move ends. The terminal door is `g` on the Forges screen (`src/tui/screens/forges.ts`; `planMove`/`moveToMachine` give the page, the MCP `forges` tool and the terminal the same words). |
docs/features/move-machine.md added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | --- | |
| 2 | topic: Backups and moving | |
| 3 | row: Moving a forge to another machine (#16859) | |
| 4 | --- | |
| 5 | # Moving a forge to another machine (#16859) | |
| 6 | ||
| 7 | A forge that runs in its own sandbox can be moved to another machine this forge | |
| 8 | was told about: copy, start, flip the router. The forge is unreachable only | |
| 9 | between the copy's start and the flip, and the budget is 60 seconds | |
| 10 | (`MOVE_BUDGET_S`); the plan says it before and the receipt says how long it | |
| 11 | really was. | |
| 12 | ||
| 13 | ## Where it is said | |
| 14 | ||
| 15 | - **/forges**: a row of a forge in its own sandbox has **Move to another | |
| 16 | machine** (`src/web/pages/forge_machine.ts`) while any machine is declared. | |
| 17 | It shows the plan (one sentence with the budget), asks, and then shows the | |
| 18 | receipt. A forge that is on a machine also offers **Restore**, previewed with | |
| 19 | the copy's time and what is lost. | |
| 20 | - **Terminal, Forges screen**: `g` picks the forge, then the machine, shows | |
| 21 | the same plan on a confirm, and toasts the same receipt; `v` is the restore | |
| 22 | from the newest copy, the same way (`src/tui/screens/forges.ts`). | |
| 23 | - **MCP**: `forges` with `{ action: "move", forge, to }` previews; with | |
| 24 | `dryRun: false` it moves. `{ action: "recover", forge, to }` previews the | |
| 25 | copy it would restore, its time and what is lost; with `dryRun: false` it | |
| 26 | restores from the bucket's last copy when the machine is gone. `to` is a | |
| 27 | machine, or `here`: the way back to this forge's own root. | |
| 28 | ||
| 29 | ## Machines | |
| 30 | ||
| 31 | `FORGE_MACHINES=name=/absolute/root,other=/other/root` declares them. A | |
| 32 | machine here is a data root and a way to run the forge's own entry on it as a | |
| 33 | process group (`src/spawn/machines.ts`); a remote machine is another driver of | |
| 34 | the same four calls, and none ships. | |
| 35 | ||
| 36 | ## The order | |
| 37 | ||
| 38 | 1. Check: it is a finished forge in its own cell, the machine is declared, it | |
| 39 | is not there already, a backup destination is set. Nothing changes. | |
| 40 | 2. Hold: its address says "waking up". | |
| 41 | 3. Copy: it is stopped, its data and ledger are written to the backup | |
| 42 | destination (`forge-moves/<name>/`), read back the same, and restored from | |
| 43 | that copy into the target's root. | |
| 44 | 4. Start: the target runs it and it answers `/healthz`. | |
| 45 | 5. Flip: `routes.json` names the machine (`src/spawn/routes.ts`), and the hold | |
| 46 | ends. The old place is stopped, never deleted: its data is the way back. | |
| 47 | ||
| 48 | Data the target already holds for this forge (the old place of an earlier | |
| 49 | move) is never deleted to make room: it is renamed `<dir>.before-<time>` beside | |
| 50 | it, and put back if the move fails. | |
| 51 | ||
| 52 | Any failure before the flip leaves the route as it was and takes the target's | |
| 53 | copy away; the forge wakes where it was. A forge that was on a machine was | |
| 54 | stopped there for the copy, so it is started there again and the route follows | |
| 55 | its new port. | |
| 56 | ||
| 57 | A machine's process group is recorded in `<root>/pids/<forge>.pid`: after this | |
| 58 | host restarts the forge goes on running, and `alive` and `stop` still find it, | |
| 59 | so a recovery never makes a second copy. A forge that is removed is ended on | |
| 60 | its machine and its route cleared; one that is on a machine is not archived | |
| 61 | (its live data is not here). | |
| 62 | ||
| 63 | ## When a machine dies | |
| 64 | ||
| 65 | `recover` restores the newest copy in the bucket on another machine, starts | |
| 66 | it, and flips. It refuses while the old machine still runs the forge. What the | |
| 67 | forge wrote after that copy is lost, and the receipt names the copy's time. | |
| 68 | ||
| 69 | ## Left out | |
| 70 | ||
| 71 | The copy is the move's own: nothing streams continuously to the bucket yet, so | |
| 72 | a machine that dies loses what was written since its last move. Nothing | |
| 73 | detects a dead machine by itself; `recover` is asked for. |
scripts/unused-exports-allow.json +4 −1
| @@ -174,5 +174,8 @@ | ||
| 174 | 174 | "src/web/studio/home_cache.ts setHomeClock", |
| 175 | 175 | "src/web/studio/home_last.ts forgetHome", |
| 176 | 176 | "src/web/studio/review_evidence.ts rememberStat", |
| 177 | "src/web/sw.ts swSource" | |
| 177 | "src/web/sw.ts swSource", | |
| 178 | "src/spawn/machines.ts forgetMachines", | |
| 179 | "src/spawn/machines.ts registerMachine", | |
| 180 | "src/spawn/routes.ts forgetRoutes" | |
| 178 | 181 | ] |
src/core/event_audience.ts +2
| @@ -374,6 +374,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 374 | 374 | // theirs to answer (`actions/ask_admin.ts`). |
| 375 | 375 | kind.startsWith("ask.") || |
| 376 | 376 | kind === "forge.moved" || |
| 377 | kind === "forge.machine_moved" || | |
| 378 | kind === "forge.recovered" || | |
| 377 | 379 | kind === "forge.move_failed" || |
| 378 | 380 | kind === "forge.move_held" || |
| 379 | 381 | // That this host now opens no forge in its own process is its admins' to know |
src/http/forges_routes.ts +3
| @@ -11,6 +11,7 @@ import { familyPage } from "../web/pages/family.ts"; | ||
| 11 | 11 | import { forgeLinkForm, forgeRevokeConfirm, forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeArchiveConfirm, forgeArchiveSubmit, forgeRestoreSubmit, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit, forgeOwnCodeSubmit, forgeSizeSubmit, forgeSandboxSubmit, forgesPage, forgesCsv } from "../web/pages/forges.ts"; |
| 12 | 12 | import { billDownload } from "./api/forge_bill.ts"; |
| 13 | 13 | import { forgeRecoveryForm, forgeRecoverySubmit } from "../web/pages/forges.ts"; |
| 14 | import { forgeMachineForm, forgeMachineSubmit } from "../web/pages/forge_machine.ts"; | |
| 14 | 15 | import { forgesRefusedPage } from "../web/pages/forges-refused.ts"; |
| 15 | 16 | import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts"; |
| 16 | 17 | import { pricingDone, pricingOrder, pricingPage, receiptHtml, receiptPage, resendPage, resendSubmit } from "../web/pages/pricing.ts"; |
| @@ -39,6 +40,8 @@ export function forgesRoutes(router: Router<Handler>): void { | ||
| 39 | 40 | router.add("POST", "/forges/:name/undo-link", forgeLinkUndo); |
| 40 | 41 | router.add("POST", "/forges/:name/stop", forgeStopSubmit); |
| 41 | 42 | router.add("POST", "/forges/:name/sandbox", forgeSandboxSubmit); |
| 43 | router.add("GET", "/forges/:name/machine", forgeMachineForm); | |
| 44 | router.add("POST", "/forges/:name/machine", forgeMachineSubmit); | |
| 42 | 45 | // An admin's answers to what a hosted forge asked to reach (`web/pages/hosted-forges.ts`). |
| 43 | 46 | router.add("POST", "/forges/:name/reach/allow", forgeReachAllow); |
| 44 | 47 | router.add("POST", "/forges/:name/reach/later", forgeReachLater); |
src/http/lazy_lists.ts +2
| @@ -234,6 +234,8 @@ export const FORGES_ROUTES = [ | ||
| 234 | 234 | ["POST", "/forges/:name/undo-link"], |
| 235 | 235 | ["POST", "/forges/:name/stop"], |
| 236 | 236 | ["POST", "/forges/:name/sandbox"], |
| 237 | ["GET", "/forges/:name/machine"], | |
| 238 | ["POST", "/forges/:name/machine"], | |
| 237 | 239 | ["POST", "/forges/:name/reach/allow"], |
| 238 | 240 | ["POST", "/forges/:name/reach/later"], |
| 239 | 241 | ["POST", "/forges/:name/reach/revoke"], |
src/http/marks/forges.json +1
src/http/mcp/tools/forges.ts +18 −2
| @@ -8,6 +8,7 @@ import { clientRows, listedKept } from "../../../spawn/clients.ts"; | ||
| 8 | 8 | import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archive.ts"; |
| 9 | 9 | import { CHILD_NAME } from "../../../spawn/placement.ts"; |
| 10 | 10 | import { checkMove } from "../../../spawn/move_check.ts"; |
| 11 | import { moveToMachine, planMove, planRecover, recoverForge } from "../../../spawn/move_machine.ts"; | |
| 11 | 12 | import { moveToCell } from "../../../spawn/move_cell.ts"; |
| 12 | 13 | import { resizeForge } from "../../../spawn/manage.ts"; |
| 13 | 14 | import { previewDoor, reissueDoor } from "../../../spawn/door.ts"; |
| @@ -18,10 +19,10 @@ const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." | ||
| 18 | 19 | export const tool: Tool = { |
| 19 | 20 | name: "forges", |
| 20 | 21 | listedTo: "admin", |
| 21 | doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link", | |
| 22 | doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link; move + `forge` + `to` a machine (or `here`, the way back): copy, start, switch the router, receipt (unreachable under 60 s); recover + `forge` + `to`: the same from the bucket's last copy, previewed with the copy's time and what is lost", | |
| 22 | 23 | description: |
| 23 | 24 | "Forges sent from here (admin).", |
| 24 | inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { type: "string", enum: ["refused", "clients"] }, action: { enum: ["resend"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } }, | |
| 25 | inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { enum: ["refused", "clients"] }, action: { enum: ["resend", "move", "recover"] }, to: {}, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } }, | |
| 25 | 26 | writes: true, |
| 26 | 27 | tier: "delete", |
| 27 | 28 | deletes: (args) => args["archive"] !== undefined, |
| @@ -31,6 +32,21 @@ export const tool: Tool = { | ||
| 31 | 32 | async run(ctx, user, args) { |
| 32 | 33 | if (!user.isAdmin) |
| 33 | 34 | return bad("forbidden", "only an admin of this forge sees the forges it sent"); |
| 35 | if (args["action"] === "move" || args["action"] === "recover") { | |
| 36 | const [forge, to] = [String(args["forge"] ?? ""), String(args["to"] ?? "")]; | |
| 37 | if (args["action"] === "recover" && args["dryRun"] === false) { | |
| 38 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "recovering a forge needs an admin token"); | |
| 39 | const back = await recoverForge(ctx.app, forge, to, { actorId: user.id }); | |
| 40 | return back.ok ? good(back) : bad(back.kind, back.says); | |
| 41 | } | |
| 42 | if (args["action"] === "move" && args["dryRun"] === false) { | |
| 43 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "moving a forge needs an admin token"); | |
| 44 | const moved = await moveToMachine(ctx.app, forge, to, { actorId: user.id }); | |
| 45 | return moved.ok ? good(moved) : bad(moved.kind, moved.says); | |
| 46 | } | |
| 47 | const plan = args["action"] === "recover" ? await planRecover(ctx.app, forge, to) : await planMove(ctx.app, forge, to); | |
| 48 | return plan.ok ? good({ ...plan.plan, says: `${plan.plan.says} Send dryRun: false to do it.` }) : bad(plan.kind, plan.says); | |
| 49 | } | |
| 34 | 50 | if (args["action"] !== undefined) { |
| 35 | 51 | const name = str(args["forge"]); |
| 36 | 52 | if (args["dryRun"] !== false) { |
src/spawn/archive.ts +44 −22
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | * copy until verified, `notices.json` when each claimant was told. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { routeOf } from "./routes.ts"; | |
| 13 | 14 | import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs"; |
| 14 | 15 | import { rm } from "node:fs/promises"; |
| 15 | 16 | import { join } from "node:path"; |
| @@ -78,12 +79,48 @@ export function archivedForges(app: App): ArchiveRecord[] { | ||
| 78 | 79 | return out.sort((a, b) => b.archivedAt.localeCompare(a.archivedAt)); |
| 79 | 80 | } |
| 80 | 81 | |
| 81 | async function tar(args: readonly string[]): Promise<{ ok: boolean; out: string; err: string }> { | |
| 82 | export async function tar(args: readonly string[]): Promise<{ ok: boolean; out: string; err: string }> { | |
| 82 | 83 | const p = Bun.spawn(["tar", ...args], { stdout: "pipe", stderr: "pipe" }); |
| 83 | 84 | const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]); |
| 84 | 85 | return { ok: (await p.exited) === 0, out, err: err.trim().slice(0, 200) }; |
| 85 | 86 | } |
| 86 | 87 | |
| 88 | /** | |
| 89 | * An archive's bytes unpacked into `<stage>/out`, which is returned; undefined (stage removed) when | |
| 90 | * it is not one forge's archive. The copy comes from a store less trusted than this host: names are | |
| 91 | * checked, and so is the kind of every entry, so no link can send a later entry's write elsewhere. | |
| 92 | */ | |
| 93 | export async function unpackForge(body: Uint8Array, stage: string, name: string, bodyId: string): Promise<string | undefined> { | |
| 94 | await rm(stage, { recursive: true, force: true }); | |
| 95 | mkdirSync(stage, { recursive: true }); | |
| 96 | const file = join(stage, "copy.tar.gz"); | |
| 97 | const extracted = join(stage, "out"); | |
| 98 | mkdirSync(extracted); | |
| 99 | await Bun.write(file, body); | |
| 100 | const listed = await tar(["-tzf", file]); | |
| 101 | const kinds = await tar(["-tvzf", file]); | |
| 102 | const entries = listed.out.split("\n").filter((l) => l !== ""); | |
| 103 | const types = kinds.out.split("\n").filter((l) => l !== ""); | |
| 104 | const plain = kinds.ok && types.length === entries.length && types.every((l) => l[0] === "-" || l[0] === "d"); | |
| 105 | const clean = listed.ok && plain && entries.length > 0 && entries.every((e) => !e.split("/").includes("..") && !e.startsWith("/") && (e === `${name}.json` || e === `${bodyId}/` || e.startsWith(`${bodyId}/`))); | |
| 106 | const out = clean ? await tar(["-xzf", file, "--no-same-owner", "-C", extracted]) : undefined; | |
| 107 | if (out === undefined || !out.ok || !existsSync(join(extracted, `${name}.json`))) { | |
| 108 | await rm(stage, { recursive: true, force: true }); | |
| 109 | return undefined; | |
| 110 | } | |
| 111 | return extracted; | |
| 112 | } | |
| 113 | ||
| 114 | /** | |
| 115 | * One forge's data directory and ledger as one gzip tar at `local`; false (nothing left) when tar | |
| 116 | * fails. | |
| 117 | */ | |
| 118 | export async function packForge(dataDir: string, name: string, bodyId: string, local: string): Promise<{ ok: boolean; err: string }> { | |
| 119 | const made = await tar(["-czf", local, "-C", join(dataDir, "spawn"), `${name}.json`, "-C", join(dataDir, "children"), bodyId]); | |
| 120 | if (!made.ok) await rm(local, { force: true }); | |
| 121 | return { ok: made.ok, err: made.err }; | |
| 122 | } | |
| 123 | ||
| 87 | 124 | /** Where an archive would be written, in words: the store, or that there is none. */ |
| 88 | 125 | export function destinationWords(app: App): string { |
| 89 | 126 | const d = resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); |
| @@ -108,6 +145,9 @@ async function archiveOne(app: App, name: string, options: ArchiveOptions): Prom | ||
| 108 | 145 | if (child === undefined) return { ok: false, says: `no forge named ${name}` }; |
| 109 | 146 | if (!child.done) return { ok: false, says: `${name} is still being made` }; |
| 110 | 147 | if (!BODY_ID.test(child.bodyId)) return { ok: false, says: `${name} has no data directory to archive` }; |
| 148 | // Its live data is on the machine, not here: archiving this stale copy would lose what it wrote. | |
| 149 | const routed = routeOf(app, name); | |
| 150 | if (routed !== undefined) return { ok: false, says: `${name} runs on ${routed.machine}: move it back here before archiving it` }; | |
| 111 | 151 | const destination = options.destination ?? resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); |
| 112 | 152 | if (destination === undefined) |
| 113 | 153 | return { ok: false, says: `${name} was not archived: this forge has no backup destination to write the copy to (set one on the Backups page)` }; |
| @@ -148,9 +188,8 @@ async function copyAndRemove( | ||
| 148 | 188 | now: number, |
| 149 | 189 | options: ArchiveOptions, |
| 150 | 190 | ): Promise<Managed> { |
| 151 | const made = await tar(["-czf", local, "-C", join(app.config.dataDir, "spawn"), `${name}.json`, "-C", join(app.config.dataDir, "children"), child.bodyId]); | |
| 191 | const made = await packForge(app.config.dataDir, name, child.bodyId, local); | |
| 152 | 192 | if (!made.ok) { |
| 153 | await rm(local, { force: true }); | |
| 154 | 193 | return { ok: false, says: `${name} was not archived: the copy could not be written (${made.err}); ${STOPPED_SAFE}` }; |
| 155 | 194 | } |
| 156 | 195 | const size = statSync(local).size; |
| @@ -229,25 +268,8 @@ async function restoreOne(app: App, name: string, options: ArchiveOptions): Prom | ||
| 229 | 268 | if (body === undefined || body.length !== record.bytes || sha256(body) !== record.sha256) |
| 230 | 269 | return { ok: false, says: `${name} was not restored: the copy at ${destination.store.where} is missing or is not what was archived` }; |
| 231 | 270 | const stage = join(root(app), `restoring-${name}`); |
| 232 | await rm(stage, { recursive: true, force: true }); | |
| 233 | mkdirSync(stage, { recursive: true }); | |
| 234 | const file = join(stage, "copy.tar.gz"); | |
| 235 | const extracted = join(stage, "out"); | |
| 236 | mkdirSync(extracted); | |
| 237 | await Bun.write(file, body); | |
| 238 | // The copy comes from a store less trusted than this host: names are checked, and so is the kind | |
| 239 | // of every entry, so no link can send a later entry's write elsewhere. | |
| 240 | const listed = await tar(["-tzf", file]); | |
| 241 | const kinds = await tar(["-tvzf", file]); | |
| 242 | const entries = listed.out.split("\n").filter((l) => l !== ""); | |
| 243 | const types = kinds.out.split("\n").filter((l) => l !== ""); | |
| 244 | const plain = kinds.ok && types.length === entries.length && types.every((l) => l[0] === "-" || l[0] === "d"); | |
| 245 | const clean = listed.ok && plain && entries.length > 0 && entries.every((e) => !e.split("/").includes("..") && !e.startsWith("/") && (e === `${name}.json` || e === `${record.bodyId}/` || e.startsWith(`${record.bodyId}/`))); | |
| 246 | const out = clean ? await tar(["-xzf", file, "--no-same-owner", "-C", extracted]) : undefined; | |
| 247 | if (out === undefined || !out.ok || !existsSync(join(extracted, `${name}.json`))) { | |
| 248 | await rm(stage, { recursive: true, force: true }); | |
| 249 | return { ok: false, says: `${name} was not restored: the copy is not a forge's archive` }; | |
| 250 | } | |
| 271 | const extracted = await unpackForge(body, stage, name, record.bodyId); | |
| 272 | if (extracted === undefined) return { ok: false, says: `${name} was not restored: the copy is not a forge's archive` }; | |
| 251 | 273 | mkdirSync(join(app.config.dataDir, "children"), { recursive: true }); |
| 252 | 274 | mkdirSync(join(app.config.dataDir, "spawn"), { recursive: true }); |
| 253 | 275 | if (existsSync(join(extracted, record.bodyId))) renameSync(join(extracted, record.bodyId), dir); |
src/spawn/host.ts +7
| @@ -36,6 +36,7 @@ import { cancelRestarts, clearStop, lastStop, noteStop, stopSentence, tryAgainAt | ||
| 36 | 36 | import { readOwnCode } from "./own_code.ts"; |
| 37 | 37 | import { awakeRefusal, budgetRefusal, idleAfterMs, wakeBudget, WakeRate } from "./sleep.ts"; |
| 38 | 38 | import { rememberAwake, takeAwake } from "./awake_at_stop.ts"; |
| 39 | import { routeOf } from "./routes.ts"; | |
| 39 | 40 | import { wakingResponse } from "../web/pages/waking.ts"; |
| 40 | 41 | import { lapsedResponse, payAgainRoute, PAY_AGAIN_PATH } from "../web/pages/lapsed.ts"; |
| 41 | 42 | import { lapseFor, type Lapse } from "../billing/lapse.ts"; |
| @@ -591,6 +592,9 @@ export function startRefused(parent: App, ledger: { readonly name: string; reado | ||
| 591 | 592 | // Being archived: its data is copied, then removed, so nothing may write to it (#14783). |
| 592 | 593 | const closed = closedRefusal(parent, ledger); |
| 593 | 594 | if (closed !== undefined) return closed; |
| 595 | // On another machine (`move_machine.ts`): two copies must never run. | |
| 596 | const routed = routeOf(parent, ledger.name); | |
| 597 | if (routed !== undefined) return `${ledger.name} runs on ${routed.machine}`; | |
| 594 | 598 | // Below the disk floor nothing wakes, whatever its filesystem (#10873). |
| 595 | 599 | const floor = floorRefusal(parent.config.dataDir); |
| 596 | 600 | if (floor !== undefined) { |
| @@ -1117,6 +1121,9 @@ export async function answerFromCell(parent: App, request: Request, named?: stri | ||
| 1117 | 1121 | if (ledger !== undefined && ledger.moving) return wakingResponse(request, ledger.name); |
| 1118 | 1122 | if (ledger !== undefined && ledger.placement !== "cell" && isSealed(parent)) return wakingResponse(request, ledger.name, waitsToMove(ledger.name)); |
| 1119 | 1123 | if (ledger === undefined || ledger.placement !== "cell") return new Response("not found", { status: 404 }); |
| 1124 | // Moved to another machine (`move_machine.ts`): the router's table says where it answers now. | |
| 1125 | const routed = routeOf(parent, ledger.name); | |
| 1126 | if (routed !== undefined) return await forward(routed, request, parent.config.clientIpHeader); | |
| 1120 | 1127 | const cells = cellChildren(parent); |
| 1121 | 1128 | const child = cells.get(ledger.bodyId); |
| 1122 | 1129 | if (child !== undefined) { |
src/spawn/machines.ts added +165
| @@ -0,0 +1,165 @@ | ||
| 1 | /** | |
| 2 | * The machines a forge may be moved to (#16859). A machine is a place an admin declared with | |
| 3 | * `FORGE_MACHINES` (`name=/data/root,name2=/other/root`): a data root and a way to run a forge on | |
| 4 | * it. `Machine` is the whole contract the move needs; `processMachine` runs the forge's own entry | |
| 5 | * as a process group on its root, so ending the group ends the forge and everything it started | |
| 6 | * (`alive` then says no, and a recovery starts it elsewhere). The group's pid is kept in | |
| 7 | * `<root>/pids/<forge>.pid`, so after this host restarts (the forge is detached and goes on | |
| 8 | * running) `alive` and `stop` still find it: two copies never run. A remote machine is another | |
| 9 | * driver of the same four calls; none is shipped here. | |
| 10 | */ | |
| 11 | ||
| 12 | import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { cellEnv } from "./cell.ts"; | |
| 16 | import { BODY_ID } from "./archive.ts"; | |
| 17 | import { CHILD_NAME } from "./placement.ts"; | |
| 18 | import { clearRoute } from "./routes.ts"; | |
| 19 | ||
| 20 | export interface Machine { | |
| 21 | readonly name: string; | |
| 22 | /** Where its forges' `spawn/` and `children/` live. */ | |
| 23 | readonly root: string; | |
| 24 | /** | |
| 25 | * Run the forge `name` (data under `root`); the loopback port it answers on, undefined when it | |
| 26 | * did not start. | |
| 27 | */ | |
| 28 | start(name: string, bodyId: string, url: string): Promise<number | undefined>; | |
| 29 | /** Whether its process tree is still there. */ | |
| 30 | alive(name: string): boolean; | |
| 31 | /** End its process tree. */ | |
| 32 | stop(name: string): Promise<void>; | |
| 33 | } | |
| 34 | ||
| 35 | export type Launch = (input: { name: string; bodyId: string; root: string; port: number; url: string }) => { | |
| 36 | /** The script this runtime runs. */ | |
| 37 | readonly script: string; | |
| 38 | readonly env: Record<string, string>; | |
| 39 | }; | |
| 40 | ||
| 41 | const MAIN = join(import.meta.dir, "..", "main.ts"); | |
| 42 | ||
| 43 | /** The forge's own entry, with the data and the port it is to use. */ | |
| 44 | export const forgeLaunch: Launch = ({ bodyId, root, port, url }) => ({ | |
| 45 | script: MAIN, | |
| 46 | env: cellEnv({ port, dataDir: join(root, "children", bodyId), url }), | |
| 47 | }); | |
| 48 | ||
| 49 | async function freePort(): Promise<number> { | |
| 50 | const s = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } }); | |
| 51 | const port = s.port; | |
| 52 | s.stop(true); | |
| 53 | return port; | |
| 54 | } | |
| 55 | ||
| 56 | const PROBE_TIMEOUT_MS = 2_000; | |
| 57 | ||
| 58 | /** `probe` answers whether the forge on `port` is up; tests hand in theirs. */ | |
| 59 | export function processMachine( | |
| 60 | name: string, | |
| 61 | root: string, | |
| 62 | launch: Launch = forgeLaunch, | |
| 63 | probe: (port: number) => Promise<boolean> = async (port) => (await fetch(`http://127.0.0.1:${port}/healthz`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) }).catch(() => undefined))?.ok === true, | |
| 64 | waitMs = 30_000, | |
| 65 | ): Machine { | |
| 66 | const running = new Map<string, { pid: number; exited: Promise<number> }>(); | |
| 67 | const pidFile = (forge: string): string => join(root, "pids", `${forge}.pid`); | |
| 68 | /** The group's pid: this process's own child, or what an earlier run of this host wrote. */ | |
| 69 | const pidOf = (forge: string): number | undefined => { | |
| 70 | const r = running.get(forge); | |
| 71 | if (r !== undefined) return r.pid; | |
| 72 | try { | |
| 73 | const n = Number(readFileSync(pidFile(forge), "utf8").trim()); | |
| 74 | return Number.isInteger(n) && n > 1 ? n : undefined; | |
| 75 | } catch { | |
| 76 | return undefined; | |
| 77 | } | |
| 78 | }; | |
| 79 | const groupAlive = (pid: number): boolean => { | |
| 80 | try { | |
| 81 | process.kill(-pid, 0); | |
| 82 | return true; | |
| 83 | } catch { | |
| 84 | return false; | |
| 85 | } | |
| 86 | }; | |
| 87 | return { | |
| 88 | name, | |
| 89 | root, | |
| 90 | async start(forge, bodyId, url) { | |
| 91 | const port = await freePort(); | |
| 92 | const how = launch({ name: forge, bodyId, root, port, url }); | |
| 93 | // Its own process group (`detached`), so one signal reaches the tree it grows. | |
| 94 | const proc = Bun.spawn([process.execPath, how.script], { detached: true, env: how.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" }); | |
| 95 | running.set(forge, { pid: proc.pid, exited: proc.exited }); | |
| 96 | mkdirSync(join(root, "pids"), { recursive: true }); | |
| 97 | writeFileSync(pidFile(forge), String(proc.pid), { mode: 0o600 }); | |
| 98 | const until = Date.now() + waitMs; | |
| 99 | while (Date.now() < until) { | |
| 100 | if (await probe(port)) return port; | |
| 101 | if (!groupAlive(proc.pid)) break; | |
| 102 | await Bun.sleep(50); | |
| 103 | } | |
| 104 | await this.stop(forge); | |
| 105 | return undefined; | |
| 106 | }, | |
| 107 | alive: (forge) => { | |
| 108 | const pid = pidOf(forge); | |
| 109 | return pid !== undefined && groupAlive(pid); | |
| 110 | }, | |
| 111 | async stop(forge) { | |
| 112 | const pid = pidOf(forge); | |
| 113 | const r = running.get(forge); | |
| 114 | running.delete(forge); | |
| 115 | rmSync(pidFile(forge), { force: true }); | |
| 116 | if (pid === undefined) return; | |
| 117 | try { | |
| 118 | process.kill(-pid, "SIGKILL"); | |
| 119 | } catch { | |
| 120 | // Already gone. | |
| 121 | } | |
| 122 | await r?.exited.catch(() => 0); | |
| 123 | }, | |
| 124 | }; | |
| 125 | } | |
| 126 | ||
| 127 | const registered = new WeakMap<App, Map<string, Machine>>(); | |
| 128 | const registryOf = (app: App): Map<string, Machine> => { | |
| 129 | let m = registered.get(app); | |
| 130 | if (m === undefined) registered.set(app, (m = new Map())); | |
| 131 | return m; | |
| 132 | }; | |
| 133 | ||
| 134 | /** | |
| 135 | * Tests and a driver of another kind put a machine here; the declared ones are made on first read. | |
| 136 | */ | |
| 137 | export const registerMachine = (app: App, m: Machine): void => void registryOf(app).set(m.name, m); | |
| 138 | export const forgetMachines = (app: App): void => void registered.delete(app); | |
| 139 | ||
| 140 | /** The machines declared and registered, by name. */ | |
| 141 | export function machinesOf(app: App, env: Record<string, string | undefined> = process.env): Machine[] { | |
| 142 | const known = registryOf(app); | |
| 143 | for (const part of (env["FORGE_MACHINES"] ?? "").split(",")) { | |
| 144 | const at = part.indexOf("="); | |
| 145 | const name = part.slice(0, at).trim(); | |
| 146 | const root = part.slice(at + 1).trim(); | |
| 147 | if (at > 0 && CHILD_NAME.test(name) && name !== "here" && root.startsWith("/") && !known.has(name)) known.set(name, processMachine(name, root)); | |
| 148 | } | |
| 149 | return [...known.values()]; | |
| 150 | } | |
| 151 | ||
| 152 | /** | |
| 153 | * A forge that is removed: it is ended where it ran and its place in the router goes. Its data | |
| 154 | * there goes too (the removal says it removes the data); undefined when it ran here. | |
| 155 | */ | |
| 156 | export async function dropFromMachine(app: App, name: string, bodyId: string): Promise<string | undefined> { | |
| 157 | const route = clearRoute(app, name); | |
| 158 | if (route === undefined || !BODY_ID.test(bodyId)) return undefined; | |
| 159 | const machine = machinesOf(app).find((m) => m.name === route.machine); | |
| 160 | if (machine === undefined) return route.machine; | |
| 161 | await machine.stop(name); | |
| 162 | rmSync(join(machine.root, "children", bodyId), { recursive: true, force: true }); | |
| 163 | rmSync(join(machine.root, "spawn", `${name}.json`), { force: true }); | |
| 164 | return undefined; | |
| 165 | } |
src/spawn/manage.ts +3
| @@ -17,6 +17,7 @@ import { forgetTouched, noteLedger, sleepChild } from "./host.ts"; | ||
| 17 | 17 | import { resizeRefusal } from "./quota.ts"; |
| 18 | 18 | import { isSize, SIZE_ORDER, SIZES, type Size } from "./sizes.ts"; |
| 19 | 19 | import { retireBody } from "./door.ts"; |
| 20 | import { dropFromMachine } from "./machines.ts"; | |
| 20 | 21 | import { CHILD_NAME } from "./placement.ts"; |
| 21 | 22 | import { switchOwnCode } from "./own_code.ts"; |
| 22 | 23 | |
| @@ -39,6 +40,8 @@ export async function removeForge(app: App, name: string): Promise<Managed> { | ||
| 39 | 40 | const child = await find(app, name); |
| 40 | 41 | if (child === undefined) return { ok: false, says: `no forge named ${name}` }; |
| 41 | 42 | await sleepChild(app, name); |
| 43 | // On another machine (`move_machine.ts`): ended there, its router entry and data there removed. | |
| 44 | await dropFromMachine(app, name, child.bodyId); | |
| 42 | 45 | await rm(join(app.config.dataDir, "spawn", `${name}.json`), { force: true }); |
| 43 | 46 | await rm(childDirOf(app, child.bodyId), { recursive: true, force: true }); |
| 44 | 47 | // What this forge minted for it to read private apps ends with it: no pass will look at it again. |
src/spawn/move_machine.ts added +342
| @@ -0,0 +1,342 @@ | ||
| 1 | /** | |
| 2 | * Move a forge to another machine (#16859): copy, start, flip the router. In order, each step | |
| 3 | * safe to stop at: | |
| 4 | * | |
| 5 | * 1. check: the forge is a finished forge in its own cell (or on another machine), the machine | |
| 6 | * is one that was declared (`machines.ts`) and is not where it already is, the bucket takes a | |
| 7 | * write. Nothing changes. | |
| 8 | * 2. hold: from here its address says "waking up", and it is the only time it is unreachable. | |
| 9 | * 3. copy: it is stopped, its data and ledger are written to the bucket (`forge-moves/<name>/`) | |
| 10 | * and read back the same, then restored from the bucket into the target's root. | |
| 11 | * 4. start: the target runs it and it answers its health route. | |
| 12 | * 5. flip: the route table names the target (`routes.ts`); the hold ends, and the next request | |
| 13 | * goes there. The old place is stopped, never deleted: its data is the way back, and `to: | |
| 14 | * "here"` is the door back (a forge that moved to a machine and returns). | |
| 15 | * | |
| 16 | * Nothing is ever deleted to make room: data the target already holds for this forge (the way | |
| 17 | * back of an earlier move) is set aside beside it as `<dir>.before-<time>`, and put back when the | |
| 18 | * move fails. | |
| 19 | * | |
| 20 | * Any failure before the flip leaves the route as it was, takes the target's copy away and ends | |
| 21 | * the hold: the forge wakes where it was. A source that is a machine was stopped for the copy, so | |
| 22 | * it is started again there and the route follows its new port. The receipt says how long it was | |
| 23 | * unreachable and whether that was within the budget it was told (`MOVE_BUDGET_S`). | |
| 24 | * | |
| 25 | * `recoverForge` is the same from the last copy in the bucket when the machine it was on is gone: | |
| 26 | * the target restores the newest copy, starts it, and flips. `planRecover` says the copy, its | |
| 27 | * time and what is lost before. What was written after that copy is lost, and the receipt names | |
| 28 | * the copy's time; the copy is the move's own (a stream that writes continuously is not built). | |
| 29 | */ | |
| 30 | ||
| 31 | import { existsSync, mkdirSync, renameSync, statSync } from "node:fs"; | |
| 32 | import { rm } from "node:fs/promises"; | |
| 33 | import { join } from "node:path"; | |
| 34 | import type { App } from "../app.ts"; | |
| 35 | import { listChildren } from "../actions/spawn.ts"; | |
| 36 | import { sha256 } from "../kernel/hash.ts"; | |
| 37 | import { resolveDestination, type Destination } from "../snapshot/destination.ts"; | |
| 38 | import { ARCHIVE_MAX_BYTES, BODY_ID, packForge, unpackForge } from "./archive.ts"; | |
| 39 | import { holdClosed } from "./held_closed.ts"; | |
| 40 | import { sleepChild } from "./host.ts"; | |
| 41 | import { machinesOf, type Machine } from "./machines.ts"; | |
| 42 | import { childPublicUrl, CHILD_NAME, parentOrigin } from "./placement.ts"; | |
| 43 | import { clearRoute, routeOf, setRoute } from "./routes.ts"; | |
| 44 | ||
| 45 | /** How long a move may leave a forge unreachable, in seconds; the words say it before and after. */ | |
| 46 | export const MOVE_BUDGET_S = 60; | |
| 47 | ||
| 48 | /** The name that means this forge's own data root: the door back from a machine. */ | |
| 49 | export const HERE = "here"; | |
| 50 | ||
| 51 | export type MoveKind = "not_found" | "invalid" | "failed"; | |
| 52 | ||
| 53 | export interface MovePlan { | |
| 54 | readonly forge: string; | |
| 55 | /** "here" or a machine's name. */ | |
| 56 | readonly from: string; | |
| 57 | readonly to: string; | |
| 58 | /** Where the copy goes, in words. */ | |
| 59 | readonly via: string; | |
| 60 | readonly budgetS: number; | |
| 61 | readonly steps: readonly string[]; | |
| 62 | readonly says: string; | |
| 63 | } | |
| 64 | ||
| 65 | export interface MoveReceipt { | |
| 66 | readonly forge: string; | |
| 67 | readonly from: string; | |
| 68 | readonly to: string; | |
| 69 | readonly unreachableMs: number; | |
| 70 | readonly withinBudget: boolean; | |
| 71 | readonly copy: { readonly key: string; readonly bytes: number; readonly at: string }; | |
| 72 | readonly says: string; | |
| 73 | } | |
| 74 | ||
| 75 | export type Planned = { readonly ok: true; readonly plan: MovePlan } | { readonly ok: false; readonly kind: MoveKind; readonly says: string }; | |
| 76 | export type Moved = { readonly ok: true; readonly receipt: MoveReceipt; readonly says: string } | { readonly ok: false; readonly kind: MoveKind; readonly says: string }; | |
| 77 | ||
| 78 | export interface MoveOptions { | |
| 79 | readonly actorId?: string | undefined; | |
| 80 | readonly destination?: Destination | undefined; | |
| 81 | readonly machines?: readonly Machine[] | undefined; | |
| 82 | readonly now?: () => number; | |
| 83 | } | |
| 84 | ||
| 85 | /** Where a forge's data may be put: a machine, or this forge's own root. */ | |
| 86 | interface Place { | |
| 87 | readonly name: string; | |
| 88 | readonly root: string; | |
| 89 | readonly machine: Machine | undefined; | |
| 90 | } | |
| 91 | ||
| 92 | /** Forges being moved now, by app and name: a second ask is refused, not raced. */ | |
| 93 | const busyOf = new WeakMap<App, Set<string>>(); | |
| 94 | ||
| 95 | const bad = (kind: MoveKind, says: string) => ({ ok: false as const, kind, says }); | |
| 96 | const prefixOf = (name: string): string => `forge-moves/${name}/`; | |
| 97 | const mib = (n: number): string => `${(n / 1_048_576).toFixed(1)} MiB`; | |
| 98 | const hereOf = (app: App): Place => ({ name: HERE, root: app.config.dataDir, machine: undefined }); | |
| 99 | const placeOf = (m: Machine): Place => ({ name: m.name, root: m.root, machine: m }); | |
| 100 | ||
| 101 | export const moveWords = (budgetS = MOVE_BUDGET_S): string => | |
| 102 | `Its address says "waking up" for the few seconds it is copied, started and switched, and the budget is ${budgetS} s; if any step fails it stays where it is.`; | |
| 103 | ||
| 104 | /** The finished forge in its own cell, or the refusal. */ | |
| 105 | async function forgeOf(app: App, forge: string) { | |
| 106 | if (!CHILD_NAME.test(forge)) return bad("invalid", "forge names a forge sent from here"); | |
| 107 | const child = (await listChildren(app)).find((c) => c.name === forge); | |
| 108 | if (child === undefined) return bad("not_found", `no forge named ${forge}`); | |
| 109 | if (!child.done) return bad("invalid", `${forge} is still being made`); | |
| 110 | if (child.placement !== "cell") return bad("invalid", `${forge} runs inside this forge's process: move it into its own sandbox first`); | |
| 111 | if (!BODY_ID.test(child.bodyId)) return bad("invalid", `${forge} has no data directory to move`); | |
| 112 | return { ok: true as const, child }; | |
| 113 | } | |
| 114 | ||
| 115 | /** The place `to` names: a declared machine, or here. */ | |
| 116 | function placeNamed(app: App, to: string, machines: readonly Machine[], from: string) { | |
| 117 | if (to === HERE) return { ok: true as const, target: hereOf(app) }; | |
| 118 | const m = machines.find((x) => x.name === to); | |
| 119 | if (m !== undefined) return { ok: true as const, target: placeOf(m) }; | |
| 120 | const names = [...(from === HERE ? [] : [HERE]), ...machines.map((x) => x.name)]; | |
| 121 | return bad("invalid", names.length === 0 ? "no other machine is declared (FORGE_MACHINES)" : `to is one of: ${names.join(", ")}`); | |
| 122 | } | |
| 123 | ||
| 124 | async function check(app: App, forge: string, to: string, options: MoveOptions) { | |
| 125 | const f = await forgeOf(app, forge); | |
| 126 | if (!f.ok) return f; | |
| 127 | const machines = options.machines ?? machinesOf(app); | |
| 128 | const from = routeOf(app, forge)?.machine ?? HERE; | |
| 129 | const t = placeNamed(app, to, machines, from); | |
| 130 | if (!t.ok) return t; | |
| 131 | if (from === to) return bad("invalid", `${forge} is on ${to} already`); | |
| 132 | const source = from === HERE ? undefined : machines.find((m) => m.name === from); | |
| 133 | if (from !== HERE && source === undefined) return bad("invalid", `${forge} is on ${from}, which is not declared now; recover it instead`); | |
| 134 | const destination = options.destination ?? resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); | |
| 135 | if (destination === undefined) return bad("invalid", `${forge} was not moved: this forge has no backup destination to copy through (set one on the Backups page)`); | |
| 136 | return { ok: true as const, child: f.child, target: t.target, source, from, destination }; | |
| 137 | } | |
| 138 | ||
| 139 | /** What a move would do and promise; nothing changes. */ | |
| 140 | export async function planMove(app: App, forge: string, to: string, options: MoveOptions = {}): Promise<Planned> { | |
| 141 | const c = await check(app, forge, to, options); | |
| 142 | if (!c.ok) return c; | |
| 143 | const steps = [ | |
| 144 | `hold ${forge}'s address and stop it on ${c.from}`, | |
| 145 | `copy its data and ledger to ${c.destination.store.where} and read the copy back`, | |
| 146 | `restore the copy on ${to} and start it there`, | |
| 147 | `switch the router to ${to}; ${c.from} keeps its data as the way back`, | |
| 148 | ]; | |
| 149 | return { ok: true, plan: { forge, from: c.from, to, via: c.destination.store.where, budgetS: MOVE_BUDGET_S, steps, says: `This would move ${forge} from ${c.from} to ${to}. ${moveWords()} Nothing changed yet.` } }; | |
| 150 | } | |
| 151 | ||
| 152 | /** | |
| 153 | * Restore `body` into `place`, start the forge there (a machine), and say the port it answers on. | |
| 154 | * What the place already holds for this forge is set aside, never removed; a failure puts it back. | |
| 155 | */ | |
| 156 | async function bringUp(place: Place, name: string, bodyId: string, body: Uint8Array, url: string, at: string): Promise<{ port: number } | string> { | |
| 157 | const stage = join(place.root, ".moving", name); | |
| 158 | const extracted = await unpackForge(body, stage, name, bodyId); | |
| 159 | if (extracted === undefined) return "the copy is not a forge's archive"; | |
| 160 | const dir = join(place.root, "children", bodyId); | |
| 161 | const ledger = join(place.root, "spawn", `${name}.json`); | |
| 162 | const tag = `.before-${at.replace(/[-:.]/g, "").slice(0, 15)}`; | |
| 163 | mkdirSync(join(place.root, "children"), { recursive: true }); | |
| 164 | mkdirSync(join(place.root, "spawn"), { recursive: true }); | |
| 165 | const asideDir = existsSync(dir) ? `${dir}${tag}` : undefined; | |
| 166 | if (asideDir !== undefined) renameSync(dir, asideDir); | |
| 167 | // This forge's own ledger stays: it is the record of the forge, whichever place runs it. | |
| 168 | const asideLedger = place.machine !== undefined && existsSync(ledger) ? `${ledger}${tag}` : undefined; | |
| 169 | if (asideLedger !== undefined) renameSync(ledger, asideLedger); | |
| 170 | const undo = async (): Promise<void> => { | |
| 171 | await rm(dir, { recursive: true, force: true }); | |
| 172 | if (place.machine !== undefined) await rm(ledger, { force: true }); | |
| 173 | if (asideDir !== undefined) renameSync(asideDir, dir); | |
| 174 | if (asideLedger !== undefined) renameSync(asideLedger, ledger); | |
| 175 | }; | |
| 176 | if (existsSync(join(extracted, bodyId))) renameSync(join(extracted, bodyId), dir); | |
| 177 | else mkdirSync(dir, { recursive: true }); | |
| 178 | if (place.machine !== undefined) renameSync(join(extracted, `${name}.json`), ledger); | |
| 179 | await rm(stage, { recursive: true, force: true }); | |
| 180 | if (place.machine === undefined) return { port: 0 }; | |
| 181 | const port = await place.machine.start(name, bodyId, url); | |
| 182 | if (port === undefined) { | |
| 183 | await undo(); | |
| 184 | return `${place.name} did not start it`; | |
| 185 | } | |
| 186 | return { port }; | |
| 187 | } | |
| 188 | ||
| 189 | /** The flip: a machine's port in the table, or no entry when it is back here. */ | |
| 190 | const flip = (app: App, forge: string, place: Place, port: number, at: string): void => { | |
| 191 | if (place.machine === undefined) clearRoute(app, forge); | |
| 192 | else setRoute(app, forge, { machine: place.name, port, movedAt: at }); | |
| 193 | }; | |
| 194 | ||
| 195 | const receiptWords = (forge: string, from: string, to: string, ms: number, within: boolean, copyAt: string): string => | |
| 196 | `${forge} moved from ${from} to ${to}: unreachable ${(ms / 1000).toFixed(1)} s, ${within ? "within" : "over"} the ${MOVE_BUDGET_S} s budget; restored from the copy of ${copyAt}.`; | |
| 197 | ||
| 198 | function finish(app: App, kind: "forge.machine_moved" | "forge.recovered", forge: string, from: string, to: string, ms: number, copy: MoveReceipt["copy"], actorId?: string): Moved { | |
| 199 | const withinBudget = ms <= MOVE_BUDGET_S * 1000; | |
| 200 | const says = | |
| 201 | kind === "forge.machine_moved" | |
| 202 | ? receiptWords(forge, from, to, ms, withinBudget, copy.at) | |
| 203 | : `${forge} is back on ${to} after ${(ms / 1000).toFixed(1)} s of restoring, from the copy of ${copy.at}; whatever it wrote after that copy is lost.`; | |
| 204 | const payload = { forge, from, to, unreachableMs: ms, withinBudget, key: copy.key }; | |
| 205 | const actor = actorId === undefined ? {} : { actorId }; | |
| 206 | if (kind === "forge.machine_moved") app.bus.append({ kind: "forge.machine_moved", ...actor, payload }); | |
| 207 | else app.bus.append({ kind: "forge.recovered", ...actor, payload }); | |
| 208 | return { ok: true, says, receipt: { forge, from, to, unreachableMs: ms, withinBudget, copy, says } }; | |
| 209 | } | |
| 210 | ||
| 211 | async function claim<T>(app: App, forge: string, work: () => Promise<T>): Promise<T | ReturnType<typeof bad>> { | |
| 212 | let busy = busyOf.get(app); | |
| 213 | if (busy === undefined) busyOf.set(app, (busy = new Set())); | |
| 214 | if (busy.has(forge)) return bad("invalid", `${forge} is being moved already`); | |
| 215 | busy.add(forge); | |
| 216 | try { | |
| 217 | return await work(); | |
| 218 | } finally { | |
| 219 | busy.delete(forge); | |
| 220 | } | |
| 221 | } | |
| 222 | ||
| 223 | /** | |
| 224 | * The source was stopped for the copy and the move failed: start it again where it was, and let | |
| 225 | * the route follow its new port. The words say what became of it. | |
| 226 | */ | |
| 227 | async function wakeSource(app: App, forge: string, bodyId: string, source: Machine, at: string): Promise<string> { | |
| 228 | if (source.alive(forge)) return ""; | |
| 229 | const port = await source.start(forge, bodyId, childPublicUrl(forge, parentOrigin(app.config))).catch(() => undefined); | |
| 230 | if (port === undefined) return ` ${source.name} could not start it again: it is stopped there, and recover or move it when ${source.name} is back`; | |
| 231 | setRoute(app, forge, { machine: source.name, port, movedAt: at }); | |
| 232 | return ""; | |
| 233 | } | |
| 234 | ||
| 235 | /** The move: copy, start, flip. */ | |
| 236 | export function moveToMachine(app: App, forge: string, to: string, options: MoveOptions = {}): Promise<Moved> { | |
| 237 | return claim(app, forge, async () => { | |
| 238 | const c = await check(app, forge, to, options); | |
| 239 | if (!c.ok) return c; | |
| 240 | const now = options.now ?? Date.now; | |
| 241 | const { child, target, source, from, destination } = c; | |
| 242 | const t0 = now(); | |
| 243 | const at = new Date(t0).toISOString(); | |
| 244 | const release = holdClosed(app, child.bodyId); | |
| 245 | let stopped = false; | |
| 246 | try { | |
| 247 | const result = await copyAndFlip(); | |
| 248 | if (result.ok || source === undefined || !stopped) return result; | |
| 249 | return bad(result.kind, result.says + (await wakeSource(app, forge, child.bodyId, source, at))); | |
| 250 | } catch (error) { | |
| 251 | const woke = source !== undefined && stopped ? await wakeSource(app, forge, child.bodyId, source, at) : ""; | |
| 252 | return bad("failed", `${forge} was not moved: ${String(error).slice(0, 160)}; it stays on ${from}${woke}`); | |
| 253 | } finally { | |
| 254 | release(); | |
| 255 | } | |
| 256 | ||
| 257 | async function copyAndFlip(): Promise<Moved> { | |
| 258 | if (source === undefined) await sleepChild(app, forge); | |
| 259 | else { | |
| 260 | stopped = true; | |
| 261 | await source.stop(forge); | |
| 262 | } | |
| 263 | const fromRoot = source?.root ?? app.config.dataDir; | |
| 264 | const local = join(target.root, ".moving", `${forge}.tar.gz`); | |
| 265 | mkdirSync(join(target.root, ".moving"), { recursive: true }); | |
| 266 | const packed = await packForge(fromRoot, forge, child.bodyId, local); | |
| 267 | if (!packed.ok) return bad("failed", `${forge} was not moved: the copy could not be written (${packed.err}); it stays on ${from}`); | |
| 268 | const size = statSync(local).size; | |
| 269 | if (size > ARCHIVE_MAX_BYTES) { | |
| 270 | await rm(local, { force: true }); | |
| 271 | return bad("failed", `${forge} was not moved: its data is ${mib(size)}, over the ${mib(ARCHIVE_MAX_BYTES)} one copy holds; it stays on ${from}`); | |
| 272 | } | |
| 273 | const body = new Uint8Array(await Bun.file(local).arrayBuffer()); | |
| 274 | await rm(local, { force: true }); | |
| 275 | const key = `${prefixOf(forge)}${at.replace(/[-:.]/g, "").slice(0, 15)}-${sha256(body).slice(0, 8)}.tar.gz`; | |
| 276 | try { | |
| 277 | await destination.store.put(key, body); | |
| 278 | const back = await destination.store.get(key); | |
| 279 | if (back === undefined || back.length !== body.length || sha256(back) !== sha256(body)) throw new Error("the copy did not read back the same"); | |
| 280 | } catch (error) { | |
| 281 | return bad("failed", `${forge} was not moved: the copy at ${destination.store.where} failed (${String(error).slice(0, 160)}); it stays on ${from}`); | |
| 282 | } | |
| 283 | const up = await bringUp(target, forge, child.bodyId, body, childPublicUrl(forge, parentOrigin(app.config)), at); | |
| 284 | if (typeof up === "string") return bad("failed", `${forge} was not moved: ${up}; it stays on ${from}`); | |
| 285 | flip(app, forge, target, up.port, at); | |
| 286 | return finish(app, "forge.machine_moved", forge, from, to, now() - t0, { key, bytes: body.length, at }, options.actorId); | |
| 287 | } | |
| 288 | }); | |
| 289 | } | |
| 290 | ||
| 291 | /** What a recovery would restore, or the refusal; nothing changes. */ | |
| 292 | async function recoverCheck(app: App, forge: string, to: string, options: MoveOptions) { | |
| 293 | if (!CHILD_NAME.test(forge)) return bad("invalid", "forge names a forge sent from here"); | |
| 294 | const child = (await listChildren(app)).find((c) => c.name === forge); | |
| 295 | if (child === undefined || !BODY_ID.test(child.bodyId)) return bad("not_found", `no forge named ${forge}`); | |
| 296 | const machines = options.machines ?? machinesOf(app); | |
| 297 | const route = routeOf(app, forge); | |
| 298 | if (route === undefined) return bad("invalid", `${forge} is not on another machine`); | |
| 299 | const t = placeNamed(app, to, machines, route.machine); | |
| 300 | if (!t.ok) return t; | |
| 301 | const destination = options.destination ?? resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); | |
| 302 | if (destination === undefined) return bad("invalid", "this forge has no backup destination to restore from"); | |
| 303 | if (route.machine === to) return bad("invalid", `${forge} is on ${to} already`); | |
| 304 | const was = machines.find((m) => m.name === route.machine); | |
| 305 | if (was?.alive(forge) === true) return bad("invalid", `${route.machine} still runs ${forge}: move it instead`); | |
| 306 | const key = (await destination.store.list(prefixOf(forge))).sort().at(-1); | |
| 307 | if (key === undefined) return bad("failed", `${forge} has no copy in ${destination.store.where} to restore`); | |
| 308 | const stamp = /(\d{8}T\d{6})/.exec(key)?.[1] ?? "an earlier time"; | |
| 309 | return { ok: true as const, child, target: t.target, destination, route, key, stamp }; | |
| 310 | } | |
| 311 | ||
| 312 | /** What a recovery would do: the copy it restores, its time, and what is lost. Nothing changes. */ | |
| 313 | export async function planRecover(app: App, forge: string, to: string, options: MoveOptions = {}): Promise<Planned> { | |
| 314 | const c = await recoverCheck(app, forge, to, options); | |
| 315 | if (!c.ok) return c; | |
| 316 | const steps = [ | |
| 317 | `restore the newest copy, ${c.key}, from ${c.destination.store.where}`, | |
| 318 | `start ${forge} on ${to} and switch the router to it`, | |
| 319 | ]; | |
| 320 | const says = `This would restore ${forge} on ${to} from its newest copy, taken ${c.stamp}. Whatever it wrote after that copy is lost; ${c.route.machine} is not asked, and is not touched.`; | |
| 321 | return { ok: true, plan: { forge, from: c.route.machine, to, via: c.destination.store.where, budgetS: MOVE_BUDGET_S, steps, says: `${says} Nothing changed yet.` } }; | |
| 322 | } | |
| 323 | ||
| 324 | /** | |
| 325 | * The machine `forge` was on is gone: the newest copy in the bucket is restored on `to` and started | |
| 326 | * there. | |
| 327 | */ | |
| 328 | export function recoverForge(app: App, forge: string, to: string, options: MoveOptions = {}): Promise<Moved> { | |
| 329 | return claim(app, forge, async () => { | |
| 330 | const c = await recoverCheck(app, forge, to, options); | |
| 331 | if (!c.ok) return c; | |
| 332 | const now = options.now ?? Date.now; | |
| 333 | const t0 = now(); | |
| 334 | const body = await c.destination.store.get(c.key); | |
| 335 | if (body === undefined) return bad("failed", `the copy ${c.key} is gone from ${c.destination.store.where}`); | |
| 336 | const at = new Date(t0).toISOString(); | |
| 337 | const up = await bringUp(c.target, forge, c.child.bodyId, body, childPublicUrl(forge, parentOrigin(app.config)), at); | |
| 338 | if (typeof up === "string") return bad("failed", `${forge} was not recovered: ${up}`); | |
| 339 | flip(app, forge, c.target, up.port, at); | |
| 340 | return finish(app, "forge.recovered", forge, c.route.machine, to, now() - t0, { key: c.key, bytes: body.length, at: c.stamp }, options.actorId); | |
| 341 | }); | |
| 342 | } |
src/spawn/routes.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * The router's table (#16859): which machine holds a forge that is not on this one, and the | |
| 3 | * loopback port it answers on. `<data>/routes.json`, written whole by a rename, so a flip is one | |
| 4 | * step: the request before it went to the old place, the request after it to the new. A forge | |
| 5 | * with no entry runs here, as before. Read once per app and kept, the only writers being | |
| 6 | * `setRoute` and `clearRoute`. | |
| 7 | */ | |
| 8 | ||
| 9 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 10 | import { dirname, join } from "node:path"; | |
| 11 | import type { App } from "../app.ts"; | |
| 12 | ||
| 13 | export interface Route { | |
| 14 | readonly machine: string; | |
| 15 | readonly port: number; | |
| 16 | readonly movedAt: string; | |
| 17 | } | |
| 18 | ||
| 19 | const tables = new WeakMap<App, Map<string, Route>>(); | |
| 20 | ||
| 21 | const fileOf = (app: App): string => join(app.config.dataDir, "routes.json"); | |
| 22 | ||
| 23 | function table(app: App): Map<string, Route> { | |
| 24 | let t = tables.get(app); | |
| 25 | if (t !== undefined) return t; | |
| 26 | t = new Map(); | |
| 27 | try { | |
| 28 | const raw: unknown = JSON.parse(readFileSync(fileOf(app), "utf8")); | |
| 29 | if (typeof raw === "object" && raw !== null) | |
| 30 | for (const [name, r] of Object.entries(raw as Record<string, Partial<Route>>)) | |
| 31 | if (typeof r?.machine === "string" && Number.isInteger(r.port) && typeof r.movedAt === "string") | |
| 32 | t.set(name, { machine: r.machine, port: r.port as number, movedAt: r.movedAt }); | |
| 33 | } catch { | |
| 34 | // No table yet, or one that does not read: every forge is here. | |
| 35 | } | |
| 36 | tables.set(app, t); | |
| 37 | return t; | |
| 38 | } | |
| 39 | ||
| 40 | function save(app: App, t: Map<string, Route>): void { | |
| 41 | const file = fileOf(app); | |
| 42 | mkdirSync(dirname(file), { recursive: true }); | |
| 43 | const tmp = `${file}.${process.pid}.tmp`; | |
| 44 | writeFileSync(tmp, JSON.stringify(Object.fromEntries(t)), { mode: 0o600 }); | |
| 45 | renameSync(tmp, file); | |
| 46 | } | |
| 47 | ||
| 48 | export const routeOf = (app: App, name: string): Route | undefined => table(app).get(name); | |
| 49 | ||
| 50 | /** The flip: from now a request for `name` goes to `route`. */ | |
| 51 | export function setRoute(app: App, name: string, route: Route): void { | |
| 52 | const t = table(app); | |
| 53 | t.set(name, route); | |
| 54 | save(app, t); | |
| 55 | } | |
| 56 | ||
| 57 | /** Back here, or the forge is gone: no entry, so it runs here (or nowhere). The entry it had. */ | |
| 58 | export function clearRoute(app: App, name: string): Route | undefined { | |
| 59 | const t = table(app); | |
| 60 | const was = t.get(name); | |
| 61 | if (was === undefined) return undefined; | |
| 62 | t.delete(name); | |
| 63 | save(app, t); | |
| 64 | return was; | |
| 65 | } | |
| 66 | ||
| 67 | /** Tests: forget what was read, so the file is read again. */ | |
| 68 | export const forgetRoutes = (app: App): void => void tables.delete(app); |
src/tui/screens/forges.ts +57 −1
| @@ -23,7 +23,10 @@ import { archiveForge, archivedForges, destinationWords, restoreForge } from ".. | ||
| 23 | 23 | import { writeClientsCsv } from "../../spawn/clients_csv.ts"; |
| 24 | 24 | import { claimedWords, keepWords } from "../../spawn/keep_words.ts"; |
| 25 | 25 | import { changeLink, revokePreview, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts"; |
| 26 | import { machinesOf } from "../../spawn/machines.ts"; | |
| 26 | 27 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 28 | import { HERE, moveToMachine, planMove, planRecover, recoverForge } from "../../spawn/move_machine.ts"; | |
| 29 | import { routeOf } from "../../spawn/routes.ts"; | |
| 27 | 30 | import { readOwnCode } from "../../spawn/own_code.ts"; |
| 28 | 31 | import type { App } from "../../app.ts"; |
| 29 | 32 | import { undoable, type LinkInfo } from "../../spawn/claim.ts"; |
| @@ -230,6 +233,57 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 230 | 233 | }), |
| 231 | 234 | ); |
| 232 | 235 | }; |
| 236 | // The page's "Move to another machine" and its restore, through the same actions (`planMove`, | |
| 237 | // `moveToMachine`, `planRecover`, `recoverForge`): the plan and its budget first, the receipt | |
| 238 | // after. `here` is the way back. | |
| 239 | const machineOne = (recover: boolean): void => { | |
| 240 | const user = session?.user; | |
| 241 | if (session === undefined || user?.isAdmin !== true) return; | |
| 242 | const app = session.app; | |
| 243 | const declared = machinesOf(app); | |
| 244 | const items = rows | |
| 245 | .filter((r) => r.made && r.placement === "cell" && (!recover || routeOf(app, r.name) !== undefined)) | |
| 246 | .map((r) => ({ id: r.name, label: r.name, hint: routeOf(app, r.name)?.machine ?? "in its own sandbox" })); | |
| 247 | if (declared.length === 0) return ctx.toast("No other machine is declared (FORGE_MACHINES)"); | |
| 248 | if (items.length === 0) return ctx.toast(recover ? "No forge runs on another machine" : "No forge runs in a sandbox of its own"); | |
| 249 | ctx.push( | |
| 250 | pickerScreen(ctx, screen, { | |
| 251 | title: recover ? "Restore which forge from its newest copy?" : "Move which forge to another machine?", | |
| 252 | items, | |
| 253 | onPick: (ids) => { | |
| 254 | const name = ids[0]; | |
| 255 | if (name === undefined) return; | |
| 256 | const on = routeOf(app, name)?.machine ?? HERE; | |
| 257 | const places = [...(on === HERE ? [] : [{ id: HERE, label: HERE, hint: "this forge's own root" }]), ...declared.map((m) => ({ id: m.name, label: m.name, hint: m.root }))].filter((p) => p.id !== on); | |
| 258 | ctx.push( | |
| 259 | pickerScreen(ctx, screen, { | |
| 260 | title: `${recover ? "Restore" : "Move"} ${name} on which machine?`, | |
| 261 | items: places, | |
| 262 | onPick: (to) => { | |
| 263 | const target = to[0]; | |
| 264 | if (target === undefined) return; | |
| 265 | void (recover ? planRecover(app, name, target) : planMove(app, name, target)).then((plan) => { | |
| 266 | if (!plan.ok) return ctx.toast(plan.says, "danger"); | |
| 267 | ctx.push( | |
| 268 | confirmScreen(ctx, screen, { | |
| 269 | title: `${recover ? "Restore" : "Move"} ${name} on ${target}?`, | |
| 270 | body: [plan.plan.says, ...plan.plan.steps], | |
| 271 | actions: [{ label: recover ? "Restore it" : "Move it" }, { label: "Leave it" }], | |
| 272 | onChoose: (i) => { | |
| 273 | if (i !== 0) return; | |
| 274 | const run = recover ? recoverForge(app, name, target, { actorId: user.id }) : moveToMachine(app, name, target, { actorId: user.id }); | |
| 275 | void run.then((done) => ctx.toast(done.says, done.ok ? "success" : "danger")); | |
| 276 | }, | |
| 277 | }), | |
| 278 | ); | |
| 279 | }); | |
| 280 | }, | |
| 281 | }), | |
| 282 | ); | |
| 283 | }, | |
| 284 | }), | |
| 285 | ); | |
| 286 | }; | |
| 233 | 287 | // The page's "Raise to xlarge", through the same action (`resizeForge`): an admin's, after |
| 234 | 288 | // reading what it would do. |
| 235 | 289 | const raiseOne = (): void => { |
| @@ -270,7 +324,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 270 | 324 | }; |
| 271 | 325 | const screen: Screen = { |
| 272 | 326 | title: "Forges you sent", |
| 273 | keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")], | |
| 327 | keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["g"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")], | |
| 274 | 328 | render(area, s) { |
| 275 | 329 | const c = ctx.theme.c; |
| 276 | 330 | const w = Math.min(100, Math.max(30, area.w - 6)); |
| @@ -334,6 +388,8 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 334 | 388 | }), |
| 335 | 389 | ); |
| 336 | 390 | } else if (e.key === "m") sandboxOne(); |
| 391 | else if (e.key === "g") machineOne(false); | |
| 392 | else if (e.key === "v") machineOne(true); | |
| 337 | 393 | else if (e.key === "w") raiseOne(); |
| 338 | 394 | else if (e.key === "x" && session !== undefined) |
| 339 | 395 | choose("Remove which forge?", (name) => |
src/web/pages/forge_machine.ts added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | /** | |
| 2 | * Move a forge to another machine, on the page (#16859): `GET /forges/:name/machine` names the | |
| 3 | * machines this forge may move it to; with `?to=` it shows what the move would do and the budget, | |
| 4 | * and asks. `POST` does it and shows the receipt. The words are the plan's and the receipt's | |
| 5 | * (`spawn/move_machine.ts`), the same the MCP `forges` tool and the terminal say. `here` is the | |
| 6 | * way back to this forge's own root; a forge that is on a machine also offers `?recover=1`, the | |
| 7 | * restore from the bucket's last copy when that machine is gone, previewed with its own plan. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { machinesOf } from "../../spawn/machines.ts"; | |
| 12 | import { routeOf } from "../../spawn/routes.ts"; | |
| 13 | import { HERE, moveToMachine, planMove, planRecover, recoverForge } from "../../spawn/move_machine.ts"; | |
| 14 | import { notFoundPage, pageHead } from "../chrome.ts"; | |
| 15 | import { readForm } from "../form.ts"; | |
| 16 | import { html } from "../html.ts"; | |
| 17 | import { page } from "../layout.ts"; | |
| 18 | import { btn } from "../ui.ts"; | |
| 19 | ||
| 20 | const back = (name: string) => btn("Back to your forges", { href: `/forges#forge-${name}`, size: "sm" }); | |
| 21 | ||
| 22 | const choose = (name: string, machines: readonly string[], recover: boolean) => | |
| 23 | html`<form method="get" action="/forges/${name}/machine" data-machine-choose="${recover ? "recover" : "move"}"> | |
| 24 | <p>${recover ? html`Restore ${name}'s newest copy on:` : html`Move ${name} to:`}</p> | |
| 25 | ${recover ? html`<input type="hidden" name="recover" value="1" />` : null} | |
| 26 | <select name="to" aria-label="Machine">${machines.map((m) => html`<option value="${m}">${m}</option>`)}</select> | |
| 27 | ${btn("See what it would do", { size: "sm" })} | |
| 28 | </form>`; | |
| 29 | ||
| 30 | export async function forgeMachineForm(ctx: Ctx): Promise<Response> { | |
| 31 | const user = ctx.auth.user; | |
| 32 | if (!user?.isAdmin) return notFoundPage(ctx); | |
| 33 | const name = ctx.params["name"] ?? ""; | |
| 34 | const to = ctx.url.searchParams.get("to") ?? ""; | |
| 35 | const recover = ctx.url.searchParams.get("recover") === "1"; | |
| 36 | const on = routeOf(ctx.app, name)?.machine ?? HERE; | |
| 37 | const machines = [...(on === HERE ? [] : [HERE]), ...machinesOf(ctx.app).map((m) => m.name)].filter((m) => m !== on); | |
| 38 | const planned = to === "" ? undefined : recover ? await planRecover(ctx.app, name, to) : await planMove(ctx.app, name, to); | |
| 39 | const body = | |
| 40 | planned === undefined | |
| 41 | ? html`${choose(name, machines, false)}${on === HERE ? null : choose(name, machines, true)}` | |
| 42 | : planned.ok | |
| 43 | ? html`<p data-preview>${planned.plan.says}</p> | |
| 44 | <form method="post" action="/forges/${name}/machine"> | |
| 45 | <input type="hidden" name="to" value="${to}" /> | |
| 46 | ${recover ? html`<input type="hidden" name="recover" value="1" />` : null} | |
| 47 | ${btn(recover ? `Restore on ${to}` : `Move to ${to}`, { variant: "primary", title: `Via ${planned.plan.via}; ${recover ? "what it wrote after that copy is lost" : "it stays where it is if any step fails"}` })} | |
| 48 | </form>` | |
| 49 | : html`<p role="status" data-preview>${planned.says}</p>`; | |
| 50 | const response = page( | |
| 51 | { ctx, title: "Move to another machine", body: html`<div class="narrow-wide" data-forges>${pageHead(`Move ${name} to another machine`)}<section class="settings-block">${body}<p class="mt">${back(name)}</p></section></div>` }, | |
| 52 | planned !== undefined && !planned.ok ? 409 : 200, | |
| 53 | ); | |
| 54 | response.headers.set("cache-control", "no-store"); | |
| 55 | return response; | |
| 56 | } | |
| 57 | ||
| 58 | export async function forgeMachineSubmit(ctx: Ctx): Promise<Response> { | |
| 59 | const user = ctx.auth.user; | |
| 60 | if (!user?.isAdmin) return notFoundPage(ctx); | |
| 61 | const form = await readForm(ctx, "admin"); | |
| 62 | if (form instanceof Response) return form; | |
| 63 | const name = ctx.params["name"] ?? ""; | |
| 64 | const to = String(form.get("to") ?? ""); | |
| 65 | const recover = form.get("recover") === "1"; | |
| 66 | const done = recover ? await recoverForge(ctx.app, name, to, { actorId: user.id }) : await moveToMachine(ctx.app, name, to, { actorId: user.id }); | |
| 67 | const title = done.ok ? (recover ? "Forge restored" : "Forge moved") : recover ? "Forge not restored" : "Forge not moved"; | |
| 68 | const response = page( | |
| 69 | { ctx, title, body: html`<div class="narrow-wide" data-forges>${pageHead(title)}<section class="settings-block"><p role="status" data-moved="${done.ok ? "yes" : done.kind}">${done.says}</p><p class="mt">${back(name)}</p></section></div>` }, | |
| 70 | done.ok ? 200 : done.kind === "not_found" ? 404 : 409, | |
| 71 | ); | |
| 72 | response.headers.set("cache-control", "no-store"); | |
| 73 | return response; | |
| 74 | } |
src/web/pages/forges.ts +6 −2
| @@ -26,6 +26,7 @@ import { listChildren } from "../../actions/spawn.ts"; | ||
| 26 | 26 | import { ownCode, removeForge, resizeForge, stopForge, type Managed } from "../../spawn/manage.ts"; |
| 27 | 27 | import { sizesView } from "../../spawn/sizes.ts"; |
| 28 | 28 | import { readOwnCode } from "../../spawn/own_code.ts"; |
| 29 | import { machinesOf } from "../../spawn/machines.ts"; | |
| 29 | 30 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 30 | 31 | import { sealedAt } from "../../spawn/sealed.ts"; |
| 31 | 32 | import { countRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts"; |
| @@ -91,7 +92,7 @@ function activityNote(r: ClientRow, seenOnRow: boolean, now: number): Html | nul | ||
| 91 | 92 | |
| 92 | 93 | const XLARGE_SAYS = `${sizeWords("xlarge")}. ${sizesView().sizes.find((x) => x.size === "xlarge")?.says ?? ""}`; |
| 93 | 94 | |
| 94 | export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false, kept?: string): Html { | |
| 95 | export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false, kept?: string, machines = false): Html { | |
| 95 | 96 | const state = claimState(r); |
| 96 | 97 | const daysLeft = state === "no" ? daysLeftWords(r.link, now) : null; |
| 97 | 98 | const seen = seenOf(r); |
| @@ -183,6 +184,8 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f | ||
| 183 | 184 | : "Closes it here, starts it in a sandbox of its own, proves its data is intact; puts it back if anything fails", |
| 184 | 185 | })} |
| 185 | 186 | </form>` |
| 187 | : null}${r.made && r.placement === "cell" && machines | |
| 188 | ? btn("Move to another machine", { size: "sm", href: `/forges/${r.name}/machine`, title: "See what it would do and the budget, then confirm; it stays where it is if any step fails" }) | |
| 186 | 189 | : null}${r.made && r.size !== "xlarge" |
| 187 | 190 | ? html`<form method="post" action="/forges/${r.name}/size" class="inline"> |
| 188 | 191 | <input type="hidden" name="size" value="xlarge" /> |
| @@ -286,6 +289,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> { | ||
| 286 | 289 | const reachOf = timePhase(ctx.request, "reach", () => reachByForge(ctx.app, user)); |
| 287 | 290 | // Sizes that together pass the machine's memory are said in one line; nothing is refused for it. |
| 288 | 291 | const hostedKept = readHosted(ctx.app.config.dataDir); |
| 292 | const machines = machinesOf(ctx.app).length > 0; | |
| 289 | 293 | const over = memoryOverLine(forgesMemory(ctx.app, memoryOf(rows))); |
| 290 | 294 | const rendering = performance.now(); |
| 291 | 295 | const action = |
| @@ -335,7 +339,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> { | ||
| 335 | 339 | : state !== null && rows.length === 0 |
| 336 | 340 | ? html`<p data-empty>${CLIENT_STATE_EMPTY[state]}. <a href="/forges?sort=${sort}">All forges</a></p>` |
| 337 | 341 | : html`<ul class="list setting-list"> |
| 338 | ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(ctx.app.db, user, r.billTo), keptWords(hostedKept, r.name, now)))} | |
| 342 | ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(ctx.app.db, user, r.billTo), keptWords(hostedKept, r.name, now), machines))} | |
| 339 | 343 | </ul>`} |
| 340 | 344 | </section>`} |
| 341 | 345 | ${sealedLine(ctx)} |
test/helpers/machine-forge.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** | |
| 2 | * A stand-in for a forge on a machine (`test/move-machine.test.ts`): answers `/healthz` and says | |
| 3 | * what its data directory holds, and starts a `sleep` of its own so the process tree has more than | |
| 4 | * one process in it. The sleep's pid is written beside the data so a test can see it end. | |
| 5 | */ | |
| 6 | import { readFileSync, writeFileSync } from "node:fs"; | |
| 7 | import { join } from "node:path"; | |
| 8 | ||
| 9 | const data = process.env["FORGE_APP_DATA"]!; | |
| 10 | const sleeper = Bun.spawn(["sleep", "300"], { stdin: "ignore", stdout: "ignore", stderr: "ignore" }); | |
| 11 | writeFileSync(join(data, "sleeper.pid"), String(sleeper.pid)); | |
| 12 | Bun.serve({ | |
| 13 | hostname: "127.0.0.1", | |
| 14 | port: Number(process.env["PORT"]), | |
| 15 | fetch: (req) => | |
| 16 | new URL(req.url).pathname === "/healthz" ? new Response("ok") : new Response(`held: ${readFileSync(join(data, "note.txt"), "utf8")}`), | |
| 17 | }); |
test/move-machine-doors.test.ts added +152
| @@ -0,0 +1,152 @@ | ||
| 1 | /** | |
| 2 | * #16859: the move to another machine on the page and in the MCP `forges` tool says the same words: | |
| 3 | * the plan with its budget first, then the receipt; and the terminal's Forges screen binds it. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createToken } from "../src/core/tokens.ts"; | |
| 11 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 12 | import { forgetMachines, registerMachine, type Machine } from "../src/spawn/machines.ts"; | |
| 13 | import { MOVE_BUDGET_S } from "../src/spawn/move_machine.ts"; | |
| 14 | import { forgetRoutes, routeOf } from "../src/spawn/routes.ts"; | |
| 15 | import { clientRows } from "../src/spawn/clients.ts"; | |
| 16 | import { getUserById } from "../src/core/users.ts"; | |
| 17 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 18 | import { forgesScreen } from "../src/tui/screens/forges.ts"; | |
| 19 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 20 | import { settleApp } from "./helpers/tui.ts"; | |
| 21 | import { waitFor } from "./helpers/poll.ts"; | |
| 22 | import { adminCookie } from "./helpers/admin.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 25 | ||
| 26 | quietLogs(); | |
| 27 | ||
| 28 | const root = mkdtempSync(join(tmpdir(), "move-doors-")); | |
| 29 | let app: App; | |
| 30 | let servers: Servers; | |
| 31 | let token = ""; | |
| 32 | let cookie = ""; | |
| 33 | const started: string[] = []; | |
| 34 | const was = process.env["FORGE_SNAPSHOT_DIR"]; | |
| 35 | ||
| 36 | /** A machine that runs nothing: it says it started, on a port. */ | |
| 37 | const machine: Machine = { | |
| 38 | name: "m1", | |
| 39 | root: join(root, "m1"), | |
| 40 | start: async (name) => (started.push(name), 4999), | |
| 41 | alive: (name) => started.includes(name), | |
| 42 | stop: async () => {}, | |
| 43 | }; | |
| 44 | ||
| 45 | function forge(name: string): void { | |
| 46 | const data = app.config.dataDir; | |
| 47 | mkdirSync(join(data, "spawn"), { recursive: true }); | |
| 48 | mkdirSync(join(data, "children", `body-${name}`), { recursive: true }); | |
| 49 | writeFileSync(join(data, "children", `body-${name}`, "note.txt"), name); | |
| 50 | writeFileSync(join(data, "spawn", `${name}.json`), JSON.stringify({ name, bodyId: `body-${name}`, done: true, placement: "cell", size: "small", apps: [] })); | |
| 51 | } | |
| 52 | ||
| 53 | beforeAll(async () => { | |
| 54 | process.env["FORGE_SNAPSHOT_DIR"] = join(root, "bucket"); | |
| 55 | app = createApp({ dataDir: join(root, "parent"), url: "https://forge.test", port: 0 }); | |
| 56 | cookie = await adminCookie(app, { username: "alice", email: "[email protected]" }); | |
| 57 | const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!; | |
| 58 | token = createToken(app.db, alice.id, "t", "admin").token; | |
| 59 | forge("alpha"); | |
| 60 | forge("beta"); | |
| 61 | forgetMachines(app); | |
| 62 | registerMachine(app, machine); | |
| 63 | servers = await serve(app); | |
| 64 | }, 30_000); | |
| 65 | ||
| 66 | afterAll(() => { | |
| 67 | servers.stop(); | |
| 68 | app.close(); | |
| 69 | forgetMachines(app); | |
| 70 | forgetRoutes(app); | |
| 71 | if (was === undefined) delete process.env["FORGE_SNAPSHOT_DIR"]; | |
| 72 | else process.env["FORGE_SNAPSHOT_DIR"] = was; | |
| 73 | rmSync(root, { recursive: true, force: true }); | |
| 74 | }); | |
| 75 | ||
| 76 | test("the MCP tool previews, then moves and receipts", async () => { | |
| 77 | const seen = await mcpTool(servers.url, token, "forges", { action: "move", forge: "alpha", to: "m1" }); | |
| 78 | expect(seen.value.says).toContain(`budget is ${MOVE_BUDGET_S} s`); | |
| 79 | expect(routeOf(app, "alpha")).toBeUndefined(); | |
| 80 | const done = await mcpTool(servers.url, token, "forges", { action: "move", forge: "alpha", to: "m1", dryRun: false }); | |
| 81 | expect(done.value.says).toContain("alpha moved from here to m1"); | |
| 82 | expect(routeOf(app, "alpha")?.machine).toBe("m1"); | |
| 83 | const missing = await mcpTool(servers.url, token, "forges", { action: "move", forge: "alpha", to: "nowhere" }); | |
| 84 | expect(missing.error).toContain("m1"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("the page offers the move, previews it with the same words, and shows the receipt", async () => { | |
| 88 | const list = await (await fetch(`${servers.url}/forges`, { headers: { cookie } })).text(); | |
| 89 | expect(list).toContain('href="/forges/beta/machine"'); | |
| 90 | const preview = await (await fetch(`${servers.url}/forges/beta/machine?to=m1`, { headers: { cookie } })).text(); | |
| 91 | expect(preview).toContain(`budget is ${MOVE_BUDGET_S} s`); | |
| 92 | expect(routeOf(app, "beta")).toBeUndefined(); | |
| 93 | const res = await fetch(`${servers.url}/forges/beta/machine`, { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: new URLSearchParams({ to: "m1" }) }); | |
| 94 | expect(await res.text()).toContain("beta moved from here to m1"); | |
| 95 | expect(routeOf(app, "beta")?.machine).toBe("m1"); | |
| 96 | const again = await fetch(`${servers.url}/forges/beta/machine`, { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: new URLSearchParams({ to: "m1" }) }); | |
| 97 | expect(again.status).toBe(409); | |
| 98 | }); | |
| 99 | ||
| 100 | test("a cross-origin post does not move anything", async () => { | |
| 101 | forge("gamma"); | |
| 102 | const res = await fetch(`${servers.url}/forges/gamma/machine`, { method: "POST", headers: { cookie, origin: "https://evil.test" }, body: new URLSearchParams({ to: "m1" }) }); | |
| 103 | expect(res.status).toBeGreaterThanOrEqual(400); | |
| 104 | expect(routeOf(app, "gamma")).toBeUndefined(); | |
| 105 | }); | |
| 106 | ||
| 107 | test("the terminal's Forges screen drives the same plan and move on g", async () => { | |
| 108 | forge("epsilon"); | |
| 109 | const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!; | |
| 110 | const user = getUserById(app.db, alice.id)!; | |
| 111 | const terminal = headlessTerminal(140, 30); | |
| 112 | const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user }, { terminal, exitHooks: false }); | |
| 113 | tui.start(); | |
| 114 | await settleApp(tui); | |
| 115 | tui.push(forgesScreen(tui.ctx, await clientRows(app), session)); | |
| 116 | await settleApp(tui); | |
| 117 | const press = async (key: string): Promise<string> => (terminal.feed(key), await settleApp(tui), tui.screen.toText()); | |
| 118 | expect(await press("g")).toContain("Move which forge to another machine?"); | |
| 119 | // The picker's rows are alpha, beta, epsilon, gamma: epsilon is the third. | |
| 120 | await press("\x1b[B"); | |
| 121 | await press("\x1b[B"); | |
| 122 | await press("\r"); | |
| 123 | expect(tui.screen.toText()).toContain("on which machine?"); | |
| 124 | await press("\r"); | |
| 125 | const plan = tui.screen.toText(); | |
| 126 | expect(plan).toContain("Move epsilon on m1?"); | |
| 127 | expect(plan).toContain("This would move epsilon from here to m1."); | |
| 128 | expect(routeOf(app, "epsilon")).toBeUndefined(); | |
| 129 | await press("\r"); | |
| 130 | await waitFor(() => routeOf(app, "epsilon") !== undefined, { every: 20, within: 2000 }); | |
| 131 | expect(routeOf(app, "epsilon")?.machine).toBe("m1"); | |
| 132 | tui.stop(); | |
| 133 | }); | |
| 134 | ||
| 135 | test("a recovery is previewed by the MCP tool and the page with its own words, and changes nothing", async () => { | |
| 136 | const seen = await mcpTool(servers.url, token, "forges", { action: "recover", forge: "alpha", to: "here" }); | |
| 137 | expect(seen.error ?? "").toContain("still runs"); | |
| 138 | started.length = 0; | |
| 139 | const plan = await mcpTool(servers.url, token, "forges", { action: "recover", forge: "alpha", to: "here" }); | |
| 140 | expect(plan.error).toBeUndefined(); | |
| 141 | expect(plan.value.says).toContain("newest copy, taken"); | |
| 142 | expect(plan.value.says).toContain("is lost"); | |
| 143 | expect(routeOf(app, "alpha")?.machine).toBe("m1"); | |
| 144 | const page = await (await fetch(`${servers.url}/forges/alpha/machine?recover=1&to=here`, { headers: { cookie } })).text(); | |
| 145 | expect(page).toContain("newest copy, taken"); | |
| 146 | const choose = await (await fetch(`${servers.url}/forges/alpha/machine`, { headers: { cookie } })).text(); | |
| 147 | expect(choose).toContain('data-machine-choose="recover"'); | |
| 148 | expect(choose).toContain('<option value="here">'); | |
| 149 | const done = await fetch(`${servers.url}/forges/alpha/machine`, { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: new URLSearchParams({ to: "here", recover: "1" }) }); | |
| 150 | expect(await done.text()).toContain("alpha is back on here"); | |
| 151 | expect(routeOf(app, "alpha")).toBeUndefined(); | |
| 152 | }); |
test/move-machine.test.ts added +202
| @@ -0,0 +1,202 @@ | ||
| 1 | /** | |
| 2 | * #16859: a forge moves to another machine (copy through the bucket, start, flip the router) within | |
| 3 | * its stated budget, and when the machine it is on is killed, the forge comes back on another from | |
| 4 | * the last copy in the bucket. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { dirStore } from "../src/blob/store.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { answerFromCell } from "../src/spawn/host.ts"; | |
| 13 | import { forgetMachines, processMachine, registerMachine, type Machine } from "../src/spawn/machines.ts"; | |
| 14 | import { archiveForge } from "../src/spawn/archive.ts"; | |
| 15 | import { removeForge } from "../src/spawn/manage.ts"; | |
| 16 | import { MOVE_BUDGET_S, moveToMachine, planMove, planRecover, recoverForge } from "../src/spawn/move_machine.ts"; | |
| 17 | import { forgetRoutes, routeOf } from "../src/spawn/routes.ts"; | |
| 18 | import { waitFor } from "./helpers/poll.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const root = mkdtempSync(join(tmpdir(), "move-machine-")); | |
| 24 | const bucket = join(root, "bucket"); | |
| 25 | const destination = { source: "dir" as const, store: dirStore(bucket) }; | |
| 26 | let app: App; | |
| 27 | let a: Machine; | |
| 28 | let b: Machine; | |
| 29 | const BODY = "body-alpha"; | |
| 30 | ||
| 31 | const launch = ({ root: r, bodyId, port }: { root: string; bodyId: string; port: number }) => ({ | |
| 32 | script: join(import.meta.dir, "helpers", "machine-forge.ts"), | |
| 33 | env: { PATH: process.env["PATH"] ?? "", PORT: String(port), FORGE_APP_DATA: join(r, "children", bodyId) }, | |
| 34 | }); | |
| 35 | ||
| 36 | beforeAll(() => { | |
| 37 | const data = join(root, "parent"); | |
| 38 | app = createApp({ dataDir: data, url: "https://forge.test", port: 0 }); | |
| 39 | mkdirSync(join(data, "spawn"), { recursive: true }); | |
| 40 | mkdirSync(join(data, "children", BODY), { recursive: true }); | |
| 41 | writeFileSync(join(data, "children", BODY, "note.txt"), "first note"); | |
| 42 | writeFileSync( | |
| 43 | join(data, "spawn", "alpha.json"), | |
| 44 | JSON.stringify({ name: "alpha", bodyId: BODY, done: true, placement: "cell", size: "small", apps: [] }), | |
| 45 | ); | |
| 46 | a = processMachine("a", join(root, "a"), launch); | |
| 47 | b = processMachine("b", join(root, "b"), launch); | |
| 48 | forgetMachines(app); | |
| 49 | registerMachine(app, a); | |
| 50 | registerMachine(app, b); | |
| 51 | }); | |
| 52 | ||
| 53 | afterAll(async () => { | |
| 54 | await a.stop("alpha"); | |
| 55 | await b.stop("alpha"); | |
| 56 | await a.stop("delta"); | |
| 57 | await b.stop("delta"); | |
| 58 | app.close(); | |
| 59 | forgetMachines(app); | |
| 60 | forgetRoutes(app); | |
| 61 | rmSync(root, { recursive: true, force: true }); | |
| 62 | }); | |
| 63 | ||
| 64 | const alive = (pid: number): boolean => { | |
| 65 | try { | |
| 66 | process.kill(pid, 0); | |
| 67 | return true; | |
| 68 | } catch { | |
| 69 | return false; | |
| 70 | } | |
| 71 | }; | |
| 72 | ||
| 73 | test("a plan says what it would do and the budget, and refuses what it cannot do", async () => { | |
| 74 | const plan = await planMove(app, "alpha", "a", { destination }); | |
| 75 | expect(plan.ok && plan.plan.says).toContain(`budget is ${MOVE_BUDGET_S} s`); | |
| 76 | expect(plan.ok && plan.plan.steps.length).toBe(4); | |
| 77 | expect(routeOf(app, "alpha")).toBeUndefined(); | |
| 78 | const none = await planMove(app, "alpha", "nowhere", { destination }); | |
| 79 | expect(!none.ok && none.says).toContain("a, b"); | |
| 80 | const missing = await planMove(app, "ghost", "a", { destination }); | |
| 81 | expect(!missing.ok && missing.kind).toBe("not_found"); | |
| 82 | }); | |
| 83 | ||
| 84 | test("a move copies through the bucket, starts, flips the router, and is receipted within budget", async () => { | |
| 85 | const done = await moveToMachine(app, "alpha", "a", { destination }); | |
| 86 | expect(done.ok).toBe(true); | |
| 87 | if (!done.ok) return; | |
| 88 | expect(done.receipt.withinBudget).toBe(true); | |
| 89 | expect(done.says).toContain(`within the ${MOVE_BUDGET_S} s budget`); | |
| 90 | expect(routeOf(app, "alpha")?.machine).toBe("a"); | |
| 91 | expect(a.alive("alpha")).toBe(true); | |
| 92 | expect((await destination.store.list("forge-moves/alpha/")).length).toBe(1); | |
| 93 | // The router: a request for the forge now goes to the machine. | |
| 94 | const res = await answerFromCell(app, new Request("https://alpha--forge.test/"), "alpha"); | |
| 95 | expect(await res.text()).toBe("held: first note"); | |
| 96 | const again = await moveToMachine(app, "alpha", "a", { destination }); | |
| 97 | expect(!again.ok && again.says).toContain("already"); | |
| 98 | }); | |
| 99 | ||
| 100 | test("a machine's process tree is killed and the forge returns on another from its copy", async () => { | |
| 101 | const dataA = join(root, "a", "children", BODY); | |
| 102 | const sleeper = Number(readFileSync(join(dataA, "sleeper.pid"), "utf8")); | |
| 103 | expect(alive(sleeper)).toBe(true); | |
| 104 | // Still running there: recovery refuses to start a second copy. | |
| 105 | const early = await recoverForge(app, "alpha", "b", { destination }); | |
| 106 | expect(!early.ok && early.says).toContain("still runs"); | |
| 107 | await a.stop("alpha"); | |
| 108 | await waitFor(() => !alive(sleeper), { every: 20, within: 1000 }); | |
| 109 | expect(alive(sleeper)).toBe(false); | |
| 110 | expect(a.alive("alpha")).toBe(false); | |
| 111 | const back = await recoverForge(app, "alpha", "b", { destination }); | |
| 112 | expect(back.ok).toBe(true); | |
| 113 | expect(routeOf(app, "alpha")?.machine).toBe("b"); | |
| 114 | const res = await answerFromCell(app, new Request("https://alpha--forge.test/"), "alpha"); | |
| 115 | expect(await res.text()).toBe("held: first note"); | |
| 116 | }); | |
| 117 | ||
| 118 | test("recovery with no copy in the bucket says so and changes nothing", async () => { | |
| 119 | const empty = { source: "dir" as const, store: dirStore(join(root, "empty")) }; | |
| 120 | await b.stop("alpha"); | |
| 121 | const none = await recoverForge(app, "alpha", "a", { destination: empty }); | |
| 122 | expect(!none.ok && none.says).toContain("no copy"); | |
| 123 | expect(routeOf(app, "alpha")?.machine).toBe("b"); | |
| 124 | }); | |
| 125 | ||
| 126 | const BODY2 = "body-delta"; | |
| 127 | const note = (r: string): string => join(r, "children", BODY2, "note.txt"); | |
| 128 | ||
| 129 | function second(): void { | |
| 130 | const data = app.config.dataDir; | |
| 131 | mkdirSync(join(data, "children", BODY2), { recursive: true }); | |
| 132 | writeFileSync(note(data), "first note"); | |
| 133 | writeFileSync(join(data, "spawn", "delta.json"), JSON.stringify({ name: "delta", bodyId: BODY2, done: true, placement: "cell", size: "small", apps: [] })); | |
| 134 | } | |
| 135 | ||
| 136 | test("a failed move from a machine starts the forge there again and the route follows it", async () => { | |
| 137 | second(); | |
| 138 | const out = await moveToMachine(app, "delta", "a", { destination }); | |
| 139 | expect(out.ok).toBe(true); | |
| 140 | const before = routeOf(app, "delta")!; | |
| 141 | const refuses: Machine = { name: "c", root: join(root, "c"), start: async () => undefined, alive: () => false, stop: async () => {} }; | |
| 142 | const failed = await moveToMachine(app, "delta", "c", { destination, machines: [a, b, refuses] }); | |
| 143 | expect(!failed.ok && failed.says).toContain("did not start it"); | |
| 144 | expect(a.alive("delta")).toBe(true); | |
| 145 | expect(routeOf(app, "delta")?.machine).toBe("a"); | |
| 146 | expect(routeOf(app, "delta")?.port).not.toBe(before.port); | |
| 147 | const res = await answerFromCell(app, new Request("https://delta--forge.test/"), "delta"); | |
| 148 | expect(await res.text()).toBe("held: first note"); | |
| 149 | }); | |
| 150 | ||
| 151 | test("a host that restarted still finds the forge it started, so recovery does not make a second copy", async () => { | |
| 152 | const reborn = processMachine("a", join(root, "a"), launch); | |
| 153 | expect(reborn.alive("delta")).toBe(true); | |
| 154 | const early = await recoverForge(app, "delta", "b", { destination, machines: [reborn, b] }); | |
| 155 | expect(!early.ok && early.says).toContain("still runs"); | |
| 156 | const plan = await planRecover(app, "delta", "b", { destination, machines: [reborn, b] }); | |
| 157 | expect(!plan.ok && plan.says).toContain("still runs"); | |
| 158 | await reborn.stop("delta"); | |
| 159 | expect(reborn.alive("delta")).toBe(false); | |
| 160 | await a.stop("delta"); | |
| 161 | expect(a.alive("delta")).toBe(false); | |
| 162 | }); | |
| 163 | ||
| 164 | test("a recovery is previewed with its copy and what is lost, and changes nothing", async () => { | |
| 165 | const plan = await planRecover(app, "delta", "b", { destination }); | |
| 166 | expect(plan.ok && plan.plan.says).toContain("newest copy, taken"); | |
| 167 | expect(plan.ok && plan.plan.says).toContain("is lost"); | |
| 168 | expect(routeOf(app, "delta")?.machine).toBe("a"); | |
| 169 | expect(existsSync(join(root, "b", "children", BODY2))).toBe(false); | |
| 170 | }); | |
| 171 | ||
| 172 | test("a move back here sets aside what is there instead of deleting it", async () => { | |
| 173 | await moveToMachine(app, "delta", "b", { destination }).then((m) => expect(m.ok).toBe(true)); | |
| 174 | writeFileSync(note(join(root, "b")), "second note"); | |
| 175 | const back = await moveToMachine(app, "delta", "here", { destination }); | |
| 176 | expect(back.ok).toBe(true); | |
| 177 | expect(routeOf(app, "delta")).toBeUndefined(); | |
| 178 | expect(readFileSync(note(app.config.dataDir), "utf8")).toBe("second note"); | |
| 179 | const aside = readdirSync(join(app.config.dataDir, "children")).filter((n) => n.startsWith(`${BODY2}.before-`)); | |
| 180 | expect(aside.length).toBe(1); | |
| 181 | expect(readFileSync(join(app.config.dataDir, "children", aside[0]!, "note.txt"), "utf8")).toBe("first note"); | |
| 182 | expect(b.alive("delta")).toBe(false); | |
| 183 | // A move onto a machine that holds its old data sets that aside too. | |
| 184 | const again = await moveToMachine(app, "delta", "a", { destination }); | |
| 185 | expect(again.ok).toBe(true); | |
| 186 | expect(readdirSync(join(root, "a", "children")).filter((n) => n.startsWith(`${BODY2}.before-`)).length).toBe(1); | |
| 187 | }); | |
| 188 | ||
| 189 | test("removing a forge that is on a machine ends it there and clears its route", async () => { | |
| 190 | expect(a.alive("delta")).toBe(true); | |
| 191 | const gone = await removeForge(app, "delta"); | |
| 192 | expect(gone.ok).toBe(true); | |
| 193 | expect(routeOf(app, "delta")).toBeUndefined(); | |
| 194 | expect(a.alive("delta")).toBe(false); | |
| 195 | expect(JSON.parse(readFileSync(join(app.config.dataDir, "routes.json"), "utf8"))["delta"]).toBeUndefined(); | |
| 196 | }); | |
| 197 | ||
| 198 | test("a forge on a machine is not archived from its stale copy here", async () => { | |
| 199 | const out = await archiveForge(app, "alpha", { destination }); | |
| 200 | expect(out.ok).toBe(false); | |
| 201 | expect(out.says).toContain("move it back here"); | |
| 202 | }); |
test/spawn-sites.test.ts +2
| @@ -111,6 +111,8 @@ const SITES: Record<string, string> = { | ||
| 111 | 111 | "bun (process.execPath) on the forge's own child_db_reader.ts, a fixed argv with an empty environment; the directory asked about and what a request presented travel over the IPC channel, never argv", |
| 112 | 112 | "src/spawn/cell.ts": |
| 113 | 113 | "a child forge launched from a launch spec the parent built, wrapped by its cell", |
| 114 | "src/spawn/machines.ts": | |
| 115 | "bun (process.execPath) on the forge's own entry for a machine the operator declared in FORGE_MACHINES, a fixed argv with the machine's root in the environment; nothing from a request", | |
| 114 | 116 | "src/spawn/supervisor.ts": |
| 115 | 117 | "setsid with the forge's own bun and its own supervisor.ts, one control directory the host made as argv; nothing from a request", |
| 116 | 118 | "src/tui/screens/external.ts": |
new above
offline
HIGH:
runningis in memory only and the forge is detached, so after a host restartalive/stoplose the process. This allows two copies and breaks recovery's refusal. Persist the pid.