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

serverRuntimeState.ts

182 lines5.8 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 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 ownerId: Schema.optional(Schema.String),
15 host: Schema.optional(Schema.String),
16 port: Schema.Int,
17 origin: Schema.String,
18 // Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).
19 // Dev is single-origin: browsers must pair through this URL, not `origin`.
20 devUrl: Schema.optional(Schema.String),
21 startedAt: Schema.String,
22 /**
23 * Set when the boot-service launcher supervises this server. Lets a CLI
24 * tell a service-managed server apart from one started by hand, which is
25 * the difference between "restart the service" and "stop your terminal".
26 */
27 serviceManaged: Schema.optional(Schema.Boolean),
28});
29export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
30​
31export class ServerRuntimeStateError extends Schema.TaggedError<ServerRuntimeStateError>()(
32 "ServerRuntimeStateError",
33 {
34 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
35 statePath: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
41 }
43​
44const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
45 Schema.fromJsonString(PersistedServerRuntimeState),
46);
47​
48const runtimeOriginForConfig = (
49 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
50 port: number,
51): PersistedServerRuntimeState["origin"] => {
52 const hostname =
53 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
54 return `http://${hostname}:${port}`;
55};
56​
57export const makePersistedServerRuntimeState = (input: {
58 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
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 port: input.port,
67 origin: runtimeOriginForConfig(input.config, input.port),
68 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
69 startedAt: DateTime.formatIso(now),
70 ...(input.serviceManaged ? { serviceManaged: true } : {}),
71 }));
72​
73export const persistServerRuntimeState = (input: {
74 readonly path: string;
75 readonly state: PersistedServerRuntimeState;
76}) =>
77 writeFileStringAtomically({
78 filePath: input.path,
79 contents: `${JSON.stringify(input.state)}\n`,
80 }).pipe(
81 Effect.mapError(
82 (cause) =>
83 new ServerRuntimeStateError({
84 operation: "persist",
85 statePath: input.path,
86 cause,
87 }),
88 ),
89 );
90​
91export const clearPersistedServerRuntimeState = (path: string) =>
92 Effect.gen(function* () {
93 const fs = yield* FileSystem.FileSystem;
94 yield* fs.remove(path, { force: true }).pipe(
95 Effect.mapError(
96 (cause) =>
97 new ServerRuntimeStateError({
98 operation: "clear",
99 statePath: path,
100 cause,
101 }),
102 ),
103 Effect.catchTags({
104 ServerRuntimeStateError: (error) =>
105 Effect.logWarning(error.message).pipe(
106 Effect.annotateLogs({
107 operation: error.operation,
108 statePath: error.statePath,
109 cause: error,
110 }),
111 ),
112 }),
113 );
114 });
115​
116/**
117 * Report whether the pid recorded in a persisted runtime state is still
118 * running. Signal 0 delivers nothing; it only reports whether the pid exists.
119 * EPERM means it exists but belongs to another user, which still counts as
120 * alive.
121 */
122export const isProcessAlive = (pid: number): boolean => {
123 if (!Number.isInteger(pid) || pid <= 0) return false;
124 try {
125 process.kill(pid, 0);
126 return true;
127 } catch (error) {
128 return error instanceof Error && "code" in error && error.code === "EPERM";
129 }
130};
131​
132export const readPersistedServerRuntimeState = (path: string) =>
133 Effect.gen(function* () {
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 }).pipe(
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 );