/** * The mesh assigns TWO media modules to one node in a single push, and they resolve and come up * together BECAUSE THEY ACCESS THE SAME OPERATOR-OWNED DIRECTORY — the proof of novox/hq ADR 0051 * (04-ISSUES/036, and the migration-rehearsal media stack of 04-ISSUES/012). * * sonarr and radarr are the tightest co-access pair: * - both ACCESS /services/media/downloads — the shared download spool. This is the exact duplicate * path the resolver refused before ADR 0051: two modules naming one path read as two owners of * it ("sonarr and radarr both declare the path"). Now each declares it as an `access`, not a * `directory` resource, and an access never enters the owner map — so the pair co-resolves and a * single push configures both. That is the whole point of a media stack, where the managers and * the download client must see the same directory. * - sonarr additionally accesses /services/media/series, radarr /services/media/movies — its own * library, still operator-owned, still an access. * - each OWNS its config directory (/services/{sonarr,radarr}/config), which the mesh does create. * * The host refuses an access whose path is ABSENT at apply (novox/hq ADR 0051): shared data is the * operator's, mounted and never made as root by the container runtime. So the operator provides * /services/media/{downloads,series,movies} on the anchor BEFORE the modules apply — this test creates * them after enrol and before the one push. (No scenario primitive is needed: the directories are the * operator's, so an ordinary `mkdir` on the anchor stands in for the operator, exactly as it would on * a real node.) * * All is assigned to the one anchor, pushed ONCE, and the node converges ONCE with both modules up. * * MESH_LAB_HOST_BINARY=.../mesh-host MESH_LAB_BUNDLE=.../examples/substrate-first-node.lock * scripts/build-module-runtime.sh {sonarr,radarr} build the runtime images into the local daemon; * scenarios/catalogue-media.yml stocks them. lscr.io/linuxserver/{sonarr,radarr} must be in the * local daemon; the service images are pulled from the internet. Each *arr runtime is given a lab * API key so its client constructs and * its tools register (as plex is given a lab token) — the server need not be configured by hand. */ import { test, before, after } from "node:test"; import assert from "node:assert/strict"; import { existsSync, readFileSync } from "node:fs"; import { loadScenario } from "../../src/declaration/parse.ts"; import { raise } from "../../src/lifecycle/raise.ts"; import { destroy, exec } from "../../src/lifecycle/operate.ts"; import { hostBinaryPath, HOST_PATH } from "../../src/lifecycle/place.ts"; import { labIsUsable, destroyAll, substrateBundle, onTheMachine } from "./harness.ts"; import type { HeldImage } from "../../src/pinning.ts"; const capability = await labIsUsable(); const binary = hostBinaryPath(); const bundle = process.env["MESH_LAB_BUNDLE"] ?? ""; const skip = !capability.usable ? `lab not usable: ${capability.why}` : !binary || !existsSync(binary) ? "MESH_LAB_HOST_BINARY is not set to a built mesh-host" : !bundle || !existsSync(bundle) ? "MESH_LAB_BUNDLE is not set to a substrate bundle (mesh-host examples/)" : false; const SCENARIO = "catalogue-media"; const MACHINE = "anchor"; let instanceId = ""; /** The mesh's own images, as the machines hold them. */ let held: HeldImage[] = []; function quote(s: string): string { return `'${s.replaceAll("'", `'\\''`)}'`; } async function on(command: string, timeoutMs?: number): Promise<{ out: string; ok: boolean }> { const { stdout } = await exec(instanceId, MACHINE, [ "sh", "-c", `exec 2>&1\n${command}\necho "__exit=$?"`, ], timeoutMs); const marker = stdout.lastIndexOf("__exit="); if (marker < 0) return { out: stdout, ok: false }; return { out: stdout.slice(0, marker), ok: stdout.slice(marker + 7).trim() === "0" }; } async function must(command: string, timeoutMs?: number): Promise { const { out, ok } = await on(command, timeoutMs); if (!ok) throw new Error(`${MACHINE}: ${command}\n${out}`); return out; } /** The control plane, a container on the node. */ async function mesh(command: string, timeoutMs?: number): Promise { return must(`docker exec mesh-control /mesh-control ${command}`, timeoutMs); } /** The reference a manifest should carry, once this scenario has been raised. */ /** What a manifest's image reference becomes on the machine — ours by ID, everything else as written. */ function pinned(reference: string): string { return onTheMachine(reference, held); } /** The substrate bundle: ours by the ID the machine holds, everything else upstream. */ function bundleFor(images: HeldImage[]): string { return substrateBundle(bundle, images); } function tokenFrom(said: string): string { const found = said.split("\n").map((l) => l.trim()).find((l) => l.length > 100 && !l.includes(" ")); assert.ok(found, `no token in:\n${said}`); return found; } async function settled(withinMs = 600_000): Promise { const until = Date.now() + withinMs; let last = ""; while (Date.now() < until) { const asked = await on(`docker exec mesh-control /mesh-control status --json`); if (asked.ok) { try { const state = JSON.parse(asked.out) as { wrong: { node: string; outcome: string }[]; waiting: { node: string }[]; reported: { node: string; outcome: string; current: boolean }[]; }; const bad = state.wrong.find((w) => w.node === MACHINE); if (bad) throw new Error(`${MACHINE} did not apply what it was sent: ${bad.outcome}\n${asked.out}`); const word = state.reported.find((r) => r.node === MACHINE); if (!state.waiting.some((w) => w.node === MACHINE) && word?.outcome === "applied" && word.current) return; last = asked.out; } catch (err) { if (err instanceof Error && err.message.includes("did not apply")) throw err; last = asked.out; } } await new Promise((r) => setTimeout(r, 5000)); } throw new Error(`${MACHINE} never caught up within ${Math.round(withinMs / 1000)}s. Last:\n${last}`); } before(async () => { if (skip) return; const raised = await raise(loadScenario(`scenarios/${SCENARIO}.yml`), { onProgress: (m) => console.log(`raise: ${m}`), }); instanceId = raised.instanceId; held = raised.images; // Raise the substrate — store, broker, control — from the bundle. await must(`cat > /tmp/substrate.lock <<'MESHBUNDLE'\n${bundleFor(raised.images)}\nMESHBUNDLE`); await must(`${HOST_PATH} apply /tmp/substrate.lock`, 600_000); const up = await must(`docker ps --format '{{.Names}}'`); for (const c of ["mesh-store", "mesh-broker", "mesh-control"]) { assert.match(up, new RegExp(c), `the substrate did not raise ${c}:\n${up}`); } // The node joins its own mesh, so it is a node the mesh can assign to, and start the host so it // applies what it is pushed. await mesh(`node add ${MACHINE}`); const token = tokenFrom(await mesh(`token issue --node ${MACHINE}`)); await must(`${HOST_PATH} enrol --token ${quote(token)}`); await must(`nohup ${HOST_PATH} run > /var/log/mesh-host.log 2>&1 & sleep 3`); }, { timeout: 1_800_000 }); after(async () => { if (instanceId) await destroy(instanceId); await destroyAll(`${SCENARIO}-`); }, { timeout: 600_000 }); test("sonarr and radarr, both accessing one operator-owned directory, co-resolve and come up in one push", { skip, timeout: 1_500_000, }, async () => { // --- sonarr: a media app. Server + broker-bound runtime that serves tools. It ACCESSES the shared // download spool and its own series library (operator-owned, mounted, not owned), and OWNS its // config directory (mesh-created). The runtime is given a lab API key so its client constructs. --- const sonarrManifest = JSON.stringify({ module: "sonarr", version: "1", emits: ["module.sonarr.episode.grabbed", "module.sonarr.download.completed"], consumes: [], "own-secrets": { broker: "/var/lib/mesh/sonarr/broker" }, accesses: [ { path: "/services/media/downloads", mode: "read-write" }, { path: "/services/media/series", mode: "read-write" }, ], resources: [ { id: "mesh-state", type: "directory", path: "/var/lib/mesh/sonarr", mode: "0700" }, { id: "config", type: "directory", path: "/services/sonarr/config", mode: "0700", owner: "1000:1000" }, { id: "server", type: "container", name: "sonarr", image: pinned("lscr.io/linuxserver/sonarr"), env: { PUID: "1000", PGID: "1000", TZ: "Etc/UTC" }, ports: ["8989:8989"], volumes: [ "/services/sonarr/config:/config", "/services/media/series:/series", "/services/media/downloads:/downloads", ], }, { id: "runtime", type: "container", name: "mesh-sonarr", image: pinned("mesh-runtime-sonarr"), network: "host", volumes: [ "/var/lib/mesh/sonarr/broker:/run/secrets/broker:ro", "/services/sonarr/config:/var/lib/sonarr/config:ro", ], env: { MESH_BROKER_FILE: "/run/secrets/broker", MESH_SONARR_URL: "http://127.0.0.1:8989", MESH_SONARR_CONFIG_DIR: "/var/lib/sonarr/config", MESH_SONARR_API_KEY: "lab-sonarr-key", }, }, ], }); // --- radarr: the second media app. Shares /services/media/downloads with sonarr — the co-access — // and additionally accesses its own /services/media/movies. --------------------------------------- const radarrManifest = JSON.stringify({ module: "radarr", version: "1", emits: ["module.radarr.movie.grabbed", "module.radarr.download.completed"], consumes: [], "own-secrets": { broker: "/var/lib/mesh/radarr/broker" }, accesses: [ { path: "/services/media/downloads", mode: "read-write" }, { path: "/services/media/movies", mode: "read-write" }, ], resources: [ { id: "mesh-state", type: "directory", path: "/var/lib/mesh/radarr", mode: "0700" }, { id: "config", type: "directory", path: "/services/radarr/config", mode: "0700", owner: "1000:1000" }, { id: "server", type: "container", name: "radarr", image: pinned("lscr.io/linuxserver/radarr"), env: { PUID: "1000", PGID: "1000", TZ: "Etc/UTC" }, ports: ["7878:7878"], volumes: [ "/services/radarr/config:/config", "/services/media/movies:/movies", "/services/media/downloads:/downloads", ], }, { id: "runtime", type: "container", name: "mesh-radarr", image: pinned("mesh-runtime-radarr"), network: "host", volumes: [ "/var/lib/mesh/radarr/broker:/run/secrets/broker:ro", "/services/radarr/config:/var/lib/radarr/config:ro", ], env: { MESH_BROKER_FILE: "/run/secrets/broker", MESH_RADARR_URL: "http://127.0.0.1:7878", MESH_RADARR_CONFIG_DIR: "/var/lib/radarr/config", MESH_RADARR_API_KEY: "lab-radarr-key", }, }, ], }); // --- add, issue (both emit events → each gets a scoped broker account), assign ------------------ async function add(name: string, manifest: string): Promise { await must(`printf %s ${quote(manifest)} > /tmp/${name}.json && docker cp /tmp/${name}.json mesh-control:/${name}.json`); await mesh(`module add /${name}.json`); } await add("sonarr", sonarrManifest); const sonarrIssued = await mesh(`module issue sonarr --node ${MACHINE}`); assert.match(sonarrIssued, /scoped to what it emits and consumes/, sonarrIssued); await mesh(`assign ${MACHINE} sonarr`); await add("radarr", radarrManifest); const radarrIssued = await mesh(`module issue radarr --node ${MACHINE}`); assert.match(radarrIssued, /scoped to what it emits and consumes/, radarrIssued); await mesh(`assign ${MACHINE} radarr`); // --- the operator provides the shared, pre-existing data BEFORE anything applies (ADR 0051) ------ // The host mounts an access and creates nothing, refusing any path that is absent. These three are // the operator's — a media library and a download spool that existed before the mesh — so an // ordinary mkdir on the node stands in for the operator, and 1000:1000 matches the *arr PUID/PGID. await must(`mkdir -p /services/media/downloads /services/media/series /services/media/movies`); await must(`chown -R 1000:1000 /services/media`); // --- ONE push — THE co-access proof -------------------------------------------------------------- // Pre-0051 this refused: sonarr and radarr both name /services/media/downloads, which the resolver // read as two modules owning one path. Now each ACCESSES it, so the pair co-resolves and both are // sent in a single declaration. A refusal here (nonzero, or "could not be resolved") is the // regression this bed exists to catch. const pushed = await on(`docker exec mesh-control /mesh-control push ${MACHINE}`); assert.ok(pushed.ok, `the co-resident push was REFUSED — the shared-access collision ADR 0051 removed is back:\n${pushed.out}`); assert.doesNotMatch(pushed.out, /could not be resolved|both declare the path|shared data is the operator/, `the push named a resolution refusal — co-access did not resolve (ADR 0051):\n${pushed.out}`); assert.match(pushed.out, new RegExp(`sent ${MACHINE}|node\\(s\\) told`), `the push did not report sending the node its declaration:\n${pushed.out}`); // The node applies both modules and converges once. await settled(1_200_000); // --- co-residence: every container of both modules is up on the one node ------------------------- const running = await must(`docker ps --format '{{.Names}}'`); for (const name of ["sonarr", "mesh-sonarr", "radarr", "mesh-radarr"]) { assert.match(running, new RegExp(`(^|\\n)${name}(\\n|$)`), `${name} is not running after a co-resident push:\n${running}\n---host log---\n${(await on(`tail -40 /var/log/mesh-host.log`)).out}`); } // Each module got its own scoped broker account (both emit events). const users = await must(`docker exec mesh-broker lavinmqctl list_users 2>&1`); for (const acct of ["anchor-sonarr", "anchor-radarr"]) { assert.match(users, new RegExp(acct), `the scoped account ${acct} is not on the broker:\n${users}`); } // --- THE access, made concrete: BOTH server containers mount the SAME operator-owned directory --- // Two modules, one shared spool — the co-access is not just a resolution that passed, it is the // same host path bound into both containers. And the mesh created neither the spool nor the // libraries: they are the operator's, mounted as declared. const mountsOf = async (container: string): Promise => must(`docker inspect -f '{{range .Mounts}}{{.Source}}->{{.Destination}} {{end}}' ${container}`); const sonarrMounts = await mountsOf("sonarr"); const radarrMounts = await mountsOf("radarr"); assert.match(sonarrMounts, /\/services\/media\/downloads->\/downloads/, `sonarr does not mount the shared download spool:\n${sonarrMounts}`); assert.match(radarrMounts, /\/services\/media\/downloads->\/downloads/, `radarr does not mount the shared download spool:\n${radarrMounts}`); assert.match(sonarrMounts, /\/services\/media\/series->\/series/, `sonarr does not mount its series library:\n${sonarrMounts}`); assert.match(radarrMounts, /\/services\/media\/movies->\/movies/, `radarr does not mount its movies library:\n${radarrMounts}`); // --- both runtimes bind their serve queues under their scoped accounts (the tools are up) -------- let served = ""; const untilServing = Date.now() + 120_000; while (Date.now() < untilServing) { served = await must(`docker exec mesh-broker lavinmqctl list_queues name 2>&1 || true`); if (/serve\.sonarr\.sonarr_status/.test(served) && /serve\.radarr\.radarr_status/.test(served)) break; await new Promise((r) => setTimeout(r, 3000)); } assert.match(served, /serve\.sonarr\.sonarr_status/, `sonarr's runtime never bound its serve queue:\n${(await on(`docker logs mesh-sonarr 2>&1 | tail -20`)).out}\n---\n${served}`); assert.match(served, /serve\.radarr\.radarr_status/, `radarr's runtime never bound its serve queue:\n${(await on(`docker logs mesh-radarr 2>&1 | tail -20`)).out}\n---\n${served}`); });