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

serverRuntimeState.ts

216 lines7.0 KB

1import * as NodeOS from "node:os";
2​
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8​
9import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
10import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
11import packageJson from "../package.json" with { type: "json" };
12import type * as ServerConfig from "./config.ts";
13​
14export const PersistedServerRuntimeState = Schema.Struct({
15 version: Schema.Literal(1),
16 pid: Schema.Int,
17 ownerId: Schema.optional(Schema.String),
18 // The machine that wrote this record; every machine sharing the T3 home can read it.
19 hostname: Schema.optional(Schema.String),
20 host: Schema.optional(Schema.String),
21 privateNetworkOnly: Schema.optional(Schema.Boolean),
22 port: Schema.Int,
23 origin: Schema.String,
24 // Dev is single-origin: browsers must pair through this URL, not `origin`.
25 devUrl: Schema.optional(Schema.String),
26 startedAt: Schema.String,
27 serviceManaged: Schema.optional(Schema.Boolean),
28 serverVersion: Schema.optional(Schema.String),
29 // The managed policy this server loaded at startup, null for none; absent from older servers.
30 managedPolicy: Schema.optional(
31 Schema.NullOr(
32 Schema.Struct({
33 source: Schema.String,
34 organization: Schema.String,
35 fingerprint: Schema.String,
36 }),
37 ),
38 ),
39});
40export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
41​
42export class ServerRuntimeStateError extends Schema.TaggedError<ServerRuntimeStateError>()(
43 "ServerRuntimeStateError",
44 {
45 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
46 statePath: Schema.String,
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
52 }
54​
55const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
56 Schema.fromJsonString(PersistedServerRuntimeState),
57);
58​
59const runtimeOriginForConfig = (
60 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
61 port: number,
62): PersistedServerRuntimeState["origin"] => {
63 const hostname =
64 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
65 return `http://${hostname}:${port}`;
66};
67​
68export const makePersistedServerRuntimeState = (input: {
69 readonly config: Pick<
70 ServerConfig.ServerConfig["Service"],
71 "host" | "privateNetworkOnly" | "devUrl"
72 >;
73 readonly port: number;
74 readonly serviceManaged?: boolean;
75 readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"];
76}): Effect.Effect<PersistedServerRuntimeState> =>
77 Effect.map(DateTime.now, (now) => ({
78 version: 1,
79 pid: process.pid,
80 hostname: NodeOS.hostname(),
81 ...(input.config.host ? { host: input.config.host } : {}),
82 ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}),
83 port: input.port,
84 origin: runtimeOriginForConfig(input.config, input.port),
85 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
86 startedAt: DateTime.formatIso(now),
87 ...(input.serviceManaged ? { serviceManaged: true } : {}),
88 serverVersion: packageJson.version,
89 ...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }),
90 }));
91​
92export const persistServerRuntimeState = (input: {
93 readonly path: string;
94 readonly state: PersistedServerRuntimeState;
95}) =>
96 writeFileStringAtomically({
97 filePath: input.path,
98 contents: `${JSON.stringify(input.state)}\n`,
99 }).pipe(
100 Effect.mapError(
101 (cause) =>
102 new ServerRuntimeStateError({
103 operation: "persist",
104 statePath: input.path,
105 cause,
106 }),
107 ),
108 );
109​
110export const clearPersistedServerRuntimeState = Effect.fn(
111 "serverRuntimeState.clearPersistedServerRuntimeState",
112)(function* (path: string) {
113 const fs = yield* FileSystem.FileSystem;
114 yield* fs.remove(path, { force: true }).pipe(
115 Effect.mapError(
116 (cause) =>
117 new ServerRuntimeStateError({
118 operation: "clear",
119 statePath: path,
120 cause,
121 }),
122 ),
123 Effect.catchTags({
124 ServerRuntimeStateError: (error) =>
125 Effect.logWarning(error.message).pipe(
126 Effect.annotateLogs({
127 operation: error.operation,
128 statePath: error.statePath,
129 cause: error,
130 }),
131 ),
132 }),
133 );
134});
135​
136/** A record written by another machine sharing this T3 home; its pid means nothing here. */
137export const isRuntimeStateFromAnotherMachine = (state: PersistedServerRuntimeState): boolean =>
138 state.hostname !== undefined && state.hostname !== NodeOS.hostname();
139​
140/** Signal 0 only probes existence; EPERM still means alive. */
141export const isProcessAlive = (pid: number): boolean => {
142 if (!Number.isInteger(pid) || pid <= 0) return false;
143 try {
144 process.kill(pid, 0);
145 return true;
146 } catch (error) {
147 return error instanceof Error && "code" in error && error.code === "EPERM";
148 }
149};
150​
151export const readPersistedServerRuntimeState = Effect.fn(
152 "serverRuntimeState.readPersistedServerRuntimeState",
153)(
154 function* (path: string) {
155 const fs = yield* FileSystem.FileSystem;
156 const raw = yield* fs.readFileString(path).pipe(
157 Effect.matchEffect({
158 onFailure: (cause) =>
159 cause.reason._tag === "NotFound"
160 ? Effect.succeed(Option.none<string>())
161 : Effect.fail(
162 new ServerRuntimeStateError({
163 operation: "read",
164 statePath: path,
165 cause,
166 }),
167 ),
168 onSuccess: (contents) => Effect.succeedSome(contents),
169 }),
170 );
171 if (Option.isNone(raw)) {
172 return Option.none<PersistedServerRuntimeState>();
173 }
174​
175 const trimmed = raw.value.trim();
176 if (trimmed.length === 0) {
177 return Option.none<PersistedServerRuntimeState>();
178 }
179​
180 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
181 Effect.asSome,
182 Effect.mapError(
183 (cause) =>
184 new ServerRuntimeStateError({
185 operation: "decode",
186 statePath: path,
187 cause,
188 }),
189 ),
190 );
191 },
192 Effect.catchTags({
193 ServerRuntimeStateError: (error) =>
194 Effect.logWarning(error.message).pipe(
195 Effect.annotateLogs({
196 operation: error.operation,
197 statePath: error.statePath,
198 cause: error,
199 }),
200 Effect.as(Option.none<PersistedServerRuntimeState>()),
201 ),
202 }),
203);
204​
205/**
206 * The runtime record, only while its server process is alive. Read this before sending
207 * credentials to the recorded origin: a killed server leaves its record behind, and
208 * another process may own its port by now.
209 */
210export const readLiveServerRuntimeState = Effect.fn(
211 "serverRuntimeState.readLiveServerRuntimeState",
212)((path: string) =>
213 readPersistedServerRuntimeState(path).pipe(
214 Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
215 ),
216);