diff --git a/docs/CLI.md b/docs/CLI.md index ffbf72145..2f9efc7b6 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -2637,6 +2637,10 @@ token again with `simlock --gateway token create --role worker` and set it as that worker's `gateway.token`: a worker still holding an old token is refused with 401 and keeps redialling. +A gateway keeps its drained workers in `state.db` too, and does not start while +a `workers.json` sits in its folder. Nothing is imported from it: remove it, and +drain the workers again with `simlock worker drain`. + A daemon also does not start when `state.db` is damaged, when another Simlock daemon holds it locked for more than five seconds, or when it was written by a newer Simlock (the message names the file and what to do). The reason is diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 87af28747..45a7ea73b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -197,9 +197,8 @@ uplink upgrades from, so a gateway without it is a process nothing can reach and no worker can join — quietly overriding the operator's value would be worse than refusing it. -The gateway keeps one small file of its own beside `state.db`: -`workers.json`, owner-only, holding the ids of workers an operator has -drained. Drain is a decision about a machine rather than something the machine +The gateway keeps the ids of workers an operator has drained in its +`state.db`. Drain is a decision about a machine rather than something the machine reports, so it has to survive both the worker's reconnect and a gateway restart; every other part of a worker view is rebuilt from the worker itself. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 6073b5d0c..03ef76e6d 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -28,7 +28,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ works against either mode unchanged. - State lives on the worker (`state.db`, its registry tables written only by core's `Registry`). A gateway keeps only its tokens, its instance id and its drained-worker set on - disk; everything else is rebuilt from the workers that reconnect. + disk (`state.db`); everything else is rebuilt from the workers that reconnect. ## Modules diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 493899bf9..8b2da1dfa 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -101,7 +101,7 @@ platform runs the deferred reclaim (step 21.2). 1. Instance identity — `instance.json`. 2. `FleetLeaseIndex`, routing policy, - `GatewayService` (`workers.json`), `FleetLeaseCoordinator`, `DaemonServer` + `GatewayService` (drained workers in `state.db`), `FleetLeaseCoordinator`, `DaemonServer` with `GatewayDispatcher`. No registry, drivers, reaper or health monitor. 3. `DaemonServer.start`: claim → host load → `admin.token` → converge starts → the event history starts → HTTP starts (uplink listener on the same server). diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 5b2d5980f..357aa9cb1 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -117,13 +117,27 @@ export async function startDaemon( await waitFor(() => !existsSync(socketPath), { timeout: 10_000 }).catch(() => undefined); }; const start = async () => { + const readLog = () => readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => ""); + const before = (await readLog()).length; const started = await cli([...gatewayFlag, "daemon", "start"], env, { timeout: 30_000 }); - if (started.code === 0) return; + // why: `daemon start` exits 0 once the daemon answers from its socket, which can come before + // the daemon fails to bind its HTTP port and stops (#553). So a clean exit is not yet a start: + // wait for this start's own "HTTP gateway listening" or `EADDRINUSE` line (the log keeps the + // earlier starts' lines), and fail on the latter. + if (started.code === 0) { + await waitFor( + async () => { + const added = (await readLog()).slice(before); + return added.includes("EADDRINUSE") || added.includes('"HTTP gateway listening"'); + }, + { label: "the daemon's HTTP listener" }, + ); + if (!(await readLog()).slice(before).includes("EADDRINUSE")) return; + } // why: a failed start reports only what the CLI saw while polling the socket, and `dispose` // deletes this home with `daemon.log` — the only record of the cause the daemon itself wrote. // Read the tail here, before any caller's catch reaches `dispose`, and fail with both. - const log = await readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => ""); - const tail = log.split("\n").slice(-20).join("\n"); + const tail = (await readLog()).split("\n").slice(-20).join("\n"); expect(started.code, `daemon start failed: ${started.stderr}\n${tail}`).toBe(0); }; const dispose = async () => { diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index ab85432ac..aa5c4a6cc 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -279,16 +279,21 @@ async function buildEnv( expectEvents: (names, expectOptions) => expectEvents(env, names, expectOptions, gatewayFlag), async startDaemon() { const started = await cli([...gatewayFlag, "daemon", "start"], env); - // `daemon start` exits once the daemon answers `status.get`, which it does from its socket + // why: `daemon start` exits once the daemon answers `status.get`, which it does from its socket // claim on, but the daemon writes `admin.token` only after that claim (ADR 0003 §5). A CLI // that reads the file before it lands connects as agent, so an admin command run next // (`token create`, the teardown's `daemon stop`) fails FORBIDDEN. After a first start, // waiting for the file orders later CLI calls after the write; after a restart the previous - // run's file may still be there and passes the wait at once. + // run's file may still be there and passes the wait at once. A daemon that stops right after + // its claim (its HTTP port taken, `withHttpDaemon`) removes the file with its socket + // (`AdminSecretManager#remove`) before this poll can see it, so a gone socket ends the wait too. if (started.code === 0) { - await waitFor(() => existsSync(join(dataDirectory, "admin.token")), { - label: "admin.token written", - }); + await waitFor( + () => existsSync(join(dataDirectory, "admin.token")) || !existsSync(socketPath), + { + label: "admin.token written", + }, + ); } return started; }, diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index ec3be705c..aaa4cc678 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -36,7 +36,7 @@ The role (`StartDaemonOptions.role`; the entry reads it from `--gateway` through when `gateway.url` and `gateway.token` are both set → `DaemonServer` with `Dispatcher`. HTTP starts only when `http.enabled`. - **Gateway** — instance id → `TokenStore`, `AdminSecretManager` → `FleetLeaseIndex` - (requester prefix `gw::`) → `GatewayService` (uplink listener, `workers.json`) + (requester prefix `gw::`) → `GatewayService` (uplink listener, drained workers in `state.db`) → `FleetLeaseCoordinator` → `createAlerts` when `gateway.alerts.destinations` is not empty (before `start()`; stopped first in `stopAuxiliary`) → `DaemonServer` with `GatewayDispatcher`. HTTP always starts; the uplink upgrades on the same listener. diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index 16858d157..6cef9ad57 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -160,7 +160,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { /** * why: #119: a gateway that can be stopped and started again *as the same gateway* -- the same * `SIMLOCK_HOME` directory and the same `Filesystem` instance backing it, which is what - * `instance.json`, `workers.json` and the `tokens` table of `state.db` actually persisting across the restart depends + * `instance.json` and the `tokens` and `drained_workers` tables of `state.db` actually persisting across the restart depends * on (ADR §30, §8a). `startGateway` above deliberately hands each call a fresh * `MemoryFilesystem`, which is right for a test that starts one gateway once; this one needs * the state to survive the restart it is about to perform. @@ -401,7 +401,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { * scripted uplink `fleet-coordinator.test.ts` and `dispatcher.test.ts` already cover each * piece of in isolation (including §27a's ownership round trip, pinned there too). What only * this shape of test can catch: the gateway's own persisted state (`instance.json`, - * `workers.json`, and the join tokens in `state.db`) actually surviving a real `stop()`/`startDaemon()` cycle, and + * the drained workers and join tokens in `state.db`) actually surviving a real `stop()`/`startDaemon()` cycle, and * a real worker's own `GatewayUplink` actually redialling and reconnecting on its own backoff * once the new process is listening again. */ @@ -523,8 +523,8 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { { timeout: 15_000 }, ); - // C1 (round 1 review, #119): this is the assertion this test's own header comment promises - // and never made -- that `workers.json` actually survived the restart. A drained-but-absent + // why: C1 (round 1 review, #119): this is the assertion this test's own header comment promises + // and never made -- that the drain actually survived the restart. A drained-but-absent // worker has no `WorkerView` at all (a view is only ever built by `connected()`/`refresh()`, // never synthesized from the persisted drain set on its own), so the only way to observe the // restarted gateway's own on-disk state through the same `worker.list` the rest of this test @@ -533,7 +533,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { // had before (so its `instance.json`, and therefore its `workerId`, survives too), exactly as // `restartedGateway` reuses the gateway's own. Its view is built from nothing but this fresh // process's own `connected()` call plus whatever `restartedGateway` loaded from - // `workers.json` at startup -- there is no other way `drained` could come back `true` here. + // `state.db` at startup -- there is no other way `drained` could come back `true` here. const restartedWorkerB = await startWorker({ label: "worker-b", model: "Pixel-B", @@ -551,6 +551,14 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { }, { timeout: 15_000 }, ); + // why: `drained: true` is the flag; this proves the restarted gateway also keeps routing off the worker. + await expect( + restartedGateway.dispatch( + "lease.request", + { model: "Pixel-B", platform: "android", noWait: true }, + agentSession({ principal: "someone-else" }), + ), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); await restartedWorkerB.daemon.stop("test"); daemons.splice(daemons.indexOf(restartedWorkerB.daemon), 1); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 9aff03000..6c6a76f3b 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -3666,18 +3666,25 @@ describe("startDaemon state.db", () => { it.each([ [ "worker", + "tokens.json", "with the older Simlock, release every lease and run `simlock nuke --delete-devices`; then remove and start again.", ], [ "gateway", + "tokens.json", + "remove and start again; then create each worker's join token again with `simlock --gateway token create --role worker`, set it as that worker's `gateway.token`, and drain workers again.", + ], + [ + "gateway", + "workers.json", "remove and start again; then create each worker's join token again with `simlock --gateway token create --role worker`, set it as that worker's `gateway.token`, and drain workers again.", ], ] as const)( - "a %s started with tokens.json in its folder refuses with the old-file message and its step", - async (role, step) => { - const directory = await mkdtemp(join(tmpdir(), "simlock-main-old-tokens-")); + "a %s started with %s in its folder refuses with the old-file message and its step", + async (role, file, step) => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-old-file-")); temporaryDirectories.push(directory); - const oldFile = join(directory, "tokens.json"); + const oldFile = join(directory, file); await writeFile(oldFile, "[]", "utf8"); await expect(start({ dataDirectory: directory, role })).rejects.toMatchObject({ diff --git a/src/daemon/main.ts b/src/daemon/main.ts index efe4e7244..eb402860d 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -107,7 +107,8 @@ import { } from "../ports/index.js"; import { createRoutingPolicy, - FileDrainStore, + StateDrainStore, + drainedWorkersOwner, FleetLeaseCoordinator, FleetLeaseIndex, GatewayDispatcher, @@ -246,10 +247,10 @@ async function composeDaemon( // why: node:sqlite writes the real disk, so the state never goes through a daemon's injected filesystem filesystem: new NodeFilesystem(), logger: logger.child("state"), - oldFiles: role === "gateway" ? ["tokens.json"] : ["state.json", "tokens.json"], + oldFiles: role === "gateway" ? ["tokens.json", "workers.json"] : ["state.json", "tokens.json"], owners: role === "gateway" - ? [tokensOwner] + ? [tokensOwner, drainedWorkersOwner] : [registryOwner, tokensOwner, ...new Set(deviceDataTables.values())], sqlite: new NodeSqliteOpener(), upgradeStep: role === "gateway" ? GATEWAY_UPGRADE_STEP : WORKER_UPGRADE_STEP, @@ -797,11 +798,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise auth.authenticateUplink(credential), clock, - drainStore: new FileDrainStore({ - filesystem, - logger: logger.child("gateway"), - path: join(dataDirectory, "workers.json"), - }), + drainStore: new StateDrainStore({ database: state.database, logger: logger.child("gateway") }), eventBus, // ADR 0005 §15: this gateway's own cap, compared against every connected worker's own // reported one so the registry can warn when a worker's is lower. diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 796112d1b..9f1b2a64e 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -16,7 +16,7 @@ Flows: [device selection](../../docs/internal/flows/device-selection.md), [devic | `service.ts` | `GatewayService`: uplink listener, one `WorkerLink` per worker, 30 s tick | | `worker-link.ts` | One uplink, gateway side: admin client, view reads, event relay | | `worker-registry.ts` | `WorkerRegistry`: views, drain, retention, `worker.*` events | -| `drain-store.ts` | `FileDrainStore`: `workers.json`, the drained ids | +| `drain-store.ts` | `StateDrainStore`: the drained ids in the `drained_workers` table of `state.db`; `drainedWorkersOwner` | | `dispatcher.ts` | `GatewayDispatcher`: the contract's handlers, answered from the fleet; `alerts.test` through the `testDestination` option | | `fleet-coordinator.ts` | `FleetLeaseCoordinator`: admit, dispatch, retry, forward renew/release/exec | | `queue.ts` | `FleetQueue`: leasing's `WaitQueue`, two lines | @@ -119,7 +119,7 @@ views. `worker.install-component` fans out. `nuke.run`, `cleanup.run`, `doctor.r | Link: channels per side, accept, stall | 64, 30 s, 60 s | `../link/` constants | | Request records | 10 000, 10 min | `lease.maxRequestRecords`, `lease.requestRetentionMs` | -Persisted: `workers.json` (drained ids), the `tokens` table of `state.db`, `instance.json`. Nothing else. +Persisted: the `drained_workers` and `tokens` tables of `state.db`, `instance.json`. Nothing else. ## Rules diff --git a/src/gateway/drain-store.test.ts b/src/gateway/drain-store.test.ts index f2d2ffdd3..8daf349fc 100644 --- a/src/gateway/drain-store.test.ts +++ b/src/gateway/drain-store.test.ts @@ -1,105 +1,34 @@ import { describe, expect, it } from "vitest"; -import type { Logger } from "../ports/index.js"; -import { MemoryFilesystem } from "../ports/index.js"; -import { FileDrainStore } from "./drain-store.js"; +import { openMemoryStateDatabase } from "../auth/testing.js"; +import { drainedWorkersOwner, StateDrainStore } from "./drain-store.js"; -/** A minimal `Logger` that only records `error` calls -- everything this suite needs to assert - * the corrupt-file fallback logs loudly rather than swallowing silently. */ -function recordingLogger(): { - logger: Logger; - errors: Array<{ message: string; fields?: Record }>; -} { - const errors: Array<{ message: string; fields?: Record }> = []; - const logger: Logger = { - debug: () => undefined, - info: () => undefined, - warn: () => undefined, - error: (message, fields) => { - errors.push(fields === undefined ? { message } : { fields, message }); - }, - child: () => logger, - }; - return { errors, logger }; +async function drainStore() { + const { database } = await openMemoryStateDatabase([drainedWorkersOwner]); + return { database, store: new StateDrainStore({ database }) }; } -/** - * C1 (round 1 review, #119): `FileDrainStore` -- the on-disk half of ADR §8a/§9's "the only - * gateway state that survives a restart" -- had no test of its own anywhere in the repo. Every - * registry-level persistence test injects `MemoryDrainStore`, which exercises the `#drained` set, - * not the file; `gateway-fleet.e2e.test.ts`'s restart test is the only place the real store was - * even constructed, and it never read the file back either. This file closes that gap directly, - * over a `MemoryFilesystem` rather than the real disk, the same way every other persistence test - * in this codebase does. - */ -describe("FileDrainStore", () => { - const PATH = "/home/.simlock/workers.json"; - - it("round-trips an empty store as an empty array without touching the filesystem", async () => { - const filesystem = new MemoryFilesystem(); - const store = new FileDrainStore({ filesystem, path: PATH }); - - expect(await filesystem.exists(PATH)).toBe(false); +describe("StateDrainStore", () => { + it("save then load returns the same ids in the order saved, a later save replaces the set, and a fresh database loads none", async () => { + const { store } = await drainStore(); await expect(store.load()).resolves.toEqual([]); - }); - - it("saves drained worker ids as `{drained: [...]}` and loads them back, mode 0o600", async () => { - const filesystem = new MemoryFilesystem(); - const store = new FileDrainStore({ filesystem, path: PATH }); - - await store.save(["wrk_a", "wrk_b"]); - - expect(await filesystem.exists(PATH)).toBe(true); - const raw = await filesystem.readFile(PATH); - expect(JSON.parse(raw)).toEqual({ drained: ["wrk_a", "wrk_b"] }); - expect((await filesystem.stat(PATH)).mode).toBe(0o600); - - // A fresh store instance -- the same file, not the same object -- reading it back is the - // shape a real gateway restart depends on: a new process, same directory. - const reloaded = new FileDrainStore({ filesystem, path: PATH }); - await expect(reloaded.load()).resolves.toEqual(["wrk_a", "wrk_b"]); - }); - - it("a later save overwrites the file rather than merging with what was there before", async () => { - const filesystem = new MemoryFilesystem(); - const store = new FileDrainStore({ filesystem, path: PATH }); - await store.save(["wrk_a", "wrk_b"]); - await store.save(["wrk_b"]); - - await expect(store.load()).resolves.toEqual(["wrk_b"]); - }); + await store.save(["wrk_b", "wrk_a"]); + await expect(store.load()).resolves.toEqual(["wrk_b", "wrk_a"]); - it("falls back to an empty array, logging loudly, when the file holds invalid JSON", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/.simlock"); - await filesystem.writeFileAtomic(PATH, "not json at all"); - const { errors, logger } = recordingLogger(); - const store = new FileDrainStore({ filesystem, logger, path: PATH }); + await store.save(["wrk_c"]); + await expect(store.load()).resolves.toEqual(["wrk_c"]); + await store.save([]); await expect(store.load()).resolves.toEqual([]); - expect(errors).toHaveLength(1); - expect(errors[0]?.fields).toMatchObject({ path: PATH }); }); - it("falls back to an empty array when the file is valid JSON but `drained` is not an array", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/.simlock"); - await filesystem.writeFileAtomic(PATH, JSON.stringify({ drained: "wrk_a" })); - const store = new FileDrainStore({ filesystem, path: PATH }); + it("a save whose statement throws resolves, and a load that throws answers none", async () => { + const { database, store } = await drainStore(); + await store.save(["wrk_a"]); + database.exec("DROP TABLE drained_workers"); + await expect(store.save(["wrk_b"])).resolves.toBeUndefined(); await expect(store.load()).resolves.toEqual([]); }); - - it("drops non-string entries from `drained` rather than throwing", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/.simlock"); - await filesystem.writeFileAtomic( - PATH, - JSON.stringify({ drained: ["wrk_a", 7, null, "wrk_b"] }), - ); - const store = new FileDrainStore({ filesystem, path: PATH }); - - await expect(store.load()).resolves.toEqual(["wrk_a", "wrk_b"]); - }); }); diff --git a/src/gateway/drain-store.ts b/src/gateway/drain-store.ts index e49eb9835..8445b3ac7 100644 --- a/src/gateway/drain-store.ts +++ b/src/gateway/drain-store.ts @@ -1,61 +1,51 @@ /** - * The one thing a gateway persists (ADR 0005, Decision 3: the worker registry is gateway - * state): which workers an operator has drained. + * why: What a gateway persists of its worker registry (ADR 0005, Decision 3; ADR 0036 §1): which + * workers an operator has drained. * * Everything else on a view is rebuilt from the workers themselves on reconnect, which is why - * this file holds ids and nothing else. Drain cannot be rebuilt that way -- it is an operator's + * this table holds ids and nothing else. Drain cannot be rebuilt that way -- it is an operator's * decision about a machine, not a fact the machine reports -- and losing it is the one failure * mode that matters: a gateway restart, or a worker reconnecting after a reboot, would silently * put a machine that was taken out of service back into rotation. */ -import { dirname } from "node:path"; - -import type { Filesystem, Logger } from "../ports/index.js"; -import { NoopLogger } from "../ports/index.js"; - -/** why: Owner-only, like the other files that hold secrets or state (`admin.token`, - * `state.db`): the trust boundary is the OS user. */ -const WORKERS_FILE_MODE = 0o600; +import type { Logger, SqliteDatabase, SqliteSchemaOwner } from "../ports/index.js"; +import { inTransaction, NoopLogger } from "../ports/index.js"; export interface DrainStore { load(): Promise; save(drainedWorkerIds: readonly string[]): Promise; } -export interface FileDrainStoreOptions { - readonly filesystem: Filesystem; - /** `workers.json` under the gateway's data directory. */ - readonly path: string; +export const drainedWorkersOwner: SqliteSchemaOwner = { + migrations: ["CREATE TABLE drained_workers (worker_id TEXT PRIMARY KEY) STRICT;"], + name: "drained-workers", + version: 1, +}; + +export interface StateDrainStoreOptions { + readonly database: SqliteDatabase; readonly logger?: Logger; } -/** - * A tiny JSON file: `{"drained": ["wrk_a", "wrk_b"]}`. - * - * Read errors never stop a gateway starting. A corrupt or unreadable file means the gateway - * forgets which workers were drained -- bad, and logged loudly -- but refusing to start would - * take a whole fleet's *routing* offline to protect a flag on some of it, which is the worse - * trade. Write errors are logged and swallowed for the same reason: the drain is already in - * effect in memory, and failing the operator's `worker.drain` call after it took effect would - * be a lie in the other direction. +/** why: The drained ids in the gateway's `state.db`. A failing statement never stops the gateway: a + * read error forgets the drains and logs, a write error logs and is swallowed, because the drain + * already holds in memory and refusing to start would take a fleet's routing offline to protect a flag. */ -export class FileDrainStore implements DrainStore { +export class StateDrainStore implements DrainStore { readonly #logger: Logger; - constructor(private readonly options: FileDrainStoreOptions) { + constructor(private readonly options: StateDrainStoreOptions) { this.#logger = options.logger ?? new NoopLogger(); } async load(): Promise { - if (!(await this.options.filesystem.exists(this.options.path))) return []; try { - const parsed: unknown = JSON.parse(await this.options.filesystem.readFile(this.options.path)); - const drained = (parsed as { readonly drained?: unknown } | null)?.drained; - if (!Array.isArray(drained)) throw new Error("`drained` is not an array"); - return drained.filter((id): id is string => typeof id === "string"); + const rows = this.options.database + .prepare("SELECT worker_id FROM drained_workers ORDER BY rowid") + .all(); + return rows.map((row) => String(row["worker_id"])); } catch (error: unknown) { this.#logger.error("Could not read the gateway's worker registry; drains are forgotten", { - path: this.options.path, message: error instanceof Error ? error.message : String(error), }); return []; @@ -63,16 +53,15 @@ export class FileDrainStore implements DrainStore { } async save(drainedWorkerIds: readonly string[]): Promise { + const { database } = this.options; try { - await this.options.filesystem.mkdirp(dirname(this.options.path)); - await this.options.filesystem.writeFileAtomic( - this.options.path, - `${JSON.stringify({ drained: [...drainedWorkerIds] }, null, 2)}\n`, - { mode: WORKERS_FILE_MODE }, - ); + inTransaction(database, () => { + database.exec("DELETE FROM drained_workers"); + const insert = database.prepare("INSERT INTO drained_workers (worker_id) VALUES (?)"); + for (const id of drainedWorkerIds) insert.run(id); + }); } catch (error: unknown) { this.#logger.error("Could not persist the gateway's worker registry", { - path: this.options.path, message: error instanceof Error ? error.message : String(error), }); } diff --git a/src/gateway/index.ts b/src/gateway/index.ts index b5e3a2854..18de9f002 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -12,7 +12,7 @@ * *by* `GatewayService` and `GatewayDispatcher`, so nothing outside builds one directly, and * their own tests import their modules. */ -export { FileDrainStore } from "./drain-store.js"; +export { drainedWorkersOwner, StateDrainStore } from "./drain-store.js"; // fallow-ignore-next-line unused-type -- public port shape for anyone supplying their own store. export type { DrainStore } from "./drain-store.js"; export { GatewayDispatcher } from "./dispatcher.js"; diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index 8a8eb3870..aced2c1c0 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -879,11 +879,11 @@ describe("WorkerRegistry", () => { expect(workers.connected("wrk_1", undefined, undefined).drained).toBe(true); }); - // Hardening: the C1 test above is correct that retention must not clear a drain flag -- but + // why: Hardening: the C1 test above is correct that retention must not clear a drain flag -- but // once a view is gone, neither `setDrained` nor `undrain` can reach that flag either // (`UNKNOWN_WORKER`, no view to require). Before this fix, nothing could ever clear it // again: `remove` returned early on a missing view before touching `#drained`, leaving - // `workers.json` growing a permanent `true` for a worker that no longer exists -- M1's + // the drain store growing a permanent `true` for a worker that no longer exists -- M1's // "unbounded file" relocated, not closed. `remove` on that same id is the one command // already documented as a no-op-but-not-an-error for a forgotten worker; it must also be // the one that can still clear a flag stranded behind it. @@ -1024,8 +1024,8 @@ describe("WorkerRegistry", () => { expect(names(events)).not.toContain("worker.removed"); }); - // M1: `#forget` used to delete the view and leave the drain flag standing forever -- - // `workers.json` grew without bound, and a worker whose id was ever seen again would come + // why: M1: `#forget` used to delete the view and leave the drain flag standing forever -- + // the drain store grew without bound, and a worker whose id was ever seen again would come // back silently drained with no way to `undrain` it (there is no view to undrain). it("clears a removed worker's drain flag too, and persists that", async () => { const store = new MemoryDrainStore(); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 4f7451f9a..cdfc444b3 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -479,8 +479,7 @@ export class WorkerRegistry { return view; } - /** - * ADR 0005 §8: forgets a disconnected worker's view. A connected one is refused -- + /** why: ADR 0005 §8: forgets a disconnected worker's view. A connected one is refused -- * `worker.remove` on a live worker would forget a machine that announces itself again on its * very next frame, which is a confusing no-op rather than an operator action. An * `incompatible` worker counts as connected for this rule: its uplink is open, and removing @@ -492,7 +491,7 @@ export class WorkerRegistry { * holding an id with nothing left to view. Neither `setDrained` nor `undrain` can reach it at * that point (`#requireView` throws `UNKNOWN_WORKER`), which is exactly M1's "unbounded file" * relocated rather than closed: nothing could ever clear that flag again, short of editing - * `workers.json` by hand. `remove` on that same id is the one command already documented as + * the drain store by hand. `remove` on that same id is the one command already documented as * "no view to forget is fine" (`removed: false`) -- letting it also clear a leftover flag, * still answering `removed: false`, is what actually closes the file rather than moving the * leak. @@ -564,10 +563,9 @@ export class WorkerRegistry { for (const view of expired) await this.#forget(view, "retention", { clearDrain: false }); } - /** - * M1: on an operator `remove`, also clears this worker's drain flag and re-saves the store, if - * it had one. Without this, a removed worker's `true` survives in `workers.json` forever -- an - * unbounded file that silently re-drains the machine if its id is ever seen again, with + /** why: M1: on an operator `remove`, also clears this worker's drain flag and re-saves the store, if + * it had one. Without this, a removed worker's `true` survives in the drain store forever -- an + * unbounded table that silently re-drains the machine if its id is ever seen again, with * `undrain` unable to clear it in the meantime (`UNKNOWN_WORKER`, since there is no view to * undrain). "Forgotten" has to mean forgotten, not "forgotten except the one flag that matters * most." diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 32bb9274c..40d772842 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -372,8 +372,8 @@ function bearerToken(request: IncomingMessage): string | undefined { return secret === "" ? undefined : secret; } -/** P3: how long a claimed `workerId` or decoded label is allowed to be before either reaches - * anything -- the event bus (`worker.rejected`, `worker.connected`), a view, or `workers.json`. +/** why: P3: how long a claimed `workerId` or decoded label is allowed to be before either reaches + * anything -- the event bus (`worker.rejected`, `worker.connected`), a view, or the drain store. * Comfortably longer than any real hostname or label an operator would set, far short of the * ~16 KB a raw header can carry. */ const MAX_CLAIMED_FIELD_LENGTH = 128;