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