Files
t3code/apps/server/src/serverRuntimeState.test.ts
T
Theo BrowneandClaude Opus 5 8a76bb83cc Fix liveness probe, --json output, and remaining unsettled state
Follow-up review of the pairing path and a second pass over seeding:

- `isPersistedServerRuntimeStateLive` reported non-positive pids as live.
  `process.kill` reads 0 and -1 as signal-group targets rather than
  process lookups, so neither throws and both were caught by the "it
  didn't throw, so it's running" branch. A truncated or hand-edited file
  recording either would be believed forever — the dev candidate wins the
  devUrl preference, so it also outranks a genuinely live server
  elsewhere and mints tokens into a database nothing reads. Rejected in
  the schema and re-checked at the call site; the errno cast is now a
  guard, since an out-of-range pid throws a TypeError with no `code`.
- `pairing url --json` emitted warnings on stdout ahead of the payload.
  The probe reads both state directories, so a corrupt file in the one
  *not* in use broke JSON for any consumer piping it; the quiet-logs
  layer was only applied around the issuing step that runs after. Verified
  with a crafted fixture: stdout is now valid JSON.
- Turns copied in the `pending` state were left unsettled. Same defect as
  the `running` case fixed previously — a user message accepted before its
  provider turn started, which only that thread's next message would ever
  clear.
- The source was read across a dozen implicit transactions while the
  installed app may be writing to it, so a project could vanish between
  the query that selected it and the copy that read its row. One deferred
  read transaction pins every query to a single snapshot.
- `--from` and `--to` resolving to the same directory is now refused. Not
  for the data loss it appears to be (the source reads a pre-transaction
  snapshot, so the rows come back — verified in both journal modes), but
  because the event log, the cursors, and everything outside the caps do
  not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-26 20:38:48 -07:00

221 lines
8.2 KiB
TypeScript

import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as ServerRuntimeState from "./serverRuntimeState.ts";
const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
interface CapturedLog {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
describe("serverRuntimeState", () => {
it.effect("persists and reads the runtime state", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "runtime", "server.json");
const state: ServerRuntimeState.PersistedServerRuntimeState = {
version: 1,
pid: 123,
host: "127.0.0.1",
port: 4_971,
origin: "http://127.0.0.1:4971",
startedAt: "2026-06-20T00:00:00.000Z",
};
yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.deepEqual(Option.getOrThrow(restored), state);
}).pipe(Effect.provide(NodeServices.layer)),
);
// A server killed with SIGKILL never runs its release finalizer, so the file
// survives it. Trusting a leftover file points callers at a dead port.
describe("isPersistedServerRuntimeStateLive", () => {
const stateForPid = (pid: number): ServerRuntimeState.PersistedServerRuntimeState => ({
version: 1,
pid,
port: 4_971,
origin: "http://127.0.0.1:4971",
startedAt: "2026-06-20T00:00:00.000Z",
});
it.effect("recognizes the current process as live", () =>
Effect.gen(function* () {
assert.isTrue(
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(process.pid)),
);
}),
);
it.effect("reports a pid that no longer exists as dead", () =>
Effect.gen(function* () {
// Above the default pid_max, so it cannot be a live process.
assert.isFalse(
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(0x7ffffffe)),
);
}),
);
// `process.kill` reads non-positive pids as signal-group targets rather
// than process lookups — 0 is the caller's own group, -1 every permitted
// process — so neither throws, and a probe that only catches would call
// both "live" no matter what wrote the file.
for (const pid of [0, -1]) {
it.effect(`reports pid ${String(pid)} as dead rather than signalling a group`, () =>
Effect.gen(function* () {
assert.isFalse(
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(pid)),
);
}),
);
}
// Out of range for a pid: process.kill throws a TypeError with no errno,
// which the EPERM check must not assume the shape of.
it.effect("reports an out-of-range pid as dead", () =>
Effect.gen(function* () {
assert.isFalse(
yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(2 ** 40)),
);
}),
);
});
it.effect("treats a missing runtime state file as absent", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(
path.join(root, "missing.json"),
);
assert.isTrue(Option.isNone(restored));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("preserves malformed state decode failures", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "server.json");
yield* fileSystem.writeFileString(statePath, "{not json");
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.isTrue(Option.isNone(restored));
assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
const error = logs[0]?.annotations.cause;
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "decode");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "SchemaError" });
}
}).pipe(
Effect.provide(
Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
),
);
});
it.effect("preserves runtime state read failures", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "server.json");
yield* fileSystem.makeDirectory(statePath);
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.isTrue(Option.isNone(restored));
assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);
const error = logs[0]?.annotations.cause;
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "read");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "PlatformError" });
}
}).pipe(
Effect.provide(
Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
),
);
});
it.effect("preserves runtime state persistence failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const blockedDirectory = path.join(root, "not-a-directory");
const statePath = path.join(blockedDirectory, "server.json");
yield* fileSystem.writeFileString(blockedDirectory, "blocked");
const error = yield* ServerRuntimeState.persistServerRuntimeState({
path: statePath,
state: {
version: 1,
pid: 123,
port: 4_971,
origin: "http://127.0.0.1:4971",
startedAt: "2026-06-20T00:00:00.000Z",
},
}).pipe(Effect.flip);
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "persist");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "PlatformError" });
}
}).pipe(Effect.provide(NodeServices.layer)),
);
});