Files
t3code/scripts/lib/server-runtime-probe.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

85 lines
3.3 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.
*/
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>();
});