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