fix(server): enforce one database owner and guard update rollback #16102
Mergedmaria-rcksmerged 13 commits into
main fromrefs/pull/16102/headmerged by t3dotgg(GitHub profile, opens in a new tab) 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:XL
- @@ -828,3 +847,6 @@828847 yield* runSteps(manager.stop);829848 }830849850+ // Stopping the unit does not stop an unmanaged desktop, SSH, or CLI server.851+ // Updating only installed launcher files with start=false remains allowed.852+ if (!installed || start) yield* requireStopped;apps/server/src/serviceLauncher.ts line 511OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -422,5 +505,7 @@422505 const paths = runtimePaths(this.#baseDir, version);423506 const context: ServiceLauncherContext = {424507 protocol: SERVICE_LAUNCHER_PROTOCOL,508+ ownershipProtocol: 1,425509 childVersion: version,426510 ...(update === undefined ? {} : { update }),511+ ...(role === "trial" && this.#trialOwnership !== undefined@@ -0,0 +20,21 @@20+ let db: { exec: (sql: string) => unknown; close: () => void };21+ if (process.versions.bun) {22+ // Keep Bun's runtime-only module out of the Node build's module resolver.23+ const sqlite = (await import("bun:sqlite".toString())) as {24+ Database: new (filename: string) => typeof db;25+ };26+ db = new sqlite.Database(lockPath);27+ } else {28+ db = new (await import("node:sqlite")).DatabaseSync(lockPath);29+ }30+ try {31+ db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");32+ if (options?.cli) {33+ let contents: string | undefined;34+ const runtimeDir = NodePath.join(NodePath.dirname(stateDir), "runtime");35+ try {36+ contents = await NodeFSP.readFile(NodePath.join(runtimeDir, "service-state.json"), "utf8");37+ } catch (cause) {38+ if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause;39+ }40+ const state = contents === undefined ? undefined : parseServiceState(contents);@@ -317,0 +354,21 @@354+ await this.#suspendForOwnership();355+ } catch (cause) {356+ await this.#fatal(cause instanceof Error ? cause : new Error(String(cause)));357+ }358+ return;359+ }360+ await this.#fatal(error);361+ }362+363+ async #suspendForOwnership(): Promise<void> {364+ this.#clearTimer();365+ this.#cliLock?.close();366+ this.#cliLock = undefined;367+ const pending = this.#state.update;368+ if (pending?.status === "pending") {369+ // Another owner may have written since the backup. Cancel this trial370+ // without restoring it; an explicit restart must never replay that371+ // stale snapshot over the intervening owner's accepted writes.372+ const next: ServiceState = {373+ ...this.#state,374+ update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),@@ -301,3 +301,4 @@301301 ),302302 onShutdown: () => desktopWindow.handleBackendNotReady,303303 onPreflightFailed: handlePrimaryPreflightFailure,304+ onStateDirOwned: () =>
- apps/server/src/serviceLauncher.ts lines 463 to 463OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -382,3 +459,5 @@382459 const update = this.#state.update;383460 if (update?.status !== "pending") {384461 if (update !== undefined) {462+ const ownership = await acquireServerOwnershipLock(463+ NodePath.join(this.#baseDir, "userdata"),
- @@ -21,0 +148,21 @@148+ );149+ assert.equal(lock.readOwnerId(), "trial-owner");150+ }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))),151+ );152+ it("releases the OS ownership lock after its task-owned process crashes", async () => {153+ const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-owner-crash-"));154+ const moduleUrl = new URL("./serverOwnershipLock.ts", import.meta.url).href;155+ const encodedModuleUrl = JSON.stringify(moduleUrl);156+ const child = NodeChildProcess.spawn(157+ process.execPath,158+ [159+ "--input-type=module",160+ "--eval",161+ `const { acquireServerOwnershipLock } = await import(${encodedModuleUrl});162+const ownership = await acquireServerOwnershipLock(process.argv[1]);163+process.on('disconnect', () => ownership.close());164+process.send('owned');`,165+ root,166+ ],167+ { stdio: ["ignore", "ignore", "pipe", "ipc"] },168+ );
- apps/server/src/cli/project.ts line 425OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -421,13 +422,4 @@421422 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),422423 );423424424- return yield* Effect.gen(function* () {425- const snapshot = yield* getOfflineSnapshot();426- const projects = yield* ProjectService.ProjectService;427- const output = yield* run({428- snapshot,429- dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),430- mode: "offline",431- });432- yield* Console.log(output);433- }).pipe(Effect.provide(layerOfflineRuntime));425+ return yield* Effect.scoped(
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -604,0 +612,21 @@612+ /**613+ * Another server owns the T3 home. Exiting would make systemd or launchd614+ * start another refused server, so stay idle until stopped or restarted.615+ * A pending update fails without restoring its backup: the other owner may616+ * have written to the database since.617+ */618+ async #idleWhileStateDirOwned(): Promise<void> {619+ this.#clearTimer();620+ const pending = this.#state.update;621+ if (pending?.status === "pending") {622+ const next: ServiceState = {623+ ...this.#state,624+ activeVersion: pending.fromVersion,625+ update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),626+ };627+ await writeServiceState(this.#statePath, next);628+ this.#state = next;629+ await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);630+ }631+ // Signal listeners alone do not keep Node alive.632+ this.#timer = setInterval(() => {}, 2_147_483_647);
juliusmarminge added labelsmacroscope-review
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.



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