@tsplc/agent 0.4.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/cli.js +1103 -152
- package/dist/cli.js.map +24 -14
- package/dist/client.js +19 -4
- package/dist/client.js.map +4 -4
- package/dist/index.js +372 -128
- package/dist/index.js.map +14 -12
- package/package.json +5 -5
- package/src/agent.ts +63 -7
- package/src/cli.ts +93 -12
- package/src/client.ts +6 -1
- package/src/codesys.ts +61 -1
- package/src/deploy.ts +37 -1
- package/src/index.ts +1 -0
- package/src/instance.ts +102 -0
- package/src/login.ts +7 -0
- package/src/maintenance.ts +313 -0
- package/src/operations.ts +17 -1
- package/src/processes.ts +24 -0
- package/src/protocol.ts +19 -1
- package/src/server-process.ts +195 -40
- package/src/service.ts +206 -0
- package/src/state.ts +10 -1
- package/src/upgrade.ts +149 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { closeSync, openSync } from "node:fs";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import {
|
|
8
|
+
type AgentControl,
|
|
9
|
+
answeringVersion,
|
|
10
|
+
createAgentControl,
|
|
11
|
+
type Instance,
|
|
12
|
+
runningAgent,
|
|
13
|
+
} from "./instance";
|
|
14
|
+
import { processAlive } from "./processes";
|
|
15
|
+
import { agentSetting } from "./secrets";
|
|
16
|
+
import { schtasks, superviseAgent, taskDefinition, taskFile } from "./service";
|
|
17
|
+
import { openState } from "./state";
|
|
18
|
+
import { installCommand, packageManagerFor, upgradeAgent } from "./upgrade";
|
|
19
|
+
|
|
20
|
+
/** The installed agent package, one directory above its source modules and its bundle alike. */
|
|
21
|
+
const agentPackage = resolve(import.meta.dir, "..");
|
|
22
|
+
|
|
23
|
+
/** The version of the agent package installed now, which an upgrade may have changed under this process. */
|
|
24
|
+
const installedVersion = async () =>
|
|
25
|
+
z
|
|
26
|
+
.object({ version: z.string() })
|
|
27
|
+
.parse(
|
|
28
|
+
JSON.parse(await readFile(join(agentPackage, "package.json"), "utf8")),
|
|
29
|
+
).version;
|
|
30
|
+
|
|
31
|
+
/** How long a new agent may take to answer, and an old one to exit. */
|
|
32
|
+
const answerWithinMs = 180_000;
|
|
33
|
+
const exitWithinMs = 60_000;
|
|
34
|
+
|
|
35
|
+
const run = (command: string[]) =>
|
|
36
|
+
Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] }).exited;
|
|
37
|
+
|
|
38
|
+
const quietly = (command: string[]) =>
|
|
39
|
+
Bun.spawn(command, { stdio: ["ignore", "ignore", "ignore"] }).exited;
|
|
40
|
+
|
|
41
|
+
/** What `command` prints, or null when it fails or isn't installed. */
|
|
42
|
+
const capture = async (command: string[]) => {
|
|
43
|
+
try {
|
|
44
|
+
const child = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
|
|
45
|
+
const [output, status] = await Promise.all([
|
|
46
|
+
new Response(child.stdout).text(),
|
|
47
|
+
child.exited,
|
|
48
|
+
]);
|
|
49
|
+
return status === 0 ? output.trim() : null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** The command that runs this agent's CLI with `args`, on the Bun running it now. */
|
|
56
|
+
const agentCommand = (...args: string[]) => [
|
|
57
|
+
process.execPath,
|
|
58
|
+
Bun.main,
|
|
59
|
+
...args,
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
/** The running agent and its control routes, which need its full token. */
|
|
63
|
+
const controlRunning = async (agentFile: string) => {
|
|
64
|
+
const instance = await runningAgent(agentFile);
|
|
65
|
+
if (!instance) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const token = await agentSetting("TSPLC_AGENT_TOKEN");
|
|
69
|
+
if (!token) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`tsplc-agent ${instance.version} is running, and holding it needs its token: set TSPLC_AGENT_TOKEN, or store it with tsplc-agent secrets set TSPLC_AGENT_TOKEN as the user the agent runs as`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return { instance, control: createAgentControl(instance, token) };
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const waitUntil = async (condition: () => Promise<boolean>, within: number) => {
|
|
78
|
+
const deadline = Date.now() + within;
|
|
79
|
+
while (Date.now() < deadline) {
|
|
80
|
+
if (await condition()) {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
await delay(1000);
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const waitForExit = async (instance: Instance) => {
|
|
89
|
+
if (
|
|
90
|
+
!(await waitUntil(async () => !processAlive(instance.pid), exitWithinMs))
|
|
91
|
+
) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`tsplc-agent (process ${instance.pid}) didn't exit within ${exitWithinMs / 1000} s`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** Whether the agent recorded in `agentFile` runs `version` and answers. */
|
|
99
|
+
const answers = (agentFile: string, version: string) =>
|
|
100
|
+
waitUntil(async () => {
|
|
101
|
+
const instance = await runningAgent(agentFile);
|
|
102
|
+
return (
|
|
103
|
+
instance?.version === version &&
|
|
104
|
+
(await answeringVersion(instance.url)) === version
|
|
105
|
+
);
|
|
106
|
+
}, answerWithinMs);
|
|
107
|
+
|
|
108
|
+
/** `tsplc-agent upgrade [version]`. */
|
|
109
|
+
export const upgradeCommand = async (options: {
|
|
110
|
+
version: string;
|
|
111
|
+
state: string;
|
|
112
|
+
}) => {
|
|
113
|
+
const state = await openState(options.state);
|
|
114
|
+
const manager =
|
|
115
|
+
packageManagerFor(agentPackage, null) ??
|
|
116
|
+
packageManagerFor(agentPackage, await capture(npm("root", "--global")));
|
|
117
|
+
if (!manager) {
|
|
118
|
+
throw new Error(
|
|
119
|
+
`This agent runs from ${agentPackage}, which isn't a global bun or npm install; upgrade it the way it was installed`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
await upgradeAgent(
|
|
123
|
+
{
|
|
124
|
+
version: options.version,
|
|
125
|
+
install: installCommand(manager, options.version, {
|
|
126
|
+
bun: process.execPath,
|
|
127
|
+
platform: process.platform,
|
|
128
|
+
}),
|
|
129
|
+
setup: agentCommand("setup", "--if-needed"),
|
|
130
|
+
running: await controlRunning(state.paths.agent),
|
|
131
|
+
agentLog: state.paths.agentLog,
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
run,
|
|
135
|
+
installedVersion: installedVersion,
|
|
136
|
+
startAgent: async (instance) => {
|
|
137
|
+
await waitForExit(instance);
|
|
138
|
+
startDetached(
|
|
139
|
+
agentCommand("serve", ...instance.serve),
|
|
140
|
+
state.paths.agentLog,
|
|
141
|
+
);
|
|
142
|
+
},
|
|
143
|
+
startService: async () =>
|
|
144
|
+
process.platform === "win32" &&
|
|
145
|
+
(await quietly(schtasks.query())) === 0 &&
|
|
146
|
+
(await run(schtasks.run())) === 0,
|
|
147
|
+
answers: (version) => answers(state.paths.agent, version),
|
|
148
|
+
print: (line) => console.log(line),
|
|
149
|
+
},
|
|
150
|
+
);
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** npm, which is a batch file on Windows that only cmd runs. */
|
|
154
|
+
const npm = (...args: string[]) =>
|
|
155
|
+
process.platform === "win32"
|
|
156
|
+
? ["cmd.exe", "/d", "/s", "/c", "npm", ...args]
|
|
157
|
+
: ["npm", ...args];
|
|
158
|
+
|
|
159
|
+
/** Starts `command` outliving this process, with its output appended to `log`. */
|
|
160
|
+
const startDetached = (command: string[], log: string) => {
|
|
161
|
+
const output = openSync(log, "a");
|
|
162
|
+
try {
|
|
163
|
+
Bun.spawn(command, {
|
|
164
|
+
detached: true,
|
|
165
|
+
stdio: ["ignore", output, output],
|
|
166
|
+
windowsHide: true,
|
|
167
|
+
}).unref();
|
|
168
|
+
} finally {
|
|
169
|
+
closeSync(output);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const requireWindows = () => {
|
|
174
|
+
if (process.platform !== "win32") {
|
|
175
|
+
throw new Error(
|
|
176
|
+
"tsplc-agent service registers a Windows Task Scheduler task. Elsewhere, have your init system run tsplc-agent service run with the serve options, such as a systemd unit",
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const releasing = async <T>(
|
|
182
|
+
running: { control: AgentControl } | null,
|
|
183
|
+
step: () => Promise<T>,
|
|
184
|
+
) =>
|
|
185
|
+
step().catch(async (error: unknown) => {
|
|
186
|
+
await running?.control.release();
|
|
187
|
+
throw error;
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
/** `tsplc-agent service install|uninstall|status|run`. */
|
|
191
|
+
export const serviceCommand = async (options: {
|
|
192
|
+
action: string | undefined;
|
|
193
|
+
state: string;
|
|
194
|
+
/** The serve options the service runs the agent with. */
|
|
195
|
+
serve: string[];
|
|
196
|
+
stopServer: boolean;
|
|
197
|
+
}) => {
|
|
198
|
+
const state = await openState(options.state);
|
|
199
|
+
const logs = `The agent's log is ${state.paths.agentLog}; the line's server's is ${state.paths.serverLog}`;
|
|
200
|
+
switch (options.action) {
|
|
201
|
+
case "run":
|
|
202
|
+
await superviseAgent({
|
|
203
|
+
command: agentCommand("serve", ...options.serve),
|
|
204
|
+
log: state.paths.agentLog,
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
case "install": {
|
|
208
|
+
requireWindows();
|
|
209
|
+
const user = [process.env.USERDOMAIN, process.env.USERNAME]
|
|
210
|
+
.filter(Boolean)
|
|
211
|
+
.join("\\");
|
|
212
|
+
if (!process.env.USERNAME) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
"USERNAME isn't set, so the service has no user to run as",
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
const running = await controlRunning(state.paths.agent);
|
|
218
|
+
await running?.control.hold();
|
|
219
|
+
await releasing(running, async () => {
|
|
220
|
+
const directory = await mkdtemp(join(tmpdir(), "tsplc-agent-service-"));
|
|
221
|
+
try {
|
|
222
|
+
const file = join(directory, "task.xml");
|
|
223
|
+
await writeFile(
|
|
224
|
+
file,
|
|
225
|
+
taskFile(
|
|
226
|
+
taskDefinition({
|
|
227
|
+
bun: process.execPath,
|
|
228
|
+
script: Bun.main,
|
|
229
|
+
serve: options.serve,
|
|
230
|
+
user,
|
|
231
|
+
workingDirectory: homedir(),
|
|
232
|
+
}),
|
|
233
|
+
),
|
|
234
|
+
);
|
|
235
|
+
console.log(
|
|
236
|
+
`Registering the ${user} service; schtasks asks for ${user}'s Windows password, which Task Scheduler keeps to start the agent at boot`,
|
|
237
|
+
);
|
|
238
|
+
if ((await run(schtasks.create(file, user))) !== 0) {
|
|
239
|
+
throw new Error(
|
|
240
|
+
"Registering the service failed. Run tsplc-agent service install in a PowerShell opened with Run as administrator, signed in as the user the agent runs as",
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
} finally {
|
|
244
|
+
await rm(directory, { recursive: true, force: true });
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
if (running) {
|
|
248
|
+
console.log(
|
|
249
|
+
`Handing over from tsplc-agent ${running.instance.version} (process ${running.instance.pid}); the line's server keeps running`,
|
|
250
|
+
);
|
|
251
|
+
await running.control.exit({ server: "leave", restart: false });
|
|
252
|
+
await waitForExit(running.instance);
|
|
253
|
+
}
|
|
254
|
+
if ((await run(schtasks.run())) !== 0) {
|
|
255
|
+
throw new Error("The service is registered but didn't start");
|
|
256
|
+
}
|
|
257
|
+
const version = await installedVersion();
|
|
258
|
+
if (!(await answers(state.paths.agent, version))) {
|
|
259
|
+
throw new Error(
|
|
260
|
+
`The service started but tsplc-agent ${version} doesn't answer. ${logs}`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
console.log(
|
|
264
|
+
`The tsplc-agent service runs tsplc-agent ${version} at boot as ${user}, and starts it again if it exits. ${logs}`,
|
|
265
|
+
);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
case "uninstall": {
|
|
269
|
+
requireWindows();
|
|
270
|
+
const running = await runningAgent(state.paths.agent);
|
|
271
|
+
if (running?.supervised) {
|
|
272
|
+
const supervised = await controlRunning(state.paths.agent);
|
|
273
|
+
await supervised?.control.hold();
|
|
274
|
+
await supervised?.control.exit({
|
|
275
|
+
server: options.stopServer ? "stop" : "leave",
|
|
276
|
+
restart: false,
|
|
277
|
+
});
|
|
278
|
+
await waitForExit(running);
|
|
279
|
+
} else {
|
|
280
|
+
// A service waiting to start the agent again is stopped instead.
|
|
281
|
+
await quietly(schtasks.end());
|
|
282
|
+
}
|
|
283
|
+
if ((await run(schtasks.remove())) !== 0) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
"Removing the service failed. Run it in a PowerShell opened with Run as administrator",
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
console.log(
|
|
289
|
+
options.stopServer || !running?.supervised
|
|
290
|
+
? "Removed the tsplc-agent service"
|
|
291
|
+
: "Removed the tsplc-agent service. The line's server keeps running; the next tsplc-agent serve takes it over",
|
|
292
|
+
);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
case "status": {
|
|
296
|
+
if (process.platform === "win32" && (await run(schtasks.query())) !== 0) {
|
|
297
|
+
console.log("The tsplc-agent service isn't installed");
|
|
298
|
+
}
|
|
299
|
+
const running = await runningAgent(state.paths.agent);
|
|
300
|
+
console.log(
|
|
301
|
+
running
|
|
302
|
+
? `tsplc-agent ${running.version} runs as process ${running.pid} at ${running.url}${running.supervised ? ", under the service" : ""}, since ${running.startedAt}`
|
|
303
|
+
: "No tsplc-agent is running",
|
|
304
|
+
);
|
|
305
|
+
console.log(logs);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
default:
|
|
309
|
+
throw new Error(
|
|
310
|
+
"Usage: tsplc-agent service install|uninstall|status|run [serve options]",
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
};
|
package/src/operations.ts
CHANGED
|
@@ -5,11 +5,18 @@ import type { AgentEvent } from "./protocol";
|
|
|
5
5
|
/** What the agent can be busy with, as its messages name it. */
|
|
6
6
|
export type Operation = "a deployment" | "a login" | "a logout";
|
|
7
7
|
|
|
8
|
-
/** The agent runs one deployment, login or logout at a time. */
|
|
8
|
+
/** The agent runs one deployment, login or logout at a time, and none while it is held for an upgrade. */
|
|
9
9
|
export const createOperations = (log: (message: string) => void) => {
|
|
10
10
|
let busy: Operation | undefined;
|
|
11
|
+
let held = false;
|
|
11
12
|
|
|
12
13
|
const requireIdle = () => {
|
|
14
|
+
if (held) {
|
|
15
|
+
throw new AgentError(
|
|
16
|
+
"The plant agent is being upgraded; try again once it is back",
|
|
17
|
+
503,
|
|
18
|
+
);
|
|
19
|
+
}
|
|
13
20
|
if (busy) {
|
|
14
21
|
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
15
22
|
}
|
|
@@ -18,6 +25,15 @@ export const createOperations = (log: (message: string) => void) => {
|
|
|
18
25
|
return {
|
|
19
26
|
busy: () => busy,
|
|
20
27
|
requireIdle,
|
|
28
|
+
/** Refuses every operation from now on; fails while one runs. */
|
|
29
|
+
hold: () => {
|
|
30
|
+
requireIdle();
|
|
31
|
+
held = true;
|
|
32
|
+
},
|
|
33
|
+
release: () => {
|
|
34
|
+
held = false;
|
|
35
|
+
},
|
|
36
|
+
held: () => held,
|
|
21
37
|
/** Runs `run` as the agent's one operation. */
|
|
22
38
|
exclusive: async <Result>(
|
|
23
39
|
operation: Operation,
|
package/src/processes.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const isGone = (error: unknown) =>
|
|
2
|
+
error instanceof Error && "code" in error && error.code === "ESRCH";
|
|
3
|
+
|
|
4
|
+
/** Whether process `pid` exists; the agent can't wait on one an earlier agent started. */
|
|
5
|
+
export const processAlive = (pid: number) => {
|
|
6
|
+
try {
|
|
7
|
+
// Signal 0 checks that the process exists without signalling it.
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
} catch (error) {
|
|
11
|
+
return !isGone(error);
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Signals process `pid`, which may have exited since it was last seen. */
|
|
16
|
+
export const signalProcess = (pid: number, name: NodeJS.Signals) => {
|
|
17
|
+
try {
|
|
18
|
+
process.kill(pid, name);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (!isGone(error)) {
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
};
|
package/src/protocol.ts
CHANGED
|
@@ -204,12 +204,30 @@ export const clientHeaders = {
|
|
|
204
204
|
/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */
|
|
205
205
|
export const agentVersionHeader = "x-tsplc-agent-version";
|
|
206
206
|
|
|
207
|
+
/** Whether `version` is at least `minimum`, comparing major, minor and patch. */
|
|
208
|
+
const atLeast = (version: string, minimum: [number, number, number]) => {
|
|
209
|
+
const parts = version.split(/[.+-]/).slice(0, 3).map(Number);
|
|
210
|
+
for (const [index, wanted] of minimum.entries()) {
|
|
211
|
+
const part = parts[index] ?? 0;
|
|
212
|
+
if (part !== wanted) {
|
|
213
|
+
return part > wanted;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return true;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */
|
|
220
|
+
export const upgradesItself = (version: string | null) =>
|
|
221
|
+
version !== null && atLeast(version, [0, 5, 0]);
|
|
222
|
+
|
|
207
223
|
/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */
|
|
208
224
|
export const versionMismatch = (versions: {
|
|
209
225
|
agent: string | null;
|
|
210
226
|
client: string;
|
|
227
|
+
/** The agent has `tsplc-agent upgrade`. */
|
|
228
|
+
agentUpgrades: boolean;
|
|
211
229
|
}) =>
|
|
212
|
-
`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match:
|
|
230
|
+
`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
|
|
213
231
|
|
|
214
232
|
/** Who sent a request, as the client reports it. */
|
|
215
233
|
export const clientIdentity = (request: Request) => {
|
package/src/server-process.ts
CHANGED
|
@@ -1,71 +1,174 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
openSync,
|
|
5
|
+
renameSync,
|
|
6
|
+
statSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from "node:fs";
|
|
9
|
+
import { readFile, rm } from "node:fs/promises";
|
|
10
|
+
import { uptime } from "node:os";
|
|
1
11
|
import { dirname } from "node:path";
|
|
2
12
|
import { setTimeout as delay } from "node:timers/promises";
|
|
3
13
|
import type { Subprocess } from "bun";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import { processAlive, signalProcess } from "./processes";
|
|
4
16
|
|
|
5
17
|
const healthyWithinMs = 60_000;
|
|
6
18
|
/** Without a health URL, a server that stays up this long counts as started. */
|
|
7
19
|
const settleMs = 5000;
|
|
8
20
|
const restartDelayMs = 2000;
|
|
21
|
+
/** How often a server this agent didn't start is checked for having exited. */
|
|
22
|
+
const watchMs = 2000;
|
|
23
|
+
/** How long a server this agent didn't start may take to answer before another is started. */
|
|
24
|
+
const adoptWithinMs = 10_000;
|
|
25
|
+
/** How long a stopped server may take to exit. */
|
|
26
|
+
const stopWithinMs = 10_000;
|
|
27
|
+
/** A server's log rotates to `<file>.1`, replacing the one before, when a server starts past this size. */
|
|
28
|
+
const rotateBytes = 10 * 2 ** 20;
|
|
29
|
+
|
|
30
|
+
/** The running server's process, which a restarted agent takes over instead of starting another. */
|
|
31
|
+
const recordSchema = z.strictObject({
|
|
32
|
+
pid: z.int().positive(),
|
|
33
|
+
executable: z.string(),
|
|
34
|
+
/** When it started, in milliseconds since the epoch. */
|
|
35
|
+
startedAt: z.number(),
|
|
36
|
+
});
|
|
37
|
+
type ServerRecord = z.infer<typeof recordSchema>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether a recorded server may still be running as the agent left it: its process exists and it
|
|
41
|
+
* started since the machine booted, so its PID can't belong to a process from before a restart.
|
|
42
|
+
*/
|
|
43
|
+
export const mayStillRun = (
|
|
44
|
+
record: ServerRecord,
|
|
45
|
+
machine: {
|
|
46
|
+
now: number;
|
|
47
|
+
uptimeSeconds: number;
|
|
48
|
+
alive: (pid: number) => boolean;
|
|
49
|
+
},
|
|
50
|
+
) =>
|
|
51
|
+
record.startedAt > machine.now - machine.uptimeSeconds * 1000 &&
|
|
52
|
+
machine.alive(record.pid);
|
|
53
|
+
|
|
54
|
+
/** One running server: one this agent started, or one an earlier agent left running. */
|
|
55
|
+
interface Running {
|
|
56
|
+
executable: string;
|
|
57
|
+
pid: number;
|
|
58
|
+
alive: () => boolean;
|
|
59
|
+
exited: Promise<unknown>;
|
|
60
|
+
}
|
|
9
61
|
|
|
10
62
|
/**
|
|
11
63
|
* Runs the deployed server executable, restarting it whenever it exits, and swaps it for
|
|
12
64
|
* another release's. The server reads its own environment and secrets, as it would anywhere.
|
|
65
|
+
* It runs detached from the agent with its output appended to `output`, so an agent that
|
|
66
|
+
* restarts, to upgrade or after a crash, leaves the line's server running and takes it over.
|
|
13
67
|
*/
|
|
14
68
|
export const createServerSupervisor = (options: {
|
|
15
69
|
/** The server's `/health` route, which answers once it is listening. */
|
|
16
70
|
healthUrl?: string;
|
|
71
|
+
/** Where the running server's process is recorded for the next agent. */
|
|
72
|
+
record: string;
|
|
73
|
+
/** The file the server's output is appended to. */
|
|
74
|
+
output: string;
|
|
17
75
|
log: (message: string) => void;
|
|
18
76
|
}) => {
|
|
19
|
-
let current:
|
|
77
|
+
let current: Running | undefined;
|
|
78
|
+
|
|
79
|
+
// Written before anything else can happen, so an agent exiting next leaves it for the one after.
|
|
80
|
+
const writeRecord = (record: ServerRecord) =>
|
|
81
|
+
writeFileSync(options.record, JSON.stringify(record));
|
|
82
|
+
const readRecord = async () => {
|
|
83
|
+
if (!existsSync(options.record)) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
return recordSchema.safeParse(
|
|
87
|
+
await readFile(options.record, "utf8").then(
|
|
88
|
+
(text): unknown => JSON.parse(text),
|
|
89
|
+
() => undefined,
|
|
90
|
+
),
|
|
91
|
+
).data;
|
|
92
|
+
};
|
|
20
93
|
|
|
21
|
-
|
|
94
|
+
/** Restarts `running` once it exits, unless it was stopped or replaced first. */
|
|
95
|
+
const restartWhenExited = (running: Running, code: () => unknown) => {
|
|
96
|
+
void running.exited.then(() => {
|
|
97
|
+
if (current !== running) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
options.log(
|
|
101
|
+
`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`,
|
|
102
|
+
);
|
|
103
|
+
void delay(restartDelayMs).then(() => {
|
|
104
|
+
if (current === running) {
|
|
105
|
+
current = spawn(running.executable);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const spawn = (executable: string): Running => {
|
|
22
112
|
// A bundled server runs on the agent's own Bun; releases before bundles shipped an executable.
|
|
23
113
|
const command = executable.endsWith(".js")
|
|
24
114
|
? [process.execPath, executable]
|
|
25
115
|
: [executable];
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
current = { executable, process: spawn(executable) };
|
|
40
|
-
}
|
|
116
|
+
if (
|
|
117
|
+
existsSync(options.output) &&
|
|
118
|
+
statSync(options.output).size >= rotateBytes
|
|
119
|
+
) {
|
|
120
|
+
renameSync(options.output, `${options.output}.1`);
|
|
121
|
+
}
|
|
122
|
+
const output = openSync(options.output, "a");
|
|
123
|
+
const child: Subprocess = (() => {
|
|
124
|
+
try {
|
|
125
|
+
return Bun.spawn(command, {
|
|
126
|
+
cwd: dirname(executable),
|
|
127
|
+
detached: true,
|
|
128
|
+
stdio: ["ignore", output, output],
|
|
41
129
|
});
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
130
|
+
} finally {
|
|
131
|
+
closeSync(output);
|
|
132
|
+
}
|
|
133
|
+
})();
|
|
134
|
+
const running: Running = {
|
|
135
|
+
executable,
|
|
136
|
+
pid: child.pid,
|
|
137
|
+
alive: () => child.exitCode === null && child.signalCode === null,
|
|
138
|
+
exited: child.exited,
|
|
139
|
+
};
|
|
140
|
+
writeRecord({ pid: child.pid, executable, startedAt: Date.now() });
|
|
141
|
+
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
142
|
+
return running;
|
|
50
143
|
};
|
|
51
144
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
145
|
+
/** Watches a server an earlier agent started, which this one can't wait on. */
|
|
146
|
+
const adopt = (record: ServerRecord): Running => {
|
|
147
|
+
const exited = Promise.withResolvers<void>();
|
|
148
|
+
const watch = setInterval(() => {
|
|
149
|
+
if (!processAlive(record.pid)) {
|
|
150
|
+
clearInterval(watch);
|
|
151
|
+
exited.resolve();
|
|
152
|
+
}
|
|
153
|
+
}, watchMs);
|
|
154
|
+
// Watching doesn't keep an agent that is exiting alive.
|
|
155
|
+
watch.unref();
|
|
156
|
+
const running: Running = {
|
|
157
|
+
executable: record.executable,
|
|
158
|
+
pid: record.pid,
|
|
159
|
+
alive: () => processAlive(record.pid),
|
|
160
|
+
exited: exited.promise,
|
|
161
|
+
};
|
|
162
|
+
restartWhenExited(running, () => "unknown status");
|
|
163
|
+
return running;
|
|
60
164
|
};
|
|
61
165
|
|
|
62
|
-
const
|
|
166
|
+
const answers = async (alive: () => boolean, within: number) => {
|
|
63
167
|
if (!options.healthUrl) {
|
|
64
|
-
|
|
65
|
-
return child.exitCode === null;
|
|
168
|
+
return alive();
|
|
66
169
|
}
|
|
67
|
-
const deadline = Date.now() +
|
|
68
|
-
while (Date.now() < deadline &&
|
|
170
|
+
const deadline = Date.now() + within;
|
|
171
|
+
while (Date.now() < deadline && alive()) {
|
|
69
172
|
if (
|
|
70
173
|
await fetch(options.healthUrl).then(
|
|
71
174
|
(response) => response.ok,
|
|
@@ -79,9 +182,61 @@ export const createServerSupervisor = (options: {
|
|
|
79
182
|
return false;
|
|
80
183
|
};
|
|
81
184
|
|
|
185
|
+
const start = (executable: string) => {
|
|
186
|
+
current = spawn(executable);
|
|
187
|
+
return current;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const stop = async () => {
|
|
191
|
+
const running = current;
|
|
192
|
+
current = undefined;
|
|
193
|
+
if (!running) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
signalProcess(running.pid, "SIGTERM");
|
|
197
|
+
await Promise.race([running.exited, delay(stopWithinMs)]);
|
|
198
|
+
if (running.alive()) {
|
|
199
|
+
signalProcess(running.pid, "SIGKILL");
|
|
200
|
+
await running.exited;
|
|
201
|
+
}
|
|
202
|
+
await rm(options.record, { force: true });
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const healthy = async (running: Running) => {
|
|
206
|
+
if (!options.healthUrl) {
|
|
207
|
+
await delay(settleMs);
|
|
208
|
+
return running.alive();
|
|
209
|
+
}
|
|
210
|
+
return answers(running.alive, healthyWithinMs);
|
|
211
|
+
};
|
|
212
|
+
|
|
82
213
|
return {
|
|
83
|
-
|
|
214
|
+
/**
|
|
215
|
+
* Runs `executable`, taking over the server an earlier agent left running when that is the one
|
|
216
|
+
* still running and, with a health route, answering it.
|
|
217
|
+
*/
|
|
218
|
+
resume: async (executable: string) => {
|
|
219
|
+
const record = await readRecord();
|
|
220
|
+
if (
|
|
221
|
+
record?.executable === executable &&
|
|
222
|
+
mayStillRun(record, {
|
|
223
|
+
now: Date.now(),
|
|
224
|
+
uptimeSeconds: uptime(),
|
|
225
|
+
alive: processAlive,
|
|
226
|
+
}) &&
|
|
227
|
+
(await answers(() => processAlive(record.pid), adoptWithinMs))
|
|
228
|
+
) {
|
|
229
|
+
options.log(`Took over the running server (process ${record.pid})`);
|
|
230
|
+
current = adopt(record);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
start(executable);
|
|
234
|
+
},
|
|
84
235
|
stop,
|
|
236
|
+
/** Stops supervising the server and leaves it running, for the agent that replaces this one. */
|
|
237
|
+
leave: () => {
|
|
238
|
+
current = undefined;
|
|
239
|
+
},
|
|
85
240
|
/** Replaces the running server; if the new one doesn't come up, the previous one runs again. */
|
|
86
241
|
replace: async (executable: string) => {
|
|
87
242
|
const previous = current?.executable;
|
|
@@ -112,7 +267,7 @@ export const createServerSupervisor = (options: {
|
|
|
112
267
|
status: () =>
|
|
113
268
|
current && {
|
|
114
269
|
executable: current.executable,
|
|
115
|
-
running: current.
|
|
270
|
+
running: current.alive(),
|
|
116
271
|
},
|
|
117
272
|
};
|
|
118
273
|
};
|