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