Open History to see the last commit
1import * as DateTime from "effect/DateTime";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6
7import { writeFileStringAtomically } from "./atomicWrite.ts";
8import type * as ServerConfig from "./config.ts";
9import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
10
11export const PersistedServerRuntimeState = Schema.Struct({
12 version: Schema.Literal(1),
13 pid: Schema.Int,
14 host: Schema.optional(Schema.String),
15 port: Schema.Int,
16 origin: Schema.String,
17 startedAt: Schema.String,
18});
19export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
20
21export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(
22 "ServerRuntimeStateError",
23 {
24 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
25 statePath: Schema.String,
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
31 }
32}
33
34const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
35 Schema.fromJsonString(PersistedServerRuntimeState),
36);
37
38const runtimeOriginForConfig = (
39 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
40 port: number,
41): PersistedServerRuntimeState["origin"] => {
42 const hostname =
43 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
44 return `http://${hostname}:${port}`;
45};
46
47export const makePersistedServerRuntimeState = (input: {
48 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host">;
49 readonly port: number;
50}): Effect.Effect<PersistedServerRuntimeState> =>
51 Effect.map(DateTime.now, (now) => ({
52 version: 1,
53 pid: process.pid,
54 ...(input.config.host ? { host: input.config.host } : {}),
55 port: input.port,
56 origin: runtimeOriginForConfig(input.config, input.port),
57 startedAt: DateTime.formatIso(now),
58 }));
59
60export const persistServerRuntimeState = (input: {
61 readonly path: string;
62 readonly state: PersistedServerRuntimeState;
63}) =>
64 writeFileStringAtomically({
65 filePath: input.path,
66 contents: `${JSON.stringify(input.state)}\n`,
67 }).pipe(
68 Effect.mapError(
69 (cause) =>
70 new ServerRuntimeStateError({
71 operation: "persist",
72 statePath: input.path,
73 cause,
74 }),
75 ),
76 );
77
78export const clearPersistedServerRuntimeState = (path: string) =>
79 Effect.gen(function* () {
80 const fs = yield* FileSystem.FileSystem;
81 yield* fs.remove(path, { force: true }).pipe(
82 Effect.mapError(
83 (cause) =>
84 new ServerRuntimeStateError({
85 operation: "clear",
86 statePath: path,
87 cause,
88 }),
89 ),
90 Effect.catchTags({
91 ServerRuntimeStateError: (error) =>
92 Effect.logWarning(error.message).pipe(
93 Effect.annotateLogs({
94 operation: error.operation,
95 statePath: error.statePath,
96 cause: error,
97 }),
98 ),
99 }),
100 );
101 });
102
103export class ServerStateDirConflictError extends Schema.TaggedErrorClass<ServerStateDirConflictError>()(
104 "ServerStateDirConflictError",
105 {
106 stateDir: Schema.String,
107 statePath: Schema.String,
108 pid: Schema.Int,
109 port: Schema.Int,
110 origin: Schema.String,
111 },
112) {
113 override get message(): string {
114 return (
115 `Another T3 server (pid ${this.pid}) already owns the state directory ${this.stateDir} ` +
116 `and is listening at ${this.origin} (port ${this.port}). ` +
117 `Refusing to start a second server against the same state directory, since two servers ` +
118 `sharing one state directory corrupt shared SQLite/discovery state. ` +
119 `Stop the other server, or start this one with a different --base-dir / T3CODE_HOME.`
120 );
121 }
122}
123
124/**
125 * Returns whether a pid refers to a live process. `process.kill(pid, 0)` does not
126 * send a signal; it only checks for the process' existence and our permission to
127 * signal it. EPERM means the process exists but is owned by another user, which we
128 * still treat as alive.
129 */
130export const isPidAlive = (pid: number): boolean => {
131 try {
132 process.kill(pid, 0);
133 return true;
134 } catch (error) {
135 return (error as NodeJS.ErrnoException).code === "EPERM";
136 }
137};
138
139export type ServerRuntimeStartupDecision =
140 | { readonly _tag: "proceed" }
141 | { readonly _tag: "conflict"; readonly state: PersistedServerRuntimeState };
142
143/**
144 * Pure decision for whether it is safe to start a server against a state directory
145 * given whatever discovery file it currently holds. Proceed when the file is absent,
146 * when it records our own pid (a same-process restart path must not self-block), or
147 * when the recorded pid is dead (stale file). Otherwise report a conflict.
148 */
149export const decideServerRuntimeStartup = (input: {
150 readonly existing: Option.Option<PersistedServerRuntimeState>;
151 readonly ownPid: number;
152 readonly isPidAlive: (pid: number) => boolean;
153}): ServerRuntimeStartupDecision => {
154 if (Option.isNone(input.existing)) {
155 return { _tag: "proceed" };
156 }
157 const state = input.existing.value;
158 if (state.pid === input.ownPid) {
159 return { _tag: "proceed" };
160 }
161 return input.isPidAlive(state.pid) ? { _tag: "conflict", state } : { _tag: "proceed" };
162};
163
164/**
165 * Best-effort single-instance guard on a state directory. Reads any existing
166 * discovery file and fails startup when a live process already owns it. This does
167 * NOT close the race between two servers that start simultaneously (both may read an
168 * empty/stale file before either writes) — it only rejects a startup when a
169 * previously-recorded, still-live server already owns the directory.
170 */
171export const ensureExclusiveStateDir = (input: {
172 readonly statePath: string;
173 readonly stateDir: string;
174 readonly ownPid?: number;
175 readonly isPidAlive?: (pid: number) => boolean;
176}) =>
177 Effect.gen(function* () {
178 const existing = yield* readPersistedServerRuntimeStateForStartup(input.statePath);
179 const decision = decideServerRuntimeStartup({
180 existing,
181 ownPid: input.ownPid ?? process.pid,
182 isPidAlive: input.isPidAlive ?? isPidAlive,
183 });
184 if (decision._tag === "conflict") {
185 return yield* new ServerStateDirConflictError({
186 stateDir: input.stateDir,
187 statePath: input.statePath,
188 pid: decision.state.pid,
189 port: decision.state.port,
190 origin: decision.state.origin,
191 });
192 }
193 });
194
195const logAndIgnoreRuntimeStateError = (error: ServerRuntimeStateError) =>
196 Effect.logWarning(error.message).pipe(
197 Effect.annotateLogs({
198 operation: error.operation,
199 statePath: error.statePath,
200 cause: error,
201 }),
202 Effect.as(Option.none<PersistedServerRuntimeState>()),
203 );
204
205const readPersistedServerRuntimeStateForStartup = (path: string) =>
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const raw = yield* fs.readFileString(path).pipe(
209 Effect.matchEffect({
210 onFailure: (cause) =>
211 cause.reason._tag === "NotFound"
212 ? Effect.succeed(Option.none<string>())
213 : Effect.fail(
214 new ServerRuntimeStateError({
215 operation: "read",
216 statePath: path,
217 cause,
218 }),
219 ),
220 onSuccess: (contents) => Effect.succeed(Option.some(contents)),
221 }),
222 );
223 if (Option.isNone(raw)) {
224 return Option.none<PersistedServerRuntimeState>();
225 }
226
227 const trimmed = raw.value.trim();
228 if (trimmed.length === 0) {
229 return Option.none<PersistedServerRuntimeState>();
230 }
231
232 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
233 Effect.map(Option.some),
234 Effect.mapError(
235 (cause) =>
236 new ServerRuntimeStateError({
237 operation: "decode",
238 statePath: path,
239 cause,
240 }),
241 ),
242 );
243 }).pipe(
244 Effect.catchTags({
245 ServerRuntimeStateError: (error) =>
246 error.operation === "decode" ? logAndIgnoreRuntimeStateError(error) : Effect.fail(error),
247 }),
248 );
249
250export const readPersistedServerRuntimeState = (path: string) =>
251 readPersistedServerRuntimeStateForStartup(path).pipe(
252 Effect.catchTags({
253 ServerRuntimeStateError: logAndIgnoreRuntimeStateError,
254 }),
255 );