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 "@t3tools/shared/atomicWrite";
8import packageJson from "../package.json" with { type: "json" };
9import type * as ServerConfig from "./config.ts";
10import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
11
12export const PersistedServerRuntimeState = Schema.Struct({
13 version: Schema.Literal(1),
14 pid: Schema.Int,
15 ownerId: Schema.optional(Schema.String),
16 host: Schema.optional(Schema.String),
17 privateNetworkOnly: Schema.optional(Schema.Boolean),
18 port: Schema.Int,
19 origin: Schema.String,
20 // Dev is single-origin: browsers must pair through this URL, not `origin`.
21 devUrl: Schema.optional(Schema.String),
22 startedAt: Schema.String,
23 serviceManaged: Schema.optional(Schema.Boolean),
24 serverVersion: Schema.optional(Schema.String),
25});
26export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
27
28export class ServerRuntimeStateError extends Schema.TaggedError<ServerRuntimeStateError>()(
29 "ServerRuntimeStateError",
30 {
31 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
32 statePath: Schema.String,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
38 }
39}
40
41const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
42 Schema.fromJsonString(PersistedServerRuntimeState),
43);
44
45const runtimeOriginForConfig = (
46 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
47 port: number,
48): PersistedServerRuntimeState["origin"] => {
49 const hostname =
50 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
51 return `http://${hostname}:${port}`;
52};
53
54export const makePersistedServerRuntimeState = (input: {
55 readonly config: Pick<
56 ServerConfig.ServerConfig["Service"],
57 "host" | "privateNetworkOnly" | "devUrl"
58 >;
59 readonly port: number;
60 readonly serviceManaged?: boolean;
61}): Effect.Effect<PersistedServerRuntimeState> =>
62 Effect.map(DateTime.now, (now) => ({
63 version: 1,
64 pid: process.pid,
65 ...(input.config.host ? { host: input.config.host } : {}),
66 ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}),
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 serverVersion: packageJson.version,
73 }));
74
75export const persistServerRuntimeState = (input: {
76 readonly path: string;
77 readonly state: PersistedServerRuntimeState;
78}) =>
79 writeFileStringAtomically({
80 filePath: input.path,
81 contents: `${JSON.stringify(input.state)}\n`,
82 }).pipe(
83 Effect.mapError(
84 (cause) =>
85 new ServerRuntimeStateError({
86 operation: "persist",
87 statePath: input.path,
88 cause,
89 }),
90 ),
91 );
92
93export const clearPersistedServerRuntimeState = Effect.fn(
94 "serverRuntimeState.clearPersistedServerRuntimeState",
95)(function* (path: string) {
96 const fs = yield* FileSystem.FileSystem;
97 yield* fs.remove(path, { force: true }).pipe(
98 Effect.mapError(
99 (cause) =>
100 new ServerRuntimeStateError({
101 operation: "clear",
102 statePath: path,
103 cause,
104 }),
105 ),
106 Effect.catchTags({
107 ServerRuntimeStateError: (error) =>
108 Effect.logWarning(error.message).pipe(
109 Effect.annotateLogs({
110 operation: error.operation,
111 statePath: error.statePath,
112 cause: error,
113 }),
114 ),
115 }),
116 );
117});
118
119/** Signal 0 only probes existence; EPERM still means alive. */
120export const isProcessAlive = (pid: number): boolean => {
121 if (!Number.isInteger(pid) || pid <= 0) return false;
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 = Effect.fn(
131 "serverRuntimeState.readPersistedServerRuntimeState",
132)(
133 function* (path: string) {
134 const fs = yield* FileSystem.FileSystem;
135 const raw = yield* fs.readFileString(path).pipe(
136 Effect.matchEffect({
137 onFailure: (cause) =>
138 cause.reason._tag === "NotFound"
139 ? Effect.succeed(Option.none<string>())
140 : Effect.fail(
141 new ServerRuntimeStateError({
142 operation: "read",
143 statePath: path,
144 cause,
145 }),
146 ),
147 onSuccess: (contents) => Effect.succeedSome(contents),
148 }),
149 );
150 if (Option.isNone(raw)) {
151 return Option.none<PersistedServerRuntimeState>();
152 }
153
154 const trimmed = raw.value.trim();
155 if (trimmed.length === 0) {
156 return Option.none<PersistedServerRuntimeState>();
157 }
158
159 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
160 Effect.asSome,
161 Effect.mapError(
162 (cause) =>
163 new ServerRuntimeStateError({
164 operation: "decode",
165 statePath: path,
166 cause,
167 }),
168 ),
169 );
170 },
171 Effect.catchTags({
172 ServerRuntimeStateError: (error) =>
173 Effect.logWarning(error.message).pipe(
174 Effect.annotateLogs({
175 operation: error.operation,
176 statePath: error.statePath,
177 cause: error,
178 }),
179 Effect.as(Option.none<PersistedServerRuntimeState>()),
180 ),
181 }),
182);