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 ServerConfigShape } 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
21const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
22 Schema.fromJsonString(PersistedServerRuntimeState),
23);
24
25const runtimeOriginForConfig = (
26 config: Pick<ServerConfigShape, "host">,
27 port: number,
28): PersistedServerRuntimeState["origin"] => {
29 const hostname =
30 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
31 return `http://${hostname}:${port}`;
32};
33
34export const makePersistedServerRuntimeState = (input: {
35 readonly config: Pick<ServerConfigShape, "host">;
36 readonly port: number;
37}): Effect.Effect<PersistedServerRuntimeState> =>
38 Effect.map(DateTime.now, (now) => ({
39 version: 1,
40 pid: process.pid,
41 ...(input.config.host ? { host: input.config.host } : {}),
42 port: input.port,
43 origin: runtimeOriginForConfig(input.config, input.port),
44 startedAt: DateTime.formatIso(now),
45 }));
46
47export const persistServerRuntimeState = (input: {
48 readonly path: string;
49 readonly state: PersistedServerRuntimeState;
50}) =>
51 writeFileStringAtomically({
52 filePath: input.path,
53 contents: `${JSON.stringify(input.state)}\n`,
54 });
55
56export const clearPersistedServerRuntimeState = (path: string) =>
57 Effect.gen(function* () {
58 const fs = yield* FileSystem.FileSystem;
59 yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true }));
60 });
61
62export const readPersistedServerRuntimeState = (path: string) =>
63 Effect.gen(function* () {
64 const fs = yield* FileSystem.FileSystem;
65 const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false));
66 if (!exists) {
67 return Option.none<PersistedServerRuntimeState>();
68 }
69
70 const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));
71 const trimmed = raw.trim();
72 if (trimmed.length === 0) {
73 return Option.none<PersistedServerRuntimeState>();
74 }
75
76 return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option);
77 });