Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverRuntimeState.ts

267 lines8.4 KB

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 PlatformError from "effect/PlatformError";
6import * as Random from "effect/Random";
7import * as Schema from "effect/Schema";
8​
9import { writeFileStringAtomically } from "./atomicWrite.ts";
10import type * as ServerConfig from "./config.ts";
11import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
12​
13export const PersistedServerRuntimeState = Schema.Struct({
14 version: Schema.Literal(1),
15 pid: Schema.Int,
16 host: Schema.optional(Schema.String),
17 port: Schema.Int,
18 origin: Schema.String,
19 // Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).
20 // Dev is single-origin: browsers must pair through this URL, not `origin`.
21 devUrl: Schema.optional(Schema.String),
22 startedAt: Schema.String,
23});
24export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
25​
26export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(
27 "ServerRuntimeStateError",
28 {
29 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
30 statePath: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
36 }
38​
39const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
40 Schema.fromJsonString(PersistedServerRuntimeState),
41);
42​
43const runtimeOriginForConfig = (
44 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
45 port: number,
46): PersistedServerRuntimeState["origin"] => {
47 const hostname =
48 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
49 return `http://${hostname}:${port}`;
50};
51​
52export const makePersistedServerRuntimeState = (input: {
53 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
54 readonly port: number;
55}): Effect.Effect<PersistedServerRuntimeState> =>
56 Effect.map(DateTime.now, (now) => ({
57 version: 1,
58 pid: process.pid,
59 ...(input.config.host ? { host: input.config.host } : {}),
60 port: input.port,
61 origin: runtimeOriginForConfig(input.config, input.port),
62 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
63 startedAt: DateTime.formatIso(now),
64 }));
65​
66export const persistServerRuntimeState = (input: {
67 readonly path: string;
68 readonly state: PersistedServerRuntimeState;
69}) =>
70 writeFileStringAtomically({
71 filePath: input.path,
72 contents: `${JSON.stringify(input.state)}\n`,
73 }).pipe(
74 Effect.mapError(
75 (cause) =>
76 new ServerRuntimeStateError({
77 operation: "persist",
78 statePath: input.path,
79 cause,
80 }),
81 ),
82 );
83​
84export const clearPersistedServerRuntimeState = (path: string) =>
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 yield* fs.remove(path, { force: true }).pipe(
88 Effect.mapError(
89 (cause) =>
90 new ServerRuntimeStateError({
91 operation: "clear",
92 statePath: path,
93 cause,
94 }),
95 ),
96 Effect.catchTags({
97 ServerRuntimeStateError: (error) =>
98 Effect.logWarning(error.message).pipe(
99 Effect.annotateLogs({
100 operation: error.operation,
101 statePath: error.statePath,
102 cause: error,
103 }),
104 ),
105 }),
106 );
107 });
108​
109export const readPersistedServerRuntimeState = (path: string) =>
110 Effect.gen(function* () {
111 const fs = yield* FileSystem.FileSystem;
112 const raw = yield* fs.readFileString(path).pipe(
113 Effect.matchEffect({
114 onFailure: (cause) =>
115 cause.reason._tag === "NotFound"
116 ? Effect.succeed(Option.none<string>())
117 : Effect.fail(
118 new ServerRuntimeStateError({
119 operation: "read",
120 statePath: path,
121 cause,
122 }),
123 ),
124 onSuccess: (contents) => Effect.succeed(Option.some(contents)),
125 }),
126 );
127 if (Option.isNone(raw)) {
128 return Option.none<PersistedServerRuntimeState>();
129 }
130​
131 const trimmed = raw.value.trim();
132 if (trimmed.length === 0) {
133 return Option.none<PersistedServerRuntimeState>();
134 }
135​
136 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
137 Effect.map(Option.some),
138 Effect.mapError(
139 (cause) =>
140 new ServerRuntimeStateError({
141 operation: "decode",
142 statePath: path,
143 cause,
144 }),
145 ),
146 );
147 }).pipe(
148 Effect.catchTags({
149 ServerRuntimeStateError: (error) =>
150 Effect.logWarning(error.message).pipe(
151 Effect.annotateLogs({
152 operation: error.operation,
153 statePath: error.statePath,
154 cause: error,
155 }),
156 Effect.as(Option.none<PersistedServerRuntimeState>()),
157 ),
158 }),
159 );
160​
161export const clearPersistedServerRuntimeStateIfOwned = (input: {
162 readonly path: string;
163 readonly state: Pick<PersistedServerRuntimeState, "pid" | "startedAt">;
164}): Effect.Effect<void, never, FileSystem.FileSystem> =>
165 Effect.gen(function* () {
166 const fs = yield* FileSystem.FileSystem;
167 const nonce = yield* Random.nextInt;
168 const capturedPath = `${input.path}.clearing-${process.pid}-${nonce.toString(36)}`;
169 const captured = yield* fs.rename(input.path, capturedPath).pipe(
170 Effect.as(true),
171 Effect.catchTags({
172 PlatformError: (cause) =>
173 cause.reason._tag === "NotFound"
174 ? Effect.succeed(false)
175 : Effect.fail(
176 new ServerRuntimeStateError({
177 operation: "clear",
178 statePath: input.path,
179 cause,
180 }),
181 ),
182 }),
183 );
184 if (!captured) {
185 return;
186 }
187​
188 const current = yield* readPersistedServerRuntimeState(capturedPath);
189 const ownsCapturedState =
190 Option.isSome(current) &&
191 current.value.pid === input.state.pid &&
192 current.value.startedAt === input.state.startedAt;
193​
194 if (!ownsCapturedState) {
195 const restoreCapturedState = (
196 linkCause: PlatformError.PlatformError,
197 ): Effect.Effect<void, ServerRuntimeStateError> =>
198 fs.readFileString(capturedPath).pipe(
199 Effect.mapError(
200 (restoreCause) =>
201 new ServerRuntimeStateError({
202 operation: "clear",
203 statePath: input.path,
204 cause: { linkCause, restoreCause },
205 }),
206 ),
207 Effect.flatMap((contents) =>
208 fs
209 .writeFileString(input.path, contents, {
210 flag: "wx",
211 mode: 0o600,
212 })
213 .pipe(
214 Effect.catchTags({
215 PlatformError: (restoreCause) =>
216 restoreCause.reason._tag === "AlreadyExists"
217 ? Effect.void
218 : Effect.fail(
219 new ServerRuntimeStateError({
220 operation: "clear",
221 statePath: input.path,
222 cause: { linkCause, restoreCause },
223 }),
224 ),
225 }),
226 ),
227 ),
228 );
229​
230 yield* fs.link(capturedPath, input.path).pipe(
231 Effect.catchTags({
232 PlatformError: (linkCause) => {
233 if (linkCause.reason._tag === "AlreadyExists") {
234 return Effect.void;
235 }
236 // Some filesystems do not support hard links. Preserve the same
237 // no-clobber contract with an exclusive create so a concurrent
238 // replacement writer always wins. The captured file stays in
239 // place unless this durable fallback completes.
240 return restoreCapturedState(linkCause);
241 },
242 }),
243 );
244 }
245​
246 yield* fs.remove(capturedPath, { force: true }).pipe(
247 Effect.mapError(
248 (cause) =>
249 new ServerRuntimeStateError({
250 operation: "clear",
251 statePath: input.path,
252 cause,
253 }),
254 ),
255 );
256 }).pipe(
257 Effect.catchTags({
258 ServerRuntimeStateError: (error) =>
259 Effect.logWarning(error.message).pipe(
260 Effect.annotateLogs({
261 operation: error.operation,
262 statePath: error.statePath,
263 cause: error,
264 }),
265 ),
266 }),
267 );