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 {
5 type PersistedServerRuntimeState,
6 ServerRuntimeStateError,
7} from "@t3tools/shared/serverRuntimeState";
8
9import { writeFileStringAtomically } from "./atomicWrite.ts";
10import type * as ServerConfig from "./config.ts";
11import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
12
13export {
14 PersistedServerRuntimeState,
15 readPersistedServerRuntimeState,
16 isProcessAlive,
17 ServerRuntimeStateError,
18} from "@t3tools/shared/serverRuntimeState";
19
20const runtimeOriginForConfig = (
21 config: Pick<ServerConfig.ServerConfig["Service"], "host">,
22 port: number,
23): PersistedServerRuntimeState["origin"] => {
24 const hostname =
25 config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
26 return `http://${hostname}:${port}`;
27};
28
29export const makePersistedServerRuntimeState = (input: {
30 readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
31 readonly port: number;
32 readonly serviceManaged?: boolean;
33}): Effect.Effect<PersistedServerRuntimeState> =>
34 Effect.map(DateTime.now, (now) => ({
35 version: 1,
36 pid: process.pid,
37 ...(input.config.host ? { host: input.config.host } : {}),
38 port: input.port,
39 origin: runtimeOriginForConfig(input.config, input.port),
40 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
41 startedAt: DateTime.formatIso(now),
42 ...(input.serviceManaged ? { serviceManaged: true } : {}),
43 }));
44
45export const persistServerRuntimeState = (input: {
46 readonly path: string;
47 readonly state: PersistedServerRuntimeState;
48}) =>
49 writeFileStringAtomically({
50 filePath: input.path,
51 contents: `${JSON.stringify(input.state)}\n`,
52 }).pipe(
53 Effect.mapError(
54 (cause) =>
55 new ServerRuntimeStateError({
56 operation: "persist",
57 statePath: input.path,
58 cause,
59 }),
60 ),
61 );
62
63export const clearPersistedServerRuntimeState = (path: string) =>
64 Effect.gen(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 yield* fs.remove(path, { force: true }).pipe(
67 Effect.mapError(
68 (cause) =>
69 new ServerRuntimeStateError({
70 operation: "clear",
71 statePath: path,
72 cause,
73 }),
74 ),
75 Effect.catchTags({
76 ServerRuntimeStateError: (error) =>
77 Effect.logWarning(error.message).pipe(
78 Effect.annotateLogs({
79 operation: error.operation,
80 statePath: error.statePath,
81 cause: error,
82 }),
83 ),
84 }),
85 );
86 });