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

serverRuntimeState.ts

72 lines2.4 KB

1import { Effect, FileSystem, Option, Schema } from "effect";
2​
3import { writeFileStringAtomically } from "./atomicWrite.ts";
4import { type ServerConfigShape } from "./config.ts";
5import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
6​
7export const PersistedServerRuntimeState = Schema.Struct({
8 version: Schema.Literal(1),
9 pid: Schema.Int,
10 host: Schema.optional(Schema.String),
11 port: Schema.Int,
12 origin: Schema.String,
13 startedAt: Schema.String,
14});
15export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
16​
17const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
18 Schema.fromJsonString(PersistedServerRuntimeState),
19);
20​
21const runtimeOriginForConfig = (
22 config: Pick<ServerConfigShape, "host">,
23 port: number,
24): PersistedServerRuntimeState["origin"] => {
25 const hostname =
26 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
27 return `http://${hostname}:${port}`;
28};
29​
30export const makePersistedServerRuntimeState = (input: {
31 readonly config: Pick<ServerConfigShape, "host">;
32 readonly port: number;
33}): PersistedServerRuntimeState => ({
34 version: 1,
35 pid: process.pid,
36 ...(input.config.host ? { host: input.config.host } : {}),
37 port: input.port,
38 origin: runtimeOriginForConfig(input.config, input.port),
39 startedAt: new Date().toISOString(),
40});
41​
42export const persistServerRuntimeState = (input: {
43 readonly path: string;
44 readonly state: PersistedServerRuntimeState;
45}) =>
46 writeFileStringAtomically({
47 filePath: input.path,
48 contents: `${JSON.stringify(input.state)}\n`,
49 });
50​
51export const clearPersistedServerRuntimeState = (path: string) =>
52 Effect.gen(function* () {
53 const fs = yield* FileSystem.FileSystem;
54 yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true }));
55 });
56​
57export const readPersistedServerRuntimeState = (path: string) =>
58 Effect.gen(function* () {
59 const fs = yield* FileSystem.FileSystem;
60 const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false));
61 if (!exists) {
62 return Option.none<PersistedServerRuntimeState>();
63 }
64​
65 const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));
66 const trimmed = raw.trim();
67 if (trimmed.length === 0) {
68 return Option.none<PersistedServerRuntimeState>();
69 }
70​
71 return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option);
72 });