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