From a3b6c7ec3aa77858836f81b36865521c9ff0ba98 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 15 Oct 2026 15:24:24 +0200 Subject: [PATCH 1/5] test: agent-device's gateway side runs as an optional module (#598) --- src/agent-device/definition.ts | 1 + src/agent-device/gateway.test.ts | 76 +++++++ src/agent-device/gateway.ts | 7 + src/daemon/gateway-modules.test.ts | 316 +++++++++++++++++++++++++++++ src/lint-rules.test.ts | 29 +-- src/modules/conformance.test.ts | 37 +++- src/modules/fleet-types.test.ts | 21 ++ src/modules/index.ts | 7 + src/modules/testing.ts | 89 ++++++++ src/modules/types.ts | 58 +++++- 10 files changed, 614 insertions(+), 27 deletions(-) create mode 100644 src/agent-device/gateway.test.ts create mode 100644 src/agent-device/gateway.ts create mode 100644 src/daemon/gateway-modules.test.ts create mode 100644 src/modules/fleet-types.test.ts diff --git a/src/agent-device/definition.ts b/src/agent-device/definition.ts index 4031f01c9..aaa6fc30c 100644 --- a/src/agent-device/definition.ts +++ b/src/agent-device/definition.ts @@ -24,6 +24,7 @@ export const agentDeviceModule: OptionalModuleDefinition import("./gateway.js"), loadWorker: () => import("./worker.js"), name: "agent-device", }; diff --git a/src/agent-device/gateway.test.ts b/src/agent-device/gateway.test.ts new file mode 100644 index 000000000..dbb7712c0 --- /dev/null +++ b/src/agent-device/gateway.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; + +import type { WorkerView } from "../modules/index.js"; +import { fakeGatewayContext } from "../modules/testing.js"; +import { agentDeviceModule } from "./definition.js"; + +const noWorker = "no worker connected to this gateway can serve agent-device"; + +function viewOf(overrides: Record = {}): WorkerView { + return { + capabilities: [{ name: "agent-device", state: "available" }], + catalog: [], + catalogReadAt: 1_000, + connection: "connected", + drained: false, + id: "w-1", + label: "w1", + lease: { maxTtlMs: 600_000 }, + ...overrides, + } as unknown as WorkerView; +} + +async function healthThroughGateway(served: readonly WorkerView[]) { + const { ctx, relayed } = await fakeGatewayContext( + "agent-device", + agentDeviceModule.config.defaults, + { + relay: () => Response.json({ ok: true, service: "agent-device-proxy" }), + serving: served, + }, + ); + const loaded = await agentDeviceModule.loadGateway?.(); + const module = loaded?.createGateway(ctx); + const handler = module?.mount?.({ dispatch: () => Promise.reject(new Error("unused")) }); + const answer = await handler?.(new Request("http://gateway.test/v1/agent-device/health"), { + requesterId: "tok_one", + role: "agent", + }); + return { body: await answer?.text(), relayed }; +} + +describe("agent-device's gateway side", () => { + it("a worker whose view has no lease.maxTtlMs is not served by agent-device's fleet port, while the same view with it is", async () => { + const served = await healthThroughGateway([viewOf()]); + expect(served.relayed.map((call) => call.workerId)).toEqual(["w-1"]); + expect(served.body).toContain("agent-device-proxy"); + + const unknown = await healthThroughGateway([viewOf({ lease: undefined })]); + + expect(unknown.relayed).toEqual([]); + expect(unknown.body).toContain(noWorker); + }); + + it("a worker whose catalog is unread, and a drained one, are not offered to a new allocate, while the same worker read and not drained is", async () => { + expect((await healthThroughGateway([viewOf()])).relayed).toHaveLength(1); + + const unread = await healthThroughGateway([viewOf({ catalogReadAt: undefined })]); + const drained = await healthThroughGateway([viewOf({ drained: true })]); + + expect([unread.relayed, drained.relayed]).toEqual([[], []]); + expect([unread.body, drained.body]).toEqual([ + expect.stringContaining(noWorker), + expect.stringContaining(noWorker), + ]); + }); + + it("agent-device's definition has a gateway side whose mount answers under /v1/agent-device", async () => { + const { ctx } = await fakeGatewayContext("agent-device", agentDeviceModule.config.defaults); + const loaded = await agentDeviceModule.loadGateway?.(); + + const module = loaded?.createGateway(ctx); + + expect(module?.mount).toBeTypeOf("function"); + expect(module?.hooks?.beforeDrain).toBeTypeOf("function"); + }); +}); diff --git a/src/agent-device/gateway.ts b/src/agent-device/gateway.ts new file mode 100644 index 000000000..2b380ee4d --- /dev/null +++ b/src/agent-device/gateway.ts @@ -0,0 +1,7 @@ +import type { GatewayContext, GatewayModule } from "../modules/index.js"; +import type { AgentDeviceModuleConfig } from "./definition.js"; + +// why: placeholder; the gateway side builds its fleet port and front here once green moves them out of main.ts. +export function createGateway(_ctx: GatewayContext): GatewayModule { + return {}; +} diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts new file mode 100644 index 000000000..ac57a10a1 --- /dev/null +++ b/src/daemon/gateway-modules.test.ts @@ -0,0 +1,316 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { agentDeviceModuleWith } from "../agent-device/testing.js"; +import { FakeDriver } from "../core/testing.js"; +import type { GatewayModule, OptionalModuleDefinition } from "../modules/index.js"; +import { fakeModule, type FakeModule } from "../modules/testing.js"; +import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { startDaemon, type StartDaemonOptions } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +const admin = { + manageEventSubscription: () => undefined, + principal: "test-operator", + role: "admin", +} as const; + +const daemons: DaemonServer[] = []; +const directories: string[] = []; + +afterEach(async () => { + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test").catch(() => undefined))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); +}); + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +function definitionsOf(...modules: FakeModule[]): OptionalModuleDefinition[] { + return modules.map((module) => module.definition as OptionalModuleDefinition); +} + +interface Gateway { + readonly daemon: DaemonServer; + readonly clock: FakeClock; + readonly sink: MemoryLogSink; + readonly origin: string; + readonly port: number; + readonly agentSecret: string; + readonly start: () => Promise; +} + +function gatewayOptions( + modules: readonly OptionalModuleDefinition[], + on: readonly string[], + directory: string, + port: number, + clock: FakeClock, + sink: MemoryLogSink, +): StartDaemonOptions { + return { + clock, + configOverrides: { + capabilities: Object.fromEntries(on.map((name) => [name, { enabled: true }])), + http: { enabled: true, host: "127.0.0.1", port }, + mode: "gateway", + }, + dataDirectory: directory, + filesystem: new MemoryFilesystem(), + hostLoadProbe: null, + logger: new JsonLinesLogger({ clock, level: "debug", sink }), + optionalModules: modules, + statePath: join(directory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions; +} + +async function startGateway( + modules: readonly OptionalModuleDefinition[], + on: readonly string[], +): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-gw-modules-")); + directories.push(directory); + const clock = new FakeClock(1_000); + const sink = new MemoryLogSink(); + const port = await freeLoopbackPort(); + const start = async () => { + const daemon = await startDaemon(gatewayOptions(modules, on, directory, port, clock, sink)); + daemons.push(daemon); + return daemon; + }; + const daemon = await start(); + const agent = await daemon.dispatch("token.create", { label: "agent", role: "agent" }, admin); + return { + agentSecret: agent.secret, + clock, + daemon, + origin: `http://127.0.0.1:${String(port)}`, + port, + sink, + start, + }; +} + +async function joinWorker( + gateway: Gateway, + modules: readonly OptionalModuleDefinition[], + on: readonly string[], + label: string, +): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-gw-worker-")); + directories.push(directory); + const { secret } = await gateway.daemon.dispatch( + "token.create", + { label, role: "worker" }, + admin, + ); + const worker = await startDaemon({ + clock: gateway.clock, + configOverrides: { + capabilities: Object.fromEntries(on.map((name) => [name, { enabled: true }])), + gateway: { label, token: secret, url: `ws://127.0.0.1:${String(gateway.port)}` }, + }, + dataDirectory: directory, + drivers: [ + new FakeDriver({ availableOsVersions: ["26.5"], clock: gateway.clock, platform: "ios" }), + ], + filesystem: new MemoryFilesystem(), + hostLoadProbe: null, + optionalModules: modules, + statePath: join(directory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions); + daemons.push(worker); + await vi.waitFor( + async () => { + const { workers } = await gateway.daemon.dispatch("worker.list", {}, admin); + const view = workers.find((entry) => entry.label === label); + expect(view?.connection).toBe("connected"); + expect(view?.capabilities).toBeDefined(); + }, + { timeout: 10_000 }, + ); + return worker; +} + +function get(gateway: Gateway, path: string): Promise { + return fetch(`${gateway.origin}${path}`, { + headers: { authorization: `Bearer ${gateway.agentSecret}`, connection: "close" }, + }); +} + +const mountPong = () => () => Promise.resolve(new Response("pong")); +const pong: GatewayModule = { mount: mountPong }; + +describe("a gateway's optional modules", () => { + it("a gateway with agent-device off mounts no /v1/agent-device, and never calls agent-device's loadGateway, while one with it on does", async () => { + const definition = agentDeviceModuleWith({}); + const loadGateway = vi.spyOn(definition, "loadGateway"); + const on = await startGateway([definition], ["agent-device"]); + expect((await get(on, "/v1/agent-device/health")).status).toBe(200); + expect(loadGateway).toHaveBeenCalledTimes(1); + await on.daemon.stop("test"); + loadGateway.mockClear(); + + const off = await startGateway([definition], []); + + expect((await get(off, "/v1/agent-device/health")).status).toBe(404); + expect(loadGateway).not.toHaveBeenCalled(); + }); + + it("a module turned on with no loadGateway is never loaded on a gateway, and mounts nothing, while one with it is mounted under its name", async () => { + const bare = fakeModule({ name: "bare" }); + const sided = fakeModule({ gateway: { module: pong }, name: "sided" }); + + const gateway = await startGateway(definitionsOf(bare, sided), ["bare", "sided"]); + + expect(await (await get(gateway, "/v1/sided/x")).text()).toBe("pong"); + expect((await get(gateway, "/v1/bare/x")).status).toBe(404); + expect({ loads: bare.loads, gatewayLoads: sided.gatewayLoads }).toEqual({ + gatewayLoads: 1, + loads: 0, + }); + }); + + it("a loadGateway() that throws, and a createGateway that throws, each stop the gateway's start with an error naming the module", async () => { + const loading = fakeModule({ + gateway: { loadError: new Error("no such file") }, + name: "loady", + }); + const creating = fakeModule({ + gateway: { createError: new Error("bad section") }, + name: "makey", + }); + + await expect(startGateway(definitionsOf(loading), ["loady"])).rejects.toThrow(/loady/); + await expect(startGateway(definitionsOf(creating), ["makey"])).rejects.toThrow(/makey/); + }); + + it("a fake gateway module's relay sends with its own name as the target, and no other", async () => { + const seen: string[] = []; + const answering = (name: string) => () => { + seen.push(name); + return Promise.resolve(new Response(`from ${name}`)); + }; + const mine = fakeModule({ + gateway: { module: pong }, + name: "mine", + relayTarget: answering("mine"), + }); + const other = fakeModule({ name: "other", relayTarget: answering("other") }); + const gateway = await startGateway(definitionsOf(mine), ["mine"]); + await joinWorker(gateway, definitionsOf(mine, other), ["mine", "other"], "w1"); + expect(mine.gatewayCreates).toBe(1); + const context = mine.gatewayContexts[0]; + const [view] = context?.workers() ?? []; + + const answer = await context?.relay(view?.id ?? "", new Request("http://relay.test/x"), "t"); + + expect(await answer?.text()).toBe("from mine"); + expect(seen).toEqual(["mine"]); + }); + + it("a fake gateway module's serving() lists only connected workers whose capability named after it is available, a drained one included", async () => { + const mine = fakeModule({ gateway: { module: pong }, name: "mine" }); + const gateway = await startGateway(definitionsOf(mine), ["mine"]); + await joinWorker(gateway, definitionsOf(mine), ["mine"], "serves"); + await joinWorker(gateway, definitionsOf(mine), [], "off"); + const gone = await joinWorker(gateway, definitionsOf(mine), ["mine"], "gone"); + await joinWorker(gateway, definitionsOf(mine), ["mine"], "drained"); + const { workers } = await gateway.daemon.dispatch("worker.list", {}, admin); + const idOf = (label: string) => workers.find((entry) => entry.label === label)?.id ?? ""; + await gateway.daemon.dispatch("worker.drain", { workerId: idOf("drained") }, admin); + await gone.stop("test"); + await vi.waitFor(async () => { + const listed = await gateway.daemon.dispatch("worker.list", {}, admin); + expect(listed.workers.find((entry) => entry.label === "gone")?.connection).toBe( + "disconnected", + ); + }); + + expect(mine.gatewayCreates).toBe(1); + const serving = mine.gatewayContexts[0]?.serving().map((view) => view.id); + + expect(serving?.sort()).toEqual([idOf("serves"), idOf("drained")].sort()); + }); + + it("a fake gateway module's beforeDrain runs while the gateway's HTTP front still answers", async () => { + let during: number | undefined; + let origin = ""; + let secret = ""; + const mine = fakeModule({ + gateway: { + module: { + hooks: { + beforeDrain: async () => { + during = ( + await fetch(`${origin}/v1/mine/x`, { + headers: { authorization: `Bearer ${secret}` }, + }) + ).status; + }, + }, + mount: mountPong, + }, + }, + name: "mine", + }); + const gateway = await startGateway(definitionsOf(mine), ["mine"]); + origin = gateway.origin; + secret = gateway.agentSecret; + + await gateway.daemon.stop("test"); + + expect(during).toBe(200); + }); + + it("a fake gateway module whose beforeDrain never settles is logged as ran out of time at 30 s on a fake clock, and the HTTP front still stops and daemon.stop() resolves", async () => { + let entered = false; + const mine = fakeModule({ + gateway: { + module: { + hooks: { + beforeDrain: () => { + entered = true; + return new Promise(() => undefined); + }, + }, + mount: mountPong, + }, + }, + name: "mine", + }); + const gateway = await startGateway(definitionsOf(mine), ["mine"]); + let stopped = false; + const stopping = gateway.daemon.stop("test").then(() => { + stopped = true; + }); + await vi.waitFor(() => expect(entered).toBe(true)); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(stopped).toBe(false); + + gateway.clock.advance(30_000); + await stopping; + + expect(gateway.sink.records).toContainEqual( + expect.objectContaining({ + fields: expect.objectContaining({ hook: "beforeDrain", module: "mine" }), + message: "Optional module hook ran out of time", + }), + ); + await expect(get(gateway, "/v1/mine/x")).rejects.toThrow(); + }); +}); diff --git a/src/lint-rules.test.ts b/src/lint-rules.test.ts index 504729afa..9808b6ba2 100644 --- a/src/lint-rules.test.ts +++ b/src/lint-rules.test.ts @@ -576,7 +576,7 @@ describe("a module's definition.ts, read by the registry without loading the mod }); }); -describe("main.ts loads optional modules lazily", () => { +describe("main.ts imports nothing from any module", () => { function mainViolations(source: string): string[] { const dir = join(scratch, `main-lazy-${counter++}`); const world: Record = { @@ -598,41 +598,24 @@ describe("main.ts loads optional modules lazily", () => { { kind: "a value import", source: 'import { value } from "../agent-device/index.js";\nexport { value };\n', - verdict: "fails", - }, - { - kind: "a re-export", - source: 'export { value } from "../agent-device/index.js";\n', - verdict: "fails", - }, - { - kind: "a bare import", - source: 'import "../agent-device/index.js";\nexport {};\n', - verdict: "fails", }, { kind: "a dynamic import", source: 'export const load = () => import("../agent-device/index.js");\n', - verdict: "passes", }, + { kind: "a re-export", source: 'export { value } from "../agent-device/index.js";\n' }, + { kind: "a bare import", source: 'import "../agent-device/index.js";\nexport {};\n' }, { kind: "a type-only import", source: 'import type { Shape } from "../agent-device/index.js";\nexport type S = Shape;\n', - verdict: "passes", }, { kind: "a type import", source: 'export type S = import("../agent-device/index.js").Shape;\n', - verdict: "passes", }, - ])( - "dependency-cruiser $verdict $kind of src/agent-device from main.ts", - ({ source, verdict }) => { - expect(mainViolations(source).includes("main-loads-modules-lazily")).toBe( - verdict === "fails", - ); - }, - ); + ])("dependency-cruiser fails $kind of src/agent-device from main.ts", ({ source }) => { + expect(mainViolations(source)).toContain("main-loads-modules-lazily"); + }); }); describe("the cycle check between components", () => { diff --git a/src/modules/conformance.test.ts b/src/modules/conformance.test.ts index 6cf2bfe9f..c7a84e666 100644 --- a/src/modules/conformance.test.ts +++ b/src/modules/conformance.test.ts @@ -4,7 +4,7 @@ import { loadConfig } from "../core/index.js"; import { optionalModules } from "../module-registry/index.js"; import { FakeSystemStats, MemoryFilesystem, NoopLogger } from "../ports/index.js"; import { createModuleHost, type ModuleEndedLease, type OptionalModuleDefinition } from "./index.js"; -import { fakeModule, fakeWorkerContext } from "./testing.js"; +import { fakeGatewayContext, fakeModule, fakeWorkerContext } from "./testing.js"; const HOOK_DEADLINE_MS = 30_000; @@ -30,10 +30,14 @@ const hooked = fakeModule({ name: "hooked", }); const plain = fakeModule({ name: "plain" }); +const gatewayHooked = fakeModule({ + gateway: { module: { hooks: { beforeDrain: () => Promise.resolve() } } }, + name: "gateway-hooked", +}); const subjects: readonly (readonly [string, OptionalModuleDefinition])[] = [ ...optionalModules.map((definition) => [definition.name, definition] as const), - ...[hooked, plain].map( + ...[hooked, plain, gatewayHooked].map( (module) => [module.definition.name, module.definition as OptionalModuleDefinition] as const, ), @@ -124,6 +128,35 @@ describe("every optional module's contract", () => { ); }); +const gatewaySubjects = subjects.filter(([, definition]) => definition.loadGateway !== undefined); + +describe("every optional module's gateway side", () => { + it.each(gatewaySubjects)("%s: createGateway starts nothing", async (name, definition) => { + const { ctx, clock } = await fakeGatewayContext(name, definition.config.defaults); + + (await definition.loadGateway?.())?.createGateway(ctx); + + expect(clock.pendingTimerCount).toBe(0); + }); + + it.each(gatewaySubjects)( + "%s: beforeDrain settles within the hook deadline", + async (name, definition) => { + const { ctx, clock } = await fakeGatewayContext(name, definition.config.defaults); + const gateway = (await definition.loadGateway?.())?.createGateway(ctx); + let settled = false; + + const pending = Promise.resolve(gateway?.hooks?.beforeDrain?.()).then(() => { + settled = true; + }); + clock.advance(HOOK_DEADLINE_MS); + await pending; + + expect(settled).toBe(true); + }, + ); +}); + describe("the registry", () => { it("registers agent-device, so the conformance suite above runs over it", () => { expect(subjects.map(([name]) => name)).toContain("agent-device"); diff --git a/src/modules/fleet-types.test.ts b/src/modules/fleet-types.test.ts new file mode 100644 index 000000000..bb5a391ac --- /dev/null +++ b/src/modules/fleet-types.test.ts @@ -0,0 +1,21 @@ +import { describe, expectTypeOf, it } from "vitest"; + +import type { FleetLeaseEntry, FleetLeaseIndex } from "../gateway/index.js"; +import type { FleetLease, FleetLeases } from "./index.js"; + +describe("the fleet types a module sees, declared by shape", () => { + it("FleetLease and the FleetLeaseEntry fields it copies are assignable both ways", () => { + expectTypeOf().toEqualTypeOf< + Pick< + FleetLeaseEntry, + "gatewayLeaseId" | "workerId" | "workerLeaseId" | "requesterId" | "ownerId" | "grantedAt" + > + >(); + }); + + it("FleetLeases and the Pick of FleetLeaseIndex's all, resolve and onRemoved are assignable both ways", () => { + expectTypeOf().toEqualTypeOf< + Pick + >(); + }); +}); diff --git a/src/modules/index.ts b/src/modules/index.ts index 2bf0032ab..8faa5a284 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -3,6 +3,12 @@ export type { ModuleConfig } from "./types.js"; // fallow-ignore-next-line unused-type -- part of the contract a module imports from this index; no registered module names it yet. export type { MountDeps } from "./types.js"; export type { + FleetGrantedDevice, + FleetLease, + FleetLeases, + GatewayContext, + GatewayHooks, + GatewayModule, ModuleCapabilitySource, ModuleDispatch, ModuleEndedLease, @@ -14,5 +20,6 @@ export type { WorkerContext, WorkerHooks, WorkerModule, + WorkerView, } from "./types.js"; export { createModuleHost } from "./host.js"; diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 91edad7a7..a86cf8ea4 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -10,11 +10,16 @@ import { ScriptedProcessRunner, } from "../ports/index.js"; import type { + FleetLease, + FleetLeases, + GatewayContext, + GatewayModule, ModuleFinding, OptionalModuleDefinition, WorkerContext, WorkerHooks, WorkerModule, + WorkerView, } from "./index.js"; export interface FakeModuleConfig { @@ -31,12 +36,23 @@ export interface FakeModuleOptions { readonly mount?: WorkerModule["mount"]; readonly loadError?: Error; readonly onCreate?: (ctx: WorkerContext) => void; + readonly gateway?: FakeGatewaySide; +} + +export interface FakeGatewaySide { + readonly loadError?: Error; + readonly createError?: Error; + readonly module?: GatewayModule; + readonly onCreate?: (ctx: GatewayContext) => void; } export interface FakeModule { readonly definition: OptionalModuleDefinition; loads: number; creates: number; + gatewayLoads: number; + gatewayCreates: number; + readonly gatewayContexts: GatewayContext[]; readonly contexts: WorkerContext[]; } @@ -44,6 +60,9 @@ export function fakeModule(options: FakeModuleOptions): FakeModule { const fake: FakeModule = { contexts: [], creates: 0, + gatewayContexts: [], + gatewayCreates: 0, + gatewayLoads: 0, definition: { config: { defaults: { greeting: "hello" }, @@ -56,6 +75,24 @@ export function fakeModule(options: FakeModuleOptions): FakeModule { return { greeting: section["greeting"] ?? "hello" }; }, }, + ...(options.gateway === undefined + ? {} + : { + loadGateway: () => { + const side = options.gateway; + fake.gatewayLoads += 1; + if (side?.loadError !== undefined) return Promise.reject(side.loadError); + return Promise.resolve({ + createGateway: (ctx: GatewayContext): GatewayModule => { + fake.gatewayCreates += 1; + if (side?.createError !== undefined) throw side.createError; + fake.gatewayContexts.push(ctx); + side?.onCreate?.(ctx); + return side?.module ?? {}; + }, + }); + }, + }), loadWorker: () => { fake.loads += 1; if (options.loadError !== undefined) return Promise.reject(options.loadError); @@ -125,3 +162,55 @@ export async function fakeWorkerContext(name: string, config: C): Promise { + readonly clock: FakeClock; + readonly ctx: GatewayContext; + readonly relayed: { readonly workerId: string; readonly url: string; readonly tenant: string }[]; +} + +export async function fakeGatewayContext( + name: string, + config: C, + facts: { + readonly serving?: readonly WorkerView[]; + readonly relay?: (request: Request) => Response; + } = {}, +): Promise> { + const clock = new FakeClock(1_000); + const daemonConfig: Config = await loadConfig({ + filesystem: new MemoryFilesystem(), + systemStats: new FakeSystemStats({ cpuCount: 4, totalRamBytes: 16 * 1024 ** 3 }), + }); + const serving = facts.serving ?? []; + const leases: FleetLeases = { + all: (): readonly FleetLease[] => [], + onRemoved: () => undefined, + resolve: () => undefined, + }; + const relayed: FakeGatewayContext["relayed"][number][] = []; + return { + clock, + ctx: { + cancelPending: () => Promise.resolve(undefined), + clock, + config, + daemonConfig, + grantedDevices: () => [], + instanceId: "gw-test", + leases, + logger: new NoopLogger(), + name, + relay: (workerId, request, tenant) => { + relayed.push({ tenant, url: request.url, workerId }); + return Promise.resolve(facts.relay?.(request) ?? new Response("{}")); + }, + requesterPrefix: "gw:gw-test:", + serving: () => serving, + startedAt: clock.now(), + worker: (id) => serving.find((view) => view.id === id), + workers: () => serving, + }, + relayed, + }; +} diff --git a/src/modules/types.ts b/src/modules/types.ts index 8840ffffd..30efa20df 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -1,7 +1,13 @@ import type { z } from "zod"; import type { EventHandler, EventName } from "../bus/index.js"; -import type { OPERATIONS, OperationName, Role } from "../contract/index.js"; +import type { + OPERATIONS, + OperationName, + Role, + grantedDeviceSchema, + workerViewSchema, +} from "../contract/index.js"; import type { Config, Platform } from "../core/index.js"; import type { Clock, @@ -112,11 +118,59 @@ export interface WorkerContext { }; } +export type WorkerView = z.infer; + +export type FleetGrantedDevice = z.infer & { + readonly workerId: string; +}; + +export interface FleetLease { + readonly gatewayLeaseId: string; + readonly workerId: string; + readonly workerLeaseId: string; + readonly requesterId: string; + readonly ownerId: string; + readonly grantedAt: number; +} + +export interface FleetLeases { + all(): readonly FleetLease[]; + resolve(gatewayLeaseId: string): FleetLease | undefined; + onRemoved(listener: (entry: FleetLease) => void): void; +} + +export interface GatewayHooks { + readonly beforeDrain?: () => Promise; +} + +export interface GatewayModule { + readonly mount?: (deps: MountDeps) => ModuleHandler; + readonly hooks?: GatewayHooks; +} + +export interface GatewayContext { + readonly name: string; + readonly config: C; + readonly daemonConfig: Config; + readonly logger: Logger; + readonly clock: Clock; + readonly instanceId: string; + readonly startedAt: number; + readonly requesterPrefix: string; + workers(): readonly WorkerView[]; + worker(id: string): WorkerView | undefined; + serving(): readonly WorkerView[]; + grantedDevices(): readonly FleetGrantedDevice[]; + readonly leases: FleetLeases; + relay(workerId: string, request: Request, tenant: string, leaseId?: string): Promise; + cancelPending(requesterId: string): Promise; +} + export interface OptionalModuleDefinition { readonly name: string; readonly config: ModuleConfig; loadWorker(): Promise<{ createWorker(ctx: WorkerContext): WorkerModule }>; - loadGateway?(): Promise; + loadGateway?(): Promise<{ createGateway(ctx: GatewayContext): GatewayModule }>; } export interface ModuleHost { From c9556d2c9deac99f8addf1be4034fbfb7fa179ef Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 15 Oct 2026 15:33:24 +0200 Subject: [PATCH 2/5] feat: agent-device's gateway side runs through the module host (#598) 4 failing -> 0 failing --- .dependency-cruiser-known-cycles.json | 23 --- .dependency-cruiser.mjs | 7 +- src/agent-device/AGENTS.md | 8 +- src/agent-device/dispose.test.ts | 2 +- src/agent-device/front/edge-parts.ts | 55 +++++++ src/agent-device/gateway.ts | 156 ++++++++++++++++++- src/agent-device/index.ts | 57 +------ src/agent-device/worker.ts | 2 +- src/daemon/main.ts | 208 +++----------------------- src/module-registry/index.ts | 2 +- src/modules/AGENTS.md | 12 +- src/modules/host.ts | 156 +++++++++++++++---- src/modules/types.ts | 34 +++++ 13 files changed, 408 insertions(+), 314 deletions(-) create mode 100644 src/agent-device/front/edge-parts.ts diff --git a/.dependency-cruiser-known-cycles.json b/.dependency-cruiser-known-cycles.json index c7c0bbeac..6af47f65f 100644 --- a/.dependency-cruiser-known-cycles.json +++ b/.dependency-cruiser-known-cycles.json @@ -22,29 +22,6 @@ } ] }, - { - "type": "cycle", - "from": "src/daemon", - "to": "src/agent-device", - "rule": { - "severity": "error", - "name": "no-cycle-between-components" - }, - "cycle": [ - { - "name": "src/agent-device", - "dependencyTypes": [] - }, - { - "name": "src/http", - "dependencyTypes": [] - }, - { - "name": "src/daemon", - "dependencyTypes": [] - } - ] - }, { "type": "cycle", "from": "src/daemon", diff --git a/.dependency-cruiser.mjs b/.dependency-cruiser.mjs index c2d521901..be18293bd 100644 --- a/.dependency-cruiser.mjs +++ b/.dependency-cruiser.mjs @@ -172,13 +172,10 @@ export default { { name: "main-loads-modules-lazily", comment: - "main.ts imports src/agent-device only by dynamic import or for types, so a daemon that has the module turned off loads none of its code", + "main.ts imports nothing from src/agent-device, of any type: a module reaches a daemon only through the module host", severity: "error", from: { path: "^src/daemon/main\\.ts$" }, - to: { - dependencyTypesNot: ["type-only", "type-import", "dynamic-import"], - path: "^src/agent-device/", - }, + to: { path: "^src/agent-device/" }, }, direction( "not-modules", diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index cfcb6f24e..ded8c1275 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -1,9 +1,9 @@ # Agent-device edge Does: runs one agent-device daemon per worker and serves the agent-device CLI at `/v1/agent-device/*`, one simlock lease per agent-device lease. -Entry: `index.ts` → `createGatewayAgentDeviceFrontParts` (gateway), `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`; the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds `AgentDeviceSupervisor`), loaded by the module host. +Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds `AgentDeviceSupervisor`). The module host loads both. Uses: ports, http (session, errors, token identity), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`. -Imported by: the module registry (`definition.ts` only); `daemon/main.ts` loads `index.ts` with a dynamic `import()` on a gateway that has it on (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`. +Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`. Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon. ## Files @@ -27,6 +27,8 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no | `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | | `front/host-link.ts` | `HostLink` port; `InProcessHostLink` (worker) | | `front/relay-host-link.ts` | `RelayHostLink` (gateway); `FleetPort` | +| `front/edge-parts.ts` | Front parts, dispose and cancel steps, `createAgentDeviceFront` | +| `gateway.ts` | Gateway side: `FleetPort` from the gateway context, the mount, `beforeDrain` | | `shared/` | Paths, routes, RPC reader, replies, compatibility, daemon env, release scope | | `testing.ts` | `FakeAgentDevice` (in-memory daemon), `FakeAgentDeviceHealth` | @@ -130,7 +132,7 @@ renewals and release scopes: memory only. - The simlock lease is the only clock; an agent-device lease never outlives it. - A pid is signalled only after the `--simlock-home` marker matches. -- The edge names no gateway type; the gateway reaches it through `FleetPort`. +- The edge names no gateway type; the gateway side builds `FleetPort` from its gateway context. - A daemon stop cancels waiting allocates (`cancelWaitingAllocates`) and stops renewals. - Tests: `edge.test.ts`, `gateway-front.test.ts`, `front/*.test.ts`, `host/*.test.ts`. diff --git a/src/agent-device/dispose.test.ts b/src/agent-device/dispose.test.ts index fcf5432d9..986fb538e 100644 --- a/src/agent-device/dispose.test.ts +++ b/src/agent-device/dispose.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { FakeClock } from "../ports/clock.js"; -import { disposeAgentDeviceEdge, type AgentDeviceFrontParts } from "./index.js"; +import { disposeAgentDeviceEdge, type AgentDeviceFrontParts } from "./front/edge-parts.js"; import { FrontMap } from "./front/front-map.js"; import { Renewals } from "./front/renewals.js"; import type { HostLink } from "./front/host-link.js"; diff --git a/src/agent-device/front/edge-parts.ts b/src/agent-device/front/edge-parts.ts new file mode 100644 index 000000000..705192822 --- /dev/null +++ b/src/agent-device/front/edge-parts.ts @@ -0,0 +1,55 @@ +import type { HttpDispatch } from "../../http/dispatcher-session.js"; +import type { HttpMount } from "../../http/app.js"; +import type { Clock, Logger } from "../../ports/index.js"; +import { FrontMap } from "./front-map.js"; +import { createFront } from "./front.js"; +import type { HostLink } from "./host-link.js"; +import { RelayHostLink, type FleetPort } from "./relay-host-link.js"; +import { Renewals } from "./renewals.js"; + +export type { FleetPort, FleetWorker } from "./relay-host-link.js"; + +export interface AgentDeviceFrontParts { + readonly link: HostLink; + readonly map: FrontMap; + readonly renewals: Renewals; +} + +export function createGatewayAgentDeviceFrontParts( + fleet: FleetPort, + clock: Clock, + leaseMaxTtlMs: number, +): AgentDeviceFrontParts { + return { + link: new RelayHostLink({ clock, fleet, leaseMaxTtlMs }), + map: new FrontMap(clock), + renewals: new Renewals(clock), + }; +} + +// why: a stop ends the gateway's sockets, so the calls that end then must send no renewal that races leasing teardown. +export function disposeAgentDeviceEdge(parts: AgentDeviceFrontParts): void { + parts.renewals.dispose(); + parts.link.dispose?.(); +} + +// why: a stop refuses every dispatch, so waiting allocates' lease requests are cancelled through leasing directly, before the gateway stops; otherwise they stay open across a restart. +export async function cancelWaitingAllocates( + parts: AgentDeviceFrontParts, + cancel: (requesterId: string) => Promise, +): Promise { + await Promise.allSettled(parts.map.waitingIds().map((id) => cancel(id))); +} + +export function createAgentDeviceFront( + parts: AgentDeviceFrontParts, + deps: { + readonly dispatch: HttpDispatch; + readonly clock: Clock; + readonly logger: Logger; + readonly leaseTtlCapMs?: number; + readonly maxRunMs: number; + }, +): HttpMount { + return createFront({ ...deps, link: parts.link, map: parts.map, renewals: parts.renewals }); +} diff --git a/src/agent-device/gateway.ts b/src/agent-device/gateway.ts index 2b380ee4d..638ff86b8 100644 --- a/src/agent-device/gateway.ts +++ b/src/agent-device/gateway.ts @@ -1,7 +1,155 @@ -import type { GatewayContext, GatewayModule } from "../modules/index.js"; +import type { HttpDispatch } from "../http/dispatcher-session.js"; +import type { TokenIdentity } from "../http/token-store.js"; +import type { FleetLease, GatewayContext, GatewayModule, WorkerView } from "../modules/index.js"; import type { AgentDeviceModuleConfig } from "./definition.js"; +import { + cancelWaitingAllocates, + createAgentDeviceFront, + createGatewayAgentDeviceFrontParts, + disposeAgentDeviceEdge, + type FleetPort, + type FleetWorker, +} from "./front/edge-parts.js"; -// why: placeholder; the gateway side builds its fleet port and front here once green moves them out of main.ts. -export function createGateway(_ctx: GatewayContext): GatewayModule { - return {}; +type Context = GatewayContext; +type FleetLeaseFacts = ReturnType[number]; + +// why: the context lists workers whose agent-device is available; the rest of what makes one fit for agent-device is judged here. +function serving(view: WorkerView, withDrained: boolean): FleetWorker | undefined { + const maxTtlMs = view.lease?.maxTtlMs; + if ( + (view.drained && !withDrained) || + view.catalogReadAt === undefined || + maxTtlMs === undefined + ) { + return undefined; + } + const platforms = (view.catalog ?? []).flatMap((entry) => + entry.platform === "ios" || entry.platform === "android" ? [entry.platform] : [], + ); + return { id: view.id, leaseMaxTtlMs: maxTtlMs, platforms }; +} + +function fleetPort(ctx: Context): FleetPort { + return { + capableWorkers: () => + ctx.serving().flatMap((view) => { + const worker = serving(view, false); + return worker === undefined ? [] : [worker]; + }), + holder: (workerId) => { + const view = ctx.serving().find((candidate) => candidate.id === workerId); + return view === undefined ? undefined : serving(view, true); + }, + instanceId: ctx.instanceId, + leasesOf: (ownerId) => + ctx.leases + .all() + .filter((entry) => entry.ownerId === ownerId) + .map((entry) => leaseFacts(ctx, entry)), + leaseOf: (leaseId) => { + const entry = ctx.leases.resolve(leaseId); + return entry === undefined ? undefined : { ownerId: entry.ownerId, workerId: entry.workerId }; + }, + onLeaseRemoved: (listener) => { + ctx.leases.onRemoved((entry) => + listener({ + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + workerId: entry.workerId, + }), + ); + }, + reach: (workerId) => { + const view = ctx.worker(workerId); + return view === undefined + ? undefined + : { + connected: view.connection === "connected", + refreshed: view.catalogReadAt !== undefined, + }; + }, + // why: looked up at each call, so a test that replaces the relay's method sits between the link and the worker. + relay: (workerId, request, tenant, leaseId) => ctx.relay(workerId, request, tenant, leaseId), + startedAt: ctx.startedAt, + }; +} + +// why: the worker's view lists the lease, its granted device and the model's class in its catalog; a lease missing any of them is not offered for adoption. +function listedLease( + ctx: Context, + view: WorkerView | undefined, + entry: FleetLease, +): FleetLeaseFacts["listed"] { + const record = view?.leases?.find((lease) => lease.id === entry.workerLeaseId); + if (view === undefined || record === undefined) return undefined; + const device = ctx + .grantedDevices() + .find((granted) => granted.workerId === entry.workerId && granted.id === record.deviceId); + if (device === undefined) return undefined; + return describeDevice(view, record, device); +} + +function describeDevice( + view: WorkerView, + record: { readonly ttlMs: number; readonly ttlDeadline: number }, + device: ReturnType[number], +): FleetLeaseFacts["listed"] { + const { platform, model } = device.spec; + if (device.address === undefined || (platform !== "ios" && platform !== "android")) { + return undefined; + } + const deviceClass = view.catalog?.find((catalog) => catalog.platform === platform)?.modelClasses[ + model + ]; + return { + address: device.address, + model, + platform, + ttlDeadline: record.ttlDeadline, + ttlMs: record.ttlMs, + ...(deviceClass === undefined ? {} : { deviceClass }), + }; +} + +function leaseFacts(ctx: Context, entry: FleetLease): FleetLeaseFacts { + const view = ctx.worker(entry.workerId); + const listed = listedLease(ctx, view, entry); + return { + connected: view?.connection === "connected", + leaseId: entry.gatewayLeaseId, + refreshed: view?.catalogReadAt !== undefined, + requesterId: entry.requesterId, + workerId: entry.workerId, + ...(listed === undefined ? {} : { listed }), + }; +} + +// fallow-ignore-next-line unused-export -- reached through the namespace of definition.ts's dynamic import. +export function createGateway(ctx: Context): GatewayModule { + const parts = createGatewayAgentDeviceFrontParts( + fleetPort(ctx), + ctx.clock, + ctx.daemonConfig.lease.maxTtlMs, + ); + return { + hooks: { + beforeDrain: async () => { + disposeAgentDeviceEdge(parts); + await cancelWaitingAllocates(parts, (id) => ctx.cancelPending(id)); + }, + }, + mount: (deps) => { + const front = createAgentDeviceFront(parts, { + clock: ctx.clock, + dispatch: deps.dispatch as HttpDispatch, + logger: ctx.logger, + maxRunMs: ctx.daemonConfig.lease.maxTtlMs, + ...(ctx.config.leaseTtlCapMs === undefined + ? {} + : { leaseTtlCapMs: ctx.config.leaseTtlCapMs }), + }); + return (request, identity) => front.handle(request, identity as TokenIdentity); + }, + }; } diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index 114d96a40..c5a4b08e2 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -1,56 +1 @@ -import type { HttpDispatch } from "../http/dispatcher-session.js"; -import type { HttpMount } from "../http/app.js"; -import type { Clock, Logger } from "../ports/index.js"; -import { FrontMap } from "./front/front-map.js"; -import { createFront } from "./front/front.js"; -import type { HostLink } from "./front/host-link.js"; -import { RelayHostLink, type FleetPort } from "./front/relay-host-link.js"; -import { Renewals } from "./front/renewals.js"; - -export type { FleetPort, FleetWorker } from "./front/relay-host-link.js"; - -export interface AgentDeviceFrontParts { - readonly link: HostLink; - readonly map: FrontMap; - readonly renewals: Renewals; -} - -// fallow-ignore-next-line unused-export -- reached through the namespace of main.ts's dynamic import. -export function createGatewayAgentDeviceFrontParts( - fleet: FleetPort, - clock: Clock, - leaseMaxTtlMs: number, -): AgentDeviceFrontParts { - return { - link: new RelayHostLink({ clock, fleet, leaseMaxTtlMs }), - map: new FrontMap(clock), - renewals: new Renewals(clock), - }; -} - -// why: a stop ends the gateway's sockets, so the calls that end then must send no renewal that races leasing teardown. -export function disposeAgentDeviceEdge(parts: AgentDeviceFrontParts): void { - parts.renewals.dispose(); - parts.link.dispose?.(); -} - -// why: a stop refuses every dispatch, so waiting allocates' lease requests are cancelled through leasing directly, before the gateway stops; otherwise they stay open across a restart. -export async function cancelWaitingAllocates( - parts: AgentDeviceFrontParts, - cancel: (requesterId: string) => Promise, -): Promise { - await Promise.allSettled(parts.map.waitingIds().map((id) => cancel(id))); -} - -export function createAgentDeviceFront( - parts: AgentDeviceFrontParts, - deps: { - readonly dispatch: HttpDispatch; - readonly clock: Clock; - readonly logger: Logger; - readonly leaseTtlCapMs?: number; - readonly maxRunMs: number; - }, -): HttpMount { - return createFront({ ...deps, link: parts.link, map: parts.map, renewals: parts.renewals }); -} +export { agentDeviceModule } from "./definition.js"; diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index 8a8a0fd1e..0be31dca2 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -17,7 +17,7 @@ import { createAgentDeviceFront, disposeAgentDeviceEdge, type AgentDeviceFrontParts, -} from "./index.js"; +} from "./front/edge-parts.js"; import { frontReplyFor, notAvailable } from "./shared/replies.js"; interface AgentDeviceEdgeParts extends AgentDeviceFrontParts { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 1e9add526..4dcee9d2e 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -2,8 +2,6 @@ import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import type { FleetPort, FleetWorker } from "../agent-device/index.js"; -import type { AgentDeviceModuleConfig } from "../agent-device/definition.js"; import { EVENT_FILE_NAME, EventBus, EventHistory, type EventBusLogger } from "../bus/index.js"; import { fitHostFacts, fitHostLoad } from "../contract/index.js"; import { HostLoadSampler } from "../host-load/index.js"; @@ -89,13 +87,11 @@ import { FileDrainStore, FleetLeaseCoordinator, FleetLeaseIndex, - type WorkerRegistry, GatewayDispatcher, GatewayOwnerRoutedFacts, GatewayRelay, GatewayService, type GatewayServiceOptions, - type FleetViews, } from "../gateway/index.js"; import { WebSocketUplinkConnector, @@ -222,6 +218,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise[]; readonly socketPath: string; readonly version: string; } @@ -795,25 +793,24 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise & { readonly enabled?: boolean }) - | undefined; - // why: loaded only when turned on, so no daemon loads agent-device's code through a static import. - const agentDeviceModule = - agentDeviceSection?.enabled === true ? await import("../agent-device/index.js") : undefined; - const agentDeviceParts = agentDeviceModule - ? agentDeviceModule.createGatewayAgentDeviceFrontParts( - agentDeviceFleetPort({ - instanceId, - leaseIndex, - relay: gatewayRelay, - startedAt: clock.now(), - views: gatewayService.workers, - }), - clock, - config.lease.maxTtlMs, - ) - : undefined; + const moduleHost = await createModuleHost({ + config, + definitions: options.optionalModules, + logger, + parts: { + cancelPending: (requesterId) => fleetCoordinator.cancelPending(requesterId), + clock, + grantedDevices: () => gatewayService.workers.grantedDevices(), + instanceId, + leases: leaseIndex, + relay: (workerId, call) => gatewayRelay.relay(workerId, call), + requesterPrefix: gatewayRequesterPrefix, + startedAt: clock.now(), + worker: (id) => gatewayService.workers.view(id), + workers: () => gatewayService.workers.views(), + }, + role: "gateway", + }); let stopHttpGateway: (() => Promise) | undefined; let resolveHttpStarted: (() => void) | undefined; @@ -890,12 +887,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { - if (agentDeviceModule !== undefined && agentDeviceParts !== undefined) { - agentDeviceModule.disposeAgentDeviceEdge(agentDeviceParts); - await agentDeviceModule.cancelWaitingAllocates(agentDeviceParts, (id) => - fleetCoordinator.cancelPending(id), - ); - } + await moduleHost.beforeDrain(); await httpStarted.catch(() => undefined); await stopHttpGateway?.(); }, @@ -925,20 +917,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise; -} - -const AGENT_DEVICE = "agent-device"; - -type WorkerView = NonNullable>; - -// why: the agent-device edge imports nothing from the gateway, so this is the one place the gateway's parts become its port. -function agentDeviceFleetPort({ - instanceId, - leaseIndex, - relay, - startedAt, - views, -}: FleetPortParts): FleetPort { - const serving = (view: WorkerView, withDrained: boolean): FleetWorker | undefined => { - const maxTtlMs = view.lease?.maxTtlMs; - const available = view.capabilities?.some( - (entry) => entry.name === AGENT_DEVICE && entry.state === "available", - ); - if ( - view.connection !== "connected" || - (view.drained && !withDrained) || - available !== true || - view.catalogReadAt === undefined || - maxTtlMs === undefined - ) { - return undefined; - } - const platforms = (view.catalog ?? []).flatMap((entry) => - entry.platform === "ios" || entry.platform === "android" ? [entry.platform] : [], - ); - return { id: view.id, leaseMaxTtlMs: maxTtlMs, platforms }; - }; - return { - capableWorkers: () => - views.views().flatMap((view) => { - const worker = serving(view, false); - return worker === undefined ? [] : [worker]; - }), - holder: (workerId) => { - const view = views.view(workerId); - return view === undefined ? undefined : serving(view, true); - }, - instanceId, - leasesOf: (ownerId) => - leaseIndex - .all() - .filter((entry) => entry.ownerId === ownerId) - .map((entry) => leaseFacts(views, entry)), - reach: (workerId) => { - const view = views.view(workerId); - return view === undefined - ? undefined - : { - connected: view.connection === "connected", - refreshed: view.catalogReadAt !== undefined, - }; - }, - startedAt, - leaseOf: (leaseId) => { - const entry = leaseIndex.resolve(leaseId); - return entry === undefined ? undefined : { ownerId: entry.ownerId, workerId: entry.workerId }; - }, - onLeaseRemoved: (listener) => - leaseIndex.onRemoved((entry) => - listener({ - leaseId: entry.gatewayLeaseId, - ownerId: entry.ownerId, - workerId: entry.workerId, - }), - ), - // why: looked up at each call, so a test that replaces the relay's method sits between the link and the worker. - relay: (workerId, request, tenant, leaseId) => - relay.relay(workerId, { - request, - target: AGENT_DEVICE, - tenant, - ...(leaseId === undefined ? {} : { leaseId }), - }), - }; -} - -type FleetLeaseFacts = ReturnType[number]; - -// why: the worker's view lists the lease, its granted device and the model's class in its catalog; a lease missing any of them is not offered for adoption. -function listedLease( - views: FleetPortParts["views"], - view: WorkerView | undefined, - entry: ReturnType[number], -): FleetLeaseFacts["listed"] { - const record = view?.leases?.find((lease) => lease.id === entry.workerLeaseId); - if (view === undefined || record === undefined) return undefined; - const device = views - .grantedDevices() - .find((granted) => granted.workerId === entry.workerId && granted.id === record.deviceId); - if (device === undefined) return undefined; - return describeDevice(view, record, device); -} - -function describeDevice( - view: WorkerView, - record: { readonly ttlMs: number; readonly ttlDeadline: number }, - device: ReturnType[number], -): FleetLeaseFacts["listed"] { - const { platform, model } = device.spec; - if (device.address === undefined || (platform !== "ios" && platform !== "android")) { - return undefined; - } - const deviceClass = view.catalog?.find((catalog) => catalog.platform === platform)?.modelClasses[ - model - ]; - return { - address: device.address, - model, - platform, - ttlDeadline: record.ttlDeadline, - ttlMs: record.ttlMs, - ...(deviceClass === undefined ? {} : { deviceClass }), - }; -} - -function leaseFacts( - views: FleetPortParts["views"], - entry: ReturnType[number], -): FleetLeaseFacts { - const view = views.view(entry.workerId); - const listed = listedLease(views, view, entry); - return { - connected: view?.connection === "connected", - leaseId: entry.gatewayLeaseId, - refreshed: view?.catalogReadAt !== undefined, - requesterId: entry.requesterId, - workerId: entry.workerId, - ...(listed === undefined ? {} : { listed }), - }; -} - function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/module-registry/index.ts b/src/module-registry/index.ts index dff7575b1..fd4e9868a 100644 --- a/src/module-registry/index.ts +++ b/src/module-registry/index.ts @@ -1,4 +1,4 @@ -import { agentDeviceModule } from "../agent-device/definition.js"; +import { agentDeviceModule } from "../agent-device/index.js"; import type { OptionalModuleDefinition } from "../modules/index.js"; export const optionalModules: readonly OptionalModuleDefinition[] = [ diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index 76939641f..0fb4e891e 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -3,15 +3,15 @@ Does: the contract an optional module implements, and the host that loads each turned-on module and plugs its handle into the daemon. Entry: `index.ts` → `createModuleHost` and the contract types; `testing.ts` → `fakeModule`, `fakeWorkerContext`. Uses: ports, contract, core; the bus for types only. Never imports: leasing, gateway, drivers, agent-device, `fs`. -Imported by: `daemon/main.ts` (the factory and types). Core, leasing, drivers, gateway and contract never import it. +Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed the gateway parts and binds each module's context to its name. Core, leasing, drivers, gateway and contract never import it. ## Files -| File | Role | -| ------------ | --------------------------------------------------------------------------------------------------------------- | -| `types.ts` | `OptionalModuleDefinition`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `WorkerContext`, the by-shape copies | -| `host.ts` | `createModuleHost`: checks names, loads turned-on modules, runs hooks | -| `testing.ts` | Fake module and context for tests and the conformance suite | +| File | Role | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | `OptionalModuleDefinition`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `WorkerContext`, the by-shape copies | +| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks; a gateway host runs `beforeDrain` under the same 30 s deadline | +| `testing.ts` | Fake module and context for tests and the conformance suite | ## Rules diff --git a/src/modules/host.ts b/src/modules/host.ts index e620fa5b7..5e2ab80b2 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -1,6 +1,9 @@ import { CORE_ROUTE_SEGMENTS, MAX_CAPABILITIES, capabilityNameSchema } from "../contract/index.js"; -import type { Logger } from "../ports/index.js"; +import type { Clock, Logger } from "../ports/index.js"; import type { + GatewayHostOptions, + GatewayModule, + GatewayModuleHost, ModuleCapabilitySource, ModuleHost, ModuleHostOptions, @@ -9,7 +12,6 @@ import type { ModuleRelayTarget, MountDeps, OptionalModuleDefinition, - WorkerHooks, WorkerModule, } from "./types.js"; @@ -83,7 +85,7 @@ async function createOne( async function runHook( logger: Logger, module: string, - hook: keyof WorkerHooks, + hook: string, call: () => unknown, ): Promise { try { @@ -93,7 +95,119 @@ async function runHook( } } -export async function createModuleHost(options: ModuleHostOptions): Promise { +async function runWithDeadline( + logger: Logger, + clock: Clock, + hook: string, + steps: readonly { readonly name: string; readonly call: () => unknown }[], +): Promise { + const running = new Set(); + const calls = steps.map(({ call, name }) => { + running.add(name); + return runHook(logger, name, hook, call).finally(() => { + running.delete(name); + }); + }); + if (calls.length === 0) return; + let timer: ReturnType | undefined; + const deadline = new Promise((resolve) => { + timer = clock.setTimer(HOOK_DEADLINE_MS, resolve); + }); + await Promise.race([Promise.all(calls), deadline]); + if (timer !== undefined) clock.cancel(timer); + for (const module of running) { + logger.warn("Optional module hook ran out of time", { hook, module }); + } +} + +async function createGatewaySide( + definition: OptionalModuleDefinition, + options: GatewayHostOptions, +): Promise { + const { name } = definition; + const { parts } = options; + try { + const loaded = await definition.loadGateway?.(); + const section = Object.fromEntries( + Object.entries(options.config.capabilities[name] ?? {}).filter(([key]) => key !== "enabled"), + ); + return ( + loaded?.createGateway({ + cancelPending: (requesterId) => parts.cancelPending(requesterId), + clock: parts.clock, + config: section, + daemonConfig: options.config, + grantedDevices: () => parts.grantedDevices(), + instanceId: parts.instanceId, + leases: parts.leases, + logger: options.logger.child(name), + name, + relay: (workerId, request, tenant, leaseId) => + parts.relay(workerId, { + request, + target: name, + tenant, + ...(leaseId === undefined ? {} : { leaseId }), + }), + requesterPrefix: parts.requesterPrefix, + serving: () => + parts + .workers() + .filter( + (view) => + view.connection === "connected" && + view.capabilities?.some( + (entry) => entry.name === name && entry.state === "available", + ) === true, + ), + startedAt: parts.startedAt, + worker: (id) => parts.worker(id), + workers: () => parts.workers(), + }) ?? {} + ); + } catch (error: unknown) { + throw new Error(`Optional module "${name}" failed to start: ${messageOf(error)}`, { + cause: error, + }); + } +} + +async function createGatewayHost(options: GatewayHostOptions): Promise { + checkNames(options.definitions); + const started: { readonly name: string; readonly gateway: GatewayModule }[] = []; + for (const definition of options.definitions) { + if (options.config.capabilities[definition.name]?.enabled !== true) continue; + if (definition.loadGateway === undefined) continue; + started.push({ gateway: await createGatewaySide(definition, options), name: definition.name }); + } + return { + beforeDrain: () => + runWithDeadline( + options.logger, + options.parts.clock, + "beforeDrain", + started.flatMap(({ gateway, name }) => { + const call = gateway.hooks?.beforeDrain; + return call === undefined ? [] : [{ call: () => call(), name }]; + }), + ), + mounts: (deps) => + started.flatMap(({ gateway, name }) => + gateway.mount === undefined ? [] : [{ handle: gateway.mount(deps), prefix: name }], + ), + }; +} + +export function createModuleHost(options: GatewayHostOptions): Promise; +export function createModuleHost(options: ModuleHostOptions): Promise; +export async function createModuleHost( + options: GatewayHostOptions | ModuleHostOptions, +): Promise { + if (options.role === "gateway") return createGatewayHost(options); + return createWorkerHost(options); +} + +async function createWorkerHost(options: ModuleHostOptions): Promise { const { definitions, logger } = options; checkNames(definitions); @@ -125,30 +239,16 @@ export async function createModuleHost(options: ModuleHostOptions): Promise => { - const running = new Set(); - const calls = started.flatMap(({ name, worker }) => { - const call = worker.hooks?.[hook]; - if (call === undefined) return []; - running.add(name); - return [ - runHook(logger, name, hook, () => call()).finally(() => { - running.delete(name); - }), - ]; - }); - if (calls.length === 0) return; - const { clock } = options.context; - let timer: ReturnType | undefined; - const deadline = new Promise((resolve) => { - timer = clock.setTimer(HOOK_DEADLINE_MS, resolve); - }); - await Promise.race([Promise.all(calls), deadline]); - if (timer !== undefined) clock.cancel(timer); - for (const module of running) { - logger.warn("Optional module hook ran out of time", { hook, module }); - } - }; + const runStopStep = (hook: StopHook): Promise => + runWithDeadline( + logger, + options.context.clock, + hook, + started.flatMap(({ name, worker }) => { + const call = worker.hooks?.[hook]; + return call === undefined ? [] : [{ call: () => call(), name }]; + }), + ); // why: doctor reads findings at every run and at startup, so a module that keeps throwing is logged when it starts to, not on every read. const unreadable = new Set(); diff --git a/src/modules/types.ts b/src/modules/types.ts index 30efa20df..70cbbd76e 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -189,6 +189,40 @@ export interface ModuleHost { beforeDriversDispose(): Promise; } +export interface GatewayParts { + readonly clock: Clock; + readonly instanceId: string; + readonly startedAt: number; + readonly requesterPrefix: string; + workers(): readonly WorkerView[]; + worker(id: string): WorkerView | undefined; + grantedDevices(): readonly FleetGrantedDevice[]; + readonly leases: FleetLeases; + relay( + workerId: string, + call: { + readonly request: Request; + readonly target: string; + readonly tenant: string; + readonly leaseId?: string; + }, + ): Promise; + cancelPending(requesterId: string): Promise; +} + +export interface GatewayModuleHost { + mounts(deps: MountDeps): readonly ModuleMount[]; + beforeDrain(): Promise; +} + +export interface GatewayHostOptions { + readonly role: "gateway"; + readonly definitions: readonly OptionalModuleDefinition[]; + readonly config: Config; + readonly logger: Logger; + readonly parts: GatewayParts; +} + export interface ModuleHostOptions { readonly role: "worker"; readonly definitions: readonly OptionalModuleDefinition[]; From 88432e63236c41622829c5fe25ab9e4f60c03269 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 15 Oct 2026 15:33:58 +0200 Subject: [PATCH 3/5] fix: index drops two type exports nothing imports (#598) --- src/modules/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/modules/index.ts b/src/modules/index.ts index 8faa5a284..33b267177 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -3,11 +3,9 @@ export type { ModuleConfig } from "./types.js"; // fallow-ignore-next-line unused-type -- part of the contract a module imports from this index; no registered module names it yet. export type { MountDeps } from "./types.js"; export type { - FleetGrantedDevice, FleetLease, FleetLeases, GatewayContext, - GatewayHooks, GatewayModule, ModuleCapabilitySource, ModuleDispatch, From 2fb2d2179dcf117c20b78ea3a9df71827b4953bc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 15 Oct 2026 15:43:30 +0200 Subject: [PATCH 4/5] test: gateway module tests prove unavailable and other-named capabilities, the warn level, and a true title (#598) --- src/agent-device/gateway.test.ts | 2 +- src/daemon/gateway-modules.test.ts | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/agent-device/gateway.test.ts b/src/agent-device/gateway.test.ts index dbb7712c0..3d98a8f1a 100644 --- a/src/agent-device/gateway.test.ts +++ b/src/agent-device/gateway.test.ts @@ -64,7 +64,7 @@ describe("agent-device's gateway side", () => { ]); }); - it("agent-device's definition has a gateway side whose mount answers under /v1/agent-device", async () => { + it("agent-device's definition has a gateway side that creates a mount and a beforeDrain hook", async () => { const { ctx } = await fakeGatewayContext("agent-device", agentDeviceModule.config.defaults); const loaded = await agentDeviceModule.loadGateway?.(); diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts index ac57a10a1..0cce89c7d 100644 --- a/src/daemon/gateway-modules.test.ts +++ b/src/daemon/gateway-modules.test.ts @@ -228,6 +228,10 @@ describe("a gateway's optional modules", () => { const gateway = await startGateway(definitionsOf(mine), ["mine"]); await joinWorker(gateway, definitionsOf(mine), ["mine"], "serves"); await joinWorker(gateway, definitionsOf(mine), [], "off"); + const unavailable = fakeModule({ name: "mine", state: "unavailable" }); + await joinWorker(gateway, definitionsOf(unavailable), ["mine"], "unavailable"); + const other = fakeModule({ name: "other" }); + await joinWorker(gateway, definitionsOf(other), ["other"], "other"); const gone = await joinWorker(gateway, definitionsOf(mine), ["mine"], "gone"); await joinWorker(gateway, definitionsOf(mine), ["mine"], "drained"); const { workers } = await gateway.daemon.dispatch("worker.list", {}, admin); @@ -308,6 +312,7 @@ describe("a gateway's optional modules", () => { expect(gateway.sink.records).toContainEqual( expect.objectContaining({ fields: expect.objectContaining({ hook: "beforeDrain", module: "mine" }), + level: "warn", message: "Optional module hook ran out of time", }), ); From 064bd625bfecc46e13323f1be54112bd25796d8f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 15 Oct 2026 15:53:03 +0200 Subject: [PATCH 5/5] test: serving() keeps catalog-unread workers, hook deadline is exactly 30 s; stale comments fixed (#598) --- src/agent-device/front/relay-host-link.ts | 2 +- src/daemon/AGENTS.md | 2 +- src/daemon/gateway-modules.test.ts | 9 ++++++- src/modules/conformance.test.ts | 30 ++++++++++++++++++++++- 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/agent-device/front/relay-host-link.ts b/src/agent-device/front/relay-host-link.ts index 9bf1c60d5..96bb7269f 100644 --- a/src/agent-device/front/relay-host-link.ts +++ b/src/agent-device/front/relay-host-link.ts @@ -43,7 +43,7 @@ export interface FleetLeaseFacts { }; } -// why: the edge imports nothing from the gateway, so the gateway's parts reach the link only through this port, built where the gateway is composed. +// why: the edge imports nothing from the gateway, so the gateway's parts reach the link only through this port, built in `gateway.ts` from the gateway context. export interface FleetPort { readonly instanceId: string; // why: when this gateway process started, which opens the window in which a lease it cannot place may still come back. diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 5c888db81..175432b80 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -2,7 +2,7 @@ Does: one process per data directory — composes a worker or a gateway and serves the contract on a unix socket. Entry: `main.ts` → `startDaemon(options)` → a started `DaemonServer`. -Uses: contract, daemon-protocol, ports, bus, link, core, leasing, drivers, http, host-load, agent-device, modules, module-registry; gateway from `main.ts` only. +Uses: contract, daemon-protocol, ports, bus, link, core, leasing, drivers, http, host-load, modules, module-registry; gateway from `main.ts` only. Never imports: gateway outside `main.ts`. `dispatch.ts` imports no core, drivers or http. Imported by: http (`dispatcher.ts`, `error-code.ts`, `owner-routed-facts.ts`); gateway (`dispatch.ts` only). Started by: cli and mcp spawn `main.ts` as a detached process. diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts index 0cce89c7d..03894d588 100644 --- a/src/daemon/gateway-modules.test.ts +++ b/src/daemon/gateway-modules.test.ts @@ -306,7 +306,14 @@ describe("a gateway's optional modules", () => { await new Promise((resolve) => setTimeout(resolve, 20)); expect(stopped).toBe(false); - gateway.clock.advance(30_000); + gateway.clock.advance(29_999); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(stopped).toBe(false); + expect( + gateway.sink.records.some((r) => r.message === "Optional module hook ran out of time"), + ).toBe(false); + + gateway.clock.advance(1); await stopping; expect(gateway.sink.records).toContainEqual( diff --git a/src/modules/conformance.test.ts b/src/modules/conformance.test.ts index c7a84e666..466be9df7 100644 --- a/src/modules/conformance.test.ts +++ b/src/modules/conformance.test.ts @@ -3,7 +3,12 @@ import { describe, expect, it, vi } from "vitest"; import { loadConfig } from "../core/index.js"; import { optionalModules } from "../module-registry/index.js"; import { FakeSystemStats, MemoryFilesystem, NoopLogger } from "../ports/index.js"; -import { createModuleHost, type ModuleEndedLease, type OptionalModuleDefinition } from "./index.js"; +import { + createModuleHost, + type ModuleEndedLease, + type OptionalModuleDefinition, + type WorkerView, +} from "./index.js"; import { fakeGatewayContext, fakeModule, fakeWorkerContext } from "./testing.js"; const HOOK_DEADLINE_MS = 30_000; @@ -157,6 +162,29 @@ describe("every optional module's gateway side", () => { ); }); +describe("a gateway module's serving()", () => { + it("keeps a connected worker whose capability is available even when its catalog is unread, and drops one that is not connected", async () => { + const mine = fakeModule({ gateway: { module: {} }, name: "mine" }); + const definition = mine.definition as OptionalModuleDefinition; + const available = [{ name: "mine", state: "available" }]; + const views = [ + { capabilities: available, connection: "connected", id: "unread" }, + { capabilities: available, connection: "disconnected", id: "gone" }, + ] as never as readonly WorkerView[]; + const { ctx } = await fakeGatewayContext("mine", definition.config.defaults); + + await createModuleHost({ + config: await configFor(definition, true), + definitions: [definition], + logger: new NoopLogger(), + parts: { ...ctx, worker: () => undefined, workers: () => views } as never, + role: "gateway", + }); + + expect(mine.gatewayContexts[0]?.serving().map((view) => view.id)).toEqual(["unread"]); + }); +}); + describe("the registry", () => { it("registers agent-device, so the conformance suite above runs over it", () => { expect(subjects.map(([name]) => name)).toContain("agent-device");