Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - The ownership lock is a native SQLite handle held for the server's lifetime.
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as NodeSqlite from "node:sqlite";
5
6import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Crypto from "effect/Crypto";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Runtime from "effect/Runtime";
14import * as Schema from "effect/Schema";
15
16import {
17 BOOT_SERVICE_LAUNCHD_LABEL,
18 BOOT_SERVICE_PLIST_FILE,
19 BOOT_SERVICE_UNIT_FILE,
20 bootServiceBaseDirOf,
21} from "./cloud/bootService.ts";
22import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
23import {
24 SERVICE_LAUNCHER_CONTEXT_ENV,
25 SERVICE_RESTART_PENDING_FILE,
26 SERVICE_STATE_FILE,
27 compareExactServiceVersions,
28 serviceStateActiveVersion,
29} from "./cloud/serviceProtocol.ts";
30import * as ProcessRunner from "./processRunner.ts";
31import {
32 clearPersistedServerRuntimeState,
33 isProcessAlive,
34 persistServerRuntimeState,
35 readPersistedServerRuntimeState,
36 type PersistedServerRuntimeState,
37} from "./serverRuntimeState.ts";
38
39export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyRunningError>()(
40 "ServerAlreadyRunningError",
41 { stateDir: Schema.String },
42) {
43 // Distinct process exit code so a supervisor can tell "owned by another
44 // server" apart from a crash and stop restarting.
45 override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
46
47 override get message(): string {
48 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.`;
49 }
50}
51
52export class OlderBootServiceError extends Schema.TaggedError<OlderBootServiceError>()(
53 "OlderBootServiceError",
54 { baseDir: Schema.String },
55) {
56 override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
57
58 override get message(): string {
59 return `A T3 Code background service set up for ${this.baseDir} may still run a release without the ownership lock. On that machine, try \`t3 update\` and let it restart (or run \`t3 service restart\` if the update is already installed). If the older launcher cannot update, run \`t3 service uninstall\`, then reinstall with \`t3 service install\` from a current CLI. You can also leave the service uninstalled. Pass \`--base-dir ${this.baseDir}\` to each command, and use \`npx t3@latest\` if \`t3\` is not installed or is outdated. Then retry. No server was stopped.`;
60 }
61}
62
63export class ServerOwnershipError extends Schema.TaggedError<ServerOwnershipError>()(
64 "ServerOwnershipError",
65 { stateDir: Schema.String, cause: Schema.Defect() },
66) {
67 override get message(): string {
68 return `Could not acquire server ownership of ${this.stateDir}.`;
69 }
70}
71
72const isSqliteBusy = (cause: unknown) =>
73 cause instanceof Error &&
74 (("errcode" in cause && cause.errcode === 5) ||
75 ("code" in cause && cause.code === "SQLITE_BUSY"));
76
77/**
78 * Servers from before this lock only publish `server-runtime.json`. Treat
79 * their record as stale only when the process start time proves PID reuse.
80 */
81const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* (
82 state: PersistedServerRuntimeState,
83) {
84 if (!isProcessAlive(state.pid)) return false;
85 const recordedAt = Date.parse(state.startedAt);
86 if (!Number.isFinite(recordedAt)) return true;
87 const windows = (yield* HostProcess.Platform) === "win32";
88 const runner = yield* ProcessRunner.ProcessRunner;
89 const result = yield* runner
90 .run({
91 command: windows ? "powershell.exe" : "ps",
92 args: windows
93 ? [
94 "-NoProfile",
95 "-NonInteractive",
96 "-Command",
97 `(Get-Process -Id ${state.pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
98 ]
99 : ["-p", String(state.pid), "-o", "lstart="],
100 env: { LC_ALL: "C", TZ: "UTC" },
101 timeout: Duration.seconds(2),
102 maxOutputBytes: 16_384,
103 })
104 .pipe(Effect.option);
105 if (Option.isNone(result) || result.value.code !== 0) return true;
106 const output = result.value.stdout.trim();
107 const startedAt = Date.parse(windows ? output : `${output} UTC`);
108 // ps reports whole seconds. Unknown identity stays conservative.
109 return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000;
110});
111
112// Pre-lock services become invisible when another server replaces their runtime
113// record. Unreadable configuration or an unavailable manager allows startup.
114const olderBootServiceHome = Effect.fn("olderBootServiceHome")(
115 function* (stateDir: string) {
116 if (
117 (yield* ServiceLauncherHostProcess).connected &&
118 (yield* HostProcess.Environment)[SERVICE_LAUNCHER_CONTEXT_ENV] !== undefined
119 ) {
120 return undefined;
121 }
122 const platform = yield* HostProcess.Platform;
123 const uid = yield* HostProcess.UserId;
124 if (platform !== "linux" && (platform !== "darwin" || uid === undefined)) return undefined;
125
126 const homeDir = yield* HostProcess.HomeDirectory;
127 const fs = yield* FileSystem.FileSystem;
128 const runner = yield* ProcessRunner.ProcessRunner;
129 const unitPath =
130 platform === "darwin"
131 ? NodePath.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE)
132 : NodePath.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
133 const baseDir = bootServiceBaseDirOf(yield* fs.readFileString(unitPath));
134 if (
135 baseDir === undefined ||
136 (yield* fs.realPath(NodePath.join(baseDir, "userdata"))) !== (yield* fs.realPath(stateDir))
137 ) {
138 return undefined;
139 }
140 const runtimeDir = NodePath.join(baseDir, "runtime");
141 const version = serviceStateActiveVersion(
142 yield* fs.readFileString(NodePath.join(runtimeDir, SERVICE_STATE_FILE)),
143 );
144 if (version === undefined) return undefined;
145 const run = (command: string, args: ReadonlyArray<string>) =>
146 runner.run({ command, args, timeout: Duration.seconds(5), maxOutputBytes: 65_536 });
147 let loaded: boolean;
148 if (platform === "darwin") {
149 loaded =
150 (yield* run("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`])).code === 0;
151 if (!loaded) {
152 const disabled = yield* run("launchctl", ["print-disabled", `gui/${uid}`]);
153 // Older macOS versions print `true` instead of `disabled`.
154 if (
155 disabled.code !== 0 ||
156 disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) ||
157 disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`)
158 )
159 return undefined;
160 }
161 } else {
162 const active = yield* run("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]);
163 // A unit waiting out its Restart= delay is activating, with exit code 3.
164 loaded = active.code === 0 || (active.code === 3 && active.stdout.trim() === "activating");
165 if (!loaded) {
166 const enabled = yield* run("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]);
167 if (enabled.code !== 0 || enabled.stdout.trim() !== "enabled") return undefined;
168 }
169 }
170 // A deferred update names the staged runtime, not the loaded service's runtime.
171 if (loaded && (yield* fs.exists(NodePath.join(runtimeDir, SERVICE_RESTART_PENDING_FILE)))) {
172 return baseDir;
173 }
174 // Stable 0.1.0 shipped the ownership lock. Earlier lock-aware prereleases
175 // are conservatively refused because older runtimes expose no capability marker.
176 return compareExactServiceVersions(version, "0.1.0") < 0 ? baseDir : undefined;
177 },
178 Effect.orElseSucceed(() => undefined),
179);
180
181/**
182 * Hold an exclusive lock on the state directory until the scope closes. The
183 * lock is an exclusive transaction on `server-owner.sqlite`, which never holds
184 * data and must never be unlinked: the OS releases it when the process exits,
185 * even on SIGKILL, so a crashed owner never blocks the next start.
186 */
187export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(function* (
188 statePath: string,
189) {
190 const stateDir = NodePath.dirname(statePath);
191 const crypto = yield* Crypto.Crypto;
192 const ownerId = yield* crypto
193 .randomUUIDv4()
194 .pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause })));
195 yield* Effect.acquireRelease(
196 Effect.try({
197 try: () => {
198 NodeFS.mkdirSync(stateDir, { recursive: true });
199 const db = new NodeSqlite.DatabaseSync(NodePath.join(stateDir, "server-owner.sqlite"));
200 try {
201 db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
202 } catch (cause) {
203 db.close();
204 throw cause;
205 }
206 return db;
207 },
208 catch: (cause) =>
209 isSqliteBusy(cause)
210 ? new ServerAlreadyRunningError({ stateDir })
211 : new ServerOwnershipError({ stateDir, cause }),
212 }),
213 (db) =>
214 readPersistedServerRuntimeState(statePath).pipe(
215 Effect.flatMap((state) =>
216 Option.isSome(state) && state.value.ownerId === ownerId
217 ? clearPersistedServerRuntimeState(statePath)
218 : Effect.void,
219 ),
220 Effect.ignore({ log: true }),
221 Effect.ensuring(Effect.sync(() => db.close())),
222 ),
223 );
224
225 const previous = yield* readPersistedServerRuntimeState(statePath).pipe(
226 Effect.orElseSucceed(() => Option.none<PersistedServerRuntimeState>()),
227 );
228 if (
229 Option.isSome(previous) &&
230 previous.value.ownerId === undefined &&
231 (yield* legacyOwnerIsLive(previous.value))
232 ) {
233 return yield* new ServerAlreadyRunningError({ stateDir });
234 }
235 const olderServiceHome = yield* olderBootServiceHome(stateDir);
236 if (olderServiceHome !== undefined) {
237 return yield* new OlderBootServiceError({ baseDir: olderServiceHome });
238 }
239
240 return {
241 publish: (state: PersistedServerRuntimeState) =>
242 persistServerRuntimeState({ path: statePath, state: { ...state, ownerId } }),
243 };
244});