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});
22export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
23
24export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(
25 "ServerRuntimeStateError",
26 {
27 operation: Schema.Literals(["persist", "read", "decode", "clear"]),
28 statePath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
34 }
35}
36
37const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
38 Schema.fromJsonString(PersistedServerRuntimeState),
39);
40
41const runtimeOriginForConfig = (
42 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
43 port: number,
44): PersistedServerRuntimeState["origin"] => {
45 const hostname =
46 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
47 return `http://${hostname}:${port}`;
48};
49
50export const makePersistedServerRuntimeState = (input: {
51 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
52 readonly port: number;
53}): Effect.Effect<PersistedServerRuntimeState> =>
54 Effect.map(DateTime.now, (now) => ({
55 version: 1,
56 pid: process.pid,
57 ...(input.config.host ? { host: input.config.host } : {}),
58 port: input.port,
59 origin: runtimeOriginForConfig(input.config, input.port),
60 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
61 startedAt: DateTime.formatIso(now),
62 }));
63
64export const persistServerRuntimeState = (input: {
65 readonly path: string;
66 readonly state: PersistedServerRuntimeState;
67}) =>
68 writeFileStringAtomically({
69 filePath: input.path,
70 contents: `${JSON.stringify(input.state)}\n`,
71 }).pipe(
72 Effect.mapError(
73 (cause) =>
74 new ServerRuntimeStateError({
75 operation: "persist",
76 statePath: input.path,
77 cause,
78 }),
79 ),
80 );
81
82export const clearPersistedServerRuntimeState = (path: string) =>
83 Effect.gen(function* () {
84 const fs = yield* FileSystem.FileSystem;
85 yield* fs.remove(path, { force: true }).pipe(
86 Effect.mapError(
87 (cause) =>
88 new ServerRuntimeStateError({
89 operation: "clear",
90 statePath: path,
91 cause,
92 }),
93 ),
94 Effect.catchTags({
95 ServerRuntimeStateError: (error) =>
96 Effect.logWarning(error.message).pipe(
97 Effect.annotateLogs({
98 operation: error.operation,
99 statePath: error.statePath,
100 cause: error,
101 }),
102 ),
103 }),
104 );
105 });
106
107export const readPersistedServerRuntimeState = (path: string) =>
108 Effect.gen(function* () {
109 const fs = yield* FileSystem.FileSystem;
110 const raw = yield* fs.readFileString(path).pipe(
111 Effect.matchEffect({
112 onFailure: (cause) =>
113 cause.reason._tag === "NotFound"
114 ? Effect.succeed(Option.none<string>())
115 : Effect.fail(
116 new ServerRuntimeStateError({
117 operation: "read",
118 statePath: path,
119 cause,
120 }),
121 ),
122 onSuccess: (contents) => Effect.succeed(Option.some(contents)),
123 }),
124 );
125 if (Option.isNone(raw)) {
126 return Option.none<PersistedServerRuntimeState>();
127 }
128
129 const trimmed = raw.value.trim();
130 if (trimmed.length === 0) {
131 return Option.none<PersistedServerRuntimeState>();
132 }
133
134 return yield* decodePersistedServerRuntimeState(trimmed).pipe(
135 Effect.map(Option.some),
136 Effect.mapError(
137 (cause) =>
138 new ServerRuntimeStateError({
139 operation: "decode",
140 statePath: path,
141 cause,
142 }),
143 ),
144 );
145 }).pipe(
146 Effect.catchTags({
147 ServerRuntimeStateError: (error) =>
148 Effect.logWarning(error.message).pipe(
149 Effect.annotateLogs({
150 operation: error.operation,
151 statePath: error.statePath,
152 cause: error,
153 }),
154 Effect.as(Option.none<PersistedServerRuntimeState>()),
155 ),
156 }),
157 );