@tsplc/tmp-agent 0.0.0-stage → 0.6.3
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/cli.ts
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { configureDocker, configureGateway } from "@tsplc/build";
|
|
7
|
+
import { agentTokenEnv } from "@tsplc/config";
|
|
8
|
+
import { tcpPort } from "@tsplc/config/build";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { readAccessConfig } from "./access";
|
|
11
|
+
import { createAgent } from "./agent";
|
|
12
|
+
import { type Instance, removeInstance, restartStatus } from "./instance";
|
|
13
|
+
import { serviceCommand, upgradeCommand } from "./maintenance";
|
|
14
|
+
import { type AccessConfig, roleSchema, tsplcVersion } from "./protocol";
|
|
15
|
+
import {
|
|
16
|
+
agentReadTokenEnv,
|
|
17
|
+
agentService,
|
|
18
|
+
agentSetting,
|
|
19
|
+
controllerSecretNames,
|
|
20
|
+
serverToken,
|
|
21
|
+
} from "./secrets";
|
|
22
|
+
import { supervisedEnv } from "./service";
|
|
23
|
+
import { openState, statePaths, writeJsonFile } from "./state";
|
|
24
|
+
import { askCredentials, askSecret } from "./terminal";
|
|
25
|
+
import { versionSchema } from "./upgrade";
|
|
26
|
+
|
|
27
|
+
const usage = `tsplc-agent setup [--if-needed]
|
|
28
|
+
tsplc-agent serve --listen host:port [--state directory] [--server-health url] [--bulk-import]
|
|
29
|
+
tsplc-agent upgrade [version] [--state directory]
|
|
30
|
+
tsplc-agent service install|uninstall|status [serve options] [--stop-server]
|
|
31
|
+
tsplc-agent secrets set|delete <name> [--service ${agentService}]
|
|
32
|
+
tsplc-agent secrets set-controller
|
|
33
|
+
tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none> [--state directory]
|
|
34
|
+
|
|
35
|
+
setup Builds the CODESYS builder and gateway images, keeping each that is already right for
|
|
36
|
+
this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so
|
|
37
|
+
only a release that changes the image's recipe (the CODESYS installation, Bun or the
|
|
38
|
+
container's third-party packages) needs it; the agent says so when it does. --if-needed
|
|
39
|
+
also keeps an image from before tsPLC 0.5.0 whose packages match.
|
|
40
|
+
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
41
|
+
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
42
|
+
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
43
|
+
TSPLC_AGENT_READ_TOKEN, as long, only reads: the debugger at /debug, GET /status
|
|
44
|
+
and the dashboard.
|
|
45
|
+
Each comes from its environment variable, or else from \`secrets set\` under ${agentService}.
|
|
46
|
+
--bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
|
|
47
|
+
in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
|
|
48
|
+
The line's server writes to logs/server.log in the state directory.
|
|
49
|
+
upgrade Installs @tsplc/agent at version (latest by default) with the bun or npm that installed
|
|
50
|
+
this one, runs its setup if it needs one, and restarts the running agent on it. It
|
|
51
|
+
refuses while a deployment runs or a login is open, and leaves the line's server running
|
|
52
|
+
and the controller untouched.
|
|
53
|
+
service Runs the agent as a Windows service: a Task Scheduler task that starts it at boot as
|
|
54
|
+
you, whether or not anyone logs on, and starts it again if it exits. install takes the
|
|
55
|
+
serve options and asks for your Windows password; run install and uninstall in a
|
|
56
|
+
PowerShell opened with Run as administrator, signed in as the user the agent runs as.
|
|
57
|
+
The agent's output goes to logs/agent.log in the state directory. uninstall leaves the
|
|
58
|
+
line's server running unless --stop-server.
|
|
59
|
+
secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
|
|
60
|
+
--service, or deletes it. set-controller stores the controller user, which deployments
|
|
61
|
+
and logins then use when they send none. Run it as the user the agent runs as.
|
|
62
|
+
access Who on the tailnet may use the dashboard, by Tailscale login: viewer reads, deployer
|
|
63
|
+
also deploys and restarts the server, admin also manages variables and access. default
|
|
64
|
+
gives every other tailnet member a role, none by default. The full token is an admin,
|
|
65
|
+
the read token a viewer, and a request from this PC an admin. The agent applies a
|
|
66
|
+
change at once.`;
|
|
67
|
+
|
|
68
|
+
const { values, positionals } = parseArgs({
|
|
69
|
+
allowPositionals: true,
|
|
70
|
+
options: {
|
|
71
|
+
help: { type: "boolean", short: "h" },
|
|
72
|
+
listen: { type: "string" },
|
|
73
|
+
state: { type: "string" },
|
|
74
|
+
"server-health": { type: "string" },
|
|
75
|
+
"bulk-import": { type: "boolean" },
|
|
76
|
+
service: { type: "string" },
|
|
77
|
+
"if-needed": { type: "boolean" },
|
|
78
|
+
"stop-server": { type: "boolean" },
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
const [command, ...args] = positionals;
|
|
82
|
+
if (!command || values.help) {
|
|
83
|
+
console.log(usage);
|
|
84
|
+
process.exit(0);
|
|
85
|
+
}
|
|
86
|
+
const takesArguments: Record<string, number> = {
|
|
87
|
+
secrets: 3,
|
|
88
|
+
access: 3,
|
|
89
|
+
upgrade: 1,
|
|
90
|
+
service: 1,
|
|
91
|
+
};
|
|
92
|
+
if (args.length > (takesArguments[command] ?? 0)) {
|
|
93
|
+
throw new Error(`Too many arguments for ${command}. See tsplc-agent --help.`);
|
|
94
|
+
}
|
|
95
|
+
const stateDirectory = values.state ?? join(homedir(), ".tsplc-agent");
|
|
96
|
+
|
|
97
|
+
/** Wildcard listen addresses, and the loopback a process on this PC reaches them by. */
|
|
98
|
+
const loopbackFor: Record<string, string> = {
|
|
99
|
+
"0.0.0.0": "127.0.0.1",
|
|
100
|
+
"::": "::1",
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** Where a process on this PC, such as the deployed server, reaches the agent. */
|
|
104
|
+
const reachableUrl = (hostname: string, port: number) => {
|
|
105
|
+
const bare = hostname.replace(/^\[(.*)\]$/, "$1");
|
|
106
|
+
const host = loopbackFor[bare] ?? bare;
|
|
107
|
+
return `http://${host.includes(":") ? `[${host}]` : host}:${port}/`;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** The serve options as given, which the service and an upgraded agent repeat. */
|
|
111
|
+
const serveOptions = () => {
|
|
112
|
+
const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
|
|
113
|
+
const port = tcpPort.safeParse(Number(portText));
|
|
114
|
+
if (!hostname || !port.success) {
|
|
115
|
+
throw new Error("--listen host:port is required, with a TCP port.");
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
hostname,
|
|
119
|
+
port: port.data,
|
|
120
|
+
args: [
|
|
121
|
+
"--listen",
|
|
122
|
+
`${hostname}:${port.data}`,
|
|
123
|
+
...(values.state ? ["--state", values.state] : []),
|
|
124
|
+
...(values["server-health"]
|
|
125
|
+
? ["--server-health", values["server-health"]]
|
|
126
|
+
: []),
|
|
127
|
+
...(values["bulk-import"] ? ["--bulk-import"] : []),
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
if (command === "setup") {
|
|
133
|
+
await configureDocker({
|
|
134
|
+
keepUnverified: values["if-needed"] ?? false,
|
|
135
|
+
winetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,
|
|
136
|
+
});
|
|
137
|
+
await configureGateway();
|
|
138
|
+
} else if (command === "serve") {
|
|
139
|
+
const { hostname, port, args: serve } = serveOptions();
|
|
140
|
+
const token = z
|
|
141
|
+
.string({
|
|
142
|
+
error: `Set ${agentTokenEnv}, or store it with tsplc-agent secrets set ${agentTokenEnv}`,
|
|
143
|
+
})
|
|
144
|
+
.min(32, `${agentTokenEnv} must be at least 32 characters`)
|
|
145
|
+
.parse(await agentSetting(agentTokenEnv, process.env));
|
|
146
|
+
const readToken = z
|
|
147
|
+
.string()
|
|
148
|
+
.min(32, `${agentReadTokenEnv} must be at least 32 characters`)
|
|
149
|
+
.refine(
|
|
150
|
+
(value) => value !== token,
|
|
151
|
+
`${agentReadTokenEnv} must differ from ${agentTokenEnv}`,
|
|
152
|
+
)
|
|
153
|
+
.nullable()
|
|
154
|
+
.parse(await agentSetting(agentReadTokenEnv, process.env));
|
|
155
|
+
const { paths } = await openState(stateDirectory);
|
|
156
|
+
const agent = await createAgent({
|
|
157
|
+
state: stateDirectory,
|
|
158
|
+
token,
|
|
159
|
+
readToken,
|
|
160
|
+
serverHealthUrl: values["server-health"] ?? null,
|
|
161
|
+
bulkImport: values["bulk-import"] ?? false,
|
|
162
|
+
environment: process.env,
|
|
163
|
+
serverAccess: {
|
|
164
|
+
url: reachableUrl(hostname, port),
|
|
165
|
+
token: await serverToken(),
|
|
166
|
+
},
|
|
167
|
+
log: (message) => console.log(`${new Date().toISOString()} ${message}`),
|
|
168
|
+
exit: ({ restart }) => {
|
|
169
|
+
void removeInstance(paths.agent, process.pid).then(() =>
|
|
170
|
+
process.exit(restart ? restartStatus : 0),
|
|
171
|
+
);
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
const server = Bun.serve({
|
|
175
|
+
hostname,
|
|
176
|
+
port,
|
|
177
|
+
fetch: (request, server) => agent.fetch(request, server.requestIP(request)),
|
|
178
|
+
// Deployments stream for minutes and upload a server executable.
|
|
179
|
+
idleTimeout: 0,
|
|
180
|
+
maxRequestBodySize: 2 ** 30,
|
|
181
|
+
});
|
|
182
|
+
writeJsonFile(paths.agent, {
|
|
183
|
+
pid: process.pid,
|
|
184
|
+
version: tsplcVersion,
|
|
185
|
+
url: server.url.href,
|
|
186
|
+
serve,
|
|
187
|
+
supervised: process.env[supervisedEnv] === "1",
|
|
188
|
+
startedAt: new Date().toISOString(),
|
|
189
|
+
} satisfies Instance);
|
|
190
|
+
console.log(`tsPLC agent ${tsplcVersion} listening on ${server.url}`);
|
|
191
|
+
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
192
|
+
process.on(signal, () => {
|
|
193
|
+
void agent
|
|
194
|
+
.stop()
|
|
195
|
+
.then(() => removeInstance(paths.agent, process.pid))
|
|
196
|
+
.then(() => process.exit(0));
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
} else if (command === "upgrade") {
|
|
200
|
+
await upgradeCommand({
|
|
201
|
+
version: versionSchema.parse(args[0] ?? "latest"),
|
|
202
|
+
state: stateDirectory,
|
|
203
|
+
environment: process.env,
|
|
204
|
+
});
|
|
205
|
+
} else if (command === "service") {
|
|
206
|
+
const action = args[0];
|
|
207
|
+
await serviceCommand({
|
|
208
|
+
action,
|
|
209
|
+
state: stateDirectory,
|
|
210
|
+
serve: action === "install" || action === "run" ? serveOptions().args : [],
|
|
211
|
+
stopServer: values["stop-server"] ?? false,
|
|
212
|
+
environment: process.env,
|
|
213
|
+
});
|
|
214
|
+
} else if (command === "secrets") {
|
|
215
|
+
const [action, name, ...extra] = args;
|
|
216
|
+
const service = values.service ?? agentService;
|
|
217
|
+
if (action === "set" && name && !extra.length) {
|
|
218
|
+
await Bun.secrets.set({
|
|
219
|
+
service,
|
|
220
|
+
name,
|
|
221
|
+
value: await askSecret(`${name}: `),
|
|
222
|
+
});
|
|
223
|
+
} else if (action === "delete" && name && !extra.length) {
|
|
224
|
+
if (!(await Bun.secrets.delete({ service, name }))) {
|
|
225
|
+
throw new Error(`Service ${service} has no ${name}.`);
|
|
226
|
+
}
|
|
227
|
+
} else if (action === "set-controller" && !name) {
|
|
228
|
+
const { username, password } = await askCredentials();
|
|
229
|
+
await Bun.secrets.set({
|
|
230
|
+
service: agentService,
|
|
231
|
+
name: controllerSecretNames.username,
|
|
232
|
+
value: username,
|
|
233
|
+
});
|
|
234
|
+
await Bun.secrets.set({
|
|
235
|
+
service: agentService,
|
|
236
|
+
name: controllerSecretNames.password,
|
|
237
|
+
value: password,
|
|
238
|
+
});
|
|
239
|
+
} else {
|
|
240
|
+
throw new Error(
|
|
241
|
+
"Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller",
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
} else if (command === "access") {
|
|
245
|
+
const file = statePaths(stateDirectory).access;
|
|
246
|
+
const config = await readAccessConfig(file);
|
|
247
|
+
const [action, first, second, ...extra] = args;
|
|
248
|
+
const change = ((): AccessConfig | null => {
|
|
249
|
+
if (action === "grant" && first && second && !extra.length) {
|
|
250
|
+
return {
|
|
251
|
+
...config,
|
|
252
|
+
roles: { ...config.roles, [first]: roleSchema.parse(second) },
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
if (action === "revoke" && first && !second) {
|
|
256
|
+
if (!(first in config.roles)) {
|
|
257
|
+
throw new Error(`${first} has no role.`);
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
...config,
|
|
261
|
+
roles: Object.fromEntries(
|
|
262
|
+
Object.entries(config.roles).filter(([login]) => login !== first),
|
|
263
|
+
),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (action === "default" && first && !second) {
|
|
267
|
+
return {
|
|
268
|
+
...config,
|
|
269
|
+
tailnetDefault: first === "none" ? null : roleSchema.parse(first),
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
if (action === "list" && !first) {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
throw new Error(
|
|
276
|
+
"Usage: tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none>",
|
|
277
|
+
);
|
|
278
|
+
})();
|
|
279
|
+
if (change) {
|
|
280
|
+
await mkdir(stateDirectory, { recursive: true });
|
|
281
|
+
writeJsonFile(file, change);
|
|
282
|
+
}
|
|
283
|
+
const shown = change ?? config;
|
|
284
|
+
for (const [login, role] of Object.entries(shown.roles)) {
|
|
285
|
+
console.log(`${login}\t${role}`);
|
|
286
|
+
}
|
|
287
|
+
console.log(`Other tailnet members: ${shown.tailnetDefault ?? "none"}`);
|
|
288
|
+
} else {
|
|
289
|
+
throw new Error(`Unknown command ${command}.`);
|
|
290
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { hostname, userInfo } from "node:os";
|
|
2
|
+
import {
|
|
3
|
+
type LoginCommand,
|
|
4
|
+
loginResultSchema,
|
|
5
|
+
type Rollback,
|
|
6
|
+
workerScriptsDigest,
|
|
7
|
+
} from "@tsplc/build";
|
|
8
|
+
import { plantVariablesSchema } from "@tsplc/config";
|
|
9
|
+
import { parseEventStream } from "@tsplc/debug/api";
|
|
10
|
+
import {
|
|
11
|
+
type ControllerRestart,
|
|
12
|
+
controllerRestartPath,
|
|
13
|
+
controllerRestartReplySchema,
|
|
14
|
+
refusalMessage,
|
|
15
|
+
} from "@tsplc/server/plant-agent";
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import {
|
|
18
|
+
type AgentExit,
|
|
19
|
+
agentExitPath,
|
|
20
|
+
agentHoldPath,
|
|
21
|
+
agentVersionHeader,
|
|
22
|
+
type Comparison,
|
|
23
|
+
type Credentials,
|
|
24
|
+
clientHeaders,
|
|
25
|
+
comparisonSchema,
|
|
26
|
+
type DeploymentEvent,
|
|
27
|
+
type DeploymentMode,
|
|
28
|
+
type DeployOptions,
|
|
29
|
+
deploymentApiPath,
|
|
30
|
+
deploymentCreatedSchema,
|
|
31
|
+
deploymentListSchema,
|
|
32
|
+
deploymentLogLineSchema,
|
|
33
|
+
deploymentRecordSchema,
|
|
34
|
+
deploymentsApiPath,
|
|
35
|
+
discoveredControllerSchema,
|
|
36
|
+
eventSchema,
|
|
37
|
+
logoutSchema,
|
|
38
|
+
networkInterfaceSchema,
|
|
39
|
+
type ReleaseManifest,
|
|
40
|
+
type ReleaseUpload,
|
|
41
|
+
releaseSchema,
|
|
42
|
+
releaseUploadType,
|
|
43
|
+
statusPath,
|
|
44
|
+
statusSchema,
|
|
45
|
+
type Target,
|
|
46
|
+
targetSchema,
|
|
47
|
+
tsplcVersion,
|
|
48
|
+
upgradesItself,
|
|
49
|
+
variableSchema,
|
|
50
|
+
versionMismatch,
|
|
51
|
+
} from "./protocol";
|
|
52
|
+
import {
|
|
53
|
+
bucketDigests,
|
|
54
|
+
encodeUpload,
|
|
55
|
+
fileBucket,
|
|
56
|
+
type ReleaseContent,
|
|
57
|
+
shortDigest,
|
|
58
|
+
} from "./transfer";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A failed agent operation; `downloadRequired` means only a full download can deploy, and
|
|
62
|
+
* `rollback` what became of the controller after a download failed mid-transfer.
|
|
63
|
+
*/
|
|
64
|
+
export class AgentOperationError extends Error {
|
|
65
|
+
readonly downloadRequired: boolean;
|
|
66
|
+
readonly rollback: Rollback | undefined;
|
|
67
|
+
|
|
68
|
+
constructor(
|
|
69
|
+
message: string,
|
|
70
|
+
{
|
|
71
|
+
downloadRequired = false,
|
|
72
|
+
rollback,
|
|
73
|
+
}: { downloadRequired?: boolean; rollback?: Rollback } = {},
|
|
74
|
+
) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.downloadRequired = downloadRequired;
|
|
77
|
+
this.rollback = rollback;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The agent can't be reached, or the connection to it broke; trying again may succeed. */
|
|
82
|
+
export class AgentUnreachable extends Error {}
|
|
83
|
+
|
|
84
|
+
export type { DeploymentEvent };
|
|
85
|
+
|
|
86
|
+
/** A response body's text as it arrives; a broken connection throws `AgentUnreachable`. */
|
|
87
|
+
async function* bodyText(body: NonNullable<Response["body"]>) {
|
|
88
|
+
try {
|
|
89
|
+
yield* body.pipeThrough(new TextDecoderStream());
|
|
90
|
+
} catch (cause) {
|
|
91
|
+
throw new AgentUnreachable("The connection to the agent broke", { cause });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A file to upload, at its path in the release. */
|
|
96
|
+
export interface ReleaseFile {
|
|
97
|
+
path: string;
|
|
98
|
+
content: Blob;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Talks to a plant agent at `url`, such as its Tailscale name and port. */
|
|
102
|
+
export const createAgentClient = (options: { url: string; token: string }) => {
|
|
103
|
+
// The agent records who deployed and who changed the controller, and refuses another tsPLC version.
|
|
104
|
+
const identity = workerScriptsDigest()
|
|
105
|
+
.then(
|
|
106
|
+
(scripts) => ({ [clientHeaders.scripts]: scripts }),
|
|
107
|
+
// The digest only tells local builds apart; an installation that can't read its scripts still deploys.
|
|
108
|
+
() => ({}),
|
|
109
|
+
)
|
|
110
|
+
.then((scripts) => ({
|
|
111
|
+
[clientHeaders.user]: userInfo().username,
|
|
112
|
+
[clientHeaders.host]: hostname(),
|
|
113
|
+
[clientHeaders.version]: tsplcVersion,
|
|
114
|
+
...scripts,
|
|
115
|
+
}));
|
|
116
|
+
const call = async (path: string, init: RequestInit = {}) => {
|
|
117
|
+
const response = await fetch(new URL(path, options.url), {
|
|
118
|
+
...init,
|
|
119
|
+
headers: {
|
|
120
|
+
...init.headers,
|
|
121
|
+
...(await identity),
|
|
122
|
+
Authorization: `Bearer ${options.token}`,
|
|
123
|
+
},
|
|
124
|
+
}).catch((cause: unknown) => {
|
|
125
|
+
throw new AgentUnreachable(
|
|
126
|
+
`Cannot reach the plant agent at ${options.url}`,
|
|
127
|
+
{ cause },
|
|
128
|
+
);
|
|
129
|
+
});
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
throw new AgentOperationError(await refusalMessage(response));
|
|
132
|
+
}
|
|
133
|
+
return response;
|
|
134
|
+
};
|
|
135
|
+
const get = async <T>(path: string, schema: z.ZodType<T>) =>
|
|
136
|
+
schema.parse(await (await call(path)).json());
|
|
137
|
+
const send = async <T>(
|
|
138
|
+
method: string,
|
|
139
|
+
path: string,
|
|
140
|
+
body: unknown,
|
|
141
|
+
schema: z.ZodType<T>,
|
|
142
|
+
) =>
|
|
143
|
+
schema.parse(
|
|
144
|
+
await (
|
|
145
|
+
await call(path, {
|
|
146
|
+
method,
|
|
147
|
+
headers: { "Content-Type": "application/json" },
|
|
148
|
+
body: JSON.stringify(body),
|
|
149
|
+
})
|
|
150
|
+
).json(),
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
/** Reads a streamed operation, reporting progress, until its result or failure. */
|
|
154
|
+
const operation = async (
|
|
155
|
+
response: Response,
|
|
156
|
+
onProgress: (message: string) => void,
|
|
157
|
+
) => {
|
|
158
|
+
const reader = response.body
|
|
159
|
+
?.pipeThrough(new TextDecoderStream())
|
|
160
|
+
.getReader();
|
|
161
|
+
if (!reader) {
|
|
162
|
+
throw new Error("The agent returned no operation stream");
|
|
163
|
+
}
|
|
164
|
+
let buffered = "";
|
|
165
|
+
while (true) {
|
|
166
|
+
const { done, value } = await reader.read();
|
|
167
|
+
if (done) {
|
|
168
|
+
throw new Error("The agent closed the operation without a result");
|
|
169
|
+
}
|
|
170
|
+
buffered += value;
|
|
171
|
+
const lines = buffered.split("\n");
|
|
172
|
+
buffered = lines.pop() ?? "";
|
|
173
|
+
for (const line of lines.filter(Boolean)) {
|
|
174
|
+
const event = eventSchema.parse(JSON.parse(line));
|
|
175
|
+
if (event.kind === "progress") {
|
|
176
|
+
onProgress(event.message);
|
|
177
|
+
} else if (event.kind === "done") {
|
|
178
|
+
return event.result;
|
|
179
|
+
} else {
|
|
180
|
+
throw new AgentOperationError(event.message, {
|
|
181
|
+
downloadRequired: event.downloadRequired,
|
|
182
|
+
rollback: event.rollback,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/** What the agent holds of a release with these bucket digests. */
|
|
190
|
+
const compare = (buckets: string[]) =>
|
|
191
|
+
send("POST", "/releases/compare", { buckets }, comparisonSchema);
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The upload body of `release`, built on what the agent already holds. Refuses an agent of
|
|
195
|
+
* another version first.
|
|
196
|
+
*/
|
|
197
|
+
const upload = async (
|
|
198
|
+
release: { manifest: ReleaseManifest; files: ReleaseFile[] },
|
|
199
|
+
settings: DeployOptions,
|
|
200
|
+
onProgress: (message: string) => void,
|
|
201
|
+
) => {
|
|
202
|
+
// Before uploading: an agent of another version, including one from before version checks,
|
|
203
|
+
// would compile the release with scripts this client doesn't expect.
|
|
204
|
+
const agentVersion = (await call(statusPath)).headers.get(
|
|
205
|
+
agentVersionHeader,
|
|
206
|
+
);
|
|
207
|
+
if (agentVersion !== tsplcVersion) {
|
|
208
|
+
throw new AgentOperationError(
|
|
209
|
+
versionMismatch({
|
|
210
|
+
agent: agentVersion,
|
|
211
|
+
client: tsplcVersion,
|
|
212
|
+
agentUpgrades: upgradesItself(agentVersion),
|
|
213
|
+
}),
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
const files = await Promise.all(
|
|
217
|
+
release.files.map(async ({ path, content }) => ({
|
|
218
|
+
path,
|
|
219
|
+
content: await content.bytes(),
|
|
220
|
+
})),
|
|
221
|
+
);
|
|
222
|
+
const digests = files.map(({ path, content }) => ({
|
|
223
|
+
path,
|
|
224
|
+
digest: shortDigest(content),
|
|
225
|
+
}));
|
|
226
|
+
const buckets = bucketDigests(digests);
|
|
227
|
+
return releaseUpload(
|
|
228
|
+
{ manifest: release.manifest, options: settings, buckets },
|
|
229
|
+
files,
|
|
230
|
+
await compare(buckets),
|
|
231
|
+
onProgress,
|
|
232
|
+
);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
/** The agent's address, where its dashboard is. */
|
|
237
|
+
url: options.url,
|
|
238
|
+
status: () => get(statusPath, statusSchema),
|
|
239
|
+
interfaces: () => get("/interfaces", z.array(networkInterfaceSchema)),
|
|
240
|
+
discover: (name: string) =>
|
|
241
|
+
send("POST", "/discover", { name }, z.array(discoveredControllerSchema)),
|
|
242
|
+
setTarget: (target: Target) => send("PUT", "/target", target, targetSchema),
|
|
243
|
+
variables: () => get("/variables", z.array(variableSchema)),
|
|
244
|
+
/** Deploys `release` at once, streaming its progress: `POST /deploy`. */
|
|
245
|
+
deploy: async (
|
|
246
|
+
release: { manifest: ReleaseManifest; files: ReleaseFile[] },
|
|
247
|
+
settings: DeployOptions,
|
|
248
|
+
onProgress: (message: string) => void,
|
|
249
|
+
) => {
|
|
250
|
+
const body = await upload(release, settings, onProgress);
|
|
251
|
+
return releaseSchema.parse(
|
|
252
|
+
await operation(
|
|
253
|
+
await call("/deploy", { method: "POST", ...body }),
|
|
254
|
+
onProgress,
|
|
255
|
+
),
|
|
256
|
+
);
|
|
257
|
+
},
|
|
258
|
+
/** Queues `release` as a deployment the agent runs on its own: `POST /api/deployments`. */
|
|
259
|
+
queueDeployment: async (
|
|
260
|
+
release: { manifest: ReleaseManifest; files: ReleaseFile[] },
|
|
261
|
+
settings: DeployOptions,
|
|
262
|
+
onProgress: (message: string) => void,
|
|
263
|
+
) => {
|
|
264
|
+
const body = await upload(release, settings, onProgress);
|
|
265
|
+
return deploymentCreatedSchema.parse(
|
|
266
|
+
await (
|
|
267
|
+
await call(deploymentsApiPath, { method: "POST", ...body })
|
|
268
|
+
).json(),
|
|
269
|
+
);
|
|
270
|
+
},
|
|
271
|
+
deployments: () => get(deploymentsApiPath, deploymentListSchema),
|
|
272
|
+
/**
|
|
273
|
+
* A deployment's events from after log line `after`, until the agent ends the stream once
|
|
274
|
+
* the deployment finishes. A broken connection throws `AgentUnreachable`.
|
|
275
|
+
*/
|
|
276
|
+
deploymentEvents: async function* (
|
|
277
|
+
id: string,
|
|
278
|
+
after: number,
|
|
279
|
+
): AsyncGenerator<DeploymentEvent> {
|
|
280
|
+
const response = await call(
|
|
281
|
+
`${deploymentApiPath(id)}/events?after=${after}`,
|
|
282
|
+
{ headers: { Accept: "text/event-stream" } },
|
|
283
|
+
);
|
|
284
|
+
if (!response.body) {
|
|
285
|
+
throw new AgentUnreachable("The agent returned no event stream");
|
|
286
|
+
}
|
|
287
|
+
for await (const event of parseEventStream(bodyText(response.body))) {
|
|
288
|
+
if (event.event === "record") {
|
|
289
|
+
yield {
|
|
290
|
+
kind: "record",
|
|
291
|
+
record: deploymentRecordSchema.parse(JSON.parse(event.data)),
|
|
292
|
+
};
|
|
293
|
+
} else if (event.event === "log") {
|
|
294
|
+
yield {
|
|
295
|
+
kind: "log",
|
|
296
|
+
line: deploymentLogLineSchema.parse(JSON.parse(event.data)),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
},
|
|
301
|
+
/** Approves a deployment that waits on a person, as a full download when `download`. */
|
|
302
|
+
approve: async (id: string, approval: { download: boolean }) => {
|
|
303
|
+
await call(`${deploymentApiPath(id)}/approve`, {
|
|
304
|
+
method: "POST",
|
|
305
|
+
headers: { "Content-Type": "application/json" },
|
|
306
|
+
body: JSON.stringify(approval),
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
redeploy: (id: string, mode: DeploymentMode) =>
|
|
310
|
+
send(
|
|
311
|
+
"POST",
|
|
312
|
+
`${deploymentApiPath(id)}/redeploy`,
|
|
313
|
+
{ mode },
|
|
314
|
+
deploymentCreatedSchema,
|
|
315
|
+
),
|
|
316
|
+
rollback: (id: string) =>
|
|
317
|
+
send(
|
|
318
|
+
"POST",
|
|
319
|
+
`${deploymentApiPath(id)}/rollback`,
|
|
320
|
+
{},
|
|
321
|
+
deploymentCreatedSchema,
|
|
322
|
+
),
|
|
323
|
+
/**
|
|
324
|
+
* The plant PC's plain variables, and the secrets it holds in `service`, or in the agent's
|
|
325
|
+
* own service when null: what a release is built with.
|
|
326
|
+
*/
|
|
327
|
+
releaseVariables: (service: string | null) =>
|
|
328
|
+
get(
|
|
329
|
+
`/api/environment/release${service === null ? "" : `?${new URLSearchParams({ service })}`}`,
|
|
330
|
+
plantVariablesSchema,
|
|
331
|
+
),
|
|
332
|
+
/** Resets the controller's application and starts it again; answers once it runs. */
|
|
333
|
+
restartController: (restart: ControllerRestart) =>
|
|
334
|
+
send(
|
|
335
|
+
"POST",
|
|
336
|
+
controllerRestartPath,
|
|
337
|
+
restart,
|
|
338
|
+
controllerRestartReplySchema,
|
|
339
|
+
),
|
|
340
|
+
login: async (
|
|
341
|
+
credentials: Credentials | null,
|
|
342
|
+
onProgress: (message: string) => void,
|
|
343
|
+
) =>
|
|
344
|
+
loginResultSchema.parse(
|
|
345
|
+
await operation(
|
|
346
|
+
await call("/login", {
|
|
347
|
+
method: "POST",
|
|
348
|
+
headers: { "Content-Type": "application/json" },
|
|
349
|
+
body: JSON.stringify(credentials),
|
|
350
|
+
}),
|
|
351
|
+
onProgress,
|
|
352
|
+
),
|
|
353
|
+
),
|
|
354
|
+
command: (command: LoginCommand) =>
|
|
355
|
+
send("POST", "/login/command", command, loginResultSchema),
|
|
356
|
+
logout: () => send("DELETE", "/login", undefined, logoutSchema),
|
|
357
|
+
/** Holds the agent for an upgrade, so it takes no operations; fails while one runs or a login is open. */
|
|
358
|
+
hold: async () => {
|
|
359
|
+
await call(agentHoldPath, { method: "POST" });
|
|
360
|
+
},
|
|
361
|
+
/** Lets a held agent take operations again. */
|
|
362
|
+
releaseHold: async () => {
|
|
363
|
+
await call(agentHoldPath, { method: "DELETE" });
|
|
364
|
+
},
|
|
365
|
+
/** Makes the held agent exit. */
|
|
366
|
+
exit: async (exit: AgentExit) => {
|
|
367
|
+
await call(agentExitPath, {
|
|
368
|
+
method: "POST",
|
|
369
|
+
headers: { "Content-Type": "application/json" },
|
|
370
|
+
body: JSON.stringify(exit),
|
|
371
|
+
});
|
|
372
|
+
},
|
|
373
|
+
};
|
|
374
|
+
};
|
|
375
|
+
export type AgentClient = ReturnType<typeof createAgentClient>;
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* A release upload built on the release the agent compared it with: in each bucket that differs,
|
|
379
|
+
* the files the agent lacks and the paths to drop. Without a base, every file.
|
|
380
|
+
*/
|
|
381
|
+
const releaseUpload = async (
|
|
382
|
+
header: Pick<ReleaseUpload, "manifest" | "options" | "buckets">,
|
|
383
|
+
files: readonly ReleaseContent[],
|
|
384
|
+
{ base, changed }: Comparison,
|
|
385
|
+
onProgress: (message: string) => void,
|
|
386
|
+
) => {
|
|
387
|
+
const stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));
|
|
388
|
+
const uploaded =
|
|
389
|
+
base === null
|
|
390
|
+
? files
|
|
391
|
+
: files.filter(({ path, content }) => {
|
|
392
|
+
const held = stored.get(fileBucket(path));
|
|
393
|
+
return held !== undefined && held[path] !== shortDigest(content);
|
|
394
|
+
});
|
|
395
|
+
const paths = new Set(files.map(({ path }) => path));
|
|
396
|
+
const remove = [...stored.values()].flatMap((held) =>
|
|
397
|
+
Object.keys(held).filter((path) => !paths.has(path)),
|
|
398
|
+
);
|
|
399
|
+
const body = await encodeUpload(
|
|
400
|
+
{ ...header, base, remove } satisfies ReleaseUpload,
|
|
401
|
+
uploaded,
|
|
402
|
+
);
|
|
403
|
+
onProgress(
|
|
404
|
+
`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,
|
|
405
|
+
);
|
|
406
|
+
return { headers: { "Content-Type": releaseUploadType }, body };
|
|
407
|
+
};
|