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

serverRuntimeState.ts

180 lines5.5 KB

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 port: Schema.Int,
18 origin: Schema.String,
19 // Dev is single-origin: browsers must pair through this URL, not `origin`.
20 devUrl: Schema.optional(Schema.String),
21 startedAt: Schema.String,
22 serviceManaged: Schema.optional(Schema.Boolean),
23 serverVersion: Schema.optional(Schema.String),
24});
25export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
26​
27export class ServerRuntimeStateError extends Schema.TaggedError<ServerRuntimeStateError>()(
28 "ServerRuntimeStateError",
29 {
30 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
31 statePath: Schema.String,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
37 }
39​
40const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
41 Schema.fromJsonString(PersistedServerRuntimeState),
42);
43​
44const runtimeOriginForConfig = (
45 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
46 port: number,
47): PersistedServerRuntimeState["origin"] => {
48 const hostname =
49 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
50 return `http://${hostname}:${port}`;
51};
52​
53export const makePersistedServerRuntimeState = (input: {
54 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
55 readonly port: number;
56 readonly serviceManaged?: boolean;
57}): Effect.Effect<PersistedServerRuntimeState> =>
58 Effect.map(DateTime.now, (now) => ({
59 version: 1,
60 pid: process.pid,
61 ...(input.config.host ? { host: input.config.host } : {}),
62 port: input.port,
63 origin: runtimeOriginForConfig(input.config, input.port),
64 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
65 startedAt: DateTime.formatIso(now),
66 ...(input.serviceManaged ? { serviceManaged: true } : {}),
67 serverVersion: packageJson.version,
68 }));
69​
70export const persistServerRuntimeState = (input: {
71 readonly path: string;
72 readonly state: PersistedServerRuntimeState;
73}) =>
74 writeFileStringAtomically({
75 filePath: input.path,
76 contents: `${JSON.stringify(input.state)}\n`,
77 }).pipe(
78 Effect.mapError(
79 (cause) =>
80 new ServerRuntimeStateError({
81 operation: "persist",
82 statePath: input.path,
83 cause,
84 }),
85 ),
86 );
87​
88export const clearPersistedServerRuntimeState = Effect.fn(
89 "serverRuntimeState.clearPersistedServerRuntimeState",
90)(function* (path: string) {
91 const fs = yield* FileSystem.FileSystem;
92 yield* fs.remove(path, { force: true }).pipe(
93 Effect.mapError(
94 (cause) =>
95 new ServerRuntimeStateError({
96 operation: "clear",
97 statePath: path,
98 cause,
99 }),
100 ),
101 Effect.catchTags({
102 ServerRuntimeStateError: (error) =>
103 Effect.logWarning(error.message).pipe(
104 Effect.annotateLogs({
105 operation: error.operation,
106 statePath: error.statePath,
107 cause: error,
108 }),
109 ),
110 }),
111 );
112});
113​
114/**
115 * Signal 0 delivers nothing; it only reports whether the pid exists. EPERM
116 * means it exists but belongs to another user, which still counts as alive.
117 */
118export const isProcessAlive = (pid: number): boolean => {
119 if (!Number.isInteger(pid) || pid <= 0) return false;
120 try {
121 process.kill(pid, 0);
122 return true;
123 } catch (error) {
124 return error instanceof Error && "code" in error && error.code === "EPERM";
125 }
126};
127​
128export const readPersistedServerRuntimeState = Effect.fn(
129 "serverRuntimeState.readPersistedServerRuntimeState",
130)(
131 function* (path: string) {
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.succeedSome(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.asSome,
159 Effect.mapError(
160 (cause) =>
161 new ServerRuntimeStateError({
162 operation: "decode",
163 statePath: path,
164 cause,
165 }),
166 ),
167 );
168 },
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);