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 // Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).
18 // Dev is single-origin: browsers must pair through this URL, not `origin`.
19 devUrl: Schema.optional(Schema.String),
20 startedAt: Schema.String,
21});
22export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
23
24export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(
25 "ServerRuntimeStateError",
26 {
27 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
28 statePath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
34 }
35}
36
37const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
38 Schema.fromJsonString(PersistedServerRuntimeState),
39);
40
41const runtimeOriginForConfig = (
42 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
43 port: number,
44): PersistedServerRuntimeState["origin"] => {
45 const hostname =
46 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
47 return `http://${hostname}:${port}`;
48};
49
50export const makePersistedServerRuntimeState = (input: {
51 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
52 readonly port: number;
53}): Effect.Effect<PersistedServerRuntimeState> =>
54 Effect.map(DateTime.now, (now) => ({
55 version: 1,
56 pid: process.pid,
57 ...(input.config.host ? { host: input.config.host } : {}),
58 port: input.port,
59 origin: runtimeOriginForConfig(input.config, input.port),
60 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
61 startedAt: DateTime.formatIso(now),
62 }));
63
64export const persistServerRuntimeState = (input: {
65 readonly path: string;
66 readonly state: PersistedServerRuntimeState;
67}) =>
68 writeFileStringAtomically({
69 filePath: input.path,
70 contents: `${JSON.stringify(input.state)}\n`,
71 }).pipe(
72 Effect.mapError(
73 (cause) =>
74 new ServerRuntimeStateError({
75 operation: "persist",
76 statePath: input.path,
77 cause,
78 }),
79 ),
80 );
81
82export const clearPersistedServerRuntimeState = (path: string) =>
83 Effect.gen(function* () {
84 const fs = yield* FileSystem.FileSystem;
85 yield* fs.remove(path, { force: true }).pipe(
86 Effect.mapError(
87 (cause) =>
88 new ServerRuntimeStateError({
89 operation: "clear",
90 statePath: path,
91 cause,
92 }),
93 ),
94 Effect.catchTags({
95 ServerRuntimeStateError: (error) =>
96 Effect.logWarning(error.message).pipe(
97 Effect.annotateLogs({
98 operation: error.operation,
99 statePath: error.statePath,
100 cause: error,
101 }),
102 ),
103 }),
104 );
105 });
106
107/**
108 * Report whether the pid recorded in a persisted runtime state is still
109 * running. Signal 0 delivers nothing; it only reports whether the pid exists.
110 * EPERM means it exists but belongs to another user, which still counts as
111 * alive.
112 */
113export const isProcessAlive = (pid: number): boolean => {
114 try {
115 process.kill(pid, 0);
116 return true;
117 } catch (error) {
118 return error instanceof Error && "code" in error && error.code === "EPERM";
119 }
120};
121
122export const readPersistedServerRuntimeState = (path: string) =>
123 Effect.gen(function* () {
124 const fs = yield* FileSystem.FileSystem;
125 const raw = yield* fs.readFileString(path).pipe(
126 Effect.matchEffect({
127 onFailure: (cause) =>
128 cause.reason._tag === "NotFound"
129 ? Effect.succeed(Option.none<string>())
130 : Effect.fail(
131 new ServerRuntimeStateError({
132 operation: "read",
133 statePath: path,
134 cause,
135 }),
136 ),
137 onSuccess: (contents) => Effect.succeed(Option.some(contents)),
138 }),
139 );
140 if (Option.isNone(raw)) {
141 return Option.none<PersistedServerRuntimeState>();
142 }
143
144 const trimmed = raw.value.trim();
145 if (trimmed.length === 0) {
146 return Option.none<PersistedServerRuntimeState>();
147 }
148
149 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
150 Effect.map(Option.some),
151 Effect.mapError(
152 (cause) =>
153 new ServerRuntimeStateError({
154 operation: "decode",
155 statePath: path,
156 cause,
157 }),
158 ),
159 );
160 }).pipe(
161 Effect.catchTags({
162 ServerRuntimeStateError: (error) =>
163 Effect.logWarning(error.message).pipe(
164 Effect.annotateLogs({
165 operation: error.operation,
166 statePath: error.statePath,
167 cause: error,
168 }),
169 Effect.as(Option.none<PersistedServerRuntimeState>()),
170 ),
171 }),
172 );