fix(server): prevent duplicate servers for one state directory #9652
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 6 commits into
main fromt3code/prevent-duplicate-server-startsopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/cloud/bootService.ts line 782Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -747,10 +763,10 @@747763 .readFileString(launcherSourcePath)748764 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));749765750- const installed = yield* fs751- .exists(unitPath)752- .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));753766 if (installed) {754767 yield* runSteps(manager.stop);755768 }756769770+ // Stopping a managed unit does not stop an SSH or foreground server.771+ // Check again after preparation and before changing service configuration.772+ yield* requireServerStopped(runtimeStatePath).pipe(apps/server/src/cli/project.ts lines 370 to 370Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -368,5 +365,6 @@368365 origin: runtimeState.value.origin,369366 cause: attempted.failure,370367 });371- yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);368+ // A failed request does not transfer ownership of the discovery record.369+ // The server may still be running, or a replacement may have published it.372370 return Option.none<{ readonly origin: string }>();
- apps/server/src/cloud/bootService.ts line 782Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -747,10 +763,12 @@747763 .readFileString(launcherSourcePath)748764 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));749765750- const installed = yield* fs751- .exists(unitPath)752- .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));753766 if (installed) {754767 yield* runSteps(manager.stop);755768 }756769770+ // Stopping a managed unit does not stop an SSH or foreground server.771+ // Check again after preparation and before changing service configuration.772+ // Keep this outside restart recovery. An older installed runtime may not773+ // honor the lock, so restarting it could duplicate the unmanaged owner.774+ yield* requireServerStopped(runtimeStatePath).pipe(
- apps/server/src/serverOwnership.ts line 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ }),81+ ),82+ ),83+ );84+85+ // Older releases have no lock. Do not replace their record while their PID86+ // exists. New records with a free lock belong to a crashed or stopped owner.87+ const previous = yield* readPersistedServerRuntimeState(resource.path);88+ if (89+ Option.isSome(previous) &&90+ previous.value.ownerId === undefined &&91+ isProcessAlive(previous.value.pid)92+ ) {93+ return yield* new ServerAlreadyRunningError({ stateDir: resource.lock.stateDir });94+ }95+96+ return {97+ publish: (state: PersistedServerRuntimeState) =>98+ Effect.try({99+ try: () => {100+ if (!resource.active) throw new Error("Server ownership has been released.");apps/server/src/serverOwnership.ts lines 22 to 33Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+import * as NodePath from "node:path";5+import * as Effect from "effect/Effect";6+import * as Option from "effect/Option";7+import * as Schema from "effect/Schema";8+9+import { acquireServerOwnershipLock } from "./serverOwnershipLock.ts";10+11+import {12+ isProcessAlive,13+ readPersistedServerRuntimeState,14+ PersistedServerRuntimeState,15+} from "./serverRuntimeState.ts";16+17+export class ServerAlreadyRunningError extends Schema.TaggedErrorClass<ServerAlreadyRunningError>()(18+ "ServerAlreadyRunningError",19+ { stateDir: Schema.String },20+) {21+ override get message(): string {22+ return `A T3 Code server already owns ${this.stateDir}. Finish active agent work, stop that server through the app or terminal that started it, then run \`t3 service install\` with the same home directory. No server was stopped.`;23+ }24+}
- apps/server/src/serverOwnership.ts line 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ }81+ },82+ catch: (cause) => new ServerOwnershipError({ statePath, cause }),83+ }).pipe(Effect.ignore({ log: true }));84+ }).pipe(85+ Effect.ensuring(86+ Effect.sync(() => {87+ resource.active = false;88+ resource.lock.close();89+ }),90+ ),91+ ),92+ );93+94+ // Older releases have no lock. Do not replace their record while their PID95+ // exists. New records with a free lock belong to a crashed or stopped owner.96+ const previous = yield* readPersistedServerRuntimeState(resource.path);97+ if (98+ Option.isSome(previous) &&99+ previous.value.ownerId === undefined &&100+ isProcessAlive(previous.value.pid)
- apps/server/src/serverOwnership.ts line 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ }81+ },82+ catch: (cause) => new ServerOwnershipError({ statePath, cause }),83+ }).pipe(Effect.ignore({ log: true }));84+ }).pipe(85+ Effect.ensuring(86+ Effect.sync(() => {87+ resource.active = false;88+ resource.lock.close();89+ }),90+ ),91+ ),92+ );93+94+ // Older releases have no lock. Do not replace their record while their PID95+ // exists. New records with a free lock belong to a crashed or stopped owner.96+ const previous = yield* readPersistedServerRuntimeState(resource.path);97+ if (98+ Option.isSome(previous) &&99+ previous.value.ownerId === undefined &&100+ isProcessAlive(previous.value.pid)
- apps/server/src/serverOwnership.ts line 102Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +76,21 @@76+ }),77+ );78+ // ps reports whole seconds. Unknown identity stays conservative, and no79+ // process is ever signalled based on this comparison.80+ return startedAt === undefined || startedAt <= recordedAt + 1_000;81+});82+83+/**84+ * Hold an OS file lock until the server and its finalizers stop. This separate85+ * SQLite file never contains application data and must never be unlinked.86+ * SQLite releases the lock on process exit, including SIGKILL. No PID is killed87+ * and no heartbeat can expire while a live server is paused.88+ */89+export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(function* (90+ statePath: string,91+) {92+ const ownerId = NodeCrypto.randomUUID();93+ const resource = yield* Effect.acquireRelease(94+ Effect.tryPromise({95+ try: async () => {96+ const lock = await acquireServerOwnershipLock(NodePath.dirname(statePath));
- @@ -566,15 +550,6 @@566550 REMOTE_MANAGED=""567551 fi568552 elif [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then569- if [ "$RUNNER_CHANGED" -eq 1 ]; then570- kill "$REMOTE_PID" 2>/dev/null || true571- wait_for_pid_exit "$REMOTE_PID"572- REMOTE_PID=""573- REMOTE_PORT=""574- REMOTE_MANAGED=""575- elif ! wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then576- kill "$REMOTE_PID" 2>/dev/null || true577- wait_for_pid_exit "$REMOTE_PID"578- REMOTE_PID=""579- REMOTE_PORT=""580- REMOTE_MANAGED=""553+ if ! wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then554+ printf 'The saved SSH server is still running but is not ready. Finish active work and stop it through its original launcher before reconnecting.\\n' >&2555+ exit 1
- apps/server/src/serverOwnership.ts lines 57 to 76OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ const windows = platform === "win32";57+ const startedAt = yield* Effect.promise(58+ () =>59+ new Promise<number | undefined>((resolve) => {60+ NodeChildProcess.execFile(61+ windows ? "powershell.exe" : "ps",62+ windows63+ ? [64+ "-NoProfile",65+ "-NonInteractive",66+ "-Command",67+ `(Get-Process -Id ${state.pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,68+ ]69+ : ["-p", String(state.pid), "-o", "lstart="],70+ { env: { ...process.env, LC_ALL: "C", TZ: "UTC" }, timeout: 2_000, maxBuffer: 16_384 },71+ (error, stdout) => {72+ const time = Date.parse(windows ? stdout.trim() : `${stdout.trim()} UTC`);73+ resolve(error || !Number.isFinite(time) ? undefined : time);74+ },75+ );76+ }),
- @@ -627,8 +612,13 @@627612 export const REMOTE_STOP_SCRIPT = `set -eu628613 STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"629614 PID_FILE="$STATE_DIR/pid"615+STARTED_FILE="$STATE_DIR/started-at"630616 PORT_FILE="$STATE_DIR/port"631617 MANAGED_FILE="$STATE_DIR/managed"632618 REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"633619 REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"634-if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then620+REMOTE_STARTED_AT="$(cat "$STARTED_FILE" 2>/dev/null || true)"621+CURRENT_STARTED_AT=""622+case "$REMOTE_PID" in623+ ''|*[!0-9]*) ;;624+ *) CURRENT_STARTED_AT="$(LC_ALL=C ps -p "$REMOTE_PID" -o lstart= 2>/dev/null || true)" ;;
- @@ -600,12 +580,9 @@600- Effect.catchCause((cause) =>601- Effect.logWarning("Failed to persist server runtime state", { cause }),602- ),603- );604- }),605- () =>606- clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(607- Effect.catchCause((cause) =>608- Effect.logWarning("Failed to clear server runtime state", { cause }),609- ),610- ),611- ),580+ Effect.gen(function* () {581+ yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);582+ yield* awaitActivation;583+ const server = yield* HttpServer.HttpServer;584+ const address = server.address;585+ if (typeof address === "string" || !("port" in address)) return;586+ const state = yield* makePersistedServerRuntimeState({ config, port: address.port });587+ yield* ownership.publish(state);588+ }),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge added labelsmacroscope-review
juliusmarminge closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed