// `archilyzer service install|status|logs|restart|uninstall` — the apps as // systemd user units, in Docker or on the host (release 32), and `service // storage-overlay`, the compose overlay that mounts every media drive at the // path the corpus's links name. // // The units are rendered by lib/service/units.ts (pure, tested byte for byte); // this file gathers the context, compares with what is installed, writes, and // drives systemctl / journalctl / loginctl / docker. Linux and systemd only — a // clear refusal anywhere else. // // Installing over units that already exist under the same names ADOPTS them: // identical text is left alone; a difference is shown as a diff and refused // unless --force, so a hand-tuned unit is never overwritten by accident. // Replacing a unit that is running does not restart it — `service restart` // does that, when its jobs can be interrupted. // // `--dry-run` prints the units and the commands and writes nothing. import { spawn, spawnSync, type SpawnSyncReturns } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { findOnPath } from "../lib/ttsInstall"; import { composeArgs, defaultMemory, DOCKER_APPS, DOCKER_UNIT, HOST_APPS, HOUSEKEEPING_SERVICE, HOUSEKEEPING_TIMER, hostUnitName, renderDockerUnit, renderHostUnit, renderHousekeepingService, renderHousekeepingTimer, renderSiteUnit, siteUnitName, unitDiff, type DockerApp, type HostApp, type MemoryLimit, } from "../lib/service/units"; export type ServiceMode = "docker" | "host"; export type ServiceOptions = { mode?: string; apps?: string; sites?: string; overlays?: string; bind?: string; editorPort?: string; umtoolPort?: string; editorMemory?: string; umtoolMemory?: string; idleBoot?: boolean; // Host mode: leave out archilyzer-housekeeping.timer and its service. noHousekeeping?: boolean; linger?: boolean; dryRun?: boolean; force?: boolean; noStart?: boolean; follow?: boolean; lines?: string; }; type Out = { log: (s: string) => void; error: (s: string) => void }; export type ServiceDeps = { env: NodeJS.ProcessEnv; out: Out; platform: NodeJS.Platform; // The checkout (paths.monorepoRoot). repoRoot: string; // Paths the status and the overlay read. settingsFile: string; exportBuildsDir: string; memTotalBytes: number; nodeBin: string; // The login name linger is about. user: string; // A probe of http://127.0.0.1:/ — the status code, or a word. probe: (url: string) => Promise; }; export async function defaultDeps(): Promise { const { getPaths } = await import("../lib/paths"); const p = getPaths(); return { env: process.env, out: console, platform: process.platform, repoRoot: p.monorepoRoot, settingsFile: p.settingsFile, exportBuildsDir: p.exportBuildsDir, memTotalBytes: os.totalmem(), nodeBin: process.execPath, user: os.userInfo().username, probe: async (url) => { try { const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(3000) }); return String(res.status); } catch { return "not answering"; } }, }; } // --- shared -------------------------------------------------------------- class Refusal extends Error {} function unitDir(env: NodeJS.ProcessEnv): string { const home = env.HOME || os.homedir(); return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "systemd", "user"); } function run(bin: string, args: string[], env: NodeJS.ProcessEnv, cwd?: string): SpawnSyncReturns { return spawnSync(bin, args, { env, cwd, encoding: "utf8" }); } function need(bin: string, env: NodeJS.ProcessEnv, why: string): string { const found = findOnPath(bin, env.PATH); if (!found) throw new Refusal(`${bin} is not on PATH — ${why}`); return found; } function refuseOffLinux(deps: ServiceDeps): void { if (deps.platform !== "linux") { throw new Refusal( `archilyzer service needs Linux and systemd (this is ${deps.platform}). In Docker Desktop, ` + "compose's own `restart: unless-stopped` brings the stack back with Docker — `docker compose up -d` is the whole install.", ); } } function splitList(v: string | undefined): string[] { return (v ?? "") .split(",") .map((s) => s.trim()) .filter(Boolean); } function installedUnits(dir: string): string[] { let names: string[]; try { names = fs.readdirSync(dir); } catch { return []; } return names.filter((n) => n === DOCKER_UNIT || /^archilyzer-[a-z0-9-]+\.service$/.test(n) || n === HOUSEKEEPING_TIMER).sort(); } /** The housekeeping pair: run by the timer, never restarted with the apps. */ const isHousekeeping = (u: string) => u === HOUSEKEEPING_SERVICE || u === HOUSEKEEPING_TIMER; /** What `systemctl enable` takes: every unit but the housekeeping service (it has no [Install]; the timer starts it). */ const enableable = (units: string[]) => units.filter((u) => u !== HOUSEKEEPING_SERVICE); function dockerAvailable(env: NodeJS.ProcessEnv): string | null { const docker = findOnPath("docker", env.PATH); if (!docker) return null; return run(docker, ["compose", "version"], env).status === 0 ? docker : null; } /** The mode a command acts on: --mode, else what is installed, else docker when compose answers, else host. */ export function resolveMode(opts: ServiceOptions, deps: ServiceDeps): ServiceMode { if (opts.mode !== undefined) { if (opts.mode !== "docker" && opts.mode !== "host") throw new Refusal("--mode is docker or host"); return opts.mode; } const installed = installedUnits(unitDir(deps.env)); if (installed.some((u) => u !== DOCKER_UNIT)) return "host"; if (installed.includes(DOCKER_UNIT)) return "docker"; return dockerAvailable(deps.env) ? "docker" : "host"; } function parsePort(v: string | undefined, fallback: number, name: string): number { if (v === undefined) return fallback; const n = Number(v); if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Refusal(`--${name} is a port number`); return n; } function parseMemory(v: string | undefined, fallback: MemoryLimit, name: string): MemoryLimit { if (v === undefined) return fallback; const m = /^(\d+)G$/i.exec(v.trim()); if (!m || Number(m[1]) < 2) throw new Refusal(`--${name} is whole GiB, at least 2 (e.g. 8G); MemoryHigh is set 1G under it`); const max = Number(m[1]); return { high: max - 1, max }; } type Planned = { name: string; text: string }; function anthropicKeyFile(env: NodeJS.ProcessEnv): string { const home = env.HOME || os.homedir(); return env.ARCHILYZER_ANTHROPIC_ENV_FILE || path.join(home, ".config", "archilyzer", "anthropic.env"); } /** The compose overlays a docker unit runs with: --overlays, or the automatic ones. */ export function resolveOverlays(opts: ServiceOptions, deps: ServiceDeps): { files: string[]; why: string[] } { const list = splitList(opts.overlays); if (list.length === 1 && list[0] === "none") return { files: [], why: [] }; if (list.length > 0) { const files = list.map((name) => `docker-compose.${name}.yml`); for (const f of files) { if (!fs.existsSync(path.join(deps.repoRoot, f))) throw new Refusal(`no ${f} in ${deps.repoRoot}`); } return { files, why: files.map((f) => `${f} (--overlays)`) }; } const files: string[] = []; const why: string[] = []; // The key file's EXISTENCE only — it is never opened here. if (fs.existsSync(anthropicKeyFile(deps.env))) { files.push("docker-compose.anthropic.yml"); why.push("docker-compose.anthropic.yml (the Claude API key file exists)"); } if (fs.existsSync(path.join(deps.repoRoot, "docker-compose.storage.yml"))) { files.push("docker-compose.storage.yml"); why.push("docker-compose.storage.yml (written by `archilyzer service storage-overlay`)"); } return { files, why }; } /** The units `install` would write, rendered. */ export function planUnits(mode: ServiceMode, opts: ServiceOptions, deps: ServiceDeps): Planned[] { const home = deps.env.HOME || os.homedir(); if (mode === "docker") { if (opts.sites) throw new Refusal("--sites is host mode's; in Docker the `site` profile serves the local deploy"); const apps = splitList(opts.apps ?? "editor"); for (const a of apps) { if (!DOCKER_APPS.includes(a as DockerApp)) throw new Refusal(`docker mode's apps are ${DOCKER_APPS.join(", ")} — not "${a}"`); } const docker = need("docker", deps.env, "docker mode runs `docker compose`"); const { files } = resolveOverlays(opts, deps); return [ { name: DOCKER_UNIT, text: renderDockerUnit({ repoRoot: deps.repoRoot, home, dockerBin: docker, apps: apps as DockerApp[], overlays: files }), }, ]; } const apps = splitList(opts.apps ?? HOST_APPS.join(",")); for (const a of apps) { if (!HOST_APPS.includes(a as HostApp)) throw new Refusal(`host mode's apps are ${HOST_APPS.join(", ")} — not "${a}" (private sites: --sites :)`); } // Next's own default, and what the editor has always been started with here. // The editor has no login: on a machine others can reach, pass --bind 127.0.0.1. const bind = opts.bind ?? "0.0.0.0"; const planned: Planned[] = []; for (const app of apps as HostApp[]) { const port = app === "editor" ? parsePort(opts.editorPort, 3001, "editor-port") : parsePort(opts.umtoolPort, 3050, "umtool-port"); const memory = app === "editor" ? parseMemory(opts.editorMemory, defaultMemory("editor", deps.memTotalBytes), "editor-memory") : parseMemory(opts.umtoolMemory, defaultMemory("umtool", deps.memTotalBytes), "umtool-memory"); planned.push({ name: hostUnitName(app), text: renderHostUnit(app, { repoRoot: deps.repoRoot, home, nodeBin: deps.nodeBin, bind, port, memory, idleBoot: opts.idleBoot === true }), }); } for (const spec of splitList(opts.sites)) { const m = /^([a-z0-9][a-z0-9-]*):(\d+)$/.exec(spec); if (!m) throw new Refusal(`--sites takes :[,:] — not "${spec}"`); const port = parsePort(m[2], 0, "sites"); planned.push({ name: siteUnitName(m[1]), text: renderSiteUnit({ repoRoot: deps.repoRoot, home, nodeBin: deps.nodeBin, siteId: m[1], bundleDir: path.join(deps.exportBuildsDir, m[1], "out"), port, }), }); } if (!opts.noHousekeeping) { planned.push( { name: HOUSEKEEPING_SERVICE, text: renderHousekeepingService({ repoRoot: deps.repoRoot, home, nodeBin: deps.nodeBin }) }, { name: HOUSEKEEPING_TIMER, text: renderHousekeepingTimer() }, ); } return planned; } // --- install ------------------------------------------------------------- export async function install(opts: ServiceOptions, deps: ServiceDeps): Promise { refuseOffLinux(deps); const { out, env } = deps; const mode = resolveMode(opts, deps); const planned = planUnits(mode, opts, deps); const dir = unitDir(env); const systemctl = opts.dryRun ? "systemctl" : need("systemctl", env, "the units are systemd user units"); out.log(`mode: ${mode}${opts.mode === undefined ? " (default)" : ""}; units in ${dir}`); if (mode === "docker") { for (const w of resolveOverlays(opts, deps).why) out.log(`overlay: ${w}`); } // Compare with what is there. const toWrite: Planned[] = []; let refused = false; for (const unit of planned) { const file = path.join(dir, unit.name); let installed: string | null = null; try { installed = fs.readFileSync(file, "utf8"); } catch { installed = null; } if (installed === null) { out.log(`+ ${unit.name}: new`); toWrite.push(unit); } else if (installed === unit.text) { out.log(`= ${unit.name}: already installed, identical — adopted`); } else { out.log(`! ${unit.name}: installed, and different from what this would write:`); out.log(unitDiff(installed, unit.text).replace(/^/gm, " ")); if (opts.force) toWrite.push(unit); else refused = true; } } if (refused) { out.error("Refused: a unit above differs from the installed one. Pass --force to replace it (a running unit is not restarted; `archilyzer service restart` does that)."); return 1; } // What a start would refuse on, said now. for (const w of buildWarnings(mode, planned, opts, deps)) out.log(`note: ${w}`); const names = enableable(planned.map((u) => u.name)); const cmds: string[][] = []; if (toWrite.length) cmds.push([systemctl, "--user", "daemon-reload"]); cmds.push([systemctl, "--user", "enable", ...(opts.noStart ? [] : ["--now"]), ...names]); const user = deps.user; if (opts.linger) cmds.push(["loginctl", "enable-linger", user]); if (opts.dryRun) { for (const unit of planned) { out.log(`\n--- ${path.join(dir, unit.name)} ---\n${unit.text}`); } out.log("Would run:"); for (const c of cmds) out.log(` ${c.join(" ")}`); out.log("(dry run: nothing written)"); return 0; } // A unit replaced while it runs keeps running the old text until a restart. const replacedRunning = toWrite.filter((u) => fs.existsSync(path.join(dir, u.name)) && isActive(systemctl, u.name, env)); fs.mkdirSync(dir, { recursive: true }); for (const unit of toWrite) { const file = path.join(dir, unit.name); const tmp = `${file}.tmp-${process.pid}`; fs.writeFileSync(tmp, unit.text); fs.renameSync(tmp, file); out.log(`wrote ${file}`); } for (const c of cmds) { const r = run(c[0], c.slice(1), env); if (r.status !== 0) { out.error(`${c.join(" ")} failed: ${(r.stderr || r.stdout || "").trim()}`); return 1; } out.log(`ran: ${c.join(" ")}`); } if (replacedRunning.length) { out.log(`Replaced while running: ${replacedRunning.map((u) => u.name).join(", ")} — the new unit applies at the next restart (archilyzer service restart).`); } if (!opts.linger && !lingerOn(user, env)) { out.log(`Linger is off for ${user}: these units start when you log in, not at boot. --linger turns it on (loginctl enable-linger ${user}).`); } return 0; } function isActive(systemctl: string, unit: string, env: NodeJS.ProcessEnv): boolean { return run(systemctl, ["--user", "is-active", "--quiet", unit], env).status === 0; } function lingerOn(user: string, env: NodeJS.ProcessEnv): boolean { const r = run("loginctl", ["show-user", user, "--property=Linger"], env); return r.status === 0 && /Linger=yes/.test(r.stdout); } function buildWarnings(mode: ServiceMode, planned: Planned[], opts: ServiceOptions, deps: ServiceDeps): string[] { const out: string[] = []; if (mode === "host") { for (const unit of planned) { const app = /^archilyzer-(editor|umtool)\.service$/.exec(unit.name)?.[1]; if (app && !fs.existsSync(path.join(deps.repoRoot, app, ".next", "BUILD_ID"))) { out.push(`${app} has no build yet; its unit refuses to start until there is one — pnpm --filter ${app} exec next build`); } const site = /^archilyzer-site-(.+)\.service$/.exec(unit.name)?.[1]; if (site && !fs.existsSync(path.join(deps.exportBuildsDir, site, "out"))) { out.push(`site ${site} has no bundle yet; its unit refuses to start until there is one — pnpm archilyzer publish build ${site}`); } } return out; } const docker = findOnPath("docker", deps.env.PATH); if (!docker) return out; const apps = splitList(opts.apps ?? "editor") as DockerApp[]; const args = composeArgs({ apps, overlays: resolveOverlays(opts, deps).files }); const images = run(docker, [...args, "config", "--images"], deps.env, deps.repoRoot); if (images.status !== 0) { out.push(`docker compose config failed: ${(images.stderr || "").trim().split("\n")[0]}`); return out; } for (const image of images.stdout.split("\n").map((s) => s.trim()).filter((s) => s.startsWith("archilyzer:"))) { if (run(docker, ["image", "inspect", image], deps.env).status !== 0) { out.push(`image ${image} is not built; the unit refuses to start until it is — docker ${args.join(" ")} build`); } } return out; } // --- status -------------------------------------------------------------- function show(systemctl: string, unit: string, env: NodeJS.ProcessEnv, which = "LoadState,ActiveState,SubState,MainPID,UnitFileState,ActiveEnterTimestamp"): Record { const r = run(systemctl, ["--user", "show", unit, `--property=${which}`], env); const props: Record = {}; for (const line of (r.stdout || "").split("\n")) { const i = line.indexOf("="); if (i > 0) props[line.slice(0, i)] = line.slice(i + 1); } return props; } function unitField(text: string, key: string): string | undefined { return new RegExp(`^${key}=(.*)$`, "m").exec(text)?.[1]; } function laneLine(settingsText: string | null): string { if (settingsText === null) return "transcription lane: settings not readable"; try { const s = JSON.parse(settingsText) as { autoQueue?: { transcription?: { held?: unknown; enabled?: unknown } } }; const t = s.autoQueue?.transcription ?? {}; return `transcription lane: ${t.held === true ? "HELD" : "free"}${t.enabled === true ? ", armed" : ", not armed"}`; } catch { return "transcription lane: settings do not parse"; } } export async function status(opts: ServiceOptions, deps: ServiceDeps): Promise { refuseOffLinux(deps); const { out, env } = deps; const dir = unitDir(env); const units = installedUnits(dir); if (units.length === 0) { out.log(`No archilyzer units in ${dir}. Install them: archilyzer service install [--mode docker|host]`); return 0; } const systemctl = need("systemctl", env, "status asks systemd"); for (const unit of units) { const text = fs.readFileSync(path.join(dir, unit), "utf8"); if (unit === HOUSEKEEPING_TIMER) { const t = show(systemctl, unit, env, "ActiveState,UnitFileState,NextElapseUSecRealtime,LastTriggerUSec"); out.log(`${unit}: ${t.ActiveState ?? "?"}, ${t.UnitFileState ?? "?"}${t.NextElapseUSecRealtime ? `, next ${t.NextElapseUSecRealtime}` : ""}${t.LastTriggerUSec ? `, last ${t.LastTriggerUSec}` : ""}`); const { readRecord, recordFileFor } = await import("./housekeeping"); const file = recordFileFor(env, env.HOME || os.homedir()); const last = readRecord(file).at(-1); if (!last) out.log(` no run recorded yet (${file})`); else if (last.skipped) out.log(` last run ${last.at}: ${last.skipped}${last.skips ? ` (${last.skips} times since ${last.firstSkippedAt})` : ""}`); else out.log(` last run ${last.at}: freed about ${(last.freedBytes / 1e9).toFixed(1)} GB${last.errors.length ? `, ${last.errors.length} error(s)` : ""} — ${file}`); continue; } const p = show(systemctl, unit, env); const state = `${p.ActiveState ?? "?"} (${p.SubState ?? "?"})`; const enabled = p.UnitFileState ?? "?"; out.log(`${unit}: ${state}, ${enabled}${p.MainPID && p.MainPID !== "0" ? `, pid ${p.MainPID}` : ""}${p.ActiveEnterTimestamp ? `, since ${p.ActiveEnterTimestamp}` : ""}`); const exec = unitField(text, "ExecStart") ?? ""; const workdir = unitField(text, "WorkingDirectory") ?? ""; if (unit === DOCKER_UNIT) { const docker = findOnPath("docker", env.PATH); const args = exec.split(" ").slice(1, -2); // drop the docker path, then "up --no-build" if (docker) { const ps = run(docker, [...args, "ps", "--format", "{{.Service}}\t{{.State}}\t{{.Status}}"], env, workdir); for (const row of (ps.stdout || "").split("\n").filter(Boolean)) out.log(` ${row.replace(/\t/g, " ")}`); const port = readDotEnv(path.join(workdir, ".env")).EDITOR_HTTP_PORT ?? "8081"; out.log(` editor http://127.0.0.1:${port}/ → ${await deps.probe(`http://127.0.0.1:${port}/`)}`); const settings = run(docker, [...args, "exec", "-T", "editor", "cat", "/data/config/settings.json"], env, workdir); out.log(` ${laneLine(settings.status === 0 ? settings.stdout : null)}`); } continue; } const port = /-p (\d+)$/.exec(exec)?.[1] ?? / (\d+)$/.exec(exec)?.[1]; if (/archilyzer-(editor|umtool)\.service/.test(unit)) { let buildId = "none"; try { buildId = fs.readFileSync(path.join(workdir, ".next", "BUILD_ID"), "utf8").trim(); } catch { /* none */ } out.log(` build ${buildId}`); } if (port) out.log(` http://127.0.0.1:${port}/ → ${await deps.probe(`http://127.0.0.1:${port}/`)}`); if (unit === hostUnitName("editor")) { let text: string | null = null; try { text = fs.readFileSync(deps.settingsFile, "utf8"); } catch { text = null; } out.log(` ${laneLine(text)}`); } } return 0; } function readDotEnv(file: string): Record { const outv: Record = {}; let text = ""; try { text = fs.readFileSync(file, "utf8"); } catch { return outv; } for (const raw of text.split("\n")) { const m = /^\s*([A-Z_][A-Z0-9_]*)=(.*)$/.exec(raw); // Only the port keys are ever read from here; nothing else is kept. if (m && /_HTTP_PORT$/.test(m[1])) outv[m[1]] = m[2].trim(); } return outv; } // --- logs / restart / uninstall ---------------------------------------------- function selectUnits(opts: ServiceOptions, deps: ServiceDeps): string[] { const units = installedUnits(unitDir(deps.env)); const apps = splitList(opts.apps); if (apps.length === 0) return units; const wanted = new Set(apps.flatMap((a) => [hostUnitName(a as HostApp), siteUnitName(a.replace(/^site-/, ""))])); if (apps.includes("docker")) wanted.add(DOCKER_UNIT); if (apps.includes("housekeeping")) [HOUSEKEEPING_SERVICE, HOUSEKEEPING_TIMER].forEach((u) => wanted.add(u)); return units.filter((u) => wanted.has(u)); } export async function logs(opts: ServiceOptions, deps: ServiceDeps): Promise { refuseOffLinux(deps); const units = selectUnits(opts, deps); if (units.length === 0) { deps.out.error("No archilyzer units installed (or none matches --apps)."); return 1; } const journalctl = need("journalctl", deps.env, "logs read the journal"); const lines = opts.lines ?? "200"; if (!/^\d+$/.test(lines)) throw new Refusal("--lines is a number"); const args = ["--user", ...units.flatMap((u) => ["-u", u]), "-n", lines, "--no-pager", ...(opts.follow ? ["-f"] : [])]; return new Promise((resolve) => { const child = spawn(journalctl, args, { stdio: "inherit", env: deps.env }); child.on("close", (code) => resolve(code ?? 1)); child.on("error", () => resolve(1)); }); } export async function restart(opts: ServiceOptions, deps: ServiceDeps): Promise { refuseOffLinux(deps); // Restarting the oneshot would RUN housekeeping; the timer has nothing to restart. const units = selectUnits(opts, deps).filter((u) => !isHousekeeping(u)); if (units.length === 0) { deps.out.error("No archilyzer units installed (or none matches --apps)."); return 1; } const cmd = ["--user", "restart", ...units]; if (opts.dryRun) { deps.out.log(`Would run: systemctl ${cmd.join(" ")}`); return 0; } const systemctl = need("systemctl", deps.env, "restart asks systemd"); const r = run(systemctl, cmd, deps.env); if (r.status !== 0) { deps.out.error(`systemctl ${cmd.join(" ")} failed: ${(r.stderr || "").trim()}`); return 1; } deps.out.log(`restarted ${units.join(", ")}`); return 0; } export async function uninstall(opts: ServiceOptions, deps: ServiceDeps): Promise { refuseOffLinux(deps); const dir = unitDir(deps.env); let units = selectUnits(opts, deps); if (opts.mode === "docker") units = units.filter((u) => u === DOCKER_UNIT); if (opts.mode === "host") units = units.filter((u) => u !== DOCKER_UNIT); if (units.length === 0) { deps.out.log(`Nothing to uninstall in ${dir}.`); return 0; } const toDisable = enableable(units); const cmds = [ ["systemctl", "--user", "disable", "--now", ...toDisable], ["systemctl", "--user", "daemon-reload"], ]; if (opts.dryRun) { deps.out.log("Would run:"); if (toDisable.length) deps.out.log(` ${cmds[0].join(" ")}`); for (const u of units) deps.out.log(` rm ${path.join(dir, u)}`); deps.out.log(` ${cmds[1].join(" ")}`); return 0; } const systemctl = need("systemctl", deps.env, "uninstall asks systemd"); const stop = toDisable.length ? run(systemctl, cmds[0].slice(1), deps.env) : { status: 0, stderr: "" }; if (stop.status !== 0) { deps.out.error(`systemctl ${cmds[0].slice(1).join(" ")} failed: ${(stop.stderr || "").trim()}`); return 1; } for (const u of units) { fs.rmSync(path.join(dir, u), { force: true }); deps.out.log(`removed ${path.join(dir, u)}`); } run(systemctl, cmds[1].slice(1), deps.env); return 0; } // --- storage-overlay --------------------------------------------------------- export type StorageOverlayOptions = { out?: string; corpus?: string; check?: boolean; dryRun?: boolean }; /** * The directories a container must see at the SAME absolute path for the * corpus's links to resolve: every storage location's root, every channel * `media` link whose target no location covers, and the saved-video store when * it is a link. Read off the corpus disk only (lstat/readlink) — no media drive * is touched, so an unmounted one cannot stall this. */ export function storageMounts(input: { locationRoots: string[]; channelsDir: string; savedVideosDir: string }): string[] { const roots = input.locationRoots.filter((r) => path.isAbsolute(r)).map((r) => path.resolve(r)); const under = (p: string) => roots.some((r) => p === r || p.startsWith(r + path.sep)); const extra = new Set(); const linkTarget = (p: string): string | null => { try { if (!fs.lstatSync(p).isSymbolicLink()) return null; const t = fs.readlinkSync(p); return path.isAbsolute(t) ? path.resolve(t) : null; } catch { return null; } }; let slugs: string[] = []; try { slugs = fs.readdirSync(input.channelsDir); } catch { slugs = []; } for (const slug of slugs.sort()) { for (const name of ["media", "data"]) { const t = linkTarget(path.join(input.channelsDir, slug, name)); if (t && !under(t)) extra.add(t); } } const saved = linkTarget(input.savedVideosDir); if (saved && !under(saved)) extra.add(saved); return [...new Set([...roots, ...[...extra].sort()])]; } export function renderStorageOverlay(mounts: string[], corpus?: string): string { const bind = (source: string, target: string) => [ " - type: bind", ` source: ${source}`, ` target: ${target}`, " bind:", " create_host_path: false", ]; const volumes = [ ...(corpus ? bind(corpus, "/data/transcripts") : []), ...mounts.flatMap((m) => bind(m, m)), ]; const header = [ "# Generated by `archilyzer service storage-overlay` — do not edit; re-run it", "# after adding a storage location or moving a channel's media.", "#", "# Every media drive the corpus's links point at, mounted at the SAME absolute", "# path inside the containers (a channel's `media` link is absolute). A drive", "# that is not mounted on the host refuses `up` (create_host_path: false)", "# rather than mounting an empty directory the corpus would read as no media.", "#", "# docker compose -f docker-compose.yml -f docker-compose.storage.yml up -d", "# (`archilyzer service install` adds it by itself when this file exists.)", ]; if (volumes.length === 0) { return [...header, "#", "# No location, and no link to another drive: nothing to mount.", "services: {}", ""].join("\n"); } return [...header, "", "services:", " editor:", " volumes:", ...volumes, " umtool:", " volumes:", ...volumes, ""].join("\n"); } export async function storageOverlay(opts: StorageOverlayOptions, deps: ServiceDeps): Promise { const { getSettings } = await import("../lib/settings"); const { getPaths } = await import("../lib/paths"); const p = getPaths(); const settings = await getSettings(); const mounts = storageMounts({ locationRoots: settings.storage.locations.map((l) => l.root), channelsDir: p.channelsDir, savedVideosDir: p.savedVideosDir, }); const corpus = opts.corpus ? path.resolve(opts.corpus) : undefined; const text = renderStorageOverlay(mounts, corpus); const file = path.resolve(deps.repoRoot, opts.out ?? "docker-compose.storage.yml"); if (opts.dryRun) { deps.out.log(text); return 0; } if (opts.check) { let current = ""; try { current = fs.readFileSync(file, "utf8"); } catch { /* missing */ } if (current === text) { deps.out.log(`${file} is current (${mounts.length} mount${mounts.length === 1 ? "" : "s"})`); return 0; } deps.out.error(`${file} is stale — re-run archilyzer service storage-overlay`); return 1; } fs.writeFileSync(file, text); deps.out.log(`wrote ${file}: ${mounts.length} mount${mounts.length === 1 ? "" : "s"}${corpus ? `, the corpus from ${corpus}` : ""}`); for (const m of mounts) deps.out.log(` ${m}`); return 0; } // --- entry ------------------------------------------------------------------- export async function main( verb: "install" | "status" | "logs" | "restart" | "uninstall", opts: ServiceOptions, deps?: ServiceDeps, ): Promise { const d = deps ?? (await defaultDeps()); try { switch (verb) { case "install": return await install(opts, d); case "status": return await status(opts, d); case "logs": return await logs(opts, d); case "restart": return await restart(opts, d); case "uninstall": return await uninstall(opts, d); } } catch (err) { if (err instanceof Refusal) { d.out.error(`service ${verb}: ${err.message}`); return 2; } throw err; } } export async function storageOverlayMain(opts: StorageOverlayOptions, deps?: ServiceDeps): Promise { const d = deps ?? (await defaultDeps()); return storageOverlay(opts, d); }