Skip to content
TypeScript

fix(server): report a deleted or replaced ownership lock (#21886)

Scott Norteman5b4f2aa15327
diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts
index 19597354255..6d89f45cb79 100644
--- a/apps/server/src/serverOwnership.ts
+++ b/apps/server/src/serverOwnership.ts
@@ -44,7 +44,7 @@ export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyR
override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
override get message(): string {
- return `A T3 Code server already owns ${this.stateDir}. Stop that server, or use a separate T3 home and pair with it, then retry. No server was stopped.`;
+ return `A T3 Code server already owns ${this.stateDir}. Stop that server, or use a separate T3 home and pair with it, then retry. No server was stopped. server-owner.sqlite is the ownership lock; do not delete it while a server is running.`;
}
}
@@ -188,25 +188,36 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
const ownerId = yield* crypto
.randomUUIDv4()
.pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause })));
- yield* Effect.acquireRelease(
+ const lockPath = NodePath.join(stateDir, "server-owner.sqlite");
+ const lock = yield* Effect.acquireRelease(
Effect.try({
try: () => {
NodeFS.mkdirSync(stateDir, { recursive: true });
- const db = new NodeSqlite.DatabaseSync(NodePath.join(stateDir, "server-owner.sqlite"));
+ let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
+ if (before === undefined) {
+ NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644));
+ before = NodeFS.statSync(lockPath, { bigint: true });
+ }
+ const db = new NodeSqlite.DatabaseSync(lockPath);
try {
db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
+ const identity = NodeFS.statSync(lockPath, { bigint: true });
+ return {
+ db,
+ identity,
+ replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino,
+ };
} catch (cause) {
db.close();
throw cause;
}
- return db;
},
catch: (cause) =>
isSqliteBusy(cause)
? new ServerAlreadyRunningError({ stateDir })
: new ServerOwnershipError({ stateDir, cause }),
}),
- (db) =>
+ ({ db }) =>
readPersistedServerRuntimeState(statePath).pipe(
Effect.flatMap((state) =>
Option.isSome(state) && state.value.ownerId === ownerId
@@ -233,6 +244,39 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
return yield* new OlderBootServiceError({ baseDir: olderServiceHome });
}
+ yield* Effect.gen(function* () {
+ let lost = lock.replacedDuringAcquire;
+ let statWarningLogged = false;
+ while (!lost) {
+ yield* Effect.sleep("5 seconds");
+ // Closing another descriptor for this inode releases SQLite's POSIX locks. Stat by path only.
+ const current = yield* Effect.sync(() => {
+ try {
+ return NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
+ } catch (cause) {
+ return cause instanceof Error && "code" in cause ? String(cause.code) : "unknown";
+ }
+ });
+ if (typeof current === "string") {
+ if (!statWarningLogged) {
+ yield* Effect.logWarning(
+ `Cannot check server ownership lock at ${lockPath} (${current}).`,
+ );
+ statWarningLogged = true;
+ }
+ continue;
+ }
+ statWarningLogged = false;
+ lost =
+ current === undefined ||
+ current.dev !== lock.identity.dev ||
+ current.ino !== lock.identity.ino;
+ }
+ yield* Effect.logError(
+ `Server ownership lock at ${lockPath} was deleted or replaced. Another server may now share this T3 home. Stop any other server using this home, then restart this server. Do not delete server-owner.sqlite while a server is running.`,
+ );
+ }).pipe(Effect.forkScoped);
+
return {
publish: (state: PersistedServerRuntimeState) =>
persistServerRuntimeState({ path: statePath, state: { ...state, ownerId } }),
diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts
index abafbc7e24f..b75ab72594a 100644
--- a/apps/server/src/serverRuntimeState.test.ts
+++ b/apps/server/src/serverRuntimeState.test.ts
@@ -1,13 +1,20 @@
+// @effect-diagnostics nodeBuiltinImport:off - Injects a real file replacement during the native SQLite transaction.
+import * as NodeFS from "node:fs";
+import * as NodeSqlite from "node:sqlite";
+
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
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 Runtime from "effect/Runtime";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import * as TestClock from "effect/testing/TestClock";
+import { vi } from "vite-plus/test";
import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
@@ -179,6 +186,7 @@ describe("server ownership", () => {
Effect.flip,
);
assert.equal(refused._tag, "ServerAlreadyRunningError");
+ assert.include(refused.message, "do not delete it while a server is running");
assert.equal(yield* fs.readFileString(statePath), before);
}),
);
@@ -187,6 +195,89 @@ describe("server ownership", () => {
}).pipe(Effect.provide(layerOwnership)),
);
+ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("lock file checks", () => {
+ it.effect.each([
+ "unchanged",
+ "unlink",
+ "replace",
+ "during acquisition",
+ "first acquisition",
+ // Root bypasses directory permissions, so chmod cannot force EACCES.
+ ...(process.getuid?.() === 0 ? [] : (["stat error"] as const)),
+ ] as const)("monitors ownership after %s", (operation) => {
+ const messages: unknown[] = [];
+ const warnings: unknown[] = [];
+ const logger = Logger.make(({ message, logLevel }) =>
+ (logLevel === "Warn" ? warnings : messages).push(message),
+ );
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-lost-" });
+ const statePath = path.join(root, "server-runtime.json");
+ const lockPath = path.join(root, "server-owner.sqlite");
+ const replacement = path.join(root, "replacement.sqlite");
+ if (operation === "during acquisition" || operation === "first acquisition") {
+ if (operation === "during acquisition") yield* fs.writeFileString(lockPath, "");
+ yield* fs.writeFileString(replacement, "");
+ const exec = NodeSqlite.DatabaseSync.prototype.exec;
+ yield* Effect.acquireRelease(
+ Effect.sync(() =>
+ vi.spyOn(NodeSqlite.DatabaseSync.prototype, "exec").mockImplementationOnce(function (
+ this: NodeSqlite.DatabaseSync,
+ sql: string,
+ ) {
+ exec.call(this, sql);
+ NodeFS.renameSync(replacement, lockPath);
+ }),
+ ),
+ (spy) => Effect.sync(() => spy.mockRestore()),
+ );
+ }
+ yield* ServerOwnership.acquireServerOwnership(statePath);
+ if (operation === "unlink") {
+ yield* fs.remove(lockPath);
+ } else if (operation === "replace") {
+ yield* fs.writeFileString(replacement, "");
+ yield* fs.rename(replacement, lockPath);
+ }
+ if (operation === "stat error") {
+ yield* fs.chmod(root, 0);
+ yield* TestClock.adjust("15 seconds").pipe(
+ Effect.ensuring(fs.chmod(root, 0o700).pipe(Effect.orDie)),
+ );
+ assert.deepEqual(warnings, [
+ [`Cannot check server ownership lock at ${lockPath} (EACCES).`],
+ ]);
+ yield* TestClock.adjust("5 seconds");
+ assert.deepEqual(messages, []);
+ yield* fs.remove(lockPath);
+ }
+ yield* TestClock.adjust("5 seconds");
+ const expected =
+ operation === "unchanged"
+ ? []
+ : [
+ [
+ `Server ownership lock at ${lockPath} was deleted or replaced. Another server may now share this T3 home. Stop any other server using this home, then restart this server. Do not delete server-owner.sqlite while a server is running.`,
+ ],
+ ];
+ assert.deepEqual(messages, expected);
+ if (operation !== "unchanged") {
+ yield* fs.remove(`${lockPath}-journal`, { force: true });
+ yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
+ }
+ yield* TestClock.adjust("15 seconds");
+ assert.deepEqual(messages, expected);
+ assert.lengthOf(warnings, operation === "stat error" ? 1 : 0);
+ }).pipe(
+ Effect.provide(
+ Layer.merge(layerOwnership, Logger.layer([logger], { mergeWithExisting: false })),
+ ),
+ );
+ });
+ });
+
it.effect("refuses beside a live pre-lock server and ignores a stale record", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;