Repository navigation
Expand file tree
/
Copy pathserverRuntimeState.ts
More file actions
194 lines (182 loc) · 6.06 KB
/
Copy pathserverRuntimeState.ts
File metadata and controls
194 lines (182 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import packageJson from "../package.json" with { type: "json" };
import type * as ServerConfig from "./config.ts";
import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
export const PersistedServerRuntimeState = Schema.Struct({
version: Schema.Literal(1),
pid: Schema.Int,
ownerId: Schema.optional(Schema.String),
host: Schema.optional(Schema.String),
privateNetworkOnly: Schema.optional(Schema.Boolean),
port: Schema.Int,
origin: Schema.String,
// Dev is single-origin: browsers must pair through this URL, not `origin`.
devUrl: Schema.optional(Schema.String),
startedAt: Schema.String,
serviceManaged: Schema.optional(Schema.Boolean),
serverVersion: Schema.optional(Schema.String),
// The managed policy this server loaded at startup, null for none; absent from older servers.
managedPolicy: Schema.optional(
Schema.NullOr(
Schema.Struct({
source: Schema.String,
organization: Schema.String,
fingerprint: Schema.String,
}),
),
),
});
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
export class ServerRuntimeStateError extends Schema.TaggedError<ServerRuntimeStateError>()(
"ServerRuntimeStateError",
{
operation: Schema.Literals(["persist", "read", "decode", "clear"]),
statePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
}
}
const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
Schema.fromJsonString(PersistedServerRuntimeState),
);
const runtimeOriginForConfig = (
config: Pick<ServerConfig.ServerConfig["Service"], "host">,
port: number,
): PersistedServerRuntimeState["origin"] => {
const hostname =
config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
return `http://${hostname}:${port}`;
};
export const makePersistedServerRuntimeState = (input: {
readonly config: Pick<
ServerConfig.ServerConfig["Service"],
"host" | "privateNetworkOnly" | "devUrl"
>;
readonly port: number;
readonly serviceManaged?: boolean;
readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"];
}): Effect.Effect<PersistedServerRuntimeState> =>
Effect.map(DateTime.now, (now) => ({
version: 1,
pid: process.pid,
...(input.config.host ? { host: input.config.host } : {}),
...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}),
port: input.port,
origin: runtimeOriginForConfig(input.config, input.port),
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
startedAt: DateTime.formatIso(now),
...(input.serviceManaged ? { serviceManaged: true } : {}),
serverVersion: packageJson.version,
...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }),
}));
export const persistServerRuntimeState = (input: {
readonly path: string;
readonly state: PersistedServerRuntimeState;
}) =>
writeFileStringAtomically({
filePath: input.path,
contents: `${JSON.stringify(input.state)}\n`,
}).pipe(
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "persist",
statePath: input.path,
cause,
}),
),
);
export const clearPersistedServerRuntimeState = Effect.fn(
"serverRuntimeState.clearPersistedServerRuntimeState",
)(function* (path: string) {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(path, { force: true }).pipe(
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "clear",
statePath: path,
cause,
}),
),
Effect.catchTags({
ServerRuntimeStateError: (error) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
operation: error.operation,
statePath: error.statePath,
cause: error,
}),
),
}),
);
});
/** Signal 0 only probes existence; EPERM still means alive. */
export const isProcessAlive = (pid: number): boolean => {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error instanceof Error && "code" in error && error.code === "EPERM";
}
};
export const readPersistedServerRuntimeState = Effect.fn(
"serverRuntimeState.readPersistedServerRuntimeState",
)(
function* (path: string) {
const fs = yield* FileSystem.FileSystem;
const raw = yield* fs.readFileString(path).pipe(
Effect.matchEffect({
onFailure: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.fail(
new ServerRuntimeStateError({
operation: "read",
statePath: path,
cause,
}),
),
onSuccess: (contents) => Effect.succeedSome(contents),
}),
);
if (Option.isNone(raw)) {
return Option.none<PersistedServerRuntimeState>();
}
const trimmed = raw.value.trim();
if (trimmed.length === 0) {
return Option.none<PersistedServerRuntimeState>();
}
return yield* decodePersistedServerRuntimeState(trimmed).pipe(
Effect.asSome,
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "decode",
statePath: path,
cause,
}),
),
);
},
Effect.catchTags({
ServerRuntimeStateError: (error) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
operation: error.operation,
statePath: error.statePath,
cause: error,
}),
Effect.as(Option.none<PersistedServerRuntimeState>()),
),
}),
);