Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Publication must finish synchronously while the scope holds ownership.
2// @effect-diagnostics schemaSyncInEffect:off - Descriptor validation and publication are synchronous under the ownership lock.
3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as NodeFS from "node:fs";
5import * as NodePath from "node:path";
6import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
7import * as Crypto from "effect/Crypto";
8import * as Effect from "effect/Effect";
9import * as Duration from "effect/Duration";
10import * as Option from "effect/Option";
11import * as Runtime from "effect/Runtime";
12import * as Schema from "effect/Schema";
13
14import * as ProcessRunner from "./processRunner.ts";
15import { acquireServerOwnershipLock } from "./serverOwnershipLock.ts";
16
17import {
18 isProcessAlive,
19 readPersistedServerRuntimeState,
20 PersistedServerRuntimeState,
21} from "./serverRuntimeState.ts";
22
23export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyRunningError>()(
24 "ServerAlreadyRunningError",
25 { stateDir: Schema.String },
26) {
27 // Distinct process exit code so a supervisor can tell "owned by another
28 // server" apart from a crash and stop restarting.
29 override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
30
31 override get message(): string {
32 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 retry this command with the same home directory. No server was stopped.`;
33 }
34}
35
36export class ServerOwnershipError extends Schema.TaggedError<ServerOwnershipError>()(
37 "ServerOwnershipError",
38 { statePath: Schema.String, cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return `Could not acquire or update server ownership at ${this.statePath}.`;
42 }
43}
44
45export class ServerOwnershipReleasedError extends Schema.TaggedError<ServerOwnershipReleasedError>()(
46 "ServerOwnershipReleasedError",
47 { statePath: Schema.String },
48) {
49 override get message(): string {
50 return `Cannot publish server runtime state after ownership was released at ${this.statePath}.`;
51 }
52}
53
54const encodeRuntimeState = Schema.encodeSync(Schema.fromJsonString(PersistedServerRuntimeState));
55const decodeRuntimeState = Schema.decodeUnknownSync(
56 Schema.fromJsonString(PersistedServerRuntimeState),
57);
58
59/** Treat a legacy record as stale only when process start time proves PID reuse. */
60const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* (
61 state: PersistedServerRuntimeState,
62) {
63 if (!isProcessAlive(state.pid)) return false;
64 const recordedAt = Date.parse(state.startedAt);
65 if (!Number.isFinite(recordedAt)) return true;
66 const platform = yield* HostProcessPlatform;
67 const windows = platform === "win32";
68 const runner = yield* ProcessRunner.ProcessRunner;
69 const result = yield* runner
70 .run({
71 command: windows ? "powershell.exe" : "ps",
72 args: windows
73 ? [
74 "-NoProfile",
75 "-NonInteractive",
76 "-Command",
77 `(Get-Process -Id ${state.pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
78 ]
79 : ["-p", String(state.pid), "-o", "lstart="],
80 env: { LC_ALL: "C", TZ: "UTC" },
81 timeout: Duration.seconds(2),
82 maxOutputBytes: 16_384,
83 })
84 .pipe(Effect.option);
85 if (Option.isNone(result) || result.value.code !== 0) return true;
86 const output = result.value.stdout.trim();
87 const startedAt = Date.parse(windows ? output : `${output} UTC`);
88 // ps reports whole seconds. Unknown identity stays conservative, and no
89 // process is ever signalled based on this comparison.
90 return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000;
91});
92
93/**
94 * Hold an OS file lock until the server and its finalizers stop. This separate
95 * SQLite file never contains application data and must never be unlinked.
96 * SQLite releases the lock on process exit, including SIGKILL. No PID is killed
97 * and no heartbeat can expire while a live server is paused.
98 */
99export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(function* (
100 statePath: string,
101) {
102 const crypto = yield* Crypto.Crypto;
103 const ownerId = yield* crypto.randomUUIDv4.pipe(
104 Effect.mapError((cause) => new ServerOwnershipError({ statePath, cause })),
105 );
106 const resource = yield* Effect.acquireRelease(
107 Effect.tryPromise({
108 try: async () => {
109 const lock = await acquireServerOwnershipLock(NodePath.dirname(statePath));
110 return {
111 lock,
112 path: NodePath.join(lock.stateDir, NodePath.basename(statePath)),
113 active: true,
114 };
115 },
116 catch: (cause) =>
117 cause instanceof Error &&
118 (("errcode" in cause && cause.errcode === 5) ||
119 ("code" in cause && cause.code === "SQLITE_BUSY"))
120 ? new ServerAlreadyRunningError({ stateDir: NodePath.dirname(statePath) })
121 : new ServerOwnershipError({ statePath, cause }),
122 }),
123 (resource) =>
124 Effect.gen(function* () {
125 resource.active = false;
126 const state = yield* readPersistedServerRuntimeState(resource.path);
127 yield* Effect.try({
128 try: () => {
129 if (Option.isSome(state) && state.value.ownerId === ownerId) {
130 NodeFS.rmSync(resource.path, { force: true });
131 }
132 },
133 catch: (cause) => new ServerOwnershipError({ statePath, cause }),
134 }).pipe(Effect.ignore({ log: true }));
135 }).pipe(
136 Effect.ensuring(
137 Effect.sync(() => {
138 resource.active = false;
139 resource.lock.close();
140 }),
141 ),
142 ),
143 );
144
145 // Older releases have no lock. Do not replace their record while their PID
146 // still identifies that process. New records with a free lock belong to a
147 // crashed or stopped owner.
148 const previous = yield* Effect.try({
149 try: () => {
150 try {
151 const contents = NodeFS.readFileSync(resource.path, "utf8");
152 return Option.some(decodeRuntimeState(contents));
153 } catch (cause) {
154 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
155 return Option.none<PersistedServerRuntimeState>();
156 }
157 throw cause;
158 }
159 },
160 catch: (cause) => new ServerOwnershipError({ statePath, cause }),
161 });
162 if (
163 Option.isSome(previous) &&
164 previous.value.ownerId === undefined &&
165 (yield* legacyOwnerIsLive(previous.value))
166 ) {
167 return yield* new ServerAlreadyRunningError({ stateDir: resource.lock.stateDir });
168 }
169
170 return {
171 publish: (state: PersistedServerRuntimeState) =>
172 Effect.suspend<void, ServerOwnershipError | ServerOwnershipReleasedError, never>(() => {
173 if (!resource.active) return Effect.fail(new ServerOwnershipReleasedError({ statePath }));
174 return Effect.try({
175 try: () => {
176 const temporaryPath = `${resource.path}.${ownerId}.tmp`;
177 try {
178 NodeFS.writeFileSync(
179 temporaryPath,
180 `${encodeRuntimeState({ ...state, ownerId })}\n`,
181 {
182 mode: 0o600,
183 },
184 );
185 NodeFS.renameSync(temporaryPath, resource.path);
186 } finally {
187 NodeFS.rmSync(temporaryPath, { force: true });
188 }
189 },
190 catch: (cause) => new ServerOwnershipError({ statePath, cause }),
191 });
192 }),
193 };
194});
195
196/** Check before service setup. The server still acquires its own lifetime lock. */
197export const requireServerStopped = (statePath: string) =>
198 Effect.scoped(acquireServerOwnership(statePath)).pipe(Effect.asVoid);