@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/dist/cli.js
ADDED
|
@@ -0,0 +1,4888 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// packages/agent/src/cli.ts
|
|
5
|
+
import { mkdir as mkdir6 } from "fs/promises";
|
|
6
|
+
import { homedir as homedir2 } from "os";
|
|
7
|
+
import { join as join10 } from "path";
|
|
8
|
+
import { parseArgs } from "util";
|
|
9
|
+
import { configureDocker, configureGateway } from "@tsplc/build";
|
|
10
|
+
import { agentTokenEnv as agentTokenEnv2 } from "@tsplc/config";
|
|
11
|
+
import { tcpPort as tcpPort3 } from "@tsplc/config/build";
|
|
12
|
+
import { z as z20 } from "zod";
|
|
13
|
+
|
|
14
|
+
// packages/agent/src/access.ts
|
|
15
|
+
import { dashboardHeader, tokenQueryParameter } from "@tsplc/debug/api";
|
|
16
|
+
import { controllerRestartPath } from "@tsplc/server/plant-agent";
|
|
17
|
+
|
|
18
|
+
// packages/agent/src/audit.ts
|
|
19
|
+
import { z as z5 } from "zod";
|
|
20
|
+
|
|
21
|
+
// packages/agent/src/logs.ts
|
|
22
|
+
import {
|
|
23
|
+
closeSync,
|
|
24
|
+
existsSync as existsSync2,
|
|
25
|
+
openSync,
|
|
26
|
+
renameSync as renameSync2,
|
|
27
|
+
statSync,
|
|
28
|
+
writeSync
|
|
29
|
+
} from "node:fs";
|
|
30
|
+
import { open } from "node:fs/promises";
|
|
31
|
+
import { z as z4 } from "zod";
|
|
32
|
+
|
|
33
|
+
// packages/agent/src/state.ts
|
|
34
|
+
import { randomUUID } from "node:crypto";
|
|
35
|
+
import { renameSync, writeFileSync } from "node:fs";
|
|
36
|
+
import { mkdir as mkdir2, readFile as readFile2 } from "node:fs/promises";
|
|
37
|
+
import { join as join2 } from "node:path";
|
|
38
|
+
import { z as z3 } from "zod";
|
|
39
|
+
|
|
40
|
+
// packages/agent/src/errors.ts
|
|
41
|
+
class AgentError extends Error {
|
|
42
|
+
status;
|
|
43
|
+
constructor(message, status) {
|
|
44
|
+
super(message);
|
|
45
|
+
this.status = status;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
49
|
+
|
|
50
|
+
// packages/agent/src/protocol.ts
|
|
51
|
+
import {
|
|
52
|
+
controllerCredentialsSchema,
|
|
53
|
+
controllerIdsSchema,
|
|
54
|
+
loginStateSchema,
|
|
55
|
+
onlineChangeFindingSchema,
|
|
56
|
+
rollbackSchema
|
|
57
|
+
} from "@tsplc/build";
|
|
58
|
+
import { plainValue, secretValue, tsplcConfigSchema } from "@tsplc/config";
|
|
59
|
+
import { envName, releaseConfigSchema, tcpPort } from "@tsplc/config/build";
|
|
60
|
+
import { z } from "zod";
|
|
61
|
+
// packages/agent/package.json
|
|
62
|
+
var version = "0.6.3";
|
|
63
|
+
|
|
64
|
+
// packages/agent/src/protocol.ts
|
|
65
|
+
var tsplcVersion = version;
|
|
66
|
+
var targetSchema = z.strictObject({
|
|
67
|
+
host: z.string().nonempty(),
|
|
68
|
+
port: tcpPort
|
|
69
|
+
});
|
|
70
|
+
var networkInterfaceSchema = z.strictObject({
|
|
71
|
+
name: z.string(),
|
|
72
|
+
address: z.ipv4(),
|
|
73
|
+
prefixLength: z.number().int().min(0).max(32)
|
|
74
|
+
});
|
|
75
|
+
var discoveredControllerSchema = z.strictObject({
|
|
76
|
+
address: z.ipv4(),
|
|
77
|
+
port: z.number().int(),
|
|
78
|
+
hostname: z.string().nullable()
|
|
79
|
+
});
|
|
80
|
+
var discoverSchema = z.strictObject({ name: z.string() });
|
|
81
|
+
var variableSchema = z.strictObject({
|
|
82
|
+
path: z.string(),
|
|
83
|
+
type: z.string()
|
|
84
|
+
});
|
|
85
|
+
var targetValuesSchema = z.record(envName, z.string());
|
|
86
|
+
var releaseManifestSchema = z.strictObject({
|
|
87
|
+
config: z.record(z.string(), z.unknown()).superRefine((config, context) => {
|
|
88
|
+
const release = releaseConfigSchema.safeParse(config);
|
|
89
|
+
if (!release.success) {
|
|
90
|
+
context.addIssue({
|
|
91
|
+
code: "custom",
|
|
92
|
+
message: `Invalid release config: ${z.prettifyError(release.error)}`
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}),
|
|
96
|
+
variables: z.array(variableSchema),
|
|
97
|
+
server: z.string().nonempty().optional(),
|
|
98
|
+
debug: tsplcConfigSchema.shape.debug,
|
|
99
|
+
serverTokenEnv: z.string().nonempty().optional(),
|
|
100
|
+
secrets: tsplcConfigSchema.shape.secrets,
|
|
101
|
+
values: targetValuesSchema.default({})
|
|
102
|
+
});
|
|
103
|
+
var uploadEncoding = "gzip";
|
|
104
|
+
var gitSourceSchema = z.strictObject({
|
|
105
|
+
commit: z.string().nonempty(),
|
|
106
|
+
branch: z.string().nullable(),
|
|
107
|
+
dirty: z.boolean(),
|
|
108
|
+
message: z.string().nullable()
|
|
109
|
+
});
|
|
110
|
+
var deploymentModeSchema = z.enum(["apply", "review"]);
|
|
111
|
+
var deploymentRequestSchema = z.strictObject({
|
|
112
|
+
mode: deploymentModeSchema,
|
|
113
|
+
git: gitSourceSchema.nullable()
|
|
114
|
+
});
|
|
115
|
+
var deployOptionsSchema = z.strictObject({
|
|
116
|
+
credentials: controllerCredentialsSchema.nullable(),
|
|
117
|
+
download: z.boolean(),
|
|
118
|
+
initializeUser: z.boolean(),
|
|
119
|
+
deployment: deploymentRequestSchema.optional()
|
|
120
|
+
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
121
|
+
var releaseBuckets = 256;
|
|
122
|
+
var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
|
|
123
|
+
var compareRequestSchema = z.strictObject({
|
|
124
|
+
buckets: z.array(shortHex).length(releaseBuckets)
|
|
125
|
+
});
|
|
126
|
+
var comparisonSchema = z.strictObject({
|
|
127
|
+
base: shortHex.nullable(),
|
|
128
|
+
changed: z.array(z.strictObject({
|
|
129
|
+
bucket: z.number().int().min(0).max(releaseBuckets - 1),
|
|
130
|
+
files: z.record(z.string(), shortHex)
|
|
131
|
+
}))
|
|
132
|
+
});
|
|
133
|
+
var releaseUploadType = "application/vnd.tsplc.release+zstd";
|
|
134
|
+
var releaseUploadSchema = z.strictObject({
|
|
135
|
+
manifest: releaseManifestSchema,
|
|
136
|
+
options: deployOptionsSchema,
|
|
137
|
+
base: shortHex.nullable(),
|
|
138
|
+
buckets: compareRequestSchema.shape.buckets,
|
|
139
|
+
remove: z.array(z.string())
|
|
140
|
+
});
|
|
141
|
+
var eventSchema = z.discriminatedUnion("kind", [
|
|
142
|
+
z.strictObject({ kind: z.literal("progress"), message: z.string() }),
|
|
143
|
+
z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
|
|
144
|
+
z.strictObject({
|
|
145
|
+
kind: z.literal("error"),
|
|
146
|
+
message: z.string(),
|
|
147
|
+
downloadRequired: z.boolean(),
|
|
148
|
+
rollback: rollbackSchema.optional()
|
|
149
|
+
})
|
|
150
|
+
]);
|
|
151
|
+
var deployOperationSchema = z.enum(["download", "online-change"]);
|
|
152
|
+
var releaseSchema = z.strictObject({
|
|
153
|
+
id: z.string(),
|
|
154
|
+
deployedAt: z.iso.datetime(),
|
|
155
|
+
operation: deployOperationSchema,
|
|
156
|
+
controllerIds: controllerIdsSchema,
|
|
157
|
+
server: z.string().optional()
|
|
158
|
+
});
|
|
159
|
+
var statusSchema = z.strictObject({
|
|
160
|
+
target: targetSchema.nullable(),
|
|
161
|
+
release: releaseSchema.nullable(),
|
|
162
|
+
server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
|
|
163
|
+
login: z.union([loginStateSchema, z.strictObject({ error: z.string() })]).nullable(),
|
|
164
|
+
credentialsStored: z.boolean()
|
|
165
|
+
});
|
|
166
|
+
var statusPath = "/status";
|
|
167
|
+
var agentHoldPath = "/agent/hold";
|
|
168
|
+
var agentExitPath = "/agent/exit";
|
|
169
|
+
var exitSchema = z.strictObject({
|
|
170
|
+
server: z.enum(["leave", "stop"]),
|
|
171
|
+
restart: z.boolean()
|
|
172
|
+
});
|
|
173
|
+
var logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
174
|
+
var clientHeaders = {
|
|
175
|
+
user: "x-tsplc-user",
|
|
176
|
+
host: "x-tsplc-host",
|
|
177
|
+
version: "x-tsplc-version",
|
|
178
|
+
scripts: "x-tsplc-scripts"
|
|
179
|
+
};
|
|
180
|
+
var agentVersionHeader = "x-tsplc-agent-version";
|
|
181
|
+
var atLeast = (version, minimum) => {
|
|
182
|
+
const parts = version.split(/[.+-]/).slice(0, 3).map(Number);
|
|
183
|
+
for (const [index, wanted] of minimum.entries()) {
|
|
184
|
+
const part = parts[index] ?? 0;
|
|
185
|
+
if (part !== wanted) {
|
|
186
|
+
return part > wanted;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
};
|
|
191
|
+
var upgradesItself = (version) => version !== null && atLeast(version, [0, 5, 0]);
|
|
192
|
+
var versionMismatch = (versions) => `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}` : ""}`;
|
|
193
|
+
var clientIdentity = (request) => {
|
|
194
|
+
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
195
|
+
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
196
|
+
};
|
|
197
|
+
var clientRelease = (request) => ({
|
|
198
|
+
version: request.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,
|
|
199
|
+
scripts: request.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined
|
|
200
|
+
});
|
|
201
|
+
var deploymentSchema = z.strictObject({
|
|
202
|
+
at: z.iso.datetime(),
|
|
203
|
+
release: z.string(),
|
|
204
|
+
build: z.string().optional(),
|
|
205
|
+
operation: deployOperationSchema,
|
|
206
|
+
credentials: z.enum(["provided", "stored"]).optional(),
|
|
207
|
+
user: z.string().optional(),
|
|
208
|
+
host: z.string().optional()
|
|
209
|
+
});
|
|
210
|
+
var auditSchema = z.strictObject({
|
|
211
|
+
at: z.iso.datetime(),
|
|
212
|
+
command: z.string(),
|
|
213
|
+
values: z.record(z.string(), z.string()),
|
|
214
|
+
previous: z.record(z.string(), z.string()).optional(),
|
|
215
|
+
user: z.string().optional(),
|
|
216
|
+
host: z.string().optional(),
|
|
217
|
+
release: z.string().optional(),
|
|
218
|
+
error: z.string().optional()
|
|
219
|
+
});
|
|
220
|
+
var roles = ["viewer", "deployer", "admin"];
|
|
221
|
+
var roleSchema = z.enum(roles);
|
|
222
|
+
var allows = (role, required) => roles.indexOf(role) >= roles.indexOf(required);
|
|
223
|
+
var identitySchema = z.strictObject({
|
|
224
|
+
login: z.string().nullable(),
|
|
225
|
+
name: z.string(),
|
|
226
|
+
role: roleSchema,
|
|
227
|
+
via: z.enum(["tailscale", "token", "local", "server"])
|
|
228
|
+
});
|
|
229
|
+
var deploymentStateSchema = z.enum([
|
|
230
|
+
"queued",
|
|
231
|
+
"building",
|
|
232
|
+
"awaitingApproval",
|
|
233
|
+
"applying",
|
|
234
|
+
"starting",
|
|
235
|
+
"verifying",
|
|
236
|
+
"ready",
|
|
237
|
+
"error",
|
|
238
|
+
"canceled"
|
|
239
|
+
]);
|
|
240
|
+
var finalStates = [
|
|
241
|
+
"ready",
|
|
242
|
+
"error",
|
|
243
|
+
"canceled"
|
|
244
|
+
];
|
|
245
|
+
var cancelableStates = [
|
|
246
|
+
"queued",
|
|
247
|
+
"building",
|
|
248
|
+
"awaitingApproval"
|
|
249
|
+
];
|
|
250
|
+
var deploymentPhaseNameSchema = z.enum([
|
|
251
|
+
"queue",
|
|
252
|
+
"build",
|
|
253
|
+
"review",
|
|
254
|
+
"apply",
|
|
255
|
+
"server",
|
|
256
|
+
"health"
|
|
257
|
+
]);
|
|
258
|
+
var deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
|
|
259
|
+
var deploymentRecordSchema = z.strictObject({
|
|
260
|
+
id: deploymentIdSchema,
|
|
261
|
+
release: z.string(),
|
|
262
|
+
build: z.string().nullable(),
|
|
263
|
+
createdAt: z.iso.datetime(),
|
|
264
|
+
updatedAt: z.iso.datetime(),
|
|
265
|
+
origin: z.discriminatedUnion("kind", [
|
|
266
|
+
z.strictObject({ kind: z.literal("upload") }),
|
|
267
|
+
z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
|
|
268
|
+
z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema })
|
|
269
|
+
]),
|
|
270
|
+
git: gitSourceSchema.nullable(),
|
|
271
|
+
requestedBy: z.strictObject({
|
|
272
|
+
identity: identitySchema.omit({ role: true }),
|
|
273
|
+
user: z.string().nullable(),
|
|
274
|
+
host: z.string().nullable()
|
|
275
|
+
}),
|
|
276
|
+
mode: deploymentModeSchema,
|
|
277
|
+
operation: deployOperationSchema,
|
|
278
|
+
state: deploymentStateSchema,
|
|
279
|
+
phases: z.array(z.strictObject({
|
|
280
|
+
name: deploymentPhaseNameSchema,
|
|
281
|
+
startedAt: z.iso.datetime(),
|
|
282
|
+
finishedAt: z.iso.datetime().nullable(),
|
|
283
|
+
outcome: z.enum(["running", "ok", "failed", "skipped"])
|
|
284
|
+
})),
|
|
285
|
+
findings: z.array(onlineChangeFindingSchema),
|
|
286
|
+
approval: z.strictObject({
|
|
287
|
+
reason: z.enum(["review", "downloadRequired"]),
|
|
288
|
+
message: z.string()
|
|
289
|
+
}).nullable(),
|
|
290
|
+
error: z.strictObject({
|
|
291
|
+
message: z.string(),
|
|
292
|
+
downloadRequired: z.boolean(),
|
|
293
|
+
rollback: rollbackSchema.optional()
|
|
294
|
+
}).nullable(),
|
|
295
|
+
controllerIds: controllerIdsSchema.nullable(),
|
|
296
|
+
health: z.strictObject({
|
|
297
|
+
controller: z.enum(["ok", "failed"]),
|
|
298
|
+
server: z.enum(["ok", "failed", "none"]),
|
|
299
|
+
plc: z.enum(["ok", "failed", "unknown"]),
|
|
300
|
+
detail: z.string().nullable()
|
|
301
|
+
}).nullable(),
|
|
302
|
+
activeFrom: z.iso.datetime().nullable(),
|
|
303
|
+
activeUntil: z.iso.datetime().nullable()
|
|
304
|
+
});
|
|
305
|
+
var deploymentLogLineSchema = z.strictObject({
|
|
306
|
+
seq: z.number().int().positive(),
|
|
307
|
+
at: z.iso.datetime(),
|
|
308
|
+
level: z.enum(["info", "warning", "error"]),
|
|
309
|
+
phase: deploymentPhaseNameSchema.nullable(),
|
|
310
|
+
message: z.string()
|
|
311
|
+
});
|
|
312
|
+
var deploymentsApiPath = "/api/deployments";
|
|
313
|
+
var deploymentApiPath = (id) => `${deploymentsApiPath}/${encodeURIComponent(id)}`;
|
|
314
|
+
var deploymentPagePath = (id) => `/deployments/${encodeURIComponent(id)}`;
|
|
315
|
+
var debuggerMount = "/debug/";
|
|
316
|
+
var deploymentCreatedSchema = z.strictObject({
|
|
317
|
+
id: deploymentIdSchema,
|
|
318
|
+
url: z.string()
|
|
319
|
+
});
|
|
320
|
+
var deploymentListSchema = z.strictObject({
|
|
321
|
+
deployments: z.array(deploymentRecordSchema),
|
|
322
|
+
current: deploymentIdSchema.nullable(),
|
|
323
|
+
lastGood: deploymentIdSchema.nullable()
|
|
324
|
+
});
|
|
325
|
+
var approveSchema = z.strictObject({ download: z.boolean() });
|
|
326
|
+
var redeploySchema = z.strictObject({ mode: deploymentModeSchema });
|
|
327
|
+
var deploymentSourceSchema = z.strictObject({
|
|
328
|
+
files: z.array(z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }))
|
|
329
|
+
});
|
|
330
|
+
var environmentEntrySchema = z.strictObject({
|
|
331
|
+
name: z.string(),
|
|
332
|
+
declared: z.boolean(),
|
|
333
|
+
set: z.boolean()
|
|
334
|
+
});
|
|
335
|
+
var environmentSchema = z.strictObject({
|
|
336
|
+
values: targetValuesSchema,
|
|
337
|
+
variables: z.record(envName, z.string()),
|
|
338
|
+
secrets: z.array(environmentEntrySchema)
|
|
339
|
+
});
|
|
340
|
+
var accessConfigSchema = z.strictObject({
|
|
341
|
+
roles: z.record(z.string().nonempty(), roleSchema),
|
|
342
|
+
tailnetDefault: roleSchema.nullable()
|
|
343
|
+
});
|
|
344
|
+
var sessionRequestSchema = z.strictObject({ token: z.string() });
|
|
345
|
+
var environmentValueSchema = z.discriminatedUnion("secret", [
|
|
346
|
+
z.strictObject({ secret: z.literal(false), value: plainValue }),
|
|
347
|
+
z.strictObject({ secret: z.literal(true), value: secretValue })
|
|
348
|
+
]);
|
|
349
|
+
|
|
350
|
+
// packages/agent/src/releases.ts
|
|
351
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
352
|
+
import { existsSync } from "node:fs";
|
|
353
|
+
import {
|
|
354
|
+
mkdir,
|
|
355
|
+
mkdtemp,
|
|
356
|
+
readdir,
|
|
357
|
+
readFile,
|
|
358
|
+
rename,
|
|
359
|
+
rm,
|
|
360
|
+
stat,
|
|
361
|
+
writeFile
|
|
362
|
+
} from "node:fs/promises";
|
|
363
|
+
import {
|
|
364
|
+
dirname,
|
|
365
|
+
isAbsolute,
|
|
366
|
+
join,
|
|
367
|
+
posix,
|
|
368
|
+
relative,
|
|
369
|
+
resolve,
|
|
370
|
+
sep
|
|
371
|
+
} from "node:path";
|
|
372
|
+
import { z as z2 } from "zod";
|
|
373
|
+
|
|
374
|
+
// packages/agent/src/transfer.ts
|
|
375
|
+
import { createHash } from "node:crypto";
|
|
376
|
+
var shortDigest = (data) => createHash("sha256").update(data).digest("hex").slice(0, 16);
|
|
377
|
+
var fileBucket = (path) => createHash("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
|
|
378
|
+
var bucketDigests = (files) => {
|
|
379
|
+
const buckets = Array.from({ length: releaseBuckets }, () => []);
|
|
380
|
+
for (const { path, digest } of files) {
|
|
381
|
+
buckets[fileBucket(path)]?.push(`${path}\x00${digest}`);
|
|
382
|
+
}
|
|
383
|
+
return buckets.map((entries) => shortDigest(entries.sort().join(`
|
|
384
|
+
`)));
|
|
385
|
+
};
|
|
386
|
+
var lengthBytes = 4;
|
|
387
|
+
var encodeUpload = async (header, files) => {
|
|
388
|
+
const encoder = new TextEncoder;
|
|
389
|
+
const frames = [
|
|
390
|
+
encoder.encode(JSON.stringify(header)),
|
|
391
|
+
...files.flatMap(({ path, content }) => [encoder.encode(path), content])
|
|
392
|
+
];
|
|
393
|
+
const body = new Uint8Array(frames.reduce((total, frame) => total + lengthBytes + frame.length, 0));
|
|
394
|
+
const view = new DataView(body.buffer);
|
|
395
|
+
let offset = 0;
|
|
396
|
+
for (const frame of frames) {
|
|
397
|
+
view.setUint32(offset, frame.length);
|
|
398
|
+
body.set(frame, offset + lengthBytes);
|
|
399
|
+
offset += lengthBytes + frame.length;
|
|
400
|
+
}
|
|
401
|
+
return new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));
|
|
402
|
+
};
|
|
403
|
+
var decodeUpload = async (compressed) => {
|
|
404
|
+
const body = new Uint8Array(await Bun.zstdDecompress(compressed));
|
|
405
|
+
const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
|
406
|
+
const frames = [];
|
|
407
|
+
let offset = 0;
|
|
408
|
+
while (offset < body.length) {
|
|
409
|
+
if (offset + lengthBytes > body.length) {
|
|
410
|
+
throw new Error("The release upload ends inside a frame");
|
|
411
|
+
}
|
|
412
|
+
const end = offset + lengthBytes + view.getUint32(offset);
|
|
413
|
+
if (end > body.length) {
|
|
414
|
+
throw new Error("The release upload ends inside a frame");
|
|
415
|
+
}
|
|
416
|
+
frames.push(body.subarray(offset + lengthBytes, end));
|
|
417
|
+
offset = end;
|
|
418
|
+
}
|
|
419
|
+
const [header, ...rest] = frames;
|
|
420
|
+
if (!header || rest.length % 2 !== 0) {
|
|
421
|
+
throw new Error("The release upload has no header or a file without content");
|
|
422
|
+
}
|
|
423
|
+
const decoder = new TextDecoder;
|
|
424
|
+
const files = Array.from({ length: rest.length / 2 }, (_, index) => ({
|
|
425
|
+
path: decoder.decode(rest[2 * index]),
|
|
426
|
+
content: rest[2 * index + 1] ?? new Uint8Array
|
|
427
|
+
}));
|
|
428
|
+
return { header: JSON.parse(decoder.decode(header)), files };
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
// packages/agent/src/releases.ts
|
|
432
|
+
var filePrefix = "files/";
|
|
433
|
+
var releasePath = (name) => {
|
|
434
|
+
const path = posix.normalize(name);
|
|
435
|
+
if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
|
|
436
|
+
throw new Error(`Invalid release file name: ${name}`);
|
|
437
|
+
}
|
|
438
|
+
return path;
|
|
439
|
+
};
|
|
440
|
+
var checkServer = ({ manifest, files }) => {
|
|
441
|
+
if (manifest.server && !files.some((file) => file.path === manifest.server)) {
|
|
442
|
+
throw new Error(`The release names a server ${manifest.server} it doesn't contain`);
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
var readUpload = async (form) => {
|
|
446
|
+
if (form.get("encoding") !== uploadEncoding) {
|
|
447
|
+
throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
|
|
448
|
+
}
|
|
449
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(z2.string().parse(form.get("manifest"))));
|
|
450
|
+
const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
|
|
451
|
+
path: releasePath(name.slice(filePrefix.length)),
|
|
452
|
+
content: Bun.gunzipSync(await z2.instanceof(File).parse(value).bytes())
|
|
453
|
+
})));
|
|
454
|
+
const upload = { manifest, files };
|
|
455
|
+
checkServer(upload);
|
|
456
|
+
return upload;
|
|
457
|
+
};
|
|
458
|
+
var readDeployRequest = async (releases, request) => {
|
|
459
|
+
const type = request.headers.get("content-type") ?? "";
|
|
460
|
+
if (type.split(";")[0]?.trim() === releaseUploadType) {
|
|
461
|
+
const { header, files } = await decodeUpload(await request.bytes());
|
|
462
|
+
const upload = releaseUploadSchema.parse(header);
|
|
463
|
+
return {
|
|
464
|
+
settings: upload.options,
|
|
465
|
+
upload: await releases.assemble(upload, files)
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
if (type.startsWith("multipart/form-data")) {
|
|
469
|
+
const form = await request.formData();
|
|
470
|
+
return {
|
|
471
|
+
settings: deployOptionsSchema.parse(JSON.parse(z2.string().parse(form.get("options")))),
|
|
472
|
+
upload: await readUpload(form)
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
throw new AgentError(`Unsupported deployment content type ${type}`, 415);
|
|
476
|
+
};
|
|
477
|
+
var manifestFile = "manifest.json";
|
|
478
|
+
var isStored = (releases, id) => existsSync(join(releases, id, manifestFile));
|
|
479
|
+
var storedIds = async (releases) => existsSync(releases) ? (await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name) : [];
|
|
480
|
+
async function* releaseFiles(directory) {
|
|
481
|
+
for await (const found of new Bun.Glob("**/*").scan({
|
|
482
|
+
cwd: directory,
|
|
483
|
+
dot: true
|
|
484
|
+
})) {
|
|
485
|
+
yield { path: found.split(sep).join("/"), file: join(directory, found) };
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
var saveRelease = async (releases, { manifest, files }) => {
|
|
489
|
+
const hash = createHash2("sha256").update(JSON.stringify(manifest));
|
|
490
|
+
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
491
|
+
hash.update(file.path).update(createHash2("sha256").update(file.content).digest("hex"));
|
|
492
|
+
}
|
|
493
|
+
const id = hash.digest("hex").slice(0, 16);
|
|
494
|
+
const directory = join(releases, id);
|
|
495
|
+
if (!existsSync(directory)) {
|
|
496
|
+
await mkdir(releases, { recursive: true });
|
|
497
|
+
const staging = await mkdtemp(join(releases, ".upload-"));
|
|
498
|
+
try {
|
|
499
|
+
for (const file of files) {
|
|
500
|
+
await mkdir(dirname(join(staging, file.path)), { recursive: true });
|
|
501
|
+
await writeFile(join(staging, file.path), file.content, {
|
|
502
|
+
mode: file.path === manifest.server ? 493 : 420
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
await writeFile(join(staging, manifestFile), JSON.stringify(manifest, null, 2));
|
|
506
|
+
await rename(staging, directory);
|
|
507
|
+
} catch (cause) {
|
|
508
|
+
await rm(staging, { recursive: true, force: true });
|
|
509
|
+
throw cause;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return { id, directory, manifest };
|
|
513
|
+
};
|
|
514
|
+
var loadRelease = async (releases, id) => {
|
|
515
|
+
const directory = join(releases, id);
|
|
516
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile(join(directory, manifestFile), "utf8")));
|
|
517
|
+
return { id, directory, manifest };
|
|
518
|
+
};
|
|
519
|
+
var releaseServerPath = (release) => release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
520
|
+
var serverReleaseId = (serverPath) => {
|
|
521
|
+
const slash = serverPath.indexOf("/");
|
|
522
|
+
return slash === -1 ? serverPath : serverPath.slice(0, slash);
|
|
523
|
+
};
|
|
524
|
+
var releaseServerFile = (releases, serverPath) => join(releases, serverPath);
|
|
525
|
+
var storedReleaseOf = (releases, file) => {
|
|
526
|
+
const id = serverReleaseId(relative(releases, file).split(sep).join("/"));
|
|
527
|
+
if (!id) {
|
|
528
|
+
throw new Error(`${file} lies in no release under ${releases}`);
|
|
529
|
+
}
|
|
530
|
+
return loadRelease(releases, id);
|
|
531
|
+
};
|
|
532
|
+
var listReleaseFiles = async (releases, id) => {
|
|
533
|
+
if (!isStored(releases, id)) {
|
|
534
|
+
throw new AgentError(`The release ${id} is no longer stored`, 404);
|
|
535
|
+
}
|
|
536
|
+
const files = [];
|
|
537
|
+
for await (const { path, file } of releaseFiles(join(releases, id))) {
|
|
538
|
+
files.push({ path, size: (await stat(file)).size });
|
|
539
|
+
}
|
|
540
|
+
return files.sort((left, right) => left.path.localeCompare(right.path));
|
|
541
|
+
};
|
|
542
|
+
var readReleaseFile = async (releases, id, path) => {
|
|
543
|
+
const directory = resolve(releases, id);
|
|
544
|
+
const file = resolve(directory, path);
|
|
545
|
+
const inside = relative(directory, file);
|
|
546
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
|
|
547
|
+
throw new AgentError(`${path} isn't a path in a release`, 400);
|
|
548
|
+
}
|
|
549
|
+
if (!await stat(file).then((found) => found.isFile(), () => false)) {
|
|
550
|
+
throw new AgentError(`The release ${id} has no file ${path}`, 404);
|
|
551
|
+
}
|
|
552
|
+
return Bun.file(file);
|
|
553
|
+
};
|
|
554
|
+
var pruneReleases = async (releases, kept) => {
|
|
555
|
+
const removed = (await storedIds(releases)).filter((id) => !kept.has(id));
|
|
556
|
+
for (const id of removed) {
|
|
557
|
+
await rm(join(releases, id), { recursive: true, force: true });
|
|
558
|
+
}
|
|
559
|
+
return removed;
|
|
560
|
+
};
|
|
561
|
+
var createReleaseStore = (releases) => {
|
|
562
|
+
const indexes = new Map;
|
|
563
|
+
const readIndex = async (id) => {
|
|
564
|
+
const files = new Map;
|
|
565
|
+
for await (const { path, file } of releaseFiles(join(releases, id))) {
|
|
566
|
+
if (path !== manifestFile) {
|
|
567
|
+
files.set(path, shortDigest(await readFile(file)));
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
571
|
+
return { files, buckets: bucketDigests(digests) };
|
|
572
|
+
};
|
|
573
|
+
const index = (id) => {
|
|
574
|
+
const known = indexes.get(id);
|
|
575
|
+
if (known) {
|
|
576
|
+
return known;
|
|
577
|
+
}
|
|
578
|
+
const reading = readIndex(id);
|
|
579
|
+
indexes.set(id, reading);
|
|
580
|
+
reading.catch(() => indexes.delete(id));
|
|
581
|
+
return reading;
|
|
582
|
+
};
|
|
583
|
+
const newest = async () => {
|
|
584
|
+
const stored = await Promise.all((await storedIds(releases)).map(async (id) => ({
|
|
585
|
+
id,
|
|
586
|
+
created: (await stat(join(releases, id))).mtimeMs
|
|
587
|
+
})));
|
|
588
|
+
return stored.sort((left, right) => right.created - left.created)[0]?.id;
|
|
589
|
+
};
|
|
590
|
+
return {
|
|
591
|
+
compare: async (buckets, deployed) => {
|
|
592
|
+
const candidates = [
|
|
593
|
+
...new Set([deployed, await newest()].filter((id) => id != null))
|
|
594
|
+
].filter((id) => isStored(releases, id));
|
|
595
|
+
const compared = await Promise.all(candidates.map(async (id) => {
|
|
596
|
+
const { files, buckets: stored } = await index(id);
|
|
597
|
+
const changed = buckets.flatMap((digest, bucket) => stored[bucket] === digest ? [] : [bucket]);
|
|
598
|
+
return { id, files, changed };
|
|
599
|
+
}));
|
|
600
|
+
const [best] = compared.sort((left, right) => left.changed.length - right.changed.length);
|
|
601
|
+
if (!best) {
|
|
602
|
+
return { base: null, changed: [] };
|
|
603
|
+
}
|
|
604
|
+
const changed = new Map(best.changed.map((bucket) => [bucket, {}]));
|
|
605
|
+
for (const [path, digest] of best.files) {
|
|
606
|
+
const held = changed.get(fileBucket(path));
|
|
607
|
+
if (held) {
|
|
608
|
+
held[path] = digest;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return {
|
|
612
|
+
base: best.id,
|
|
613
|
+
changed: [...changed].map(([bucket, files]) => ({ bucket, files }))
|
|
614
|
+
};
|
|
615
|
+
},
|
|
616
|
+
assemble: async ({ manifest, base, buckets, remove }, uploaded) => {
|
|
617
|
+
const files = new Map(uploaded.map(({ path, content }) => [releasePath(path), content]));
|
|
618
|
+
if (files.size !== uploaded.length) {
|
|
619
|
+
throw new AgentError("The release upload sends a file twice", 400);
|
|
620
|
+
}
|
|
621
|
+
if (base !== null) {
|
|
622
|
+
if (!isStored(releases, base)) {
|
|
623
|
+
throw new AgentError(`The release ${base} this upload builds on is gone; deploy again`, 409);
|
|
624
|
+
}
|
|
625
|
+
const removed = new Set(remove);
|
|
626
|
+
const reused = [...(await index(base)).files.keys()].filter((path) => !removed.has(path) && !files.has(path));
|
|
627
|
+
for (const path of reused) {
|
|
628
|
+
files.set(path, new Uint8Array(await readFile(join(releases, base, path))));
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const assembled = bucketDigests([...files].map(([path, content]) => ({
|
|
632
|
+
path,
|
|
633
|
+
digest: shortDigest(content)
|
|
634
|
+
})));
|
|
635
|
+
if (assembled.some((digest, bucket) => digest !== buckets[bucket])) {
|
|
636
|
+
throw new AgentError("The release upload doesn't match the release it describes; deploy again", 400);
|
|
637
|
+
}
|
|
638
|
+
const upload = {
|
|
639
|
+
manifest,
|
|
640
|
+
files: [...files].map(([path, content]) => ({ path, content }))
|
|
641
|
+
};
|
|
642
|
+
checkServer(upload);
|
|
643
|
+
return upload;
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
// packages/agent/src/state.ts
|
|
649
|
+
var readTextIfPresent = (path) => readFile2(path, "utf8").catch((error) => {
|
|
650
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
throw error;
|
|
654
|
+
});
|
|
655
|
+
var readJsonFile = async (path, schema) => {
|
|
656
|
+
const text = await readTextIfPresent(path);
|
|
657
|
+
return text === null ? null : schema.parse(JSON.parse(text));
|
|
658
|
+
};
|
|
659
|
+
var readJsonFileIfValid = (path, schema) => readJsonFile(path, schema).catch((error) => {
|
|
660
|
+
if (error instanceof SyntaxError || error instanceof z3.ZodError) {
|
|
661
|
+
return null;
|
|
662
|
+
}
|
|
663
|
+
throw error;
|
|
664
|
+
});
|
|
665
|
+
var writeJsonFile = (path, value) => {
|
|
666
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
667
|
+
writeFileSync(temporary, JSON.stringify(value, null, 2));
|
|
668
|
+
renameSync(temporary, path);
|
|
669
|
+
};
|
|
670
|
+
var statePaths = (directory) => ({
|
|
671
|
+
releases: join2(directory, "releases"),
|
|
672
|
+
controller: join2(directory, "controller"),
|
|
673
|
+
sources: join2(directory, "sources"),
|
|
674
|
+
release: join2(directory, "release.json"),
|
|
675
|
+
target: join2(directory, "target.json"),
|
|
676
|
+
deployments: join2(directory, "deployments.jsonl"),
|
|
677
|
+
deploymentRecords: join2(directory, "deployments"),
|
|
678
|
+
audit: join2(directory, "audit.jsonl"),
|
|
679
|
+
access: join2(directory, "access.json"),
|
|
680
|
+
environment: join2(directory, "environment.json"),
|
|
681
|
+
variables: join2(directory, "variables.json"),
|
|
682
|
+
debug: join2(directory, "debug"),
|
|
683
|
+
server: join2(directory, "server.json"),
|
|
684
|
+
agent: join2(directory, "agent.json"),
|
|
685
|
+
logs: join2(directory, "logs"),
|
|
686
|
+
serverLog: join2(directory, "logs", "server.log"),
|
|
687
|
+
agentLog: join2(directory, "logs", "agent.log")
|
|
688
|
+
});
|
|
689
|
+
var openState = async (directory) => {
|
|
690
|
+
const paths = statePaths(directory);
|
|
691
|
+
await mkdir2(paths.logs, { recursive: true });
|
|
692
|
+
const target = () => readJsonFile(paths.target, targetSchema);
|
|
693
|
+
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
694
|
+
return {
|
|
695
|
+
paths,
|
|
696
|
+
target,
|
|
697
|
+
setTarget: async (selected) => writeJsonFile(paths.target, selected),
|
|
698
|
+
requireTarget: async () => {
|
|
699
|
+
const selected = await target();
|
|
700
|
+
if (!selected) {
|
|
701
|
+
throw new AgentError("Select the controller first: tsplc target", 409);
|
|
702
|
+
}
|
|
703
|
+
return selected;
|
|
704
|
+
},
|
|
705
|
+
release,
|
|
706
|
+
setRelease: async (deployed) => writeJsonFile(paths.release, deployed),
|
|
707
|
+
requireRelease: async () => {
|
|
708
|
+
const deployed = await release();
|
|
709
|
+
if (!deployed) {
|
|
710
|
+
throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
|
|
711
|
+
}
|
|
712
|
+
return loadRelease(paths.releases, deployed.id);
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
// packages/agent/src/logs.ts
|
|
718
|
+
var rotateLog = (file, bytes) => {
|
|
719
|
+
if (existsSync2(file) && statSync(file).size >= bytes) {
|
|
720
|
+
renameSync2(file, `${file}.1`);
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
var outputLogBytes = 10 * 2 ** 20;
|
|
724
|
+
var spawnWithLog = (command, log, options) => {
|
|
725
|
+
const { heading, ...spawnOptions } = options;
|
|
726
|
+
rotateLog(log, outputLogBytes);
|
|
727
|
+
const output = openSync(log, "a");
|
|
728
|
+
try {
|
|
729
|
+
if (heading) {
|
|
730
|
+
writeSync(output, heading);
|
|
731
|
+
}
|
|
732
|
+
return Bun.spawn(command, {
|
|
733
|
+
...spawnOptions,
|
|
734
|
+
stdio: ["ignore", output, output]
|
|
735
|
+
});
|
|
736
|
+
} finally {
|
|
737
|
+
closeSync(output);
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
var appendJsonLine = async (file, value) => {
|
|
741
|
+
const log = await open(file, "a+");
|
|
742
|
+
try {
|
|
743
|
+
const { size } = await log.stat();
|
|
744
|
+
const last = Buffer.alloc(1);
|
|
745
|
+
if (size) {
|
|
746
|
+
await log.read(last, 0, 1, size - 1);
|
|
747
|
+
}
|
|
748
|
+
const separator = size && last[0] !== 10 ? `
|
|
749
|
+
` : "";
|
|
750
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
751
|
+
`);
|
|
752
|
+
} finally {
|
|
753
|
+
await log.close();
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
var appendOnlyBytes = 5 * 2 ** 20;
|
|
757
|
+
var appendJsonl = async (file, value) => {
|
|
758
|
+
rotateLog(file, appendOnlyBytes);
|
|
759
|
+
await appendJsonLine(file, value);
|
|
760
|
+
};
|
|
761
|
+
var parsesAsJson = (line) => {
|
|
762
|
+
try {
|
|
763
|
+
return { json: JSON.parse(line) };
|
|
764
|
+
} catch {
|
|
765
|
+
return null;
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
var readJsonl = async (file, schema, limit) => {
|
|
769
|
+
const text = await readTextIfPresent(file);
|
|
770
|
+
if (text === null) {
|
|
771
|
+
return [];
|
|
772
|
+
}
|
|
773
|
+
return text.split(`
|
|
774
|
+
`).map((line, index) => ({ line, number: index + 1 })).filter(({ line }) => line).slice(-limit).flatMap(({ line, number }) => {
|
|
775
|
+
const parsed = parsesAsJson(line);
|
|
776
|
+
if (!parsed) {
|
|
777
|
+
return [];
|
|
778
|
+
}
|
|
779
|
+
const entry = schema.safeParse(parsed.json);
|
|
780
|
+
if (!entry.success) {
|
|
781
|
+
throw new Error(`Line ${number} of ${file} isn't a valid entry: ${z4.prettifyError(entry.error)}`);
|
|
782
|
+
}
|
|
783
|
+
return [entry.data];
|
|
784
|
+
});
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
// packages/agent/src/audit.ts
|
|
788
|
+
var auditLimits = { default: 100, max: 1000 };
|
|
789
|
+
var auditQuerySchema = z5.object({
|
|
790
|
+
limit: z5.coerce.number().int().positive().max(auditLimits.max).default(auditLimits.default)
|
|
791
|
+
});
|
|
792
|
+
var authorOf = (identity) => ({
|
|
793
|
+
user: identity.login ?? identity.name
|
|
794
|
+
});
|
|
795
|
+
var createAudit = (context) => {
|
|
796
|
+
const record = async (change) => {
|
|
797
|
+
const entry = {
|
|
798
|
+
at: new Date().toISOString(),
|
|
799
|
+
command: change.command,
|
|
800
|
+
values: change.values,
|
|
801
|
+
...change.previous && { previous: change.previous },
|
|
802
|
+
...change.by,
|
|
803
|
+
...change.error !== null && { error: change.error }
|
|
804
|
+
};
|
|
805
|
+
await appendJsonl(context.file, entry);
|
|
806
|
+
await context.onRecord(entry);
|
|
807
|
+
};
|
|
808
|
+
const routes = [
|
|
809
|
+
{
|
|
810
|
+
method: "GET",
|
|
811
|
+
pattern: "/api/audit",
|
|
812
|
+
role: "viewer",
|
|
813
|
+
handle: async (request) => {
|
|
814
|
+
const { limit } = auditQuerySchema.parse(Object.fromEntries(new URL(request.url).searchParams));
|
|
815
|
+
return Response.json((await readJsonl(context.file, auditSchema, limit)).reverse());
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
];
|
|
819
|
+
return { record, routes };
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
// packages/agent/src/sessions.ts
|
|
823
|
+
import { randomBytes } from "node:crypto";
|
|
824
|
+
var sessionCookie = "tsplc_session";
|
|
825
|
+
var sessionLifetimeMs = 12 * 60 * 60 * 1000;
|
|
826
|
+
var createSessions = (now) => {
|
|
827
|
+
const sessions = new Map;
|
|
828
|
+
const sessionId = (request) => new Bun.CookieMap(request.headers.get("cookie") ?? "").get(sessionCookie);
|
|
829
|
+
const cookie = (value, maxAgeMs) => new Bun.Cookie(sessionCookie, value, {
|
|
830
|
+
httpOnly: true,
|
|
831
|
+
sameSite: "strict",
|
|
832
|
+
path: "/",
|
|
833
|
+
maxAge: Math.floor(maxAgeMs / 1000)
|
|
834
|
+
}).serialize();
|
|
835
|
+
return {
|
|
836
|
+
open: (identity) => {
|
|
837
|
+
const time = now();
|
|
838
|
+
for (const [id, { expires }] of sessions) {
|
|
839
|
+
if (expires <= time) {
|
|
840
|
+
sessions.delete(id);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
const id = randomBytes(32).toString("base64url");
|
|
844
|
+
sessions.set(id, { identity, expires: time + sessionLifetimeMs });
|
|
845
|
+
return cookie(id, sessionLifetimeMs);
|
|
846
|
+
},
|
|
847
|
+
find: (request) => {
|
|
848
|
+
const id = sessionId(request);
|
|
849
|
+
const session = id === null ? undefined : sessions.get(id);
|
|
850
|
+
if (!session || session.expires <= now()) {
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
return session.identity;
|
|
854
|
+
},
|
|
855
|
+
close: (request) => {
|
|
856
|
+
const id = sessionId(request);
|
|
857
|
+
if (id !== null) {
|
|
858
|
+
sessions.delete(id);
|
|
859
|
+
}
|
|
860
|
+
return cookie("", 0);
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
// packages/agent/src/tailscale.ts
|
|
866
|
+
import { BlockList, isIP } from "node:net";
|
|
867
|
+
import { z as z6 } from "zod";
|
|
868
|
+
var tailnet = new BlockList;
|
|
869
|
+
tailnet.addSubnet("100.64.0.0", 10, "ipv4");
|
|
870
|
+
tailnet.addSubnet("fd7a:115c:a1e0::", 48, "ipv6");
|
|
871
|
+
var loopback = new BlockList;
|
|
872
|
+
loopback.addSubnet("127.0.0.0", 8, "ipv4");
|
|
873
|
+
loopback.addAddress("::1", "ipv6");
|
|
874
|
+
var peerKind = (address) => {
|
|
875
|
+
const version = isIP(address);
|
|
876
|
+
if (version === 0) {
|
|
877
|
+
return "other";
|
|
878
|
+
}
|
|
879
|
+
const family = version === 6 ? "ipv6" : "ipv4";
|
|
880
|
+
if (loopback.check(address, family)) {
|
|
881
|
+
return "loopback";
|
|
882
|
+
}
|
|
883
|
+
return tailnet.check(address, family) ? "tailnet" : "other";
|
|
884
|
+
};
|
|
885
|
+
var whoisSchema = z6.object({
|
|
886
|
+
UserProfile: z6.object({
|
|
887
|
+
LoginName: z6.string().nonempty(),
|
|
888
|
+
DisplayName: z6.string()
|
|
889
|
+
})
|
|
890
|
+
});
|
|
891
|
+
var runCommand = async (command) => {
|
|
892
|
+
const child = Bun.spawn(command, {
|
|
893
|
+
stdout: "pipe",
|
|
894
|
+
stderr: "ignore",
|
|
895
|
+
timeout: 5000
|
|
896
|
+
});
|
|
897
|
+
const [stdout, exitCode] = await Promise.all([
|
|
898
|
+
new Response(child.stdout).text(),
|
|
899
|
+
child.exited
|
|
900
|
+
]);
|
|
901
|
+
return { stdout, exitCode };
|
|
902
|
+
};
|
|
903
|
+
var whoisCacheMs = 60000;
|
|
904
|
+
var createWhois = (context) => {
|
|
905
|
+
const cache = new Map;
|
|
906
|
+
const lookUp = async (address) => {
|
|
907
|
+
try {
|
|
908
|
+
const { exitCode, stdout } = await context.run([
|
|
909
|
+
"tailscale",
|
|
910
|
+
"whois",
|
|
911
|
+
"--json",
|
|
912
|
+
address
|
|
913
|
+
]);
|
|
914
|
+
if (exitCode !== 0) {
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
const { UserProfile } = whoisSchema.parse(JSON.parse(stdout));
|
|
918
|
+
return {
|
|
919
|
+
login: UserProfile.LoginName,
|
|
920
|
+
name: UserProfile.DisplayName || UserProfile.LoginName
|
|
921
|
+
};
|
|
922
|
+
} catch (error) {
|
|
923
|
+
context.log(`tailscale whois ${address} failed: ${errorMessage(error)}`);
|
|
924
|
+
return null;
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
return (address) => {
|
|
928
|
+
const now = context.now();
|
|
929
|
+
for (const [cached, { expires }] of cache) {
|
|
930
|
+
if (expires <= now) {
|
|
931
|
+
cache.delete(cached);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const known = cache.get(address);
|
|
935
|
+
if (known) {
|
|
936
|
+
return known.user;
|
|
937
|
+
}
|
|
938
|
+
const user = lookUp(address);
|
|
939
|
+
cache.set(address, { expires: now + whoisCacheMs, user });
|
|
940
|
+
return user;
|
|
941
|
+
};
|
|
942
|
+
};
|
|
943
|
+
|
|
944
|
+
// packages/agent/src/access.ts
|
|
945
|
+
var noAccess = { roles: {}, tailnetDefault: null };
|
|
946
|
+
var readAccessConfig = async (file) => await readJsonFile(file, accessConfigSchema) ?? noAccess;
|
|
947
|
+
|
|
948
|
+
// packages/agent/src/agent.ts
|
|
949
|
+
import { controllerCredentialsSchema as controllerCredentialsSchema2, loginCommandSchema } from "@tsplc/build";
|
|
950
|
+
import { runtimePort } from "@tsplc/config/build";
|
|
951
|
+
import { plantAgentEnv } from "@tsplc/server/plant-agent";
|
|
952
|
+
|
|
953
|
+
// packages/agent/src/access.ts
|
|
954
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
955
|
+
import { isIP as isIP2 } from "node:net";
|
|
956
|
+
import { dashboardHeader as dashboardHeader2, tokenQueryParameter as tokenQueryParameter2 } from "@tsplc/debug/api";
|
|
957
|
+
import { controllerRestartPath as controllerRestartPath2 } from "@tsplc/server/plant-agent";
|
|
958
|
+
var noAccess2 = { roles: {}, tailnetDefault: null };
|
|
959
|
+
var readAccessConfig2 = async (file) => await readJsonFile(file, accessConfigSchema) ?? noAccess2;
|
|
960
|
+
var matches = (presented, token) => timingSafeEqual(createHash3("sha256").update(presented).digest(), createHash3("sha256").update(token).digest());
|
|
961
|
+
var refuse = (status, error) => Response.json({ error }, { status });
|
|
962
|
+
var unauthorized = () => refuse(401, "Unauthorized");
|
|
963
|
+
var forwardingHeaders = [
|
|
964
|
+
"forwarded",
|
|
965
|
+
"x-forwarded-for",
|
|
966
|
+
"tailscale-user-login"
|
|
967
|
+
];
|
|
968
|
+
var namesAgentDirectly = (request) => {
|
|
969
|
+
const host = new URL(request.url).hostname.replace(/^\[(.*)\]$/, "$1");
|
|
970
|
+
return isIP2(host) !== 0 || !host.includes(".") || host.endsWith(".ts.net") || host === "localhost";
|
|
971
|
+
};
|
|
972
|
+
var changes = (request) => request.method !== "GET";
|
|
973
|
+
var fromDashboard = (request) => request.headers.get(dashboardHeader2) === "1";
|
|
974
|
+
var crossSite = () => refuse(403, `A browser's request that changes something needs the ${dashboardHeader2}: 1 header`);
|
|
975
|
+
var createAccess = (options) => {
|
|
976
|
+
const sessions = createSessions(options.now);
|
|
977
|
+
const tokenIdentity = (presented) => {
|
|
978
|
+
if (matches(presented, options.token)) {
|
|
979
|
+
return { login: null, name: "Agent token", role: "admin", via: "token" };
|
|
980
|
+
}
|
|
981
|
+
if (options.readToken !== null && matches(presented, options.readToken)) {
|
|
982
|
+
return {
|
|
983
|
+
login: null,
|
|
984
|
+
name: "Read token",
|
|
985
|
+
role: "viewer",
|
|
986
|
+
via: "token"
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
return null;
|
|
990
|
+
};
|
|
991
|
+
const serverIdentity = {
|
|
992
|
+
login: null,
|
|
993
|
+
name: "Line server",
|
|
994
|
+
role: "deployer",
|
|
995
|
+
via: "server"
|
|
996
|
+
};
|
|
997
|
+
const peerIdentity = async (request, peer) => {
|
|
998
|
+
if (!peer || !namesAgentDirectly(request) || forwardingHeaders.some((name) => request.headers.has(name))) {
|
|
999
|
+
return null;
|
|
1000
|
+
}
|
|
1001
|
+
const kind = peerKind(peer.address);
|
|
1002
|
+
if (kind === "loopback") {
|
|
1003
|
+
return { login: null, name: "This PC", role: "admin", via: "local" };
|
|
1004
|
+
}
|
|
1005
|
+
if (kind !== "tailnet") {
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
const user = await options.whois(peer.address);
|
|
1009
|
+
if (!user) {
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
const config = await readAccessConfig2(options.file).catch((error) => {
|
|
1013
|
+
options.log(`Can't read ${options.file}: ${errorMessage(error)}`);
|
|
1014
|
+
return noAccess2;
|
|
1015
|
+
});
|
|
1016
|
+
const role = config.roles[user.login] ?? config.tailnetDefault;
|
|
1017
|
+
return role && { login: user.login, name: user.name, role, via: "tailscale" };
|
|
1018
|
+
};
|
|
1019
|
+
const identify = async (request, peer, route) => {
|
|
1020
|
+
const { searchParams, pathname } = new URL(request.url);
|
|
1021
|
+
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (pathname.startsWith(debuggerMount) ? searchParams.get(tokenQueryParameter2) : null);
|
|
1022
|
+
if (presented !== null) {
|
|
1023
|
+
if (options.serverToken !== null && matches(presented, options.serverToken)) {
|
|
1024
|
+
return request.method === "POST" && pathname === controllerRestartPath2 ? serverIdentity : refuse(403, "The server's token only restarts the controller");
|
|
1025
|
+
}
|
|
1026
|
+
return tokenIdentity(presented) ?? unauthorized();
|
|
1027
|
+
}
|
|
1028
|
+
if (!route.browser) {
|
|
1029
|
+
return unauthorized();
|
|
1030
|
+
}
|
|
1031
|
+
const identity = sessions.find(request) ?? await peerIdentity(request, peer);
|
|
1032
|
+
if (!identity) {
|
|
1033
|
+
return unauthorized();
|
|
1034
|
+
}
|
|
1035
|
+
return changes(request) && !fromDashboard(request) ? crossSite() : identity;
|
|
1036
|
+
};
|
|
1037
|
+
const handle = async (request) => {
|
|
1038
|
+
const { pathname } = new URL(request.url);
|
|
1039
|
+
if (pathname !== "/api/session" || request.method !== "POST" && request.method !== "DELETE") {
|
|
1040
|
+
return null;
|
|
1041
|
+
}
|
|
1042
|
+
if (!fromDashboard(request)) {
|
|
1043
|
+
return crossSite();
|
|
1044
|
+
}
|
|
1045
|
+
if (request.method === "DELETE") {
|
|
1046
|
+
return new Response(null, {
|
|
1047
|
+
status: 204,
|
|
1048
|
+
headers: { "Set-Cookie": sessions.close(request) }
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
const body = sessionRequestSchema.safeParse(await request.json().catch(() => null));
|
|
1052
|
+
if (!body.success) {
|
|
1053
|
+
return Response.json({ error: "Send { token }" }, { status: 400 });
|
|
1054
|
+
}
|
|
1055
|
+
const identity = tokenIdentity(body.data.token);
|
|
1056
|
+
if (!identity) {
|
|
1057
|
+
return unauthorized();
|
|
1058
|
+
}
|
|
1059
|
+
return Response.json(identity, {
|
|
1060
|
+
headers: { "Set-Cookie": sessions.open(identity) }
|
|
1061
|
+
});
|
|
1062
|
+
};
|
|
1063
|
+
const routes = [
|
|
1064
|
+
{
|
|
1065
|
+
method: "GET",
|
|
1066
|
+
pattern: "/api/session",
|
|
1067
|
+
role: "viewer",
|
|
1068
|
+
handle: async (_request, { identity }) => Response.json(identity)
|
|
1069
|
+
},
|
|
1070
|
+
{
|
|
1071
|
+
method: "GET",
|
|
1072
|
+
pattern: "/api/access",
|
|
1073
|
+
role: "admin",
|
|
1074
|
+
handle: async () => Response.json(await readAccessConfig2(options.file))
|
|
1075
|
+
},
|
|
1076
|
+
{
|
|
1077
|
+
method: "PUT",
|
|
1078
|
+
pattern: "/api/access",
|
|
1079
|
+
role: "admin",
|
|
1080
|
+
handle: async (request, { identity }) => {
|
|
1081
|
+
const config = accessConfigSchema.parse(await request.json());
|
|
1082
|
+
const previous = await readAccessConfig2(options.file);
|
|
1083
|
+
writeJsonFile(options.file, config);
|
|
1084
|
+
await options.audit.record({
|
|
1085
|
+
by: authorOf(identity),
|
|
1086
|
+
command: "access",
|
|
1087
|
+
values: auditedAccess(config),
|
|
1088
|
+
previous: auditedAccess(previous),
|
|
1089
|
+
error: null
|
|
1090
|
+
});
|
|
1091
|
+
return Response.json(config);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
];
|
|
1095
|
+
return { identify, handle, routes };
|
|
1096
|
+
};
|
|
1097
|
+
var auditedAccess = (config) => ({
|
|
1098
|
+
...config.roles,
|
|
1099
|
+
"(tailnet default)": config.tailnetDefault ?? "none"
|
|
1100
|
+
});
|
|
1101
|
+
|
|
1102
|
+
// packages/agent/src/codesys.ts
|
|
1103
|
+
import { join as join3 } from "node:path";
|
|
1104
|
+
import {
|
|
1105
|
+
builderImageStatus,
|
|
1106
|
+
captureDocker,
|
|
1107
|
+
gatewayImage,
|
|
1108
|
+
setupReason
|
|
1109
|
+
} from "@tsplc/build";
|
|
1110
|
+
import { gatewayPort, resolveConfig } from "@tsplc/config/build";
|
|
1111
|
+
var network = "tsplc-agent";
|
|
1112
|
+
var codesysNetwork = "tsplc-agent-codesys";
|
|
1113
|
+
var gateway = { host: "tsplc-agent-gateway", port: gatewayPort };
|
|
1114
|
+
var loginContainer = "tsplc-agent-login";
|
|
1115
|
+
var deployContainer = "tsplc-agent-deploy";
|
|
1116
|
+
var agentDockerResources = {
|
|
1117
|
+
containers: [gateway.host, deployContainer, loginContainer],
|
|
1118
|
+
networks: [network, codesysNetwork]
|
|
1119
|
+
};
|
|
1120
|
+
var credentialNames = {
|
|
1121
|
+
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
1122
|
+
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
1123
|
+
};
|
|
1124
|
+
var dockerTimeout = 60000;
|
|
1125
|
+
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
1126
|
+
var ensureNetwork = async (name, ...options) => {
|
|
1127
|
+
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
1128
|
+
await docker("network", "create", ...options, name);
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
var setupNeeded = async () => {
|
|
1132
|
+
const status = await builderImageStatus();
|
|
1133
|
+
const reason = setupReason(status) ?? (await docker("image", "ls", "--quiet", gatewayImage) ? null : `the CODESYS gateway image ${gatewayImage} is missing`);
|
|
1134
|
+
return { status, reason };
|
|
1135
|
+
};
|
|
1136
|
+
var requireBuilder = async () => {
|
|
1137
|
+
const { status, reason } = await setupNeeded().catch((cause) => {
|
|
1138
|
+
throw new AgentError(`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`, 503);
|
|
1139
|
+
});
|
|
1140
|
+
if (reason) {
|
|
1141
|
+
throw new AgentError(`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`, 409);
|
|
1142
|
+
}
|
|
1143
|
+
return status;
|
|
1144
|
+
};
|
|
1145
|
+
var describeBuilder = async () => {
|
|
1146
|
+
const { status, reason } = await setupNeeded();
|
|
1147
|
+
if (reason) {
|
|
1148
|
+
return `Deployments and logins need tsplc-agent setup first: ${reason}`;
|
|
1149
|
+
}
|
|
1150
|
+
if (status.kind === "unverified") {
|
|
1151
|
+
return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
|
|
1152
|
+
}
|
|
1153
|
+
return "The CODESYS images match this tsPLC";
|
|
1154
|
+
};
|
|
1155
|
+
var removeContainer = (name) => docker("rm", "--force", name);
|
|
1156
|
+
var ensureGateway = async () => {
|
|
1157
|
+
await ensureNetwork(network);
|
|
1158
|
+
await ensureNetwork(codesysNetwork, "--internal");
|
|
1159
|
+
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
1160
|
+
await docker("rm", "--force", gateway.host);
|
|
1161
|
+
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
1162
|
+
}
|
|
1163
|
+
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
1164
|
+
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
1165
|
+
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
1166
|
+
}
|
|
1167
|
+
};
|
|
1168
|
+
var credentialEnvironment = (credentials) => ({
|
|
1169
|
+
[credentialNames.usernameEnv]: credentials.username,
|
|
1170
|
+
[credentialNames.passwordEnv]: credentials.password
|
|
1171
|
+
});
|
|
1172
|
+
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
1173
|
+
...resolveConfig({
|
|
1174
|
+
...release.manifest.config,
|
|
1175
|
+
...settings.bulkImport && { bulkImport: true },
|
|
1176
|
+
online: {
|
|
1177
|
+
network: codesysNetwork,
|
|
1178
|
+
gateway,
|
|
1179
|
+
device: target,
|
|
1180
|
+
credentials: credentialNames
|
|
1181
|
+
}
|
|
1182
|
+
}, join3(release.directory, manifestFile)),
|
|
1183
|
+
outDir: controllerDirectory
|
|
1184
|
+
});
|
|
1185
|
+
var deployedControllerConfig = async (state, settings) => {
|
|
1186
|
+
const deployed = await state.release();
|
|
1187
|
+
const target = await state.target();
|
|
1188
|
+
if (!deployed || !target) {
|
|
1189
|
+
return null;
|
|
1190
|
+
}
|
|
1191
|
+
return controllerConfig(await loadRelease(state.paths.releases, deployed.id), target, state.paths.controller, settings);
|
|
1192
|
+
};
|
|
1193
|
+
|
|
1194
|
+
// packages/agent/src/dashboard/index.ts
|
|
1195
|
+
import { createRequire } from "node:module";
|
|
1196
|
+
import { basename, dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
1197
|
+
import { envName as envName2 } from "@tsplc/config/build";
|
|
1198
|
+
import { dashboardHeader as dashboardHeader3 } from "@tsplc/debug/api";
|
|
1199
|
+
import { z as z7 } from "zod";
|
|
1200
|
+
var pages = [
|
|
1201
|
+
{ path: "/deployments", label: "Deployments", role: "viewer" },
|
|
1202
|
+
{ path: "/environment", label: "Environment", role: "viewer" },
|
|
1203
|
+
{ path: "/audit", label: "Audit", role: "viewer" },
|
|
1204
|
+
{ path: "/access", label: "Access", role: "admin" }
|
|
1205
|
+
];
|
|
1206
|
+
var dashboardAssets = "/dashboard-assets/";
|
|
1207
|
+
var themeKey = "tsplc-theme";
|
|
1208
|
+
var page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>tsPLC</title><script>document.documentElement.dataset.theme=localStorage.getItem(${JSON.stringify(themeKey)})||""</script><link rel="stylesheet" href="${dashboardAssets}dashboard.css"><script type="module" src="${dashboardAssets}main.js"></script></head><body><main id="app"></main></body></html>`;
|
|
1209
|
+
var envNamePattern = () => {
|
|
1210
|
+
const { pattern } = z7.toJSONSchema(envName2);
|
|
1211
|
+
if (pattern === undefined) {
|
|
1212
|
+
throw new Error("The config's environment variable name has no pattern");
|
|
1213
|
+
}
|
|
1214
|
+
return pattern;
|
|
1215
|
+
};
|
|
1216
|
+
var dashboardContract = () => ({
|
|
1217
|
+
roles,
|
|
1218
|
+
permissions: Object.fromEntries(roles.map((role) => [
|
|
1219
|
+
role,
|
|
1220
|
+
Object.fromEntries(roles.map((required) => [required, allows(role, required)]))
|
|
1221
|
+
])),
|
|
1222
|
+
pages,
|
|
1223
|
+
themeKey,
|
|
1224
|
+
auditLimits,
|
|
1225
|
+
finalStates,
|
|
1226
|
+
cancelableStates,
|
|
1227
|
+
envNamePattern: envNamePattern(),
|
|
1228
|
+
dashboardHeader: dashboardHeader3,
|
|
1229
|
+
agentVersionHeader,
|
|
1230
|
+
debuggerMount,
|
|
1231
|
+
statusPath,
|
|
1232
|
+
deploymentsApiPath,
|
|
1233
|
+
deploymentPages: deploymentPagePath("")
|
|
1234
|
+
});
|
|
1235
|
+
var bundle = async () => {
|
|
1236
|
+
const sources = resolve2(dirname2(createRequire(import.meta.url).resolve("@tsplc/agent")), "../src/dashboard/ui");
|
|
1237
|
+
const result = await Bun.build({
|
|
1238
|
+
entrypoints: [
|
|
1239
|
+
resolve2(sources, "main.ts"),
|
|
1240
|
+
resolve2(sources, "dashboard.css")
|
|
1241
|
+
],
|
|
1242
|
+
target: "browser",
|
|
1243
|
+
conditions: ["bun"],
|
|
1244
|
+
minify: true,
|
|
1245
|
+
naming: "[name].[ext]",
|
|
1246
|
+
define: { TSPLC_CONTRACT: JSON.stringify(dashboardContract()) }
|
|
1247
|
+
});
|
|
1248
|
+
if (!result.success) {
|
|
1249
|
+
throw new Error(`Bundling the dashboard failed:
|
|
1250
|
+
${result.logs.map(String).join(`
|
|
1251
|
+
`)}`);
|
|
1252
|
+
}
|
|
1253
|
+
const assets = new Map;
|
|
1254
|
+
for (const output of result.outputs) {
|
|
1255
|
+
assets.set(basename(output.path), {
|
|
1256
|
+
text: await output.text(),
|
|
1257
|
+
type: output.type
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
return assets;
|
|
1261
|
+
};
|
|
1262
|
+
var isPage = (pathname) => pathname === "/" || pages.some(({ path }) => pathname === path || pathname.startsWith(`${path}/`));
|
|
1263
|
+
var createDashboard = () => {
|
|
1264
|
+
let assets;
|
|
1265
|
+
return {
|
|
1266
|
+
handle: async (request) => {
|
|
1267
|
+
const { pathname } = new URL(request.url);
|
|
1268
|
+
if (request.method !== "GET") {
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
if (isPage(pathname)) {
|
|
1272
|
+
return new Response(page, {
|
|
1273
|
+
headers: {
|
|
1274
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
1275
|
+
"Cache-Control": "no-cache"
|
|
1276
|
+
}
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
if (!pathname.startsWith(dashboardAssets)) {
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
assets ??= bundle();
|
|
1283
|
+
try {
|
|
1284
|
+
const asset = (await assets).get(pathname.slice(dashboardAssets.length));
|
|
1285
|
+
if (!asset) {
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
1288
|
+
return new Response(asset.text, {
|
|
1289
|
+
headers: { "Content-Type": asset.type, "Cache-Control": "no-cache" }
|
|
1290
|
+
});
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
assets = undefined;
|
|
1293
|
+
return new Response(errorMessage(error), { status: 500 });
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
};
|
|
1298
|
+
|
|
1299
|
+
// packages/agent/src/debugging.ts
|
|
1300
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
1301
|
+
import { join as join5 } from "node:path";
|
|
1302
|
+
import {
|
|
1303
|
+
createDebugger,
|
|
1304
|
+
createDebugHandler,
|
|
1305
|
+
loadDebugBuild,
|
|
1306
|
+
loginReader,
|
|
1307
|
+
timelineEntries
|
|
1308
|
+
} from "@tsplc/debug";
|
|
1309
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
1310
|
+
|
|
1311
|
+
// packages/agent/src/secrets.ts
|
|
1312
|
+
import { mkdir as mkdir3, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1313
|
+
import { dirname as dirname3, join as join4, relative as relative2 } from "node:path";
|
|
1314
|
+
import {
|
|
1315
|
+
secretPlaceholder,
|
|
1316
|
+
secretValue as secretValue2
|
|
1317
|
+
} from "@tsplc/config";
|
|
1318
|
+
import { escapeString } from "@tsplc/iec/st";
|
|
1319
|
+
var agentService = "tsplc-agent";
|
|
1320
|
+
var environmentService = "tsplc-agent-env";
|
|
1321
|
+
var controllerSecretNames = {
|
|
1322
|
+
username: "controller-username",
|
|
1323
|
+
password: "controller-password"
|
|
1324
|
+
};
|
|
1325
|
+
var agentSetting = async (name, environment) => environment[name] ?? await Bun.secrets.get({ service: agentService, name });
|
|
1326
|
+
var storedCredentials = async () => {
|
|
1327
|
+
const [username, password] = await Promise.all([
|
|
1328
|
+
Bun.secrets.get({
|
|
1329
|
+
service: agentService,
|
|
1330
|
+
name: controllerSecretNames.username
|
|
1331
|
+
}),
|
|
1332
|
+
Bun.secrets.get({
|
|
1333
|
+
service: agentService,
|
|
1334
|
+
name: controllerSecretNames.password
|
|
1335
|
+
})
|
|
1336
|
+
]);
|
|
1337
|
+
return username && password ? { username, password } : null;
|
|
1338
|
+
};
|
|
1339
|
+
var controllerCredentials = async (sent) => {
|
|
1340
|
+
const credentials = sent ?? await storedCredentials();
|
|
1341
|
+
if (!credentials) {
|
|
1342
|
+
throw new AgentError("No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there", 409);
|
|
1343
|
+
}
|
|
1344
|
+
return credentials;
|
|
1345
|
+
};
|
|
1346
|
+
var readSecrets = async (secrets) => {
|
|
1347
|
+
const values = new Map;
|
|
1348
|
+
if (!secrets) {
|
|
1349
|
+
return values;
|
|
1350
|
+
}
|
|
1351
|
+
const { service } = secrets;
|
|
1352
|
+
const missing = [];
|
|
1353
|
+
for (const name of secrets.names) {
|
|
1354
|
+
const value = await Bun.secrets.get({ service, name });
|
|
1355
|
+
const valid = secretValue2.safeParse(value);
|
|
1356
|
+
if (!value) {
|
|
1357
|
+
missing.push(name);
|
|
1358
|
+
} else if (!valid.success) {
|
|
1359
|
+
throw new AgentError(`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(" and ")}`, 409);
|
|
1360
|
+
} else {
|
|
1361
|
+
values.set(name, value);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (missing.length) {
|
|
1365
|
+
throw new AgentError(`The plant PC has no ${missing.join(", ")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`, 409);
|
|
1366
|
+
}
|
|
1367
|
+
return values;
|
|
1368
|
+
};
|
|
1369
|
+
var storedSecrets = async (secrets) => {
|
|
1370
|
+
if (!secrets) {
|
|
1371
|
+
return {};
|
|
1372
|
+
}
|
|
1373
|
+
const stored = await Promise.all(secrets.names.map(async (name) => ({
|
|
1374
|
+
name,
|
|
1375
|
+
value: await Bun.secrets.get({ service: secrets.service, name })
|
|
1376
|
+
})));
|
|
1377
|
+
return Object.fromEntries(stored.flatMap(({ name, value }) => value === null ? [] : [[name, value]]));
|
|
1378
|
+
};
|
|
1379
|
+
var serverEnvironment = async ({ manifest }, environment) => ({
|
|
1380
|
+
...environment,
|
|
1381
|
+
...manifest.values,
|
|
1382
|
+
...await storedSecrets(manifest.secrets)
|
|
1383
|
+
});
|
|
1384
|
+
var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
|
|
1385
|
+
var withSecrets = async (config, secrets, directory) => {
|
|
1386
|
+
await rm2(directory, { recursive: true, force: true });
|
|
1387
|
+
for await (const path of new Bun.Glob("**/*").scan({
|
|
1388
|
+
cwd: config.sourceDir,
|
|
1389
|
+
dot: true
|
|
1390
|
+
})) {
|
|
1391
|
+
const file = join4(directory, path);
|
|
1392
|
+
await mkdir3(dirname3(file), { recursive: true });
|
|
1393
|
+
await writeFile2(file, fillSecrets(await readFile3(join4(config.sourceDir, path), "utf8"), secrets));
|
|
1394
|
+
}
|
|
1395
|
+
return {
|
|
1396
|
+
...config,
|
|
1397
|
+
sourceDir: directory,
|
|
1398
|
+
entry: join4(directory, relative2(config.sourceDir, config.entry))
|
|
1399
|
+
};
|
|
1400
|
+
};
|
|
1401
|
+
|
|
1402
|
+
// packages/agent/src/debugging.ts
|
|
1403
|
+
var recentEntries = 500;
|
|
1404
|
+
var createDebugging = (context) => {
|
|
1405
|
+
const { state, log } = context;
|
|
1406
|
+
const start = async () => {
|
|
1407
|
+
const release = await state.release();
|
|
1408
|
+
if (!release) {
|
|
1409
|
+
return null;
|
|
1410
|
+
}
|
|
1411
|
+
const stored = await loadRelease(state.paths.releases, release.id);
|
|
1412
|
+
const manifestFile = join5(stored.directory, debugManifestFile);
|
|
1413
|
+
if (!existsSync3(manifestFile)) {
|
|
1414
|
+
return null;
|
|
1415
|
+
}
|
|
1416
|
+
const { serverTokenEnv, debug: settings } = stored.manifest;
|
|
1417
|
+
const serverToken = serverTokenEnv && (await serverEnvironment(stored, context.environment))[serverTokenEnv];
|
|
1418
|
+
const build = await loadDebugBuild(manifestFile);
|
|
1419
|
+
const debug = await createDebugger({
|
|
1420
|
+
...build,
|
|
1421
|
+
...loginReader(build.manifest, {
|
|
1422
|
+
read: context.readLogin,
|
|
1423
|
+
status: context.loginStatus,
|
|
1424
|
+
endpoint: "the agent's login"
|
|
1425
|
+
}),
|
|
1426
|
+
stateDirectory: state.paths.debug,
|
|
1427
|
+
watch: settings?.watch ?? {},
|
|
1428
|
+
...context.serverHealthUrl && serverToken && {
|
|
1429
|
+
server: {
|
|
1430
|
+
url: new URL(context.serverHealthUrl).origin,
|
|
1431
|
+
token: serverToken
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
release: {
|
|
1435
|
+
id: release.id,
|
|
1436
|
+
deployedAt: release.deployedAt,
|
|
1437
|
+
operation: release.operation
|
|
1438
|
+
},
|
|
1439
|
+
timeline: [
|
|
1440
|
+
...(await readJsonl(state.paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
1441
|
+
...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
1442
|
+
],
|
|
1443
|
+
log
|
|
1444
|
+
});
|
|
1445
|
+
return { debug, handle: createDebugHandler(debug, log) };
|
|
1446
|
+
};
|
|
1447
|
+
const startOrLog = () => start().catch((error) => {
|
|
1448
|
+
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
1449
|
+
return null;
|
|
1450
|
+
});
|
|
1451
|
+
let current = startOrLog();
|
|
1452
|
+
return {
|
|
1453
|
+
handle: async (request, route) => {
|
|
1454
|
+
const debugging = await current;
|
|
1455
|
+
if (!debugging) {
|
|
1456
|
+
return Response.json({
|
|
1457
|
+
error: "The deployed release has no debug manifest, or the debugger failed to start"
|
|
1458
|
+
}, { status: 503 });
|
|
1459
|
+
}
|
|
1460
|
+
return debugging.handle(request, route);
|
|
1461
|
+
},
|
|
1462
|
+
record: async ({ at, ...audit }) => {
|
|
1463
|
+
(await current)?.debug.record(timelineEntries.audit(at, audit));
|
|
1464
|
+
},
|
|
1465
|
+
restart: () => {
|
|
1466
|
+
current = current.then(async (debugging) => {
|
|
1467
|
+
await debugging?.debug.close();
|
|
1468
|
+
return startOrLog();
|
|
1469
|
+
});
|
|
1470
|
+
},
|
|
1471
|
+
close: async () => {
|
|
1472
|
+
await (await current)?.debug.close();
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
};
|
|
1476
|
+
|
|
1477
|
+
// packages/agent/src/deploy.ts
|
|
1478
|
+
import {
|
|
1479
|
+
controllerBaseline,
|
|
1480
|
+
restartWarmController,
|
|
1481
|
+
reviewWarmController,
|
|
1482
|
+
settleWarmController,
|
|
1483
|
+
startWarmController,
|
|
1484
|
+
updateWarmController
|
|
1485
|
+
} from "@tsplc/build";
|
|
1486
|
+
|
|
1487
|
+
// packages/agent/src/deployments/runner.ts
|
|
1488
|
+
import { once } from "node:events";
|
|
1489
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
1490
|
+
import { join as join7 } from "node:path";
|
|
1491
|
+
import {
|
|
1492
|
+
DownloadRequiredError,
|
|
1493
|
+
describeFinding,
|
|
1494
|
+
requiresDownload as requiresDownload2
|
|
1495
|
+
} from "@tsplc/build";
|
|
1496
|
+
import { loadManifest } from "@tsplc/debug";
|
|
1497
|
+
import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
|
|
1498
|
+
|
|
1499
|
+
// packages/agent/src/operations.ts
|
|
1500
|
+
import { requiresDownload, transferRollback } from "@tsplc/build";
|
|
1501
|
+
var failureReport = (error) => {
|
|
1502
|
+
const rollback = transferRollback(error);
|
|
1503
|
+
return {
|
|
1504
|
+
message: errorMessage(error),
|
|
1505
|
+
downloadRequired: requiresDownload(error),
|
|
1506
|
+
...rollback && { rollback }
|
|
1507
|
+
};
|
|
1508
|
+
};
|
|
1509
|
+
var createOperations = (log) => {
|
|
1510
|
+
let busy;
|
|
1511
|
+
let held = false;
|
|
1512
|
+
const waiting = new Set;
|
|
1513
|
+
const requireIdle = () => {
|
|
1514
|
+
if (held) {
|
|
1515
|
+
throw new AgentError("The plant agent is being upgraded; try again once it is back", 503);
|
|
1516
|
+
}
|
|
1517
|
+
if (busy) {
|
|
1518
|
+
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
const wakeWaiting = () => {
|
|
1522
|
+
for (const wake of waiting) {
|
|
1523
|
+
wake();
|
|
1524
|
+
}
|
|
1525
|
+
waiting.clear();
|
|
1526
|
+
};
|
|
1527
|
+
const acquire = (operation) => {
|
|
1528
|
+
requireIdle();
|
|
1529
|
+
busy = operation;
|
|
1530
|
+
};
|
|
1531
|
+
const free = () => {
|
|
1532
|
+
busy = undefined;
|
|
1533
|
+
wakeWaiting();
|
|
1534
|
+
};
|
|
1535
|
+
const blockedBy = () => held ? "the plant agent's upgrade" : busy;
|
|
1536
|
+
return {
|
|
1537
|
+
busy: () => busy,
|
|
1538
|
+
blockedBy,
|
|
1539
|
+
whenIdle: () => blockedBy() ? new Promise((resolve) => waiting.add(resolve)) : Promise.resolve(),
|
|
1540
|
+
requireIdle,
|
|
1541
|
+
hold: () => {
|
|
1542
|
+
requireIdle();
|
|
1543
|
+
held = true;
|
|
1544
|
+
},
|
|
1545
|
+
release: () => {
|
|
1546
|
+
held = false;
|
|
1547
|
+
wakeWaiting();
|
|
1548
|
+
},
|
|
1549
|
+
held: () => held,
|
|
1550
|
+
exclusive: async (operation, run) => {
|
|
1551
|
+
acquire(operation);
|
|
1552
|
+
try {
|
|
1553
|
+
return await run();
|
|
1554
|
+
} finally {
|
|
1555
|
+
free();
|
|
1556
|
+
}
|
|
1557
|
+
},
|
|
1558
|
+
stream: (operation, run, { reportsRollback = false } = {}) => {
|
|
1559
|
+
acquire(operation);
|
|
1560
|
+
const encoder = new TextEncoder;
|
|
1561
|
+
let listening = true;
|
|
1562
|
+
return new Response(new ReadableStream({
|
|
1563
|
+
start: async (controller) => {
|
|
1564
|
+
const write = (text) => {
|
|
1565
|
+
if (listening) {
|
|
1566
|
+
controller.enqueue(encoder.encode(text));
|
|
1567
|
+
}
|
|
1568
|
+
};
|
|
1569
|
+
const emit = (event) => write(`${JSON.stringify(event)}
|
|
1570
|
+
`);
|
|
1571
|
+
const heartbeat = setInterval(() => write(`
|
|
1572
|
+
`), 15000);
|
|
1573
|
+
try {
|
|
1574
|
+
emit({ kind: "done", result: await run(emit) });
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1577
|
+
const { rollback, ...failure } = failureReport(error);
|
|
1578
|
+
emit({
|
|
1579
|
+
kind: "error",
|
|
1580
|
+
...failure,
|
|
1581
|
+
...reportsRollback && rollback && { rollback }
|
|
1582
|
+
});
|
|
1583
|
+
} finally {
|
|
1584
|
+
clearInterval(heartbeat);
|
|
1585
|
+
free();
|
|
1586
|
+
if (listening) {
|
|
1587
|
+
controller.close();
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
},
|
|
1591
|
+
cancel: () => {
|
|
1592
|
+
listening = false;
|
|
1593
|
+
}
|
|
1594
|
+
}), { headers: { "Content-Type": "application/x-ndjson" } });
|
|
1595
|
+
}
|
|
1596
|
+
};
|
|
1597
|
+
};
|
|
1598
|
+
|
|
1599
|
+
// packages/agent/src/deployments/health.ts
|
|
1600
|
+
import { healthReplySchema } from "@tsplc/server/plant-agent";
|
|
1601
|
+
var healthTimeoutMs = 5000;
|
|
1602
|
+
var plcHealth = (body) => {
|
|
1603
|
+
const parsed = healthReplySchema.safeParse(body);
|
|
1604
|
+
if (!parsed.success) {
|
|
1605
|
+
return "unknown";
|
|
1606
|
+
}
|
|
1607
|
+
return parsed.data.plcConnected ? "ok" : "failed";
|
|
1608
|
+
};
|
|
1609
|
+
var serverHealth = async (server) => {
|
|
1610
|
+
const { healthUrl } = server;
|
|
1611
|
+
if (healthUrl === null) {
|
|
1612
|
+
return server.status()?.running ? { server: "ok", plc: "unknown", failure: null } : {
|
|
1613
|
+
server: "failed",
|
|
1614
|
+
plc: "unknown",
|
|
1615
|
+
failure: "The server isn't running"
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
const response = await fetch(healthUrl, {
|
|
1619
|
+
signal: AbortSignal.timeout(healthTimeoutMs)
|
|
1620
|
+
}).catch((error) => errorMessage(error));
|
|
1621
|
+
if (typeof response === "string") {
|
|
1622
|
+
return {
|
|
1623
|
+
server: "failed",
|
|
1624
|
+
plc: "unknown",
|
|
1625
|
+
failure: `The server doesn't answer on ${healthUrl}: ${response}`
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
if (!response.ok) {
|
|
1629
|
+
return {
|
|
1630
|
+
server: "failed",
|
|
1631
|
+
plc: "unknown",
|
|
1632
|
+
failure: `The server answers ${response.status} on ${healthUrl}`
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
return {
|
|
1636
|
+
server: "ok",
|
|
1637
|
+
plc: plcHealth(await response.json().catch(() => null)),
|
|
1638
|
+
failure: null
|
|
1639
|
+
};
|
|
1640
|
+
};
|
|
1641
|
+
var noServer = {
|
|
1642
|
+
server: "none",
|
|
1643
|
+
plc: "unknown",
|
|
1644
|
+
failure: null
|
|
1645
|
+
};
|
|
1646
|
+
var checkHealth = async (options) => {
|
|
1647
|
+
const controller = options.controllerState === "run" ? "ok" : "failed";
|
|
1648
|
+
const { server, plc, failure } = options.hasServer ? await serverHealth(options.server) : noServer;
|
|
1649
|
+
const problems = [
|
|
1650
|
+
controller === "failed" && `The controller's application is in state ${options.controllerState}`,
|
|
1651
|
+
failure,
|
|
1652
|
+
plc === "failed" && "The server isn't connected to the PLC"
|
|
1653
|
+
].filter((problem) => typeof problem === "string");
|
|
1654
|
+
return {
|
|
1655
|
+
controller,
|
|
1656
|
+
server,
|
|
1657
|
+
plc,
|
|
1658
|
+
detail: problems.length ? problems.join(". ") : null
|
|
1659
|
+
};
|
|
1660
|
+
};
|
|
1661
|
+
var healthy = (health) => health.controller === "ok" && health.server !== "failed";
|
|
1662
|
+
|
|
1663
|
+
// packages/agent/src/deployments/store.ts
|
|
1664
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1665
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
1666
|
+
import { mkdir as mkdir4, readdir as readdir2, readFile as readFile4, rm as rm3 } from "node:fs/promises";
|
|
1667
|
+
import { join as join6 } from "node:path";
|
|
1668
|
+
var isFinished = (record) => finalStates.includes(record.state);
|
|
1669
|
+
var activeDeployments = (records) => {
|
|
1670
|
+
const running = records.filter((record) => record.activeFrom !== null);
|
|
1671
|
+
const newest = (candidates) => candidates.reduce((best, record) => best && best.activeFrom >= record.activeFrom ? best : record, null)?.id ?? null;
|
|
1672
|
+
return {
|
|
1673
|
+
current: newest(running.filter((record) => record.activeUntil === null)),
|
|
1674
|
+
lastGood: newest(running.filter((record) => record.state === "ready"))
|
|
1675
|
+
};
|
|
1676
|
+
};
|
|
1677
|
+
var newId = () => `dpl_${[...randomBytes2(20)].map((byte) => (byte % 36).toString(36)).join("")}`;
|
|
1678
|
+
var openDeploymentStore = async (options) => {
|
|
1679
|
+
const { directory } = options;
|
|
1680
|
+
const records = new Map;
|
|
1681
|
+
const sequences = new Map;
|
|
1682
|
+
const writes = new Map;
|
|
1683
|
+
const listeners = new Map;
|
|
1684
|
+
await mkdir4(directory, { recursive: true });
|
|
1685
|
+
for (const entry of await readdir2(directory, { withFileTypes: true })) {
|
|
1686
|
+
const file = join6(directory, entry.name, "record.json");
|
|
1687
|
+
if (!entry.isDirectory() || !existsSync4(file)) {
|
|
1688
|
+
continue;
|
|
1689
|
+
}
|
|
1690
|
+
const record = await readJsonFileIfValid(file, deploymentRecordSchema);
|
|
1691
|
+
if (record?.id === entry.name) {
|
|
1692
|
+
records.set(record.id, record);
|
|
1693
|
+
} else {
|
|
1694
|
+
options.log(`Skipping the unreadable deployment record ${file}`);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
const recordDirectory = (id) => join6(directory, id);
|
|
1698
|
+
const logFile = (id) => join6(recordDirectory(id), "log.jsonl");
|
|
1699
|
+
const inTurn = (id, write) => {
|
|
1700
|
+
const next = (writes.get(id) ?? Promise.resolve()).then(write);
|
|
1701
|
+
writes.set(id, next.then(() => {
|
|
1702
|
+
return;
|
|
1703
|
+
}, (error) => options.log(`Writing deployment ${id} failed: ${errorMessage(error)}`)));
|
|
1704
|
+
return next;
|
|
1705
|
+
};
|
|
1706
|
+
const emit = (id, event) => {
|
|
1707
|
+
for (const listener of listeners.get(id) ?? []) {
|
|
1708
|
+
listener(event);
|
|
1709
|
+
}
|
|
1710
|
+
};
|
|
1711
|
+
const readLines = async (id) => {
|
|
1712
|
+
const file = logFile(id);
|
|
1713
|
+
if (!existsSync4(file)) {
|
|
1714
|
+
return [];
|
|
1715
|
+
}
|
|
1716
|
+
return (await readFile4(file, "utf8")).split(`
|
|
1717
|
+
`).filter(Boolean).flatMap((line) => {
|
|
1718
|
+
const parsed = deploymentLogLineSchema.safeParse(parsesAsJson(line)?.json);
|
|
1719
|
+
return parsed.success ? [parsed.data] : [];
|
|
1720
|
+
});
|
|
1721
|
+
};
|
|
1722
|
+
const writeRecord = (record) => inTurn(record.id, async () => {
|
|
1723
|
+
const latest = records.get(record.id);
|
|
1724
|
+
if (!latest) {
|
|
1725
|
+
return;
|
|
1726
|
+
}
|
|
1727
|
+
await mkdir4(recordDirectory(record.id), { recursive: true });
|
|
1728
|
+
writeJsonFile(join6(recordDirectory(record.id), "record.json"), latest);
|
|
1729
|
+
});
|
|
1730
|
+
const get = (id) => {
|
|
1731
|
+
const record = records.get(id);
|
|
1732
|
+
if (!record) {
|
|
1733
|
+
throw new AgentError(`No deployment ${id}`, 404);
|
|
1734
|
+
}
|
|
1735
|
+
return record;
|
|
1736
|
+
};
|
|
1737
|
+
return {
|
|
1738
|
+
newId,
|
|
1739
|
+
get,
|
|
1740
|
+
list: () => [...records.values()].sort((left, right) => right.createdAt.localeCompare(left.createdAt)),
|
|
1741
|
+
create: async (record) => {
|
|
1742
|
+
records.set(record.id, record);
|
|
1743
|
+
sequences.set(record.id, 0);
|
|
1744
|
+
await writeRecord(record);
|
|
1745
|
+
return record;
|
|
1746
|
+
},
|
|
1747
|
+
update: async (id, change) => {
|
|
1748
|
+
const record = {
|
|
1749
|
+
...change(get(id)),
|
|
1750
|
+
updatedAt: options.now().toISOString()
|
|
1751
|
+
};
|
|
1752
|
+
records.set(id, record);
|
|
1753
|
+
emit(id, { kind: "record", record });
|
|
1754
|
+
await writeRecord(record);
|
|
1755
|
+
return record;
|
|
1756
|
+
},
|
|
1757
|
+
log: (id, entry) => inTurn(id, async () => {
|
|
1758
|
+
const last = sequences.get(id) ?? (await readLines(id)).reduce((highest, line) => Math.max(highest, line.seq), 0);
|
|
1759
|
+
const line = {
|
|
1760
|
+
seq: last + 1,
|
|
1761
|
+
at: options.now().toISOString(),
|
|
1762
|
+
...entry
|
|
1763
|
+
};
|
|
1764
|
+
sequences.set(id, line.seq);
|
|
1765
|
+
await mkdir4(recordDirectory(id), { recursive: true });
|
|
1766
|
+
await appendJsonLine(logFile(id), line);
|
|
1767
|
+
emit(id, { kind: "log", line });
|
|
1768
|
+
return line;
|
|
1769
|
+
}),
|
|
1770
|
+
flush: async (id) => {
|
|
1771
|
+
await writes.get(id);
|
|
1772
|
+
},
|
|
1773
|
+
lines: async (id, after) => {
|
|
1774
|
+
await writes.get(id);
|
|
1775
|
+
return (await readLines(id)).filter((line) => line.seq > after);
|
|
1776
|
+
},
|
|
1777
|
+
subscribe: (id, listener) => {
|
|
1778
|
+
const subscribed = listeners.get(id) ?? new Set;
|
|
1779
|
+
subscribed.add(listener);
|
|
1780
|
+
listeners.set(id, subscribed);
|
|
1781
|
+
return () => {
|
|
1782
|
+
subscribed.delete(listener);
|
|
1783
|
+
};
|
|
1784
|
+
},
|
|
1785
|
+
remove: (id) => inTurn(id, async () => {
|
|
1786
|
+
records.delete(id);
|
|
1787
|
+
sequences.delete(id);
|
|
1788
|
+
await rm3(recordDirectory(id), { recursive: true, force: true });
|
|
1789
|
+
})
|
|
1790
|
+
};
|
|
1791
|
+
};
|
|
1792
|
+
|
|
1793
|
+
// packages/agent/src/deployments/retention.ts
|
|
1794
|
+
var retentionMs = 14 * 24 * 60 * 60 * 1000;
|
|
1795
|
+
var pruneDeployments = async (options) => {
|
|
1796
|
+
const { store } = options;
|
|
1797
|
+
const records = store.list();
|
|
1798
|
+
const { current, lastGood } = activeDeployments(records);
|
|
1799
|
+
const cutoff = options.now().getTime() - retentionMs;
|
|
1800
|
+
const expired = records.filter((record) => Date.parse(record.createdAt) < cutoff && record.id !== current && record.id !== lastGood && isFinished(record));
|
|
1801
|
+
for (const record of expired) {
|
|
1802
|
+
await store.remove(record.id);
|
|
1803
|
+
}
|
|
1804
|
+
const kept = new Set(store.list().map((record) => record.release));
|
|
1805
|
+
if (options.deployed) {
|
|
1806
|
+
kept.add(options.deployed.id);
|
|
1807
|
+
if (options.deployed.server) {
|
|
1808
|
+
kept.add(serverReleaseId(options.deployed.server));
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
return {
|
|
1812
|
+
deployments: expired.map((record) => record.id),
|
|
1813
|
+
releases: await pruneReleases(options.releases, kept)
|
|
1814
|
+
};
|
|
1815
|
+
};
|
|
1816
|
+
|
|
1817
|
+
// packages/agent/src/deployments/submission.ts
|
|
1818
|
+
import { workerScriptsDigest } from "@tsplc/build";
|
|
1819
|
+
var clientWarnings = async (clientTsplc) => {
|
|
1820
|
+
if (clientTsplc.version === undefined) {
|
|
1821
|
+
return [
|
|
1822
|
+
`the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`
|
|
1823
|
+
];
|
|
1824
|
+
}
|
|
1825
|
+
if (clientTsplc.version !== tsplcVersion) {
|
|
1826
|
+
throw new AgentError(versionMismatch({
|
|
1827
|
+
agent: tsplcVersion,
|
|
1828
|
+
client: clientTsplc.version,
|
|
1829
|
+
agentUpgrades: true
|
|
1830
|
+
}), 409);
|
|
1831
|
+
}
|
|
1832
|
+
if (clientTsplc.scripts !== undefined && clientTsplc.scripts !== await workerScriptsDigest()) {
|
|
1833
|
+
return [
|
|
1834
|
+
`the plant agent's CODESYS scripts differ from the deploying tsPLC's, though both are ${tsplcVersion}, so one is a local build. The deployment runs the agent's scripts: update the plant agent to run the client's`
|
|
1835
|
+
];
|
|
1836
|
+
}
|
|
1837
|
+
return [];
|
|
1838
|
+
};
|
|
1839
|
+
var requester = (identity, client) => ({
|
|
1840
|
+
identity: { login: identity.login, name: identity.name, via: identity.via },
|
|
1841
|
+
user: client.user ?? null,
|
|
1842
|
+
host: client.host ?? null
|
|
1843
|
+
});
|
|
1844
|
+
var submissionFrom = (settings, identity, client, warnings) => ({
|
|
1845
|
+
git: settings.deployment?.git ?? null,
|
|
1846
|
+
requestedBy: requester(identity, client),
|
|
1847
|
+
mode: settings.deployment?.mode ?? "apply",
|
|
1848
|
+
download: settings.download,
|
|
1849
|
+
credentials: settings.credentials,
|
|
1850
|
+
initializeUser: settings.initializeUser,
|
|
1851
|
+
warnings
|
|
1852
|
+
});
|
|
1853
|
+
var checkSubmission = async (state, credentials) => {
|
|
1854
|
+
await state.requireTarget();
|
|
1855
|
+
await controllerCredentials(credentials);
|
|
1856
|
+
};
|
|
1857
|
+
|
|
1858
|
+
// packages/agent/src/deployments/runner.ts
|
|
1859
|
+
class Canceled extends Error {
|
|
1860
|
+
}
|
|
1861
|
+
var releaseBuild = async (release) => {
|
|
1862
|
+
const file = join7(release.directory, debugManifestFile2);
|
|
1863
|
+
return existsSync5(file) ? (await loadManifest(file)).build.id : null;
|
|
1864
|
+
};
|
|
1865
|
+
var createDeploymentRunner = (context) => {
|
|
1866
|
+
const { store, state, operations, controller } = context;
|
|
1867
|
+
const pending = new Map;
|
|
1868
|
+
const queue = [];
|
|
1869
|
+
let draining = false;
|
|
1870
|
+
let releasesTurn = Promise.resolve();
|
|
1871
|
+
const withReleases = (run) => {
|
|
1872
|
+
const next = releasesTurn.then(run);
|
|
1873
|
+
releasesTurn = next.catch(() => {
|
|
1874
|
+
return;
|
|
1875
|
+
});
|
|
1876
|
+
return next;
|
|
1877
|
+
};
|
|
1878
|
+
const timestamp = () => context.now().toISOString();
|
|
1879
|
+
const recordOf = store.get;
|
|
1880
|
+
const say = (item, level, message) => {
|
|
1881
|
+
const phase = recordOf(item.id).phases.find((entry) => entry.outcome === "running")?.name ?? null;
|
|
1882
|
+
store.log(item.id, { level, phase, message }).catch(() => {
|
|
1883
|
+
return;
|
|
1884
|
+
});
|
|
1885
|
+
};
|
|
1886
|
+
const update = (item, change) => store.update(item.id, change);
|
|
1887
|
+
const startPhase = (item, name) => update(item, (record) => ({
|
|
1888
|
+
...record,
|
|
1889
|
+
phases: [
|
|
1890
|
+
...record.phases,
|
|
1891
|
+
{ name, startedAt: timestamp(), finishedAt: null, outcome: "running" }
|
|
1892
|
+
]
|
|
1893
|
+
}));
|
|
1894
|
+
const closeRunning = (phases, outcome) => {
|
|
1895
|
+
const at = timestamp();
|
|
1896
|
+
return phases.map((phase) => phase.outcome === "running" ? { ...phase, finishedAt: at, outcome } : phase);
|
|
1897
|
+
};
|
|
1898
|
+
const finishPhase = (item, outcome) => update(item, (record) => ({
|
|
1899
|
+
...record,
|
|
1900
|
+
phases: closeRunning(record.phases, outcome)
|
|
1901
|
+
}));
|
|
1902
|
+
const skipPhase = (item, name) => update(item, (record) => ({
|
|
1903
|
+
...record,
|
|
1904
|
+
phases: [
|
|
1905
|
+
...record.phases,
|
|
1906
|
+
{
|
|
1907
|
+
name,
|
|
1908
|
+
startedAt: timestamp(),
|
|
1909
|
+
finishedAt: timestamp(),
|
|
1910
|
+
outcome: "skipped"
|
|
1911
|
+
}
|
|
1912
|
+
]
|
|
1913
|
+
}));
|
|
1914
|
+
const enter = (item, state, changes = {}) => update(item, (record) => ({ ...record, ...changes, state }));
|
|
1915
|
+
const requireNotCanceled = (item) => {
|
|
1916
|
+
if (item.cancellation.signal.aborted) {
|
|
1917
|
+
throw new Canceled;
|
|
1918
|
+
}
|
|
1919
|
+
};
|
|
1920
|
+
const whenFree = async (item, run) => {
|
|
1921
|
+
const waitingFor = operations.blockedBy();
|
|
1922
|
+
if (waitingFor) {
|
|
1923
|
+
say(item, "info", `Waiting for ${waitingFor} to finish`);
|
|
1924
|
+
}
|
|
1925
|
+
while (operations.blockedBy()) {
|
|
1926
|
+
requireNotCanceled(item);
|
|
1927
|
+
await Promise.race([
|
|
1928
|
+
operations.whenIdle(),
|
|
1929
|
+
once(item.cancellation.signal, "abort")
|
|
1930
|
+
]);
|
|
1931
|
+
}
|
|
1932
|
+
return operations.exclusive("a deployment", run);
|
|
1933
|
+
};
|
|
1934
|
+
const awaitApproval = async (item, reason, message) => {
|
|
1935
|
+
if (!item.waitsForApproval) {
|
|
1936
|
+
throw reason === "downloadRequired" ? new DownloadRequiredError(message) : new AgentError(message, 409);
|
|
1937
|
+
}
|
|
1938
|
+
item.approved = false;
|
|
1939
|
+
item.running = false;
|
|
1940
|
+
say(item, "warning", message);
|
|
1941
|
+
await enter(item, "awaitingApproval", { approval: { reason, message } });
|
|
1942
|
+
return null;
|
|
1943
|
+
};
|
|
1944
|
+
const announce = (item, warnings) => {
|
|
1945
|
+
for (const warning of warnings) {
|
|
1946
|
+
say(item, "warning", warning);
|
|
1947
|
+
}
|
|
1948
|
+
};
|
|
1949
|
+
const prepare = async (item) => {
|
|
1950
|
+
const warnings = await controller.ready();
|
|
1951
|
+
const target = await state.requireTarget();
|
|
1952
|
+
const config = await withSecrets(controllerConfig(item.release, target, state.paths.controller, context.codesys), await readSecrets(item.release.manifest.secrets), state.paths.sources);
|
|
1953
|
+
await controller.settle(config);
|
|
1954
|
+
return { config, warnings };
|
|
1955
|
+
};
|
|
1956
|
+
const progress = (item) => (message) => say(item, "info", message);
|
|
1957
|
+
const review = async (item, config) => {
|
|
1958
|
+
const { mode } = recordOf(item.id);
|
|
1959
|
+
await startPhase(item, "review");
|
|
1960
|
+
const result = await controller.review(config, {
|
|
1961
|
+
credentials: await controllerCredentials(item.credentials),
|
|
1962
|
+
onProgress: progress(item)
|
|
1963
|
+
});
|
|
1964
|
+
await update(item, (record) => ({ ...record, findings: result.findings }));
|
|
1965
|
+
await finishPhase(item, "ok");
|
|
1966
|
+
for (const finding of result.findings) {
|
|
1967
|
+
say(item, finding.refuses ? "warning" : "info", describeFinding(finding));
|
|
1968
|
+
}
|
|
1969
|
+
requireNotCanceled(item);
|
|
1970
|
+
if (!result.possible) {
|
|
1971
|
+
return awaitApproval(item, "downloadRequired", `CODESYS can't apply this as an online change${result.messages.length ? `: ${result.messages.join(" ")}` : ""}. Only a full download, which stops the application, can deploy it`);
|
|
1972
|
+
}
|
|
1973
|
+
if (mode === "review") {
|
|
1974
|
+
return awaitApproval(item, "review", "Review the online change's findings, then approve it to apply");
|
|
1975
|
+
}
|
|
1976
|
+
return config;
|
|
1977
|
+
};
|
|
1978
|
+
const build = async (item) => {
|
|
1979
|
+
await finishPhase(item, "ok");
|
|
1980
|
+
await enter(item, "building");
|
|
1981
|
+
await startPhase(item, "build");
|
|
1982
|
+
const { config, warnings } = await prepare(item);
|
|
1983
|
+
announce(item, warnings);
|
|
1984
|
+
const { operation, mode } = recordOf(item.id);
|
|
1985
|
+
const baseline = operation === "download" ? "valid" : await controller.baseline();
|
|
1986
|
+
await finishPhase(item, "ok");
|
|
1987
|
+
requireNotCanceled(item);
|
|
1988
|
+
if (baseline !== "valid") {
|
|
1989
|
+
await skipPhase(item, "review");
|
|
1990
|
+
return awaitApproval(item, "downloadRequired", baseline === "missing" ? "The controller has no application downloaded by this agent; only a full download can deploy" : "This agent's record of the controller's download can't be read; only a full download can deploy");
|
|
1991
|
+
}
|
|
1992
|
+
if (operation === "online-change") {
|
|
1993
|
+
return review(item, config);
|
|
1994
|
+
}
|
|
1995
|
+
await skipPhase(item, "review");
|
|
1996
|
+
if (mode === "review") {
|
|
1997
|
+
return awaitApproval(item, "review", "Approve it to apply as a full download, which stops the application");
|
|
1998
|
+
}
|
|
1999
|
+
return config;
|
|
2000
|
+
};
|
|
2001
|
+
const apply = async (item, config) => {
|
|
2002
|
+
requireNotCanceled(item);
|
|
2003
|
+
const { operation } = recordOf(item.id);
|
|
2004
|
+
await enter(item, "applying", { approval: null });
|
|
2005
|
+
await startPhase(item, "apply");
|
|
2006
|
+
say(item, "info", `Starting the ${operation}`);
|
|
2007
|
+
const receipt = await controller.apply(config, operation, {
|
|
2008
|
+
initializeUser: item.initializeUser,
|
|
2009
|
+
credentials: await controllerCredentials(item.credentials),
|
|
2010
|
+
onProgress: progress(item)
|
|
2011
|
+
}).catch(async (error) => {
|
|
2012
|
+
if (operation === "download" || !requiresDownload2(error)) {
|
|
2013
|
+
throw error;
|
|
2014
|
+
}
|
|
2015
|
+
await finishPhase(item, "failed");
|
|
2016
|
+
if (error instanceof DownloadRequiredError) {
|
|
2017
|
+
await update(item, (record) => ({
|
|
2018
|
+
...record,
|
|
2019
|
+
findings: error.findings
|
|
2020
|
+
}));
|
|
2021
|
+
}
|
|
2022
|
+
return awaitApproval(item, "downloadRequired", errorMessage(error));
|
|
2023
|
+
});
|
|
2024
|
+
if (!receipt) {
|
|
2025
|
+
return null;
|
|
2026
|
+
}
|
|
2027
|
+
await update(item, (record) => ({
|
|
2028
|
+
...record,
|
|
2029
|
+
controllerIds: receipt.controllerIds
|
|
2030
|
+
}));
|
|
2031
|
+
await finishPhase(item, "ok");
|
|
2032
|
+
return receipt;
|
|
2033
|
+
};
|
|
2034
|
+
const startServer = async (item, serverPath) => {
|
|
2035
|
+
if (!serverPath) {
|
|
2036
|
+
await skipPhase(item, "server");
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
await startPhase(item, "server");
|
|
2040
|
+
say(item, "info", "Starting the new server");
|
|
2041
|
+
const failure = await context.server.replace(releaseServerFile(state.paths.releases, serverPath)).then(() => {
|
|
2042
|
+
return;
|
|
2043
|
+
}, (error) => errorMessage(error));
|
|
2044
|
+
await finishPhase(item, failure === undefined ? "ok" : "failed");
|
|
2045
|
+
return failure;
|
|
2046
|
+
};
|
|
2047
|
+
const activate = async (item) => {
|
|
2048
|
+
const at = timestamp();
|
|
2049
|
+
const { current } = activeDeployments(store.list());
|
|
2050
|
+
if (current && current !== item.id) {
|
|
2051
|
+
await store.update(current, (record) => ({
|
|
2052
|
+
...record,
|
|
2053
|
+
activeUntil: at
|
|
2054
|
+
}));
|
|
2055
|
+
}
|
|
2056
|
+
await update(item, (record) => ({
|
|
2057
|
+
...record,
|
|
2058
|
+
activeFrom: at,
|
|
2059
|
+
activeUntil: null
|
|
2060
|
+
}));
|
|
2061
|
+
};
|
|
2062
|
+
const startRelease = async (item, receipt) => {
|
|
2063
|
+
const { release } = item;
|
|
2064
|
+
const record = recordOf(item.id);
|
|
2065
|
+
await enter(item, "starting");
|
|
2066
|
+
const serverPath = releaseServerPath(release);
|
|
2067
|
+
const previous = await state.release();
|
|
2068
|
+
const serverFailure = await startServer(item, serverPath);
|
|
2069
|
+
const deployed = {
|
|
2070
|
+
id: release.id,
|
|
2071
|
+
deployedAt: timestamp(),
|
|
2072
|
+
operation: record.operation,
|
|
2073
|
+
controllerIds: receipt.controllerIds,
|
|
2074
|
+
server: serverFailure === undefined ? serverPath ?? previous?.server : previous?.server
|
|
2075
|
+
};
|
|
2076
|
+
await state.setRelease(deployed);
|
|
2077
|
+
const line = {
|
|
2078
|
+
at: deployed.deployedAt,
|
|
2079
|
+
release: release.id,
|
|
2080
|
+
...record.build !== null && { build: record.build },
|
|
2081
|
+
operation: record.operation,
|
|
2082
|
+
credentials: item.credentials ? "provided" : "stored",
|
|
2083
|
+
...record.requestedBy.user !== null && {
|
|
2084
|
+
user: record.requestedBy.user
|
|
2085
|
+
},
|
|
2086
|
+
...record.requestedBy.host !== null && {
|
|
2087
|
+
host: record.requestedBy.host
|
|
2088
|
+
}
|
|
2089
|
+
};
|
|
2090
|
+
await appendJsonl(state.paths.deployments, line);
|
|
2091
|
+
await activate(item);
|
|
2092
|
+
context.onActivated();
|
|
2093
|
+
if (serverFailure !== undefined) {
|
|
2094
|
+
throw new Error(`The controller runs release ${release.id}. ${serverFailure}`);
|
|
2095
|
+
}
|
|
2096
|
+
return deployed;
|
|
2097
|
+
};
|
|
2098
|
+
const verify = async (item, receipt) => {
|
|
2099
|
+
await enter(item, "verifying");
|
|
2100
|
+
await startPhase(item, "health");
|
|
2101
|
+
const health = await checkHealth({
|
|
2102
|
+
controllerState: receipt.state,
|
|
2103
|
+
hasServer: item.release.manifest.server !== undefined,
|
|
2104
|
+
server: context.server
|
|
2105
|
+
});
|
|
2106
|
+
await update(item, (record) => ({ ...record, health }));
|
|
2107
|
+
if (!healthy(health)) {
|
|
2108
|
+
throw new Error(health.detail ?? "The deployment isn't healthy");
|
|
2109
|
+
}
|
|
2110
|
+
await finishPhase(item, "ok");
|
|
2111
|
+
say(item, "info", health.detail ? `Ready. ${health.detail}` : "Ready");
|
|
2112
|
+
await enter(item, "ready");
|
|
2113
|
+
};
|
|
2114
|
+
const fail = async (item, error) => {
|
|
2115
|
+
if (error instanceof Canceled) {
|
|
2116
|
+
await finishPhase(item, "skipped");
|
|
2117
|
+
await enter(item, "canceled", { approval: null });
|
|
2118
|
+
return;
|
|
2119
|
+
}
|
|
2120
|
+
context.log(`Deployment ${item.id} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
2121
|
+
await finishPhase(item, "failed");
|
|
2122
|
+
say(item, "error", errorMessage(error));
|
|
2123
|
+
await enter(item, "error", { approval: null, error: failureReport(error) });
|
|
2124
|
+
};
|
|
2125
|
+
const prune = () => withReleases(async () => {
|
|
2126
|
+
const pruned = await pruneDeployments({
|
|
2127
|
+
store,
|
|
2128
|
+
releases: state.paths.releases,
|
|
2129
|
+
deployed: await state.release(),
|
|
2130
|
+
now: context.now
|
|
2131
|
+
});
|
|
2132
|
+
if (pruned.deployments.length || pruned.releases.length) {
|
|
2133
|
+
context.log(`Removed ${pruned.deployments.length} deployments and ${pruned.releases.length} releases older than the retention`);
|
|
2134
|
+
}
|
|
2135
|
+
}).catch((error) => context.log(`Pruning deployments failed: ${errorMessage(error)}`));
|
|
2136
|
+
const waitsForPerson = (item) => recordOf(item.id).state === "awaitingApproval" && !item.approved;
|
|
2137
|
+
const conclude = (item) => {
|
|
2138
|
+
if (recordOf(item.id).state === "awaitingApproval") {
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
pending.delete(item.id);
|
|
2142
|
+
const index = queue.indexOf(item);
|
|
2143
|
+
if (index >= 0) {
|
|
2144
|
+
queue.splice(index, 1);
|
|
2145
|
+
}
|
|
2146
|
+
prune();
|
|
2147
|
+
};
|
|
2148
|
+
const advance = async (item, lock) => {
|
|
2149
|
+
item.running = true;
|
|
2150
|
+
try {
|
|
2151
|
+
const deployed = await lock(async () => {
|
|
2152
|
+
requireNotCanceled(item);
|
|
2153
|
+
const config = recordOf(item.id).state === "queued" ? await build(item) : (await prepare(item)).config;
|
|
2154
|
+
if (!config) {
|
|
2155
|
+
return null;
|
|
2156
|
+
}
|
|
2157
|
+
const receipt = await apply(item, config);
|
|
2158
|
+
if (!receipt) {
|
|
2159
|
+
return null;
|
|
2160
|
+
}
|
|
2161
|
+
const release = await startRelease(item, receipt);
|
|
2162
|
+
await verify(item, receipt);
|
|
2163
|
+
return release;
|
|
2164
|
+
});
|
|
2165
|
+
return { deployed, failure: null };
|
|
2166
|
+
} catch (error) {
|
|
2167
|
+
await fail(item, error).catch((failure) => context.log(`Recording deployment ${item.id}'s failure failed: ${errorMessage(failure)}`));
|
|
2168
|
+
return {
|
|
2169
|
+
deployed: null,
|
|
2170
|
+
failure: error instanceof Canceled ? null : { error }
|
|
2171
|
+
};
|
|
2172
|
+
} finally {
|
|
2173
|
+
item.running = false;
|
|
2174
|
+
conclude(item);
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
const advanceQueue = async () => {
|
|
2178
|
+
const [head] = queue;
|
|
2179
|
+
if (!head || waitsForPerson(head)) {
|
|
2180
|
+
return;
|
|
2181
|
+
}
|
|
2182
|
+
await advance(head, (run) => whenFree(head, run));
|
|
2183
|
+
return advanceQueue();
|
|
2184
|
+
};
|
|
2185
|
+
const drain = async () => {
|
|
2186
|
+
if (draining) {
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
draining = true;
|
|
2190
|
+
try {
|
|
2191
|
+
await advanceQueue();
|
|
2192
|
+
} finally {
|
|
2193
|
+
draining = false;
|
|
2194
|
+
}
|
|
2195
|
+
};
|
|
2196
|
+
const create = async (release, requested, handling) => {
|
|
2197
|
+
const at = timestamp();
|
|
2198
|
+
const record = {
|
|
2199
|
+
id: store.newId(),
|
|
2200
|
+
release: release.id,
|
|
2201
|
+
build: await releaseBuild(release),
|
|
2202
|
+
createdAt: at,
|
|
2203
|
+
updatedAt: at,
|
|
2204
|
+
...requested,
|
|
2205
|
+
state: "queued",
|
|
2206
|
+
phases: [
|
|
2207
|
+
{ name: "queue", startedAt: at, finishedAt: null, outcome: "running" }
|
|
2208
|
+
],
|
|
2209
|
+
findings: [],
|
|
2210
|
+
approval: null,
|
|
2211
|
+
error: null,
|
|
2212
|
+
controllerIds: null,
|
|
2213
|
+
health: null,
|
|
2214
|
+
activeFrom: null,
|
|
2215
|
+
activeUntil: null
|
|
2216
|
+
};
|
|
2217
|
+
await store.create(record);
|
|
2218
|
+
const item = {
|
|
2219
|
+
id: record.id,
|
|
2220
|
+
release,
|
|
2221
|
+
...handling,
|
|
2222
|
+
cancellation: new AbortController,
|
|
2223
|
+
approved: false,
|
|
2224
|
+
running: false
|
|
2225
|
+
};
|
|
2226
|
+
pending.set(item.id, item);
|
|
2227
|
+
return item;
|
|
2228
|
+
};
|
|
2229
|
+
const createUpload = (release, submission, options) => create(release, {
|
|
2230
|
+
origin: { kind: "upload" },
|
|
2231
|
+
git: submission.git,
|
|
2232
|
+
requestedBy: submission.requestedBy,
|
|
2233
|
+
mode: submission.mode,
|
|
2234
|
+
operation: submission.download ? "download" : "online-change"
|
|
2235
|
+
}, {
|
|
2236
|
+
credentials: submission.credentials,
|
|
2237
|
+
initializeUser: submission.initializeUser,
|
|
2238
|
+
waitsForApproval: options.waitsForApproval
|
|
2239
|
+
});
|
|
2240
|
+
const enqueue = (item, warnings) => {
|
|
2241
|
+
announce(item, warnings);
|
|
2242
|
+
queue.push(item);
|
|
2243
|
+
drain();
|
|
2244
|
+
return recordOf(item.id);
|
|
2245
|
+
};
|
|
2246
|
+
const again = async (source, origin, mode, requestedBy) => {
|
|
2247
|
+
await checkSubmission(state, null);
|
|
2248
|
+
return withReleases(async () => {
|
|
2249
|
+
if (!isStored(state.paths.releases, source.release)) {
|
|
2250
|
+
throw new AgentError(`The release of ${source.id}, ${source.release}, is no longer stored`, 409);
|
|
2251
|
+
}
|
|
2252
|
+
const release = await loadRelease(state.paths.releases, source.release);
|
|
2253
|
+
const item = await create(release, {
|
|
2254
|
+
origin,
|
|
2255
|
+
git: source.git,
|
|
2256
|
+
requestedBy,
|
|
2257
|
+
mode,
|
|
2258
|
+
operation: "online-change"
|
|
2259
|
+
}, { credentials: null, initializeUser: false, waitsForApproval: true });
|
|
2260
|
+
return enqueue(item, []);
|
|
2261
|
+
});
|
|
2262
|
+
};
|
|
2263
|
+
return {
|
|
2264
|
+
start: async () => {
|
|
2265
|
+
for (const record of store.list().filter((entry) => !isFinished(entry))) {
|
|
2266
|
+
await store.update(record.id, (unfinished) => ({
|
|
2267
|
+
...unfinished,
|
|
2268
|
+
state: "error",
|
|
2269
|
+
approval: null,
|
|
2270
|
+
phases: closeRunning(unfinished.phases, "failed"),
|
|
2271
|
+
error: {
|
|
2272
|
+
message: "The plant agent stopped before this deployment finished",
|
|
2273
|
+
downloadRequired: false
|
|
2274
|
+
}
|
|
2275
|
+
}));
|
|
2276
|
+
}
|
|
2277
|
+
await prune();
|
|
2278
|
+
},
|
|
2279
|
+
submit: async (upload, submission) => {
|
|
2280
|
+
await checkSubmission(state, submission.credentials);
|
|
2281
|
+
return withReleases(async () => {
|
|
2282
|
+
const item = await createUpload(await saveRelease(state.paths.releases, upload), submission, { waitsForApproval: true });
|
|
2283
|
+
return enqueue(item, submission.warnings);
|
|
2284
|
+
});
|
|
2285
|
+
},
|
|
2286
|
+
redeploy: async (id, mode, requestedBy) => {
|
|
2287
|
+
const source = recordOf(id);
|
|
2288
|
+
if (!isFinished(source)) {
|
|
2289
|
+
throw new AgentError(`Deployment ${id} is ${source.state}; only a finished deployment can be redeployed`, 409);
|
|
2290
|
+
}
|
|
2291
|
+
return again(source, { kind: "redeploy", from: id }, mode, requestedBy);
|
|
2292
|
+
},
|
|
2293
|
+
rollback: async (id, requestedBy) => {
|
|
2294
|
+
const source = recordOf(id);
|
|
2295
|
+
if (source.state !== "ready") {
|
|
2296
|
+
throw new AgentError(`Deployment ${id} is ${source.state}; only a ready deployment can be rolled back to`, 409);
|
|
2297
|
+
}
|
|
2298
|
+
if (activeDeployments(store.list()).current === id) {
|
|
2299
|
+
throw new AgentError(`Deployment ${id} runs now; there is nothing to roll back`, 409);
|
|
2300
|
+
}
|
|
2301
|
+
return again(source, { kind: "rollback", from: id }, "apply", requestedBy);
|
|
2302
|
+
},
|
|
2303
|
+
approve: async (id, { download }, by) => {
|
|
2304
|
+
const record = recordOf(id);
|
|
2305
|
+
const item = pending.get(id);
|
|
2306
|
+
if (!item || record.state !== "awaitingApproval" || item.approved) {
|
|
2307
|
+
throw new AgentError(`Deployment ${id} isn't awaiting approval`, 409);
|
|
2308
|
+
}
|
|
2309
|
+
if (record.approval?.reason === "downloadRequired" && !download) {
|
|
2310
|
+
throw new AgentError(`Only a full download can apply deployment ${id}; approve it with a download`, 409);
|
|
2311
|
+
}
|
|
2312
|
+
item.approved = true;
|
|
2313
|
+
say(item, "info", `${by} approved it${download ? " as a full download" : ""}`);
|
|
2314
|
+
const approved = await update(item, (current) => ({
|
|
2315
|
+
...current,
|
|
2316
|
+
operation: download ? "download" : current.operation
|
|
2317
|
+
}));
|
|
2318
|
+
drain();
|
|
2319
|
+
return approved;
|
|
2320
|
+
},
|
|
2321
|
+
cancel: async (id, by) => {
|
|
2322
|
+
const record = recordOf(id);
|
|
2323
|
+
const item = pending.get(id);
|
|
2324
|
+
if (!item || !cancelableStates.includes(record.state)) {
|
|
2325
|
+
throw new AgentError(`Deployment ${id} is ${record.state}; a deployment can only be canceled before it applies`, 409);
|
|
2326
|
+
}
|
|
2327
|
+
item.cancellation.abort();
|
|
2328
|
+
say(item, "info", `${by} canceled it`);
|
|
2329
|
+
if (item.running) {
|
|
2330
|
+
return record;
|
|
2331
|
+
}
|
|
2332
|
+
const index = queue.indexOf(item);
|
|
2333
|
+
if (index >= 0) {
|
|
2334
|
+
queue.splice(index, 1);
|
|
2335
|
+
}
|
|
2336
|
+
await fail(item, new Canceled);
|
|
2337
|
+
conclude(item);
|
|
2338
|
+
drain();
|
|
2339
|
+
return recordOf(id);
|
|
2340
|
+
},
|
|
2341
|
+
requireIdle: () => {
|
|
2342
|
+
const [head] = queue;
|
|
2343
|
+
if (!head) {
|
|
2344
|
+
return;
|
|
2345
|
+
}
|
|
2346
|
+
throw new AgentError(waitsForPerson(head) ? `Deployment ${head.id} waits for approval on the dashboard; approve or cancel it first` : "The agent is busy with a deployment", 409);
|
|
2347
|
+
},
|
|
2348
|
+
runNow: async (upload, submission, onLine) => {
|
|
2349
|
+
const item = await withReleases(async () => createUpload(await saveRelease(state.paths.releases, upload), submission, { waitsForApproval: false }));
|
|
2350
|
+
const unsubscribe = store.subscribe(item.id, (event) => {
|
|
2351
|
+
if (event.kind === "log") {
|
|
2352
|
+
onLine(event.line);
|
|
2353
|
+
}
|
|
2354
|
+
});
|
|
2355
|
+
try {
|
|
2356
|
+
announce(item, submission.warnings);
|
|
2357
|
+
const { deployed, failure } = await advance(item, (run) => run());
|
|
2358
|
+
await store.flush(item.id);
|
|
2359
|
+
if (failure) {
|
|
2360
|
+
throw failure.error;
|
|
2361
|
+
}
|
|
2362
|
+
if (!deployed) {
|
|
2363
|
+
throw new AgentError(`Deployment ${item.id} was canceled`, 409);
|
|
2364
|
+
}
|
|
2365
|
+
return deployed;
|
|
2366
|
+
} finally {
|
|
2367
|
+
unsubscribe();
|
|
2368
|
+
}
|
|
2369
|
+
},
|
|
2370
|
+
list: () => {
|
|
2371
|
+
const deployments = store.list();
|
|
2372
|
+
return { deployments, ...activeDeployments(deployments) };
|
|
2373
|
+
},
|
|
2374
|
+
get: recordOf,
|
|
2375
|
+
lines: (id, after) => {
|
|
2376
|
+
recordOf(id);
|
|
2377
|
+
return store.lines(id, after);
|
|
2378
|
+
},
|
|
2379
|
+
subscribe: (id, listener) => {
|
|
2380
|
+
recordOf(id);
|
|
2381
|
+
return store.subscribe(id, listener);
|
|
2382
|
+
},
|
|
2383
|
+
source: (id) => listReleaseFiles(state.paths.releases, recordOf(id).release),
|
|
2384
|
+
sourceFile: (id, path) => readReleaseFile(state.paths.releases, recordOf(id).release, path)
|
|
2385
|
+
};
|
|
2386
|
+
};
|
|
2387
|
+
|
|
2388
|
+
// packages/agent/src/deploy.ts
|
|
2389
|
+
var createDeployments = async (context) => {
|
|
2390
|
+
const { state } = context;
|
|
2391
|
+
const warming = (async () => {
|
|
2392
|
+
const config = await deployedControllerConfig(state, context.codesys);
|
|
2393
|
+
if (!config) {
|
|
2394
|
+
return;
|
|
2395
|
+
}
|
|
2396
|
+
await requireBuilder();
|
|
2397
|
+
await ensureGateway();
|
|
2398
|
+
await startWarmController(config, deployContainer);
|
|
2399
|
+
})().catch((error) => {
|
|
2400
|
+
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
2401
|
+
});
|
|
2402
|
+
const warmed = async () => {
|
|
2403
|
+
await ensureGateway();
|
|
2404
|
+
await warming;
|
|
2405
|
+
};
|
|
2406
|
+
const controller = {
|
|
2407
|
+
ready: async () => {
|
|
2408
|
+
const builder = await requireBuilder();
|
|
2409
|
+
if (await context.login.isOpen()) {
|
|
2410
|
+
throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
|
|
2411
|
+
}
|
|
2412
|
+
return builder.kind === "unverified" ? [
|
|
2413
|
+
`${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`
|
|
2414
|
+
] : [];
|
|
2415
|
+
},
|
|
2416
|
+
settle: (config) => settleWarmController(config, deployContainer),
|
|
2417
|
+
baseline: () => controllerBaseline(state.paths.controller),
|
|
2418
|
+
review: async (config, options) => {
|
|
2419
|
+
await warmed();
|
|
2420
|
+
return reviewWarmController(config, deployContainer, options);
|
|
2421
|
+
},
|
|
2422
|
+
apply: async (config, operation, options) => {
|
|
2423
|
+
await warmed();
|
|
2424
|
+
return updateWarmController(config, deployContainer, operation, options);
|
|
2425
|
+
}
|
|
2426
|
+
};
|
|
2427
|
+
const runner = createDeploymentRunner({
|
|
2428
|
+
store: await openDeploymentStore({
|
|
2429
|
+
directory: state.paths.deploymentRecords,
|
|
2430
|
+
now: context.now,
|
|
2431
|
+
log: context.log
|
|
2432
|
+
}),
|
|
2433
|
+
state,
|
|
2434
|
+
operations: context.operations,
|
|
2435
|
+
codesys: context.codesys,
|
|
2436
|
+
server: context.server,
|
|
2437
|
+
controller,
|
|
2438
|
+
onActivated: () => context.debugging.restart(),
|
|
2439
|
+
now: context.now,
|
|
2440
|
+
log: context.log
|
|
2441
|
+
});
|
|
2442
|
+
await runner.start();
|
|
2443
|
+
return {
|
|
2444
|
+
runner,
|
|
2445
|
+
restart: (reset) => context.operations.exclusive("a controller restart", async () => {
|
|
2446
|
+
if (await context.login.isOpen()) {
|
|
2447
|
+
return context.login.restart(reset);
|
|
2448
|
+
}
|
|
2449
|
+
const config = await deployedControllerConfig(state, context.codesys);
|
|
2450
|
+
if (!config) {
|
|
2451
|
+
throw new AgentError("Nothing is deployed to the controller yet", 409);
|
|
2452
|
+
}
|
|
2453
|
+
await requireBuilder();
|
|
2454
|
+
await warmed();
|
|
2455
|
+
return restartWarmController(config, deployContainer, reset, {
|
|
2456
|
+
credentials: await controllerCredentials(null)
|
|
2457
|
+
});
|
|
2458
|
+
}),
|
|
2459
|
+
retire: async () => {
|
|
2460
|
+
await warming;
|
|
2461
|
+
const config = await deployedControllerConfig(state, context.codesys);
|
|
2462
|
+
if (config) {
|
|
2463
|
+
await settleWarmController(config, deployContainer);
|
|
2464
|
+
}
|
|
2465
|
+
await removeContainer(deployContainer);
|
|
2466
|
+
},
|
|
2467
|
+
deploy: async (readRequest, identity, client, clientTsplc) => {
|
|
2468
|
+
const warnings = await clientWarnings(clientTsplc);
|
|
2469
|
+
context.operations.requireIdle();
|
|
2470
|
+
runner.requireIdle();
|
|
2471
|
+
await requireBuilder();
|
|
2472
|
+
const { settings, upload } = await readRequest();
|
|
2473
|
+
await checkSubmission(state, settings.credentials);
|
|
2474
|
+
await readSecrets(upload.manifest.secrets);
|
|
2475
|
+
return context.operations.stream("a deployment", (emit) => runner.runNow(upload, {
|
|
2476
|
+
...submissionFrom(settings, identity, client, warnings),
|
|
2477
|
+
mode: "apply"
|
|
2478
|
+
}, (line) => {
|
|
2479
|
+
if (line.level === "error") {
|
|
2480
|
+
return;
|
|
2481
|
+
}
|
|
2482
|
+
emit({
|
|
2483
|
+
kind: "progress",
|
|
2484
|
+
message: line.level === "warning" ? `Warning: ${line.message}` : line.message
|
|
2485
|
+
});
|
|
2486
|
+
}), { reportsRollback: clientTsplc.version !== undefined });
|
|
2487
|
+
}
|
|
2488
|
+
};
|
|
2489
|
+
};
|
|
2490
|
+
|
|
2491
|
+
// packages/agent/src/deployments/routes.ts
|
|
2492
|
+
import { z as z8 } from "zod";
|
|
2493
|
+
var heartbeatMs = 15000;
|
|
2494
|
+
var afterSchema = z8.coerce.number().int().nonnegative();
|
|
2495
|
+
var after = (request) => afterSchema.parse(new URL(request.url).searchParams.get("after") ?? request.headers.get("last-event-id") ?? 0);
|
|
2496
|
+
var param = (params, name) => {
|
|
2497
|
+
const value = params[name];
|
|
2498
|
+
if (value === undefined) {
|
|
2499
|
+
throw new Error(`The route's pattern has no ${name}`);
|
|
2500
|
+
}
|
|
2501
|
+
return value;
|
|
2502
|
+
};
|
|
2503
|
+
var eventStream = (runner, id, from) => {
|
|
2504
|
+
const initial = runner.get(id);
|
|
2505
|
+
const encoder = new TextEncoder;
|
|
2506
|
+
const stream = {
|
|
2507
|
+
open: true,
|
|
2508
|
+
sent: from,
|
|
2509
|
+
replaying: true,
|
|
2510
|
+
held: [],
|
|
2511
|
+
stop: () => {}
|
|
2512
|
+
};
|
|
2513
|
+
return new Response(new ReadableStream({
|
|
2514
|
+
start: async (controller) => {
|
|
2515
|
+
const write = (text) => {
|
|
2516
|
+
if (stream.open) {
|
|
2517
|
+
controller.enqueue(encoder.encode(text));
|
|
2518
|
+
}
|
|
2519
|
+
};
|
|
2520
|
+
const sendLine = (line) => {
|
|
2521
|
+
if (line.seq <= stream.sent) {
|
|
2522
|
+
return;
|
|
2523
|
+
}
|
|
2524
|
+
stream.sent = line.seq;
|
|
2525
|
+
write(`id: ${line.seq}
|
|
2526
|
+
event: log
|
|
2527
|
+
data: ${JSON.stringify(line)}
|
|
2528
|
+
|
|
2529
|
+
`);
|
|
2530
|
+
};
|
|
2531
|
+
const end = () => {
|
|
2532
|
+
if (stream.open) {
|
|
2533
|
+
stream.stop();
|
|
2534
|
+
controller.close();
|
|
2535
|
+
}
|
|
2536
|
+
};
|
|
2537
|
+
const sendRecord = (record) => write(`event: record
|
|
2538
|
+
data: ${JSON.stringify(record)}
|
|
2539
|
+
|
|
2540
|
+
`);
|
|
2541
|
+
const finish = () => runner.lines(id, stream.sent).then((lines) => {
|
|
2542
|
+
lines.forEach(sendLine);
|
|
2543
|
+
sendRecord(runner.get(id));
|
|
2544
|
+
end();
|
|
2545
|
+
}, end);
|
|
2546
|
+
const deliver = (event) => {
|
|
2547
|
+
if (event.kind === "log") {
|
|
2548
|
+
sendLine(event.line);
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2551
|
+
if (isFinished(event.record)) {
|
|
2552
|
+
finish();
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
sendRecord(event.record);
|
|
2556
|
+
};
|
|
2557
|
+
const unsubscribe = runner.subscribe(id, (event) => {
|
|
2558
|
+
if (stream.replaying) {
|
|
2559
|
+
stream.held.push(event);
|
|
2560
|
+
return;
|
|
2561
|
+
}
|
|
2562
|
+
deliver(event);
|
|
2563
|
+
});
|
|
2564
|
+
const heartbeat = setInterval(() => write(`: heartbeat
|
|
2565
|
+
|
|
2566
|
+
`), heartbeatMs);
|
|
2567
|
+
stream.stop = () => {
|
|
2568
|
+
stream.open = false;
|
|
2569
|
+
clearInterval(heartbeat);
|
|
2570
|
+
unsubscribe();
|
|
2571
|
+
};
|
|
2572
|
+
if (!isFinished(initial)) {
|
|
2573
|
+
sendRecord(initial);
|
|
2574
|
+
}
|
|
2575
|
+
(await runner.lines(id, from)).forEach(sendLine);
|
|
2576
|
+
stream.replaying = false;
|
|
2577
|
+
stream.held.splice(0).forEach(deliver);
|
|
2578
|
+
if (isFinished(runner.get(id))) {
|
|
2579
|
+
finish();
|
|
2580
|
+
}
|
|
2581
|
+
},
|
|
2582
|
+
cancel: () => stream.stop()
|
|
2583
|
+
}), {
|
|
2584
|
+
headers: {
|
|
2585
|
+
"Content-Type": "text/event-stream",
|
|
2586
|
+
"Cache-Control": "no-cache"
|
|
2587
|
+
}
|
|
2588
|
+
});
|
|
2589
|
+
};
|
|
2590
|
+
var createDeploymentRoutes = (context) => {
|
|
2591
|
+
const { runner } = context;
|
|
2592
|
+
const created = (request, record) => Response.json({
|
|
2593
|
+
id: record.id,
|
|
2594
|
+
url: `${new URL(request.url).origin}${deploymentPagePath(record.id)}`
|
|
2595
|
+
}, { status: 202 });
|
|
2596
|
+
const id = (params) => param(params, "id");
|
|
2597
|
+
return [
|
|
2598
|
+
{
|
|
2599
|
+
method: "POST",
|
|
2600
|
+
pattern: deploymentsApiPath,
|
|
2601
|
+
role: "deployer",
|
|
2602
|
+
handle: async (request, { identity }) => {
|
|
2603
|
+
const warnings = await clientWarnings(clientRelease(request));
|
|
2604
|
+
const { settings, upload } = await readDeployRequest(context.releases, request);
|
|
2605
|
+
const record = await runner.submit(upload, submissionFrom(settings, identity, clientIdentity(request), warnings));
|
|
2606
|
+
return created(request, record);
|
|
2607
|
+
}
|
|
2608
|
+
},
|
|
2609
|
+
{
|
|
2610
|
+
method: "GET",
|
|
2611
|
+
pattern: deploymentsApiPath,
|
|
2612
|
+
role: "viewer",
|
|
2613
|
+
handle: async () => Response.json(runner.list())
|
|
2614
|
+
},
|
|
2615
|
+
{
|
|
2616
|
+
method: "GET",
|
|
2617
|
+
pattern: `${deploymentsApiPath}/:id`,
|
|
2618
|
+
role: "viewer",
|
|
2619
|
+
handle: async (_request, { params }) => Response.json(runner.get(id(params)))
|
|
2620
|
+
},
|
|
2621
|
+
{
|
|
2622
|
+
method: "GET",
|
|
2623
|
+
pattern: `${deploymentsApiPath}/:id/logs`,
|
|
2624
|
+
role: "viewer",
|
|
2625
|
+
handle: async (request, { params }) => Response.json({
|
|
2626
|
+
lines: await runner.lines(id(params), after(request))
|
|
2627
|
+
})
|
|
2628
|
+
},
|
|
2629
|
+
{
|
|
2630
|
+
method: "GET",
|
|
2631
|
+
pattern: `${deploymentsApiPath}/:id/events`,
|
|
2632
|
+
role: "viewer",
|
|
2633
|
+
handle: async (request, { params }) => eventStream(runner, id(params), after(request))
|
|
2634
|
+
},
|
|
2635
|
+
{
|
|
2636
|
+
method: "POST",
|
|
2637
|
+
pattern: `${deploymentsApiPath}/:id/approve`,
|
|
2638
|
+
role: "deployer",
|
|
2639
|
+
handle: async (request, { identity, params }) => {
|
|
2640
|
+
const { download } = approveSchema.parse(await request.json());
|
|
2641
|
+
return Response.json(await runner.approve(id(params), { download }, identity.name));
|
|
2642
|
+
}
|
|
2643
|
+
},
|
|
2644
|
+
{
|
|
2645
|
+
method: "POST",
|
|
2646
|
+
pattern: `${deploymentsApiPath}/:id/cancel`,
|
|
2647
|
+
role: "deployer",
|
|
2648
|
+
handle: async (_request, { identity, params }) => Response.json(await runner.cancel(id(params), identity.name))
|
|
2649
|
+
},
|
|
2650
|
+
{
|
|
2651
|
+
method: "POST",
|
|
2652
|
+
pattern: `${deploymentsApiPath}/:id/redeploy`,
|
|
2653
|
+
role: "deployer",
|
|
2654
|
+
handle: async (request, { identity, params }) => {
|
|
2655
|
+
const { mode } = redeploySchema.parse(await request.json());
|
|
2656
|
+
return created(request, await runner.redeploy(id(params), mode, requester(identity, clientIdentity(request))));
|
|
2657
|
+
}
|
|
2658
|
+
},
|
|
2659
|
+
{
|
|
2660
|
+
method: "POST",
|
|
2661
|
+
pattern: `${deploymentsApiPath}/:id/rollback`,
|
|
2662
|
+
role: "deployer",
|
|
2663
|
+
handle: async (request, { identity, params }) => created(request, await runner.rollback(id(params), requester(identity, clientIdentity(request))))
|
|
2664
|
+
},
|
|
2665
|
+
{
|
|
2666
|
+
method: "GET",
|
|
2667
|
+
pattern: `${deploymentsApiPath}/:id/source`,
|
|
2668
|
+
role: "viewer",
|
|
2669
|
+
handle: async (_request, { params }) => Response.json({
|
|
2670
|
+
files: await runner.source(id(params))
|
|
2671
|
+
})
|
|
2672
|
+
},
|
|
2673
|
+
{
|
|
2674
|
+
method: "GET",
|
|
2675
|
+
pattern: `${deploymentsApiPath}/:id/source/*`,
|
|
2676
|
+
role: "viewer",
|
|
2677
|
+
handle: async (_request, { params }) => new Response(await runner.sourceFile(id(params), param(params, "*")), {
|
|
2678
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
2679
|
+
})
|
|
2680
|
+
}
|
|
2681
|
+
];
|
|
2682
|
+
};
|
|
2683
|
+
|
|
2684
|
+
// packages/agent/src/discovery.ts
|
|
2685
|
+
import { Resolver } from "node:dns/promises";
|
|
2686
|
+
import { createConnection } from "node:net";
|
|
2687
|
+
import { networkInterfaces as osInterfaces } from "node:os";
|
|
2688
|
+
var largestPrefix = 22;
|
|
2689
|
+
var probeTimeoutMs = 500;
|
|
2690
|
+
var probesAtOnce = 128;
|
|
2691
|
+
var networkInterfaces = () => Object.entries(osInterfaces()).flatMap(([name, addresses]) => (addresses ?? []).filter((address) => address.family === "IPv4" && !address.internal).map((address) => ({
|
|
2692
|
+
name,
|
|
2693
|
+
address: address.address,
|
|
2694
|
+
prefixLength: address.netmask.split(".").reduce((bits, octet) => bits + Number(octet).toString(2).replaceAll("0", "").length, 0)
|
|
2695
|
+
})));
|
|
2696
|
+
var toNumber = (address) => address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
|
|
2697
|
+
var toAddress = (value) => [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
|
|
2698
|
+
var subnetHosts = ({ address, prefixLength }) => {
|
|
2699
|
+
if (prefixLength < largestPrefix) {
|
|
2700
|
+
throw new Error(`The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`);
|
|
2701
|
+
}
|
|
2702
|
+
const size = 2 ** (32 - prefixLength);
|
|
2703
|
+
const network = toNumber(address) - toNumber(address) % size;
|
|
2704
|
+
const hosts = size <= 2 ? Array.from({ length: size }, (_, index) => network + index) : Array.from({ length: size - 2 }, (_, index) => network + index + 1);
|
|
2705
|
+
return hosts.map(toAddress).filter((host) => host !== address);
|
|
2706
|
+
};
|
|
2707
|
+
var accepts = (host, port) => new Promise((resolve) => {
|
|
2708
|
+
const socket = createConnection({ host, port });
|
|
2709
|
+
const timer = setTimeout(() => finish(false), probeTimeoutMs);
|
|
2710
|
+
const finish = (open) => {
|
|
2711
|
+
clearTimeout(timer);
|
|
2712
|
+
socket.destroy();
|
|
2713
|
+
resolve(open);
|
|
2714
|
+
};
|
|
2715
|
+
socket.once("connect", () => finish(true));
|
|
2716
|
+
socket.once("error", () => finish(false));
|
|
2717
|
+
});
|
|
2718
|
+
var resolver = new Resolver({ timeout: 1000, tries: 1 });
|
|
2719
|
+
var hostname = (address) => resolver.reverse(address).then((names) => names[0] ?? null, () => null);
|
|
2720
|
+
var discoverControllers = async (network, port) => {
|
|
2721
|
+
const hosts = subnetHosts(network);
|
|
2722
|
+
const found = [];
|
|
2723
|
+
for (let start = 0;start < hosts.length; start += probesAtOnce) {
|
|
2724
|
+
const batch = hosts.slice(start, start + probesAtOnce);
|
|
2725
|
+
const open = await Promise.all(batch.map((host) => accepts(host, port)));
|
|
2726
|
+
for (const [index, host] of batch.entries()) {
|
|
2727
|
+
if (open[index]) {
|
|
2728
|
+
found.push({ address: host, port, hostname: await hostname(host) });
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
return found;
|
|
2733
|
+
};
|
|
2734
|
+
|
|
2735
|
+
// packages/agent/src/environment.ts
|
|
2736
|
+
import { envName as envName3 } from "@tsplc/config/build";
|
|
2737
|
+
import { z as z9 } from "zod";
|
|
2738
|
+
var storedNamesSchema = z9.record(z9.string(), z9.array(envName3));
|
|
2739
|
+
var storedVariablesSchema = z9.record(envName3, z9.string());
|
|
2740
|
+
var createEnvironment = (context) => {
|
|
2741
|
+
const { state, audit } = context;
|
|
2742
|
+
const { paths } = state;
|
|
2743
|
+
const storedNames = async () => await readJsonFile(paths.environment, storedNamesSchema) ?? {};
|
|
2744
|
+
const writeStoredNames = async (service, update) => {
|
|
2745
|
+
const stored = await storedNames();
|
|
2746
|
+
writeJsonFile(paths.environment, {
|
|
2747
|
+
...stored,
|
|
2748
|
+
[service]: update(stored[service] ?? [])
|
|
2749
|
+
});
|
|
2750
|
+
};
|
|
2751
|
+
const storedVariables = async () => await readJsonFile(paths.variables, storedVariablesSchema) ?? {};
|
|
2752
|
+
const deployedManifest = async () => {
|
|
2753
|
+
const release = await state.release();
|
|
2754
|
+
return release ? (await loadRelease(state.paths.releases, release.id)).manifest : undefined;
|
|
2755
|
+
};
|
|
2756
|
+
const declared = async () => (await deployedManifest())?.secrets ?? {
|
|
2757
|
+
service: environmentService,
|
|
2758
|
+
names: []
|
|
2759
|
+
};
|
|
2760
|
+
const isSet = async (service, name) => await Bun.secrets.get({ service, name }) !== null;
|
|
2761
|
+
const entries = async () => {
|
|
2762
|
+
const { service, names } = await declared();
|
|
2763
|
+
const stored = ((await storedNames())[service] ?? []).filter((name) => !names.includes(name));
|
|
2764
|
+
const undeclared = await Promise.all(stored.map(async (name) => ({
|
|
2765
|
+
name,
|
|
2766
|
+
declared: false,
|
|
2767
|
+
set: await isSet(service, name)
|
|
2768
|
+
})));
|
|
2769
|
+
return [
|
|
2770
|
+
...await Promise.all(names.map(async (name) => ({
|
|
2771
|
+
name,
|
|
2772
|
+
declared: true,
|
|
2773
|
+
set: await isSet(service, name)
|
|
2774
|
+
}))),
|
|
2775
|
+
...undeclared.filter(({ set }) => set)
|
|
2776
|
+
];
|
|
2777
|
+
};
|
|
2778
|
+
const listing = async () => ({
|
|
2779
|
+
values: (await deployedManifest())?.values ?? {},
|
|
2780
|
+
variables: await storedVariables(),
|
|
2781
|
+
secrets: await entries()
|
|
2782
|
+
});
|
|
2783
|
+
const forRelease = async (service) => {
|
|
2784
|
+
const held = (await storedNames())[service] ?? [];
|
|
2785
|
+
const set = await Promise.all(held.map(async (name) => await isSet(service, name) ? [name] : []));
|
|
2786
|
+
return { service, values: await storedVariables(), secrets: set.flat() };
|
|
2787
|
+
};
|
|
2788
|
+
const record = (identity, command, change) => audit.record({
|
|
2789
|
+
by: authorOf(identity),
|
|
2790
|
+
command,
|
|
2791
|
+
values: change.values,
|
|
2792
|
+
previous: change.previous,
|
|
2793
|
+
error: null
|
|
2794
|
+
});
|
|
2795
|
+
const nameOnly = { values: {}, previous: null };
|
|
2796
|
+
const withoutVariable = async (name) => {
|
|
2797
|
+
const { [name]: removed, ...rest } = await storedVariables();
|
|
2798
|
+
if (removed !== undefined) {
|
|
2799
|
+
writeJsonFile(paths.variables, rest);
|
|
2800
|
+
}
|
|
2801
|
+
return removed;
|
|
2802
|
+
};
|
|
2803
|
+
const routes = [
|
|
2804
|
+
{
|
|
2805
|
+
method: "GET",
|
|
2806
|
+
pattern: "/api/environment",
|
|
2807
|
+
role: "viewer",
|
|
2808
|
+
handle: async () => Response.json(await listing())
|
|
2809
|
+
},
|
|
2810
|
+
{
|
|
2811
|
+
method: "GET",
|
|
2812
|
+
pattern: "/api/environment/release",
|
|
2813
|
+
role: "deployer",
|
|
2814
|
+
handle: async (request) => Response.json(await forRelease(new URL(request.url).searchParams.get("service") || environmentService))
|
|
2815
|
+
},
|
|
2816
|
+
{
|
|
2817
|
+
method: "PUT",
|
|
2818
|
+
pattern: "/api/environment/:name",
|
|
2819
|
+
role: "admin",
|
|
2820
|
+
handle: async (request, { identity, params }) => {
|
|
2821
|
+
const name = envName3.parse(params.name);
|
|
2822
|
+
const change = environmentValueSchema.parse(await request.json());
|
|
2823
|
+
const { service } = await declared();
|
|
2824
|
+
if (change.secret) {
|
|
2825
|
+
await Bun.secrets.set({ service, name, value: change.value });
|
|
2826
|
+
await writeStoredNames(service, (stored) => [
|
|
2827
|
+
...stored.filter((other) => other !== name),
|
|
2828
|
+
name
|
|
2829
|
+
]);
|
|
2830
|
+
await withoutVariable(name);
|
|
2831
|
+
await record(identity, `environment set ${name}`, nameOnly);
|
|
2832
|
+
return Response.json(await listing());
|
|
2833
|
+
}
|
|
2834
|
+
const variables = await storedVariables();
|
|
2835
|
+
const previous = variables[name];
|
|
2836
|
+
writeJsonFile(paths.variables, { ...variables, [name]: change.value });
|
|
2837
|
+
if (await Bun.secrets.delete({ service, name })) {
|
|
2838
|
+
await writeStoredNames(service, (stored) => stored.filter((other) => other !== name));
|
|
2839
|
+
}
|
|
2840
|
+
await record(identity, `environment set ${name}`, {
|
|
2841
|
+
values: { [name]: change.value },
|
|
2842
|
+
previous: previous === undefined ? null : { [name]: previous }
|
|
2843
|
+
});
|
|
2844
|
+
return Response.json(await listing());
|
|
2845
|
+
}
|
|
2846
|
+
},
|
|
2847
|
+
{
|
|
2848
|
+
method: "DELETE",
|
|
2849
|
+
pattern: "/api/environment/:name",
|
|
2850
|
+
role: "admin",
|
|
2851
|
+
handle: async (_request, { identity, params }) => {
|
|
2852
|
+
const name = envName3.parse(params.name);
|
|
2853
|
+
const removed = await withoutVariable(name);
|
|
2854
|
+
if (removed !== undefined) {
|
|
2855
|
+
await record(identity, `environment delete ${name}`, {
|
|
2856
|
+
values: {},
|
|
2857
|
+
previous: { [name]: removed }
|
|
2858
|
+
});
|
|
2859
|
+
return Response.json(await listing());
|
|
2860
|
+
}
|
|
2861
|
+
const { service } = await declared();
|
|
2862
|
+
if (!await Bun.secrets.delete({ service, name })) {
|
|
2863
|
+
throw new AgentError(`${name} isn't set`, 404);
|
|
2864
|
+
}
|
|
2865
|
+
await writeStoredNames(service, (stored) => stored.filter((other) => other !== name));
|
|
2866
|
+
await record(identity, `environment delete ${name}`, nameOnly);
|
|
2867
|
+
return Response.json(await listing());
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
];
|
|
2871
|
+
return { routes };
|
|
2872
|
+
};
|
|
2873
|
+
|
|
2874
|
+
// packages/agent/src/login.ts
|
|
2875
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2876
|
+
import {
|
|
2877
|
+
failureReason,
|
|
2878
|
+
findControllerLogin,
|
|
2879
|
+
openControllerLogin,
|
|
2880
|
+
settleWarmController as settleWarmController2
|
|
2881
|
+
} from "@tsplc/build";
|
|
2882
|
+
import { LoginUnavailable, noLogin } from "@tsplc/debug";
|
|
2883
|
+
var loginStateTimeout = 30000;
|
|
2884
|
+
var stoppedAnswering = { error: "The login stopped answering" };
|
|
2885
|
+
var auditOf = (command) => {
|
|
2886
|
+
switch (command.command) {
|
|
2887
|
+
case "write":
|
|
2888
|
+
case "force":
|
|
2889
|
+
return { command: command.command, values: command.values };
|
|
2890
|
+
case "unforce":
|
|
2891
|
+
return {
|
|
2892
|
+
command: command.restore ? "unforce --restore" : "unforce",
|
|
2893
|
+
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
|
|
2894
|
+
};
|
|
2895
|
+
case "start":
|
|
2896
|
+
case "stop":
|
|
2897
|
+
return { command: command.command, values: {} };
|
|
2898
|
+
case "reset":
|
|
2899
|
+
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
2900
|
+
case "state":
|
|
2901
|
+
case "read":
|
|
2902
|
+
return;
|
|
2903
|
+
}
|
|
2904
|
+
};
|
|
2905
|
+
var createLogin = (context) => {
|
|
2906
|
+
const { state, operations } = context;
|
|
2907
|
+
let generation = 0;
|
|
2908
|
+
let commands = Promise.resolve();
|
|
2909
|
+
const enqueue = (run) => {
|
|
2910
|
+
const queuedIn = generation;
|
|
2911
|
+
const sent = commands.then(() => {
|
|
2912
|
+
if (queuedIn !== generation) {
|
|
2913
|
+
throw new AgentError("The login was closed", 409);
|
|
2914
|
+
}
|
|
2915
|
+
return run();
|
|
2916
|
+
});
|
|
2917
|
+
commands = sent.catch(() => {
|
|
2918
|
+
return;
|
|
2919
|
+
});
|
|
2920
|
+
return sent;
|
|
2921
|
+
};
|
|
2922
|
+
const send = (login, command) => enqueue(() => login.send(command));
|
|
2923
|
+
const openLogin = async () => {
|
|
2924
|
+
const lookedUpIn = generation;
|
|
2925
|
+
const login = await findControllerLogin(loginContainer);
|
|
2926
|
+
if (lookedUpIn !== generation) {
|
|
2927
|
+
throw new AgentError("The login was closed", 409);
|
|
2928
|
+
}
|
|
2929
|
+
if (!login) {
|
|
2930
|
+
throw new AgentError("No login is open: tsplc login", 409);
|
|
2931
|
+
}
|
|
2932
|
+
return login;
|
|
2933
|
+
};
|
|
2934
|
+
const requireLogin = async () => {
|
|
2935
|
+
operations.requireIdle();
|
|
2936
|
+
const login = await openLogin();
|
|
2937
|
+
operations.requireIdle();
|
|
2938
|
+
return login;
|
|
2939
|
+
};
|
|
2940
|
+
const isOpen = async () => await findControllerLogin(loginContainer) !== undefined;
|
|
2941
|
+
return {
|
|
2942
|
+
read: async ([first, ...rest]) => {
|
|
2943
|
+
const busy = operations.busy();
|
|
2944
|
+
if (busy === "a login") {
|
|
2945
|
+
throw new LoginUnavailable("The engineering login is opening", {
|
|
2946
|
+
state: "connecting"
|
|
2947
|
+
});
|
|
2948
|
+
}
|
|
2949
|
+
if (busy) {
|
|
2950
|
+
throw new LoginUnavailable(`Live values pause during ${busy}`);
|
|
2951
|
+
}
|
|
2952
|
+
const login = await findControllerLogin(loginContainer);
|
|
2953
|
+
if (!login) {
|
|
2954
|
+
throw new LoginUnavailable(noLogin);
|
|
2955
|
+
}
|
|
2956
|
+
if (!first) {
|
|
2957
|
+
return {};
|
|
2958
|
+
}
|
|
2959
|
+
const result = await send(login, {
|
|
2960
|
+
command: "read",
|
|
2961
|
+
expressions: [first, ...rest]
|
|
2962
|
+
});
|
|
2963
|
+
if (!("values" in result)) {
|
|
2964
|
+
throw new Error("The login answered a read without values");
|
|
2965
|
+
}
|
|
2966
|
+
return result.values;
|
|
2967
|
+
},
|
|
2968
|
+
open: async (sent) => {
|
|
2969
|
+
operations.requireIdle();
|
|
2970
|
+
await requireBuilder();
|
|
2971
|
+
const credentials = await controllerCredentials(sent);
|
|
2972
|
+
context.log(`Opening a login with the ${sent ? "provided" : "stored"} controller user`);
|
|
2973
|
+
const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller, context.codesys);
|
|
2974
|
+
return operations.stream("a login", async (emit) => {
|
|
2975
|
+
if (await isOpen()) {
|
|
2976
|
+
throw new AgentError("A login is already open", 409);
|
|
2977
|
+
}
|
|
2978
|
+
await settleWarmController2(config, deployContainer);
|
|
2979
|
+
emit({
|
|
2980
|
+
kind: "progress",
|
|
2981
|
+
message: "Logging in; CODESYS takes minutes to start"
|
|
2982
|
+
});
|
|
2983
|
+
await ensureGateway();
|
|
2984
|
+
const login = await openControllerLogin(config, loginContainer, {
|
|
2985
|
+
environment: credentialEnvironment(credentials)
|
|
2986
|
+
});
|
|
2987
|
+
return send(login, { command: "state" });
|
|
2988
|
+
});
|
|
2989
|
+
},
|
|
2990
|
+
command: async (command, client) => {
|
|
2991
|
+
const login = await requireLogin();
|
|
2992
|
+
const change = auditOf(command);
|
|
2993
|
+
if (!change) {
|
|
2994
|
+
return send(login, command);
|
|
2995
|
+
}
|
|
2996
|
+
return enqueue(async () => {
|
|
2997
|
+
const [first, ...rest] = Object.keys(change.values);
|
|
2998
|
+
const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
|
|
2999
|
+
return;
|
|
3000
|
+
}) : undefined;
|
|
3001
|
+
const audit = async (error) => context.audit.record({
|
|
3002
|
+
by: { ...client, release: (await state.release())?.id },
|
|
3003
|
+
...change,
|
|
3004
|
+
previous: previous ?? null,
|
|
3005
|
+
error
|
|
3006
|
+
});
|
|
3007
|
+
try {
|
|
3008
|
+
const result = await login.send(command);
|
|
3009
|
+
await audit(null);
|
|
3010
|
+
return result;
|
|
3011
|
+
} catch (error) {
|
|
3012
|
+
await audit(errorMessage(error));
|
|
3013
|
+
throw error;
|
|
3014
|
+
}
|
|
3015
|
+
});
|
|
3016
|
+
},
|
|
3017
|
+
restart: async (reset) => {
|
|
3018
|
+
const login = await openLogin();
|
|
3019
|
+
return enqueue(async () => {
|
|
3020
|
+
await login.send({ command: "reset", kind: reset });
|
|
3021
|
+
const started = await login.send({ command: "start" });
|
|
3022
|
+
if (!("state" in started)) {
|
|
3023
|
+
throw new Error("The login answered a start without the state");
|
|
3024
|
+
}
|
|
3025
|
+
return { state: started.state };
|
|
3026
|
+
});
|
|
3027
|
+
},
|
|
3028
|
+
isOpen,
|
|
3029
|
+
status: async () => {
|
|
3030
|
+
const login = await findControllerLogin(loginContainer);
|
|
3031
|
+
if (!login) {
|
|
3032
|
+
return null;
|
|
3033
|
+
}
|
|
3034
|
+
if (!await login.ready()) {
|
|
3035
|
+
return operations.busy() === "a login" ? null : stoppedAnswering;
|
|
3036
|
+
}
|
|
3037
|
+
try {
|
|
3038
|
+
const loginState = await Promise.race([
|
|
3039
|
+
send(login, { command: "state" }),
|
|
3040
|
+
delay(loginStateTimeout, null)
|
|
3041
|
+
]);
|
|
3042
|
+
if (!loginState) {
|
|
3043
|
+
return stoppedAnswering;
|
|
3044
|
+
}
|
|
3045
|
+
return "state" in loginState ? loginState : null;
|
|
3046
|
+
} catch (error) {
|
|
3047
|
+
return { error: failureReason(error) };
|
|
3048
|
+
}
|
|
3049
|
+
},
|
|
3050
|
+
logout: async () => {
|
|
3051
|
+
const login = await requireLogin();
|
|
3052
|
+
return operations.exclusive("a logout", async () => {
|
|
3053
|
+
generation++;
|
|
3054
|
+
const failure = await login.close();
|
|
3055
|
+
commands = Promise.resolve();
|
|
3056
|
+
if (failure) {
|
|
3057
|
+
context.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
3058
|
+
}
|
|
3059
|
+
return failure ? { failure } : {};
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
3062
|
+
};
|
|
3063
|
+
};
|
|
3064
|
+
|
|
3065
|
+
// packages/agent/src/restarts.ts
|
|
3066
|
+
import { resetLabel } from "@tsplc/build";
|
|
3067
|
+
import {
|
|
3068
|
+
controllerRestartPath as controllerRestartPath3,
|
|
3069
|
+
controllerRestartSchema
|
|
3070
|
+
} from "@tsplc/server/plant-agent";
|
|
3071
|
+
var createRestartRoutes = (context) => {
|
|
3072
|
+
const audited = async (identity, restart, run) => {
|
|
3073
|
+
const outcome = await run().then((result) => ({ result }), (failure) => ({ failure }));
|
|
3074
|
+
if ("failure" in outcome && outcome.failure instanceof AgentError) {
|
|
3075
|
+
throw outcome.failure;
|
|
3076
|
+
}
|
|
3077
|
+
await context.audit.record({
|
|
3078
|
+
by: authorOf(identity),
|
|
3079
|
+
command: restart.command,
|
|
3080
|
+
values: {},
|
|
3081
|
+
previous: null,
|
|
3082
|
+
error: "failure" in outcome ? errorMessage(outcome.failure) : null
|
|
3083
|
+
});
|
|
3084
|
+
if ("result" in outcome) {
|
|
3085
|
+
return outcome.result;
|
|
3086
|
+
}
|
|
3087
|
+
context.log(`${restart.action} failed: ${errorMessage(outcome.failure)}`);
|
|
3088
|
+
throw new AgentError(errorMessage(outcome.failure), 500);
|
|
3089
|
+
};
|
|
3090
|
+
return [
|
|
3091
|
+
{
|
|
3092
|
+
method: "POST",
|
|
3093
|
+
pattern: controllerRestartPath3,
|
|
3094
|
+
role: "deployer",
|
|
3095
|
+
handle: async (request, { identity }) => {
|
|
3096
|
+
const { reset } = controllerRestartSchema.parse(await request.json());
|
|
3097
|
+
return Response.json(await audited(identity, {
|
|
3098
|
+
command: reset === "warm" ? "restart" : "restart --cold",
|
|
3099
|
+
action: "Restarting the controller"
|
|
3100
|
+
}, () => context.restartController(resetLabel(reset))));
|
|
3101
|
+
}
|
|
3102
|
+
},
|
|
3103
|
+
{
|
|
3104
|
+
method: "POST",
|
|
3105
|
+
pattern: "/api/server/restart",
|
|
3106
|
+
role: "deployer",
|
|
3107
|
+
handle: async (_request, { identity }) => {
|
|
3108
|
+
const running = context.server.status();
|
|
3109
|
+
if (!running) {
|
|
3110
|
+
throw new AgentError("The deployed release runs no server", 409);
|
|
3111
|
+
}
|
|
3112
|
+
await audited(identity, { command: "server restart", action: "Restarting the server" }, () => context.operations.exclusive("a server restart", () => context.server.replace(running.executable)));
|
|
3113
|
+
return Response.json(context.server.status());
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
];
|
|
3117
|
+
};
|
|
3118
|
+
|
|
3119
|
+
// packages/agent/src/routes.ts
|
|
3120
|
+
import { z as z10 } from "zod";
|
|
3121
|
+
var matchRoute = (routes, method, pathname) => {
|
|
3122
|
+
const parts = pathname.split("/");
|
|
3123
|
+
for (const route of routes) {
|
|
3124
|
+
const pattern = route.pattern.split("/");
|
|
3125
|
+
const rest = pattern.at(-1) === "*";
|
|
3126
|
+
if (route.method !== method || (rest ? parts.length < pattern.length : pattern.length !== parts.length)) {
|
|
3127
|
+
continue;
|
|
3128
|
+
}
|
|
3129
|
+
const params = {};
|
|
3130
|
+
const matched = pattern.every((segment, index) => {
|
|
3131
|
+
const part = parts[index] ?? "";
|
|
3132
|
+
if (rest && index === pattern.length - 1) {
|
|
3133
|
+
params["*"] = parts.slice(index).map(decodeURIComponent).join("/");
|
|
3134
|
+
return part !== "";
|
|
3135
|
+
}
|
|
3136
|
+
if (segment.startsWith(":")) {
|
|
3137
|
+
params[segment.slice(1)] = decodeURIComponent(part);
|
|
3138
|
+
return part !== "";
|
|
3139
|
+
}
|
|
3140
|
+
return segment === part;
|
|
3141
|
+
});
|
|
3142
|
+
if (matched) {
|
|
3143
|
+
return { route, params };
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
return;
|
|
3147
|
+
};
|
|
3148
|
+
var routeDestination = (request, table) => {
|
|
3149
|
+
const matched = matchRoute(table.routes, request.method, new URL(request.url).pathname);
|
|
3150
|
+
return matched && {
|
|
3151
|
+
browser: table.browser,
|
|
3152
|
+
role: matched.route.role,
|
|
3153
|
+
handle: (identity) => matched.route.handle(request, { identity, params: matched.params })
|
|
3154
|
+
};
|
|
3155
|
+
};
|
|
3156
|
+
var answer = async (request, destination, identity, log) => {
|
|
3157
|
+
if (!destination) {
|
|
3158
|
+
return allows(identity.role, "admin") ? Response.json({
|
|
3159
|
+
error: `No route ${request.method} ${new URL(request.url).pathname}`
|
|
3160
|
+
}, { status: 404 }) : Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
3161
|
+
}
|
|
3162
|
+
if (!allows(identity.role, destination.role)) {
|
|
3163
|
+
return destination.browser ? Response.json({ error: `This needs the ${destination.role} role` }, { status: 403 }) : Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
3164
|
+
}
|
|
3165
|
+
try {
|
|
3166
|
+
return await destination.handle(identity);
|
|
3167
|
+
} catch (error) {
|
|
3168
|
+
if (error instanceof AgentError) {
|
|
3169
|
+
return Response.json({ error: error.message }, { status: error.status });
|
|
3170
|
+
}
|
|
3171
|
+
if (error instanceof z10.ZodError) {
|
|
3172
|
+
return Response.json({ error: z10.prettifyError(error) }, { status: 400 });
|
|
3173
|
+
}
|
|
3174
|
+
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
3175
|
+
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
3176
|
+
}
|
|
3177
|
+
};
|
|
3178
|
+
|
|
3179
|
+
// packages/agent/src/server-process.ts
|
|
3180
|
+
import { rm as rm4 } from "node:fs/promises";
|
|
3181
|
+
import { uptime } from "node:os";
|
|
3182
|
+
import { dirname as dirname4 } from "node:path";
|
|
3183
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
3184
|
+
import { z as z11 } from "zod";
|
|
3185
|
+
|
|
3186
|
+
// packages/agent/src/processes.ts
|
|
3187
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
3188
|
+
var isGone = (error) => error instanceof Error && ("code" in error) && error.code === "ESRCH";
|
|
3189
|
+
var processAlive = (pid) => {
|
|
3190
|
+
try {
|
|
3191
|
+
process.kill(pid, 0);
|
|
3192
|
+
return true;
|
|
3193
|
+
} catch (error) {
|
|
3194
|
+
return !isGone(error);
|
|
3195
|
+
}
|
|
3196
|
+
};
|
|
3197
|
+
var signalProcess = (pid, name) => {
|
|
3198
|
+
try {
|
|
3199
|
+
process.kill(pid, name);
|
|
3200
|
+
} catch (error) {
|
|
3201
|
+
if (!isGone(error)) {
|
|
3202
|
+
throw error;
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
};
|
|
3206
|
+
var waitUntil = async (condition, within) => {
|
|
3207
|
+
const deadline = Date.now() + within;
|
|
3208
|
+
while (Date.now() < deadline) {
|
|
3209
|
+
if (await condition()) {
|
|
3210
|
+
return true;
|
|
3211
|
+
}
|
|
3212
|
+
await delay2(1000);
|
|
3213
|
+
}
|
|
3214
|
+
return false;
|
|
3215
|
+
};
|
|
3216
|
+
|
|
3217
|
+
// packages/agent/src/server-process.ts
|
|
3218
|
+
var healthyWithinMs = 60000;
|
|
3219
|
+
var settleMs = 5000;
|
|
3220
|
+
var restartDelayMs = 2000;
|
|
3221
|
+
var watchMs = 2000;
|
|
3222
|
+
var adoptWithinMs = 1e4;
|
|
3223
|
+
var stopWithinMs = 1e4;
|
|
3224
|
+
var recordSchema = z11.strictObject({
|
|
3225
|
+
pid: z11.int().positive(),
|
|
3226
|
+
executable: z11.string(),
|
|
3227
|
+
startedAt: z11.number()
|
|
3228
|
+
});
|
|
3229
|
+
var mayStillRun = (record, machine) => record.startedAt > machine.now - machine.uptimeSeconds * 1000 && machine.alive(record.pid);
|
|
3230
|
+
var createServerSupervisor = (options) => {
|
|
3231
|
+
let current;
|
|
3232
|
+
const readEnvironment = (executable) => options.environment(executable).catch((error) => {
|
|
3233
|
+
options.log(`Starting the deployed server failed: ${errorMessage(error)}`);
|
|
3234
|
+
return null;
|
|
3235
|
+
});
|
|
3236
|
+
const restartWhenExited = (running, code) => {
|
|
3237
|
+
running.exited.then(() => {
|
|
3238
|
+
if (current !== running) {
|
|
3239
|
+
return;
|
|
3240
|
+
}
|
|
3241
|
+
options.log(`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`);
|
|
3242
|
+
delay3(restartDelayMs).then(async () => {
|
|
3243
|
+
if (current !== running) {
|
|
3244
|
+
return;
|
|
3245
|
+
}
|
|
3246
|
+
const environment = await readEnvironment(running.executable);
|
|
3247
|
+
if (current === running) {
|
|
3248
|
+
current = environment ? spawn(running.executable, environment) : undefined;
|
|
3249
|
+
}
|
|
3250
|
+
});
|
|
3251
|
+
});
|
|
3252
|
+
};
|
|
3253
|
+
const spawn = (executable, environment) => {
|
|
3254
|
+
const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
|
|
3255
|
+
const child = spawnWithLog(command, options.output, {
|
|
3256
|
+
cwd: dirname4(executable),
|
|
3257
|
+
env: environment,
|
|
3258
|
+
detached: true
|
|
3259
|
+
});
|
|
3260
|
+
const running = {
|
|
3261
|
+
executable,
|
|
3262
|
+
pid: child.pid,
|
|
3263
|
+
alive: () => child.exitCode === null && child.signalCode === null,
|
|
3264
|
+
exited: child.exited
|
|
3265
|
+
};
|
|
3266
|
+
writeJsonFile(options.record, {
|
|
3267
|
+
pid: child.pid,
|
|
3268
|
+
executable,
|
|
3269
|
+
startedAt: Date.now()
|
|
3270
|
+
});
|
|
3271
|
+
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
3272
|
+
return running;
|
|
3273
|
+
};
|
|
3274
|
+
const adopt = (record) => {
|
|
3275
|
+
const exited = Promise.withResolvers();
|
|
3276
|
+
const watch = setInterval(() => {
|
|
3277
|
+
if (!processAlive(record.pid)) {
|
|
3278
|
+
clearInterval(watch);
|
|
3279
|
+
exited.resolve();
|
|
3280
|
+
}
|
|
3281
|
+
}, watchMs);
|
|
3282
|
+
watch.unref();
|
|
3283
|
+
const running = {
|
|
3284
|
+
executable: record.executable,
|
|
3285
|
+
pid: record.pid,
|
|
3286
|
+
alive: () => processAlive(record.pid),
|
|
3287
|
+
exited: exited.promise
|
|
3288
|
+
};
|
|
3289
|
+
restartWhenExited(running, () => "unknown status");
|
|
3290
|
+
return running;
|
|
3291
|
+
};
|
|
3292
|
+
const answers = async (alive, within) => {
|
|
3293
|
+
const { healthUrl } = options;
|
|
3294
|
+
if (healthUrl === null) {
|
|
3295
|
+
return alive();
|
|
3296
|
+
}
|
|
3297
|
+
const settled = await waitUntil(async () => !alive() || await fetch(healthUrl).then((response) => response.ok, () => false), within);
|
|
3298
|
+
return settled && alive();
|
|
3299
|
+
};
|
|
3300
|
+
const start = (executable, environment) => {
|
|
3301
|
+
current = spawn(executable, environment);
|
|
3302
|
+
return current;
|
|
3303
|
+
};
|
|
3304
|
+
const stop = async () => {
|
|
3305
|
+
const running = current;
|
|
3306
|
+
current = undefined;
|
|
3307
|
+
if (!running) {
|
|
3308
|
+
return;
|
|
3309
|
+
}
|
|
3310
|
+
signalProcess(running.pid, "SIGTERM");
|
|
3311
|
+
await Promise.race([running.exited, delay3(stopWithinMs)]);
|
|
3312
|
+
if (running.alive()) {
|
|
3313
|
+
signalProcess(running.pid, "SIGKILL");
|
|
3314
|
+
await running.exited;
|
|
3315
|
+
}
|
|
3316
|
+
await rm4(options.record, { force: true });
|
|
3317
|
+
};
|
|
3318
|
+
const healthy = async (running) => {
|
|
3319
|
+
if (options.healthUrl === null) {
|
|
3320
|
+
await delay3(settleMs);
|
|
3321
|
+
return running.alive();
|
|
3322
|
+
}
|
|
3323
|
+
return answers(running.alive, healthyWithinMs);
|
|
3324
|
+
};
|
|
3325
|
+
return {
|
|
3326
|
+
healthUrl: options.healthUrl,
|
|
3327
|
+
resume: async (executable) => {
|
|
3328
|
+
const record = await readJsonFileIfValid(options.record, recordSchema);
|
|
3329
|
+
if (record?.executable === executable && mayStillRun(record, {
|
|
3330
|
+
now: Date.now(),
|
|
3331
|
+
uptimeSeconds: uptime(),
|
|
3332
|
+
alive: processAlive
|
|
3333
|
+
}) && await answers(() => processAlive(record.pid), adoptWithinMs)) {
|
|
3334
|
+
options.log(`Took over the running server (process ${record.pid})`);
|
|
3335
|
+
current = adopt(record);
|
|
3336
|
+
return;
|
|
3337
|
+
}
|
|
3338
|
+
const environment = await readEnvironment(executable);
|
|
3339
|
+
if (environment) {
|
|
3340
|
+
start(executable, environment);
|
|
3341
|
+
}
|
|
3342
|
+
},
|
|
3343
|
+
stop,
|
|
3344
|
+
leave: () => {
|
|
3345
|
+
current = undefined;
|
|
3346
|
+
},
|
|
3347
|
+
replace: async (executable) => {
|
|
3348
|
+
const previous = current;
|
|
3349
|
+
const environment = await options.environment(executable);
|
|
3350
|
+
await stop();
|
|
3351
|
+
const { started, failure } = await (async () => healthy(start(executable, environment)))().then((answered) => ({ started: answered, failure: undefined }), (error) => ({ started: false, failure: error }));
|
|
3352
|
+
if (started) {
|
|
3353
|
+
return;
|
|
3354
|
+
}
|
|
3355
|
+
await stop();
|
|
3356
|
+
const previousEnvironment = previous && await readEnvironment(previous.executable);
|
|
3357
|
+
if (previous && previousEnvironment) {
|
|
3358
|
+
start(previous.executable, previousEnvironment);
|
|
3359
|
+
}
|
|
3360
|
+
const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
3361
|
+
throw new Error(`The new server failed: ${reason}. ${previousEnvironment ? "The previous one is running again." : ""}`.trim(), { cause: failure });
|
|
3362
|
+
},
|
|
3363
|
+
status: () => current ? { executable: current.executable, running: current.alive() } : null
|
|
3364
|
+
};
|
|
3365
|
+
};
|
|
3366
|
+
|
|
3367
|
+
// packages/agent/src/agent.ts
|
|
3368
|
+
var statusRoute = (context) => ({
|
|
3369
|
+
method: "GET",
|
|
3370
|
+
pattern: statusPath,
|
|
3371
|
+
role: "viewer",
|
|
3372
|
+
handle: async () => Response.json({
|
|
3373
|
+
target: await context.state.target(),
|
|
3374
|
+
release: await context.state.release(),
|
|
3375
|
+
server: context.server.status(),
|
|
3376
|
+
login: await context.loginStatus(),
|
|
3377
|
+
credentialsStored: await storedCredentials() !== null
|
|
3378
|
+
})
|
|
3379
|
+
});
|
|
3380
|
+
var compareRoute = (context) => ({
|
|
3381
|
+
method: "POST",
|
|
3382
|
+
pattern: "/releases/compare",
|
|
3383
|
+
role: "admin",
|
|
3384
|
+
handle: async (request) => {
|
|
3385
|
+
const { buckets } = compareRequestSchema.parse(await request.json());
|
|
3386
|
+
const comparison = await context.releases.compare(buckets, (await context.state.release())?.id ?? null);
|
|
3387
|
+
return new Response(Bun.gzipSync(JSON.stringify(comparison)), {
|
|
3388
|
+
headers: {
|
|
3389
|
+
"Content-Type": "application/json",
|
|
3390
|
+
"Content-Encoding": "gzip"
|
|
3391
|
+
}
|
|
3392
|
+
});
|
|
3393
|
+
}
|
|
3394
|
+
});
|
|
3395
|
+
var createBrowserRoutes = (context) => [
|
|
3396
|
+
statusRoute(context),
|
|
3397
|
+
...createDeploymentRoutes(context),
|
|
3398
|
+
...context.access.routes,
|
|
3399
|
+
...createEnvironment(context).routes,
|
|
3400
|
+
...createRestartRoutes(context),
|
|
3401
|
+
...context.audit.routes
|
|
3402
|
+
];
|
|
3403
|
+
var answerRequest = async (request, peer, context) => {
|
|
3404
|
+
const page = await context.dashboard.handle(request);
|
|
3405
|
+
if (page) {
|
|
3406
|
+
return page;
|
|
3407
|
+
}
|
|
3408
|
+
const signing = await context.access.handle(request);
|
|
3409
|
+
if (signing) {
|
|
3410
|
+
return signing;
|
|
3411
|
+
}
|
|
3412
|
+
const target = context.destination(request);
|
|
3413
|
+
const identity = await context.access.identify(request, peer, {
|
|
3414
|
+
browser: target?.browser ?? new URL(request.url).pathname.startsWith("/api/")
|
|
3415
|
+
});
|
|
3416
|
+
if (identity instanceof Response) {
|
|
3417
|
+
return identity;
|
|
3418
|
+
}
|
|
3419
|
+
return answer(request, target, identity, context.log);
|
|
3420
|
+
};
|
|
3421
|
+
var debugRoute = (pathname) => pathname.slice(debuggerMount.length - 1);
|
|
3422
|
+
var createAgent = async (options) => {
|
|
3423
|
+
const { log } = options;
|
|
3424
|
+
const state = await openState(options.state);
|
|
3425
|
+
const server = createServerSupervisor({
|
|
3426
|
+
healthUrl: options.serverHealthUrl,
|
|
3427
|
+
record: state.paths.server,
|
|
3428
|
+
output: state.paths.serverLog,
|
|
3429
|
+
environment: async (executable) => ({
|
|
3430
|
+
...await serverEnvironment(await storedReleaseOf(state.paths.releases, executable), options.environment),
|
|
3431
|
+
...options.serverAccess && {
|
|
3432
|
+
[plantAgentEnv.url]: options.serverAccess.url,
|
|
3433
|
+
[plantAgentEnv.token]: options.serverAccess.token
|
|
3434
|
+
}
|
|
3435
|
+
}),
|
|
3436
|
+
log
|
|
3437
|
+
});
|
|
3438
|
+
const deployed = await state.release();
|
|
3439
|
+
if (deployed?.server) {
|
|
3440
|
+
await server.resume(releaseServerFile(state.paths.releases, deployed.server));
|
|
3441
|
+
}
|
|
3442
|
+
describeBuilder().then(log, (error) => log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`));
|
|
3443
|
+
const operations = createOperations(log);
|
|
3444
|
+
const codesys = { bulkImport: options.bulkImport };
|
|
3445
|
+
const releases = createReleaseStore(state.paths.releases);
|
|
3446
|
+
const audit = createAudit({
|
|
3447
|
+
file: state.paths.audit,
|
|
3448
|
+
onRecord: (entry) => debugging.record(entry)
|
|
3449
|
+
});
|
|
3450
|
+
const login = createLogin({ state, operations, codesys, audit, log });
|
|
3451
|
+
const debugging = createDebugging({
|
|
3452
|
+
state,
|
|
3453
|
+
readLogin: login.read,
|
|
3454
|
+
loginStatus: login.status,
|
|
3455
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
3456
|
+
environment: options.environment,
|
|
3457
|
+
log
|
|
3458
|
+
});
|
|
3459
|
+
const deployments = await createDeployments({
|
|
3460
|
+
state,
|
|
3461
|
+
operations,
|
|
3462
|
+
codesys,
|
|
3463
|
+
server,
|
|
3464
|
+
debugging,
|
|
3465
|
+
login,
|
|
3466
|
+
now: () => new Date,
|
|
3467
|
+
log
|
|
3468
|
+
});
|
|
3469
|
+
const access = createAccess({
|
|
3470
|
+
token: options.token,
|
|
3471
|
+
readToken: options.readToken,
|
|
3472
|
+
serverToken: options.serverAccess?.token ?? null,
|
|
3473
|
+
file: state.paths.access,
|
|
3474
|
+
whois: createWhois({ run: runCommand, now: Date.now, log }),
|
|
3475
|
+
audit,
|
|
3476
|
+
now: Date.now,
|
|
3477
|
+
log
|
|
3478
|
+
});
|
|
3479
|
+
const dashboard = createDashboard();
|
|
3480
|
+
const stop = async () => {
|
|
3481
|
+
await debugging.close();
|
|
3482
|
+
await server.stop();
|
|
3483
|
+
};
|
|
3484
|
+
const leave = async () => {
|
|
3485
|
+
await debugging.close();
|
|
3486
|
+
server.leave();
|
|
3487
|
+
};
|
|
3488
|
+
const browserRoutes = createBrowserRoutes({
|
|
3489
|
+
state,
|
|
3490
|
+
server,
|
|
3491
|
+
loginStatus: login.status,
|
|
3492
|
+
runner: deployments.runner,
|
|
3493
|
+
releases,
|
|
3494
|
+
access,
|
|
3495
|
+
restartController: deployments.restart,
|
|
3496
|
+
operations,
|
|
3497
|
+
audit,
|
|
3498
|
+
log
|
|
3499
|
+
});
|
|
3500
|
+
const cliRoutes = [
|
|
3501
|
+
{
|
|
3502
|
+
method: "GET",
|
|
3503
|
+
pattern: "/interfaces",
|
|
3504
|
+
role: "admin",
|
|
3505
|
+
handle: async () => Response.json(networkInterfaces())
|
|
3506
|
+
},
|
|
3507
|
+
{
|
|
3508
|
+
method: "POST",
|
|
3509
|
+
pattern: "/discover",
|
|
3510
|
+
role: "admin",
|
|
3511
|
+
handle: async (request) => {
|
|
3512
|
+
const { name } = discoverSchema.parse(await request.json());
|
|
3513
|
+
const selected = networkInterfaces().find((network) => network.name === name);
|
|
3514
|
+
if (!selected) {
|
|
3515
|
+
throw new AgentError(`No IPv4 interface named ${name}`, 404);
|
|
3516
|
+
}
|
|
3517
|
+
return Response.json(await discoverControllers(selected, runtimePort));
|
|
3518
|
+
}
|
|
3519
|
+
},
|
|
3520
|
+
{
|
|
3521
|
+
method: "PUT",
|
|
3522
|
+
pattern: "/target",
|
|
3523
|
+
role: "admin",
|
|
3524
|
+
handle: async (request) => {
|
|
3525
|
+
const target = targetSchema.parse(await request.json());
|
|
3526
|
+
await state.setTarget(target);
|
|
3527
|
+
return Response.json(target);
|
|
3528
|
+
}
|
|
3529
|
+
},
|
|
3530
|
+
{
|
|
3531
|
+
method: "GET",
|
|
3532
|
+
pattern: "/variables",
|
|
3533
|
+
role: "admin",
|
|
3534
|
+
handle: async () => Response.json((await state.requireRelease()).manifest.variables)
|
|
3535
|
+
},
|
|
3536
|
+
compareRoute({ state, releases }),
|
|
3537
|
+
{
|
|
3538
|
+
method: "POST",
|
|
3539
|
+
pattern: "/deploy",
|
|
3540
|
+
role: "admin",
|
|
3541
|
+
handle: async (request, { identity }) => deployments.deploy(() => readDeployRequest(releases, request), identity, clientIdentity(request), clientRelease(request))
|
|
3542
|
+
},
|
|
3543
|
+
{
|
|
3544
|
+
method: "POST",
|
|
3545
|
+
pattern: "/login",
|
|
3546
|
+
role: "admin",
|
|
3547
|
+
handle: async (request) => login.open(controllerCredentialsSchema2.nullable().parse(await request.json()))
|
|
3548
|
+
},
|
|
3549
|
+
{
|
|
3550
|
+
method: "POST",
|
|
3551
|
+
pattern: "/login/command",
|
|
3552
|
+
role: "admin",
|
|
3553
|
+
handle: async (request) => Response.json(await login.command(loginCommandSchema.parse(await request.json()), clientIdentity(request)))
|
|
3554
|
+
},
|
|
3555
|
+
{
|
|
3556
|
+
method: "DELETE",
|
|
3557
|
+
pattern: "/login",
|
|
3558
|
+
role: "admin",
|
|
3559
|
+
handle: async () => Response.json(await login.logout())
|
|
3560
|
+
},
|
|
3561
|
+
{
|
|
3562
|
+
method: "POST",
|
|
3563
|
+
pattern: agentHoldPath,
|
|
3564
|
+
role: "admin",
|
|
3565
|
+
handle: async () => {
|
|
3566
|
+
operations.hold();
|
|
3567
|
+
try {
|
|
3568
|
+
if (await login.isOpen()) {
|
|
3569
|
+
throw new AgentError("A login is open; log out before upgrading the agent: tsplc logout", 409);
|
|
3570
|
+
}
|
|
3571
|
+
await deployments.retire();
|
|
3572
|
+
} catch (error) {
|
|
3573
|
+
operations.release();
|
|
3574
|
+
throw error;
|
|
3575
|
+
}
|
|
3576
|
+
return Response.json({ held: true });
|
|
3577
|
+
}
|
|
3578
|
+
},
|
|
3579
|
+
{
|
|
3580
|
+
method: "DELETE",
|
|
3581
|
+
pattern: agentHoldPath,
|
|
3582
|
+
role: "admin",
|
|
3583
|
+
handle: async () => {
|
|
3584
|
+
operations.release();
|
|
3585
|
+
return Response.json({ held: false });
|
|
3586
|
+
}
|
|
3587
|
+
},
|
|
3588
|
+
{
|
|
3589
|
+
method: "POST",
|
|
3590
|
+
pattern: agentExitPath,
|
|
3591
|
+
role: "admin",
|
|
3592
|
+
handle: async (request) => {
|
|
3593
|
+
const exit = exitSchema.parse(await request.json());
|
|
3594
|
+
if (!operations.held()) {
|
|
3595
|
+
throw new AgentError("Hold the agent before it exits, so no operation is cut short", 409);
|
|
3596
|
+
}
|
|
3597
|
+
setTimeout(() => {
|
|
3598
|
+
(exit.server === "leave" ? leave() : stop()).then(() => options.exit(exit));
|
|
3599
|
+
}, 100);
|
|
3600
|
+
return Response.json({ exiting: true });
|
|
3601
|
+
}
|
|
3602
|
+
}
|
|
3603
|
+
];
|
|
3604
|
+
const destination = (request) => {
|
|
3605
|
+
const { pathname } = new URL(request.url);
|
|
3606
|
+
if (pathname.startsWith(debuggerMount)) {
|
|
3607
|
+
return {
|
|
3608
|
+
browser: true,
|
|
3609
|
+
role: "viewer",
|
|
3610
|
+
handle: () => debugging.handle(request, debugRoute(pathname))
|
|
3611
|
+
};
|
|
3612
|
+
}
|
|
3613
|
+
return routeDestination(request, { routes: browserRoutes, browser: true }) ?? routeDestination(request, { routes: cliRoutes, browser: false });
|
|
3614
|
+
};
|
|
3615
|
+
const respond = async (request, peer) => {
|
|
3616
|
+
const { pathname, search } = new URL(request.url);
|
|
3617
|
+
if (pathname === debuggerMount.slice(0, -1)) {
|
|
3618
|
+
return new Response(null, {
|
|
3619
|
+
status: 308,
|
|
3620
|
+
headers: { Location: `${debuggerMount}${search}` }
|
|
3621
|
+
});
|
|
3622
|
+
}
|
|
3623
|
+
if (request.method === "GET" && (pathname === debuggerMount || pathname === `${debuggerMount}ui.js`)) {
|
|
3624
|
+
return debugging.handle(request, debugRoute(pathname));
|
|
3625
|
+
}
|
|
3626
|
+
return answerRequest(request, peer, {
|
|
3627
|
+
dashboard,
|
|
3628
|
+
access,
|
|
3629
|
+
destination,
|
|
3630
|
+
log
|
|
3631
|
+
});
|
|
3632
|
+
};
|
|
3633
|
+
return {
|
|
3634
|
+
fetch: async (request, peer = null) => {
|
|
3635
|
+
const response = await respond(request, peer);
|
|
3636
|
+
const headers = new Headers(response.headers);
|
|
3637
|
+
headers.set(agentVersionHeader, tsplcVersion);
|
|
3638
|
+
return new Response(response.body, {
|
|
3639
|
+
status: response.status,
|
|
3640
|
+
statusText: response.statusText,
|
|
3641
|
+
headers
|
|
3642
|
+
});
|
|
3643
|
+
},
|
|
3644
|
+
stop,
|
|
3645
|
+
leave
|
|
3646
|
+
};
|
|
3647
|
+
};
|
|
3648
|
+
|
|
3649
|
+
// packages/agent/src/instance.ts
|
|
3650
|
+
import { rm as rm5 } from "node:fs/promises";
|
|
3651
|
+
import { z as z12 } from "zod";
|
|
3652
|
+
var instanceSchema = z12.strictObject({
|
|
3653
|
+
pid: z12.int().positive(),
|
|
3654
|
+
version: z12.string(),
|
|
3655
|
+
url: z12.url(),
|
|
3656
|
+
serve: z12.array(z12.string()),
|
|
3657
|
+
supervised: z12.boolean(),
|
|
3658
|
+
startedAt: z12.iso.datetime()
|
|
3659
|
+
});
|
|
3660
|
+
var restartStatus = 75;
|
|
3661
|
+
var removeInstance = async (file, pid) => {
|
|
3662
|
+
if ((await readInstance(file))?.pid === pid) {
|
|
3663
|
+
await rm5(file, { force: true });
|
|
3664
|
+
}
|
|
3665
|
+
};
|
|
3666
|
+
var readInstance = (file) => readJsonFileIfValid(file, instanceSchema);
|
|
3667
|
+
|
|
3668
|
+
// packages/agent/src/maintenance.ts
|
|
3669
|
+
import { mkdtemp as mkdtemp2, readFile as readFile5, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
|
|
3670
|
+
import { homedir, tmpdir } from "node:os";
|
|
3671
|
+
import { join as join8, resolve as resolve3 } from "node:path";
|
|
3672
|
+
import { agentTokenEnv } from "@tsplc/config";
|
|
3673
|
+
import { z as z16 } from "zod";
|
|
3674
|
+
|
|
3675
|
+
// packages/agent/src/client.ts
|
|
3676
|
+
import { hostname as hostname2, userInfo } from "node:os";
|
|
3677
|
+
import {
|
|
3678
|
+
loginResultSchema,
|
|
3679
|
+
workerScriptsDigest as workerScriptsDigest2
|
|
3680
|
+
} from "@tsplc/build";
|
|
3681
|
+
import { plantVariablesSchema } from "@tsplc/config";
|
|
3682
|
+
import { parseEventStream } from "@tsplc/debug/api";
|
|
3683
|
+
import {
|
|
3684
|
+
controllerRestartPath as controllerRestartPath4,
|
|
3685
|
+
controllerRestartReplySchema,
|
|
3686
|
+
refusalMessage
|
|
3687
|
+
} from "@tsplc/server/plant-agent";
|
|
3688
|
+
import { z as z13 } from "zod";
|
|
3689
|
+
class AgentOperationError extends Error {
|
|
3690
|
+
downloadRequired;
|
|
3691
|
+
rollback;
|
|
3692
|
+
constructor(message, {
|
|
3693
|
+
downloadRequired = false,
|
|
3694
|
+
rollback
|
|
3695
|
+
} = {}) {
|
|
3696
|
+
super(message);
|
|
3697
|
+
this.downloadRequired = downloadRequired;
|
|
3698
|
+
this.rollback = rollback;
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
class AgentUnreachable extends Error {
|
|
3703
|
+
}
|
|
3704
|
+
async function* bodyText(body) {
|
|
3705
|
+
try {
|
|
3706
|
+
yield* body.pipeThrough(new TextDecoderStream);
|
|
3707
|
+
} catch (cause) {
|
|
3708
|
+
throw new AgentUnreachable("The connection to the agent broke", { cause });
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
var createAgentClient = (options) => {
|
|
3712
|
+
const identity = workerScriptsDigest2().then((scripts) => ({ [clientHeaders.scripts]: scripts }), () => ({})).then((scripts) => ({
|
|
3713
|
+
[clientHeaders.user]: userInfo().username,
|
|
3714
|
+
[clientHeaders.host]: hostname2(),
|
|
3715
|
+
[clientHeaders.version]: tsplcVersion,
|
|
3716
|
+
...scripts
|
|
3717
|
+
}));
|
|
3718
|
+
const call = async (path, init = {}) => {
|
|
3719
|
+
const response = await fetch(new URL(path, options.url), {
|
|
3720
|
+
...init,
|
|
3721
|
+
headers: {
|
|
3722
|
+
...init.headers,
|
|
3723
|
+
...await identity,
|
|
3724
|
+
Authorization: `Bearer ${options.token}`
|
|
3725
|
+
}
|
|
3726
|
+
}).catch((cause) => {
|
|
3727
|
+
throw new AgentUnreachable(`Cannot reach the plant agent at ${options.url}`, { cause });
|
|
3728
|
+
});
|
|
3729
|
+
if (!response.ok) {
|
|
3730
|
+
throw new AgentOperationError(await refusalMessage(response));
|
|
3731
|
+
}
|
|
3732
|
+
return response;
|
|
3733
|
+
};
|
|
3734
|
+
const get = async (path, schema) => schema.parse(await (await call(path)).json());
|
|
3735
|
+
const send = async (method, path, body, schema) => schema.parse(await (await call(path, {
|
|
3736
|
+
method,
|
|
3737
|
+
headers: { "Content-Type": "application/json" },
|
|
3738
|
+
body: JSON.stringify(body)
|
|
3739
|
+
})).json());
|
|
3740
|
+
const operation = async (response, onProgress) => {
|
|
3741
|
+
const reader = response.body?.pipeThrough(new TextDecoderStream).getReader();
|
|
3742
|
+
if (!reader) {
|
|
3743
|
+
throw new Error("The agent returned no operation stream");
|
|
3744
|
+
}
|
|
3745
|
+
let buffered = "";
|
|
3746
|
+
while (true) {
|
|
3747
|
+
const { done, value } = await reader.read();
|
|
3748
|
+
if (done) {
|
|
3749
|
+
throw new Error("The agent closed the operation without a result");
|
|
3750
|
+
}
|
|
3751
|
+
buffered += value;
|
|
3752
|
+
const lines = buffered.split(`
|
|
3753
|
+
`);
|
|
3754
|
+
buffered = lines.pop() ?? "";
|
|
3755
|
+
for (const line of lines.filter(Boolean)) {
|
|
3756
|
+
const event = eventSchema.parse(JSON.parse(line));
|
|
3757
|
+
if (event.kind === "progress") {
|
|
3758
|
+
onProgress(event.message);
|
|
3759
|
+
} else if (event.kind === "done") {
|
|
3760
|
+
return event.result;
|
|
3761
|
+
} else {
|
|
3762
|
+
throw new AgentOperationError(event.message, {
|
|
3763
|
+
downloadRequired: event.downloadRequired,
|
|
3764
|
+
rollback: event.rollback
|
|
3765
|
+
});
|
|
3766
|
+
}
|
|
3767
|
+
}
|
|
3768
|
+
}
|
|
3769
|
+
};
|
|
3770
|
+
const compare = (buckets) => send("POST", "/releases/compare", { buckets }, comparisonSchema);
|
|
3771
|
+
const upload = async (release, settings, onProgress) => {
|
|
3772
|
+
const agentVersion = (await call(statusPath)).headers.get(agentVersionHeader);
|
|
3773
|
+
if (agentVersion !== tsplcVersion) {
|
|
3774
|
+
throw new AgentOperationError(versionMismatch({
|
|
3775
|
+
agent: agentVersion,
|
|
3776
|
+
client: tsplcVersion,
|
|
3777
|
+
agentUpgrades: upgradesItself(agentVersion)
|
|
3778
|
+
}));
|
|
3779
|
+
}
|
|
3780
|
+
const files = await Promise.all(release.files.map(async ({ path, content }) => ({
|
|
3781
|
+
path,
|
|
3782
|
+
content: await content.bytes()
|
|
3783
|
+
})));
|
|
3784
|
+
const digests = files.map(({ path, content }) => ({
|
|
3785
|
+
path,
|
|
3786
|
+
digest: shortDigest(content)
|
|
3787
|
+
}));
|
|
3788
|
+
const buckets = bucketDigests(digests);
|
|
3789
|
+
return releaseUpload({ manifest: release.manifest, options: settings, buckets }, files, await compare(buckets), onProgress);
|
|
3790
|
+
};
|
|
3791
|
+
return {
|
|
3792
|
+
url: options.url,
|
|
3793
|
+
status: () => get(statusPath, statusSchema),
|
|
3794
|
+
interfaces: () => get("/interfaces", z13.array(networkInterfaceSchema)),
|
|
3795
|
+
discover: (name) => send("POST", "/discover", { name }, z13.array(discoveredControllerSchema)),
|
|
3796
|
+
setTarget: (target) => send("PUT", "/target", target, targetSchema),
|
|
3797
|
+
variables: () => get("/variables", z13.array(variableSchema)),
|
|
3798
|
+
deploy: async (release, settings, onProgress) => {
|
|
3799
|
+
const body = await upload(release, settings, onProgress);
|
|
3800
|
+
return releaseSchema.parse(await operation(await call("/deploy", { method: "POST", ...body }), onProgress));
|
|
3801
|
+
},
|
|
3802
|
+
queueDeployment: async (release, settings, onProgress) => {
|
|
3803
|
+
const body = await upload(release, settings, onProgress);
|
|
3804
|
+
return deploymentCreatedSchema.parse(await (await call(deploymentsApiPath, { method: "POST", ...body })).json());
|
|
3805
|
+
},
|
|
3806
|
+
deployments: () => get(deploymentsApiPath, deploymentListSchema),
|
|
3807
|
+
deploymentEvents: async function* (id, after) {
|
|
3808
|
+
const response = await call(`${deploymentApiPath(id)}/events?after=${after}`, { headers: { Accept: "text/event-stream" } });
|
|
3809
|
+
if (!response.body) {
|
|
3810
|
+
throw new AgentUnreachable("The agent returned no event stream");
|
|
3811
|
+
}
|
|
3812
|
+
for await (const event of parseEventStream(bodyText(response.body))) {
|
|
3813
|
+
if (event.event === "record") {
|
|
3814
|
+
yield {
|
|
3815
|
+
kind: "record",
|
|
3816
|
+
record: deploymentRecordSchema.parse(JSON.parse(event.data))
|
|
3817
|
+
};
|
|
3818
|
+
} else if (event.event === "log") {
|
|
3819
|
+
yield {
|
|
3820
|
+
kind: "log",
|
|
3821
|
+
line: deploymentLogLineSchema.parse(JSON.parse(event.data))
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
},
|
|
3826
|
+
approve: async (id, approval) => {
|
|
3827
|
+
await call(`${deploymentApiPath(id)}/approve`, {
|
|
3828
|
+
method: "POST",
|
|
3829
|
+
headers: { "Content-Type": "application/json" },
|
|
3830
|
+
body: JSON.stringify(approval)
|
|
3831
|
+
});
|
|
3832
|
+
},
|
|
3833
|
+
redeploy: (id, mode) => send("POST", `${deploymentApiPath(id)}/redeploy`, { mode }, deploymentCreatedSchema),
|
|
3834
|
+
rollback: (id) => send("POST", `${deploymentApiPath(id)}/rollback`, {}, deploymentCreatedSchema),
|
|
3835
|
+
releaseVariables: (service) => get(`/api/environment/release${service === null ? "" : `?${new URLSearchParams({ service })}`}`, plantVariablesSchema),
|
|
3836
|
+
restartController: (restart) => send("POST", controllerRestartPath4, restart, controllerRestartReplySchema),
|
|
3837
|
+
login: async (credentials, onProgress) => loginResultSchema.parse(await operation(await call("/login", {
|
|
3838
|
+
method: "POST",
|
|
3839
|
+
headers: { "Content-Type": "application/json" },
|
|
3840
|
+
body: JSON.stringify(credentials)
|
|
3841
|
+
}), onProgress)),
|
|
3842
|
+
command: (command) => send("POST", "/login/command", command, loginResultSchema),
|
|
3843
|
+
logout: () => send("DELETE", "/login", undefined, logoutSchema),
|
|
3844
|
+
hold: async () => {
|
|
3845
|
+
await call(agentHoldPath, { method: "POST" });
|
|
3846
|
+
},
|
|
3847
|
+
releaseHold: async () => {
|
|
3848
|
+
await call(agentHoldPath, { method: "DELETE" });
|
|
3849
|
+
},
|
|
3850
|
+
exit: async (exit) => {
|
|
3851
|
+
await call(agentExitPath, {
|
|
3852
|
+
method: "POST",
|
|
3853
|
+
headers: { "Content-Type": "application/json" },
|
|
3854
|
+
body: JSON.stringify(exit)
|
|
3855
|
+
});
|
|
3856
|
+
}
|
|
3857
|
+
};
|
|
3858
|
+
};
|
|
3859
|
+
var releaseUpload = async (header, files, { base, changed }, onProgress) => {
|
|
3860
|
+
const stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));
|
|
3861
|
+
const uploaded = base === null ? files : files.filter(({ path, content }) => {
|
|
3862
|
+
const held = stored.get(fileBucket(path));
|
|
3863
|
+
return held !== undefined && held[path] !== shortDigest(content);
|
|
3864
|
+
});
|
|
3865
|
+
const paths = new Set(files.map(({ path }) => path));
|
|
3866
|
+
const remove = [...stored.values()].flatMap((held) => Object.keys(held).filter((path) => !paths.has(path)));
|
|
3867
|
+
const body = await encodeUpload({ ...header, base, remove }, uploaded);
|
|
3868
|
+
onProgress(`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`);
|
|
3869
|
+
return { headers: { "Content-Type": releaseUploadType }, body };
|
|
3870
|
+
};
|
|
3871
|
+
|
|
3872
|
+
// packages/agent/src/instance.ts
|
|
3873
|
+
import { z as z14 } from "zod";
|
|
3874
|
+
var instanceSchema2 = z14.strictObject({
|
|
3875
|
+
pid: z14.int().positive(),
|
|
3876
|
+
version: z14.string(),
|
|
3877
|
+
url: z14.url(),
|
|
3878
|
+
serve: z14.array(z14.string()),
|
|
3879
|
+
supervised: z14.boolean(),
|
|
3880
|
+
startedAt: z14.iso.datetime()
|
|
3881
|
+
});
|
|
3882
|
+
var restartStatus2 = 75;
|
|
3883
|
+
var readInstance2 = (file) => readJsonFileIfValid(file, instanceSchema2);
|
|
3884
|
+
var runningAgent = async (file) => {
|
|
3885
|
+
const instance = await readInstance2(file);
|
|
3886
|
+
return instance && processAlive(instance.pid) ? instance : null;
|
|
3887
|
+
};
|
|
3888
|
+
var answeringVersion = (url) => fetch(new URL(statusPath, url), { signal: AbortSignal.timeout(5000) }).then((response) => response.headers.get(agentVersionHeader), () => null);
|
|
3889
|
+
|
|
3890
|
+
// packages/agent/src/service.ts
|
|
3891
|
+
import { appendFile } from "node:fs/promises";
|
|
3892
|
+
import { setTimeout as delay4 } from "node:timers/promises";
|
|
3893
|
+
var serviceName = "tsplc-agent";
|
|
3894
|
+
var supervisedEnv = "TSPLC_AGENT_SUPERVISED";
|
|
3895
|
+
var quoteWindowsArgument = (argument) => {
|
|
3896
|
+
if (argument !== "" && !/[\s"]/.test(argument)) {
|
|
3897
|
+
return argument;
|
|
3898
|
+
}
|
|
3899
|
+
const escaped = argument.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/, "$1$1");
|
|
3900
|
+
return `"${escaped}"`;
|
|
3901
|
+
};
|
|
3902
|
+
var escapeXml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
3903
|
+
var taskDefinition = (task) => {
|
|
3904
|
+
const argumentsText = [task.script, "service", "run", ...task.serve].map(quoteWindowsArgument).join(" ");
|
|
3905
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
3906
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
3907
|
+
<RegistrationInfo>
|
|
3908
|
+
<Description>tsPLC plant agent: deploys to the controller and runs the line's server</Description>
|
|
3909
|
+
</RegistrationInfo>
|
|
3910
|
+
<Triggers>
|
|
3911
|
+
<BootTrigger>
|
|
3912
|
+
<Enabled>true</Enabled>
|
|
3913
|
+
</BootTrigger>
|
|
3914
|
+
</Triggers>
|
|
3915
|
+
<Principals>
|
|
3916
|
+
<Principal id="Author">
|
|
3917
|
+
<UserId>${escapeXml(task.user)}</UserId>
|
|
3918
|
+
<LogonType>Password</LogonType>
|
|
3919
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
3920
|
+
</Principal>
|
|
3921
|
+
</Principals>
|
|
3922
|
+
<Settings>
|
|
3923
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
3924
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
3925
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
3926
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
3927
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
3928
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
3929
|
+
<IdleSettings>
|
|
3930
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
3931
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
3932
|
+
</IdleSettings>
|
|
3933
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
3934
|
+
<Enabled>true</Enabled>
|
|
3935
|
+
<Hidden>false</Hidden>
|
|
3936
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
3937
|
+
<WakeToRun>false</WakeToRun>
|
|
3938
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
3939
|
+
<Priority>7</Priority>
|
|
3940
|
+
<RestartOnFailure>
|
|
3941
|
+
<Interval>PT1M</Interval>
|
|
3942
|
+
<Count>999</Count>
|
|
3943
|
+
</RestartOnFailure>
|
|
3944
|
+
</Settings>
|
|
3945
|
+
<Actions Context="Author">
|
|
3946
|
+
<Exec>
|
|
3947
|
+
<Command>${escapeXml(task.bun)}</Command>
|
|
3948
|
+
<Arguments>${escapeXml(argumentsText)}</Arguments>
|
|
3949
|
+
<WorkingDirectory>${escapeXml(task.workingDirectory)}</WorkingDirectory>
|
|
3950
|
+
</Exec>
|
|
3951
|
+
</Actions>
|
|
3952
|
+
</Task>
|
|
3953
|
+
`;
|
|
3954
|
+
};
|
|
3955
|
+
var taskFile = (definition) => Buffer.concat([
|
|
3956
|
+
Buffer.from([255, 254]),
|
|
3957
|
+
Buffer.from(definition, "utf16le")
|
|
3958
|
+
]);
|
|
3959
|
+
var schtasks = {
|
|
3960
|
+
create: (file, user) => [
|
|
3961
|
+
"schtasks",
|
|
3962
|
+
"/Create",
|
|
3963
|
+
"/TN",
|
|
3964
|
+
serviceName,
|
|
3965
|
+
"/XML",
|
|
3966
|
+
file,
|
|
3967
|
+
"/RU",
|
|
3968
|
+
user,
|
|
3969
|
+
"/RP",
|
|
3970
|
+
"*",
|
|
3971
|
+
"/F"
|
|
3972
|
+
],
|
|
3973
|
+
run: () => ["schtasks", "/Run", "/TN", serviceName],
|
|
3974
|
+
end: () => ["schtasks", "/End", "/TN", serviceName],
|
|
3975
|
+
remove: () => ["schtasks", "/Delete", "/TN", serviceName, "/F"],
|
|
3976
|
+
query: () => ["schtasks", "/Query", "/TN", serviceName, "/FO", "LIST", "/V"]
|
|
3977
|
+
};
|
|
3978
|
+
var steadyMs = 60000;
|
|
3979
|
+
var restartDelay = (exits) => {
|
|
3980
|
+
if (exits.ranMs >= steadyMs) {
|
|
3981
|
+
return 1000;
|
|
3982
|
+
}
|
|
3983
|
+
return Math.min(5000 * 2 ** (exits.quickExits - 1), 60000);
|
|
3984
|
+
};
|
|
3985
|
+
var stampedLine = (message) => `${new Date().toISOString()} ${message}
|
|
3986
|
+
`;
|
|
3987
|
+
var logLine = (file, message) => appendFile(file, stampedLine(message));
|
|
3988
|
+
var superviseAgent = async (options) => {
|
|
3989
|
+
const wait = options.wait ?? delay4;
|
|
3990
|
+
let quickExits = 0;
|
|
3991
|
+
while (true) {
|
|
3992
|
+
const started = Date.now();
|
|
3993
|
+
const child = spawnWithLog(options.command, options.log, {
|
|
3994
|
+
env: { ...options.environment, [supervisedEnv]: "1" },
|
|
3995
|
+
heading: stampedLine(`Starting ${options.command.join(" ")}`)
|
|
3996
|
+
});
|
|
3997
|
+
const status = await child.exited;
|
|
3998
|
+
const ranMs = Date.now() - started;
|
|
3999
|
+
if (status === 0) {
|
|
4000
|
+
await logLine(options.log, "The agent stopped as asked");
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
if (status === restartStatus2) {
|
|
4004
|
+
quickExits = 0;
|
|
4005
|
+
await logLine(options.log, "The agent exited to restart");
|
|
4006
|
+
continue;
|
|
4007
|
+
}
|
|
4008
|
+
quickExits = ranMs < steadyMs ? quickExits + 1 : 0;
|
|
4009
|
+
const pause = restartDelay({ ranMs, quickExits });
|
|
4010
|
+
await logLine(options.log, `The agent exited (${status}); starting it again in ${pause / 1000} s`);
|
|
4011
|
+
await wait(pause);
|
|
4012
|
+
}
|
|
4013
|
+
};
|
|
4014
|
+
|
|
4015
|
+
// packages/agent/src/upgrade.ts
|
|
4016
|
+
import { z as z15 } from "zod";
|
|
4017
|
+
var versionSchema = z15.string().regex(/^[0-9A-Za-z][0-9A-Za-z.+-]*$/, "Name a version, such as 0.5.0, or a dist-tag, such as latest");
|
|
4018
|
+
var normalize = (path) => path.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase();
|
|
4019
|
+
var packageManagerFor = (packagePath, npmGlobalRoot) => {
|
|
4020
|
+
const path = normalize(packagePath);
|
|
4021
|
+
if (path.endsWith("/install/global/node_modules/@tsplc/agent")) {
|
|
4022
|
+
return "bun";
|
|
4023
|
+
}
|
|
4024
|
+
if (npmGlobalRoot !== null && path === `${normalize(npmGlobalRoot)}/@tsplc/agent`) {
|
|
4025
|
+
return "npm";
|
|
4026
|
+
}
|
|
4027
|
+
return null;
|
|
4028
|
+
};
|
|
4029
|
+
var npmCommand = (platform, ...args) => platform === "win32" ? ["cmd.exe", "/d", "/s", "/c", "npm", ...args] : ["npm", ...args];
|
|
4030
|
+
var installCommand = (manager, version, host) => {
|
|
4031
|
+
const spec = `@tsplc/agent@${versionSchema.parse(version)}`;
|
|
4032
|
+
if (manager === "bun") {
|
|
4033
|
+
return [host.bun, "add", "--global", spec];
|
|
4034
|
+
}
|
|
4035
|
+
return npmCommand(host.platform, "install", "--global", spec);
|
|
4036
|
+
};
|
|
4037
|
+
var upgradeAgent = async (request, effects) => {
|
|
4038
|
+
const { running } = request;
|
|
4039
|
+
if (running) {
|
|
4040
|
+
effects.print(`Holding tsplc-agent ${running.instance.version} (process ${running.instance.pid}): it takes no deployments or logins until the new version runs`);
|
|
4041
|
+
await running.control.hold();
|
|
4042
|
+
}
|
|
4043
|
+
const installed = await (async () => {
|
|
4044
|
+
if (await effects.run(request.install) !== 0) {
|
|
4045
|
+
throw new Error(`Installing @tsplc/agent@${request.version} failed; see the output above`);
|
|
4046
|
+
}
|
|
4047
|
+
const version = await effects.installedVersion();
|
|
4048
|
+
if (running?.instance.version === version) {
|
|
4049
|
+
return null;
|
|
4050
|
+
}
|
|
4051
|
+
effects.print(`Installed tsplc-agent ${version}; checking its images`);
|
|
4052
|
+
if (await effects.run(request.setup) !== 0) {
|
|
4053
|
+
throw new Error(`tsplc-agent ${version} is installed, but its setup failed; see the output above. Run tsplc-agent upgrade ${version} again once it can`);
|
|
4054
|
+
}
|
|
4055
|
+
return version;
|
|
4056
|
+
})().catch(async (error) => {
|
|
4057
|
+
await running?.control.releaseHold();
|
|
4058
|
+
throw error;
|
|
4059
|
+
});
|
|
4060
|
+
if (installed === null) {
|
|
4061
|
+
await running?.control.releaseHold();
|
|
4062
|
+
effects.print(`tsplc-agent ${running?.instance.version} is installed and running already`);
|
|
4063
|
+
return;
|
|
4064
|
+
}
|
|
4065
|
+
if (!running) {
|
|
4066
|
+
if (!await effects.startService()) {
|
|
4067
|
+
effects.print(`tsplc-agent ${installed} is installed. No agent was running: start it with tsplc-agent serve, or install the service with tsplc-agent service install`);
|
|
4068
|
+
return;
|
|
4069
|
+
}
|
|
4070
|
+
effects.print("Started the tsplc-agent service");
|
|
4071
|
+
} else {
|
|
4072
|
+
effects.print(`Restarting the agent; the line's server keeps running and CODESYS starts again in the background`);
|
|
4073
|
+
await running.control.exit({ server: "leave", restart: true });
|
|
4074
|
+
if (!running.instance.supervised) {
|
|
4075
|
+
await effects.startAgent(running.instance);
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
if (!await effects.answers(installed)) {
|
|
4079
|
+
throw new Error(`tsplc-agent ${installed} is installed but doesn't answer; see ${request.agentLog}`);
|
|
4080
|
+
}
|
|
4081
|
+
effects.print(`tsplc-agent ${installed} is running`);
|
|
4082
|
+
};
|
|
4083
|
+
|
|
4084
|
+
// packages/agent/src/maintenance.ts
|
|
4085
|
+
var agentPackage = resolve3(import.meta.dir, "..");
|
|
4086
|
+
var installedVersion = async () => z16.object({ version: z16.string() }).parse(JSON.parse(await readFile5(join8(agentPackage, "package.json"), "utf8"))).version;
|
|
4087
|
+
var answerWithinMs = 180000;
|
|
4088
|
+
var exitWithinMs = 60000;
|
|
4089
|
+
var run = (command) => Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] }).exited;
|
|
4090
|
+
var quietly = (command) => Bun.spawn(command, { stdio: ["ignore", "ignore", "ignore"] }).exited;
|
|
4091
|
+
var capture = async (command) => {
|
|
4092
|
+
try {
|
|
4093
|
+
const child = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
|
|
4094
|
+
const [output, status] = await Promise.all([
|
|
4095
|
+
new Response(child.stdout).text(),
|
|
4096
|
+
child.exited
|
|
4097
|
+
]);
|
|
4098
|
+
return status === 0 ? output.trim() : null;
|
|
4099
|
+
} catch {
|
|
4100
|
+
return null;
|
|
4101
|
+
}
|
|
4102
|
+
};
|
|
4103
|
+
var agentCommand = (...args) => [
|
|
4104
|
+
process.execPath,
|
|
4105
|
+
Bun.main,
|
|
4106
|
+
...args
|
|
4107
|
+
];
|
|
4108
|
+
var controlOf = async (instance, environment) => {
|
|
4109
|
+
const token = await agentSetting(agentTokenEnv, environment);
|
|
4110
|
+
if (!token) {
|
|
4111
|
+
throw new Error(`tsplc-agent ${instance.version} is running, and holding it needs its token: set ${agentTokenEnv}, or store it with tsplc-agent secrets set ${agentTokenEnv} as the user the agent runs as`);
|
|
4112
|
+
}
|
|
4113
|
+
return createAgentClient({ url: instance.url, token });
|
|
4114
|
+
};
|
|
4115
|
+
var controlRunning = async (agentFile, environment) => {
|
|
4116
|
+
const instance = await runningAgent(agentFile);
|
|
4117
|
+
return instance && { instance, control: await controlOf(instance, environment) };
|
|
4118
|
+
};
|
|
4119
|
+
var waitForExit = async (instance) => {
|
|
4120
|
+
if (!await waitUntil(async () => !processAlive(instance.pid), exitWithinMs)) {
|
|
4121
|
+
throw new Error(`tsplc-agent (process ${instance.pid}) didn't exit within ${exitWithinMs / 1000} s`);
|
|
4122
|
+
}
|
|
4123
|
+
};
|
|
4124
|
+
var answers = (agentFile, version) => waitUntil(async () => {
|
|
4125
|
+
const instance = await runningAgent(agentFile);
|
|
4126
|
+
return instance?.version === version && await answeringVersion(instance.url) === version;
|
|
4127
|
+
}, answerWithinMs);
|
|
4128
|
+
var upgradeCommand = async (options) => {
|
|
4129
|
+
const state = await openState(options.state);
|
|
4130
|
+
const manager = packageManagerFor(agentPackage, null) ?? packageManagerFor(agentPackage, await capture(npmCommand(process.platform, "root", "--global")));
|
|
4131
|
+
if (!manager) {
|
|
4132
|
+
throw new Error(`This agent runs from ${agentPackage}, which isn't a global bun or npm install; upgrade it the way it was installed`);
|
|
4133
|
+
}
|
|
4134
|
+
await upgradeAgent({
|
|
4135
|
+
version: options.version,
|
|
4136
|
+
install: installCommand(manager, options.version, {
|
|
4137
|
+
bun: process.execPath,
|
|
4138
|
+
platform: process.platform
|
|
4139
|
+
}),
|
|
4140
|
+
setup: agentCommand("setup", "--if-needed"),
|
|
4141
|
+
running: await controlRunning(state.paths.agent, options.environment),
|
|
4142
|
+
agentLog: state.paths.agentLog
|
|
4143
|
+
}, {
|
|
4144
|
+
run,
|
|
4145
|
+
installedVersion,
|
|
4146
|
+
startAgent: async (instance) => {
|
|
4147
|
+
await waitForExit(instance);
|
|
4148
|
+
spawnWithLog(agentCommand("serve", ...instance.serve), state.paths.agentLog, { detached: true, windowsHide: true }).unref();
|
|
4149
|
+
},
|
|
4150
|
+
startService: async () => process.platform === "win32" && await quietly(schtasks.query()) === 0 && await run(schtasks.run()) === 0,
|
|
4151
|
+
answers: (version) => answers(state.paths.agent, version),
|
|
4152
|
+
print: (line) => console.log(line)
|
|
4153
|
+
});
|
|
4154
|
+
};
|
|
4155
|
+
var requireWindows = () => {
|
|
4156
|
+
if (process.platform !== "win32") {
|
|
4157
|
+
throw new Error("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");
|
|
4158
|
+
}
|
|
4159
|
+
};
|
|
4160
|
+
var releasing = async (running, step) => step().catch(async (error) => {
|
|
4161
|
+
await running?.control.releaseHold();
|
|
4162
|
+
throw error;
|
|
4163
|
+
});
|
|
4164
|
+
var serviceCommand = async (options) => {
|
|
4165
|
+
const state = await openState(options.state);
|
|
4166
|
+
const logs = `The agent's log is ${state.paths.agentLog}; the line's server's is ${state.paths.serverLog}`;
|
|
4167
|
+
switch (options.action) {
|
|
4168
|
+
case "run":
|
|
4169
|
+
await superviseAgent({
|
|
4170
|
+
command: agentCommand("serve", ...options.serve),
|
|
4171
|
+
log: state.paths.agentLog,
|
|
4172
|
+
environment: options.environment
|
|
4173
|
+
});
|
|
4174
|
+
return;
|
|
4175
|
+
case "install": {
|
|
4176
|
+
requireWindows();
|
|
4177
|
+
const { USERDOMAIN, USERNAME } = options.environment;
|
|
4178
|
+
if (!USERNAME) {
|
|
4179
|
+
throw new Error("USERNAME isn't set, so the service has no user to run as");
|
|
4180
|
+
}
|
|
4181
|
+
const user = [USERDOMAIN, USERNAME].filter(Boolean).join("\\");
|
|
4182
|
+
const running = await controlRunning(state.paths.agent, options.environment);
|
|
4183
|
+
await running?.control.hold();
|
|
4184
|
+
await releasing(running, async () => {
|
|
4185
|
+
const directory = await mkdtemp2(join8(tmpdir(), "tsplc-agent-service-"));
|
|
4186
|
+
try {
|
|
4187
|
+
const file = join8(directory, "task.xml");
|
|
4188
|
+
await writeFile3(file, taskFile(taskDefinition({
|
|
4189
|
+
bun: process.execPath,
|
|
4190
|
+
script: Bun.main,
|
|
4191
|
+
serve: options.serve,
|
|
4192
|
+
user,
|
|
4193
|
+
workingDirectory: homedir()
|
|
4194
|
+
})));
|
|
4195
|
+
console.log(`Registering the ${user} service; schtasks asks for ${user}'s Windows password, which Task Scheduler keeps to start the agent at boot`);
|
|
4196
|
+
if (await run(schtasks.create(file, user)) !== 0) {
|
|
4197
|
+
throw new Error("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");
|
|
4198
|
+
}
|
|
4199
|
+
} finally {
|
|
4200
|
+
await rm6(directory, { recursive: true, force: true });
|
|
4201
|
+
}
|
|
4202
|
+
});
|
|
4203
|
+
if (running) {
|
|
4204
|
+
console.log(`Handing over from tsplc-agent ${running.instance.version} (process ${running.instance.pid}); the line's server keeps running`);
|
|
4205
|
+
await running.control.exit({ server: "leave", restart: false });
|
|
4206
|
+
await waitForExit(running.instance);
|
|
4207
|
+
}
|
|
4208
|
+
if (await run(schtasks.run()) !== 0) {
|
|
4209
|
+
throw new Error("The service is registered but didn't start");
|
|
4210
|
+
}
|
|
4211
|
+
const version = await installedVersion();
|
|
4212
|
+
if (!await answers(state.paths.agent, version)) {
|
|
4213
|
+
throw new Error(`The service started but tsplc-agent ${version} doesn't answer. ${logs}`);
|
|
4214
|
+
}
|
|
4215
|
+
console.log(`The tsplc-agent service runs tsplc-agent ${version} at boot as ${user}, and starts it again if it exits. ${logs}`);
|
|
4216
|
+
return;
|
|
4217
|
+
}
|
|
4218
|
+
case "uninstall": {
|
|
4219
|
+
requireWindows();
|
|
4220
|
+
const running = await runningAgent(state.paths.agent);
|
|
4221
|
+
if (running?.supervised) {
|
|
4222
|
+
const control = await controlOf(running, options.environment);
|
|
4223
|
+
await control.hold();
|
|
4224
|
+
await control.exit({
|
|
4225
|
+
server: options.stopServer ? "stop" : "leave",
|
|
4226
|
+
restart: false
|
|
4227
|
+
});
|
|
4228
|
+
await waitForExit(running);
|
|
4229
|
+
} else {
|
|
4230
|
+
await quietly(schtasks.end());
|
|
4231
|
+
}
|
|
4232
|
+
if (await run(schtasks.remove()) !== 0) {
|
|
4233
|
+
throw new Error("Removing the service failed. Run it in a PowerShell opened with Run as administrator");
|
|
4234
|
+
}
|
|
4235
|
+
console.log(options.stopServer || !running?.supervised ? "Removed the tsplc-agent service" : "Removed the tsplc-agent service. The line's server keeps running; the next tsplc-agent serve takes it over");
|
|
4236
|
+
return;
|
|
4237
|
+
}
|
|
4238
|
+
case "status": {
|
|
4239
|
+
if (process.platform === "win32" && await run(schtasks.query()) !== 0) {
|
|
4240
|
+
console.log("The tsplc-agent service isn't installed");
|
|
4241
|
+
}
|
|
4242
|
+
const running = await runningAgent(state.paths.agent);
|
|
4243
|
+
console.log(running ? `tsplc-agent ${running.version} runs as process ${running.pid} at ${running.url}${running.supervised ? ", under the service" : ""}, since ${running.startedAt}` : "No tsplc-agent is running");
|
|
4244
|
+
console.log(logs);
|
|
4245
|
+
return;
|
|
4246
|
+
}
|
|
4247
|
+
default:
|
|
4248
|
+
throw new Error("Usage: tsplc-agent service install|uninstall|status|run [serve options]");
|
|
4249
|
+
}
|
|
4250
|
+
};
|
|
4251
|
+
|
|
4252
|
+
// packages/agent/src/protocol.ts
|
|
4253
|
+
import {
|
|
4254
|
+
controllerCredentialsSchema as controllerCredentialsSchema3,
|
|
4255
|
+
controllerIdsSchema as controllerIdsSchema2,
|
|
4256
|
+
loginStateSchema as loginStateSchema2,
|
|
4257
|
+
onlineChangeFindingSchema as onlineChangeFindingSchema2,
|
|
4258
|
+
rollbackSchema as rollbackSchema2
|
|
4259
|
+
} from "@tsplc/build";
|
|
4260
|
+
import { plainValue as plainValue2, secretValue as secretValue3, tsplcConfigSchema as tsplcConfigSchema2 } from "@tsplc/config";
|
|
4261
|
+
import { envName as envName4, releaseConfigSchema as releaseConfigSchema2, tcpPort as tcpPort2 } from "@tsplc/config/build";
|
|
4262
|
+
import { z as z17 } from "zod";
|
|
4263
|
+
var tsplcVersion2 = version;
|
|
4264
|
+
var targetSchema2 = z17.strictObject({
|
|
4265
|
+
host: z17.string().nonempty(),
|
|
4266
|
+
port: tcpPort2
|
|
4267
|
+
});
|
|
4268
|
+
var networkInterfaceSchema2 = z17.strictObject({
|
|
4269
|
+
name: z17.string(),
|
|
4270
|
+
address: z17.ipv4(),
|
|
4271
|
+
prefixLength: z17.number().int().min(0).max(32)
|
|
4272
|
+
});
|
|
4273
|
+
var discoveredControllerSchema2 = z17.strictObject({
|
|
4274
|
+
address: z17.ipv4(),
|
|
4275
|
+
port: z17.number().int(),
|
|
4276
|
+
hostname: z17.string().nullable()
|
|
4277
|
+
});
|
|
4278
|
+
var discoverSchema2 = z17.strictObject({ name: z17.string() });
|
|
4279
|
+
var variableSchema2 = z17.strictObject({
|
|
4280
|
+
path: z17.string(),
|
|
4281
|
+
type: z17.string()
|
|
4282
|
+
});
|
|
4283
|
+
var targetValuesSchema2 = z17.record(envName4, z17.string());
|
|
4284
|
+
var releaseManifestSchema2 = z17.strictObject({
|
|
4285
|
+
config: z17.record(z17.string(), z17.unknown()).superRefine((config, context) => {
|
|
4286
|
+
const release = releaseConfigSchema2.safeParse(config);
|
|
4287
|
+
if (!release.success) {
|
|
4288
|
+
context.addIssue({
|
|
4289
|
+
code: "custom",
|
|
4290
|
+
message: `Invalid release config: ${z17.prettifyError(release.error)}`
|
|
4291
|
+
});
|
|
4292
|
+
}
|
|
4293
|
+
}),
|
|
4294
|
+
variables: z17.array(variableSchema2),
|
|
4295
|
+
server: z17.string().nonempty().optional(),
|
|
4296
|
+
debug: tsplcConfigSchema2.shape.debug,
|
|
4297
|
+
serverTokenEnv: z17.string().nonempty().optional(),
|
|
4298
|
+
secrets: tsplcConfigSchema2.shape.secrets,
|
|
4299
|
+
values: targetValuesSchema2.default({})
|
|
4300
|
+
});
|
|
4301
|
+
var gitSourceSchema2 = z17.strictObject({
|
|
4302
|
+
commit: z17.string().nonempty(),
|
|
4303
|
+
branch: z17.string().nullable(),
|
|
4304
|
+
dirty: z17.boolean(),
|
|
4305
|
+
message: z17.string().nullable()
|
|
4306
|
+
});
|
|
4307
|
+
var deploymentModeSchema2 = z17.enum(["apply", "review"]);
|
|
4308
|
+
var deploymentRequestSchema2 = z17.strictObject({
|
|
4309
|
+
mode: deploymentModeSchema2,
|
|
4310
|
+
git: gitSourceSchema2.nullable()
|
|
4311
|
+
});
|
|
4312
|
+
var deployOptionsSchema2 = z17.strictObject({
|
|
4313
|
+
credentials: controllerCredentialsSchema3.nullable(),
|
|
4314
|
+
download: z17.boolean(),
|
|
4315
|
+
initializeUser: z17.boolean(),
|
|
4316
|
+
deployment: deploymentRequestSchema2.optional()
|
|
4317
|
+
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
4318
|
+
var releaseBuckets2 = 256;
|
|
4319
|
+
var shortHex2 = z17.string().regex(/^[a-f0-9]{16}$/);
|
|
4320
|
+
var compareRequestSchema2 = z17.strictObject({
|
|
4321
|
+
buckets: z17.array(shortHex2).length(releaseBuckets2)
|
|
4322
|
+
});
|
|
4323
|
+
var comparisonSchema2 = z17.strictObject({
|
|
4324
|
+
base: shortHex2.nullable(),
|
|
4325
|
+
changed: z17.array(z17.strictObject({
|
|
4326
|
+
bucket: z17.number().int().min(0).max(releaseBuckets2 - 1),
|
|
4327
|
+
files: z17.record(z17.string(), shortHex2)
|
|
4328
|
+
}))
|
|
4329
|
+
});
|
|
4330
|
+
var releaseUploadSchema2 = z17.strictObject({
|
|
4331
|
+
manifest: releaseManifestSchema2,
|
|
4332
|
+
options: deployOptionsSchema2,
|
|
4333
|
+
base: shortHex2.nullable(),
|
|
4334
|
+
buckets: compareRequestSchema2.shape.buckets,
|
|
4335
|
+
remove: z17.array(z17.string())
|
|
4336
|
+
});
|
|
4337
|
+
var eventSchema2 = z17.discriminatedUnion("kind", [
|
|
4338
|
+
z17.strictObject({ kind: z17.literal("progress"), message: z17.string() }),
|
|
4339
|
+
z17.strictObject({ kind: z17.literal("done"), result: z17.unknown() }),
|
|
4340
|
+
z17.strictObject({
|
|
4341
|
+
kind: z17.literal("error"),
|
|
4342
|
+
message: z17.string(),
|
|
4343
|
+
downloadRequired: z17.boolean(),
|
|
4344
|
+
rollback: rollbackSchema2.optional()
|
|
4345
|
+
})
|
|
4346
|
+
]);
|
|
4347
|
+
var deployOperationSchema2 = z17.enum(["download", "online-change"]);
|
|
4348
|
+
var releaseSchema2 = z17.strictObject({
|
|
4349
|
+
id: z17.string(),
|
|
4350
|
+
deployedAt: z17.iso.datetime(),
|
|
4351
|
+
operation: deployOperationSchema2,
|
|
4352
|
+
controllerIds: controllerIdsSchema2,
|
|
4353
|
+
server: z17.string().optional()
|
|
4354
|
+
});
|
|
4355
|
+
var statusSchema2 = z17.strictObject({
|
|
4356
|
+
target: targetSchema2.nullable(),
|
|
4357
|
+
release: releaseSchema2.nullable(),
|
|
4358
|
+
server: z17.strictObject({ executable: z17.string(), running: z17.boolean() }).nullable(),
|
|
4359
|
+
login: z17.union([loginStateSchema2, z17.strictObject({ error: z17.string() })]).nullable(),
|
|
4360
|
+
credentialsStored: z17.boolean()
|
|
4361
|
+
});
|
|
4362
|
+
var exitSchema2 = z17.strictObject({
|
|
4363
|
+
server: z17.enum(["leave", "stop"]),
|
|
4364
|
+
restart: z17.boolean()
|
|
4365
|
+
});
|
|
4366
|
+
var logoutSchema2 = z17.strictObject({ failure: z17.string().optional() });
|
|
4367
|
+
var deploymentSchema2 = z17.strictObject({
|
|
4368
|
+
at: z17.iso.datetime(),
|
|
4369
|
+
release: z17.string(),
|
|
4370
|
+
build: z17.string().optional(),
|
|
4371
|
+
operation: deployOperationSchema2,
|
|
4372
|
+
credentials: z17.enum(["provided", "stored"]).optional(),
|
|
4373
|
+
user: z17.string().optional(),
|
|
4374
|
+
host: z17.string().optional()
|
|
4375
|
+
});
|
|
4376
|
+
var auditSchema2 = z17.strictObject({
|
|
4377
|
+
at: z17.iso.datetime(),
|
|
4378
|
+
command: z17.string(),
|
|
4379
|
+
values: z17.record(z17.string(), z17.string()),
|
|
4380
|
+
previous: z17.record(z17.string(), z17.string()).optional(),
|
|
4381
|
+
user: z17.string().optional(),
|
|
4382
|
+
host: z17.string().optional(),
|
|
4383
|
+
release: z17.string().optional(),
|
|
4384
|
+
error: z17.string().optional()
|
|
4385
|
+
});
|
|
4386
|
+
var roles2 = ["viewer", "deployer", "admin"];
|
|
4387
|
+
var roleSchema2 = z17.enum(roles2);
|
|
4388
|
+
var identitySchema2 = z17.strictObject({
|
|
4389
|
+
login: z17.string().nullable(),
|
|
4390
|
+
name: z17.string(),
|
|
4391
|
+
role: roleSchema2,
|
|
4392
|
+
via: z17.enum(["tailscale", "token", "local", "server"])
|
|
4393
|
+
});
|
|
4394
|
+
var deploymentStateSchema2 = z17.enum([
|
|
4395
|
+
"queued",
|
|
4396
|
+
"building",
|
|
4397
|
+
"awaitingApproval",
|
|
4398
|
+
"applying",
|
|
4399
|
+
"starting",
|
|
4400
|
+
"verifying",
|
|
4401
|
+
"ready",
|
|
4402
|
+
"error",
|
|
4403
|
+
"canceled"
|
|
4404
|
+
]);
|
|
4405
|
+
var deploymentPhaseNameSchema2 = z17.enum([
|
|
4406
|
+
"queue",
|
|
4407
|
+
"build",
|
|
4408
|
+
"review",
|
|
4409
|
+
"apply",
|
|
4410
|
+
"server",
|
|
4411
|
+
"health"
|
|
4412
|
+
]);
|
|
4413
|
+
var deploymentIdSchema2 = z17.string().regex(/^dpl_[a-z0-9]{16,32}$/);
|
|
4414
|
+
var deploymentRecordSchema2 = z17.strictObject({
|
|
4415
|
+
id: deploymentIdSchema2,
|
|
4416
|
+
release: z17.string(),
|
|
4417
|
+
build: z17.string().nullable(),
|
|
4418
|
+
createdAt: z17.iso.datetime(),
|
|
4419
|
+
updatedAt: z17.iso.datetime(),
|
|
4420
|
+
origin: z17.discriminatedUnion("kind", [
|
|
4421
|
+
z17.strictObject({ kind: z17.literal("upload") }),
|
|
4422
|
+
z17.strictObject({ kind: z17.literal("redeploy"), from: deploymentIdSchema2 }),
|
|
4423
|
+
z17.strictObject({ kind: z17.literal("rollback"), from: deploymentIdSchema2 })
|
|
4424
|
+
]),
|
|
4425
|
+
git: gitSourceSchema2.nullable(),
|
|
4426
|
+
requestedBy: z17.strictObject({
|
|
4427
|
+
identity: identitySchema2.omit({ role: true }),
|
|
4428
|
+
user: z17.string().nullable(),
|
|
4429
|
+
host: z17.string().nullable()
|
|
4430
|
+
}),
|
|
4431
|
+
mode: deploymentModeSchema2,
|
|
4432
|
+
operation: deployOperationSchema2,
|
|
4433
|
+
state: deploymentStateSchema2,
|
|
4434
|
+
phases: z17.array(z17.strictObject({
|
|
4435
|
+
name: deploymentPhaseNameSchema2,
|
|
4436
|
+
startedAt: z17.iso.datetime(),
|
|
4437
|
+
finishedAt: z17.iso.datetime().nullable(),
|
|
4438
|
+
outcome: z17.enum(["running", "ok", "failed", "skipped"])
|
|
4439
|
+
})),
|
|
4440
|
+
findings: z17.array(onlineChangeFindingSchema2),
|
|
4441
|
+
approval: z17.strictObject({
|
|
4442
|
+
reason: z17.enum(["review", "downloadRequired"]),
|
|
4443
|
+
message: z17.string()
|
|
4444
|
+
}).nullable(),
|
|
4445
|
+
error: z17.strictObject({
|
|
4446
|
+
message: z17.string(),
|
|
4447
|
+
downloadRequired: z17.boolean(),
|
|
4448
|
+
rollback: rollbackSchema2.optional()
|
|
4449
|
+
}).nullable(),
|
|
4450
|
+
controllerIds: controllerIdsSchema2.nullable(),
|
|
4451
|
+
health: z17.strictObject({
|
|
4452
|
+
controller: z17.enum(["ok", "failed"]),
|
|
4453
|
+
server: z17.enum(["ok", "failed", "none"]),
|
|
4454
|
+
plc: z17.enum(["ok", "failed", "unknown"]),
|
|
4455
|
+
detail: z17.string().nullable()
|
|
4456
|
+
}).nullable(),
|
|
4457
|
+
activeFrom: z17.iso.datetime().nullable(),
|
|
4458
|
+
activeUntil: z17.iso.datetime().nullable()
|
|
4459
|
+
});
|
|
4460
|
+
var deploymentLogLineSchema2 = z17.strictObject({
|
|
4461
|
+
seq: z17.number().int().positive(),
|
|
4462
|
+
at: z17.iso.datetime(),
|
|
4463
|
+
level: z17.enum(["info", "warning", "error"]),
|
|
4464
|
+
phase: deploymentPhaseNameSchema2.nullable(),
|
|
4465
|
+
message: z17.string()
|
|
4466
|
+
});
|
|
4467
|
+
var deploymentCreatedSchema2 = z17.strictObject({
|
|
4468
|
+
id: deploymentIdSchema2,
|
|
4469
|
+
url: z17.string()
|
|
4470
|
+
});
|
|
4471
|
+
var deploymentListSchema2 = z17.strictObject({
|
|
4472
|
+
deployments: z17.array(deploymentRecordSchema2),
|
|
4473
|
+
current: deploymentIdSchema2.nullable(),
|
|
4474
|
+
lastGood: deploymentIdSchema2.nullable()
|
|
4475
|
+
});
|
|
4476
|
+
var approveSchema2 = z17.strictObject({ download: z17.boolean() });
|
|
4477
|
+
var redeploySchema2 = z17.strictObject({ mode: deploymentModeSchema2 });
|
|
4478
|
+
var deploymentSourceSchema2 = z17.strictObject({
|
|
4479
|
+
files: z17.array(z17.strictObject({ path: z17.string(), size: z17.number().int().nonnegative() }))
|
|
4480
|
+
});
|
|
4481
|
+
var environmentEntrySchema2 = z17.strictObject({
|
|
4482
|
+
name: z17.string(),
|
|
4483
|
+
declared: z17.boolean(),
|
|
4484
|
+
set: z17.boolean()
|
|
4485
|
+
});
|
|
4486
|
+
var environmentSchema2 = z17.strictObject({
|
|
4487
|
+
values: targetValuesSchema2,
|
|
4488
|
+
variables: z17.record(envName4, z17.string()),
|
|
4489
|
+
secrets: z17.array(environmentEntrySchema2)
|
|
4490
|
+
});
|
|
4491
|
+
var accessConfigSchema2 = z17.strictObject({
|
|
4492
|
+
roles: z17.record(z17.string().nonempty(), roleSchema2),
|
|
4493
|
+
tailnetDefault: roleSchema2.nullable()
|
|
4494
|
+
});
|
|
4495
|
+
var sessionRequestSchema2 = z17.strictObject({ token: z17.string() });
|
|
4496
|
+
var environmentValueSchema2 = z17.discriminatedUnion("secret", [
|
|
4497
|
+
z17.strictObject({ secret: z17.literal(false), value: plainValue2 }),
|
|
4498
|
+
z17.strictObject({ secret: z17.literal(true), value: secretValue3 })
|
|
4499
|
+
]);
|
|
4500
|
+
|
|
4501
|
+
// packages/agent/src/secrets.ts
|
|
4502
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
4503
|
+
import {
|
|
4504
|
+
secretPlaceholder as secretPlaceholder2,
|
|
4505
|
+
secretValue as secretValue4
|
|
4506
|
+
} from "@tsplc/config";
|
|
4507
|
+
import { escapeString as escapeString2 } from "@tsplc/iec/st";
|
|
4508
|
+
var agentService2 = "tsplc-agent";
|
|
4509
|
+
var agentReadTokenEnv = "TSPLC_AGENT_READ_TOKEN";
|
|
4510
|
+
var controllerSecretNames2 = {
|
|
4511
|
+
username: "controller-username",
|
|
4512
|
+
password: "controller-password"
|
|
4513
|
+
};
|
|
4514
|
+
var agentSetting2 = async (name, environment) => environment[name] ?? await Bun.secrets.get({ service: agentService2, name });
|
|
4515
|
+
var serverToken = async () => {
|
|
4516
|
+
const name = "server-token";
|
|
4517
|
+
const stored = await Bun.secrets.get({ service: agentService2, name });
|
|
4518
|
+
if (stored) {
|
|
4519
|
+
return stored;
|
|
4520
|
+
}
|
|
4521
|
+
const token = randomBytes3(32).toString("hex");
|
|
4522
|
+
await Bun.secrets.set({ service: agentService2, name, value: token });
|
|
4523
|
+
return token;
|
|
4524
|
+
};
|
|
4525
|
+
|
|
4526
|
+
// packages/agent/src/service.ts
|
|
4527
|
+
var supervisedEnv2 = "TSPLC_AGENT_SUPERVISED";
|
|
4528
|
+
|
|
4529
|
+
// packages/agent/src/state.ts
|
|
4530
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
4531
|
+
import { renameSync as renameSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
4532
|
+
import { mkdir as mkdir5, readFile as readFile6 } from "node:fs/promises";
|
|
4533
|
+
import { join as join9 } from "node:path";
|
|
4534
|
+
import { z as z18 } from "zod";
|
|
4535
|
+
var readTextIfPresent2 = (path) => readFile6(path, "utf8").catch((error) => {
|
|
4536
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
4537
|
+
return null;
|
|
4538
|
+
}
|
|
4539
|
+
throw error;
|
|
4540
|
+
});
|
|
4541
|
+
var readJsonFile2 = async (path, schema) => {
|
|
4542
|
+
const text = await readTextIfPresent2(path);
|
|
4543
|
+
return text === null ? null : schema.parse(JSON.parse(text));
|
|
4544
|
+
};
|
|
4545
|
+
var writeJsonFile2 = (path, value) => {
|
|
4546
|
+
const temporary = `${path}.${randomUUID2()}.tmp`;
|
|
4547
|
+
writeFileSync2(temporary, JSON.stringify(value, null, 2));
|
|
4548
|
+
renameSync3(temporary, path);
|
|
4549
|
+
};
|
|
4550
|
+
var statePaths2 = (directory) => ({
|
|
4551
|
+
releases: join9(directory, "releases"),
|
|
4552
|
+
controller: join9(directory, "controller"),
|
|
4553
|
+
sources: join9(directory, "sources"),
|
|
4554
|
+
release: join9(directory, "release.json"),
|
|
4555
|
+
target: join9(directory, "target.json"),
|
|
4556
|
+
deployments: join9(directory, "deployments.jsonl"),
|
|
4557
|
+
deploymentRecords: join9(directory, "deployments"),
|
|
4558
|
+
audit: join9(directory, "audit.jsonl"),
|
|
4559
|
+
access: join9(directory, "access.json"),
|
|
4560
|
+
environment: join9(directory, "environment.json"),
|
|
4561
|
+
variables: join9(directory, "variables.json"),
|
|
4562
|
+
debug: join9(directory, "debug"),
|
|
4563
|
+
server: join9(directory, "server.json"),
|
|
4564
|
+
agent: join9(directory, "agent.json"),
|
|
4565
|
+
logs: join9(directory, "logs"),
|
|
4566
|
+
serverLog: join9(directory, "logs", "server.log"),
|
|
4567
|
+
agentLog: join9(directory, "logs", "agent.log")
|
|
4568
|
+
});
|
|
4569
|
+
var openState2 = async (directory) => {
|
|
4570
|
+
const paths = statePaths2(directory);
|
|
4571
|
+
await mkdir5(paths.logs, { recursive: true });
|
|
4572
|
+
const target = () => readJsonFile2(paths.target, targetSchema);
|
|
4573
|
+
const release = () => readJsonFile2(paths.release, releaseSchema);
|
|
4574
|
+
return {
|
|
4575
|
+
paths,
|
|
4576
|
+
target,
|
|
4577
|
+
setTarget: async (selected) => writeJsonFile2(paths.target, selected),
|
|
4578
|
+
requireTarget: async () => {
|
|
4579
|
+
const selected = await target();
|
|
4580
|
+
if (!selected) {
|
|
4581
|
+
throw new AgentError("Select the controller first: tsplc target", 409);
|
|
4582
|
+
}
|
|
4583
|
+
return selected;
|
|
4584
|
+
},
|
|
4585
|
+
release,
|
|
4586
|
+
setRelease: async (deployed) => writeJsonFile2(paths.release, deployed),
|
|
4587
|
+
requireRelease: async () => {
|
|
4588
|
+
const deployed = await release();
|
|
4589
|
+
if (!deployed) {
|
|
4590
|
+
throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
|
|
4591
|
+
}
|
|
4592
|
+
return loadRelease(paths.releases, deployed.id);
|
|
4593
|
+
}
|
|
4594
|
+
};
|
|
4595
|
+
};
|
|
4596
|
+
|
|
4597
|
+
// packages/agent/src/terminal.ts
|
|
4598
|
+
import { createInterface } from "node:readline/promises";
|
|
4599
|
+
var ask = async (question) => {
|
|
4600
|
+
const lines = createInterface({
|
|
4601
|
+
input: process.stdin,
|
|
4602
|
+
output: process.stdout
|
|
4603
|
+
});
|
|
4604
|
+
try {
|
|
4605
|
+
return (await lines.question(question)).trim();
|
|
4606
|
+
} finally {
|
|
4607
|
+
lines.close();
|
|
4608
|
+
}
|
|
4609
|
+
};
|
|
4610
|
+
var askSecret = (question) => new Promise((accept, reject) => {
|
|
4611
|
+
if (!process.stdin.isTTY) {
|
|
4612
|
+
reject(new Error("Typing a secret needs an interactive terminal."));
|
|
4613
|
+
return;
|
|
4614
|
+
}
|
|
4615
|
+
process.stdin.setRawMode(true);
|
|
4616
|
+
process.stdin.setEncoding("utf8");
|
|
4617
|
+
process.stdin.resume();
|
|
4618
|
+
process.stdout.write(question);
|
|
4619
|
+
let secret = "";
|
|
4620
|
+
const finish = () => {
|
|
4621
|
+
process.stdin.off("data", read);
|
|
4622
|
+
process.stdin.setRawMode(false);
|
|
4623
|
+
process.stdin.pause();
|
|
4624
|
+
process.stdout.write(`
|
|
4625
|
+
`);
|
|
4626
|
+
};
|
|
4627
|
+
const read = (text) => {
|
|
4628
|
+
for (const character of text) {
|
|
4629
|
+
if (character === "\r" || character === `
|
|
4630
|
+
`) {
|
|
4631
|
+
finish();
|
|
4632
|
+
accept(secret);
|
|
4633
|
+
return;
|
|
4634
|
+
}
|
|
4635
|
+
if (character === "\x03") {
|
|
4636
|
+
finish();
|
|
4637
|
+
reject(new Error("Cancelled."));
|
|
4638
|
+
return;
|
|
4639
|
+
}
|
|
4640
|
+
secret = character === "" ? secret.slice(0, -1) : secret + character;
|
|
4641
|
+
}
|
|
4642
|
+
};
|
|
4643
|
+
process.stdin.on("data", read);
|
|
4644
|
+
});
|
|
4645
|
+
var askCredentials = async () => ({
|
|
4646
|
+
username: await ask("Controller username: "),
|
|
4647
|
+
password: await askSecret("Controller password: ")
|
|
4648
|
+
});
|
|
4649
|
+
|
|
4650
|
+
// packages/agent/src/upgrade.ts
|
|
4651
|
+
import { z as z19 } from "zod";
|
|
4652
|
+
var versionSchema2 = z19.string().regex(/^[0-9A-Za-z][0-9A-Za-z.+-]*$/, "Name a version, such as 0.5.0, or a dist-tag, such as latest");
|
|
4653
|
+
|
|
4654
|
+
// packages/agent/src/cli.ts
|
|
4655
|
+
var usage = `tsplc-agent setup [--if-needed]
|
|
4656
|
+
tsplc-agent serve --listen host:port [--state directory] [--server-health url] [--bulk-import]
|
|
4657
|
+
tsplc-agent upgrade [version] [--state directory]
|
|
4658
|
+
tsplc-agent service install|uninstall|status [serve options] [--stop-server]
|
|
4659
|
+
tsplc-agent secrets set|delete <name> [--service ${agentService2}]
|
|
4660
|
+
tsplc-agent secrets set-controller
|
|
4661
|
+
tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none> [--state directory]
|
|
4662
|
+
|
|
4663
|
+
setup Builds the CODESYS builder and gateway images, keeping each that is already right for
|
|
4664
|
+
this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so
|
|
4665
|
+
only a release that changes the image's recipe (the CODESYS installation, Bun or the
|
|
4666
|
+
container's third-party packages) needs it; the agent says so when it does. --if-needed
|
|
4667
|
+
also keeps an image from before tsPLC 0.5.0 whose packages match.
|
|
4668
|
+
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
4669
|
+
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
4670
|
+
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
4671
|
+
TSPLC_AGENT_READ_TOKEN, as long, only reads: the debugger at /debug, GET /status
|
|
4672
|
+
and the dashboard.
|
|
4673
|
+
Each comes from its environment variable, or else from \`secrets set\` under ${agentService2}.
|
|
4674
|
+
--bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
|
|
4675
|
+
in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
|
|
4676
|
+
The line's server writes to logs/server.log in the state directory.
|
|
4677
|
+
upgrade Installs @tsplc/agent at version (latest by default) with the bun or npm that installed
|
|
4678
|
+
this one, runs its setup if it needs one, and restarts the running agent on it. It
|
|
4679
|
+
refuses while a deployment runs or a login is open, and leaves the line's server running
|
|
4680
|
+
and the controller untouched.
|
|
4681
|
+
service Runs the agent as a Windows service: a Task Scheduler task that starts it at boot as
|
|
4682
|
+
you, whether or not anyone logs on, and starts it again if it exits. install takes the
|
|
4683
|
+
serve options and asks for your Windows password; run install and uninstall in a
|
|
4684
|
+
PowerShell opened with Run as administrator, signed in as the user the agent runs as.
|
|
4685
|
+
The agent's output goes to logs/agent.log in the state directory. uninstall leaves the
|
|
4686
|
+
line's server running unless --stop-server.
|
|
4687
|
+
secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
|
|
4688
|
+
--service, or deletes it. set-controller stores the controller user, which deployments
|
|
4689
|
+
and logins then use when they send none. Run it as the user the agent runs as.
|
|
4690
|
+
access Who on the tailnet may use the dashboard, by Tailscale login: viewer reads, deployer
|
|
4691
|
+
also deploys and restarts the server, admin also manages variables and access. default
|
|
4692
|
+
gives every other tailnet member a role, none by default. The full token is an admin,
|
|
4693
|
+
the read token a viewer, and a request from this PC an admin. The agent applies a
|
|
4694
|
+
change at once.`;
|
|
4695
|
+
var { values, positionals } = parseArgs({
|
|
4696
|
+
allowPositionals: true,
|
|
4697
|
+
options: {
|
|
4698
|
+
help: { type: "boolean", short: "h" },
|
|
4699
|
+
listen: { type: "string" },
|
|
4700
|
+
state: { type: "string" },
|
|
4701
|
+
"server-health": { type: "string" },
|
|
4702
|
+
"bulk-import": { type: "boolean" },
|
|
4703
|
+
service: { type: "string" },
|
|
4704
|
+
"if-needed": { type: "boolean" },
|
|
4705
|
+
"stop-server": { type: "boolean" }
|
|
4706
|
+
}
|
|
4707
|
+
});
|
|
4708
|
+
var [command, ...args] = positionals;
|
|
4709
|
+
if (!command || values.help) {
|
|
4710
|
+
console.log(usage);
|
|
4711
|
+
process.exit(0);
|
|
4712
|
+
}
|
|
4713
|
+
var takesArguments = {
|
|
4714
|
+
secrets: 3,
|
|
4715
|
+
access: 3,
|
|
4716
|
+
upgrade: 1,
|
|
4717
|
+
service: 1
|
|
4718
|
+
};
|
|
4719
|
+
if (args.length > (takesArguments[command] ?? 0)) {
|
|
4720
|
+
throw new Error(`Too many arguments for ${command}. See tsplc-agent --help.`);
|
|
4721
|
+
}
|
|
4722
|
+
var stateDirectory = values.state ?? join10(homedir2(), ".tsplc-agent");
|
|
4723
|
+
var loopbackFor = {
|
|
4724
|
+
"0.0.0.0": "127.0.0.1",
|
|
4725
|
+
"::": "::1"
|
|
4726
|
+
};
|
|
4727
|
+
var reachableUrl = (hostname, port) => {
|
|
4728
|
+
const bare = hostname.replace(/^\[(.*)\]$/, "$1");
|
|
4729
|
+
const host = loopbackFor[bare] ?? bare;
|
|
4730
|
+
return `http://${host.includes(":") ? `[${host}]` : host}:${port}/`;
|
|
4731
|
+
};
|
|
4732
|
+
var serveOptions = () => {
|
|
4733
|
+
const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
|
|
4734
|
+
const port = tcpPort3.safeParse(Number(portText));
|
|
4735
|
+
if (!hostname || !port.success) {
|
|
4736
|
+
throw new Error("--listen host:port is required, with a TCP port.");
|
|
4737
|
+
}
|
|
4738
|
+
return {
|
|
4739
|
+
hostname,
|
|
4740
|
+
port: port.data,
|
|
4741
|
+
args: [
|
|
4742
|
+
"--listen",
|
|
4743
|
+
`${hostname}:${port.data}`,
|
|
4744
|
+
...values.state ? ["--state", values.state] : [],
|
|
4745
|
+
...values["server-health"] ? ["--server-health", values["server-health"]] : [],
|
|
4746
|
+
...values["bulk-import"] ? ["--bulk-import"] : []
|
|
4747
|
+
]
|
|
4748
|
+
};
|
|
4749
|
+
};
|
|
4750
|
+
if (command === "setup") {
|
|
4751
|
+
await configureDocker({
|
|
4752
|
+
keepUnverified: values["if-needed"] ?? false,
|
|
4753
|
+
winetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null
|
|
4754
|
+
});
|
|
4755
|
+
await configureGateway();
|
|
4756
|
+
} else if (command === "serve") {
|
|
4757
|
+
const { hostname, port, args: serve } = serveOptions();
|
|
4758
|
+
const token = z20.string({
|
|
4759
|
+
error: `Set ${agentTokenEnv2}, or store it with tsplc-agent secrets set ${agentTokenEnv2}`
|
|
4760
|
+
}).min(32, `${agentTokenEnv2} must be at least 32 characters`).parse(await agentSetting2(agentTokenEnv2, process.env));
|
|
4761
|
+
const readToken = z20.string().min(32, `${agentReadTokenEnv} must be at least 32 characters`).refine((value) => value !== token, `${agentReadTokenEnv} must differ from ${agentTokenEnv2}`).nullable().parse(await agentSetting2(agentReadTokenEnv, process.env));
|
|
4762
|
+
const { paths } = await openState2(stateDirectory);
|
|
4763
|
+
const agent = await createAgent({
|
|
4764
|
+
state: stateDirectory,
|
|
4765
|
+
token,
|
|
4766
|
+
readToken,
|
|
4767
|
+
serverHealthUrl: values["server-health"] ?? null,
|
|
4768
|
+
bulkImport: values["bulk-import"] ?? false,
|
|
4769
|
+
environment: process.env,
|
|
4770
|
+
serverAccess: {
|
|
4771
|
+
url: reachableUrl(hostname, port),
|
|
4772
|
+
token: await serverToken()
|
|
4773
|
+
},
|
|
4774
|
+
log: (message) => console.log(`${new Date().toISOString()} ${message}`),
|
|
4775
|
+
exit: ({ restart }) => {
|
|
4776
|
+
removeInstance(paths.agent, process.pid).then(() => process.exit(restart ? restartStatus : 0));
|
|
4777
|
+
}
|
|
4778
|
+
});
|
|
4779
|
+
const server = Bun.serve({
|
|
4780
|
+
hostname,
|
|
4781
|
+
port,
|
|
4782
|
+
fetch: (request, server) => agent.fetch(request, server.requestIP(request)),
|
|
4783
|
+
idleTimeout: 0,
|
|
4784
|
+
maxRequestBodySize: 2 ** 30
|
|
4785
|
+
});
|
|
4786
|
+
writeJsonFile2(paths.agent, {
|
|
4787
|
+
pid: process.pid,
|
|
4788
|
+
version: tsplcVersion2,
|
|
4789
|
+
url: server.url.href,
|
|
4790
|
+
serve,
|
|
4791
|
+
supervised: process.env[supervisedEnv2] === "1",
|
|
4792
|
+
startedAt: new Date().toISOString()
|
|
4793
|
+
});
|
|
4794
|
+
console.log(`tsPLC agent ${tsplcVersion2} listening on ${server.url}`);
|
|
4795
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
4796
|
+
process.on(signal, () => {
|
|
4797
|
+
agent.stop().then(() => removeInstance(paths.agent, process.pid)).then(() => process.exit(0));
|
|
4798
|
+
});
|
|
4799
|
+
}
|
|
4800
|
+
} else if (command === "upgrade") {
|
|
4801
|
+
await upgradeCommand({
|
|
4802
|
+
version: versionSchema2.parse(args[0] ?? "latest"),
|
|
4803
|
+
state: stateDirectory,
|
|
4804
|
+
environment: process.env
|
|
4805
|
+
});
|
|
4806
|
+
} else if (command === "service") {
|
|
4807
|
+
const action = args[0];
|
|
4808
|
+
await serviceCommand({
|
|
4809
|
+
action,
|
|
4810
|
+
state: stateDirectory,
|
|
4811
|
+
serve: action === "install" || action === "run" ? serveOptions().args : [],
|
|
4812
|
+
stopServer: values["stop-server"] ?? false,
|
|
4813
|
+
environment: process.env
|
|
4814
|
+
});
|
|
4815
|
+
} else if (command === "secrets") {
|
|
4816
|
+
const [action, name, ...extra] = args;
|
|
4817
|
+
const service = values.service ?? agentService2;
|
|
4818
|
+
if (action === "set" && name && !extra.length) {
|
|
4819
|
+
await Bun.secrets.set({
|
|
4820
|
+
service,
|
|
4821
|
+
name,
|
|
4822
|
+
value: await askSecret(`${name}: `)
|
|
4823
|
+
});
|
|
4824
|
+
} else if (action === "delete" && name && !extra.length) {
|
|
4825
|
+
if (!await Bun.secrets.delete({ service, name })) {
|
|
4826
|
+
throw new Error(`Service ${service} has no ${name}.`);
|
|
4827
|
+
}
|
|
4828
|
+
} else if (action === "set-controller" && !name) {
|
|
4829
|
+
const { username, password } = await askCredentials();
|
|
4830
|
+
await Bun.secrets.set({
|
|
4831
|
+
service: agentService2,
|
|
4832
|
+
name: controllerSecretNames2.username,
|
|
4833
|
+
value: username
|
|
4834
|
+
});
|
|
4835
|
+
await Bun.secrets.set({
|
|
4836
|
+
service: agentService2,
|
|
4837
|
+
name: controllerSecretNames2.password,
|
|
4838
|
+
value: password
|
|
4839
|
+
});
|
|
4840
|
+
} else {
|
|
4841
|
+
throw new Error("Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller");
|
|
4842
|
+
}
|
|
4843
|
+
} else if (command === "access") {
|
|
4844
|
+
const file = statePaths2(stateDirectory).access;
|
|
4845
|
+
const config = await readAccessConfig(file);
|
|
4846
|
+
const [action, first, second, ...extra] = args;
|
|
4847
|
+
const change = (() => {
|
|
4848
|
+
if (action === "grant" && first && second && !extra.length) {
|
|
4849
|
+
return {
|
|
4850
|
+
...config,
|
|
4851
|
+
roles: { ...config.roles, [first]: roleSchema2.parse(second) }
|
|
4852
|
+
};
|
|
4853
|
+
}
|
|
4854
|
+
if (action === "revoke" && first && !second) {
|
|
4855
|
+
if (!(first in config.roles)) {
|
|
4856
|
+
throw new Error(`${first} has no role.`);
|
|
4857
|
+
}
|
|
4858
|
+
return {
|
|
4859
|
+
...config,
|
|
4860
|
+
roles: Object.fromEntries(Object.entries(config.roles).filter(([login]) => login !== first))
|
|
4861
|
+
};
|
|
4862
|
+
}
|
|
4863
|
+
if (action === "default" && first && !second) {
|
|
4864
|
+
return {
|
|
4865
|
+
...config,
|
|
4866
|
+
tailnetDefault: first === "none" ? null : roleSchema2.parse(first)
|
|
4867
|
+
};
|
|
4868
|
+
}
|
|
4869
|
+
if (action === "list" && !first) {
|
|
4870
|
+
return null;
|
|
4871
|
+
}
|
|
4872
|
+
throw new Error("Usage: tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none>");
|
|
4873
|
+
})();
|
|
4874
|
+
if (change) {
|
|
4875
|
+
await mkdir6(stateDirectory, { recursive: true });
|
|
4876
|
+
writeJsonFile2(file, change);
|
|
4877
|
+
}
|
|
4878
|
+
const shown = change ?? config;
|
|
4879
|
+
for (const [login, role] of Object.entries(shown.roles)) {
|
|
4880
|
+
console.log(`${login} ${role}`);
|
|
4881
|
+
}
|
|
4882
|
+
console.log(`Other tailnet members: ${shown.tailnetDefault ?? "none"}`);
|
|
4883
|
+
} else {
|
|
4884
|
+
throw new Error(`Unknown command ${command}.`);
|
|
4885
|
+
}
|
|
4886
|
+
|
|
4887
|
+
//# debugId=27C9EBB22D54A6B464756E2164756E21
|
|
4888
|
+
//# sourceMappingURL=cli.js.map
|