import { jsonKey } from "@usine/core/json-key"; import { DateTime, Effect, Option } from "effect"; import { chmodSync, existsSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync, // The synchronous fixture filesystem has no Effect FileSystem equivalent. // @effect-diagnostics-next-line nodeBuiltinImport:off } from "node:fs"; // Synchronous Node path callbacks retain the host platform’s path semantics. // @effect-diagnostics-next-line nodeBuiltinImport:off import { join } from "node:path"; import { RunId } from "@usine/core/run"; import { assert, describe, it } from "@effect/vitest"; import { UiOrigin } from "@usine/config/factory"; import { writeAdminToken } from "../../src/auth/local.ts"; import { holdInstance } from "../../src/instance/lock.ts"; import { ListeningPortsError } from "../../src/instance/ports.ts"; import { InstanceLaunch, InstanceRecord, ProcessId, instanceFiles, } from "../../src/instance/record.ts"; import { probeInstance } from "../../src/instance/state.ts"; import { restart } from "../../src/restart.ts"; import { stop } from "../../src/stop.ts"; import { alive, FIXTURE, freePort, instanceFolder, options, pid1OfAnotherUser, pids, recordedOnly, registerLifecycleCleanup, runCli, SCENARIO_TIMEOUT_MS, services, startFixture, } from "./support.ts"; registerLifecycleCleanup(); describe("instance lifecycle", { timeout: SCENARIO_TIMEOUT_MS }, () => { it.live("starts in the background, records the new process, and stops it after the drain", () => Effect.gen(function* () { const directory = instanceFolder(); const files = instanceFiles(directory); const record = yield* startFixture(directory); assert.match( readFileSync(files.log, "utf8"), new RegExp(`fixture listening on ${record.launch.port}`), ); assert.strictEqual(readFileSync(files.pid, "utf8").trim(), String(record.pid)); yield* stop(directory, options(20)).pipe(Effect.provide(services)); assert.isFalse(alive(record.pid)); assert.isFalse(existsSync(files.record)); assert.isFalse(existsSync(files.pid)); const state = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(state._tag === "Stopped"); assert.deepStrictEqual(state.stale, Option.none()); }), ); it.live.each([ ["stop", ["--force"]], ["restart", []], ] as const)( "refuses stop and restart before signaling when the admin token is unsafe or missing: %s %j", ([command, flags]) => Effect.gen(function* () { const directory = instanceFolder(); const first = yield* startFixture(directory); const path = join(directory, ".usine/admin-token"); const expectRefusal = () => Effect.gen(function* () { const error = yield* runCli(directory, [command, ...flags]).pipe(Effect.flip); assert.include(error.message, path); assert.include(error.message, `uid ${process.getuid?.()}`); assert.include(error.message, "0600"); assert.isTrue(alive(first.pid)); }); chmodSync(path, 0o644); yield* expectRefusal(); chmodSync(path, 0o600); renameSync(path, `${path}.real`); symlinkSync(`${path}.real`, path); yield* expectRefusal(); rmSync(path); yield* expectRefusal(); writeFileSync(instanceFiles(directory).record, "unreadable"); yield* expectRefusal(); }), ); it.live("restarts into a new process with the recorded launch, port, origin, and log level", () => Effect.gen(function* () { const directory = instanceFolder(); const files = instanceFiles(directory); const first = yield* startFixture( directory, FIXTURE, "Debug", Option.some(UiOrigin.make("https://usine-orchestrator.tail1234.ts.net")), ); yield* restart(directory, options(20), recordedOnly).pipe(Effect.provide(services)); const state = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(state._tag === "Running"); pids.add(state.record.pid); assert.notStrictEqual(state.record.pid, first.pid); assert.isFalse(alive(first.pid)); assert.strictEqual(state.record.launch.port, first.launch.port); assert.deepStrictEqual(state.record.launch.nodeOptions, first.launch.nodeOptions); // Both starts passed --log-level and --origin to the fixture, which recorded them as usine up does. assert.strictEqual(state.record.launch.logLevel, "Debug"); assert.deepStrictEqual(state.record.launch.origin, first.launch.origin); assert.strictEqual(readFileSync(files.pid, "utf8").trim(), String(state.record.pid)); const log = readFileSync(files.log, "utf8"); assert.strictEqual(log.match(/fixture listening/gu)?.length, 2, log); yield* stop(directory, options(20)).pipe(Effect.provide(services)); }), ); it.live("refuses to restart while a run has a live attempt, unless forced", () => Effect.gen(function* () { const directory = instanceFolder(); const first = yield* startFixture(directory); const json1 = jsonKey([ { id: "run-live", state: "Running" }, { id: "run-done", state: "Succeeded" }, ]); writeFileSync(join(directory, "fixture-runs.json"), json1); writeFileSync(join(directory, "fixture-drain"), "never"); const refused = yield* restart(directory, options(20), recordedOnly).pipe( Effect.flip, Effect.provide(services), ); assert(refused._tag === "LiveAttemptsError"); assert.deepStrictEqual(refused.runs, [RunId.make("run-live")]); assert.isTrue(alive(first.pid), "a refused restart leaves the instance running"); yield* restart(directory, options(20, true), recordedOnly).pipe(Effect.provide(services)); const state = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(state._tag === "Running"); pids.add(state.record.pid); assert.isFalse(alive(first.pid)); yield* stop(directory, options(20, true)).pipe(Effect.provide(services)); }), ); it.live("checks an instance without a readable record on its own port, then restarts it", () => Effect.gen(function* () { const directory = instanceFolder(); const files = instanceFiles(directory); const first = yield* startFixture(directory); const json2 = jsonKey({ pid: "unreadable", }); const unreadable = json2; writeFileSync(files.record, unreadable); const variable = `USINE_TEST_GATEWAY_TOKEN_${process.pid}`; writeFileSync(join(directory, "fixture-gateway-env"), variable); const json3 = jsonKey([{ id: "run-live", state: "Running" }]); writeFileSync(join(directory, "fixture-runs.json"), json3); writeFileSync(join(directory, "fixture-drain"), "never"); // Nothing answers on the new port, so checks that asked it would pass and signal the instance. const fallback = InstanceLaunch.make({ node: first.launch.node, nodeOptions: first.launch.nodeOptions, script: FIXTURE, port: yield* freePort, logLevel: "Debug", allowVolatileInstance: false, }); assert.notStrictEqual(fallback.port, first.launch.port); const missing = yield* restart(directory, options(1), Effect.succeed(fallback)).pipe( Effect.flip, Effect.provide(services), ); assert(missing._tag === "MissingEnvironmentError"); assert.deepStrictEqual(missing.variables, [variable]); rmSync(join(directory, "fixture-gateway-env")); const refused = yield* restart(directory, options(1), Effect.succeed(fallback)).pipe( Effect.flip, Effect.provide(services), ); assert(refused._tag === "LiveAttemptsError"); assert.deepStrictEqual(refused.runs, [RunId.make("run-live")]); // A signal would make the fixture record its drain over the unreadable record. assert.strictEqual(readFileSync(files.record, "utf8"), unreadable, "no signal was sent"); assert.isTrue(alive(first.pid), "a refused restart leaves the instance running"); yield* restart(directory, options(20, true), Effect.succeed(fallback)).pipe( Effect.provide(services), ); const state = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(state._tag === "Running"); pids.add(state.record.pid); assert.notStrictEqual(state.record.pid, first.pid); assert.isFalse(alive(first.pid)); assert.strictEqual(state.record.launch.port, fallback.port); assert.strictEqual(state.record.launch.logLevel, "Debug"); yield* stop(directory, options(20, true)).pipe(Effect.provide(services)); }), ); // Another user's descriptors are unreadable, so this runs where pid 1 belongs to someone else. it.live.skipIf(!pid1OfAnotherUser)( "refuses to restart an instance without a readable record whose ports it can't list", () => Effect.gen(function* () { const directory = instanceFolder(); const files = instanceFiles(directory); const fallback = InstanceLaunch.make({ node: process.execPath, nodeOptions: [], script: FIXTURE, port: yield* freePort, logLevel: "Info", allowVolatileInstance: false, }); const refused = yield* Effect.gen(function* () { yield* holdInstance( directory, InstanceRecord.make({ pid: ProcessId.make(1), version: "0.3.0", startedAt: yield* DateTime.now, launch: fallback, }), ); yield* writeAdminToken(directory); writeFileSync(files.record, "unreadable"); return yield* restart(directory, options(1), Effect.succeed(fallback)).pipe(Effect.flip); }).pipe(Effect.scoped, Effect.provide(services)); assert.instanceOf(refused, ListeningPortsError); assert.strictEqual(refused.pid, 1); }), ); it.live("waits for a long drain without sending the second signal, and --force ends it", () => Effect.gen(function* () { const directory = instanceFolder(); const record = yield* startFixture(directory); writeFileSync(join(directory, "fixture-drain"), "never"); const timedOut = yield* stop(directory, options(1)).pipe( Effect.flip, Effect.provide(services), ); assert(timedOut._tag === "StopTimeoutError"); assert.isTrue(alive(record.pid)); const stopping = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(stopping._tag === "Running"); assert.isDefined(stopping.record.stoppingSince, "the drain is recorded"); // A second stop must not end the drain. const again = yield* stop(directory, options(1)).pipe(Effect.flip, Effect.provide(services)); assert(again._tag === "StopTimeoutError"); assert.isTrue(alive(record.pid)); yield* stop(directory, options(20, true)).pipe(Effect.provide(services)); assert.isFalse(alive(record.pid)); }), ); it.live("sends SIGKILL to a forced stop that doesn't exit before the timeout, and says so", () => Effect.gen(function* () { const directory = instanceFolder(); const record = yield* startFixture(directory); writeFileSync(join(directory, "fixture-drain"), "never"); writeFileSync(join(directory, "fixture-close"), "never"); const output = yield* runCli(directory, ["stop", "--force", "--timeout", "1"]); assert.match( output, new RegExp(`usine \\(pid ${record.pid}\\) did not exit within 1s\\. Sent SIGKILL`, "u"), ); assert.match(output, /usine stopped\./u); assert.isFalse(alive(record.pid)); const state = yield* probeInstance(directory).pipe(Effect.provide(services)); assert(state._tag === "Stopped"); }), ); });