Files
t3code/scripts/lib/server-runtime-probe.ts
T
Theo BrowneandClaude Opus 5 bc12b990a4 Re-check for a live server before commit; make the tie WAL-aware
Two findings from Macroscope review:

- The running-server guard was check-then-act. A copy takes seconds, and
  nothing stopped a server starting after the check returned None — the
  seed would then replace the projections and event log underneath it,
  which is exactly what the guard exists to prevent. `seedDevDatabase`
  now takes an optional probe and re-runs it immediately before COMMIT,
  where a rollback still costs nothing. This narrows the window to the
  commit itself rather than closing it: a filesystem read and a SQLite
  transaction share no lock, so a server starting in that last instant is
  still possible. Documented as such rather than claimed as airtight.
- The state-dir tiebreak read `state.sqlite` mtime, but the server runs
  SQLite in WAL mode, where writes land in `state.sqlite-wal` and the
  main file can stay untouched until a checkpoint. Verified: 50 writes
  left the main mtime unchanged while the sidecar advanced. So a busy
  directory lost the tie to a dormant one, and the seed overwrote the
  wrong database. Recency is now the newer of the two files.

Both verified end-to-end: a backdated main file with a fresh -wal now
wins the tie, and a probe returning a pid mid-copy leaves the target's
rows and event log intact.

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

119 lines
4.5 KiB
TypeScript

/**
* Whether a T3 Code server is currently running against a data directory.
*
* A maintained copy of the parts of `apps/server/src/serverRuntimeState.ts` that
* host scripts need: that package exposes no importable surface to `scripts/`,
* the same reason `./projection-tables.ts` exists. Only the fields read here are
* modelled, so a server that adds a field stays readable.
*/
// @effect-diagnostics nodeBuiltinImport:off - the sync probe runs inside a
// synchronous SQLite transaction, where the platform layer is not available.
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
/** The two state directories `deriveServerPaths` can select. */
const STATE_DIRS = ["dev", "userdata"] as const;
const RuntimeStateProbe = Schema.Struct({
/** Positive, for the reason `isPidLive` explains. */
pid: Schema.Int.check(Schema.isGreaterThan(0)),
});
const decodeRuntimeStateProbe = Schema.decodeUnknownEffect(
Schema.fromJsonString(RuntimeStateProbe),
);
/**
* The runtime-state file is removed by a release finalizer, so a server killed
* with SIGKILL — or one that crashed — leaves it behind. Signal 0 runs the
* permission and existence checks without delivering a signal, which is what
* distinguishes "still running" from "left this here on the way out".
*
* PIDs are reused eventually, so a false positive is possible in principle. For
* a guard on a destructive local-dev command that errs the safe way: the worst
* case is being told to stop a server that is already stopped.
*/
const isPidLive = (pid: number): boolean => {
// `process.kill` reads non-positive pids as signal-group targets rather than
// process lookups — 0 signals the caller's own group, -1 every permitted
// process — so neither throws and both would report "live" unconditionally.
// The schema rejects those, and this repeats the check so the invariant
// travels with the code that depends on it.
if (!Number.isSafeInteger(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch (cause) {
// EPERM means the process exists but belongs to another user. An
// out-of-range pid throws a TypeError instead, which has no errno.
return typeof cause === "object" && cause !== null && "code" in cause
? cause.code === "EPERM"
: false;
}
};
/**
* The pid of a live server under `baseDir`, if any.
*
* Both state directories are checked because which one a given server chose
* depends on flags the caller of this should not have to reason about — the
* same reason `auth pairing url` checks both.
*/
export const findRunningServerPid = Effect.fn("findRunningServerPid")(function* (baseDir: string) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
for (const stateDir of STATE_DIRS) {
const statePath = path.join(baseDir, stateDir, "server-runtime.json");
const raw = yield* fileSystem.readFileString(statePath).pipe(Effect.option);
if (Option.isNone(raw)) {
continue;
}
// A malformed or half-written file says nothing about liveness; treating it
// as "a server is up" would block seeding with no way to clear it.
const state = yield* decodeRuntimeStateProbe(raw.value).pipe(Effect.option);
if (Option.isSome(state) && isPidLive(state.value.pid)) {
return Option.some(state.value.pid);
}
}
return Option.none<number>();
});
/**
* The same probe, synchronously.
*
* `seedDevDatabase` is synchronous — it holds an open SQLite transaction — so
* its last-moment re-check cannot await an Effect. Reads the file directly
* rather than through the platform layer for that reason, and applies the same
* rules: a positive live pid counts, anything unparseable does not.
*/
export function findRunningServerPidSync(baseDir: string): number | undefined {
for (const stateDir of STATE_DIRS) {
const statePath = NodePath.join(baseDir, stateDir, "server-runtime.json");
let raw: string;
try {
raw = NodeFS.readFileSync(statePath, "utf8");
} catch {
continue;
}
try {
const parsed: unknown = JSON.parse(raw);
const pid: unknown = (parsed as { pid?: unknown } | null)?.pid;
if (typeof pid === "number" && isPidLive(pid)) {
return pid;
}
} catch {
// Half-written or malformed: says nothing about liveness either way.
}
}
return undefined;
}