Files
t3code/apps/server/src/serverRuntimeState.test.ts
T

305 lines
12 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 ProcessRunner from "./processRunner.ts";
import * as ServerOwnership from "./serverOwnership.ts";
import * as ServerRuntimeState from "./serverRuntimeState.ts";
const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
interface CapturedLog {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
describe("server ownership", () => {
const layerOwnership = ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer));
const makeState = ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: undefined },
port: 3773,
});
it.effect("lets only one of two racing starts own a state directory", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-race-" });
const statePath = path.join(root, "server-runtime.json");
const attempts = yield* Effect.all(
[
ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
],
{ concurrency: "unbounded" },
);
assert.equal(attempts.filter((result) => result._tag === "Success").length, 1);
const refused = attempts.find((result) => result._tag === "Failure");
assert.equal(refused?.failure._tag, "ServerAlreadyRunningError");
}).pipe(Effect.provide(layerOwnership)),
);
it.effect("refuses a second owner without touching its record, then allows a restart", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-" });
const statePath = path.join(root, "server-runtime.json");
const state = yield* makeState;
yield* Effect.scoped(
Effect.gen(function* () {
const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
yield* owner.publish(state);
const before = yield* fs.readFileString(statePath);
const refused = yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
Effect.flip,
);
assert.equal(refused._tag, "ServerAlreadyRunningError");
assert.equal(yield* fs.readFileString(statePath), before);
}),
);
assert.isFalse(yield* fs.exists(statePath));
yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
}).pipe(Effect.provide(layerOwnership)),
);
it.effect("refuses beside a live pre-lock server and ignores a stale record", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-legacy-" });
const statePath = path.join(root, "server-runtime.json");
const state = yield* makeState;
yield* ServerRuntimeState.persistServerRuntimeState({
path: statePath,
// @effect-diagnostics-next-line globalDateInEffect:off - Legacy identity uses the real process start time, not TestClock.
state: { ...state, startedAt: new Date().toISOString() },
});
const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
Effect.flip,
);
assert.equal(refused._tag, "ServerAlreadyRunningError");
yield* ServerRuntimeState.persistServerRuntimeState({
path: statePath,
state: { ...state, pid: 0 },
});
yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
}).pipe(Effect.provide(layerOwnership)),
);
it.effect("never removes a runtime record another server published", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-cleanup-" });
const statePath = path.join(root, "server-runtime.json");
const state = yield* makeState;
yield* Effect.scoped(
Effect.gen(function* () {
const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
yield* owner.publish(state);
yield* ServerRuntimeState.persistServerRuntimeState({
path: statePath,
state: { ...state, ownerId: "other-owner" },
});
}),
);
const remaining = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner");
}).pipe(Effect.provide(layerOwnership)),
);
});
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",
devUrl: "http://localhost:5733/",
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)),
);
it.effect("records the dev web URL when the server fronts a dev server", () =>
Effect.gen(function* () {
const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: new URL("http://localhost:5733") },
port: 13_773,
});
assert.equal(state.devUrl, "http://localhost:5733/");
assert.equal(state.origin, "http://127.0.0.1:13773");
const withoutDev = yield* ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: undefined },
port: 13_773,
});
assert.isFalse("devUrl" in withoutDev);
}),
);
it.effect("marks a service-supervised server so CLIs can tell it from a manual one", () =>
Effect.gen(function* () {
const managed = yield* ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: undefined },
port: 13_773,
serviceManaged: true,
});
const manual = yield* ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: undefined },
port: 13_773,
});
assert.isTrue(managed.serviceManaged);
// Older readers decode the file without the field, so it is omitted
// rather than written as false.
assert.isFalse("serviceManaged" in manual);
}),
);
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)),
);
});