diff --git a/packages/cli/src/cli/commands/restart.ts b/packages/cli/src/cli/commands/restart.ts index 6618560..cb68210 100644 --- a/packages/cli/src/cli/commands/restart.ts +++ b/packages/cli/src/cli/commands/restart.ts @@ -80,8 +80,10 @@ export const restartCommand = new Command("restart") // Held from reading the state to writing it, so concurrent restarts // can't overwrite each other's process ids. - await withWorkspaceLock(workspaceDir, () => - restartServices(names, workspaceDir, controller.signal), + await withWorkspaceLock( + workspaceDir, + () => restartServices(names, workspaceDir, controller.signal), + { signal: controller.signal }, ); }); diff --git a/packages/cli/src/cli/commands/status.ts b/packages/cli/src/cli/commands/status.ts index 6b95814..8af6269 100644 --- a/packages/cli/src/cli/commands/status.ts +++ b/packages/cli/src/cli/commands/status.ts @@ -1,45 +1,127 @@ import { Command } from "commander"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; import { readState } from "../../orchestrator/state"; import { loadWorkspaceConfig } from "../../config/loader"; import { composePs, type ComposeServiceStatus } from "../../runner/compose"; -import type { WorkspaceState } from "../../orchestrator/types"; +import { serviceUrl } from "../../proxy/domains"; +import { applyModeOverride } from "../../orchestrator/start"; +import type { ServiceState, WorkspaceState } from "../../orchestrator/types"; import type { WorkspaceConfig } from "@lo1/sdk"; export type StatusDeps = { readState: (workspaceDir: string) => Promise; composePs: typeof composePs; loadConfig: (configPath?: string) => Promise; + isProcessAlive: (pid: number) => boolean; + /** Docker's state for a container (`running`, `exited`, …), or null if it doesn't exist. */ + inspectContainer: (nameOrId: string) => Promise; }; +export type ServiceRunState = "running" | "starting" | "unhealthy" | "exited"; + export type StatusServiceEntry = { name: string; - state: string; + state: ServiceRunState; mode: string; port?: number; hostPort?: number; + url?: string; }; +export type InfrastructureState = "healthy" | "starting" | "degraded" | "down" | "none"; + export type StatusResult = { workspace: string; + healthy: boolean; services: StatusServiceEntry[]; infrastructure: { - state: string; + state: InfrastructureState; services: string[]; }; }; -function deriveInfraState(statuses: ComposeServiceStatus[]): string { - if (statuses.length === 0) return "down"; +/** Exit codes for `lo1 status`, which agents and scripts rely on. */ +export const STATUS_EXIT = { healthy: 0, unhealthy: 1, notRunning: 2 } as const; - const allHealthy = statuses.every( - (s) => s.State === "running" && (s.Health === "healthy" || s.Health === ""), - ); - if (allHealthy) return "healthy"; +/** What `lo1 status` knows about the infrastructure lo1 started. */ +export type InfraExpectation = { + /** The infrastructure services lo1 started; undefined for state from older lo1 versions. */ + services?: string[]; + /** Infrastructure init tasks, which are done once they exit 0. */ + initTasks: string[]; +}; - const anyUnhealthy = statuses.some((s) => s.Health === "unhealthy"); - if (anyUnhealthy) return "degraded"; +function isSettled(s: ComposeServiceStatus, initTasks: Set): boolean { + // Only an init task is done when it has exited; stopped infrastructure is not. + if (s.State === "exited") return initTasks.has(s.Service) && s.ExitCode === 0; + return s.State === "running" && (s.Health === "healthy" || s.Health === ""); +} - return "starting"; +function hasFailed(s: ComposeServiceStatus, initTasks: Set): boolean { + if (s.Health === "unhealthy" || s.State === "dead") return true; + return s.State === "exited" && !(initTasks.has(s.Service) && s.ExitCode === 0); +} + +/** Older state files don't list the infrastructure, so fall back to what the config implies. */ +function expectsInfrastructure(expected: InfraExpectation, config: WorkspaceConfig | null) { + if (expected.services) return expected.services.length > 0; + if (!config) return true; + return config.proxy?.enabled !== false || config.extraCompose !== undefined; +} + +export function deriveInfraState( + statuses: ComposeServiceStatus[], + expected: InfraExpectation, + config: WorkspaceConfig | null, +): InfrastructureState { + if (statuses.length === 0) return expectsInfrastructure(expected, config) ? "down" : "none"; + + const initTasks = new Set(expected.initTasks); + const seen = new Set(statuses.map((s) => s.Service)); + const missing = (expected.services ?? []).some((name) => !seen.has(name)); + if (!missing && statuses.every((s) => isSettled(s, initTasks))) return "healthy"; + + const anyFailed = missing || statuses.some((s) => hasFailed(s, initTasks)); + return anyFailed ? "degraded" : "starting"; +} + +function composeRunState(status: ComposeServiceStatus | undefined): ServiceRunState { + if (!status || status.State === "exited" || status.State === "dead") return "exited"; + if (status.State !== "running") return "starting"; + if (status.Health === "unhealthy") return "unhealthy"; + if (status.Health === "starting") return "starting"; + return "running"; +} + +type RunStateContext = { + name: string; + svc: ServiceState; + workspaceName: string; + composeByService: Map; + deps: StatusDeps; +}; + +async function resolveRunState(ctx: RunStateContext): Promise { + const { name, svc, deps } = ctx; + if (svc.runner === "process") { + return svc.pid !== undefined && deps.isProcessAlive(svc.pid) ? "running" : "exited"; + } + if (svc.runner === "container") { + const state = await deps.inspectContainer( + svc.containerId ?? `lo1-${ctx.workspaceName}-${name}`, + ); + return state === "running" ? "running" : "exited"; + } + return composeRunState(ctx.composeByService.get(name)); +} + +async function loadConfigOrNull(deps: StatusDeps): Promise { + try { + return await deps.loadConfig(); + } catch { + return null; + } } export async function getWorkspaceStatus( @@ -49,90 +131,126 @@ export async function getWorkspaceStatus( const state = await deps.readState(workspaceDir); if (!state) return null; - let config: WorkspaceConfig | null; - try { - config = await deps.loadConfig(); - } catch { - config = null; - } - + // Status describes the workspace as `lo1 up --mode` started it. + const loaded = await loadConfigOrNull(deps); + const config = loaded && applyModeOverride(loaded, state.modeOverride); const statuses = await deps.composePs({ projectName: state.projectName, fileArgs: state.fileArgs, cwd: state.workspaceDir, }); + const composeByService = new Map(statuses.map((s) => [s.Service, s])); const services: StatusServiceEntry[] = []; for (const [name, svc] of Object.entries(state.services)) { const svcConfig = config?.services[name]; + // Init tasks have finished by the time the workspace is ready. + if (svcConfig?.initTask) continue; + + const runState = await resolveRunState({ + name, + svc, + workspaceName: state.workspaceName, + composeByService, + deps, + }); + const hostPort = + svcConfig?.mode === "container" ? (svcConfig.hostPort ?? svcConfig.port) : svcConfig?.port; + const url = config ? serviceUrl(config, name) : undefined; services.push({ name, - state: "running", + state: runState, mode: svcConfig?.mode ?? svc.runner, ...(svcConfig?.port !== undefined && { port: svcConfig.port }), - ...(svcConfig?.hostPort !== undefined - ? { hostPort: svcConfig.hostPort } - : svcConfig?.port !== undefined - ? { hostPort: svcConfig.port } - : {}), + ...(hostPort !== undefined && { hostPort }), + ...(url !== undefined && { url }), }); } + const infraStatuses = statuses.filter((s) => !(s.Service in state.services)); + const expected = { services: state.infraServices, initTasks: state.infraInitTasks ?? [] }; + const infraState = deriveInfraState(infraStatuses, expected, config); + // Until lo1 up has started every service, the state file lists only some of them. + const startupDone = state.ready !== false; + const healthy = + startupDone && + services.every((s) => s.state === "running") && + (infraState === "healthy" || infraState === "none"); + return { workspace: state.workspaceName, + healthy, services, - infrastructure: { - state: deriveInfraState(statuses), - services: statuses.map((s) => s.Service), - }, + infrastructure: { state: infraState, services: infraStatuses.map((s) => s.Service) }, }; } +const execAsync = promisify(execFile); + const defaultDeps: StatusDeps = { readState, composePs, loadConfig: loadWorkspaceConfig, + isProcessAlive: (pid) => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }, + inspectContainer: async (nameOrId) => { + try { + const { stdout } = await execAsync("docker", [ + "inspect", + "--format", + "{{.State.Status}}", + nameOrId, + ]); + return stdout.trim(); + } catch { + return null; + } + }, }; +export function formatStatus(result: StatusResult): string { + const lines = [`Workspace: ${result.workspace} (${result.healthy ? "healthy" : "not healthy"})`]; + + if (result.infrastructure.services.length > 0) { + lines.push("", `Infrastructure: ${result.infrastructure.state}`); + for (const name of result.infrastructure.services) lines.push(` ${name}`); + } + + if (result.services.length > 0) { + lines.push("", "Services:"); + const nameWidth = Math.max(...result.services.map((s) => s.name.length)) + 2; + const stateWidth = Math.max(...result.services.map((s) => s.state.length)) + 2; + for (const svc of result.services) { + const mode = svc.port ? `${svc.mode}:${svc.port}` : svc.mode; + const url = svc.url ? ` ${svc.url}` : ""; + lines.push(` ${svc.name.padEnd(nameWidth)}${svc.state.padEnd(stateWidth)}${mode}${url}`); + } + } + + return lines.join("\n") + "\n"; +} + export const statusCommand = new Command("status") - .description("Show status of all services") + .description("Show the health of the running workspace (exit 0 healthy, 1 not, 2 not running)") .action(async function (this: Command) { const json = this.optsWithGlobals().json === true; - const workspaceDir = process.cwd(); - - const result = await getWorkspaceStatus(workspaceDir, defaultDeps); - - if (json) { - if (!result) { - process.stdout.write( - JSON.stringify({ error: "NoWorkspace", message: "No running workspace found." }) + "\n", - ); - } else { - process.stdout.write(JSON.stringify(result) + "\n"); - } - return; - } + const result = await getWorkspaceStatus(process.cwd(), defaultDeps); if (!result) { - console.log("No running workspace found."); + const message = "No running workspace found."; + process.stdout.write( + json ? JSON.stringify({ error: "NoWorkspace", message }) + "\n" : message + "\n", + ); + process.exitCode = STATUS_EXIT.notRunning; return; } - console.log(`Workspace: ${result.workspace}\n`); - - if (result.infrastructure.services.length > 0) { - console.log(`Infrastructure: ${result.infrastructure.state}`); - for (const name of result.infrastructure.services) { - console.log(` ${name}`); - } - } - - if (result.services.length > 0) { - console.log("\nServices:"); - const maxName = Math.max(...result.services.map((s) => s.name.length)); - for (const svc of result.services) { - const port = svc.port ? `:${svc.port}` : ""; - console.log(` ${svc.name.padEnd(maxName + 2)} ${svc.mode}${port}`); - } - } + process.stdout.write(json ? JSON.stringify(result) + "\n" : formatStatus(result)); + process.exitCode = result.healthy ? STATUS_EXIT.healthy : STATUS_EXIT.unhealthy; }); diff --git a/packages/cli/src/cli/commands/up.ts b/packages/cli/src/cli/commands/up.ts index 40b8072..bbe2c0b 100644 --- a/packages/cli/src/cli/commands/up.ts +++ b/packages/cli/src/cli/commands/up.ts @@ -3,35 +3,50 @@ import { spawn } from "node:child_process"; import { platform } from "node:os"; import { buildServiceState, startWorkspace } from "../../orchestrator/start"; import { hydrateHandles, stopWorkspace } from "../../orchestrator/stop"; -import { watchPluginServices } from "../../orchestrator/watch"; +import { watchPluginServices, type WatchHandle } from "../../orchestrator/watch"; import { withWorkspaceLock } from "../../orchestrator/lock"; import { readState, writeState } from "../../orchestrator/state"; import { startService, type ServiceHandle } from "../../orchestrator/service"; import { executeHook } from "../../hooks/executor"; import { loadWorkspaceConfig } from "../../config/loader"; -import { collectDomains } from "../../proxy/domains"; +import { collectDomains, serviceUrl } from "../../proxy/domains"; import { initLogDir, appendLog, logDir } from "../../logs/writer"; import { createEventFormatter } from "../../output/format"; import type { WorkspaceConfig } from "@lo1/sdk"; -import type { OrchestratorEvent } from "../../orchestrator/types"; - -function printReadySummary(config: WorkspaceConfig, workspaceDir: string, detached: boolean): void { - const tld = config.proxy?.tld ?? "local"; - const tlsEnabled = config.proxy?.tls?.enabled === true; - const scheme = tlsEnabled ? "https" : "http"; - const lines: string[] = ["", ` Workspace ${config.name} is ready!`, ""]; - - const serviceUrls: { name: string; url: string }[] = []; - for (const [name, service] of Object.entries(config.services)) { - if (service.mode === "skip" || service.initTask || !service.port) continue; - const domain = service.proxy?.domain ?? `${name}.${config.name}.${tld}`; - serviceUrls.push({ name, url: `${scheme}://${domain}` }); - } +import type { OrchestratorEvent, StartResult } from "../../orchestrator/types"; + +function formatSeconds(ms: number): string { + return `${(ms / 1000).toFixed(1)}s`; +} + +type ReadyResult = Pick; + +function readyServices(config: WorkspaceConfig): { name: string; url: string }[] { + return Object.keys(config.services).flatMap((name) => { + const url = serviceUrl(config, name); + return url ? [{ name, url }] : []; + }); +} - if (serviceUrls.length > 0) { +export function formatReadySummary( + result: ReadyResult, + workspaceDir: string, + detached: boolean, +): string { + const { config, timings } = result; + const breakdown = timings.phases.map((p) => `${p.name} ${formatSeconds(p.ms)}`).join(" · "); + const lines: string[] = [ + "", + ` Workspace ${config.name} is ready in ${formatSeconds(timings.totalMs)}`, + ` ${breakdown}`, + "", + ]; + + const services = readyServices(config); + if (services.length > 0) { lines.push(" Services:"); - const maxName = Math.max(...serviceUrls.map((s) => s.name.length)); - for (const { name, url } of serviceUrls) { + const maxName = Math.max(...services.map((s) => s.name.length)); + for (const { name, url } of services) { lines.push(` ${name.padEnd(maxName + 2)}${url}`); } lines.push(""); @@ -40,24 +55,36 @@ function printReadySummary(config: WorkspaceConfig, workspaceDir: string, detach lines.push(` Logs: ${logDir(workspaceDir)}`); lines.push(" Run lo1 logs [service] to tail, lo1 logs --list to see available"); lines.push(""); - - if (detached) { - lines.push(" Run lo1 down to stop"); - } else { - lines.push(" Press Ctrl+C to stop"); - } + lines.push(detached ? " Run lo1 down to stop" : " Press Ctrl+C to stop"); lines.push(""); - process.stdout.write(lines.join("\n")); + return lines.join("\n"); +} + +/** The one line `lo1 --json up` prints to stdout once the workspace is ready. */ +export function buildReadyJson(result: ReadyResult, workspaceDir: string, detached: boolean) { + return { + workspace: result.config.name, + ready: true, + detached, + durationMs: result.timings.totalMs, + phases: result.timings.phases, + services: readyServices(result.config), + logs: logDir(workspaceDir), + }; } +/** Exit code when Ctrl+C interrupts startup before the workspace is ready. */ +export const EXIT_INTERRUPTED = 130; + async function acquireSudo(): Promise { if (platform() === "win32") return; const config = await loadWorkspaceConfig(); const domains = collectDomains(config); const needsHosts = domains.length > 0; - const needsTls = config.proxy?.tls?.enabled && platform() === "linux"; + const needsTls = + config.proxy?.enabled !== false && config.proxy?.tls?.enabled && platform() === "linux"; if (!needsHosts && !needsTls) return; @@ -65,7 +92,7 @@ async function acquireSudo(): Promise { if (needsHosts) reasons.push("update /etc/hosts"); if (needsTls) reasons.push("trust TLS certificates"); - console.log(`lo1 needs sudo to ${reasons.join(" and ")}.\n`); + console.error(`lo1 needs sudo to ${reasons.join(" and ")}.\n`); await new Promise((resolve, reject) => { const proc = spawn("/usr/bin/sudo", ["-v"], { stdio: "inherit" }); @@ -75,7 +102,7 @@ async function acquireSudo(): Promise { proc.on("error", reject); }); - console.log(); + console.error(); } function waitForShutdownSignal(controller: AbortController): Promise { @@ -152,6 +179,45 @@ export async function recordReplacement( ); } +/** + * Follows plugins' watchForChanges() in a foreground `lo1 up`. The workspace + * is already up when this runs, so a watcher that fails to start is reported + * and the workspace keeps running without it. + */ +export function startWatching( + result: Awaited>, + workspaceDir: string, + signal: AbortSignal, + onEvent: (event: OrchestratorEvent) => void, +): WatchHandle | undefined { + try { + return watchPluginServices( + result.handles, + { + config: result.config, + workspaceDir, + registry: result.registry, + plugins: result.plugins, + pluginEnvVars: result.pluginEnvVars, + compose: result.compose, + detached: false, + signal, + emit: onEvent, + deps: { startService, executeHook }, + }, + { + runExclusive: (fn) => withWorkspaceLock(workspaceDir, fn, { signal }), + onReplaced: (handle) => recordReplacement(workspaceDir, handle), + recordedHandle: (name) => recordedHandle(workspaceDir, name), + }, + ); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + onEvent({ kind: "error", message: `Watching for changes failed to start: ${message}` }); + return undefined; + } +} + export const upCommand = new Command("up") .description("Start all services and infrastructure") .option("--services ", "Comma-separated list of services to start") @@ -159,7 +225,8 @@ export const upCommand = new Command("up") .option("-d, --detach", "Start in the background and exit") .option("--skip-teardown", "Leave containers running on exit (useful for debugging)") .option("--clean", "Remove volumes and orphan containers on teardown") - .action(async (options) => { + .action(async function (this: Command, options) { + const json = this.optsWithGlobals().json === true; const detached = options.detach === true; const skipTeardown = options.skipTeardown === true; const clean = options.clean === true; @@ -191,7 +258,8 @@ export const upCommand = new Command("up") } const msg = formatEvent(event); - if (msg) process.stdout.write(msg.trimEnd() + "\n"); + // With --json, stdout carries only the final JSON line; progress goes to stderr. + if (msg) (json ? process.stderr : process.stdout).write(msg.trimEnd() + "\n"); }; let result: Awaited> | undefined; @@ -207,7 +275,11 @@ export const upCommand = new Command("up") }); logOnly = true; - printReadySummary(result.config, workspaceDir, detached); + if (json) { + process.stdout.write(JSON.stringify(buildReadyJson(result, workspaceDir, detached)) + "\n"); + } else { + process.stdout.write(formatReadySummary(result, workspaceDir, detached)); + } if (detached) { result.logsHandle.kill(); @@ -215,29 +287,10 @@ export const upCommand = new Command("up") return; } - const watcher = watchPluginServices( - result.handles, - { - config: result.config, - workspaceDir, - registry: result.registry, - plugins: result.plugins, - pluginEnvVars: result.pluginEnvVars, - compose: result.compose, - detached: false, - signal: controller.signal, - emit: onEvent, - deps: { startService, executeHook }, - }, - { - runExclusive: (fn) => withWorkspaceLock(workspaceDir, fn), - onReplaced: (handle) => recordReplacement(workspaceDir, handle), - recordedHandle: (name) => recordedHandle(workspaceDir, name), - }, - ); + const watcher = startWatching(result, workspaceDir, controller.signal, onEvent); await waitForShutdownSignal(controller); // Let a restart under way finish, so teardown sees its new process. - await watcher.stop(); + await watcher?.stop(); } catch (err) { if (!controller.signal.aborted) { startupError = err; @@ -254,4 +307,5 @@ export const upCommand = new Command("up") }); if (startupError) throw startupError; + if (!result) process.exitCode = EXIT_INTERRUPTED; }); diff --git a/packages/cli/src/hooks/executor.ts b/packages/cli/src/hooks/executor.ts index 33ec27a..f8dad55 100644 --- a/packages/cli/src/hooks/executor.ts +++ b/packages/cli/src/hooks/executor.ts @@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "node:child_process"; import { platform } from "node:os"; import { createLog } from "../debug"; import { Lo1Error } from "../errors"; +import { followLines } from "../output/line-buffer"; const debug = createLog("hooks"); @@ -70,17 +71,11 @@ export async function executeHook( signal: options.signal, }); - if (options.onOutput && child.stdout) { - child.stdout.on("data", (chunk: Buffer) => { - options.onOutput!({ stream: "stdout", text: chunk.toString() }); - }); - } - - if (options.onOutput && child.stderr) { - child.stderr.on("data", (chunk: Buffer) => { - options.onOutput!({ stream: "stderr", text: chunk.toString() }); - }); - } + const onOutput = options.onOutput; + if (onOutput && child.stdout) + followLines(child.stdout, (text) => onOutput({ stream: "stdout", text })); + if (onOutput && child.stderr) + followLines(child.stderr, (text) => onOutput({ stream: "stderr", text })); return new Promise((resolve, reject) => { child.on("error", (err) => { diff --git a/packages/cli/src/orchestrator/lock.ts b/packages/cli/src/orchestrator/lock.ts index 484b43c..802fe9c 100644 --- a/packages/cli/src/orchestrator/lock.ts +++ b/packages/cli/src/orchestrator/lock.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises"; +import { link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createLog } from "../debug"; import { Lo1Error } from "../errors"; @@ -18,6 +18,8 @@ export type WorkspaceLockOptions = { timeoutMs?: number; pollMs?: number; isAlive?: (pid: number) => boolean; + /** Stops waiting for the lock, e.g. on Ctrl+C. */ + signal?: AbortSignal; }; export function lockPath(workspaceDir: string): string { @@ -29,7 +31,7 @@ function isProcessAlive(pid: number): boolean { process.kill(pid, 0); return true; } catch (err) { - return (err as NodeJS.ErrnoException).code === "EPERM"; + return errorCode(err) === "EPERM"; } } @@ -46,23 +48,73 @@ async function tryAcquire(path: string): Promise { await link(own, path); return true; } catch (err) { - if ((err as NodeJS.ErrnoException).code === "EEXIST") return false; + if (errorCode(err) === "EEXIST") return false; throw err; } finally { await unlink(own).catch(() => {}); } } +function errorCode(err: unknown): string | undefined { + return (err as NodeJS.ErrnoException).code; +} + +/** The lock file's contents, or null when there is no lock. Other read errors propagate. */ +async function readLock(path: string): Promise { + try { + return await readFile(path, "utf-8"); + } catch (err) { + if (errorCode(err) === "ENOENT") return null; + throw err; + } +} + +/** + * Removes the lock only if it is still the stale one we checked. The lock is + * first renamed to a private name, which is atomic, so nobody can replace it + * between our check and the removal. If what we moved turns out to be a + * newer lock, it is put back. + */ +export async function removeStaleLock(path: string, staleContent: string): Promise { + const moved = `${path}.stale.${randomUUID()}`; + try { + await rename(path, moved); + } catch (err) { + if (errorCode(err) === "ENOENT") return; + throw err; + } + + if ((await readFile(moved, "utf-8")) !== staleContent) { + debug("lock changed hands while removing a stale one; restoring it"); + await link(moved, path).catch(() => {}); + } + await unlink(moved).catch(() => {}); +} + /** The pid holding the lock, or null when the lock is gone or its holder has exited. */ async function liveHolder(path: string, isAlive: (pid: number) => boolean): Promise { - const content = await readFile(path, "utf-8").catch(() => ""); + const content = await readLock(path); + if (content === null) return null; + const pid = Number.parseInt(content, 10); if (Number.isInteger(pid) && isAlive(pid)) return pid; - await unlink(path).catch(() => {}); + await removeStaleLock(path, content); return null; } +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve) => { + const timer = setTimeout(done, ms); + signal?.addEventListener("abort", done, { once: true }); + function done() { + clearTimeout(timer); + signal?.removeEventListener("abort", done); + resolve(); + } + }); +} + /** * Runs `fn` while holding the workspace's state lock, so lo1 commands that * read, change and write the state file (restarts) never interleave. Waits @@ -73,12 +125,13 @@ export async function withWorkspaceLock( fn: () => Promise, options: WorkspaceLockOptions = {}, ): Promise { - const { timeoutMs = 120_000, pollMs = 100, isAlive = isProcessAlive } = options; + const { timeoutMs = 120_000, pollMs = 100, isAlive = isProcessAlive, signal } = options; const path = lockPath(workspaceDir); await mkdir(join(workspaceDir, ".lo1"), { recursive: true }); const deadline = Date.now() + timeoutMs; while (!(await tryAcquire(path))) { + if (signal?.aborted) throw new WorkspaceLockError("Stopped waiting for the workspace lock."); const holder = await liveHolder(path, isAlive); if (holder === null) continue; if (Date.now() >= deadline) { @@ -87,7 +140,7 @@ export async function withWorkspaceLock( `Wait for it to finish, then try again.`, ); } - await new Promise((r) => setTimeout(r, pollMs)); + await sleep(pollMs, signal); } debug("acquired %s", path); diff --git a/packages/cli/src/orchestrator/restart.ts b/packages/cli/src/orchestrator/restart.ts index 51a2cb0..eca5010 100644 --- a/packages/cli/src/orchestrator/restart.ts +++ b/packages/cli/src/orchestrator/restart.ts @@ -49,6 +49,11 @@ export async function restartService( await current.stop(); current.releaseLogs?.(); ctx.emit({ kind: "service", service: name, status: "stopped" }); + } else if (current?.type === "container") { + // An exited container (or a finished init task's) still holds its name, + // which the new container needs; stop() also removes it. + await current.stop(); + current.releaseLogs?.(); } ctx.emit({ kind: "service", service: name, status: "starting" }); diff --git a/packages/cli/src/orchestrator/service.ts b/packages/cli/src/orchestrator/service.ts index 026a8f0..957c30d 100644 --- a/packages/cli/src/orchestrator/service.ts +++ b/packages/cli/src/orchestrator/service.ts @@ -179,6 +179,8 @@ async function waitForInitTask(started: StartedRunner, options: StartServiceOpti throw new ServiceStartError("Startup aborted"); } if (code !== 0) { + // Remove a failed init task's container, so the next start can reuse its name. + await started.handle.stop().catch(() => {}); const reason = code === null ? "failed to run" : `exited with code ${code}`; throw new ServiceStartError(`Init task "${options.serviceName}" ${reason}`); } diff --git a/packages/cli/src/orchestrator/start.ts b/packages/cli/src/orchestrator/start.ts index f3a565a..78d336d 100644 --- a/packages/cli/src/orchestrator/start.ts +++ b/packages/cli/src/orchestrator/start.ts @@ -16,6 +16,7 @@ import { discoverExtraComposeServices, extraComposeFile, extraComposeInitTasks, + networkId, } from "../compose/generate"; import { generateCaddyfile, writeCaddyfile, type CaddyfileResult } from "../proxy/caddyfile"; import { generateHostsBlock, applyHosts } from "../hosts/index"; @@ -33,6 +34,8 @@ import type { OrchestratorDeps, StartOptions, StartResult, + StartTimings, + PhaseTiming, OrchestratorEvent, ServiceState, } from "./types"; @@ -95,6 +98,8 @@ function createDefaultDeps(): OrchestratorDeps { composeLogs, discoverExtraComposeServices, composeDown: (opts) => import("../runner/compose").then((m) => m.composeDown(opts)), + ensureNetwork: (project, key) => + import("../runner/compose").then((m) => m.ensureComposeNetwork(project, key)), composePs: (opts) => import("../runner/compose").then((m) => m.composePs(opts)), startService: defaultStartService, executeHook, @@ -124,6 +129,7 @@ export async function startWorkspace( const deps = { ...createDefaultDeps(), ...overrides }; const emit = options.onEvent ?? (() => {}); const workspaceDir = options.workspaceDir ?? "."; + const timer = createPhaseTimer(); await cleanupStaleWorkspace(deps, workspaceDir, emit); @@ -141,8 +147,10 @@ export async function startWorkspace( services: {} as Record, pluginEnvVars: composeResult.pluginEnvVars, ...(options.modeOverride && { modeOverride: options.modeOverride }), + infraServices: composeResult.infraServices, + infraInitTasks, }; - await deps.writeState(baseState, workspaceDir); + await deps.writeState({ ...baseState, ready: false }, workspaceDir); debug("startWorkspace: starting compose phases"); const infraLogs = await startInfrastructure( @@ -154,11 +162,17 @@ export async function startWorkspace( emit, ); + // With no infrastructure, nothing has created the network plugin containers join. + if (composeResult.infraServices.length === 0) { + await deps.ensureNetwork(composeResult.projectName, networkId(config.name)); + } + if (config.proxy?.tls?.enabled && caddyResult.internalDomains.length > 0) { debug("startWorkspace: trusting Caddy CA for %d domain(s)", caddyResult.internalDomains.length); emit({ kind: "phase", phase: "Trusting Caddy CA" }); await deps.trustCaddyCa(`${composeResult.projectName}-proxy`, workspaceDir); } + timer.mark("infrastructure", infraLogs !== undefined); checkAborted(options.signal); @@ -180,6 +194,7 @@ export async function startWorkspace( debug("startWorkspace: seeding data"); emit({ kind: "phase", phase: "Seeding data" }); await runPluginSeeding(config, plugins, registry, workspaceDir); + timer.mark("setup", hasSetupWork(config, plugins)); debug("startWorkspace: starting services"); emit({ kind: "phase", phase: "Starting services" }); @@ -202,8 +217,12 @@ export async function startWorkspace( emit, }); - await deps.writeState({ ...baseState, services: buildServiceState(handles) }, workspaceDir); + await deps.writeState( + { ...baseState, services: buildServiceState(handles), ready: true }, + workspaceDir, + ); await runWorkspaceHook({ hookName: "postSetup", ...hookCtx }); + timer.mark("services", true); emit({ kind: "phase", phase: "Ready" }); const composeOptions = { @@ -226,9 +245,34 @@ export async function startWorkspace( registry, pluginEnvVars: composeResult.pluginEnvVars, compose: composeContext, + timings: timer.result(), + }; +} + +/** Measures consecutive startup phases; `mark` closes the phase that just ran. */ +function createPhaseTimer() { + const startedAt = Date.now(); + let phaseStart = startedAt; + const phases: PhaseTiming[] = []; + return { + mark(name: string, include: boolean) { + const now = Date.now(); + if (include) phases.push({ name, ms: now - phaseStart }); + phaseStart = now; + }, + result: (): StartTimings => ({ totalMs: Date.now() - startedAt, phases }), }; } +/** Whether anything runs between infrastructure and services worth timing on its own. */ +function hasSetupWork(config: WorkspaceConfig, plugins: Map): boolean { + if (config.hooks?.postInfrastructure) return true; + return Object.values(config.services).some((service) => { + const plugin = plugins.get(service.type); + return Boolean(plugin?.provisionInfra || plugin?.seedData); + }); +} + async function cleanupStaleWorkspace( deps: OrchestratorDeps, workspaceDir: string, diff --git a/packages/cli/src/orchestrator/stop.ts b/packages/cli/src/orchestrator/stop.ts index 883c690..ed09891 100644 --- a/packages/cli/src/orchestrator/stop.ts +++ b/packages/cli/src/orchestrator/stop.ts @@ -6,7 +6,8 @@ import type { WorkspaceConfig } from "@lo1/sdk"; import { createLog } from "../debug"; import { loadWorkspaceConfig } from "../config/loader"; import { buildEndpointRegistry, buildServiceEnv } from "../discovery/registry"; -import { composeDown } from "../runner/compose"; +import { composeDown, removeComposeNetwork } from "../runner/compose"; +import { networkId } from "../compose/generate"; import { signalProcessTree } from "../runner/process"; import { executeHook } from "../hooks/executor"; import { readState as defaultReadState, removeState as defaultRemoveState } from "./state"; @@ -28,6 +29,7 @@ export type StopDeps = Pick< "loadConfig" | "composeDown" | "executeHook" | "readState" | "removeState" > & { exec?: (cmd: string, args: string[]) => Promise<{ stdout: string; stderr: string }>; + removeNetwork: (projectName: string, networkKey: string) => Promise; }; function createDefaultStopDeps(): StopDeps { @@ -38,6 +40,7 @@ function createDefaultStopDeps(): StopDeps { readState: defaultReadState, removeState: defaultRemoveState, exec: defaultExec, + removeNetwork: (project, key) => removeComposeNetwork(project, key), }; } @@ -106,12 +109,13 @@ function hydrateHandle( }; } +/** Fails closed like isGroupAlive: only ESRCH means the process is gone. */ function isAlive(pid: number): boolean { try { process.kill(pid, 0); return true; - } catch { - return false; + } catch (err) { + return (err as NodeJS.ErrnoException).code !== "ESRCH"; } } @@ -149,12 +153,24 @@ function trySignal(pid: number, signal: NodeJS.Signals): void { */ async function stopProcessByPid(pid: number, timeoutMs: number): Promise { trySignal(pid, "SIGTERM"); + if (await waitForTreeExit(pid, timeoutMs)) return; + + trySignal(pid, "SIGKILL"); + // SIGKILL can't be ignored, but the kernel may take a moment to release the + // tree; wait so a restart doesn't start while the old process holds its port. + await waitForTreeExit(pid, KILL_WAIT_MS); +} + +const KILL_WAIT_MS = 2000; +/** Polls until the process tree is gone; false if it outlasts `timeoutMs`. */ +async function waitForTreeExit(pid: number, timeoutMs: number): Promise { const deadline = Date.now() + timeoutMs; - while (isTreeAlive(pid) && Date.now() < deadline) { + while (isTreeAlive(pid)) { + if (Date.now() >= deadline) return false; await new Promise((r) => setTimeout(r, 100)); } - if (isTreeAlive(pid)) trySignal(pid, "SIGKILL"); + return true; } /** @@ -248,6 +264,7 @@ export async function stopWorkspace( cwd: state.workspaceDir, clean: options.clean, }); + await deps.removeNetwork(state.projectName, networkId(state.workspaceName)); await deps.removeState(workspaceDir); emit({ kind: "phase", phase: "Stopped" }); diff --git a/packages/cli/src/orchestrator/types.ts b/packages/cli/src/orchestrator/types.ts index 71101c5..bd51b33 100644 --- a/packages/cli/src/orchestrator/types.ts +++ b/packages/cli/src/orchestrator/types.ts @@ -52,6 +52,8 @@ export type OrchestratorDeps = { ) => ComposeLogsHandle; discoverExtraComposeServices: (path: string, workspaceDir?: string) => Promise; composeDown: (options: ComposeExecOptions & { clean?: boolean }) => Promise; + /** Creates the workspace network when no compose service will create it. */ + ensureNetwork: (projectName: string, networkKey: string) => Promise; composePs: (options: ComposeExecOptions) => Promise; startService: (options: StartServiceOptions) => Promise; executeHook: ( @@ -83,6 +85,15 @@ export type StartOptions = { onEvent?: (event: OrchestratorEvent) => void; }; +export type PhaseTiming = { name: string; ms: number }; + +/** + * How long `lo1 up` took. Phases are "infrastructure" (when there is any), + * "setup" (postInfrastructure hook and plugin provisioning/seeding, when + * there are any) and "services" (every layer, init tasks included). + */ +export type StartTimings = { totalMs: number; phases: PhaseTiming[] }; + export type StartResult = { handles: ServiceHandle[]; composeOptions: ComposeExecOptions; @@ -95,6 +106,7 @@ export type StartResult = { registry: EndpointRegistry; pluginEnvVars: Record; compose: ComposeContext; + timings: StartTimings; }; export type StopOptions = { @@ -124,4 +136,10 @@ export type WorkspaceState = { pluginEnvVars?: Record; /** The `lo1 up --mode` override, so a restart runs the service the same way. */ modeOverride?: "dev" | "container"; + /** False while `lo1 up` is still starting; true once every service is ready. */ + ready?: boolean; + /** The infrastructure services lo1 started (plugins, extraCompose, proxy). */ + infraServices?: string[]; + /** Infrastructure init tasks, which are done once they exit 0. */ + infraInitTasks?: string[]; }; diff --git a/packages/cli/src/output/line-buffer.ts b/packages/cli/src/output/line-buffer.ts index d795013..32108e7 100644 --- a/packages/cli/src/output/line-buffer.ts +++ b/packages/cli/src/output/line-buffer.ts @@ -1,17 +1,44 @@ +import type { EventEmitter } from "node:events"; + +/** Feeds chunks in; `flush` emits whatever partial line is left at the end. */ +export type LineBuffer = ((chunk: string) => void) & { flush: () => void }; + /** * Creates a line-buffering function that accumulates chunks and emits * complete lines (split on newline). Partial trailing content is held - * until the next chunk completes the line. + * until the next chunk completes the line, or until `flush`. Blank lines + * are dropped. */ -export function createLineBuffer(onLine: (line: string) => void): (chunk: string) => void { +export function createLineBuffer(onLine: (line: string) => void): LineBuffer { let buffer = ""; + const emit = (line: string) => { + const text = line.endsWith("\r") ? line.slice(0, -1) : line; + if (text.trim()) onLine(text); + }; - return (chunk: string) => { + const push = (chunk: string) => { buffer += chunk; const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; - for (const line of lines) { - if (line.trim()) onLine(line); - } + for (const line of lines) emit(line); }; + + return Object.assign(push, { + flush: () => { + const rest = buffer; + buffer = ""; + emit(rest); + }, + }); +} + +/** + * Calls `onLine` with each line a stream writes, so output from a child + * process arrives whole however the OS chunks it. A last line without a + * newline is emitted when the stream ends. + */ +export function followLines(stream: EventEmitter, onLine: (line: string) => void): void { + const buffer = createLineBuffer(onLine); + stream.on("data", (chunk: Buffer | string) => buffer(chunk.toString())); + stream.on("end", () => buffer.flush()); } diff --git a/packages/cli/src/proxy/domains.ts b/packages/cli/src/proxy/domains.ts index d4719ad..8aa23e5 100644 --- a/packages/cli/src/proxy/domains.ts +++ b/packages/cli/src/proxy/domains.ts @@ -2,9 +2,12 @@ import type { WorkspaceConfig } from "@lo1/sdk"; /** * Collects all proxy domains from workspace config. - * Used by Caddyfile generation, hosts management, and TLS setup. + * Used by Caddyfile generation, hosts management, and TLS setup. With the + * proxy disabled there are none, so lo1 leaves the hosts file alone and + * needs no sudo for it. */ export function collectDomains(config: WorkspaceConfig): string[] { + if (config.proxy?.enabled === false) return []; const tld = config.proxy?.tld ?? "local"; const baseDomain = `${config.name}.${tld}`; const domains = new Set(); @@ -30,3 +33,32 @@ export function collectDomains(config: WorkspaceConfig): string[] { return [...domains]; } + +function portSuffix(port: number, defaultPort: number): string { + return port === defaultPort ? "" : `:${port}`; +} + +/** + * The URL to open a service at: through the proxy on its first domain, or + * straight to its host port when the proxy is disabled. Undefined for + * services with no port, skip-mode services and init tasks. + */ +export function serviceUrl(config: WorkspaceConfig, name: string): string | undefined { + const service = config.services[name]; + if (!service?.port || service.mode === "skip" || service.initTask) return undefined; + + if (config.proxy?.enabled === false) { + const port = service.mode === "container" ? (service.hostPort ?? service.port) : service.port; + return `http://localhost:${port}`; + } + + const tls = config.proxy?.tls?.enabled === true; + const suffix = tls + ? portSuffix(config.proxy?.tls?.port ?? 443, 443) + : portSuffix(config.proxy?.port ?? 80, 80); + const custom = service.proxy?.domain; + const domain = + (Array.isArray(custom) ? custom[0] : custom) ?? + `${name}.${config.name}.${config.proxy?.tld ?? "local"}`; + return `${tls ? "https" : "http"}://${domain}${suffix}`; +} diff --git a/packages/cli/src/runner/compose.ts b/packages/cli/src/runner/compose.ts index be8df2b..a09ea96 100644 --- a/packages/cli/src/runner/compose.ts +++ b/packages/cli/src/runner/compose.ts @@ -337,3 +337,58 @@ export async function composePs( .filter((line) => line.trim()) .map((line) => JSON.parse(line) as ComposeServiceStatus); } + +/** + * Creates the project's network as Compose would, labelled so Compose adopts + * it and `compose down` removes it. Containers lo1 starts with `docker run` + * (plugin containers) join this network, which otherwise only exists once + * Compose has started a service. + */ +export async function ensureComposeNetwork( + projectName: string, + networkKey: string, + exec: ExecFn = defaultExec, +): Promise { + const name = `${projectName}_${networkKey}`; + try { + await exec("docker", ["network", "inspect", name]); + return; + } catch { + // Not created yet. + } + + debug("ensureComposeNetwork: creating %s", name); + try { + await exec("docker", [ + "network", + "create", + "--driver", + "bridge", + "--label", + `com.docker.compose.project=${projectName}`, + "--label", + `com.docker.compose.network=${networkKey}`, + name, + ]); + } catch (err) { + const stderr = err instanceof Error && "stderr" in err ? String(err.stderr) : undefined; + throw new ComposeExecError(`Could not create the Docker network ${name}`, stderr); + } +} + +/** + * Removes the workspace network if it is still there. `compose down` only + * removes networks when the project has services, so a network + * ensureComposeNetwork created for plugin containers would otherwise stay. + */ +export async function removeComposeNetwork( + projectName: string, + networkKey: string, + exec: ExecFn = defaultExec, +): Promise { + try { + await exec("docker", ["network", "rm", `${projectName}_${networkKey}`]); + } catch { + // Already removed by compose down, or never created. + } +} diff --git a/packages/cli/src/runner/container.ts b/packages/cli/src/runner/container.ts index 30d3afc..91a296f 100644 --- a/packages/cli/src/runner/container.ts +++ b/packages/cli/src/runner/container.ts @@ -5,6 +5,7 @@ import type { ContainerConfig } from "@lo1/sdk"; import type { OutputLine } from "./process"; import { createLog } from "../debug"; import { Lo1Error } from "../errors"; +import { followLines } from "../output/line-buffer"; const debug = createLog("runner:container"); @@ -121,27 +122,11 @@ export async function startContainer( stdio: ["ignore", "pipe", "pipe"], }); - if (options.onOutput && logChild.stdout) { - logChild.stdout.on("data", (chunk: Buffer) => { - options.onOutput!({ - service: options.serviceName, - stream: "stdout", - text: chunk.toString(), - timestamp: new Date(), - }); - }); - } - - if (options.onOutput && logChild.stderr) { - logChild.stderr.on("data", (chunk: Buffer) => { - options.onOutput!({ - service: options.serviceName, - stream: "stderr", - text: chunk.toString(), - timestamp: new Date(), - }); - }); - } + const onOutput = options.onOutput; + const emitLine = (stream: "stdout" | "stderr") => (text: string) => + onOutput?.({ service: options.serviceName, stream, text, timestamp: new Date() }); + if (onOutput && logChild.stdout) followLines(logChild.stdout, emitLine("stdout")); + if (onOutput && logChild.stderr) followLines(logChild.stderr, emitLine("stderr")); const exitPromise = new Promise((resolve) => { logChild.on("close", () => { diff --git a/packages/cli/src/runner/process.ts b/packages/cli/src/runner/process.ts index af4ce72..928bec4 100644 --- a/packages/cli/src/runner/process.ts +++ b/packages/cli/src/runner/process.ts @@ -3,6 +3,7 @@ import { closeSync, openSync } from "node:fs"; import { platform } from "node:os"; import { createLog } from "../debug"; import { Lo1Error } from "../errors"; +import { followLines } from "../output/line-buffer"; const debug = createLog("runner:process"); @@ -143,16 +144,12 @@ export function startProcess( timestamp: new Date(), }); - if (options.onOutput && child.stdout) { - child.stdout.on("data", (chunk: Buffer) => { - options.onOutput!(makeOutputLine("stdout", chunk.toString())); - }); + const onOutput = options.onOutput; + if (onOutput && child.stdout) { + followLines(child.stdout, (line) => onOutput(makeOutputLine("stdout", line))); } - - if (options.onOutput && child.stderr) { - child.stderr.on("data", (chunk: Buffer) => { - options.onOutput!(makeOutputLine("stderr", chunk.toString())); - }); + if (onOutput && child.stderr) { + followLines(child.stderr, (line) => onOutput(makeOutputLine("stderr", line))); } const exitPromise = new Promise((resolve) => { diff --git a/packages/cli/tests/cli/status.test.ts b/packages/cli/tests/cli/status.test.ts index ffe19f7..ba90bfc 100644 --- a/packages/cli/tests/cli/status.test.ts +++ b/packages/cli/tests/cli/status.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, mock } from "bun:test"; import { getWorkspaceStatus, + formatStatus, type StatusDeps, } from "../../src/cli/commands/status"; import type { WorkspaceState } from "../../src/orchestrator/types"; @@ -62,6 +63,8 @@ function makeDeps(overrides: Partial = {}): StatusDeps { loadConfig: mock(() => Promise.resolve(makeConfig({ api: { port: 3000, hostPort: 3001 } })), ), + isProcessAlive: mock(() => true), + inspectContainer: mock(() => Promise.resolve("running")), ...overrides, }; } @@ -162,8 +165,14 @@ describe("getWorkspaceStatus", () => { it("services include port and hostPort from config", async () => { const deps = makeDeps({ + readState: mock(() => + Promise.resolve(makeWorkspaceState({ services: { api: { runner: "compose" } } })), + ), + composePs: mock(() => Promise.resolve([makeComposeStatus({ Service: "api" })])), loadConfig: mock(() => - Promise.resolve(makeConfig({ api: { port: 3000, hostPort: 3001 } })), + Promise.resolve( + makeConfig({ api: { port: 3000, hostPort: 3001, mode: "container", command: undefined } }), + ), ), }); @@ -192,4 +201,191 @@ describe("getWorkspaceStatus", () => { expect(apiService).toBeDefined(); expect(apiService!.mode).toBe("container"); }); + + it("reports a dev process that has exited, and the workspace as not healthy", async () => { + const deps = makeDeps({ isProcessAlive: mock(() => false) }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.services[0].state).toBe("exited"); + expect(result!.healthy).toBe(false); + }); + + it("is healthy when every service runs and infrastructure is healthy", async () => { + const result = await getWorkspaceStatus("/workspace", makeDeps()); + + expect(result!.healthy).toBe(true); + expect(result!.services[0]).toMatchObject({ + name: "api", + state: "running", + url: "http://api.my-platform.local", + }); + }); + + it("reports compose service health from docker compose ps", async () => { + const deps = makeDeps({ + readState: mock(() => + Promise.resolve(makeWorkspaceState({ services: { worker: { runner: "compose" } } })), + ), + composePs: mock(() => + Promise.resolve([ + makeComposeStatus(), + makeComposeStatus({ Service: "worker", Health: "unhealthy" }), + ]), + ), + loadConfig: mock(() => + Promise.resolve(makeConfig({ worker: { mode: "container", containerImage: "w:1" } })), + ), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.services[0].state).toBe("unhealthy"); + expect(result!.infrastructure.services).toEqual(["lo1-my-platform-proxy"]); + expect(result!.healthy).toBe(false); + }); + + it("leaves init tasks out of services", async () => { + const deps = makeDeps({ + readState: mock(() => + Promise.resolve( + makeWorkspaceState({ + services: { api: { runner: "process", pid: 1 }, migrate: { runner: "compose" } }, + }), + ), + ), + loadConfig: mock(() => + Promise.resolve(makeConfig({ api: {}, migrate: { initTask: true, mode: "container" } })), + ), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.services.map((s) => s.name)).toEqual(["api"]); + }); + + it("treats infrastructure init tasks that exited 0 as healthy, and non-zero as degraded", async () => { + const exited = (code: number) => + makeDeps({ + readState: mock(() => Promise.resolve(makeWorkspaceState({ infraInitTasks: ["migrator"] }))), + composePs: mock(() => + Promise.resolve([ + makeComposeStatus(), + makeComposeStatus({ Service: "migrator", State: "exited", ExitCode: code }), + ]), + ), + }); + + expect((await getWorkspaceStatus("/workspace", exited(0)))!.infrastructure.state).toBe( + "healthy", + ); + expect((await getWorkspaceStatus("/workspace", exited(1)))!.infrastructure.state).toBe( + "degraded", + ); + }); + + it("treats long-running infrastructure that has stopped as degraded, even with exit 0", async () => { + const deps = makeDeps({ + composePs: mock(() => + Promise.resolve([ + makeComposeStatus(), + makeComposeStatus({ Service: "postgres", State: "exited", ExitCode: 0 }), + ]), + ), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.infrastructure.state).toBe("degraded"); + expect(result!.healthy).toBe(false); + }); + + it("reports infrastructure lo1 started but compose no longer lists as degraded", async () => { + const deps = makeDeps({ + readState: mock(() => + Promise.resolve(makeWorkspaceState({ infraServices: ["lo1-my-platform-proxy", "postgres"] })), + ), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.infrastructure.state).toBe("degraded"); + }); + + it('reports "none" for a plugin workspace with no infrastructure, and stays healthy', async () => { + const config = { + ...makeConfig({ api: {} }), + proxy: { enabled: false, port: 80, tld: "local" }, + plugins: { celerity: "@lo1/plugin-celerity" }, + }; + const deps = makeDeps({ + readState: mock(() => Promise.resolve(makeWorkspaceState({ infraServices: [] }))), + composePs: mock(() => Promise.resolve([])), + loadConfig: mock(() => Promise.resolve(config)), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.infrastructure.state).toBe("none"); + expect(result!.healthy).toBe(true); + }); + + it("is not healthy while lo1 up is still starting services", async () => { + const deps = makeDeps({ + readState: mock(() => Promise.resolve(makeWorkspaceState({ services: {}, ready: false }))), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.healthy).toBe(false); + }); + + it("describes services in the mode lo1 up --mode started them in", async () => { + const deps = makeDeps({ + readState: mock(() => Promise.resolve(makeWorkspaceState({ modeOverride: "dev" }))), + loadConfig: mock(() => + Promise.resolve(makeConfig({ api: { mode: "container", port: 3000, hostPort: 3001 } })), + ), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.services[0]).toMatchObject({ mode: "dev", port: 3000, hostPort: 3000 }); + }); + + it('reports infrastructure "none" when the workspace has none, and stays healthy', async () => { + const config = { ...makeConfig({ api: {} }), proxy: { enabled: false, port: 80, tld: "local" } }; + const deps = makeDeps({ + composePs: mock(() => Promise.resolve([])), + loadConfig: mock(() => Promise.resolve(config)), + }); + + const result = await getWorkspaceStatus("/workspace", deps); + + expect(result!.infrastructure.state).toBe("none"); + expect(result!.healthy).toBe(true); + expect(result!.services[0].url).toBe("http://localhost:3000"); + }); +}); + +describe("formatStatus", () => { + it("shows health, infrastructure and each service's state", () => { + const text = formatStatus({ + workspace: "shop", + healthy: false, + infrastructure: { state: "healthy", services: ["postgres"] }, + services: [ + { name: "api", state: "running", mode: "dev", port: 3000, url: "https://api.shop.local" }, + { name: "worker", state: "exited", mode: "dev" }, + ], + }); + + expect(text).toBe( + "Workspace: shop (not healthy)\n\n" + + "Infrastructure: healthy\n postgres\n\n" + + "Services:\n" + + " api running dev:3000 https://api.shop.local\n" + + " worker exited dev\n", + ); + }); }); diff --git a/packages/cli/tests/cli/up.test.ts b/packages/cli/tests/cli/up.test.ts index 8c7cc08..0b29c44 100644 --- a/packages/cli/tests/cli/up.test.ts +++ b/packages/cli/tests/cli/up.test.ts @@ -2,9 +2,92 @@ import { describe, it, expect } from "bun:test"; import { mkdtemp, rm } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { recordedHandle, recordReplacement } from "../../src/cli/commands/up"; +import type { WorkspaceConfig } from "@lo1/sdk"; +import { + buildReadyJson, + formatReadySummary, + recordedHandle, + recordReplacement, + startWatching, +} from "../../src/cli/commands/up"; +import type { OrchestratorEvent } from "../../src/orchestrator/types"; import { readState, writeState } from "../../src/orchestrator/state"; +const config: WorkspaceConfig = { + version: "1", + name: "shop", + proxy: { enabled: true, port: 80, tld: "local", tls: { enabled: true, port: 443, mode: "internal" } }, + services: { + api: { type: "service", path: "./api", port: 3000, mode: "dev", dependsOn: [], initTask: false }, + migrate: { type: "service", path: "./api", mode: "dev", dependsOn: [], initTask: true }, + web: { + type: "app", + path: "./web", + port: 5173, + mode: "dev", + dependsOn: ["api"], + initTask: false, + proxy: { domain: ["shop.example.test", "www.shop.example.test"] }, + }, + }, +}; + +const result = { + config, + timings: { + totalMs: 11_430, + phases: [ + { name: "infrastructure", ms: 4_210 }, + { name: "services", ms: 6_080 }, + ], + }, +}; + +describe("formatReadySummary", () => { + it("should show the total time, the phase breakdown and each service URL", () => { + const text = formatReadySummary(result, "/ws", true); + + expect(text).toBe( + [ + "", + " Workspace shop is ready in 11.4s", + " infrastructure 4.2s · services 6.1s", + "", + " Services:", + " api https://api.shop.local", + " web https://shop.example.test", + "", + ` Logs: ${join("/ws", ".lo1", "logs")}`, + " Run lo1 logs [service] to tail, lo1 logs --list to see available", + "", + " Run lo1 down to stop", + "", + ].join("\n"), + ); + }); + + it("should tell a foreground run how to stop", () => { + expect(formatReadySummary(result, "/ws", false)).toContain(" Press Ctrl+C to stop\n"); + }); +}); + +describe("buildReadyJson", () => { + it("should describe the ready workspace for scripts and agents", () => { + expect(buildReadyJson(result, "/ws", true)).toEqual({ + workspace: "shop", + ready: true, + detached: true, + durationMs: 11_430, + phases: result.timings.phases, + services: [ + { name: "api", url: "https://api.shop.local" }, + { name: "web", url: "https://shop.example.test" }, + ], + logs: join("/ws", ".lo1", "logs"), + }); + }); +}); + describe("recordReplacement", () => { it("points the state file at the restarted process and keeps the other services", async () => { const dir = await mkdtemp(join(tmpdir(), "lo1-up-")); @@ -69,3 +152,41 @@ describe("recordedHandle", () => { await rm(dir, { recursive: true, force: true }); }); }); + +describe("startWatching", () => { + it("reports a watcher that fails to start and keeps the workspace running", () => { + const events: OrchestratorEvent[] = []; + const result = { + handles: [], + config: { + version: "1", + name: "shop", + services: { + orders: { type: "broken", path: "./orders", mode: "container", dependsOn: [], initTask: false }, + }, + }, + registry: { endpoints: new Map() }, + plugins: new Map([ + [ + "broken", + { + name: "broken", + watchForChanges: () => { + throw new Error("no watcher"); + }, + }, + ], + ]), + pluginEnvVars: {}, + compose: { projectName: "lo1-shop", fileArgs: [], cwd: "/ws" }, + } as unknown as Parameters[0]; + + const watcher = startWatching(result, "/ws", new AbortController().signal, (e) => events.push(e)); + + expect(watcher).toBeUndefined(); + expect(events).toContainEqual({ + kind: "error", + message: "Watching for changes failed to start: no watcher", + }); + }); +}); diff --git a/packages/cli/tests/hooks/executor.test.ts b/packages/cli/tests/hooks/executor.test.ts index 5a03802..d460d25 100644 --- a/packages/cli/tests/hooks/executor.test.ts +++ b/packages/cli/tests/hooks/executor.test.ts @@ -152,3 +152,20 @@ describe("executeHook", () => { } }); }); + +describe("executeHook with a real shell", () => { + it("reports each line of output separately", async () => { + const outputs: HookOutput[] = []; + + await executeHook("seed", "printf 'one\\ntwo\\n' && printf 'three' >&2", { + cwd: process.cwd(), + env: {}, + onOutput: (o) => outputs.push(o), + }); + + expect(outputs).toContainEqual({ stream: "stdout", text: "one" }); + expect(outputs).toContainEqual({ stream: "stdout", text: "two" }); + expect(outputs).toContainEqual({ stream: "stderr", text: "three" }); + expect(outputs).toHaveLength(3); + }); +}); diff --git a/packages/cli/tests/orchestrator/lock.test.ts b/packages/cli/tests/orchestrator/lock.test.ts index 96296bd..9103055 100644 --- a/packages/cli/tests/orchestrator/lock.test.ts +++ b/packages/cli/tests/orchestrator/lock.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect } from "bun:test"; -import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { lockPath, withWorkspaceLock } from "../../src/orchestrator/lock"; +import { lockPath, removeStaleLock, withWorkspaceLock } from "../../src/orchestrator/lock"; async function withTempDir(fn: (dir: string) => Promise) { const dir = await mkdtemp(join(tmpdir(), "lo1-lock-")); @@ -73,4 +73,46 @@ describe("withWorkspaceLock", () => { await expect(attempt).rejects.toThrow("Another lo1 command (pid 4242)"); })); + + it("stops waiting when its signal aborts", () => + withTempDir(async (dir) => { + await mkdir(join(dir, ".lo1"), { recursive: true }); + await writeFile(lockPath(dir), "4242"); + const controller = new AbortController(); + + const attempt = withWorkspaceLock(dir, async () => "ran", { + isAlive: () => true, + pollMs: 5, + signal: controller.signal, + }); + setTimeout(() => controller.abort(), 20); + + await expect(attempt).rejects.toThrow("Stopped waiting for the workspace lock."); + })); + + it("removes a stale lock, but not a lock that has replaced it since it was checked", () => + withTempDir(async (dir) => { + await mkdir(join(dir, ".lo1"), { recursive: true }); + // Holder 111 was found stale, but 222 took the lock before the removal. + await writeFile(lockPath(dir), "222"); + + await removeStaleLock(lockPath(dir), "111"); + const kept = await readFile(lockPath(dir), "utf-8"); + await removeStaleLock(lockPath(dir), "222"); + + expect(kept).toBe("222"); + await expect(readFile(lockPath(dir), "utf-8")).rejects.toThrow(); + expect((await readdir(join(dir, ".lo1"))).length).toBe(0); + })); + + it("propagates errors reading the lock other than it being missing", () => + withTempDir(async (dir) => { + // A directory where the lock file should be makes linking fail with EEXIST + // and reading it fail with EISDIR. + await mkdir(lockPath(dir), { recursive: true }); + + await expect(withWorkspaceLock(dir, async () => "ran", { timeoutMs: 50 })).rejects.toThrow( + /EISDIR/, + ); + })); }); diff --git a/packages/cli/tests/orchestrator/restart.test.ts b/packages/cli/tests/orchestrator/restart.test.ts index f386593..8d96eba 100644 --- a/packages/cli/tests/orchestrator/restart.test.ts +++ b/packages/cli/tests/orchestrator/restart.test.ts @@ -78,6 +78,44 @@ describe("restartService", () => { expect(handle.pid).toBe(2); }); + it("should remove an exited container before starting its replacement", async () => { + const calls: string[] = []; + const withPreStop: WorkspaceConfig = { + ...config, + services: { + ...config.services, + orders: service({ type: "celerity", mode: "container", hooks: { preStop: "./drain.sh" } }), + }, + }; + const { ctx, events } = makeContext({ + config: withPreStop, + deps: { + startService: mock((opts) => { + calls.push("start"); + return Promise.resolve(makeHandle(opts.serviceName, { type: "container", pid: undefined })); + }), + executeHook: mock((name) => { + calls.push(`hook:${name}`); + return Promise.resolve({ exitCode: 0, hookName: name }); + }), + }, + }); + const exited = makeHandle("orders", { + type: "container", + running: false, + stop: mock(async () => { + calls.push("stop"); + }), + }); + + await restartService("orders", exited, ctx); + + // The old container is removed first, so its name is free for the new one, + // and a container that has already exited gets no preStop hook. + expect(calls).toEqual(["stop", "start"]); + expect(statuses(events)).toEqual(["starting", "started"]); + }); + it("should rerun an init task without stopping anything and report it completed", async () => { const { ctx, events } = makeContext(); diff --git a/packages/cli/tests/orchestrator/service.test.ts b/packages/cli/tests/orchestrator/service.test.ts index 106e672..9b4999a 100644 --- a/packages/cli/tests/orchestrator/service.test.ts +++ b/packages/cli/tests/orchestrator/service.test.ts @@ -208,6 +208,37 @@ describe("startService", () => { ).rejects.toThrow('Init task "api" exited with code 2'); }); + it("should remove a failed init task's container before reporting the failure", async () => { + const plugin: Plugin = { + name: "celerity", + configureContainer: mock(async () => ({ + image: "celerity:latest", + cmd: ["migrate"], + envVars: {}, + binds: [], + workingDir: "/app", + })), + }; + const stop = mock(() => Promise.resolve()); + const startContainer = mock(() => + Promise.resolve({ + serviceName: "api", + containerId: "abc123", + running: false, + stop, + exitPromise: Promise.resolve(null), + waitForExit: () => Promise.resolve(1), + releaseLogs: () => {}, + }), + ); + const serviceConfig = { ...makeOptions().serviceConfig, initTask: true }; + + await expect( + startService(makeOptions({ plugin, serviceConfig }), makeDeps({ startContainer })), + ).rejects.toThrow("exited with code 1"); + expect(stop).toHaveBeenCalled(); + }); + it("should call configureContainer with correct ContainerInput", async () => { const configureFn = mock(async (_input) => ({ image: "test:latest", diff --git a/packages/cli/tests/orchestrator/start.test.ts b/packages/cli/tests/orchestrator/start.test.ts index 11d2b33..95f9c64 100644 --- a/packages/cli/tests/orchestrator/start.test.ts +++ b/packages/cli/tests/orchestrator/start.test.ts @@ -84,6 +84,7 @@ function makeDeps(overrides: Partial = {}): OrchestratorDeps { composeLogs: mock(() => ({ kill: mock(() => {}) })), discoverExtraComposeServices: mock(() => Promise.resolve([])), composeDown: mock(() => Promise.resolve()), + ensureNetwork: mock(() => Promise.resolve()), composePs: mock(() => Promise.resolve([])), startService: mock((opts) => Promise.resolve({ @@ -106,6 +107,26 @@ function makeDeps(overrides: Partial = {}): OrchestratorDeps { } describe("startWorkspace", () => { + it("should time infrastructure and services, leaving out setup when there is none", async () => { + const result = await startWorkspace({}, makeDeps()); + + expect(result.timings.phases.map((p) => p.name)).toEqual(["infrastructure", "services"]); + expect(result.timings.totalMs).toBeGreaterThanOrEqual(0); + }); + + it("should time setup when a postInfrastructure hook runs", async () => { + const config = makeConfig({ hooks: { postInfrastructure: "./migrate.sh" } }); + const deps = makeDeps({ loadConfig: mock(() => Promise.resolve(config)) }); + + const result = await startWorkspace({}, deps); + + expect(result.timings.phases.map((p) => p.name)).toEqual([ + "infrastructure", + "setup", + "services", + ]); + }); + it("should fail before starting anything when a port it needs is in use", async () => { const deps = makeDeps({ findPortConflicts: mock(() => @@ -387,6 +408,16 @@ describe("startWorkspace", () => { expect(deps.composeUp).not.toHaveBeenCalled(); expect(deps.composeWait).not.toHaveBeenCalled(); + // Plugin containers still need the workspace network. + expect(deps.ensureNetwork).toHaveBeenCalledWith("lo1-my-platform", "lo1-my-platform-network"); + }); + + it("should leave creating the network to compose when infrastructure starts", async () => { + const deps = makeDeps(); + + await startWorkspace({}, deps); + + expect(deps.ensureNetwork).not.toHaveBeenCalled(); }); it("should write initial state after infra and update after services", async () => { diff --git a/packages/cli/tests/orchestrator/stop.test.ts b/packages/cli/tests/orchestrator/stop.test.ts index c8e0f43..f7d5928 100644 --- a/packages/cli/tests/orchestrator/stop.test.ts +++ b/packages/cli/tests/orchestrator/stop.test.ts @@ -41,6 +41,7 @@ function makeDeps(overrides: Partial = {}): StopDeps { ), readState: mock(() => Promise.resolve(sampleState)), removeState: mock(() => Promise.resolve()), + removeNetwork: mock(() => Promise.resolve()), exec: mock(() => Promise.resolve({ stdout: "", stderr: "" })), ...overrides, }; @@ -278,6 +279,17 @@ describe("stopWorkspace", () => { expect(callArgs.fileArgs).toEqual([".lo1/docker-compose.yml"]); }); + it("should remove the workspace network after compose down", async () => { + const deps = makeDeps(); + + await stopWorkspace({ workspaceDir: "/workspace" }, deps); + + expect(deps.removeNetwork).toHaveBeenCalledWith( + sampleState.projectName, + `lo1-${sampleState.workspaceName}-network`, + ); + }); + it("should remove state file after shutdown", async () => { const deps = makeDeps(); @@ -403,6 +415,21 @@ describe("hydrateHandles", () => { await rm(dir, { recursive: true, force: true }); }); + /** Waits for the shell to write the child's pid, failing on anything but a missing file. */ + async function readPidFile(path: string, timeoutMs = 3000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const content = await readFile(path, "utf-8").catch((err: NodeJS.ErrnoException) => { + if (err.code === "ENOENT") return ""; + throw err; + }); + const pid = Number.parseInt(content.trim(), 10); + if (Number.isInteger(pid) && pid > 0) return pid; + await new Promise((r) => setTimeout(r, 20)); + } + throw new Error(`No pid in ${path} after ${timeoutMs}ms`); + } + it.skipIf(platform() === "win32")( "should kill children that outlive their parent's exit", async () => { @@ -410,21 +437,24 @@ describe("hydrateHandles", () => { "(trap '' TERM; while true; do sleep 0.1; done) & echo $! > child.pid; " + "trap 'exit 0' TERM; while true; do sleep 0.1; done", ); - const childPid = Number.parseInt(await readFile(join(dir, "child.pid"), "utf-8"), 10); + try { + const childPid = await readPidFile(join(dir, "child.pid")); - await handle.stop(500); - await new Promise((r) => setTimeout(r, 100)); + await handle.stop(500); - expect(isAlive(childPid)).toBe(false); - await rm(dir, { recursive: true, force: true }); + expect(isAlive(childPid)).toBe(false); + } finally { + await handle.stop(500); + await rm(dir, { recursive: true, force: true }); + } }, ); it.skipIf(platform() === "win32")("should kill a process that ignores SIGTERM", async () => { const { dir, pid, handle } = await startDetached("trap '' TERM; while true; do sleep 0.1; done"); + // stop() waits for the SIGKILL to take effect, so no extra delay is needed. await handle.stop(300); - await new Promise((r) => setTimeout(r, 100)); expect(isAlive(pid)).toBe(false); await rm(dir, { recursive: true, force: true }); diff --git a/packages/cli/tests/output/line-buffer.test.ts b/packages/cli/tests/output/line-buffer.test.ts new file mode 100644 index 0000000..04b6ec9 --- /dev/null +++ b/packages/cli/tests/output/line-buffer.test.ts @@ -0,0 +1,40 @@ +import { describe, it, expect } from "bun:test"; +import { PassThrough } from "node:stream"; +import { createLineBuffer, followLines } from "../../src/output/line-buffer"; + +describe("createLineBuffer", () => { + it("splits chunks into lines, joining a line split across chunks", () => { + const lines: string[] = []; + const push = createLineBuffer((l) => lines.push(l)); + + push("first\nsec"); + push("ond\n\nthird\r\n"); + + expect(lines).toEqual(["first", "second", "third"]); + }); + + it("emits a trailing partial line on flush", () => { + const lines: string[] = []; + const push = createLineBuffer((l) => lines.push(l)); + + push("done"); + push.flush(); + push.flush(); + + expect(lines).toEqual(["done"]); + }); +}); + +describe("followLines", () => { + it("gives each line of a stream its own call, flushing at the end", async () => { + const stream = new PassThrough(); + const lines: string[] = []; + followLines(stream, (l) => lines.push(l)); + + stream.write("\nadded 14 packages in 213ms\nmigrations "); + stream.end("applied"); + await new Promise((r) => setImmediate(r)); + + expect(lines).toEqual(["added 14 packages in 213ms", "migrations applied"]); + }); +}); diff --git a/packages/cli/tests/proxy/domains.test.ts b/packages/cli/tests/proxy/domains.test.ts index 7d34285..f757cac 100644 --- a/packages/cli/tests/proxy/domains.test.ts +++ b/packages/cli/tests/proxy/domains.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "bun:test"; import type { WorkspaceConfig } from "@lo1/sdk"; -import { collectDomains } from "../../src/proxy/domains"; +import { collectDomains, serviceUrl } from "../../src/proxy/domains"; function makeConfig( services: Record>, @@ -21,6 +21,19 @@ function makeConfig( } describe("collectDomains", () => { + it("should return no domains when the proxy is disabled, so lo1 leaves the hosts file alone", () => { + const config = { + version: "1", + name: "shop", + proxy: { enabled: false, port: 80, tld: "local" }, + services: { + api: { type: "service", path: "./api", port: 3000, mode: "dev", dependsOn: [], initTask: false }, + }, + } as unknown as Parameters[0]; + + expect(collectDomains(config)).toEqual([]); + }); + it("should return subdomain for each service with a port", () => { const config = makeConfig({ api: { port: 3000 }, @@ -88,3 +101,40 @@ describe("collectDomains", () => { expect(domains).toContain("api.my-app.test"); }); }); + +describe("serviceUrl", () => { + const base = { + version: "1" as const, + name: "shop", + services: { + api: { type: "service", path: "./api", port: 3000, mode: "dev" as const, dependsOn: [], initTask: false }, + db: { + type: "service", + path: "./db", + port: 5432, + hostPort: 15432, + mode: "container" as const, + dependsOn: [], + initTask: false, + }, + worker: { type: "service", path: "./w", mode: "dev" as const, dependsOn: [], initTask: false }, + }, + }; + + it("should use the proxy domain, with a non-default proxy port", () => { + expect(serviceUrl(base, "api")).toBe("http://api.shop.local"); + expect(serviceUrl({ ...base, proxy: { enabled: true, port: 8080, tld: "test" } }, "api")).toBe( + "http://api.shop.test:8080", + ); + }); + + it("should go straight to the host port when the proxy is disabled", () => { + const noProxy = { ...base, proxy: { enabled: false, port: 80, tld: "local" } }; + expect(serviceUrl(noProxy, "api")).toBe("http://localhost:3000"); + expect(serviceUrl(noProxy, "db")).toBe("http://localhost:15432"); + }); + + it("should have no URL for a service without a port", () => { + expect(serviceUrl(base, "worker")).toBeUndefined(); + }); +}); diff --git a/packages/cli/tests/runner/compose.test.ts b/packages/cli/tests/runner/compose.test.ts index 4be3c8d..23d5910 100644 --- a/packages/cli/tests/runner/compose.test.ts +++ b/packages/cli/tests/runner/compose.test.ts @@ -2,6 +2,8 @@ import { describe, it, expect, mock, beforeEach } from "bun:test"; import { EventEmitter } from "node:events"; import { composeUp, + ensureComposeNetwork, + removeComposeNetwork, composeWait, composeLogs, composeDown, @@ -559,3 +561,53 @@ describe("composeWait", () => { expect(waitExec).toHaveBeenCalled(); }); }); + +describe("ensureComposeNetwork", () => { + it("creates the network with compose's labels when it doesn't exist", async () => { + const exec = mock((_cmd, args) => + args[1] === "inspect" + ? Promise.reject(new Error("No such network")) + : Promise.resolve({ stdout: "", stderr: "" }), + ); + + await ensureComposeNetwork("lo1-shop", "lo1-shop-network", exec); + + expect(exec.mock.calls[1][1]).toEqual([ + "network", + "create", + "--driver", + "bridge", + "--label", + "com.docker.compose.project=lo1-shop", + "--label", + "com.docker.compose.network=lo1-shop-network", + "lo1-shop_lo1-shop-network", + ]); + }); + + it("leaves an existing network alone", async () => { + const exec = mock(() => Promise.resolve({ stdout: "[]", stderr: "" })); + + await ensureComposeNetwork("lo1-shop", "lo1-shop-network", exec); + + expect(exec).toHaveBeenCalledTimes(1); + }); + + it("throws a ComposeExecError when docker can't create it", async () => { + const exec = mock(() => Promise.reject(new Error("daemon down"))); + + await expect(ensureComposeNetwork("lo1-shop", "lo1-shop-network", exec)).rejects.toThrow( + "Could not create the Docker network lo1-shop_lo1-shop-network", + ); + }); +}); + +describe("removeComposeNetwork", () => { + it("removes the network, and doesn't mind when it's already gone", async () => { + const exec = mock(() => Promise.reject(new Error("network not found"))); + + await removeComposeNetwork("lo1-shop", "lo1-shop-network", exec); + + expect(exec.mock.calls[0][1]).toEqual(["network", "rm", "lo1-shop_lo1-shop-network"]); + }); +}); diff --git a/packages/cli/tests/runner/process.test.ts b/packages/cli/tests/runner/process.test.ts index 5bd95fd..6ed2f62 100644 --- a/packages/cli/tests/runner/process.test.ts +++ b/packages/cli/tests/runner/process.test.ts @@ -190,6 +190,21 @@ describe("startProcess", () => { await rm(dir, { recursive: true, force: true }); }); + it.skipIf(platform() === "win32")("should report each line of real output separately", async () => { + const outputs: OutputLine[] = []; + const handle = startProcess({ + serviceName: "migrate", + command: "printf '\\nadded 14 packages\\nmigrations applied'", + cwd: tmpdir(), + env: {}, + onOutput: (line) => outputs.push(line), + }); + + await handle.exitPromise; + + expect(outputs.map((o) => o.text)).toEqual(["added 14 packages", "migrations applied"]); + }); + it.skipIf(platform() === "win32")("should write real process output to the log file", async () => { const dir = await mkdtemp(join(tmpdir(), "lo1-proc-")); const logFile = join(dir, "api.log");