@tsplc/tmp-agent 0.0.0-stage → 0.6.2
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 +26 -2
- package/dist/cli.js +4888 -0
- package/dist/cli.js.map +53 -0
- package/dist/client.js +514 -0
- package/dist/client.js.map +12 -0
- package/dist/index.js +3680 -0
- package/dist/index.js.map +41 -0
- package/package.json +61 -4
- package/src/access.ts +260 -0
- package/src/agent.ts +461 -0
- package/src/audit.ts +74 -0
- package/src/cli.ts +290 -0
- package/src/client.ts +407 -0
- package/src/codesys.ts +195 -0
- package/src/dashboard/index.ts +159 -0
- package/src/dashboard/ui/access.ts +191 -0
- package/src/dashboard/ui/actions.ts +207 -0
- package/src/dashboard/ui/api.ts +138 -0
- package/src/dashboard/ui/app.ts +41 -0
- package/src/dashboard/ui/approval.ts +131 -0
- package/src/dashboard/ui/audit.ts +115 -0
- package/src/dashboard/ui/contract.ts +19 -0
- package/src/dashboard/ui/dashboard.css +1332 -0
- package/src/dashboard/ui/deployment.ts +431 -0
- package/src/dashboard/ui/deployments.ts +319 -0
- package/src/dashboard/ui/details.ts +214 -0
- package/src/dashboard/ui/dom.ts +87 -0
- package/src/dashboard/ui/environment.ts +345 -0
- package/src/dashboard/ui/format.ts +124 -0
- package/src/dashboard/ui/logs.ts +126 -0
- package/src/dashboard/ui/main.ts +88 -0
- package/src/dashboard/ui/overlay.ts +144 -0
- package/src/dashboard/ui/shell.ts +185 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/debugging.ts +142 -0
- package/src/deploy.ts +203 -0
- package/src/deployments/health.ts +98 -0
- package/src/deployments/retention.ts +44 -0
- package/src/deployments/routes.ts +281 -0
- package/src/deployments/runner.ts +900 -0
- package/src/deployments/store.ts +209 -0
- package/src/deployments/submission.ts +78 -0
- package/src/discovery.ts +90 -0
- package/src/environment.ts +214 -0
- package/src/errors.ts +12 -0
- package/src/index.ts +36 -0
- package/src/instance.ts +51 -0
- package/src/login.ts +267 -0
- package/src/logs.ts +115 -0
- package/src/maintenance.ts +303 -0
- package/src/operations.ts +149 -0
- package/src/processes.ts +41 -0
- package/src/protocol.ts +557 -0
- package/src/releases.ts +414 -0
- package/src/restarts.ts +96 -0
- package/src/routes.ts +128 -0
- package/src/secrets.ts +174 -0
- package/src/server-process.ts +264 -0
- package/src/service.ts +194 -0
- package/src/sessions.ts +58 -0
- package/src/state.ts +126 -0
- package/src/tailscale.ts +112 -0
- package/src/terminal.ts +57 -0
- package/src/transfer.ts +94 -0
- package/src/upgrade.ts +153 -0
package/src/secrets.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, relative } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
type agentTokenEnv,
|
|
6
|
+
type Environment,
|
|
7
|
+
secretPlaceholder,
|
|
8
|
+
secretValue,
|
|
9
|
+
} from "@tsplc/config";
|
|
10
|
+
import type { ResolvedConfig } from "@tsplc/config/build";
|
|
11
|
+
import { escapeString } from "@tsplc/iec/st";
|
|
12
|
+
import { AgentError } from "./errors";
|
|
13
|
+
import type { Credentials, ReleaseManifest } from "./protocol";
|
|
14
|
+
import type { StoredRelease } from "./releases";
|
|
15
|
+
|
|
16
|
+
/** The agent's own Bun.secrets service, which holds the controller user and the agent's tokens. */
|
|
17
|
+
export const agentService = "tsplc-agent";
|
|
18
|
+
/** Where the dashboard stores the environment's secrets while the deployed release declares none. */
|
|
19
|
+
export const environmentService = "tsplc-agent-env";
|
|
20
|
+
/** The token that only reads from the agent. */
|
|
21
|
+
export const agentReadTokenEnv = "TSPLC_AGENT_READ_TOKEN";
|
|
22
|
+
export const controllerSecretNames = {
|
|
23
|
+
username: "controller-username",
|
|
24
|
+
password: "controller-password",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Agent setting `name`: its variable in `environment` when set, otherwise the value stored under the agent's service, or null. */
|
|
28
|
+
export const agentSetting = async (
|
|
29
|
+
name: typeof agentTokenEnv | typeof agentReadTokenEnv,
|
|
30
|
+
environment: Environment,
|
|
31
|
+
) =>
|
|
32
|
+
environment[name] ?? (await Bun.secrets.get({ service: agentService, name }));
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The token the deployed server is started with, made once and kept under the agent's service, so
|
|
36
|
+
* a server an earlier agent started still has a valid one.
|
|
37
|
+
*/
|
|
38
|
+
export const serverToken = async () => {
|
|
39
|
+
const name = "server-token";
|
|
40
|
+
const stored = await Bun.secrets.get({ service: agentService, name });
|
|
41
|
+
if (stored) {
|
|
42
|
+
return stored;
|
|
43
|
+
}
|
|
44
|
+
const token = randomBytes(32).toString("hex");
|
|
45
|
+
await Bun.secrets.set({ service: agentService, name, value: token });
|
|
46
|
+
return token;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** The controller user stored with `tsplc-agent secrets set-controller`, or null. */
|
|
50
|
+
export const storedCredentials = async (): Promise<Credentials | null> => {
|
|
51
|
+
const [username, password] = await Promise.all([
|
|
52
|
+
Bun.secrets.get({
|
|
53
|
+
service: agentService,
|
|
54
|
+
name: controllerSecretNames.username,
|
|
55
|
+
}),
|
|
56
|
+
Bun.secrets.get({
|
|
57
|
+
service: agentService,
|
|
58
|
+
name: controllerSecretNames.password,
|
|
59
|
+
}),
|
|
60
|
+
]);
|
|
61
|
+
return username && password ? { username, password } : null;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** The controller user a request sent, or the stored one when it sent null. */
|
|
65
|
+
export const controllerCredentials = async (sent: Credentials | null) => {
|
|
66
|
+
const credentials = sent ?? (await storedCredentials());
|
|
67
|
+
if (!credentials) {
|
|
68
|
+
throw new AgentError(
|
|
69
|
+
"No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there",
|
|
70
|
+
409,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return credentials;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** The release's secrets from Bun.secrets, by name. Fails naming every one that is missing. */
|
|
77
|
+
export const readSecrets = async (secrets: ReleaseManifest["secrets"]) => {
|
|
78
|
+
const values = new Map<string, string>();
|
|
79
|
+
if (!secrets) {
|
|
80
|
+
return values;
|
|
81
|
+
}
|
|
82
|
+
const { service } = secrets;
|
|
83
|
+
const missing: string[] = [];
|
|
84
|
+
for (const name of secrets.names) {
|
|
85
|
+
const value = await Bun.secrets.get({ service, name });
|
|
86
|
+
const valid = secretValue.safeParse(value);
|
|
87
|
+
if (!value) {
|
|
88
|
+
missing.push(name);
|
|
89
|
+
} else if (!valid.success) {
|
|
90
|
+
throw new AgentError(
|
|
91
|
+
`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(" and ")}`,
|
|
92
|
+
409,
|
|
93
|
+
);
|
|
94
|
+
} else {
|
|
95
|
+
values.set(name, value);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (missing.length) {
|
|
99
|
+
throw new AgentError(
|
|
100
|
+
`The plant PC has no ${missing.join(", ")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`,
|
|
101
|
+
409,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return values;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** The release's secrets that Bun.secrets holds, by name. */
|
|
108
|
+
const storedSecrets = async (secrets: ReleaseManifest["secrets"]) => {
|
|
109
|
+
if (!secrets) {
|
|
110
|
+
return {};
|
|
111
|
+
}
|
|
112
|
+
const stored = await Promise.all(
|
|
113
|
+
secrets.names.map(async (name) => ({
|
|
114
|
+
name,
|
|
115
|
+
value: await Bun.secrets.get({ service: secrets.service, name }),
|
|
116
|
+
})),
|
|
117
|
+
);
|
|
118
|
+
return Object.fromEntries(
|
|
119
|
+
stored.flatMap(({ name, value }): [string, string][] =>
|
|
120
|
+
value === null ? [] : [[name, value]],
|
|
121
|
+
),
|
|
122
|
+
);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The environment the server of `release` runs in, and so what the agent reads a variable of the
|
|
127
|
+
* release's as: `environment`, then the values of the target the release was built for, as the
|
|
128
|
+
* PLC's program got them, then the release's secrets that Bun.secrets holds.
|
|
129
|
+
*/
|
|
130
|
+
export const serverEnvironment = async (
|
|
131
|
+
{ manifest }: StoredRelease,
|
|
132
|
+
environment: Environment,
|
|
133
|
+
): Promise<Environment> => ({
|
|
134
|
+
...environment,
|
|
135
|
+
...manifest.values,
|
|
136
|
+
...(await storedSecrets(manifest.secrets)),
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
/** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */
|
|
140
|
+
const fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>
|
|
141
|
+
[...secrets].reduce(
|
|
142
|
+
// A replacer function, since a replacement string would read `$'` and `$$` as patterns.
|
|
143
|
+
(text, [name, value]) =>
|
|
144
|
+
text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")),
|
|
145
|
+
st,
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
/** The config with its ST copied to `directory`, the secrets filled in. */
|
|
149
|
+
export const withSecrets = async (
|
|
150
|
+
config: ResolvedConfig,
|
|
151
|
+
secrets: ReadonlyMap<string, string>,
|
|
152
|
+
directory: string,
|
|
153
|
+
): Promise<ResolvedConfig> => {
|
|
154
|
+
await rm(directory, { recursive: true, force: true });
|
|
155
|
+
for await (const path of new Bun.Glob("**/*").scan({
|
|
156
|
+
cwd: config.sourceDir,
|
|
157
|
+
dot: true,
|
|
158
|
+
})) {
|
|
159
|
+
const file = join(directory, path);
|
|
160
|
+
await mkdir(dirname(file), { recursive: true });
|
|
161
|
+
await writeFile(
|
|
162
|
+
file,
|
|
163
|
+
fillSecrets(
|
|
164
|
+
await readFile(join(config.sourceDir, path), "utf8"),
|
|
165
|
+
secrets,
|
|
166
|
+
),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
return {
|
|
170
|
+
...config,
|
|
171
|
+
sourceDir: directory,
|
|
172
|
+
entry: join(directory, relative(config.sourceDir, config.entry)),
|
|
173
|
+
};
|
|
174
|
+
};
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { rm } from "node:fs/promises";
|
|
2
|
+
import { uptime } from "node:os";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import type { Environment } from "@tsplc/config";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { errorMessage } from "./errors";
|
|
8
|
+
import { spawnWithLog } from "./logs";
|
|
9
|
+
import { processAlive, signalProcess, waitUntil } from "./processes";
|
|
10
|
+
import { readJsonFileIfValid, writeJsonFile } from "./state";
|
|
11
|
+
|
|
12
|
+
const healthyWithinMs = 60_000;
|
|
13
|
+
/** Without a health URL, a server that stays up this long counts as started. */
|
|
14
|
+
const settleMs = 5000;
|
|
15
|
+
const restartDelayMs = 2000;
|
|
16
|
+
/** How often a server this agent didn't start is checked for having exited. */
|
|
17
|
+
const watchMs = 2000;
|
|
18
|
+
/** How long a server this agent didn't start may take to answer before another is started. */
|
|
19
|
+
const adoptWithinMs = 10_000;
|
|
20
|
+
/** How long a stopped server may take to exit. */
|
|
21
|
+
const stopWithinMs = 10_000;
|
|
22
|
+
|
|
23
|
+
/** The running server's process, which a restarted agent takes over instead of starting another. */
|
|
24
|
+
const recordSchema = z.strictObject({
|
|
25
|
+
pid: z.int().positive(),
|
|
26
|
+
executable: z.string(),
|
|
27
|
+
/** When it started, in milliseconds since the epoch. */
|
|
28
|
+
startedAt: z.number(),
|
|
29
|
+
});
|
|
30
|
+
type ServerRecord = z.infer<typeof recordSchema>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whether a recorded server may still be running as the agent left it: its process exists and it
|
|
34
|
+
* started since the machine booted, so its PID can't belong to a process from before a restart.
|
|
35
|
+
*/
|
|
36
|
+
export const mayStillRun = (
|
|
37
|
+
record: ServerRecord,
|
|
38
|
+
machine: {
|
|
39
|
+
now: number;
|
|
40
|
+
uptimeSeconds: number;
|
|
41
|
+
alive: (pid: number) => boolean;
|
|
42
|
+
},
|
|
43
|
+
) =>
|
|
44
|
+
record.startedAt > machine.now - machine.uptimeSeconds * 1000 &&
|
|
45
|
+
machine.alive(record.pid);
|
|
46
|
+
|
|
47
|
+
/** One running server: one this agent started, or one an earlier agent left running. */
|
|
48
|
+
interface Running {
|
|
49
|
+
executable: string;
|
|
50
|
+
pid: number;
|
|
51
|
+
alive: () => boolean;
|
|
52
|
+
exited: Promise<unknown>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Runs the deployed server executable, restarting it whenever it exits, and swaps it for
|
|
57
|
+
* another release's. Each start reads the environment afresh, so a restart applies changed secrets.
|
|
58
|
+
* It runs detached from the agent with its output appended to `output`, so an agent that
|
|
59
|
+
* restarts, to upgrade or after a crash, leaves the line's server running and takes it over.
|
|
60
|
+
*/
|
|
61
|
+
export const createServerSupervisor = (options: {
|
|
62
|
+
/** The server's `/health` route, which answers once it is listening, or null for none. */
|
|
63
|
+
healthUrl: string | null;
|
|
64
|
+
/** Where the running server's process is recorded for the next agent. */
|
|
65
|
+
record: string;
|
|
66
|
+
/** The file the server's output is appended to. */
|
|
67
|
+
output: string;
|
|
68
|
+
/** The environment `executable` starts in. */
|
|
69
|
+
environment: (executable: string) => Promise<Environment>;
|
|
70
|
+
log: (message: string) => void;
|
|
71
|
+
}) => {
|
|
72
|
+
let current: Running | undefined;
|
|
73
|
+
|
|
74
|
+
/** The environment `executable` starts in now, or null after logging why it can't be read. */
|
|
75
|
+
const readEnvironment = (executable: string) =>
|
|
76
|
+
options.environment(executable).catch((error: unknown) => {
|
|
77
|
+
options.log(
|
|
78
|
+
`Starting the deployed server failed: ${errorMessage(error)}`,
|
|
79
|
+
);
|
|
80
|
+
return null;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
/** Restarts `running` once it exits, unless it was stopped or replaced first. */
|
|
84
|
+
const restartWhenExited = (running: Running, code: () => unknown) => {
|
|
85
|
+
void running.exited.then(() => {
|
|
86
|
+
if (current !== running) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
options.log(
|
|
90
|
+
`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`,
|
|
91
|
+
);
|
|
92
|
+
void delay(restartDelayMs).then(async () => {
|
|
93
|
+
if (current !== running) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const environment = await readEnvironment(running.executable);
|
|
97
|
+
if (current === running) {
|
|
98
|
+
current = environment
|
|
99
|
+
? spawn(running.executable, environment)
|
|
100
|
+
: undefined;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const spawn = (executable: string, environment: Environment): Running => {
|
|
107
|
+
// A bundled server runs on the agent's own Bun; releases before bundles shipped an executable.
|
|
108
|
+
const command = executable.endsWith(".js")
|
|
109
|
+
? [process.execPath, executable]
|
|
110
|
+
: [executable];
|
|
111
|
+
const child = spawnWithLog(command, options.output, {
|
|
112
|
+
cwd: dirname(executable),
|
|
113
|
+
env: environment,
|
|
114
|
+
detached: true,
|
|
115
|
+
});
|
|
116
|
+
const running: Running = {
|
|
117
|
+
executable,
|
|
118
|
+
pid: child.pid,
|
|
119
|
+
alive: () => child.exitCode === null && child.signalCode === null,
|
|
120
|
+
exited: child.exited,
|
|
121
|
+
};
|
|
122
|
+
// Written before anything else can happen, so an agent exiting next leaves it for the one after.
|
|
123
|
+
writeJsonFile(options.record, {
|
|
124
|
+
pid: child.pid,
|
|
125
|
+
executable,
|
|
126
|
+
startedAt: Date.now(),
|
|
127
|
+
} satisfies ServerRecord);
|
|
128
|
+
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
129
|
+
return running;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** Watches a server an earlier agent started, which this one can't wait on. */
|
|
133
|
+
const adopt = (record: ServerRecord): Running => {
|
|
134
|
+
const exited = Promise.withResolvers<void>();
|
|
135
|
+
const watch = setInterval(() => {
|
|
136
|
+
if (!processAlive(record.pid)) {
|
|
137
|
+
clearInterval(watch);
|
|
138
|
+
exited.resolve();
|
|
139
|
+
}
|
|
140
|
+
}, watchMs);
|
|
141
|
+
watch.unref();
|
|
142
|
+
const running: Running = {
|
|
143
|
+
executable: record.executable,
|
|
144
|
+
pid: record.pid,
|
|
145
|
+
alive: () => processAlive(record.pid),
|
|
146
|
+
exited: exited.promise,
|
|
147
|
+
};
|
|
148
|
+
restartWhenExited(running, () => "unknown status");
|
|
149
|
+
return running;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/** Whether the server answers its health route within `within`, giving up once it has exited. */
|
|
153
|
+
const answers = async (alive: () => boolean, within: number) => {
|
|
154
|
+
const { healthUrl } = options;
|
|
155
|
+
if (healthUrl === null) {
|
|
156
|
+
return alive();
|
|
157
|
+
}
|
|
158
|
+
const settled = await waitUntil(
|
|
159
|
+
async () =>
|
|
160
|
+
!alive() ||
|
|
161
|
+
(await fetch(healthUrl).then(
|
|
162
|
+
(response) => response.ok,
|
|
163
|
+
() => false,
|
|
164
|
+
)),
|
|
165
|
+
within,
|
|
166
|
+
);
|
|
167
|
+
return settled && alive();
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const start = (executable: string, environment: Environment) => {
|
|
171
|
+
current = spawn(executable, environment);
|
|
172
|
+
return current;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const stop = async () => {
|
|
176
|
+
const running = current;
|
|
177
|
+
current = undefined;
|
|
178
|
+
if (!running) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
signalProcess(running.pid, "SIGTERM");
|
|
182
|
+
await Promise.race([running.exited, delay(stopWithinMs)]);
|
|
183
|
+
if (running.alive()) {
|
|
184
|
+
signalProcess(running.pid, "SIGKILL");
|
|
185
|
+
await running.exited;
|
|
186
|
+
}
|
|
187
|
+
await rm(options.record, { force: true });
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const healthy = async (running: Running) => {
|
|
191
|
+
if (options.healthUrl === null) {
|
|
192
|
+
await delay(settleMs);
|
|
193
|
+
return running.alive();
|
|
194
|
+
}
|
|
195
|
+
return answers(running.alive, healthyWithinMs);
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
return {
|
|
199
|
+
healthUrl: options.healthUrl,
|
|
200
|
+
/**
|
|
201
|
+
* Runs `executable`, taking over the server an earlier agent left running when that is the one
|
|
202
|
+
* still running and, with a health route, answering it. One whose environment can't be read is
|
|
203
|
+
* logged and left stopped rather than failing the agent, which can still deploy another release.
|
|
204
|
+
*/
|
|
205
|
+
resume: async (executable: string) => {
|
|
206
|
+
const record = await readJsonFileIfValid(options.record, recordSchema);
|
|
207
|
+
if (
|
|
208
|
+
record?.executable === executable &&
|
|
209
|
+
mayStillRun(record, {
|
|
210
|
+
now: Date.now(),
|
|
211
|
+
uptimeSeconds: uptime(),
|
|
212
|
+
alive: processAlive,
|
|
213
|
+
}) &&
|
|
214
|
+
(await answers(() => processAlive(record.pid), adoptWithinMs))
|
|
215
|
+
) {
|
|
216
|
+
options.log(`Took over the running server (process ${record.pid})`);
|
|
217
|
+
current = adopt(record);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const environment = await readEnvironment(executable);
|
|
221
|
+
if (environment) {
|
|
222
|
+
start(executable, environment);
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
stop,
|
|
226
|
+
/** Stops supervising the server and leaves it running, for the agent that replaces this one. */
|
|
227
|
+
leave: () => {
|
|
228
|
+
current = undefined;
|
|
229
|
+
},
|
|
230
|
+
/** Replaces the running server; if the new one doesn't come up, the previous one runs again. */
|
|
231
|
+
replace: async (executable: string) => {
|
|
232
|
+
const previous = current;
|
|
233
|
+
const environment = await options.environment(executable);
|
|
234
|
+
await stop();
|
|
235
|
+
const { started, failure } = await (async () =>
|
|
236
|
+
healthy(start(executable, environment)))().then(
|
|
237
|
+
(answered) => ({ started: answered, failure: undefined }),
|
|
238
|
+
(error: unknown) => ({ started: false, failure: error }),
|
|
239
|
+
);
|
|
240
|
+
if (started) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
await stop();
|
|
244
|
+
const previousEnvironment =
|
|
245
|
+
previous && (await readEnvironment(previous.executable));
|
|
246
|
+
if (previous && previousEnvironment) {
|
|
247
|
+
start(previous.executable, previousEnvironment);
|
|
248
|
+
}
|
|
249
|
+
const reason =
|
|
250
|
+
failure instanceof Error
|
|
251
|
+
? failure.message
|
|
252
|
+
: `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
253
|
+
throw new Error(
|
|
254
|
+
`The new server failed: ${reason}. ${previousEnvironment ? "The previous one is running again." : ""}`.trim(),
|
|
255
|
+
{ cause: failure },
|
|
256
|
+
);
|
|
257
|
+
},
|
|
258
|
+
status: () =>
|
|
259
|
+
current
|
|
260
|
+
? { executable: current.executable, running: current.alive() }
|
|
261
|
+
: null,
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
export type ServerSupervisor = ReturnType<typeof createServerSupervisor>;
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { appendFile } from "node:fs/promises";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import type { Environment } from "@tsplc/config";
|
|
4
|
+
import { restartStatus } from "./instance";
|
|
5
|
+
import { spawnWithLog } from "./logs";
|
|
6
|
+
|
|
7
|
+
/** The Task Scheduler task that runs the agent as a service. */
|
|
8
|
+
export const serviceName = "tsplc-agent";
|
|
9
|
+
|
|
10
|
+
/** Set in the environment of a `serve` that `service run` started, which says so in its record. */
|
|
11
|
+
export const supervisedEnv = "TSPLC_AGENT_SUPERVISED";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One argument of a Windows command line, quoted so that a program's C runtime
|
|
15
|
+
* (CommandLineToArgvW) reads it back unchanged: backslashes double only before a quote.
|
|
16
|
+
*/
|
|
17
|
+
export const quoteWindowsArgument = (argument: string) => {
|
|
18
|
+
if (argument !== "" && !/[\s"]/.test(argument)) {
|
|
19
|
+
return argument;
|
|
20
|
+
}
|
|
21
|
+
const escaped = argument
|
|
22
|
+
.replace(/(\\*)"/g, '$1$1\\"')
|
|
23
|
+
.replace(/(\\+)$/, "$1$1");
|
|
24
|
+
return `"${escaped}"`;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const escapeXml = (text: string) =>
|
|
28
|
+
text
|
|
29
|
+
.replaceAll("&", "&")
|
|
30
|
+
.replaceAll("<", "<")
|
|
31
|
+
.replaceAll(">", ">")
|
|
32
|
+
.replaceAll('"', """);
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The Task Scheduler definition of the agent's service: `bun script service run <serve…>` as
|
|
36
|
+
* `user`, at boot whether or not anyone logs on, so the line's server runs after a power cut.
|
|
37
|
+
* The password logon keeps the user's Credential Manager, where Bun.secrets keeps the agent's
|
|
38
|
+
* token, readable. `service run` restarts the agent itself; Task Scheduler restarts `service run`
|
|
39
|
+
* if it fails to start. It runs without a time limit, and only one at a time.
|
|
40
|
+
*/
|
|
41
|
+
export const taskDefinition = (task: {
|
|
42
|
+
bun: string;
|
|
43
|
+
script: string;
|
|
44
|
+
serve: string[];
|
|
45
|
+
user: string;
|
|
46
|
+
workingDirectory: string;
|
|
47
|
+
}) => {
|
|
48
|
+
const argumentsText = [task.script, "service", "run", ...task.serve]
|
|
49
|
+
.map(quoteWindowsArgument)
|
|
50
|
+
.join(" ");
|
|
51
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
52
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
53
|
+
<RegistrationInfo>
|
|
54
|
+
<Description>tsPLC plant agent: deploys to the controller and runs the line's server</Description>
|
|
55
|
+
</RegistrationInfo>
|
|
56
|
+
<Triggers>
|
|
57
|
+
<BootTrigger>
|
|
58
|
+
<Enabled>true</Enabled>
|
|
59
|
+
</BootTrigger>
|
|
60
|
+
</Triggers>
|
|
61
|
+
<Principals>
|
|
62
|
+
<Principal id="Author">
|
|
63
|
+
<UserId>${escapeXml(task.user)}</UserId>
|
|
64
|
+
<LogonType>Password</LogonType>
|
|
65
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
66
|
+
</Principal>
|
|
67
|
+
</Principals>
|
|
68
|
+
<Settings>
|
|
69
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
70
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
71
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
72
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
73
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
74
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
75
|
+
<IdleSettings>
|
|
76
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
77
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
78
|
+
</IdleSettings>
|
|
79
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
80
|
+
<Enabled>true</Enabled>
|
|
81
|
+
<Hidden>false</Hidden>
|
|
82
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
83
|
+
<WakeToRun>false</WakeToRun>
|
|
84
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
85
|
+
<Priority>7</Priority>
|
|
86
|
+
<RestartOnFailure>
|
|
87
|
+
<Interval>PT1M</Interval>
|
|
88
|
+
<Count>999</Count>
|
|
89
|
+
</RestartOnFailure>
|
|
90
|
+
</Settings>
|
|
91
|
+
<Actions Context="Author">
|
|
92
|
+
<Exec>
|
|
93
|
+
<Command>${escapeXml(task.bun)}</Command>
|
|
94
|
+
<Arguments>${escapeXml(argumentsText)}</Arguments>
|
|
95
|
+
<WorkingDirectory>${escapeXml(task.workingDirectory)}</WorkingDirectory>
|
|
96
|
+
</Exec>
|
|
97
|
+
</Actions>
|
|
98
|
+
</Task>
|
|
99
|
+
`;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** A task definition as `schtasks /XML` reads it: UTF-16 with a byte order mark. */
|
|
103
|
+
export const taskFile = (definition: string) =>
|
|
104
|
+
Buffer.concat([
|
|
105
|
+
Buffer.from([0xff, 0xfe]),
|
|
106
|
+
Buffer.from(definition, "utf16le"),
|
|
107
|
+
]);
|
|
108
|
+
|
|
109
|
+
/** The schtasks commands the service's lifecycle runs, as Task Scheduler names them. */
|
|
110
|
+
export const schtasks = {
|
|
111
|
+
/** Registers `file` as `user`; schtasks asks for the password, which it keeps for boot. */
|
|
112
|
+
create: (file: string, user: string) => [
|
|
113
|
+
"schtasks",
|
|
114
|
+
"/Create",
|
|
115
|
+
"/TN",
|
|
116
|
+
serviceName,
|
|
117
|
+
"/XML",
|
|
118
|
+
file,
|
|
119
|
+
"/RU",
|
|
120
|
+
user,
|
|
121
|
+
"/RP",
|
|
122
|
+
"*",
|
|
123
|
+
"/F",
|
|
124
|
+
],
|
|
125
|
+
run: () => ["schtasks", "/Run", "/TN", serviceName],
|
|
126
|
+
end: () => ["schtasks", "/End", "/TN", serviceName],
|
|
127
|
+
remove: () => ["schtasks", "/Delete", "/TN", serviceName, "/F"],
|
|
128
|
+
query: () => ["schtasks", "/Query", "/TN", serviceName, "/FO", "LIST", "/V"],
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** An agent that ran this long before it failed is started again at once. */
|
|
132
|
+
const steadyMs = 60_000;
|
|
133
|
+
|
|
134
|
+
/** How long `service run` waits before starting an agent that failed again. */
|
|
135
|
+
export const restartDelay = (exits: {
|
|
136
|
+
/** How long the agent that failed ran. */
|
|
137
|
+
ranMs: number;
|
|
138
|
+
/** How many agents in a row, this one included, failed within `steadyMs` of starting. */
|
|
139
|
+
quickExits: number;
|
|
140
|
+
}) => {
|
|
141
|
+
if (exits.ranMs >= steadyMs) {
|
|
142
|
+
return 1000;
|
|
143
|
+
}
|
|
144
|
+
return Math.min(5000 * 2 ** (exits.quickExits - 1), 60_000);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const stampedLine = (message: string) =>
|
|
148
|
+
`${new Date().toISOString()} ${message}\n`;
|
|
149
|
+
|
|
150
|
+
/** Appends a timestamped line to the agent log. */
|
|
151
|
+
const logLine = (file: string, message: string) =>
|
|
152
|
+
appendFile(file, stampedLine(message));
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Runs `serve` with `arguments`, writing its output to `log`, and starts it again whenever it
|
|
156
|
+
* exits: at once when it exits to be restarted, as after an upgrade, which re-reads the installed
|
|
157
|
+
* agent; after a growing delay when it fails; never when it exits as asked to stop.
|
|
158
|
+
*/
|
|
159
|
+
export const superviseAgent = async (options: {
|
|
160
|
+
command: string[];
|
|
161
|
+
log: string;
|
|
162
|
+
/** The environment the agent runs in, which also says it is supervised. */
|
|
163
|
+
environment: Environment;
|
|
164
|
+
/** Waits between restarts; real time by default. */
|
|
165
|
+
wait?: (milliseconds: number) => Promise<unknown>;
|
|
166
|
+
}) => {
|
|
167
|
+
const wait = options.wait ?? delay;
|
|
168
|
+
let quickExits = 0;
|
|
169
|
+
while (true) {
|
|
170
|
+
const started = Date.now();
|
|
171
|
+
const child = spawnWithLog(options.command, options.log, {
|
|
172
|
+
env: { ...options.environment, [supervisedEnv]: "1" },
|
|
173
|
+
heading: stampedLine(`Starting ${options.command.join(" ")}`),
|
|
174
|
+
});
|
|
175
|
+
const status = await child.exited;
|
|
176
|
+
const ranMs = Date.now() - started;
|
|
177
|
+
if (status === 0) {
|
|
178
|
+
await logLine(options.log, "The agent stopped as asked");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (status === restartStatus) {
|
|
182
|
+
quickExits = 0;
|
|
183
|
+
await logLine(options.log, "The agent exited to restart");
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
quickExits = ranMs < steadyMs ? quickExits + 1 : 0;
|
|
187
|
+
const pause = restartDelay({ ranMs, quickExits });
|
|
188
|
+
await logLine(
|
|
189
|
+
options.log,
|
|
190
|
+
`The agent exited (${status}); starting it again in ${pause / 1000} s`,
|
|
191
|
+
);
|
|
192
|
+
await wait(pause);
|
|
193
|
+
}
|
|
194
|
+
};
|
package/src/sessions.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import type { Identity } from "./protocol";
|
|
3
|
+
|
|
4
|
+
/** The cookie a signed-in browser sends: a random session id, never a token. */
|
|
5
|
+
export const sessionCookie = "tsplc_session";
|
|
6
|
+
|
|
7
|
+
/** How long a browser stays signed in. */
|
|
8
|
+
export const sessionLifetimeMs = 12 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Browsers signed in with a token, kept in memory: restarting the agent signs every browser out.
|
|
12
|
+
*/
|
|
13
|
+
export const createSessions = (now: () => number) => {
|
|
14
|
+
const sessions = new Map<string, { identity: Identity; expires: number }>();
|
|
15
|
+
|
|
16
|
+
const sessionId = (request: Request) =>
|
|
17
|
+
new Bun.CookieMap(request.headers.get("cookie") ?? "").get(sessionCookie);
|
|
18
|
+
|
|
19
|
+
const cookie = (value: string, maxAgeMs: number) =>
|
|
20
|
+
new Bun.Cookie(sessionCookie, value, {
|
|
21
|
+
httpOnly: true,
|
|
22
|
+
sameSite: "strict",
|
|
23
|
+
path: "/",
|
|
24
|
+
maxAge: Math.floor(maxAgeMs / 1000),
|
|
25
|
+
}).serialize();
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
/** Signs a browser in as `identity`; the answer sets the returned cookie. */
|
|
29
|
+
open: (identity: Identity) => {
|
|
30
|
+
const time = now();
|
|
31
|
+
for (const [id, { expires }] of sessions) {
|
|
32
|
+
if (expires <= time) {
|
|
33
|
+
sessions.delete(id);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const id = randomBytes(32).toString("base64url");
|
|
37
|
+
sessions.set(id, { identity, expires: time + sessionLifetimeMs });
|
|
38
|
+
return cookie(id, sessionLifetimeMs);
|
|
39
|
+
},
|
|
40
|
+
/** Who the request's cookie signed in, while the session lasts. */
|
|
41
|
+
find: (request: Request) => {
|
|
42
|
+
const id = sessionId(request);
|
|
43
|
+
const session = id === null ? undefined : sessions.get(id);
|
|
44
|
+
if (!session || session.expires <= now()) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
return session.identity;
|
|
48
|
+
},
|
|
49
|
+
/** Ends the request's session; the answer sets the returned cookie, which clears it. */
|
|
50
|
+
close: (request: Request) => {
|
|
51
|
+
const id = sessionId(request);
|
|
52
|
+
if (id !== null) {
|
|
53
|
+
sessions.delete(id);
|
|
54
|
+
}
|
|
55
|
+
return cookie("", 0);
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
};
|