From b2116d9556854c3ead2f3631bc73b8054d94fd77 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 16 Nov 2026 20:38:38 +0000 Subject: [PATCH 1/4] feat(cli): add lo1 restart and follow plugin watchForChanges `lo1 restart ` restarts services in the running workspace, in the order given. A long-running service runs its preStop hook, stops and starts again, waiting for readiness. An init task is run again and waited on, so `lo1 restart seed` reruns a seed script. Restarted dev processes are detached and log to .lo1/logs, compose services are recreated, and the state file is updated so lo1 down stops the new processes. During a foreground `lo1 up`, lo1 now follows each plugin's watchForChanges() and restarts the service on every signal it yields. Supporting changes: - The state file records plugin env vars and the --mode override, so a restart starts a service the same way lo1 up did. - Stopping a process from the state file waits for it to exit and kills it after a timeout, so its port is free for the restart. - Teardown also stops processes in the state file it holds no handle for, and skips processes that have already exited. --- packages/cli/src/cli/commands/restart.ts | 112 +++++++++++ packages/cli/src/cli/commands/up.ts | 16 ++ packages/cli/src/cli/index.ts | 2 + packages/cli/src/orchestrator/restart.ts | 75 +++++++ packages/cli/src/orchestrator/service.ts | 39 +++- packages/cli/src/orchestrator/start.ts | 22 ++- packages/cli/src/orchestrator/stop.ts | 72 +++++-- packages/cli/src/orchestrator/types.ts | 11 +- packages/cli/src/orchestrator/watch.ts | 67 +++++++ packages/cli/src/runner/compose.ts | 3 + .../cli/tests/orchestrator/restart.test.ts | 187 ++++++++++++++++++ .../cli/tests/orchestrator/service.test.ts | 21 ++ packages/cli/tests/orchestrator/stop.test.ts | 114 ++++++++++- packages/cli/tests/runner/compose.test.ts | 9 + packages/sdk/src/plugin.ts | 4 + 15 files changed, 728 insertions(+), 26 deletions(-) create mode 100644 packages/cli/src/cli/commands/restart.ts create mode 100644 packages/cli/src/orchestrator/restart.ts create mode 100644 packages/cli/src/orchestrator/watch.ts create mode 100644 packages/cli/tests/orchestrator/restart.test.ts diff --git a/packages/cli/src/cli/commands/restart.ts b/packages/cli/src/cli/commands/restart.ts new file mode 100644 index 0000000..c5397d8 --- /dev/null +++ b/packages/cli/src/cli/commands/restart.ts @@ -0,0 +1,112 @@ +import { Command } from "commander"; +import type { Plugin, WorkspaceConfig } from "@lo1/sdk"; +import { loadWorkspaceConfig } from "../../config/loader"; +import { buildEndpointRegistry } from "../../discovery/registry"; +import { Lo1Error } from "../../errors"; +import { executeHook } from "../../hooks/executor"; +import { appendLog } from "../../logs/writer"; +import { createEventFormatter } from "../../output/format"; +import { loadPlugins } from "../../plugin/loader"; +import { restartService } from "../../orchestrator/restart"; +import { startService, BUILTIN_TYPES } from "../../orchestrator/service"; +import { applyModeOverride, buildServiceState, createLogger } from "../../orchestrator/start"; +import { readState, writeState } from "../../orchestrator/state"; +import { hydrateHandles } from "../../orchestrator/stop"; +import type { OrchestratorEvent, WorkspaceState } from "../../orchestrator/types"; + +export class RestartError extends Lo1Error { + constructor(message: string, code = "RestartError") { + super(message, code); + this.name = "RestartError"; + } +} + +export function validateRestartTargets(names: string[], config: WorkspaceConfig): void { + for (const name of names) { + const service = config.services[name]; + if (!service) { + throw new RestartError(`Unknown service "${name}". Check the services in lo1.yaml.`); + } + if (service.mode === "skip") { + throw new RestartError(`Service "${name}" has mode: skip, so lo1 does not run it.`); + } + } +} + +async function loadNeededPlugins( + names: string[], + config: WorkspaceConfig, + workspaceDir: string, + emit: (event: OrchestratorEvent) => void, +): Promise> { + const needsPlugins = names.some((name) => !BUILTIN_TYPES.has(config.services[name].type)); + if (!needsPlugins) return new Map(); + return loadPlugins(config.plugins ?? {}, { + workspaceDir, + workspaceName: config.name, + logger: createLogger(emit), + }); +} + +function createRestartEventHandler(workspaceDir: string): (event: OrchestratorEvent) => void { + const format = createEventFormatter(); + return (event) => { + if (event.kind === "output") { + void appendLog(workspaceDir, event.line.service, event.line.text).catch(() => {}); + } else if (event.kind === "hook") { + void appendLog(workspaceDir, "hooks", event.output.text).catch(() => {}); + } + const message = format(event); + if (message) process.stdout.write(message.trimEnd() + "\n"); + }; +} + +async function requireRunningWorkspace(workspaceDir: string): Promise { + const state = await readState(workspaceDir); + if (!state) { + throw new RestartError("No running workspace found. Start one with lo1 up.", "NoWorkspace"); + } + return state; +} + +export const restartCommand = new Command("restart") + .description("Restart services, or run init tasks again, in the running workspace") + .argument("", "Services or init tasks to restart, in order") + .action(async (names: string[]) => { + const workspaceDir = process.cwd(); + const controller = new AbortController(); + process.on("SIGINT", () => controller.abort()); + + const state = await requireRunningWorkspace(workspaceDir); + const config = applyModeOverride(await loadWorkspaceConfig(), state.modeOverride); + validateRestartTargets(names, config); + + const emit = createRestartEventHandler(workspaceDir); + const ctx = { + config, + workspaceDir, + registry: buildEndpointRegistry(config), + plugins: await loadNeededPlugins(names, config, workspaceDir, emit), + pluginEnvVars: state.pluginEnvVars ?? {}, + compose: { projectName: state.projectName, fileArgs: state.fileArgs, cwd: workspaceDir }, + detached: true, + signal: controller.signal, + emit, + deps: { startService, executeHook }, + }; + + const current = hydrateHandles(state); + for (const name of names) { + const handle = await restartService( + name, + current.find((h) => h.serviceName === name), + ctx, + ); + handle.releaseLogs?.(); + handle.detach?.(); + + const { [name]: _previous, ...others } = state.services; + state.services = { ...others, ...buildServiceState([handle]) }; + await writeState(state, workspaceDir); + } + }); diff --git a/packages/cli/src/cli/commands/up.ts b/packages/cli/src/cli/commands/up.ts index bd39df1..b02f3dd 100644 --- a/packages/cli/src/cli/commands/up.ts +++ b/packages/cli/src/cli/commands/up.ts @@ -3,6 +3,9 @@ import { spawn } from "node:child_process"; import { platform } from "node:os"; import { startWorkspace } from "../../orchestrator/start"; import { stopWorkspace } from "../../orchestrator/stop"; +import { watchPluginServices } from "../../orchestrator/watch"; +import { startService } from "../../orchestrator/service"; +import { executeHook } from "../../hooks/executor"; import { loadWorkspaceConfig } from "../../config/loader"; import { collectDomains } from "../../proxy/domains"; import { initLogDir, appendLog, logDir } from "../../logs/writer"; @@ -186,7 +189,20 @@ 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 }, + }); await waitForShutdownSignal(controller); + watcher.stop(); } catch (err) { if (!controller.signal.aborted) { startupError = err; diff --git a/packages/cli/src/cli/index.ts b/packages/cli/src/cli/index.ts index a3b7a04..6eec6af 100644 --- a/packages/cli/src/cli/index.ts +++ b/packages/cli/src/cli/index.ts @@ -11,6 +11,7 @@ import { hostsCommand } from "./commands/hosts"; import { tlsSetupCommand } from "./commands/tls-setup"; import { logsCommand } from "./commands/logs"; import { doctorCommand } from "./commands/doctor"; +import { restartCommand } from "./commands/restart"; export const program = new Command(); @@ -31,6 +32,7 @@ program.addCommand(hostsCommand); program.addCommand(tlsSetupCommand); program.addCommand(logsCommand); program.addCommand(doctorCommand); +program.addCommand(restartCommand); export function formatErrorForOutput(err: unknown, json: boolean): string { if (json) { diff --git a/packages/cli/src/orchestrator/restart.ts b/packages/cli/src/orchestrator/restart.ts new file mode 100644 index 0000000..74c3c71 --- /dev/null +++ b/packages/cli/src/orchestrator/restart.ts @@ -0,0 +1,75 @@ +import { resolve } from "node:path"; +import type { Plugin, WorkspaceConfig } from "@lo1/sdk"; +import type { EndpointRegistry } from "../discovery/registry"; +import { createLog } from "../debug"; +import { runServicePreStop } from "./stop"; +import type { ComposeContext, ServiceHandle } from "./service"; +import type { OrchestratorDeps, OrchestratorEvent } from "./types"; + +const debug = createLog("orchestrator:restart"); + +/** Everything needed to start a service again outside the initial `lo1 up`. */ +export type RestartContext = { + config: WorkspaceConfig; + workspaceDir: string; + registry: EndpointRegistry; + plugins: Map; + pluginEnvVars: Record; + compose: ComposeContext; + /** Restarted host processes outlive the command that restarted them. */ + detached: boolean; + signal?: AbortSignal; + emit: (event: OrchestratorEvent) => void; + deps: Pick; +}; + +/** + * Stops a service (running its preStop hook) and starts it again, waiting + * for it to be ready. An init task is simply run again and waited on. + */ +export async function restartService( + name: string, + current: ServiceHandle | undefined, + ctx: RestartContext, +): Promise { + const serviceConfig = ctx.config.services[name]; + debug("restartService: %s (init task: %s)", name, serviceConfig.initTask); + + if (current?.running && !serviceConfig.initTask) { + ctx.emit({ kind: "service", service: name, status: "stopping" }); + await runServicePreStop({ + handle: current, + config: ctx.config, + workspaceDir: ctx.workspaceDir, + executeHook: ctx.deps.executeHook, + emit: ctx.emit, + signal: ctx.signal, + }); + await current.stop(); + current.releaseLogs?.(); + ctx.emit({ kind: "service", service: name, status: "stopped" }); + } + + ctx.emit({ kind: "service", service: name, status: "starting" }); + const handle = await ctx.deps.startService({ + serviceName: name, + serviceConfig, + config: ctx.config, + plugin: ctx.plugins.get(serviceConfig.type), + registry: ctx.registry, + pluginEnvVars: ctx.pluginEnvVars, + workspaceDir: resolve(ctx.workspaceDir), + compose: ctx.compose, + detached: ctx.detached, + recreate: true, + signal: ctx.signal, + onOutput: (line) => ctx.emit({ kind: "output", line }), + onHookOutput: (output) => ctx.emit({ kind: "hook", hook: name, output }), + }); + ctx.emit({ + kind: "service", + service: name, + status: serviceConfig.initTask ? "completed" : "started", + }); + return handle; +} diff --git a/packages/cli/src/orchestrator/service.ts b/packages/cli/src/orchestrator/service.ts index c022965..a8482d7 100644 --- a/packages/cli/src/orchestrator/service.ts +++ b/packages/cli/src/orchestrator/service.ts @@ -61,6 +61,8 @@ export type StartServiceOptions = { compose?: ComposeContext; /** Host processes write straight to their log file so they can outlive lo1. */ detached?: boolean; + /** Replace the service's existing container rather than reusing it (restarts). */ + recreate?: boolean; signal?: AbortSignal; onOutput?: (line: OutputLine) => void; onHookOutput?: (output: HookOutput) => void; @@ -342,11 +344,7 @@ async function startWithCompose( } const services = [serviceName]; - // Without --no-deps, compose would also start whatever the service's - // depends_on names, re-running lo1 services such as an init task that has - // already completed. Helpers from the service's own compose file still start. - const helpers = await deps.findComposeHelpers(options.config, options.workspaceDir, serviceName); - await deps.composeUp({ ...compose, services: [...services, ...helpers], noDeps: true, signal }); + await composeUpWithHelpers(options, compose, deps); const logs = deps.composeLogs({ ...compose, services }, (line) => options.onOutput?.({ @@ -378,3 +376,34 @@ async function startWithCompose( releaseLogs: () => logs.kill(), }; } + +/** + * Brings up a compose-run service with --no-deps, which keeps compose from + * also starting whatever its depends_on names and so re-running lo1 services + * such as an init task that has already completed. Helpers from the service's + * own compose file are started alongside it instead. + */ +async function composeUpWithHelpers( + options: StartServiceOptions, + compose: ComposeContext, + deps: StartServiceDeps, +): Promise { + const { serviceName, signal } = options; + const services = [serviceName]; + const helpers = await deps.findComposeHelpers(options.config, options.workspaceDir, serviceName); + + if (options.recreate && helpers.length > 0) { + // A restart replaces the service's container, not its helpers'. + await deps.composeUp({ ...compose, services: helpers, noDeps: true, signal }); + await deps.composeUp({ ...compose, services, noDeps: true, signal, forceRecreate: true }); + return; + } + + await deps.composeUp({ + ...compose, + services: [...services, ...helpers], + noDeps: true, + signal, + forceRecreate: options.recreate, + }); +} diff --git a/packages/cli/src/orchestrator/start.ts b/packages/cli/src/orchestrator/start.ts index 68ddd32..f3a565a 100644 --- a/packages/cli/src/orchestrator/start.ts +++ b/packages/cli/src/orchestrator/start.ts @@ -139,6 +139,8 @@ export async function startWorkspace( fileArgs: composeResult.fileArgs, workspaceDir, services: {} as Record, + pluginEnvVars: composeResult.pluginEnvVars, + ...(options.modeOverride && { modeOverride: options.modeOverride }), }; await deps.writeState(baseState, workspaceDir); @@ -215,7 +217,16 @@ export async function startWorkspace( for (const handle of handles) handle.releaseLogs?.(); }, }; - return { handles, composeOptions, config, logsHandle }; + return { + handles, + composeOptions, + config, + logsHandle, + plugins, + registry, + pluginEnvVars: composeResult.pluginEnvVars, + compose: composeContext, + }; } async function cleanupStaleWorkspace( @@ -369,7 +380,10 @@ async function startInfrastructure( return logsHandle; } -function applyModeOverride(config: WorkspaceConfig, mode?: "dev" | "container"): WorkspaceConfig { +export function applyModeOverride( + config: WorkspaceConfig, + mode?: "dev" | "container", +): WorkspaceConfig { if (!mode) return config; const services: Record = {}; @@ -426,7 +440,7 @@ async function collectContributions( return contributions; } -function buildServiceState(handles: ServiceHandle[]): Record { +export function buildServiceState(handles: ServiceHandle[]): Record { const services: Record = {}; for (const h of handles) { // A finished init task has nothing left to stop, and its pid may be reused. @@ -574,7 +588,7 @@ async function startServicesInLayers(ctx: LayerStartContext): Promise void) { +export function createLogger(emit: (event: OrchestratorEvent) => void) { return { info: (msg: string) => emit({ kind: "phase", phase: msg }), warn: (msg: string) => emit({ kind: "error", message: msg }), diff --git a/packages/cli/src/orchestrator/stop.ts b/packages/cli/src/orchestrator/stop.ts index 2bf2ea4..dc0a3a6 100644 --- a/packages/cli/src/orchestrator/stop.ts +++ b/packages/cli/src/orchestrator/stop.ts @@ -67,14 +67,8 @@ function hydrateHandle( type: "process", pid: svc.pid, running: true, - async stop() { - if (svc.pid) { - try { - signalProcessTree(svc.pid, "SIGTERM"); - } catch { - // Process may have already exited - } - } + async stop(timeoutMs = 5000) { + if (svc.pid) await stopProcessByPid(svc.pid, timeoutMs); }, }; } @@ -111,6 +105,52 @@ function hydrateHandle( }; } +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function trySignal(pid: number, signal: NodeJS.Signals): void { + try { + signalProcessTree(pid, signal); + } catch { + // Process may have already exited + } +} + +/** + * Stops a process lo1 did not spawn in this run, waiting for it to exit so + * its port is free again, and killing it if it outlasts the timeout. + */ +async function stopProcessByPid(pid: number, timeoutMs: number): Promise { + trySignal(pid, "SIGTERM"); + + const deadline = Date.now() + timeoutMs; + while (isAlive(pid) && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 100)); + } + if (isAlive(pid)) trySignal(pid, "SIGKILL"); +} + +/** + * Processes recorded in the state file that the caller holds no handle for, + * such as a service `lo1 restart` started while `lo1 up` was in the foreground. + */ +function untrackedProcessHandles( + state: WorkspaceState, + known: ServiceHandle[], + exec: StopDeps["exec"], +): ServiceHandle[] { + const knownPids = new Set(known.map((h) => h.pid).filter((pid) => pid !== undefined)); + return hydrateHandles(state, exec).filter( + (h) => h.type === "process" && h.pid !== undefined && !knownPids.has(h.pid), + ); +} + export async function stopWorkspace( options: StopOptions, overrides: Partial = {}, @@ -144,19 +184,23 @@ export async function stopWorkspace( }); } - const handles = options.handles ?? hydrateHandles(state, deps.exec); + const handles = options.handles + ? [...options.handles, ...untrackedProcessHandles(state, options.handles, deps.exec)] + : hydrateHandles(state, deps.exec); debug("stopWorkspace: %d handles to stop", handles.length); if (handles.length > 0) { emit({ kind: "phase", phase: "Stopping services" }); for (const handle of handles) { + // Finished init tasks and replaced processes have nothing left to stop. + if (handle.type === "process" && !handle.running) continue; emit({ kind: "service", service: handle.serviceName, status: "stopping" }); if (config && handle.running) { await runServicePreStop({ handle, config, workspaceDir, - deps, + executeHook: deps.executeHook, emit, signal: options.signal, }); @@ -181,11 +225,11 @@ export async function stopWorkspace( emit({ kind: "phase", phase: "Stopped" }); } -type ServicePreStopContext = { +export type ServicePreStopContext = { handle: ServiceHandle; config: WorkspaceConfig; workspaceDir: string; - deps: StopDeps; + executeHook: OrchestratorDeps["executeHook"]; emit: (event: OrchestratorEvent) => void; signal?: AbortSignal; }; @@ -194,7 +238,7 @@ type ServicePreStopContext = { * Runs a service's preStop hook with the same environment its other hooks get. * A failing hook is reported but does not stop the rest of the teardown. */ -async function runServicePreStop(ctx: ServicePreStopContext): Promise { +export async function runServicePreStop(ctx: ServicePreStopContext): Promise { const name = ctx.handle.serviceName; const service = ctx.config.services[name]; const command = service?.hooks?.preStop; @@ -205,7 +249,7 @@ async function runServicePreStop(ctx: ServicePreStopContext): Promise { const env = buildServiceEnv(name, service, ctx.config, registry, {}, consumerMode); try { - await ctx.deps.executeHook(`${name}:preStop`, command, { + await ctx.executeHook(`${name}:preStop`, command, { cwd: resolve(ctx.workspaceDir, service.path), env, signal: ctx.signal, diff --git a/packages/cli/src/orchestrator/types.ts b/packages/cli/src/orchestrator/types.ts index 32151e6..71101c5 100644 --- a/packages/cli/src/orchestrator/types.ts +++ b/packages/cli/src/orchestrator/types.ts @@ -12,7 +12,7 @@ import type { ComposeLogLine, ComposeLogsHandle, } from "../runner/compose"; -import type { ServiceHandle, StartServiceOptions } from "./service"; +import type { ComposeContext, ServiceHandle, StartServiceOptions } from "./service"; import type { PortClaim } from "../doctor/ports"; export type ServiceStatus = "starting" | "started" | "completed" | "stopping" | "stopped"; @@ -90,6 +90,11 @@ export type StartResult = { /** Handle for the long-running `docker compose logs -f` process. * Caller should kill it during shutdown. */ logsHandle: { kill: () => void }; + /** What a later restart of a service needs to start it the same way. */ + plugins: Map; + registry: EndpointRegistry; + pluginEnvVars: Record; + compose: ComposeContext; }; export type StopOptions = { @@ -115,4 +120,8 @@ export type WorkspaceState = { fileArgs: string[]; workspaceDir: string; services: Record; + /** Plugin env vars the services were started with, so a restart can reuse them. */ + pluginEnvVars?: Record; + /** The `lo1 up --mode` override, so a restart runs the service the same way. */ + modeOverride?: "dev" | "container"; }; diff --git a/packages/cli/src/orchestrator/watch.ts b/packages/cli/src/orchestrator/watch.ts new file mode 100644 index 0000000..eb063ba --- /dev/null +++ b/packages/cli/src/orchestrator/watch.ts @@ -0,0 +1,67 @@ +import { resolve } from "node:path"; +import type { RestartSignal } from "@lo1/sdk"; +import { createLog } from "../debug"; +import { restartService, type RestartContext } from "./restart"; +import type { ServiceHandle } from "./service"; + +const debug = createLog("orchestrator:watch"); + +export type WatchHandle = { stop: () => void }; + +/** + * Follows each plugin's watchForChanges() for the services it owns and + * restarts a service whenever its plugin yields a restart signal. Restarted + * handles replace the old ones in `handles`, so teardown stops the new ones. + * Restarts of one service never overlap; a failed restart is reported and + * watching continues. + */ +export function watchPluginServices(handles: ServiceHandle[], ctx: RestartContext): WatchHandle { + const iterators: AsyncIterator[] = []; + let stopped = false; + + for (const [name, service] of Object.entries(ctx.config.services)) { + const plugin = ctx.plugins.get(service.type); + if (service.mode === "skip" || service.initTask || !plugin?.watchForChanges) continue; + + const iterable = plugin.watchForChanges({ + serviceName: name, + servicePath: resolve(ctx.workspaceDir, service.path), + }); + const iterator = iterable[Symbol.asyncIterator](); + iterators.push(iterator); + void followSignals(name, iterator); + } + + async function followSignals(name: string, iterator: AsyncIterator) { + debug("watching %s", name); + while (!stopped) { + const next = await iterator.next().catch((err: unknown) => { + ctx.emit({ kind: "error", message: `Watching "${name}" failed: ${String(err)}` }); + return { done: true as const, value: undefined }; + }); + if (next.done || stopped) return; + + ctx.emit({ kind: "phase", phase: `Restarting ${name}: ${next.value.reason}` }); + await restartAndReplace(name); + } + } + + async function restartAndReplace(name: string) { + const index = handles.findIndex((h) => h.serviceName === name); + try { + const handle = await restartService(name, handles[index], ctx); + if (index === -1) handles.push(handle); + else handles[index] = handle; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + ctx.emit({ kind: "error", message: `Restarting "${name}" failed: ${message}` }); + } + } + + return { + stop: () => { + stopped = true; + for (const iterator of iterators) void iterator.return?.(); + }, + }; +} diff --git a/packages/cli/src/runner/compose.ts b/packages/cli/src/runner/compose.ts index ad4ac8a..be8df2b 100644 --- a/packages/cli/src/runner/compose.ts +++ b/packages/cli/src/runner/compose.ts @@ -37,6 +37,8 @@ export type ComposeExecOptions = { cwd?: string; signal?: AbortSignal; onOutput?: (line: ComposeOutputLine) => void; + /** Replace existing containers even if their config is unchanged (composeUp only). */ + forceRecreate?: boolean; /** Start only the listed services, not what they depend on (composeUp only). */ noDeps?: boolean; }; @@ -94,6 +96,7 @@ export async function composeUp( ): Promise { debug("composeUp: project=%s services=%o", options.projectName, options.services ?? []); const args = [...buildBaseArgs(options), "up", "-d", "--build"]; + if (options.forceRecreate) args.push("--force-recreate"); if (options.noDeps) args.push("--no-deps"); if (options.services?.length) { args.push(...options.services); diff --git a/packages/cli/tests/orchestrator/restart.test.ts b/packages/cli/tests/orchestrator/restart.test.ts new file mode 100644 index 0000000..17f9cb1 --- /dev/null +++ b/packages/cli/tests/orchestrator/restart.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect, mock } from "bun:test"; +import type { Plugin, RestartSignal, ServiceConfig, WorkspaceConfig } from "@lo1/sdk"; +import { restartService, type RestartContext } from "../../src/orchestrator/restart"; +import { watchPluginServices } from "../../src/orchestrator/watch"; +import type { ServiceHandle } from "../../src/orchestrator/service"; +import type { OrchestratorEvent } from "../../src/orchestrator/types"; +import { validateRestartTargets } from "../../src/cli/commands/restart"; + +function service(overrides: Partial = {}): ServiceConfig { + return { + type: "service", + path: "./svc", + mode: "dev", + command: "run", + dependsOn: [], + initTask: false, + ...overrides, + } as ServiceConfig; +} + +const config: WorkspaceConfig = { + version: "1", + name: "shop", + services: { + api: service({ port: 3000, hooks: { preStop: "./drain.sh" } }), + seed: service({ initTask: true }), + orders: service({ type: "celerity", mode: "container" }), + off: service({ mode: "skip" }), + }, +}; + +function makeHandle(name: string, overrides: Partial = {}): ServiceHandle { + return { + serviceName: name, + type: "process", + pid: 1, + running: true, + stop: mock(() => Promise.resolve()), + ...overrides, + }; +} + +function makeContext(overrides: Partial = {}) { + const events: OrchestratorEvent[] = []; + const ctx: RestartContext = { + config, + workspaceDir: "/ws", + registry: { endpoints: new Map() }, + plugins: new Map(), + pluginEnvVars: { QUEUE_URL: "x" }, + compose: { projectName: "lo1-shop", fileArgs: [], cwd: "/ws" }, + detached: true, + emit: (e) => events.push(e), + deps: { + startService: mock((opts) => Promise.resolve(makeHandle(opts.serviceName, { pid: 2 }))), + executeHook: mock((name) => Promise.resolve({ exitCode: 0, hookName: name })), + }, + ...overrides, + }; + return { ctx, events }; +} + +const statuses = (events: OrchestratorEvent[]) => + events.filter((e) => e.kind === "service").map((e) => (e.kind === "service" ? e.status : "")); + +describe("restartService", () => { + it("should run preStop, stop the service, then start it again detached and recreated", async () => { + const { ctx, events } = makeContext(); + const current = makeHandle("api"); + + const handle = await restartService("api", current, ctx); + + expect(statuses(events)).toEqual(["stopping", "stopped", "starting", "started"]); + expect(ctx.deps.executeHook).toHaveBeenCalledTimes(1); + expect(current.stop).toHaveBeenCalled(); + const opts = (ctx.deps.startService as ReturnType).mock.calls[0][0]; + expect(opts).toMatchObject({ detached: true, recreate: true, pluginEnvVars: { QUEUE_URL: "x" } }); + expect(handle.pid).toBe(2); + }); + + it("should rerun an init task without stopping anything and report it completed", async () => { + const { ctx, events } = makeContext(); + + await restartService("seed", undefined, ctx); + + expect(statuses(events)).toEqual(["starting", "completed"]); + }); + + it("should propagate a failed start", async () => { + const { ctx } = makeContext({ + deps: { + startService: mock(() => Promise.reject(new Error('Init task "seed" exited with code 1'))), + executeHook: mock((name) => Promise.resolve({ exitCode: 0, hookName: name })), + }, + }); + + await expect(restartService("seed", undefined, ctx)).rejects.toThrow("exited with code 1"); + }); +}); + +function signalChannel() { + const queue: RestartSignal[] = []; + let wake: (() => void) | undefined; + let closed = false; + const iterable: AsyncIterable = { + [Symbol.asyncIterator]: () => ({ + async next() { + while (queue.length === 0 && !closed) await new Promise((r) => (wake = r)); + if (queue.length > 0) return { done: false, value: queue.shift()! }; + return { done: true, value: undefined }; + }, + async return() { + closed = true; + wake?.(); + return { done: true, value: undefined }; + }, + }), + }; + return { + iterable, + send(signal: RestartSignal) { + queue.push(signal); + wake?.(); + }, + }; +} + +describe("watchPluginServices", () => { + it("should restart a service when its plugin signals a change and keep the new handle", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + const { ctx, events } = makeContext({ plugins: new Map([["celerity", plugin]]) }); + const handles = [makeHandle("orders", { type: "container" })]; + + const watcher = watchPluginServices(handles, ctx); + channel.send({ reason: "blueprint changed" }); + await new Promise((r) => setTimeout(r, 20)); + watcher.stop(); + + expect(events).toContainEqual({ kind: "phase", phase: "Restarting orders: blueprint changed" }); + expect(handles[0].pid).toBe(2); + }); + + it("should report a failed restart and keep watching", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + const startService = mock() + .mockImplementationOnce(() => Promise.reject(new Error("boom"))) + .mockImplementation((opts) => Promise.resolve(makeHandle(opts.serviceName, { pid: 3 }))); + const { ctx, events } = makeContext({ + plugins: new Map([["celerity", plugin]]), + deps: { startService, executeHook: mock((n) => Promise.resolve({ exitCode: 0, hookName: n })) }, + }); + const handles = [makeHandle("orders", { type: "container" })]; + + const watcher = watchPluginServices(handles, ctx); + channel.send({ reason: "first" }); + await new Promise((r) => setTimeout(r, 20)); + channel.send({ reason: "second" }); + await new Promise((r) => setTimeout(r, 20)); + watcher.stop(); + + expect(events).toContainEqual({ kind: "error", message: 'Restarting "orders" failed: boom' }); + expect(handles[0].pid).toBe(3); + }); + + it("should not watch services whose plugin has no watchForChanges", () => { + const watch = mock(() => signalChannel().iterable); + const { ctx } = makeContext({ plugins: new Map([["other", { name: "other", watchForChanges: watch }]]) }); + + watchPluginServices([], ctx).stop(); + + expect(watch).not.toHaveBeenCalled(); + }); +}); + +describe("validateRestartTargets", () => { + it("should reject unknown and skip-mode services", () => { + expect(() => validateRestartTargets(["nope"], config)).toThrow( + 'Unknown service "nope". Check the services in lo1.yaml.', + ); + expect(() => validateRestartTargets(["off"], config)).toThrow( + 'Service "off" has mode: skip, so lo1 does not run it.', + ); + expect(() => validateRestartTargets(["api", "seed"], config)).not.toThrow(); + }); +}); diff --git a/packages/cli/tests/orchestrator/service.test.ts b/packages/cli/tests/orchestrator/service.test.ts index 43749bf..65b16fe 100644 --- a/packages/cli/tests/orchestrator/service.test.ts +++ b/packages/cli/tests/orchestrator/service.test.ts @@ -215,6 +215,27 @@ describe("startService", () => { expect(waitOpts.waitForExit).toEqual([]); }); + it("should recreate only the service, not its helpers, when restarting", async () => { + const config = makeConfig({ + web: { mode: "container", compose: "compose.yaml" }, + }); + const deps = makeDeps({ findComposeHelpers: mock(() => Promise.resolve(["cache"])) }); + const options = makeOptions({ + serviceName: "web", + serviceConfig: config.services.web, + config, + recreate: true, + }); + + await startService(options, deps); + + const calls = (deps.composeUp as ReturnType).mock.calls.map((c) => c[0]); + expect(calls).toHaveLength(2); + expect(calls[0]).toMatchObject({ services: ["cache"], noDeps: true }); + expect(calls[0].forceRecreate).toBeUndefined(); + expect(calls[1]).toMatchObject({ services: ["web"], noDeps: true, forceRecreate: true }); + }); + it("should start a compose service's own helpers but wait only on the service", async () => { const config = makeConfig({ web: { mode: "container", compose: "compose.yaml" }, diff --git a/packages/cli/tests/orchestrator/stop.test.ts b/packages/cli/tests/orchestrator/stop.test.ts index 1eb4e65..3fff36b 100644 --- a/packages/cli/tests/orchestrator/stop.test.ts +++ b/packages/cli/tests/orchestrator/stop.test.ts @@ -1,5 +1,8 @@ import { describe, it, expect, mock } from "bun:test"; -import { resolve } from "node:path"; +import { resolve, join } from "node:path"; +import { mkdtemp, rm } from "node:fs/promises"; +import { platform, tmpdir } from "node:os"; +import { startProcess } from "../../src/runner/process"; import { stopWorkspace, hydrateHandles, type StopDeps } from "../../src/orchestrator/stop"; import type { ServiceHandle } from "../../src/orchestrator/service"; import type { WorkspaceState, OrchestratorEvent } from "../../src/orchestrator/types"; @@ -109,6 +112,7 @@ describe("stopWorkspace", () => { const handle: ServiceHandle = { serviceName: "web", type: "process", + pid: 12345, running: true, stop: mock(async () => { calls.push("stop:web"); @@ -144,7 +148,13 @@ describe("stopWorkspace", () => { executeHook: mock(() => Promise.reject(new Error("exit 1"))), }); const stop = mock(() => Promise.resolve()); - const handle: ServiceHandle = { serviceName: "web", type: "process", running: true, stop }; + const handle: ServiceHandle = { + serviceName: "web", + type: "process", + pid: 12345, + running: true, + stop, + }; const events: OrchestratorEvent[] = []; await stopWorkspace( @@ -160,6 +170,55 @@ describe("stopWorkspace", () => { }); }); + it("should also stop processes in the state file that it holds no handle for", async () => { + const killCalls: number[] = []; + const originalKill = process.kill; + process.kill = ((pid: number, signal?: string | number) => { + if (signal === 0) throw new Error("ESRCH"); + killCalls.push(pid); + return true; + }) as typeof process.kill; + + try { + const tracked: ServiceHandle = { + serviceName: "api", + type: "process", + pid: 999, + running: true, + stop: mock(() => Promise.resolve()), + }; + await stopWorkspace({ workspaceDir: "/workspace", handles: [tracked] }, makeDeps()); + + expect(tracked.stop).toHaveBeenCalled(); + expect(killCalls.some((pid) => Math.abs(pid) === 12345)).toBe(true); + } finally { + process.kill = originalKill; + } + }); + + it("should skip process handles that have already exited", async () => { + const finished: ServiceHandle = { + serviceName: "migrate", + type: "process", + pid: 777, + running: false, + stop: mock(() => Promise.resolve()), + }; + const events: OrchestratorEvent[] = []; + + await stopWorkspace( + { + workspaceDir: "/workspace", + handles: [finished], + onEvent: (e) => events.push(e), + }, + makeDeps({ readState: mock(() => Promise.resolve({ ...sampleState, services: {} })) }), + ); + + expect(finished.stop).not.toHaveBeenCalled(); + expect(events.some((e) => e.kind === "service" && e.service === "migrate")).toBe(false); + }); + it("should stop container services using containerId from state", async () => { const deps = makeDeps(); @@ -183,6 +242,8 @@ describe("stopWorkspace", () => { const killCalls: [number, string | number][] = []; const originalKill = process.kill; process.kill = ((pid: number, signal?: string | number) => { + // Signal 0 is the liveness check: report the process gone once signalled. + if (signal === 0) throw new Error("ESRCH"); killCalls.push([pid, signal ?? "SIGTERM"]); return true; }) as typeof process.kill; @@ -281,6 +342,8 @@ describe("hydrateHandles", () => { const killCalls: [number, string | number][] = []; const originalKill = process.kill; process.kill = ((pid: number, signal?: string | number) => { + // Signal 0 is the liveness check: report the process gone once signalled. + if (signal === 0) throw new Error("ESRCH"); killCalls.push([pid, signal ?? "SIGTERM"]); return true; }) as typeof process.kill; @@ -296,4 +359,51 @@ describe("hydrateHandles", () => { process.kill = originalKill; } }); + + describe("with real processes", () => { + function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + } + + async function startDetached(command: string) { + const dir = await mkdtemp(join(tmpdir(), "lo1-stop-")); + const proc = startProcess({ + serviceName: "web", + command, + cwd: dir, + env: {}, + logFile: join(dir, "web.log"), + }); + await new Promise((r) => setTimeout(r, 200)); + const state: WorkspaceState = { + ...sampleState, + services: { web: { runner: "process", pid: proc.pid } }, + }; + return { dir, pid: proc.pid!, handle: hydrateHandles(state)[0] }; + } + + it.skipIf(platform() === "win32")("should wait for the process to exit", async () => { + const { dir, pid, handle } = await startDetached("sleep 30"); + + await handle.stop(2000); + + expect(isAlive(pid)).toBe(false); + 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"); + + 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/runner/compose.test.ts b/packages/cli/tests/runner/compose.test.ts index 512a548..4be3c8d 100644 --- a/packages/cli/tests/runner/compose.test.ts +++ b/packages/cli/tests/runner/compose.test.ts @@ -77,6 +77,15 @@ describe("composeUp", () => { expect(args).not.toContain("--wait"); }); + it("should add --force-recreate only when asked", async () => { + const spawnMock = mock(() => createMockChild()); + await composeUp(defaultOptions, spawnMock); + await composeUp({ ...defaultOptions, forceRecreate: true }, spawnMock); + + expect(spawnMock.mock.calls[0][1]).not.toContain("--force-recreate"); + expect(spawnMock.mock.calls[1][1]).toContain("--force-recreate"); + }); + it("should stream output via onOutput callback", async () => { const child = createMockChild(); // Prevent auto-close so we can emit data first diff --git a/packages/sdk/src/plugin.ts b/packages/sdk/src/plugin.ts index 0d8127f..996fd1b 100644 --- a/packages/sdk/src/plugin.ts +++ b/packages/sdk/src/plugin.ts @@ -47,6 +47,10 @@ export interface Plugin { /** * Sets up file watchers that trigger rebuilds/restarts. * Returns an async iterable that yields restart signals. Optional. + * + * lo1 follows it while `lo1 up` runs in the foreground (not with --detach), + * restarting the service on each signal and logging `signal.reason`. It + * calls the iterator's `return()` on shutdown, so release watchers there. */ watchForChanges?(input: WatchInput): AsyncIterable; } From 562fe1e460fd1a2fe357b091448e8df17080fe3a Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 17 Nov 2026 07:42:13 +0000 Subject: [PATCH 2/4] refactor(cli): move the service stop loop out of stopWorkspace --- packages/cli/src/orchestrator/stop.ts | 58 +++++++++++++++------------ 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/packages/cli/src/orchestrator/stop.ts b/packages/cli/src/orchestrator/stop.ts index dc0a3a6..138b1f6 100644 --- a/packages/cli/src/orchestrator/stop.ts +++ b/packages/cli/src/orchestrator/stop.ts @@ -151,6 +151,30 @@ function untrackedProcessHandles( ); } +type StopServicesContext = Omit & { + config: WorkspaceConfig | null; +}; + +/** Stops each service, running its preStop hook first while it is still running. */ +async function stopServiceHandles( + handles: ServiceHandle[], + ctx: StopServicesContext, +): Promise { + if (handles.length === 0) return; + + ctx.emit({ kind: "phase", phase: "Stopping services" }); + for (const handle of handles) { + // Finished init tasks and replaced processes have nothing left to stop. + if (handle.type === "process" && !handle.running) continue; + ctx.emit({ kind: "service", service: handle.serviceName, status: "stopping" }); + if (ctx.config && handle.running) { + await runServicePreStop({ ...ctx, handle, config: ctx.config }); + } + await handle.stop(); + ctx.emit({ kind: "service", service: handle.serviceName, status: "stopped" }); + } +} + export async function stopWorkspace( options: StopOptions, overrides: Partial = {}, @@ -167,12 +191,7 @@ export async function stopWorkspace( return; } - let config; - try { - config = await deps.loadConfig(); - } catch { - config = null; - } + const config = await deps.loadConfig().catch(() => null); if (config?.hooks?.preStop) { emit({ kind: "phase", phase: "Running preStop hook" }); @@ -189,26 +208,13 @@ export async function stopWorkspace( : hydrateHandles(state, deps.exec); debug("stopWorkspace: %d handles to stop", handles.length); - if (handles.length > 0) { - emit({ kind: "phase", phase: "Stopping services" }); - for (const handle of handles) { - // Finished init tasks and replaced processes have nothing left to stop. - if (handle.type === "process" && !handle.running) continue; - emit({ kind: "service", service: handle.serviceName, status: "stopping" }); - if (config && handle.running) { - await runServicePreStop({ - handle, - config, - workspaceDir, - executeHook: deps.executeHook, - emit, - signal: options.signal, - }); - } - await handle.stop(); - emit({ kind: "service", service: handle.serviceName, status: "stopped" }); - } - } + await stopServiceHandles(handles, { + config, + workspaceDir, + executeHook: deps.executeHook, + emit, + signal: options.signal, + }); const phase = options.clean ? "Removing infrastructure (volumes + orphans)" From 759c07c24f9c904e93c810dda8d9d8f7e0a6d4cb Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 17 Nov 2026 08:15:05 +0000 Subject: [PATCH 3/4] fix(cli): make restarts safe to repeat, run concurrently and interrupt lo1 restart now holds a workspace lock from reading the state file to writing it, and restarts the replacement when a name is given twice. The watcher records each replacement in the state file under the same lock, cleans up after a failed setup, and lets an in-flight restart finish before lo1 up tears down. Stopping a process waits for its whole process group, service preStop hooks get the plugin variables, and plugin-container init tasks are waited on until they exit. --- packages/cli/src/cli/commands/restart.ts | 73 +++++++------ packages/cli/src/cli/commands/up.ts | 54 +++++++--- packages/cli/src/orchestrator/lock.ts | 100 ++++++++++++++++++ packages/cli/src/orchestrator/restart.ts | 1 + packages/cli/src/orchestrator/service.ts | 26 ++--- packages/cli/src/orchestrator/stop.ts | 35 +++++- packages/cli/src/orchestrator/watch.ts | 73 +++++++++---- packages/cli/src/runner/container.ts | 13 +++ packages/cli/tests/cli/up.test.ts | 49 +++++++++ packages/cli/tests/orchestrator/lock.test.ts | 76 +++++++++++++ .../cli/tests/orchestrator/restart.test.ts | 86 ++++++++++++++- .../cli/tests/orchestrator/service.test.ts | 39 +++++++ packages/cli/tests/orchestrator/stop.test.ts | 79 +++++++++++++- packages/cli/tests/runner/container.test.ts | 23 ++++ 14 files changed, 640 insertions(+), 87 deletions(-) create mode 100644 packages/cli/src/orchestrator/lock.ts create mode 100644 packages/cli/tests/cli/up.test.ts create mode 100644 packages/cli/tests/orchestrator/lock.test.ts diff --git a/packages/cli/src/cli/commands/restart.ts b/packages/cli/src/cli/commands/restart.ts index c5397d8..6618560 100644 --- a/packages/cli/src/cli/commands/restart.ts +++ b/packages/cli/src/cli/commands/restart.ts @@ -12,6 +12,7 @@ import { startService, BUILTIN_TYPES } from "../../orchestrator/service"; import { applyModeOverride, buildServiceState, createLogger } from "../../orchestrator/start"; import { readState, writeState } from "../../orchestrator/state"; import { hydrateHandles } from "../../orchestrator/stop"; +import { withWorkspaceLock } from "../../orchestrator/lock"; import type { OrchestratorEvent, WorkspaceState } from "../../orchestrator/types"; export class RestartError extends Lo1Error { @@ -77,36 +78,48 @@ export const restartCommand = new Command("restart") const controller = new AbortController(); process.on("SIGINT", () => controller.abort()); - const state = await requireRunningWorkspace(workspaceDir); - const config = applyModeOverride(await loadWorkspaceConfig(), state.modeOverride); - validateRestartTargets(names, config); + // 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), + ); + }); - const emit = createRestartEventHandler(workspaceDir); - const ctx = { - config, - workspaceDir, - registry: buildEndpointRegistry(config), - plugins: await loadNeededPlugins(names, config, workspaceDir, emit), - pluginEnvVars: state.pluginEnvVars ?? {}, - compose: { projectName: state.projectName, fileArgs: state.fileArgs, cwd: workspaceDir }, - detached: true, - signal: controller.signal, - emit, - deps: { startService, executeHook }, - }; +async function restartServices( + names: string[], + workspaceDir: string, + signal: AbortSignal, +): Promise { + const state = await requireRunningWorkspace(workspaceDir); + const config = applyModeOverride(await loadWorkspaceConfig(), state.modeOverride); + validateRestartTargets(names, config); - const current = hydrateHandles(state); - for (const name of names) { - const handle = await restartService( - name, - current.find((h) => h.serviceName === name), - ctx, - ); - handle.releaseLogs?.(); - handle.detach?.(); + const emit = createRestartEventHandler(workspaceDir); + const ctx = { + config, + workspaceDir, + registry: buildEndpointRegistry(config), + plugins: await loadNeededPlugins(names, config, workspaceDir, emit), + pluginEnvVars: state.pluginEnvVars ?? {}, + compose: { projectName: state.projectName, fileArgs: state.fileArgs, cwd: workspaceDir }, + detached: true, + signal, + emit, + deps: { startService, executeHook }, + }; - const { [name]: _previous, ...others } = state.services; - state.services = { ...others, ...buildServiceState([handle]) }; - await writeState(state, workspaceDir); - } - }); + const current = hydrateHandles(state); + for (const name of names) { + const index = current.findIndex((h) => h.serviceName === name); + const handle = await restartService(name, current[index], ctx); + handle.releaseLogs?.(); + handle.detach?.(); + // A name given twice restarts the replacement, not the original again. + if (index === -1) current.push(handle); + else current[index] = handle; + + const { [name]: _previous, ...others } = state.services; + state.services = { ...others, ...buildServiceState([handle]) }; + await writeState(state, workspaceDir); + } +} diff --git a/packages/cli/src/cli/commands/up.ts b/packages/cli/src/cli/commands/up.ts index b02f3dd..98e0cc3 100644 --- a/packages/cli/src/cli/commands/up.ts +++ b/packages/cli/src/cli/commands/up.ts @@ -1,10 +1,12 @@ import { Command } from "commander"; import { spawn } from "node:child_process"; import { platform } from "node:os"; -import { startWorkspace } from "../../orchestrator/start"; +import { buildServiceState, startWorkspace } from "../../orchestrator/start"; import { stopWorkspace } from "../../orchestrator/stop"; import { watchPluginServices } from "../../orchestrator/watch"; -import { startService } from "../../orchestrator/service"; +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"; @@ -126,6 +128,20 @@ async function teardown(opts: TeardownOptions): Promise { } } +/** Points the state file at a service's new process after the watcher restarts it. */ +export async function recordReplacement( + workspaceDir: string, + handle: ServiceHandle, +): Promise { + const state = await readState(workspaceDir); + if (!state) return; + const { [handle.serviceName]: _previous, ...others } = state.services; + await writeState( + { ...state, services: { ...others, ...buildServiceState([handle]) } }, + workspaceDir, + ); +} + export const upCommand = new Command("up") .description("Start all services and infrastructure") .option("--services ", "Comma-separated list of services to start") @@ -189,20 +205,28 @@ 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 }, - }); + 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), + }, + ); await waitForShutdownSignal(controller); - watcher.stop(); + // Let a restart under way finish, so teardown sees its new process. + await watcher.stop(); } catch (err) { if (!controller.signal.aborted) { startupError = err; diff --git a/packages/cli/src/orchestrator/lock.ts b/packages/cli/src/orchestrator/lock.ts new file mode 100644 index 0000000..484b43c --- /dev/null +++ b/packages/cli/src/orchestrator/lock.ts @@ -0,0 +1,100 @@ +import { randomUUID } from "node:crypto"; +import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { createLog } from "../debug"; +import { Lo1Error } from "../errors"; + +const debug = createLog("orchestrator:lock"); + +export class WorkspaceLockError extends Lo1Error { + constructor(message: string) { + super(message, "WorkspaceLocked"); + this.name = "WorkspaceLockError"; + } +} + +export type WorkspaceLockOptions = { + /** How long to wait for another lo1 command to finish. */ + timeoutMs?: number; + pollMs?: number; + isAlive?: (pid: number) => boolean; +}; + +export function lockPath(workspaceDir: string): string { + return join(workspaceDir, ".lo1", "state.lock"); +} + +function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException).code === "EPERM"; + } +} + +/** + * Creates the lock with our pid already in it: the pid goes into a private + * file that is then hard-linked into place, which fails if the lock exists. + * Nobody can see a lock file without a pid and mistake it for a stale one. + */ +async function tryAcquire(path: string): Promise { + // Unique per attempt: the watcher may contend for the lock within one process. + const own = `${path}.${process.pid}.${randomUUID()}`; + await writeFile(own, String(process.pid)); + try { + await link(own, path); + return true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "EEXIST") return false; + throw err; + } finally { + await unlink(own).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 pid = Number.parseInt(content, 10); + if (Number.isInteger(pid) && isAlive(pid)) return pid; + + await unlink(path).catch(() => {}); + return null; +} + +/** + * Runs `fn` while holding the workspace's state lock, so lo1 commands that + * read, change and write the state file (restarts) never interleave. Waits + * for a running holder and takes over a lock whose holder has exited. + */ +export async function withWorkspaceLock( + workspaceDir: string, + fn: () => Promise, + options: WorkspaceLockOptions = {}, +): Promise { + const { timeoutMs = 120_000, pollMs = 100, isAlive = isProcessAlive } = options; + const path = lockPath(workspaceDir); + await mkdir(join(workspaceDir, ".lo1"), { recursive: true }); + + const deadline = Date.now() + timeoutMs; + while (!(await tryAcquire(path))) { + const holder = await liveHolder(path, isAlive); + if (holder === null) continue; + if (Date.now() >= deadline) { + throw new WorkspaceLockError( + `Another lo1 command (pid ${holder}) is still changing this workspace. ` + + `Wait for it to finish, then try again.`, + ); + } + await new Promise((r) => setTimeout(r, pollMs)); + } + + debug("acquired %s", path); + try { + return await fn(); + } finally { + await unlink(path).catch(() => {}); + debug("released %s", path); + } +} diff --git a/packages/cli/src/orchestrator/restart.ts b/packages/cli/src/orchestrator/restart.ts index 74c3c71..51a2cb0 100644 --- a/packages/cli/src/orchestrator/restart.ts +++ b/packages/cli/src/orchestrator/restart.ts @@ -41,6 +41,7 @@ export async function restartService( handle: current, config: ctx.config, workspaceDir: ctx.workspaceDir, + pluginEnvVars: ctx.pluginEnvVars, executeHook: ctx.deps.executeHook, emit: ctx.emit, signal: ctx.signal, diff --git a/packages/cli/src/orchestrator/service.ts b/packages/cli/src/orchestrator/service.ts index a8482d7..026a8f0 100644 --- a/packages/cli/src/orchestrator/service.ts +++ b/packages/cli/src/orchestrator/service.ts @@ -96,7 +96,7 @@ export const BUILTIN_TYPES = new Set(["service", "app"]); type Runner = "plugin-container" | "process" | "compose"; -/** A started service, plus the exit of its process when lo1 runs it on the host. */ +/** A started service, plus how lo1 learns it exited when it waits on that (init tasks). */ type StartedRunner = { handle: ServiceHandle; exited?: Promise; @@ -160,9 +160,7 @@ async function startRunner( env: Record, deps: StartServiceDeps, ): Promise { - if (runner === "plugin-container") { - return { handle: await startWithContainer(options, env, deps) }; - } + if (runner === "plugin-container") return startWithContainer(options, env, deps); if (runner === "process") return startWithProcess(options, env, deps); return { handle: await startWithCompose(options, deps) }; } @@ -245,7 +243,7 @@ async function startWithContainer( options: StartServiceOptions, env: Record, deps: StartServiceDeps, -): Promise { +): Promise { const { serviceName, serviceConfig, plugin, config, registry } = options; const endpoints: Record = {}; @@ -277,14 +275,18 @@ async function startWithContainer( }); return { - serviceName, - type: "container", - containerId: handle.containerId, - get running() { - return handle.running; + handle: { + serviceName, + type: "container", + containerId: handle.containerId, + get running() { + return handle.running; + }, + stop: (timeout) => handle.stop(timeout), + releaseLogs: () => handle.releaseLogs(), }, - stop: (timeout) => handle.stop(timeout), - releaseLogs: () => handle.releaseLogs(), + // An init task only counts as done once its container exits with code 0. + exited: serviceConfig.initTask ? handle.waitForExit() : undefined, }; } diff --git a/packages/cli/src/orchestrator/stop.ts b/packages/cli/src/orchestrator/stop.ts index 138b1f6..883c690 100644 --- a/packages/cli/src/orchestrator/stop.ts +++ b/packages/cli/src/orchestrator/stop.ts @@ -1,5 +1,6 @@ import { execFile } from "node:child_process"; import { resolve } from "node:path"; +import { platform } from "node:os"; import { promisify } from "node:util"; import type { WorkspaceConfig } from "@lo1/sdk"; import { createLog } from "../debug"; @@ -114,6 +115,25 @@ function isAlive(pid: number): boolean { } } +/** + * Whether anything in the process group `pid` leads is still running. Only + * ESRCH means the group is gone; any other error (EPERM) means it may exist. + */ +export function isGroupAlive(pid: number, kill: typeof process.kill = process.kill): boolean { + try { + kill(-pid, 0); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +/** Detached services lead their own process group; on Windows there are no groups. */ +function isTreeAlive(pid: number): boolean { + if (platform() === "win32") return isAlive(pid); + return isGroupAlive(pid) || isAlive(pid); +} + function trySignal(pid: number, signal: NodeJS.Signals): void { try { signalProcessTree(pid, signal); @@ -123,17 +143,18 @@ function trySignal(pid: number, signal: NodeJS.Signals): void { } /** - * Stops a process lo1 did not spawn in this run, waiting for it to exit so - * its port is free again, and killing it if it outlasts the timeout. + * Stops a process lo1 did not spawn in this run, waiting for it and its + * children to exit so its port is free again, and killing whatever is left + * of the group if it outlasts the timeout. */ async function stopProcessByPid(pid: number, timeoutMs: number): Promise { trySignal(pid, "SIGTERM"); const deadline = Date.now() + timeoutMs; - while (isAlive(pid) && Date.now() < deadline) { + while (isTreeAlive(pid) && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); } - if (isAlive(pid)) trySignal(pid, "SIGKILL"); + if (isTreeAlive(pid)) trySignal(pid, "SIGKILL"); } /** @@ -211,6 +232,7 @@ export async function stopWorkspace( await stopServiceHandles(handles, { config, workspaceDir, + pluginEnvVars: state.pluginEnvVars ?? {}, executeHook: deps.executeHook, emit, signal: options.signal, @@ -235,6 +257,8 @@ export type ServicePreStopContext = { handle: ServiceHandle; config: WorkspaceConfig; workspaceDir: string; + /** The plugin variables the service was started with, as its other hooks get them. */ + pluginEnvVars?: Record; executeHook: OrchestratorDeps["executeHook"]; emit: (event: OrchestratorEvent) => void; signal?: AbortSignal; @@ -252,7 +276,8 @@ export async function runServicePreStop(ctx: ServicePreStopContext): Promise void }; +export type WatchHandle = { + /** Stops watching and resolves once any restart already under way has finished. */ + stop: () => Promise; +}; + +export type WatchOptions = { + /** Runs each restart exclusively, e.g. under the workspace state lock. */ + runExclusive?: (fn: () => Promise) => Promise; + /** Called with each replacement handle, inside `runExclusive`, to record it. */ + onReplaced?: (handle: ServiceHandle) => Promise; +}; /** * Follows each plugin's watchForChanges() for the services it owns and @@ -15,21 +25,38 @@ export type WatchHandle = { stop: () => void }; * Restarts of one service never overlap; a failed restart is reported and * watching continues. */ -export function watchPluginServices(handles: ServiceHandle[], ctx: RestartContext): WatchHandle { +export function watchPluginServices( + handles: ServiceHandle[], + ctx: RestartContext, + options: WatchOptions = {}, +): WatchHandle { + const runExclusive = options.runExclusive ?? ((fn) => fn()); const iterators: AsyncIterator[] = []; + const inFlight = new Set>(); let stopped = false; - for (const [name, service] of Object.entries(ctx.config.services)) { - const plugin = ctx.plugins.get(service.type); - if (service.mode === "skip" || service.initTask || !plugin?.watchForChanges) continue; + const closeIterators = () => { + stopped = true; + for (const iterator of iterators) void iterator.return?.(); + }; + + try { + for (const [name, service] of Object.entries(ctx.config.services)) { + const plugin = ctx.plugins.get(service.type); + if (service.mode === "skip" || service.initTask || !plugin?.watchForChanges) continue; - const iterable = plugin.watchForChanges({ - serviceName: name, - servicePath: resolve(ctx.workspaceDir, service.path), - }); - const iterator = iterable[Symbol.asyncIterator](); - iterators.push(iterator); - void followSignals(name, iterator); + const iterable = plugin.watchForChanges({ + serviceName: name, + servicePath: resolve(ctx.workspaceDir, service.path), + }); + const iterator = iterable[Symbol.asyncIterator](); + iterators.push(iterator); + void followSignals(name, iterator); + } + } catch (err) { + // Don't leave the watchers that did start running behind a failed setup. + closeIterators(); + throw err; } async function followSignals(name: string, iterator: AsyncIterator) { @@ -42,7 +69,12 @@ export function watchPluginServices(handles: ServiceHandle[], ctx: RestartContex if (next.done || stopped) return; ctx.emit({ kind: "phase", phase: `Restarting ${name}: ${next.value.reason}` }); - await restartAndReplace(name); + const restart = runExclusive(() => restartAndReplace(name)).catch((err: unknown) => + reportRestartFailure(name, err), + ); + inFlight.add(restart); + await restart; + inFlight.delete(restart); } } @@ -52,16 +84,21 @@ export function watchPluginServices(handles: ServiceHandle[], ctx: RestartContex const handle = await restartService(name, handles[index], ctx); if (index === -1) handles.push(handle); else handles[index] = handle; + await options.onReplaced?.(handle); } catch (err) { - const message = err instanceof Error ? err.message : String(err); - ctx.emit({ kind: "error", message: `Restarting "${name}" failed: ${message}` }); + reportRestartFailure(name, err); } } + function reportRestartFailure(name: string, err: unknown) { + const message = err instanceof Error ? err.message : String(err); + ctx.emit({ kind: "error", message: `Restarting "${name}" failed: ${message}` }); + } + return { - stop: () => { - stopped = true; - for (const iterator of iterators) void iterator.return?.(); + stop: async () => { + closeIterators(); + await Promise.allSettled([...inFlight]); }, }; } diff --git a/packages/cli/src/runner/container.ts b/packages/cli/src/runner/container.ts index 9e656bb..30d3afc 100644 --- a/packages/cli/src/runner/container.ts +++ b/packages/cli/src/runner/container.ts @@ -34,6 +34,8 @@ export type ContainerHandle = { readonly running: boolean; stop(timeoutMs?: number): Promise; readonly exitPromise: Promise; + /** Waits for the container to exit and returns its exit code, or null if Docker can't say. */ + waitForExit(): Promise; /** Stops following the container's logs; the container keeps running. */ releaseLogs(): void; }; @@ -181,6 +183,17 @@ export async function startContainer( }, stop, exitPromise, + waitForExit: () => waitForContainerExit(containerId, exec), releaseLogs: () => logChild.kill(), }; } + +async function waitForContainerExit(containerId: string, exec: ExecFn): Promise { + try { + const { stdout } = await exec("docker", ["wait", containerId]); + const code = Number.parseInt(stdout.trim(), 10); + return Number.isNaN(code) ? null : code; + } catch { + return null; + } +} diff --git a/packages/cli/tests/cli/up.test.ts b/packages/cli/tests/cli/up.test.ts new file mode 100644 index 0000000..467e227 --- /dev/null +++ b/packages/cli/tests/cli/up.test.ts @@ -0,0 +1,49 @@ +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 { recordReplacement } from "../../src/cli/commands/up"; +import { readState, writeState } from "../../src/orchestrator/state"; + +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-")); + await writeState( + { + workspaceName: "shop", + projectName: "lo1-shop", + fileArgs: [], + workspaceDir: dir, + services: { + api: { runner: "process", pid: 100 }, + web: { runner: "process", pid: 200 }, + }, + }, + dir, + ); + + await recordReplacement(dir, { + serviceName: "api", + type: "process", + pid: 300, + running: true, + stop: async () => {}, + }); + + const state = await readState(dir); + expect(state?.services).toEqual({ + api: { runner: "process", pid: 300 }, + web: { runner: "process", pid: 200 }, + }); + await rm(dir, { recursive: true, force: true }); + }); + + it("does nothing once the workspace is gone", async () => { + const dir = await mkdtemp(join(tmpdir(), "lo1-up-")); + + await recordReplacement(dir, { serviceName: "api", type: "process", pid: 1, running: true, stop: async () => {} }); + + expect(await readState(dir)).toBeNull(); + await rm(dir, { recursive: true, force: true }); + }); +}); diff --git a/packages/cli/tests/orchestrator/lock.test.ts b/packages/cli/tests/orchestrator/lock.test.ts new file mode 100644 index 0000000..96296bd --- /dev/null +++ b/packages/cli/tests/orchestrator/lock.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect } from "bun:test"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { lockPath, withWorkspaceLock } from "../../src/orchestrator/lock"; + +async function withTempDir(fn: (dir: string) => Promise) { + const dir = await mkdtemp(join(tmpdir(), "lo1-lock-")); + try { + await fn(dir); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +describe("withWorkspaceLock", () => { + it("runs one holder at a time", () => + withTempDir(async (dir) => { + const order: string[] = []; + const hold = (name: string) => + withWorkspaceLock( + dir, + async () => { + order.push(`${name} in`); + await new Promise((r) => setTimeout(r, 30)); + order.push(`${name} out`); + }, + { pollMs: 5 }, + ); + + await Promise.all([hold("a"), hold("b"), hold("c")]); + + // Whatever the order, each holder leaves before the next one enters. + expect(order).toHaveLength(6); + for (let i = 0; i < order.length; i += 2) { + expect(order[i].replace(" in", "")).toBe(order[i + 1].replace(" out", "")); + } + })); + + it("records its pid while held and removes the lock afterwards, even on failure", () => + withTempDir(async (dir) => { + let held = ""; + await withWorkspaceLock(dir, async () => { + held = await readFile(lockPath(dir), "utf-8"); + }); + const failed = withWorkspaceLock(dir, () => Promise.reject(new Error("boom"))); + + expect(held).toBe(String(process.pid)); + await expect(failed).rejects.toThrow("boom"); + await expect(readFile(lockPath(dir), "utf-8")).rejects.toThrow(); + })); + + it("takes over a lock whose holder has exited", () => + withTempDir(async (dir) => { + await mkdir(join(dir, ".lo1"), { recursive: true }); + await writeFile(lockPath(dir), "999999"); + + const result = await withWorkspaceLock(dir, async () => "ran", { isAlive: () => false }); + + expect(result).toBe("ran"); + })); + + it("gives up with a clear error while another command keeps the lock", () => + withTempDir(async (dir) => { + await mkdir(join(dir, ".lo1"), { recursive: true }); + await writeFile(lockPath(dir), "4242"); + + const attempt = withWorkspaceLock(dir, async () => "ran", { + isAlive: () => true, + timeoutMs: 30, + pollMs: 5, + }); + + await expect(attempt).rejects.toThrow("Another lo1 command (pid 4242)"); + })); +}); diff --git a/packages/cli/tests/orchestrator/restart.test.ts b/packages/cli/tests/orchestrator/restart.test.ts index 17f9cb1..cf64e3d 100644 --- a/packages/cli/tests/orchestrator/restart.test.ts +++ b/packages/cli/tests/orchestrator/restart.test.ts @@ -135,7 +135,7 @@ describe("watchPluginServices", () => { const watcher = watchPluginServices(handles, ctx); channel.send({ reason: "blueprint changed" }); await new Promise((r) => setTimeout(r, 20)); - watcher.stop(); + await watcher.stop(); expect(events).toContainEqual({ kind: "phase", phase: "Restarting orders: blueprint changed" }); expect(handles[0].pid).toBe(2); @@ -164,11 +164,93 @@ describe("watchPluginServices", () => { expect(handles[0].pid).toBe(3); }); + it("should let a restart under way finish before stop() resolves", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + let finishStart: () => void = () => {}; + const startService = mock( + (opts: { serviceName: string }) => + new Promise((r) => (finishStart = () => r(makeHandle(opts.serviceName, { pid: 4 })))), + ); + const { ctx } = makeContext({ + plugins: new Map([["celerity", plugin]]), + deps: { startService, executeHook: mock((n) => Promise.resolve({ exitCode: 0, hookName: n })) }, + }); + const handles = [makeHandle("orders", { type: "container" })]; + + const watcher = watchPluginServices(handles, ctx); + channel.send({ reason: "changed" }); + await new Promise((r) => setTimeout(r, 20)); + const stopped = watcher.stop(); + finishStart(); + await stopped; + + expect(handles[0].pid).toBe(4); + }); + + it("should run each restart exclusively and report the replacement", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + const { ctx } = makeContext({ plugins: new Map([["celerity", plugin]]) }); + const order: string[] = []; + const runExclusive = async (fn: () => Promise) => { + order.push("lock"); + const result = await fn(); + order.push("unlock"); + return result; + }; + const onReplaced = mock(async (handle: ServiceHandle) => { + order.push(`recorded ${handle.serviceName}:${handle.pid}`); + }); + + const watcher = watchPluginServices([makeHandle("orders", { type: "container" })], ctx, { + runExclusive, + onReplaced, + }); + channel.send({ reason: "changed" }); + await new Promise((r) => setTimeout(r, 20)); + await watcher.stop(); + + expect(order).toEqual(["lock", "recorded orders:2", "unlock"]); + }); + + it("should stop the watchers it started when a later plugin fails to set up", () => { + const returned = mock(() => Promise.resolve({ done: true as const, value: undefined })); + const started: AsyncIterable = { + [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}), return: returned }), + }; + const configWithTwo: WorkspaceConfig = { + ...config, + services: { + orders: service({ type: "celerity", mode: "container" }), + billing: service({ type: "broken", mode: "container" }), + }, + }; + const { ctx } = makeContext({ + config: configWithTwo, + plugins: new Map([ + ["celerity", { name: "celerity", watchForChanges: () => started }], + [ + "broken", + { + name: "broken", + watchForChanges: () => { + throw new Error("no watcher"); + }, + }, + ], + ]), + }); + + expect(() => watchPluginServices([], ctx)).toThrow("no watcher"); + expect(returned).toHaveBeenCalled(); + }); + it("should not watch services whose plugin has no watchForChanges", () => { const watch = mock(() => signalChannel().iterable); const { ctx } = makeContext({ plugins: new Map([["other", { name: "other", watchForChanges: watch }]]) }); - watchPluginServices([], ctx).stop(); + void watchPluginServices([], ctx).stop(); expect(watch).not.toHaveBeenCalled(); }); diff --git a/packages/cli/tests/orchestrator/service.test.ts b/packages/cli/tests/orchestrator/service.test.ts index 65b16fe..106e672 100644 --- a/packages/cli/tests/orchestrator/service.test.ts +++ b/packages/cli/tests/orchestrator/service.test.ts @@ -169,6 +169,45 @@ describe("startService", () => { expect(opts.ports).toEqual(["3000:3000"]); }); + it("should wait for a plugin-container init task to exit, and fail on a non-zero code", async () => { + const plugin: Plugin = { + name: "celerity", + configureContainer: mock(async () => ({ + image: "celerity:latest", + cmd: ["migrate"], + envVars: {}, + binds: [], + workingDir: "/app", + })), + }; + const containerExiting = (code: number) => + mock(() => + Promise.resolve({ + serviceName: "api", + containerId: "abc123", + running: true, + stop: mock(() => Promise.resolve()), + exitPromise: new Promise(() => {}), + waitForExit: () => Promise.resolve(code), + releaseLogs: () => {}, + }), + ); + const serviceConfig = { ...makeOptions().serviceConfig, initTask: true }; + + await expect( + startService( + makeOptions({ plugin, serviceConfig }), + makeDeps({ startContainer: containerExiting(0) }), + ), + ).resolves.toBeDefined(); + await expect( + startService( + makeOptions({ plugin, serviceConfig }), + makeDeps({ startContainer: containerExiting(2) }), + ), + ).rejects.toThrow('Init task "api" exited with code 2'); + }); + it("should call configureContainer with correct ContainerInput", async () => { const configureFn = mock(async (_input) => ({ image: "test:latest", diff --git a/packages/cli/tests/orchestrator/stop.test.ts b/packages/cli/tests/orchestrator/stop.test.ts index 3fff36b..c8e0f43 100644 --- a/packages/cli/tests/orchestrator/stop.test.ts +++ b/packages/cli/tests/orchestrator/stop.test.ts @@ -1,11 +1,18 @@ import { describe, it, expect, mock } from "bun:test"; import { resolve, join } from "node:path"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; import { platform, tmpdir } from "node:os"; import { startProcess } from "../../src/runner/process"; -import { stopWorkspace, hydrateHandles, type StopDeps } from "../../src/orchestrator/stop"; +import { + stopWorkspace, + hydrateHandles, + isGroupAlive, + runServicePreStop, + type StopDeps, +} from "../../src/orchestrator/stop"; import type { ServiceHandle } from "../../src/orchestrator/service"; import type { WorkspaceState, OrchestratorEvent } from "../../src/orchestrator/types"; +import type { WorkspaceConfig } from "@lo1/sdk"; const sampleState: WorkspaceState = { workspaceName: "my-platform", @@ -174,7 +181,7 @@ describe("stopWorkspace", () => { const killCalls: number[] = []; const originalKill = process.kill; process.kill = ((pid: number, signal?: string | number) => { - if (signal === 0) throw new Error("ESRCH"); + if (signal === 0) throw Object.assign(new Error("ESRCH"), { code: "ESRCH" }); killCalls.push(pid); return true; }) as typeof process.kill; @@ -243,7 +250,7 @@ describe("stopWorkspace", () => { const originalKill = process.kill; process.kill = ((pid: number, signal?: string | number) => { // Signal 0 is the liveness check: report the process gone once signalled. - if (signal === 0) throw new Error("ESRCH"); + if (signal === 0) throw Object.assign(new Error("ESRCH"), { code: "ESRCH" }); killCalls.push([pid, signal ?? "SIGTERM"]); return true; }) as typeof process.kill; @@ -343,7 +350,7 @@ describe("hydrateHandles", () => { const originalKill = process.kill; process.kill = ((pid: number, signal?: string | number) => { // Signal 0 is the liveness check: report the process gone once signalled. - if (signal === 0) throw new Error("ESRCH"); + if (signal === 0) throw Object.assign(new Error("ESRCH"), { code: "ESRCH" }); killCalls.push([pid, signal ?? "SIGTERM"]); return true; }) as typeof process.kill; @@ -396,6 +403,23 @@ describe("hydrateHandles", () => { await rm(dir, { recursive: true, force: true }); }); + it.skipIf(platform() === "win32")( + "should kill children that outlive their parent's exit", + async () => { + const { dir, handle } = await startDetached( + "(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); + + await handle.stop(500); + await new Promise((r) => setTimeout(r, 100)); + + expect(isAlive(childPid)).toBe(false); + 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"); @@ -407,3 +431,48 @@ describe("hydrateHandles", () => { }); }); }); + +describe("isGroupAlive", () => { + const killThrowing = (code: string) => + (() => { + throw Object.assign(new Error(code), { code }); + }) as unknown as typeof process.kill; + + it("probes the whole group, not just its leader", () => { + const kill = mock(() => true) as unknown as typeof process.kill; + + expect(isGroupAlive(42, kill)).toBe(true); + expect(kill).toHaveBeenCalledWith(-42, 0); + }); + + it("treats only ESRCH as the group being gone", () => { + expect(isGroupAlive(42, killThrowing("ESRCH"))).toBe(false); + expect(isGroupAlive(42, killThrowing("EPERM"))).toBe(true); + }); +}); + +describe("runServicePreStop", () => { + it("gives the hook the plugin variables the service was started with", async () => { + const executeHook = mock((name: string) => Promise.resolve({ exitCode: 0, hookName: name })); + const config = { + version: "1", + name: "shop", + services: { + api: { type: "service", path: "./api", mode: "dev", dependsOn: [], initTask: false, + hooks: { preStop: "./drain.sh" } }, + }, + } as unknown as WorkspaceConfig; + + await runServicePreStop({ + handle: { serviceName: "api", type: "process", running: true, stop: async () => {} }, + config, + workspaceDir: "/ws", + pluginEnvVars: { QUEUE_URL: "http://localhost:9324" }, + executeHook, + emit: () => {}, + }); + + const [, , opts] = executeHook.mock.calls[0] as unknown as [string, string, { env: Record }]; + expect(opts.env.QUEUE_URL).toBe("http://localhost:9324"); + }); +}); diff --git a/packages/cli/tests/runner/container.test.ts b/packages/cli/tests/runner/container.test.ts index bc29b08..86c4917 100644 --- a/packages/cli/tests/runner/container.test.ts +++ b/packages/cli/tests/runner/container.test.ts @@ -188,6 +188,29 @@ describe("startContainer", () => { expect(args[tIdx + 1]).toBe("30"); }); + it("should report the container's exit code from docker wait", async () => { + const execFn = mock((_cmd, args) => + Promise.resolve({ stdout: args[0] === "wait" ? "3\n" : "abc123def456\n", stderr: "" }), + ); + + const handle = await startContainer(defaultOptions, execFn, makeLogSpawnFn()); + + expect(await handle.waitForExit()).toBe(3); + expect(execFn.mock.calls.at(-1)?.[1]).toEqual(["wait", "abc123def456"]); + }); + + it("should report null when docker wait fails", async () => { + const execFn = mock((_cmd, args) => + args[0] === "wait" + ? Promise.reject(new Error("no such container")) + : Promise.resolve({ stdout: "abc123def456\n", stderr: "" }), + ); + + const handle = await startContainer(defaultOptions, execFn, makeLogSpawnFn()); + + expect(await handle.waitForExit()).toBeNull(); + }); + it("should throw ContainerRunnerError on docker run failure", () => { const execFn = mock(() => Promise.reject(new Error("docker failed"))); const logSpawn = makeLogSpawnFn(); From bf2db1f46a6e499667c126c2bb1eba54c58c41f0 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 17 Nov 2026 08:29:01 +0000 Subject: [PATCH 4/4] fix(cli): restart from the recorded process when lo1 restart replaced a watched service --- packages/cli/src/cli/commands/up.ts | 13 ++++++- packages/cli/src/orchestrator/watch.ts | 25 +++++++++++++- packages/cli/tests/cli/up.test.ts | 24 ++++++++++++- .../cli/tests/orchestrator/restart.test.ts | 34 +++++++++++++++++++ 4 files changed, 93 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/cli/commands/up.ts b/packages/cli/src/cli/commands/up.ts index 98e0cc3..40b8072 100644 --- a/packages/cli/src/cli/commands/up.ts +++ b/packages/cli/src/cli/commands/up.ts @@ -2,7 +2,7 @@ import { Command } from "commander"; import { spawn } from "node:child_process"; import { platform } from "node:os"; import { buildServiceState, startWorkspace } from "../../orchestrator/start"; -import { stopWorkspace } from "../../orchestrator/stop"; +import { hydrateHandles, stopWorkspace } from "../../orchestrator/stop"; import { watchPluginServices } from "../../orchestrator/watch"; import { withWorkspaceLock } from "../../orchestrator/lock"; import { readState, writeState } from "../../orchestrator/state"; @@ -128,6 +128,16 @@ async function teardown(opts: TeardownOptions): Promise { } } +/** A service's handle as the state file records it, if the workspace is still running. */ +export async function recordedHandle( + workspaceDir: string, + name: string, +): Promise { + const state = await readState(workspaceDir); + if (!state?.services[name]) return undefined; + return hydrateHandles({ ...state, services: { [name]: state.services[name] } })[0]; +} + /** Points the state file at a service's new process after the watcher restarts it. */ export async function recordReplacement( workspaceDir: string, @@ -222,6 +232,7 @@ export const upCommand = new Command("up") { runExclusive: (fn) => withWorkspaceLock(workspaceDir, fn), onReplaced: (handle) => recordReplacement(workspaceDir, handle), + recordedHandle: (name) => recordedHandle(workspaceDir, name), }, ); await waitForShutdownSignal(controller); diff --git a/packages/cli/src/orchestrator/watch.ts b/packages/cli/src/orchestrator/watch.ts index 727abcb..b3b3b44 100644 --- a/packages/cli/src/orchestrator/watch.ts +++ b/packages/cli/src/orchestrator/watch.ts @@ -16,8 +16,22 @@ export type WatchOptions = { runExclusive?: (fn: () => Promise) => Promise; /** Called with each replacement handle, inside `runExclusive`, to record it. */ onReplaced?: (handle: ServiceHandle) => Promise; + /** + * The service's handle as the state file records it, read inside + * `runExclusive`. Lets a restart pick up a process `lo1 restart` started + * since this watcher last replaced the service. + */ + recordedHandle?: (name: string) => Promise; }; +/** Whether two handles refer to different host processes or containers. */ +function isDifferentInstance(held: ServiceHandle | undefined, recorded: ServiceHandle): boolean { + if (recorded.type === "process") return recorded.pid !== held?.pid; + if (recorded.type === "container") return recorded.containerId !== held?.containerId; + // Compose services are recreated by compose itself, whichever handle is used. + return false; +} + /** * Follows each plugin's watchForChanges() for the services it owns and * restarts a service whenever its plugin yields a restart signal. Restarted @@ -78,10 +92,19 @@ export function watchPluginServices( } } + /** The handle to restart from: ours, unless `lo1 restart` has replaced the service since. */ + async function currentHandle(name: string, held: ServiceHandle | undefined) { + const recorded = await options.recordedHandle?.(name); + if (!recorded || !isDifferentInstance(held, recorded)) return held; + debug("%s was restarted elsewhere; restarting from the recorded handle", name); + return recorded; + } + async function restartAndReplace(name: string) { const index = handles.findIndex((h) => h.serviceName === name); try { - const handle = await restartService(name, handles[index], ctx); + const current = await currentHandle(name, handles[index]); + const handle = await restartService(name, current, ctx); if (index === -1) handles.push(handle); else handles[index] = handle; await options.onReplaced?.(handle); diff --git a/packages/cli/tests/cli/up.test.ts b/packages/cli/tests/cli/up.test.ts index 467e227..8c7cc08 100644 --- a/packages/cli/tests/cli/up.test.ts +++ b/packages/cli/tests/cli/up.test.ts @@ -2,7 +2,7 @@ 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 { recordReplacement } from "../../src/cli/commands/up"; +import { recordedHandle, recordReplacement } from "../../src/cli/commands/up"; import { readState, writeState } from "../../src/orchestrator/state"; describe("recordReplacement", () => { @@ -47,3 +47,25 @@ describe("recordReplacement", () => { await rm(dir, { recursive: true, force: true }); }); }); + +describe("recordedHandle", () => { + it("returns the service's handle from the state file, or undefined", async () => { + const dir = await mkdtemp(join(tmpdir(), "lo1-up-")); + await writeState( + { + workspaceName: "shop", + projectName: "lo1-shop", + fileArgs: [], + workspaceDir: dir, + services: { api: { runner: "process", pid: 300 } }, + }, + dir, + ); + + const handle = await recordedHandle(dir, "api"); + + expect(handle).toMatchObject({ serviceName: "api", type: "process", pid: 300 }); + expect(await recordedHandle(dir, "web")).toBeUndefined(); + await rm(dir, { recursive: true, force: true }); + }); +}); diff --git a/packages/cli/tests/orchestrator/restart.test.ts b/packages/cli/tests/orchestrator/restart.test.ts index cf64e3d..f386593 100644 --- a/packages/cli/tests/orchestrator/restart.test.ts +++ b/packages/cli/tests/orchestrator/restart.test.ts @@ -214,6 +214,40 @@ describe("watchPluginServices", () => { expect(order).toEqual(["lock", "recorded orders:2", "unlock"]); }); + it("should restart from the recorded process when lo1 restart replaced it", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + const { ctx } = makeContext({ plugins: new Map([["celerity", plugin]]) }); + const held = makeHandle("orders", { pid: 10 }); + const recorded = makeHandle("orders", { pid: 20 }); + + const watcher = watchPluginServices([held], ctx, { + recordedHandle: async () => recorded, + }); + channel.send({ reason: "changed" }); + await new Promise((r) => setTimeout(r, 20)); + await watcher.stop(); + + expect(recorded.stop).toHaveBeenCalled(); + expect(held.stop).not.toHaveBeenCalled(); + }); + + it("should keep its own handle when the state file records the same process", async () => { + const channel = signalChannel(); + const plugin: Plugin = { name: "celerity", watchForChanges: () => channel.iterable }; + const { ctx } = makeContext({ plugins: new Map([["celerity", plugin]]) }); + const held = makeHandle("orders", { pid: 10 }); + const recorded = makeHandle("orders", { pid: 10 }); + + const watcher = watchPluginServices([held], ctx, { recordedHandle: async () => recorded }); + channel.send({ reason: "changed" }); + await new Promise((r) => setTimeout(r, 20)); + await watcher.stop(); + + expect(held.stop).toHaveBeenCalled(); + expect(recorded.stop).not.toHaveBeenCalled(); + }); + it("should stop the watchers it started when a later plugin fails to set up", () => { const returned = mock(() => Promise.resolve({ done: true as const, value: undefined })); const started: AsyncIterable = {