@tsplc/agent 0.5.8 → 0.5.10
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/dist/cli.js +2462 -533
- package/dist/cli.js.map +30 -17
- package/dist/client.js +238 -36
- package/dist/client.js.map +4 -4
- package/dist/index.js +2162 -416
- package/dist/index.js.map +25 -13
- package/package.json +5 -5
- package/src/access.ts +257 -0
- package/src/agent.ts +101 -29
- package/src/audit.ts +64 -0
- package/src/cli.ts +58 -4
- package/src/client.ts +181 -36
- package/src/dashboard/index.ts +116 -0
- package/src/dashboard/ui/access.ts +192 -0
- package/src/dashboard/ui/actions.ts +142 -0
- package/src/dashboard/ui/api.ts +147 -0
- package/src/dashboard/ui/app.ts +41 -0
- package/src/dashboard/ui/approval.ts +132 -0
- package/src/dashboard/ui/audit.ts +115 -0
- package/src/dashboard/ui/contract.ts +16 -0
- package/src/dashboard/ui/dashboard.css +1332 -0
- package/src/dashboard/ui/deployment.ts +432 -0
- package/src/dashboard/ui/deployments.ts +317 -0
- package/src/dashboard/ui/details.ts +240 -0
- package/src/dashboard/ui/dom.ts +91 -0
- package/src/dashboard/ui/environment.ts +224 -0
- package/src/dashboard/ui/format.ts +118 -0
- package/src/dashboard/ui/logs.ts +127 -0
- package/src/dashboard/ui/main.ts +86 -0
- package/src/dashboard/ui/overlay.ts +146 -0
- package/src/dashboard/ui/shell.ts +171 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/deploy.ts +138 -144
- package/src/deployments/health.ts +80 -0
- package/src/deployments/retention.ts +45 -0
- package/src/deployments/routes.ts +273 -0
- package/src/deployments/runner.ts +877 -0
- package/src/deployments/store.ts +233 -0
- package/src/environment.ts +205 -0
- package/src/index.ts +4 -0
- package/src/operations.ts +5 -1
- package/src/protocol.ts +218 -2
- package/src/releases.ts +73 -1
- package/src/routes.ts +52 -0
- package/src/secrets.ts +43 -2
- package/src/server-process.ts +33 -16
- package/src/sessions.ts +58 -0
- package/src/state.ts +2 -0
- package/src/tailscale.ts +112 -0
package/dist/index.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
1
|
// packages/agent/src/agent.ts
|
|
2
|
-
import {
|
|
3
|
-
import { join as join7 } from "node:path";
|
|
2
|
+
import { join as join10 } from "node:path";
|
|
4
3
|
import { loginCommandSchema } from "@tsplc/build";
|
|
5
|
-
import { z as
|
|
4
|
+
import { z as z10 } from "zod";
|
|
6
5
|
|
|
7
|
-
// packages/agent/src/
|
|
6
|
+
// packages/agent/src/access.ts
|
|
7
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
10
|
+
import { isIP as isIP2 } from "node:net";
|
|
8
11
|
import { join } from "node:path";
|
|
9
|
-
import {
|
|
10
|
-
builderImageStatus,
|
|
11
|
-
captureDocker,
|
|
12
|
-
gatewayImage,
|
|
13
|
-
setupReason
|
|
14
|
-
} from "@tsplc/build";
|
|
15
|
-
import { resolveConfig } from "@tsplc/config/build";
|
|
12
|
+
import { dashboardHeader } from "@tsplc/debug/api";
|
|
16
13
|
|
|
17
14
|
// packages/agent/src/errors.ts
|
|
18
15
|
class AgentError extends Error {
|
|
@@ -26,139 +23,13 @@ class AgentError extends Error {
|
|
|
26
23
|
}
|
|
27
24
|
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
28
25
|
|
|
29
|
-
// packages/agent/src/codesys.ts
|
|
30
|
-
var network = "tsplc-agent";
|
|
31
|
-
var codesysNetwork = "tsplc-agent-codesys";
|
|
32
|
-
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
33
|
-
var loginContainer = "tsplc-agent-login";
|
|
34
|
-
var deployContainer = "tsplc-agent-deploy";
|
|
35
|
-
var agentDockerResources = {
|
|
36
|
-
containers: [gateway.host, deployContainer, loginContainer],
|
|
37
|
-
networks: [network, codesysNetwork]
|
|
38
|
-
};
|
|
39
|
-
var credentialNames = {
|
|
40
|
-
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
41
|
-
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
42
|
-
};
|
|
43
|
-
var dockerTimeout = 60000;
|
|
44
|
-
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
45
|
-
var ensureNetwork = async (name, ...options) => {
|
|
46
|
-
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
47
|
-
await docker("network", "create", ...options, name);
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
var setupNeeded = async () => {
|
|
51
|
-
const status = await builderImageStatus();
|
|
52
|
-
const reason = setupReason(status) ?? (await docker("image", "ls", "--quiet", gatewayImage) ? null : `the CODESYS gateway image ${gatewayImage} is missing`);
|
|
53
|
-
return { status, reason };
|
|
54
|
-
};
|
|
55
|
-
var requireBuilder = async () => {
|
|
56
|
-
const { status, reason } = await setupNeeded().catch((cause) => {
|
|
57
|
-
throw new AgentError(`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`, 503);
|
|
58
|
-
});
|
|
59
|
-
if (reason) {
|
|
60
|
-
throw new AgentError(`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`, 409);
|
|
61
|
-
}
|
|
62
|
-
return status;
|
|
63
|
-
};
|
|
64
|
-
var describeBuilder = async () => {
|
|
65
|
-
const { status, reason } = await setupNeeded();
|
|
66
|
-
if (reason) {
|
|
67
|
-
return `Deployments and logins need tsplc-agent setup first: ${reason}`;
|
|
68
|
-
}
|
|
69
|
-
if (status.kind === "unverified") {
|
|
70
|
-
return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
|
|
71
|
-
}
|
|
72
|
-
return "The CODESYS images match this tsPLC";
|
|
73
|
-
};
|
|
74
|
-
var removeContainer = (name) => docker("rm", "--force", name);
|
|
75
|
-
var ensureGateway = async () => {
|
|
76
|
-
await ensureNetwork(network);
|
|
77
|
-
await ensureNetwork(codesysNetwork, "--internal");
|
|
78
|
-
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
79
|
-
await docker("rm", "--force", gateway.host);
|
|
80
|
-
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
81
|
-
}
|
|
82
|
-
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
83
|
-
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
84
|
-
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
var credentialEnvironment = (credentials) => ({
|
|
88
|
-
[credentialNames.usernameEnv]: credentials.username,
|
|
89
|
-
[credentialNames.passwordEnv]: credentials.password
|
|
90
|
-
});
|
|
91
|
-
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
92
|
-
...resolveConfig({
|
|
93
|
-
...release.manifest.config,
|
|
94
|
-
...settings.bulkImport && { bulkImport: true },
|
|
95
|
-
online: {
|
|
96
|
-
network: codesysNetwork,
|
|
97
|
-
gateway,
|
|
98
|
-
device: target,
|
|
99
|
-
credentials: credentialNames
|
|
100
|
-
}
|
|
101
|
-
}, join(release.directory, "manifest.json")),
|
|
102
|
-
outDir: controllerDirectory
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
// packages/agent/src/debugging.ts
|
|
106
|
-
import { existsSync as existsSync3 } from "node:fs";
|
|
107
|
-
import { join as join4 } from "node:path";
|
|
108
|
-
import {
|
|
109
|
-
createDebugger,
|
|
110
|
-
createDebugHandler,
|
|
111
|
-
createLoginAdapter,
|
|
112
|
-
loadExplanations,
|
|
113
|
-
loadManifest,
|
|
114
|
-
timelineEntries
|
|
115
|
-
} from "@tsplc/debug";
|
|
116
|
-
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
117
|
-
|
|
118
|
-
// packages/agent/src/logs.ts
|
|
119
|
-
import { existsSync } from "node:fs";
|
|
120
|
-
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
121
|
-
var rotateBytes = 5 * 2 ** 20;
|
|
122
|
-
var appendJsonl = async (file, value) => {
|
|
123
|
-
if (existsSync(file) && (await stat(file)).size >= rotateBytes) {
|
|
124
|
-
await rename(file, `${file}.1`);
|
|
125
|
-
}
|
|
126
|
-
const log = await open(file, "a+");
|
|
127
|
-
try {
|
|
128
|
-
const { size } = await log.stat();
|
|
129
|
-
const last = Buffer.alloc(1);
|
|
130
|
-
if (size) {
|
|
131
|
-
await log.read(last, 0, 1, size - 1);
|
|
132
|
-
}
|
|
133
|
-
const separator = size && last[0] !== 10 ? `
|
|
134
|
-
` : "";
|
|
135
|
-
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
136
|
-
`);
|
|
137
|
-
} finally {
|
|
138
|
-
await log.close();
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
var readJsonl = async (file, schema, limit) => {
|
|
142
|
-
if (!existsSync(file)) {
|
|
143
|
-
return [];
|
|
144
|
-
}
|
|
145
|
-
return (await readFile(file, "utf8")).split(`
|
|
146
|
-
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
147
|
-
try {
|
|
148
|
-
return [schema.parse(JSON.parse(line))];
|
|
149
|
-
} catch {
|
|
150
|
-
return [];
|
|
151
|
-
}
|
|
152
|
-
});
|
|
153
|
-
};
|
|
154
|
-
|
|
155
26
|
// packages/agent/src/protocol.ts
|
|
156
|
-
import { rollbackSchema } from "@tsplc/build";
|
|
157
|
-
import { tsplcConfigSchema } from "@tsplc/config";
|
|
27
|
+
import { onlineChangeFindingSchema, rollbackSchema } from "@tsplc/build";
|
|
28
|
+
import { secretValue, tsplcConfigSchema } from "@tsplc/config";
|
|
158
29
|
import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
|
|
159
30
|
import { z } from "zod";
|
|
160
31
|
// packages/agent/package.json
|
|
161
|
-
var version = "0.5.
|
|
32
|
+
var version = "0.5.10";
|
|
162
33
|
|
|
163
34
|
// packages/agent/src/protocol.ts
|
|
164
35
|
var tsplcVersion = version;
|
|
@@ -205,7 +76,8 @@ var uploadEncoding = "gzip";
|
|
|
205
76
|
var deployOptionsSchema = z.strictObject({
|
|
206
77
|
credentials: credentialsSchema.nullable(),
|
|
207
78
|
download: z.boolean(),
|
|
208
|
-
initializeUser: z.boolean()
|
|
79
|
+
initializeUser: z.boolean(),
|
|
80
|
+
deployment: z.lazy(() => deploymentRequestSchema).optional()
|
|
209
81
|
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
210
82
|
var releaseBuckets = 256;
|
|
211
83
|
var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
|
|
@@ -292,27 +164,663 @@ var auditSchema = z.strictObject({
|
|
|
292
164
|
release: z.string().optional(),
|
|
293
165
|
error: z.string().optional()
|
|
294
166
|
});
|
|
167
|
+
var roles = ["viewer", "deployer", "admin"];
|
|
168
|
+
var roleSchema = z.enum(roles);
|
|
169
|
+
var allows = (role, required) => roles.indexOf(role) >= roles.indexOf(required);
|
|
170
|
+
var identitySchema = z.strictObject({
|
|
171
|
+
login: z.string().nullable(),
|
|
172
|
+
name: z.string(),
|
|
173
|
+
role: roleSchema,
|
|
174
|
+
via: z.enum(["tailscale", "token", "local"])
|
|
175
|
+
});
|
|
176
|
+
var gitSourceSchema = z.strictObject({
|
|
177
|
+
commit: z.string().nonempty(),
|
|
178
|
+
branch: z.string().nullable(),
|
|
179
|
+
dirty: z.boolean(),
|
|
180
|
+
message: z.string().nullable()
|
|
181
|
+
});
|
|
182
|
+
var deploymentModeSchema = z.enum(["apply", "review"]);
|
|
183
|
+
var deploymentStateSchema = z.enum([
|
|
184
|
+
"queued",
|
|
185
|
+
"building",
|
|
186
|
+
"awaitingApproval",
|
|
187
|
+
"applying",
|
|
188
|
+
"starting",
|
|
189
|
+
"verifying",
|
|
190
|
+
"ready",
|
|
191
|
+
"error",
|
|
192
|
+
"canceled"
|
|
193
|
+
]);
|
|
194
|
+
var deploymentPhaseNameSchema = z.enum([
|
|
195
|
+
"queue",
|
|
196
|
+
"build",
|
|
197
|
+
"review",
|
|
198
|
+
"apply",
|
|
199
|
+
"server",
|
|
200
|
+
"health"
|
|
201
|
+
]);
|
|
202
|
+
var deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
|
|
203
|
+
var deploymentRecordSchema = z.strictObject({
|
|
204
|
+
id: deploymentIdSchema,
|
|
205
|
+
release: z.string(),
|
|
206
|
+
build: z.string().nullable(),
|
|
207
|
+
createdAt: z.iso.datetime(),
|
|
208
|
+
updatedAt: z.iso.datetime(),
|
|
209
|
+
origin: z.discriminatedUnion("kind", [
|
|
210
|
+
z.strictObject({ kind: z.literal("upload") }),
|
|
211
|
+
z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
|
|
212
|
+
z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema })
|
|
213
|
+
]),
|
|
214
|
+
git: gitSourceSchema.nullable(),
|
|
215
|
+
requestedBy: z.strictObject({
|
|
216
|
+
identity: identitySchema.omit({ role: true }),
|
|
217
|
+
user: z.string().nullable(),
|
|
218
|
+
host: z.string().nullable()
|
|
219
|
+
}),
|
|
220
|
+
mode: deploymentModeSchema,
|
|
221
|
+
operation: deployOperationSchema,
|
|
222
|
+
state: deploymentStateSchema,
|
|
223
|
+
phases: z.array(z.strictObject({
|
|
224
|
+
name: deploymentPhaseNameSchema,
|
|
225
|
+
startedAt: z.iso.datetime(),
|
|
226
|
+
finishedAt: z.iso.datetime().nullable(),
|
|
227
|
+
outcome: z.enum(["running", "ok", "failed", "skipped"])
|
|
228
|
+
})),
|
|
229
|
+
findings: z.array(onlineChangeFindingSchema),
|
|
230
|
+
approval: z.strictObject({
|
|
231
|
+
reason: z.enum(["review", "downloadRequired"]),
|
|
232
|
+
message: z.string()
|
|
233
|
+
}).nullable(),
|
|
234
|
+
error: z.strictObject({
|
|
235
|
+
message: z.string(),
|
|
236
|
+
downloadRequired: z.boolean(),
|
|
237
|
+
rollback: rollbackSchema.optional()
|
|
238
|
+
}).nullable(),
|
|
239
|
+
controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }).nullable(),
|
|
240
|
+
health: z.strictObject({
|
|
241
|
+
controller: z.enum(["ok", "failed"]),
|
|
242
|
+
server: z.enum(["ok", "failed", "none"]),
|
|
243
|
+
plc: z.enum(["ok", "failed", "unknown"]),
|
|
244
|
+
detail: z.string().nullable()
|
|
245
|
+
}).nullable(),
|
|
246
|
+
activeFrom: z.iso.datetime().nullable(),
|
|
247
|
+
activeUntil: z.iso.datetime().nullable()
|
|
248
|
+
});
|
|
249
|
+
var deploymentLogLineSchema = z.strictObject({
|
|
250
|
+
seq: z.number().int().positive(),
|
|
251
|
+
at: z.iso.datetime(),
|
|
252
|
+
level: z.enum(["info", "warning", "error"]),
|
|
253
|
+
phase: deploymentPhaseNameSchema.nullable(),
|
|
254
|
+
message: z.string()
|
|
255
|
+
});
|
|
256
|
+
var deploymentRequestSchema = z.strictObject({
|
|
257
|
+
mode: deploymentModeSchema,
|
|
258
|
+
git: gitSourceSchema.nullable()
|
|
259
|
+
});
|
|
260
|
+
var deploymentCreatedSchema = z.strictObject({
|
|
261
|
+
id: deploymentIdSchema,
|
|
262
|
+
url: z.string()
|
|
263
|
+
});
|
|
264
|
+
var deploymentListSchema = z.strictObject({
|
|
265
|
+
deployments: z.array(deploymentRecordSchema),
|
|
266
|
+
current: deploymentIdSchema.nullable(),
|
|
267
|
+
lastGood: deploymentIdSchema.nullable()
|
|
268
|
+
});
|
|
269
|
+
var approveSchema = z.strictObject({ download: z.boolean() });
|
|
270
|
+
var redeploySchema = z.strictObject({ mode: deploymentModeSchema });
|
|
271
|
+
var deploymentSourceSchema = z.strictObject({
|
|
272
|
+
files: z.array(z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }))
|
|
273
|
+
});
|
|
274
|
+
var environmentEntrySchema = z.strictObject({
|
|
275
|
+
name: z.string(),
|
|
276
|
+
declared: z.boolean(),
|
|
277
|
+
set: z.boolean()
|
|
278
|
+
});
|
|
279
|
+
var accessConfigSchema = z.strictObject({
|
|
280
|
+
roles: z.record(z.string().nonempty(), roleSchema),
|
|
281
|
+
tailnetDefault: roleSchema.nullable()
|
|
282
|
+
});
|
|
283
|
+
var sessionRequestSchema = z.strictObject({ token: z.string() });
|
|
284
|
+
var environmentValueSchema = z.strictObject({ value: secretValue });
|
|
285
|
+
|
|
286
|
+
// packages/agent/src/sessions.ts
|
|
287
|
+
import { randomBytes } from "node:crypto";
|
|
288
|
+
var sessionCookie = "tsplc_session";
|
|
289
|
+
var sessionLifetimeMs = 12 * 60 * 60 * 1000;
|
|
290
|
+
var createSessions = (now) => {
|
|
291
|
+
const sessions = new Map;
|
|
292
|
+
const sessionId = (request) => new Bun.CookieMap(request.headers.get("cookie") ?? "").get(sessionCookie);
|
|
293
|
+
const cookie = (value, maxAgeMs) => new Bun.Cookie(sessionCookie, value, {
|
|
294
|
+
httpOnly: true,
|
|
295
|
+
sameSite: "strict",
|
|
296
|
+
path: "/",
|
|
297
|
+
maxAge: Math.floor(maxAgeMs / 1000)
|
|
298
|
+
}).serialize();
|
|
299
|
+
return {
|
|
300
|
+
open: (identity) => {
|
|
301
|
+
const time = now();
|
|
302
|
+
for (const [id, { expires }] of sessions) {
|
|
303
|
+
if (expires <= time) {
|
|
304
|
+
sessions.delete(id);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const id = randomBytes(32).toString("base64url");
|
|
308
|
+
sessions.set(id, { identity, expires: time + sessionLifetimeMs });
|
|
309
|
+
return cookie(id, sessionLifetimeMs);
|
|
310
|
+
},
|
|
311
|
+
find: (request) => {
|
|
312
|
+
const id = sessionId(request);
|
|
313
|
+
const session = id === null ? undefined : sessions.get(id);
|
|
314
|
+
if (!session || session.expires <= now()) {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
return session.identity;
|
|
318
|
+
},
|
|
319
|
+
close: (request) => {
|
|
320
|
+
const id = sessionId(request);
|
|
321
|
+
if (id !== null) {
|
|
322
|
+
sessions.delete(id);
|
|
323
|
+
}
|
|
324
|
+
return cookie("", 0);
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
// packages/agent/src/tailscale.ts
|
|
330
|
+
import { BlockList, isIP } from "node:net";
|
|
331
|
+
import { z as z2 } from "zod";
|
|
332
|
+
var tailnet = new BlockList;
|
|
333
|
+
tailnet.addSubnet("100.64.0.0", 10, "ipv4");
|
|
334
|
+
tailnet.addSubnet("fd7a:115c:a1e0::", 48, "ipv6");
|
|
335
|
+
var loopback = new BlockList;
|
|
336
|
+
loopback.addSubnet("127.0.0.0", 8, "ipv4");
|
|
337
|
+
loopback.addAddress("::1", "ipv6");
|
|
338
|
+
var peerKind = (address) => {
|
|
339
|
+
const version = isIP(address);
|
|
340
|
+
if (version === 0) {
|
|
341
|
+
return "other";
|
|
342
|
+
}
|
|
343
|
+
const family = version === 6 ? "ipv6" : "ipv4";
|
|
344
|
+
if (loopback.check(address, family)) {
|
|
345
|
+
return "loopback";
|
|
346
|
+
}
|
|
347
|
+
return tailnet.check(address, family) ? "tailnet" : "other";
|
|
348
|
+
};
|
|
349
|
+
var whoisSchema = z2.object({
|
|
350
|
+
UserProfile: z2.object({
|
|
351
|
+
LoginName: z2.string().nonempty(),
|
|
352
|
+
DisplayName: z2.string()
|
|
353
|
+
})
|
|
354
|
+
});
|
|
355
|
+
var runCommand = async (command) => {
|
|
356
|
+
const child = Bun.spawn(command, {
|
|
357
|
+
stdout: "pipe",
|
|
358
|
+
stderr: "ignore",
|
|
359
|
+
timeout: 5000
|
|
360
|
+
});
|
|
361
|
+
const [stdout, exitCode] = await Promise.all([
|
|
362
|
+
new Response(child.stdout).text(),
|
|
363
|
+
child.exited
|
|
364
|
+
]);
|
|
365
|
+
return { stdout, exitCode };
|
|
366
|
+
};
|
|
367
|
+
var whoisCacheMs = 60000;
|
|
368
|
+
var createWhois = (context) => {
|
|
369
|
+
const cache = new Map;
|
|
370
|
+
const lookUp = async (address) => {
|
|
371
|
+
try {
|
|
372
|
+
const { exitCode, stdout } = await context.run([
|
|
373
|
+
"tailscale",
|
|
374
|
+
"whois",
|
|
375
|
+
"--json",
|
|
376
|
+
address
|
|
377
|
+
]);
|
|
378
|
+
if (exitCode !== 0) {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
const { UserProfile } = whoisSchema.parse(JSON.parse(stdout));
|
|
382
|
+
return {
|
|
383
|
+
login: UserProfile.LoginName,
|
|
384
|
+
name: UserProfile.DisplayName || UserProfile.LoginName
|
|
385
|
+
};
|
|
386
|
+
} catch (error) {
|
|
387
|
+
context.log(`tailscale whois ${address} failed: ${errorMessage(error)}`);
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
return (address) => {
|
|
392
|
+
const now = context.now();
|
|
393
|
+
for (const [cached, { expires }] of cache) {
|
|
394
|
+
if (expires <= now) {
|
|
395
|
+
cache.delete(cached);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const known = cache.get(address);
|
|
399
|
+
if (known) {
|
|
400
|
+
return known.user;
|
|
401
|
+
}
|
|
402
|
+
const user = lookUp(address);
|
|
403
|
+
cache.set(address, { expires: now + whoisCacheMs, user });
|
|
404
|
+
return user;
|
|
405
|
+
};
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
// packages/agent/src/access.ts
|
|
409
|
+
var accessFile = (state) => join(state, "access.json");
|
|
410
|
+
var noAccess = { roles: {}, tailnetDefault: null };
|
|
411
|
+
var readAccessConfig = async (file) => existsSync(file) ? accessConfigSchema.parse(JSON.parse(await readFile(file, "utf8"))) : noAccess;
|
|
412
|
+
var writeAccessConfig = async (file, config) => {
|
|
413
|
+
await writeFile(`${file}.tmp`, JSON.stringify(config, null, 2));
|
|
414
|
+
await rename(`${file}.tmp`, file);
|
|
415
|
+
};
|
|
416
|
+
var matches = (presented, token) => timingSafeEqual(createHash("sha256").update(presented).digest(), createHash("sha256").update(token).digest());
|
|
417
|
+
var refuse = (status, error) => Response.json({ error }, { status });
|
|
418
|
+
var unauthorized = () => refuse(401, "Unauthorized");
|
|
419
|
+
var forwardingHeaders = [
|
|
420
|
+
"forwarded",
|
|
421
|
+
"x-forwarded-for",
|
|
422
|
+
"tailscale-user-login"
|
|
423
|
+
];
|
|
424
|
+
var namesAgentDirectly = (request) => {
|
|
425
|
+
const host = new URL(request.url).hostname.replace(/^\[(.*)\]$/, "$1");
|
|
426
|
+
return isIP2(host) !== 0 || !host.includes(".") || host.endsWith(".ts.net") || host === "localhost";
|
|
427
|
+
};
|
|
428
|
+
var changes = (request) => request.method !== "GET";
|
|
429
|
+
var fromDashboard = (request) => request.headers.get(dashboardHeader) === "1";
|
|
430
|
+
var crossSite = () => refuse(403, `A browser's request that changes something needs the ${dashboardHeader}: 1 header`);
|
|
431
|
+
var createAccess = (options) => {
|
|
432
|
+
const sessions = createSessions(options.now);
|
|
433
|
+
const tokenIdentity = (presented) => {
|
|
434
|
+
if (matches(presented, options.token)) {
|
|
435
|
+
return { login: null, name: "Agent token", role: "admin", via: "token" };
|
|
436
|
+
}
|
|
437
|
+
if (options.readToken !== undefined && matches(presented, options.readToken)) {
|
|
438
|
+
return {
|
|
439
|
+
login: null,
|
|
440
|
+
name: "Read token",
|
|
441
|
+
role: "viewer",
|
|
442
|
+
via: "token"
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
return null;
|
|
446
|
+
};
|
|
447
|
+
const peerIdentity = async (request, peer) => {
|
|
448
|
+
if (!peer || !namesAgentDirectly(request) || forwardingHeaders.some((name) => request.headers.has(name))) {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
const kind = peerKind(peer.address);
|
|
452
|
+
if (kind === "loopback") {
|
|
453
|
+
return { login: null, name: "This PC", role: "admin", via: "local" };
|
|
454
|
+
}
|
|
455
|
+
if (kind !== "tailnet") {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
const user = await options.whois(peer.address);
|
|
459
|
+
if (!user) {
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
const config = await readAccessConfig(options.file).catch((error) => {
|
|
463
|
+
options.log(`Can't read ${options.file}: ${errorMessage(error)}`);
|
|
464
|
+
return noAccess;
|
|
465
|
+
});
|
|
466
|
+
const role = config.roles[user.login] ?? config.tailnetDefault;
|
|
467
|
+
return role && { login: user.login, name: user.name, role, via: "tailscale" };
|
|
468
|
+
};
|
|
469
|
+
const identify = async (request, peer) => {
|
|
470
|
+
const { searchParams, pathname } = new URL(request.url);
|
|
471
|
+
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (pathname.startsWith("/debug/") ? searchParams.get("token") : null);
|
|
472
|
+
if (presented !== null) {
|
|
473
|
+
return tokenIdentity(presented) ?? unauthorized();
|
|
474
|
+
}
|
|
475
|
+
const browserRoute = pathname.startsWith("/api/") || pathname.startsWith("/debug/") || request.method === "GET" && pathname === "/status";
|
|
476
|
+
if (!browserRoute) {
|
|
477
|
+
return unauthorized();
|
|
478
|
+
}
|
|
479
|
+
const identity = sessions.find(request) ?? await peerIdentity(request, peer);
|
|
480
|
+
if (!identity) {
|
|
481
|
+
return unauthorized();
|
|
482
|
+
}
|
|
483
|
+
return changes(request) && !fromDashboard(request) ? crossSite() : identity;
|
|
484
|
+
};
|
|
485
|
+
const handle = async (request) => {
|
|
486
|
+
const { pathname } = new URL(request.url);
|
|
487
|
+
if (pathname !== "/api/session" || request.method !== "POST" && request.method !== "DELETE") {
|
|
488
|
+
return null;
|
|
489
|
+
}
|
|
490
|
+
if (!fromDashboard(request)) {
|
|
491
|
+
return crossSite();
|
|
492
|
+
}
|
|
493
|
+
if (request.method === "DELETE") {
|
|
494
|
+
return new Response(null, {
|
|
495
|
+
status: 204,
|
|
496
|
+
headers: { "Set-Cookie": sessions.close(request) }
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
const body = sessionRequestSchema.safeParse(await request.json().catch(() => null));
|
|
500
|
+
if (!body.success) {
|
|
501
|
+
return Response.json({ error: "Send { token }" }, { status: 400 });
|
|
502
|
+
}
|
|
503
|
+
const identity = tokenIdentity(body.data.token);
|
|
504
|
+
if (!identity) {
|
|
505
|
+
return unauthorized();
|
|
506
|
+
}
|
|
507
|
+
return Response.json(identity, {
|
|
508
|
+
headers: { "Set-Cookie": sessions.open(identity) }
|
|
509
|
+
});
|
|
510
|
+
};
|
|
511
|
+
const routes = [
|
|
512
|
+
{
|
|
513
|
+
method: "GET",
|
|
514
|
+
pattern: "/api/session",
|
|
515
|
+
role: "viewer",
|
|
516
|
+
handle: async (_request, { identity }) => Response.json(identity)
|
|
517
|
+
},
|
|
518
|
+
{
|
|
519
|
+
method: "GET",
|
|
520
|
+
pattern: "/api/access",
|
|
521
|
+
role: "admin",
|
|
522
|
+
handle: async () => Response.json(await readAccessConfig(options.file))
|
|
523
|
+
},
|
|
524
|
+
{
|
|
525
|
+
method: "PUT",
|
|
526
|
+
pattern: "/api/access",
|
|
527
|
+
role: "admin",
|
|
528
|
+
handle: async (request, { identity }) => {
|
|
529
|
+
const config = accessConfigSchema.parse(await request.json());
|
|
530
|
+
const previous = await readAccessConfig(options.file);
|
|
531
|
+
await writeAccessConfig(options.file, config);
|
|
532
|
+
await options.audit.record({
|
|
533
|
+
identity,
|
|
534
|
+
command: "access",
|
|
535
|
+
values: auditedAccess(config),
|
|
536
|
+
previous: auditedAccess(previous),
|
|
537
|
+
error: null
|
|
538
|
+
});
|
|
539
|
+
return Response.json(config);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
];
|
|
543
|
+
return { identify, handle, routes };
|
|
544
|
+
};
|
|
545
|
+
var auditedAccess = (config) => ({
|
|
546
|
+
...config.roles,
|
|
547
|
+
"(tailnet default)": config.tailnetDefault ?? "none"
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
// packages/agent/src/audit.ts
|
|
551
|
+
import { z as z3 } from "zod";
|
|
552
|
+
|
|
553
|
+
// packages/agent/src/logs.ts
|
|
554
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
555
|
+
import { open, readFile as readFile2, rename as rename2, stat } from "node:fs/promises";
|
|
556
|
+
var rotateBytes = 5 * 2 ** 20;
|
|
557
|
+
var appendJsonl = async (file, value) => {
|
|
558
|
+
if (existsSync2(file) && (await stat(file)).size >= rotateBytes) {
|
|
559
|
+
await rename2(file, `${file}.1`);
|
|
560
|
+
}
|
|
561
|
+
const log = await open(file, "a+");
|
|
562
|
+
try {
|
|
563
|
+
const { size } = await log.stat();
|
|
564
|
+
const last = Buffer.alloc(1);
|
|
565
|
+
if (size) {
|
|
566
|
+
await log.read(last, 0, 1, size - 1);
|
|
567
|
+
}
|
|
568
|
+
const separator = size && last[0] !== 10 ? `
|
|
569
|
+
` : "";
|
|
570
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
571
|
+
`);
|
|
572
|
+
} finally {
|
|
573
|
+
await log.close();
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
var readJsonl = async (file, schema, limit) => {
|
|
577
|
+
if (!existsSync2(file)) {
|
|
578
|
+
return [];
|
|
579
|
+
}
|
|
580
|
+
return (await readFile2(file, "utf8")).split(`
|
|
581
|
+
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
582
|
+
try {
|
|
583
|
+
return [schema.parse(JSON.parse(line))];
|
|
584
|
+
} catch {
|
|
585
|
+
return [];
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// packages/agent/src/audit.ts
|
|
591
|
+
var auditLimits = { default: 100, max: 1000 };
|
|
592
|
+
var auditQuerySchema = z3.object({
|
|
593
|
+
limit: z3.coerce.number().int().positive().max(auditLimits.max).default(auditLimits.default)
|
|
594
|
+
});
|
|
595
|
+
var createAudit = (context) => {
|
|
596
|
+
const record = async (change) => {
|
|
597
|
+
const entry = {
|
|
598
|
+
at: new Date().toISOString(),
|
|
599
|
+
command: change.command,
|
|
600
|
+
values: change.values,
|
|
601
|
+
...change.previous && { previous: change.previous },
|
|
602
|
+
user: change.identity.login ?? change.identity.name,
|
|
603
|
+
...change.error !== null && { error: change.error }
|
|
604
|
+
};
|
|
605
|
+
await appendJsonl(context.file, entry);
|
|
606
|
+
await context.onRecord(entry);
|
|
607
|
+
};
|
|
608
|
+
const routes = [
|
|
609
|
+
{
|
|
610
|
+
method: "GET",
|
|
611
|
+
pattern: "/api/audit",
|
|
612
|
+
role: "viewer",
|
|
613
|
+
handle: async (request) => {
|
|
614
|
+
const { limit } = auditQuerySchema.parse(Object.fromEntries(new URL(request.url).searchParams));
|
|
615
|
+
return Response.json((await readJsonl(context.file, auditSchema, limit)).reverse());
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
];
|
|
619
|
+
return { record, routes };
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
// packages/agent/src/codesys.ts
|
|
623
|
+
import { join as join2 } from "node:path";
|
|
624
|
+
import {
|
|
625
|
+
builderImageStatus,
|
|
626
|
+
captureDocker,
|
|
627
|
+
gatewayImage,
|
|
628
|
+
setupReason
|
|
629
|
+
} from "@tsplc/build";
|
|
630
|
+
import { resolveConfig } from "@tsplc/config/build";
|
|
631
|
+
var network = "tsplc-agent";
|
|
632
|
+
var codesysNetwork = "tsplc-agent-codesys";
|
|
633
|
+
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
634
|
+
var loginContainer = "tsplc-agent-login";
|
|
635
|
+
var deployContainer = "tsplc-agent-deploy";
|
|
636
|
+
var agentDockerResources = {
|
|
637
|
+
containers: [gateway.host, deployContainer, loginContainer],
|
|
638
|
+
networks: [network, codesysNetwork]
|
|
639
|
+
};
|
|
640
|
+
var credentialNames = {
|
|
641
|
+
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
642
|
+
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
643
|
+
};
|
|
644
|
+
var dockerTimeout = 60000;
|
|
645
|
+
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
646
|
+
var ensureNetwork = async (name, ...options) => {
|
|
647
|
+
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
648
|
+
await docker("network", "create", ...options, name);
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
var setupNeeded = async () => {
|
|
652
|
+
const status = await builderImageStatus();
|
|
653
|
+
const reason = setupReason(status) ?? (await docker("image", "ls", "--quiet", gatewayImage) ? null : `the CODESYS gateway image ${gatewayImage} is missing`);
|
|
654
|
+
return { status, reason };
|
|
655
|
+
};
|
|
656
|
+
var requireBuilder = async () => {
|
|
657
|
+
const { status, reason } = await setupNeeded().catch((cause) => {
|
|
658
|
+
throw new AgentError(`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`, 503);
|
|
659
|
+
});
|
|
660
|
+
if (reason) {
|
|
661
|
+
throw new AgentError(`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`, 409);
|
|
662
|
+
}
|
|
663
|
+
return status;
|
|
664
|
+
};
|
|
665
|
+
var describeBuilder = async () => {
|
|
666
|
+
const { status, reason } = await setupNeeded();
|
|
667
|
+
if (reason) {
|
|
668
|
+
return `Deployments and logins need tsplc-agent setup first: ${reason}`;
|
|
669
|
+
}
|
|
670
|
+
if (status.kind === "unverified") {
|
|
671
|
+
return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
|
|
672
|
+
}
|
|
673
|
+
return "The CODESYS images match this tsPLC";
|
|
674
|
+
};
|
|
675
|
+
var removeContainer = (name) => docker("rm", "--force", name);
|
|
676
|
+
var ensureGateway = async () => {
|
|
677
|
+
await ensureNetwork(network);
|
|
678
|
+
await ensureNetwork(codesysNetwork, "--internal");
|
|
679
|
+
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
680
|
+
await docker("rm", "--force", gateway.host);
|
|
681
|
+
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
682
|
+
}
|
|
683
|
+
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
684
|
+
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
685
|
+
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
var credentialEnvironment = (credentials) => ({
|
|
689
|
+
[credentialNames.usernameEnv]: credentials.username,
|
|
690
|
+
[credentialNames.passwordEnv]: credentials.password
|
|
691
|
+
});
|
|
692
|
+
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
693
|
+
...resolveConfig({
|
|
694
|
+
...release.manifest.config,
|
|
695
|
+
...settings.bulkImport && { bulkImport: true },
|
|
696
|
+
online: {
|
|
697
|
+
network: codesysNetwork,
|
|
698
|
+
gateway,
|
|
699
|
+
device: target,
|
|
700
|
+
credentials: credentialNames
|
|
701
|
+
}
|
|
702
|
+
}, join2(release.directory, "manifest.json")),
|
|
703
|
+
outDir: controllerDirectory
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
// packages/agent/src/dashboard/index.ts
|
|
707
|
+
import { createRequire } from "node:module";
|
|
708
|
+
import { basename, dirname, resolve } from "node:path";
|
|
709
|
+
var pages = ["/", "/deployments", "/environment", "/audit", "/access"];
|
|
710
|
+
var dashboardAssets = "/dashboard-assets/";
|
|
711
|
+
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("tsplc-theme")||""</script><link rel="stylesheet" href="${dashboardAssets}dashboard.css"><script type="module" src="${dashboardAssets}main.js"></script></head><body><main id="app"></main></body></html>`;
|
|
712
|
+
var contract = {
|
|
713
|
+
roles,
|
|
714
|
+
permissions: Object.fromEntries(roles.map((role) => [
|
|
715
|
+
role,
|
|
716
|
+
Object.fromEntries(roles.map((required) => [required, allows(role, required)]))
|
|
717
|
+
]))
|
|
718
|
+
};
|
|
719
|
+
var bundle = async () => {
|
|
720
|
+
const sources = resolve(dirname(createRequire(import.meta.url).resolve("@tsplc/agent")), "../src/dashboard/ui");
|
|
721
|
+
const result = await Bun.build({
|
|
722
|
+
entrypoints: [
|
|
723
|
+
resolve(sources, "main.ts"),
|
|
724
|
+
resolve(sources, "dashboard.css")
|
|
725
|
+
],
|
|
726
|
+
target: "browser",
|
|
727
|
+
conditions: ["bun"],
|
|
728
|
+
minify: true,
|
|
729
|
+
naming: "[name].[ext]",
|
|
730
|
+
define: { TSPLC_CONTRACT: JSON.stringify(contract) }
|
|
731
|
+
});
|
|
732
|
+
if (!result.success) {
|
|
733
|
+
throw new Error(`Bundling the dashboard failed:
|
|
734
|
+
${result.logs.map(String).join(`
|
|
735
|
+
`)}`);
|
|
736
|
+
}
|
|
737
|
+
const assets = new Map;
|
|
738
|
+
for (const output of result.outputs) {
|
|
739
|
+
assets.set(basename(output.path), {
|
|
740
|
+
text: await output.text(),
|
|
741
|
+
type: output.type
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
return assets;
|
|
745
|
+
};
|
|
746
|
+
var isPage = (pathname) => pages.some((path) => pathname === path || path !== "/" && pathname.startsWith(`${path}/`));
|
|
747
|
+
var createDashboard = () => {
|
|
748
|
+
let assets;
|
|
749
|
+
return {
|
|
750
|
+
handle: async (request) => {
|
|
751
|
+
const { pathname } = new URL(request.url);
|
|
752
|
+
if (request.method !== "GET") {
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (isPage(pathname)) {
|
|
756
|
+
return new Response(page, {
|
|
757
|
+
headers: {
|
|
758
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
759
|
+
"Cache-Control": "no-cache"
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
if (!pathname.startsWith(dashboardAssets)) {
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
assets ??= bundle();
|
|
767
|
+
try {
|
|
768
|
+
const asset = (await assets).get(pathname.slice(dashboardAssets.length));
|
|
769
|
+
if (!asset) {
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
return new Response(asset.text, {
|
|
773
|
+
headers: { "Content-Type": asset.type, "Cache-Control": "no-cache" }
|
|
774
|
+
});
|
|
775
|
+
} catch (error) {
|
|
776
|
+
assets = undefined;
|
|
777
|
+
return new Response(errorMessage(error), { status: 500 });
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
// packages/agent/src/debugging.ts
|
|
784
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
785
|
+
import { join as join5 } from "node:path";
|
|
786
|
+
import {
|
|
787
|
+
createDebugger,
|
|
788
|
+
createDebugHandler,
|
|
789
|
+
createLoginAdapter,
|
|
790
|
+
loadExplanations,
|
|
791
|
+
loadManifest,
|
|
792
|
+
timelineEntries
|
|
793
|
+
} from "@tsplc/debug";
|
|
794
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
295
795
|
|
|
296
796
|
// packages/agent/src/releases.ts
|
|
297
|
-
import { createHash as
|
|
298
|
-
import { existsSync as
|
|
797
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
798
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
299
799
|
import {
|
|
300
800
|
mkdir,
|
|
301
801
|
mkdtemp,
|
|
302
802
|
readdir,
|
|
303
|
-
readFile as
|
|
304
|
-
rename as
|
|
803
|
+
readFile as readFile3,
|
|
804
|
+
rename as rename3,
|
|
305
805
|
rm,
|
|
306
806
|
stat as stat2,
|
|
307
|
-
writeFile
|
|
807
|
+
writeFile as writeFile2
|
|
308
808
|
} from "node:fs/promises";
|
|
309
|
-
import {
|
|
310
|
-
|
|
809
|
+
import {
|
|
810
|
+
dirname as dirname2,
|
|
811
|
+
isAbsolute,
|
|
812
|
+
join as join3,
|
|
813
|
+
posix,
|
|
814
|
+
relative,
|
|
815
|
+
resolve as resolve2,
|
|
816
|
+
sep
|
|
817
|
+
} from "node:path";
|
|
818
|
+
import { z as z4 } from "zod";
|
|
311
819
|
|
|
312
820
|
// packages/agent/src/transfer.ts
|
|
313
|
-
import { createHash } from "node:crypto";
|
|
314
|
-
var shortDigest = (data) =>
|
|
315
|
-
var fileBucket = (path) =>
|
|
821
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
822
|
+
var shortDigest = (data) => createHash2("sha256").update(data).digest("hex").slice(0, 16);
|
|
823
|
+
var fileBucket = (path) => createHash2("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
|
|
316
824
|
var bucketDigests = (files) => {
|
|
317
825
|
const buckets = Array.from({ length: releaseBuckets }, () => []);
|
|
318
826
|
for (const { path, digest } of files) {
|
|
@@ -368,10 +876,10 @@ var readUpload = async (form) => {
|
|
|
368
876
|
if (form.get("encoding") !== uploadEncoding) {
|
|
369
877
|
throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
|
|
370
878
|
}
|
|
371
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(
|
|
879
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(z4.string().parse(form.get("manifest"))));
|
|
372
880
|
const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
|
|
373
881
|
path: releasePath(name.slice(filePrefix.length)),
|
|
374
|
-
content: Bun.gunzipSync(await
|
|
882
|
+
content: Bun.gunzipSync(await z4.instanceof(File).parse(value).bytes())
|
|
375
883
|
})));
|
|
376
884
|
const upload = { manifest, files };
|
|
377
885
|
checkServer(upload);
|
|
@@ -390,31 +898,31 @@ var readDeployRequest = async (releases, request) => {
|
|
|
390
898
|
if (type.startsWith("multipart/form-data")) {
|
|
391
899
|
const form = await request.formData();
|
|
392
900
|
return {
|
|
393
|
-
settings: deployOptionsSchema.parse(JSON.parse(
|
|
901
|
+
settings: deployOptionsSchema.parse(JSON.parse(z4.string().parse(form.get("options")))),
|
|
394
902
|
upload: await readUpload(form)
|
|
395
903
|
};
|
|
396
904
|
}
|
|
397
905
|
throw new AgentError(`Unsupported deployment content type ${type}`, 415);
|
|
398
906
|
};
|
|
399
907
|
var saveRelease = async (releases, { manifest, files }) => {
|
|
400
|
-
const hash =
|
|
908
|
+
const hash = createHash3("sha256").update(JSON.stringify(manifest));
|
|
401
909
|
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
402
|
-
hash.update(file.path).update(
|
|
910
|
+
hash.update(file.path).update(createHash3("sha256").update(file.content).digest("hex"));
|
|
403
911
|
}
|
|
404
912
|
const id = hash.digest("hex").slice(0, 16);
|
|
405
|
-
const directory =
|
|
406
|
-
if (!
|
|
913
|
+
const directory = join3(releases, id);
|
|
914
|
+
if (!existsSync3(directory)) {
|
|
407
915
|
await mkdir(releases, { recursive: true });
|
|
408
|
-
const staging = await mkdtemp(
|
|
916
|
+
const staging = await mkdtemp(join3(releases, ".upload-"));
|
|
409
917
|
try {
|
|
410
918
|
for (const file of files) {
|
|
411
|
-
await mkdir(
|
|
412
|
-
await
|
|
919
|
+
await mkdir(dirname2(join3(staging, file.path)), { recursive: true });
|
|
920
|
+
await writeFile2(join3(staging, file.path), file.content, {
|
|
413
921
|
mode: file.path === manifest.server ? 493 : 420
|
|
414
922
|
});
|
|
415
923
|
}
|
|
416
|
-
await
|
|
417
|
-
await
|
|
924
|
+
await writeFile2(join3(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
925
|
+
await rename3(staging, directory);
|
|
418
926
|
} catch (cause) {
|
|
419
927
|
await rm(staging, { recursive: true, force: true });
|
|
420
928
|
throw cause;
|
|
@@ -423,14 +931,53 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
423
931
|
return { id, directory, manifest };
|
|
424
932
|
};
|
|
425
933
|
var loadRelease = async (releases, id) => {
|
|
426
|
-
const directory =
|
|
427
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(await
|
|
934
|
+
const directory = join3(releases, id);
|
|
935
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile3(join3(directory, "manifest.json"), "utf8")));
|
|
428
936
|
return { id, directory, manifest };
|
|
429
937
|
};
|
|
938
|
+
var listReleaseFiles = async (releases, id) => {
|
|
939
|
+
const directory = join3(releases, id);
|
|
940
|
+
if (!existsSync3(join3(directory, "manifest.json"))) {
|
|
941
|
+
throw new AgentError(`The release ${id} is no longer stored`, 404);
|
|
942
|
+
}
|
|
943
|
+
const files = [];
|
|
944
|
+
for await (const found of new Bun.Glob("**/*").scan({
|
|
945
|
+
cwd: directory,
|
|
946
|
+
dot: true
|
|
947
|
+
})) {
|
|
948
|
+
files.push({
|
|
949
|
+
path: found.split(sep).join("/"),
|
|
950
|
+
size: (await stat2(join3(directory, found))).size
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
return files.sort((left, right) => left.path.localeCompare(right.path));
|
|
954
|
+
};
|
|
955
|
+
var readReleaseFile = async (releases, id, path) => {
|
|
956
|
+
const directory = resolve2(releases, id);
|
|
957
|
+
const file = resolve2(directory, path);
|
|
958
|
+
const inside = relative(directory, file);
|
|
959
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
|
|
960
|
+
throw new AgentError(`${path} isn't a path in a release`, 400);
|
|
961
|
+
}
|
|
962
|
+
if (!await stat2(file).then((found) => found.isFile(), () => false)) {
|
|
963
|
+
throw new AgentError(`The release ${id} has no file ${path}`, 404);
|
|
964
|
+
}
|
|
965
|
+
return Bun.file(file);
|
|
966
|
+
};
|
|
967
|
+
var pruneReleases = async (releases, kept) => {
|
|
968
|
+
if (!existsSync3(releases)) {
|
|
969
|
+
return [];
|
|
970
|
+
}
|
|
971
|
+
const removed = (await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !kept.has(entry.name)).map((entry) => entry.name);
|
|
972
|
+
for (const id of removed) {
|
|
973
|
+
await rm(join3(releases, id), { recursive: true, force: true });
|
|
974
|
+
}
|
|
975
|
+
return removed;
|
|
976
|
+
};
|
|
430
977
|
var createReleaseStore = (releases) => {
|
|
431
978
|
const indexes = new Map;
|
|
432
979
|
const readIndex = async (id) => {
|
|
433
|
-
const directory =
|
|
980
|
+
const directory = join3(releases, id);
|
|
434
981
|
const files = new Map;
|
|
435
982
|
for await (const found of new Bun.Glob("**/*").scan({
|
|
436
983
|
cwd: directory,
|
|
@@ -438,7 +985,7 @@ var createReleaseStore = (releases) => {
|
|
|
438
985
|
})) {
|
|
439
986
|
const path = found.split(sep).join("/");
|
|
440
987
|
if (path !== "manifest.json") {
|
|
441
|
-
files.set(path, shortDigest(await
|
|
988
|
+
files.set(path, shortDigest(await readFile3(join3(directory, found))));
|
|
442
989
|
}
|
|
443
990
|
}
|
|
444
991
|
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
@@ -455,12 +1002,12 @@ var createReleaseStore = (releases) => {
|
|
|
455
1002
|
return reading;
|
|
456
1003
|
};
|
|
457
1004
|
const newest = async () => {
|
|
458
|
-
if (!
|
|
1005
|
+
if (!existsSync3(releases)) {
|
|
459
1006
|
return;
|
|
460
1007
|
}
|
|
461
1008
|
const stored = await Promise.all((await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map(async ({ name }) => ({
|
|
462
1009
|
name,
|
|
463
|
-
created: (await stat2(
|
|
1010
|
+
created: (await stat2(join3(releases, name))).mtimeMs
|
|
464
1011
|
})));
|
|
465
1012
|
return stored.sort((left, right) => right.created - left.created)[0]?.name;
|
|
466
1013
|
};
|
|
@@ -468,7 +1015,7 @@ var createReleaseStore = (releases) => {
|
|
|
468
1015
|
compare: async (buckets, deployed) => {
|
|
469
1016
|
const candidates = [
|
|
470
1017
|
...new Set([deployed, await newest()].filter((id) => id != null))
|
|
471
|
-
].filter((id) =>
|
|
1018
|
+
].filter((id) => existsSync3(join3(releases, id, "manifest.json")));
|
|
472
1019
|
const compared = await Promise.all(candidates.map(async (id) => {
|
|
473
1020
|
const { files, buckets: stored } = await index(id);
|
|
474
1021
|
const changed = buckets.flatMap((digest, bucket) => stored[bucket] === digest ? [] : [bucket]);
|
|
@@ -496,13 +1043,13 @@ var createReleaseStore = (releases) => {
|
|
|
496
1043
|
throw new AgentError("The release upload sends a file twice", 400);
|
|
497
1044
|
}
|
|
498
1045
|
if (base !== null) {
|
|
499
|
-
if (!
|
|
1046
|
+
if (!existsSync3(join3(releases, base, "manifest.json"))) {
|
|
500
1047
|
throw new AgentError(`The release ${base} this upload builds on is gone; deploy again`, 409);
|
|
501
1048
|
}
|
|
502
1049
|
const removed = new Set(remove);
|
|
503
1050
|
const reused = [...(await index(base)).files.keys()].filter((path) => !removed.has(path) && !files.has(path));
|
|
504
1051
|
for (const path of reused) {
|
|
505
|
-
files.set(path, new Uint8Array(await
|
|
1052
|
+
files.set(path, new Uint8Array(await readFile3(join3(releases, base, path))));
|
|
506
1053
|
}
|
|
507
1054
|
}
|
|
508
1055
|
const assembled = bucketDigests([...files].map(([path, content]) => ({
|
|
@@ -523,11 +1070,15 @@ var createReleaseStore = (releases) => {
|
|
|
523
1070
|
};
|
|
524
1071
|
|
|
525
1072
|
// packages/agent/src/secrets.ts
|
|
526
|
-
import { mkdir as mkdir2, readFile as
|
|
527
|
-
import { dirname as
|
|
528
|
-
import {
|
|
1073
|
+
import { mkdir as mkdir2, readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
1074
|
+
import { dirname as dirname3, join as join4, relative as relative2, sep as sep2 } from "node:path";
|
|
1075
|
+
import {
|
|
1076
|
+
secretPlaceholder,
|
|
1077
|
+
secretValue as secretValue2
|
|
1078
|
+
} from "@tsplc/config";
|
|
529
1079
|
import { escapeString } from "@tsplc/iec/st";
|
|
530
1080
|
var agentService = "tsplc-agent";
|
|
1081
|
+
var environmentService = "tsplc-agent-env";
|
|
531
1082
|
var controllerSecretNames = {
|
|
532
1083
|
username: "controller-username",
|
|
533
1084
|
password: "controller-password"
|
|
@@ -561,7 +1112,7 @@ var readSecrets = async (secrets) => {
|
|
|
561
1112
|
const missing = [];
|
|
562
1113
|
for (const name of secrets.names) {
|
|
563
1114
|
const value = await Bun.secrets.get({ service, name });
|
|
564
|
-
const valid =
|
|
1115
|
+
const valid = secretValue2.safeParse(value);
|
|
565
1116
|
if (!value) {
|
|
566
1117
|
missing.push(name);
|
|
567
1118
|
} else if (!valid.success) {
|
|
@@ -576,6 +1127,23 @@ var readSecrets = async (secrets) => {
|
|
|
576
1127
|
return values;
|
|
577
1128
|
};
|
|
578
1129
|
var releaseVariable = async (manifest, name, environment) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : environment[name];
|
|
1130
|
+
var serverEnvironment = async (releases, executable, environment) => {
|
|
1131
|
+
const [id = ""] = relative2(releases, executable).split(sep2);
|
|
1132
|
+
const secrets = await loadRelease(releases, id).then(({ manifest }) => manifest.secrets, () => {
|
|
1133
|
+
return;
|
|
1134
|
+
});
|
|
1135
|
+
if (!secrets) {
|
|
1136
|
+
return environment;
|
|
1137
|
+
}
|
|
1138
|
+
const stored = await Promise.all(secrets.names.map(async (name) => ({
|
|
1139
|
+
name,
|
|
1140
|
+
value: await Bun.secrets.get({ service: secrets.service, name })
|
|
1141
|
+
})));
|
|
1142
|
+
return {
|
|
1143
|
+
...environment,
|
|
1144
|
+
...Object.fromEntries(stored.flatMap(({ name, value }) => value === null ? [] : [[name, value]]))
|
|
1145
|
+
};
|
|
1146
|
+
};
|
|
579
1147
|
var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
|
|
580
1148
|
var withSecrets = async (config, secrets, directory) => {
|
|
581
1149
|
await rm2(directory, { recursive: true, force: true });
|
|
@@ -583,14 +1151,14 @@ var withSecrets = async (config, secrets, directory) => {
|
|
|
583
1151
|
cwd: config.sourceDir,
|
|
584
1152
|
dot: true
|
|
585
1153
|
})) {
|
|
586
|
-
const file =
|
|
587
|
-
await mkdir2(
|
|
588
|
-
await
|
|
1154
|
+
const file = join4(directory, path);
|
|
1155
|
+
await mkdir2(dirname3(file), { recursive: true });
|
|
1156
|
+
await writeFile3(file, fillSecrets(await readFile4(join4(config.sourceDir, path), "utf8"), secrets));
|
|
589
1157
|
}
|
|
590
1158
|
return {
|
|
591
1159
|
...config,
|
|
592
1160
|
sourceDir: directory,
|
|
593
|
-
entry:
|
|
1161
|
+
entry: join4(directory, relative2(config.sourceDir, config.entry))
|
|
594
1162
|
};
|
|
595
1163
|
};
|
|
596
1164
|
|
|
@@ -603,91 +1171,883 @@ var createDebugging = (context) => {
|
|
|
603
1171
|
if (!release) {
|
|
604
1172
|
return null;
|
|
605
1173
|
}
|
|
606
|
-
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
607
|
-
const manifestFile =
|
|
608
|
-
if (!
|
|
609
|
-
return null;
|
|
1174
|
+
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
1175
|
+
const manifestFile = join5(directory, debugManifestFile);
|
|
1176
|
+
if (!existsSync4(manifestFile)) {
|
|
1177
|
+
return null;
|
|
1178
|
+
}
|
|
1179
|
+
const manifest = await loadManifest(manifestFile);
|
|
1180
|
+
const serverToken = releaseManifest.serverTokenEnv && await releaseVariable(releaseManifest, releaseManifest.serverTokenEnv, context.environment);
|
|
1181
|
+
const debug = await createDebugger({
|
|
1182
|
+
manifest,
|
|
1183
|
+
adapter: createLoginAdapter({
|
|
1184
|
+
read: context.readLogin,
|
|
1185
|
+
probe: manifest.build.target,
|
|
1186
|
+
endpoint: "the agent's login"
|
|
1187
|
+
}),
|
|
1188
|
+
stateDirectory: state.paths.debug,
|
|
1189
|
+
watch: releaseManifest.debug?.watch ?? {},
|
|
1190
|
+
...context.serverHealthUrl && serverToken && {
|
|
1191
|
+
server: {
|
|
1192
|
+
url: new URL(context.serverHealthUrl).origin,
|
|
1193
|
+
token: serverToken
|
|
1194
|
+
}
|
|
1195
|
+
},
|
|
1196
|
+
release: {
|
|
1197
|
+
id: release.id,
|
|
1198
|
+
deployedAt: release.deployedAt,
|
|
1199
|
+
operation: release.operation
|
|
1200
|
+
},
|
|
1201
|
+
timeline: [
|
|
1202
|
+
...(await readJsonl(state.paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
1203
|
+
...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
1204
|
+
],
|
|
1205
|
+
explanations: await loadExplanations(manifestFile, manifest),
|
|
1206
|
+
forced: async () => {
|
|
1207
|
+
const login = await context.loginStatus();
|
|
1208
|
+
return login && "forced" in login ? login.forced : null;
|
|
1209
|
+
},
|
|
1210
|
+
log
|
|
1211
|
+
});
|
|
1212
|
+
return { debug, handle: createDebugHandler(debug, log) };
|
|
1213
|
+
};
|
|
1214
|
+
const startOrLog = () => start().catch((error) => {
|
|
1215
|
+
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
1216
|
+
return null;
|
|
1217
|
+
});
|
|
1218
|
+
let current = startOrLog();
|
|
1219
|
+
return {
|
|
1220
|
+
handle: async (request, route) => {
|
|
1221
|
+
const debugging = await current;
|
|
1222
|
+
if (!debugging) {
|
|
1223
|
+
return Response.json({
|
|
1224
|
+
error: "The deployed release has no debug manifest, or the debugger failed to start"
|
|
1225
|
+
}, { status: 503 });
|
|
1226
|
+
}
|
|
1227
|
+
return debugging.handle(request, route);
|
|
1228
|
+
},
|
|
1229
|
+
record: async ({ at, ...audit }) => {
|
|
1230
|
+
(await current)?.debug.record(timelineEntries.audit(at, audit));
|
|
1231
|
+
},
|
|
1232
|
+
restart: () => {
|
|
1233
|
+
current = current.then(async (debugging) => {
|
|
1234
|
+
await debugging?.debug.close();
|
|
1235
|
+
return startOrLog();
|
|
1236
|
+
});
|
|
1237
|
+
},
|
|
1238
|
+
close: async () => {
|
|
1239
|
+
await (await current)?.debug.close();
|
|
1240
|
+
}
|
|
1241
|
+
};
|
|
1242
|
+
};
|
|
1243
|
+
|
|
1244
|
+
// packages/agent/src/deploy.ts
|
|
1245
|
+
import {
|
|
1246
|
+
controllerBaseline,
|
|
1247
|
+
findControllerLogin,
|
|
1248
|
+
reviewWarmController,
|
|
1249
|
+
settleWarmController,
|
|
1250
|
+
startWarmController,
|
|
1251
|
+
updateWarmController,
|
|
1252
|
+
workerScriptsDigest
|
|
1253
|
+
} from "@tsplc/build";
|
|
1254
|
+
|
|
1255
|
+
// packages/agent/src/deployments/runner.ts
|
|
1256
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
1257
|
+
import { join as join7 } from "node:path";
|
|
1258
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1259
|
+
import {
|
|
1260
|
+
DownloadRequiredError,
|
|
1261
|
+
describeFinding,
|
|
1262
|
+
requiresDownload,
|
|
1263
|
+
transferRollback
|
|
1264
|
+
} from "@tsplc/build";
|
|
1265
|
+
import { loadManifest as loadManifest2 } from "@tsplc/debug";
|
|
1266
|
+
import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
|
|
1267
|
+
|
|
1268
|
+
// packages/agent/src/deployments/health.ts
|
|
1269
|
+
import { z as z5 } from "zod";
|
|
1270
|
+
var serverHealthSchema = z5.looseObject({ plcConnected: z5.boolean() });
|
|
1271
|
+
var healthTimeoutMs = 5000;
|
|
1272
|
+
var plcHealth = (body) => {
|
|
1273
|
+
const parsed = serverHealthSchema.safeParse(body);
|
|
1274
|
+
if (!parsed.success) {
|
|
1275
|
+
return "unknown";
|
|
1276
|
+
}
|
|
1277
|
+
return parsed.data.plcConnected ? "ok" : "failed";
|
|
1278
|
+
};
|
|
1279
|
+
var serverHealth = async (healthUrl, server) => {
|
|
1280
|
+
if (!healthUrl) {
|
|
1281
|
+
return {
|
|
1282
|
+
server: server.status()?.running ? "ok" : "failed",
|
|
1283
|
+
plc: "unknown"
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
const response = await fetch(healthUrl, {
|
|
1287
|
+
signal: AbortSignal.timeout(healthTimeoutMs)
|
|
1288
|
+
}).catch(() => null);
|
|
1289
|
+
if (!response?.ok) {
|
|
1290
|
+
return { server: "failed", plc: "unknown" };
|
|
1291
|
+
}
|
|
1292
|
+
return {
|
|
1293
|
+
server: "ok",
|
|
1294
|
+
plc: plcHealth(await response.json().catch(() => null))
|
|
1295
|
+
};
|
|
1296
|
+
};
|
|
1297
|
+
var noServer = {
|
|
1298
|
+
server: "none",
|
|
1299
|
+
plc: "unknown"
|
|
1300
|
+
};
|
|
1301
|
+
var checkHealth = async (options) => {
|
|
1302
|
+
const controller = options.controllerState === "run" ? "ok" : "failed";
|
|
1303
|
+
const { server, plc } = options.hasServer ? await serverHealth(options.healthUrl, options.server) : noServer;
|
|
1304
|
+
const problems = [
|
|
1305
|
+
controller === "failed" && `The controller's application is in state ${options.controllerState}`,
|
|
1306
|
+
server === "failed" && "The server isn't running",
|
|
1307
|
+
plc === "failed" && "The server isn't connected to the PLC"
|
|
1308
|
+
].filter((problem) => typeof problem === "string");
|
|
1309
|
+
return {
|
|
1310
|
+
controller,
|
|
1311
|
+
server,
|
|
1312
|
+
plc,
|
|
1313
|
+
detail: problems.length ? problems.join(". ") : null
|
|
1314
|
+
};
|
|
1315
|
+
};
|
|
1316
|
+
var healthy = (health) => health.controller === "ok" && health.server !== "failed";
|
|
1317
|
+
|
|
1318
|
+
// packages/agent/src/deployments/store.ts
|
|
1319
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1320
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
1321
|
+
import {
|
|
1322
|
+
appendFile,
|
|
1323
|
+
mkdir as mkdir3,
|
|
1324
|
+
readdir as readdir2,
|
|
1325
|
+
readFile as readFile5,
|
|
1326
|
+
rename as rename4,
|
|
1327
|
+
rm as rm3,
|
|
1328
|
+
writeFile as writeFile4
|
|
1329
|
+
} from "node:fs/promises";
|
|
1330
|
+
import { join as join6 } from "node:path";
|
|
1331
|
+
var finalStates = ["ready", "error", "canceled"];
|
|
1332
|
+
var isFinished = (record) => finalStates.includes(record.state);
|
|
1333
|
+
var activeDeployments = (records) => {
|
|
1334
|
+
const running = records.filter((record) => record.activeFrom !== null);
|
|
1335
|
+
const newest = (candidates) => candidates.reduce((best, record) => best && (best.activeFrom ?? "") >= (record.activeFrom ?? "") ? best : record, null)?.id ?? null;
|
|
1336
|
+
return {
|
|
1337
|
+
current: newest(running.filter((record) => record.activeUntil === null)),
|
|
1338
|
+
lastGood: newest(running.filter((record) => record.state === "ready"))
|
|
1339
|
+
};
|
|
1340
|
+
};
|
|
1341
|
+
var parseJson = (text) => {
|
|
1342
|
+
try {
|
|
1343
|
+
return JSON.parse(text);
|
|
1344
|
+
} catch {
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
var newId = () => `dpl_${[...randomBytes2(20)].map((byte) => (byte % 36).toString(36)).join("")}`;
|
|
1349
|
+
var openDeploymentStore = async (options) => {
|
|
1350
|
+
const { directory } = options;
|
|
1351
|
+
const records = new Map;
|
|
1352
|
+
const sequences = new Map;
|
|
1353
|
+
const writes = new Map;
|
|
1354
|
+
const listeners = new Map;
|
|
1355
|
+
await mkdir3(directory, { recursive: true });
|
|
1356
|
+
for (const entry of await readdir2(directory, { withFileTypes: true })) {
|
|
1357
|
+
const file = join6(directory, entry.name, "record.json");
|
|
1358
|
+
if (!entry.isDirectory() || !existsSync5(file)) {
|
|
1359
|
+
continue;
|
|
1360
|
+
}
|
|
1361
|
+
const parsed = deploymentRecordSchema.safeParse(parseJson(await readFile5(file, "utf8")));
|
|
1362
|
+
if (parsed.success && parsed.data.id === entry.name) {
|
|
1363
|
+
records.set(parsed.data.id, parsed.data);
|
|
1364
|
+
} else {
|
|
1365
|
+
options.log(`Skipping the unreadable deployment record ${file}`);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const recordDirectory = (id) => join6(directory, id);
|
|
1369
|
+
const logFile = (id) => join6(recordDirectory(id), "log.jsonl");
|
|
1370
|
+
const inTurn = (id, write) => {
|
|
1371
|
+
const next = (writes.get(id) ?? Promise.resolve()).then(write);
|
|
1372
|
+
writes.set(id, next.then(() => {
|
|
1373
|
+
return;
|
|
1374
|
+
}, (error) => options.log(`Writing deployment ${id} failed: ${errorMessage(error)}`)));
|
|
1375
|
+
return next;
|
|
1376
|
+
};
|
|
1377
|
+
const emit = (id, event) => {
|
|
1378
|
+
for (const listener of listeners.get(id) ?? []) {
|
|
1379
|
+
listener(event);
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
const readLines = async (id) => {
|
|
1383
|
+
const file = logFile(id);
|
|
1384
|
+
if (!existsSync5(file)) {
|
|
1385
|
+
return [];
|
|
1386
|
+
}
|
|
1387
|
+
return (await readFile5(file, "utf8")).split(`
|
|
1388
|
+
`).filter(Boolean).flatMap((line) => {
|
|
1389
|
+
const parsed = deploymentLogLineSchema.safeParse(parseJson(line));
|
|
1390
|
+
return parsed.success ? [parsed.data] : [];
|
|
1391
|
+
});
|
|
1392
|
+
};
|
|
1393
|
+
const writeRecord = (record) => inTurn(record.id, async () => {
|
|
1394
|
+
const latest = records.get(record.id);
|
|
1395
|
+
if (!latest) {
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
const file = join6(recordDirectory(record.id), "record.json");
|
|
1399
|
+
const temporary = `${file}.tmp`;
|
|
1400
|
+
await mkdir3(recordDirectory(record.id), { recursive: true });
|
|
1401
|
+
await writeFile4(temporary, JSON.stringify(latest, null, 2));
|
|
1402
|
+
await rename4(temporary, file);
|
|
1403
|
+
});
|
|
1404
|
+
const existing = (id) => {
|
|
1405
|
+
const record = records.get(id);
|
|
1406
|
+
if (!record) {
|
|
1407
|
+
throw new Error(`No deployment ${id}`);
|
|
1408
|
+
}
|
|
1409
|
+
return record;
|
|
1410
|
+
};
|
|
1411
|
+
return {
|
|
1412
|
+
newId,
|
|
1413
|
+
get: (id) => records.get(id),
|
|
1414
|
+
list: () => [...records.values()].sort((left, right) => right.createdAt.localeCompare(left.createdAt)),
|
|
1415
|
+
create: async (record) => {
|
|
1416
|
+
records.set(record.id, record);
|
|
1417
|
+
sequences.set(record.id, 0);
|
|
1418
|
+
await writeRecord(record);
|
|
1419
|
+
return record;
|
|
1420
|
+
},
|
|
1421
|
+
update: async (id, change) => {
|
|
1422
|
+
const record = {
|
|
1423
|
+
...change(existing(id)),
|
|
1424
|
+
updatedAt: options.now().toISOString()
|
|
1425
|
+
};
|
|
1426
|
+
records.set(id, record);
|
|
1427
|
+
emit(id, { kind: "record", record });
|
|
1428
|
+
await writeRecord(record);
|
|
1429
|
+
return record;
|
|
1430
|
+
},
|
|
1431
|
+
log: (id, entry) => inTurn(id, async () => {
|
|
1432
|
+
const last = sequences.get(id) ?? (await readLines(id)).reduce((highest, line) => Math.max(highest, line.seq), 0);
|
|
1433
|
+
const line = {
|
|
1434
|
+
seq: last + 1,
|
|
1435
|
+
at: options.now().toISOString(),
|
|
1436
|
+
...entry
|
|
1437
|
+
};
|
|
1438
|
+
sequences.set(id, line.seq);
|
|
1439
|
+
await mkdir3(recordDirectory(id), { recursive: true });
|
|
1440
|
+
await appendFile(logFile(id), `${JSON.stringify(line)}
|
|
1441
|
+
`);
|
|
1442
|
+
emit(id, { kind: "log", line });
|
|
1443
|
+
return line;
|
|
1444
|
+
}),
|
|
1445
|
+
flush: async (id) => {
|
|
1446
|
+
await writes.get(id);
|
|
1447
|
+
},
|
|
1448
|
+
lines: async (id, after) => {
|
|
1449
|
+
await writes.get(id);
|
|
1450
|
+
return (await readLines(id)).filter((line) => line.seq > after);
|
|
1451
|
+
},
|
|
1452
|
+
subscribe: (id, listener) => {
|
|
1453
|
+
const subscribed = listeners.get(id) ?? new Set;
|
|
1454
|
+
subscribed.add(listener);
|
|
1455
|
+
listeners.set(id, subscribed);
|
|
1456
|
+
return () => {
|
|
1457
|
+
subscribed.delete(listener);
|
|
1458
|
+
};
|
|
1459
|
+
},
|
|
1460
|
+
remove: (id) => inTurn(id, async () => {
|
|
1461
|
+
records.delete(id);
|
|
1462
|
+
sequences.delete(id);
|
|
1463
|
+
await rm3(recordDirectory(id), { recursive: true, force: true });
|
|
1464
|
+
})
|
|
1465
|
+
};
|
|
1466
|
+
};
|
|
1467
|
+
|
|
1468
|
+
// packages/agent/src/deployments/retention.ts
|
|
1469
|
+
var retentionMs = 14 * 24 * 60 * 60 * 1000;
|
|
1470
|
+
var pruneDeployments = async (options) => {
|
|
1471
|
+
const { store } = options;
|
|
1472
|
+
const records = store.list();
|
|
1473
|
+
const { current, lastGood } = activeDeployments(records);
|
|
1474
|
+
const cutoff = options.now().getTime() - retentionMs;
|
|
1475
|
+
const expired = records.filter((record) => Date.parse(record.createdAt) < cutoff && record.id !== current && record.id !== lastGood && isFinished(record));
|
|
1476
|
+
for (const record of expired) {
|
|
1477
|
+
await store.remove(record.id);
|
|
1478
|
+
}
|
|
1479
|
+
const kept = new Set(store.list().map((record) => record.release));
|
|
1480
|
+
if (options.deployed) {
|
|
1481
|
+
kept.add(options.deployed.id);
|
|
1482
|
+
const server = options.deployed.server?.split("/")[0];
|
|
1483
|
+
if (server) {
|
|
1484
|
+
kept.add(server);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
return {
|
|
1488
|
+
deployments: expired.map((record) => record.id),
|
|
1489
|
+
releases: await pruneReleases(options.releases, kept)
|
|
1490
|
+
};
|
|
1491
|
+
};
|
|
1492
|
+
|
|
1493
|
+
// packages/agent/src/deployments/runner.ts
|
|
1494
|
+
class Canceled extends Error {
|
|
1495
|
+
}
|
|
1496
|
+
var cancelable = [
|
|
1497
|
+
"queued",
|
|
1498
|
+
"building",
|
|
1499
|
+
"awaitingApproval"
|
|
1500
|
+
];
|
|
1501
|
+
var retryMs = 1000;
|
|
1502
|
+
var releaseBuild = async (release) => {
|
|
1503
|
+
const file = join7(release.directory, debugManifestFile2);
|
|
1504
|
+
return existsSync6(file) ? (await loadManifest2(file)).build.id : null;
|
|
1505
|
+
};
|
|
1506
|
+
var createDeploymentRunner = (context) => {
|
|
1507
|
+
const { store, state, operations, controller } = context;
|
|
1508
|
+
const pending = new Map;
|
|
1509
|
+
const queue = [];
|
|
1510
|
+
let draining = false;
|
|
1511
|
+
let releasesTurn = Promise.resolve();
|
|
1512
|
+
const withReleases = (run) => {
|
|
1513
|
+
const next = releasesTurn.then(run);
|
|
1514
|
+
releasesTurn = next.catch(() => {
|
|
1515
|
+
return;
|
|
1516
|
+
});
|
|
1517
|
+
return next;
|
|
1518
|
+
};
|
|
1519
|
+
const timestamp = () => context.now().toISOString();
|
|
1520
|
+
const recordOf = (id) => {
|
|
1521
|
+
const record = store.get(id);
|
|
1522
|
+
if (!record) {
|
|
1523
|
+
throw new AgentError(`No deployment ${id}`, 404);
|
|
1524
|
+
}
|
|
1525
|
+
return record;
|
|
1526
|
+
};
|
|
1527
|
+
const say = (item, level, message) => {
|
|
1528
|
+
const phase = recordOf(item.id).phases.find((entry) => entry.outcome === "running")?.name ?? null;
|
|
1529
|
+
store.log(item.id, { level, phase, message }).catch(() => {
|
|
1530
|
+
return;
|
|
1531
|
+
});
|
|
1532
|
+
};
|
|
1533
|
+
const update = (item, change) => store.update(item.id, change);
|
|
1534
|
+
const startPhase = (item, name) => update(item, (record) => ({
|
|
1535
|
+
...record,
|
|
1536
|
+
phases: [
|
|
1537
|
+
...record.phases,
|
|
1538
|
+
{ name, startedAt: timestamp(), finishedAt: null, outcome: "running" }
|
|
1539
|
+
]
|
|
1540
|
+
}));
|
|
1541
|
+
const finishPhase = (item, outcome) => update(item, (record) => ({
|
|
1542
|
+
...record,
|
|
1543
|
+
phases: record.phases.map((phase) => phase.outcome === "running" ? { ...phase, finishedAt: timestamp(), outcome } : phase)
|
|
1544
|
+
}));
|
|
1545
|
+
const skipPhase = (item, name) => update(item, (record) => ({
|
|
1546
|
+
...record,
|
|
1547
|
+
phases: [
|
|
1548
|
+
...record.phases,
|
|
1549
|
+
{
|
|
1550
|
+
name,
|
|
1551
|
+
startedAt: timestamp(),
|
|
1552
|
+
finishedAt: timestamp(),
|
|
1553
|
+
outcome: "skipped"
|
|
1554
|
+
}
|
|
1555
|
+
]
|
|
1556
|
+
}));
|
|
1557
|
+
const enter = (item, state, changes = {}) => update(item, (record) => ({ ...record, ...changes, state }));
|
|
1558
|
+
const requireNotCanceled = (item) => {
|
|
1559
|
+
if (item.canceled) {
|
|
1560
|
+
throw new Canceled;
|
|
1561
|
+
}
|
|
1562
|
+
};
|
|
1563
|
+
const blocker = () => operations.held() ? "the plant agent's upgrade" : operations.busy();
|
|
1564
|
+
const whenFree = async (item, run) => {
|
|
1565
|
+
const waitingFor = blocker();
|
|
1566
|
+
if (waitingFor) {
|
|
1567
|
+
say(item, "info", `Waiting for ${waitingFor} to finish`);
|
|
1568
|
+
}
|
|
1569
|
+
while (blocker()) {
|
|
1570
|
+
requireNotCanceled(item);
|
|
1571
|
+
await delay(retryMs);
|
|
1572
|
+
}
|
|
1573
|
+
return operations.exclusive("a deployment", run);
|
|
1574
|
+
};
|
|
1575
|
+
const awaitApproval = async (item, reason, message) => {
|
|
1576
|
+
if (!item.waitsForApproval) {
|
|
1577
|
+
throw new AgentError(message, 409, {
|
|
1578
|
+
downloadRequired: reason === "downloadRequired"
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
item.approved = false;
|
|
1582
|
+
item.running = false;
|
|
1583
|
+
say(item, "warning", message);
|
|
1584
|
+
await enter(item, "awaitingApproval", { approval: { reason, message } });
|
|
1585
|
+
return null;
|
|
1586
|
+
};
|
|
1587
|
+
const prepare = async (item) => {
|
|
1588
|
+
const warnings = await controller.ready();
|
|
1589
|
+
const target = await state.requireTarget();
|
|
1590
|
+
const config = await withSecrets(controllerConfig(item.release, target, state.paths.controller, context.codesys), await readSecrets(item.release.manifest.secrets), state.paths.sources);
|
|
1591
|
+
await controller.settle(config);
|
|
1592
|
+
return { config, warnings };
|
|
1593
|
+
};
|
|
1594
|
+
const progress = (item) => (message) => say(item, "info", message);
|
|
1595
|
+
const review = async (item, config) => {
|
|
1596
|
+
const { mode } = recordOf(item.id);
|
|
1597
|
+
await startPhase(item, "review");
|
|
1598
|
+
const result = await controller.review(config, {
|
|
1599
|
+
credentials: await controllerCredentials(item.credentials),
|
|
1600
|
+
onProgress: progress(item)
|
|
1601
|
+
});
|
|
1602
|
+
await update(item, (record) => ({ ...record, findings: result.findings }));
|
|
1603
|
+
await finishPhase(item, "ok");
|
|
1604
|
+
for (const finding of result.findings) {
|
|
1605
|
+
say(item, finding.refuses ? "warning" : "info", describeFinding(finding));
|
|
1606
|
+
}
|
|
1607
|
+
requireNotCanceled(item);
|
|
1608
|
+
if (!result.possible) {
|
|
1609
|
+
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`);
|
|
1610
|
+
}
|
|
1611
|
+
if (mode === "review") {
|
|
1612
|
+
return awaitApproval(item, "review", "Review the online change's findings, then approve it to apply");
|
|
1613
|
+
}
|
|
1614
|
+
return config;
|
|
1615
|
+
};
|
|
1616
|
+
const build = async (item) => {
|
|
1617
|
+
await finishPhase(item, "ok");
|
|
1618
|
+
await enter(item, "building");
|
|
1619
|
+
await startPhase(item, "build");
|
|
1620
|
+
const { config, warnings } = await prepare(item);
|
|
1621
|
+
for (const warning of warnings) {
|
|
1622
|
+
say(item, "warning", warning);
|
|
1623
|
+
}
|
|
1624
|
+
const { operation, mode } = recordOf(item.id);
|
|
1625
|
+
const baseline = operation === "download" ? "valid" : await controller.baseline();
|
|
1626
|
+
await finishPhase(item, "ok");
|
|
1627
|
+
requireNotCanceled(item);
|
|
1628
|
+
if (baseline !== "valid") {
|
|
1629
|
+
await skipPhase(item, "review");
|
|
1630
|
+
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");
|
|
1631
|
+
}
|
|
1632
|
+
if (operation === "online-change") {
|
|
1633
|
+
return review(item, config);
|
|
1634
|
+
}
|
|
1635
|
+
await skipPhase(item, "review");
|
|
1636
|
+
if (mode === "review") {
|
|
1637
|
+
return awaitApproval(item, "review", "Approve it to apply as a full download, which stops the application");
|
|
1638
|
+
}
|
|
1639
|
+
return config;
|
|
1640
|
+
};
|
|
1641
|
+
const apply = async (item, config) => {
|
|
1642
|
+
requireNotCanceled(item);
|
|
1643
|
+
const { operation } = recordOf(item.id);
|
|
1644
|
+
await enter(item, "applying", { approval: null });
|
|
1645
|
+
await startPhase(item, "apply");
|
|
1646
|
+
say(item, "info", `Starting the ${operation}`);
|
|
1647
|
+
const receipt = await controller.apply(config, operation, {
|
|
1648
|
+
initializeUser: item.initializeUser,
|
|
1649
|
+
credentials: await controllerCredentials(item.credentials),
|
|
1650
|
+
onProgress: progress(item)
|
|
1651
|
+
}).catch(async (error) => {
|
|
1652
|
+
if (operation === "download" || !requiresDownload(error)) {
|
|
1653
|
+
throw error;
|
|
1654
|
+
}
|
|
1655
|
+
await finishPhase(item, "failed");
|
|
1656
|
+
if (error instanceof DownloadRequiredError) {
|
|
1657
|
+
await update(item, (record) => ({
|
|
1658
|
+
...record,
|
|
1659
|
+
findings: error.findings
|
|
1660
|
+
}));
|
|
1661
|
+
}
|
|
1662
|
+
return awaitApproval(item, "downloadRequired", errorMessage(error));
|
|
1663
|
+
});
|
|
1664
|
+
if (!receipt) {
|
|
1665
|
+
return null;
|
|
1666
|
+
}
|
|
1667
|
+
await update(item, (record) => ({
|
|
1668
|
+
...record,
|
|
1669
|
+
controllerIds: receipt.controllerIds
|
|
1670
|
+
}));
|
|
1671
|
+
await finishPhase(item, "ok");
|
|
1672
|
+
return receipt;
|
|
1673
|
+
};
|
|
1674
|
+
const startServer = async (item, serverPath) => {
|
|
1675
|
+
if (!serverPath) {
|
|
1676
|
+
await skipPhase(item, "server");
|
|
1677
|
+
return;
|
|
1678
|
+
}
|
|
1679
|
+
await startPhase(item, "server");
|
|
1680
|
+
say(item, "info", "Starting the new server");
|
|
1681
|
+
const failure = await context.server.replace(join7(state.paths.releases, serverPath)).then(() => {
|
|
1682
|
+
return;
|
|
1683
|
+
}, (error) => errorMessage(error));
|
|
1684
|
+
await finishPhase(item, failure === undefined ? "ok" : "failed");
|
|
1685
|
+
return failure;
|
|
1686
|
+
};
|
|
1687
|
+
const activate = async (item) => {
|
|
1688
|
+
const at = timestamp();
|
|
1689
|
+
const { current } = activeDeployments(store.list());
|
|
1690
|
+
if (current && current !== item.id) {
|
|
1691
|
+
await store.update(current, (record) => ({
|
|
1692
|
+
...record,
|
|
1693
|
+
activeUntil: at
|
|
1694
|
+
}));
|
|
1695
|
+
}
|
|
1696
|
+
await update(item, (record) => ({
|
|
1697
|
+
...record,
|
|
1698
|
+
activeFrom: at,
|
|
1699
|
+
activeUntil: null
|
|
1700
|
+
}));
|
|
1701
|
+
};
|
|
1702
|
+
const start = async (item, receipt) => {
|
|
1703
|
+
const { release } = item;
|
|
1704
|
+
const record = recordOf(item.id);
|
|
1705
|
+
await enter(item, "starting");
|
|
1706
|
+
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
1707
|
+
const previous = await state.release();
|
|
1708
|
+
const serverFailure = await startServer(item, serverPath);
|
|
1709
|
+
const deployed = {
|
|
1710
|
+
id: release.id,
|
|
1711
|
+
deployedAt: timestamp(),
|
|
1712
|
+
operation: record.operation,
|
|
1713
|
+
controllerIds: receipt.controllerIds,
|
|
1714
|
+
server: serverFailure === undefined ? serverPath ?? previous?.server : previous?.server
|
|
1715
|
+
};
|
|
1716
|
+
await state.setRelease(deployed);
|
|
1717
|
+
item.deployed = deployed;
|
|
1718
|
+
const line = {
|
|
1719
|
+
at: deployed.deployedAt,
|
|
1720
|
+
release: release.id,
|
|
1721
|
+
...record.build !== null && { build: record.build },
|
|
1722
|
+
operation: record.operation,
|
|
1723
|
+
credentials: item.credentials ? "provided" : "stored",
|
|
1724
|
+
...record.requestedBy.user !== null && {
|
|
1725
|
+
user: record.requestedBy.user
|
|
1726
|
+
},
|
|
1727
|
+
...record.requestedBy.host !== null && {
|
|
1728
|
+
host: record.requestedBy.host
|
|
1729
|
+
}
|
|
1730
|
+
};
|
|
1731
|
+
await appendJsonl(state.paths.deployments, line);
|
|
1732
|
+
await activate(item);
|
|
1733
|
+
context.onActivated();
|
|
1734
|
+
if (serverFailure !== undefined) {
|
|
1735
|
+
throw new Error(`The controller runs release ${release.id}. ${serverFailure}`);
|
|
1736
|
+
}
|
|
1737
|
+
};
|
|
1738
|
+
const verify = async (item, receipt) => {
|
|
1739
|
+
await enter(item, "verifying");
|
|
1740
|
+
await startPhase(item, "health");
|
|
1741
|
+
const health = await checkHealth({
|
|
1742
|
+
controllerState: receipt.state,
|
|
1743
|
+
hasServer: item.release.manifest.server !== undefined,
|
|
1744
|
+
healthUrl: context.serverHealthUrl,
|
|
1745
|
+
server: context.server
|
|
1746
|
+
});
|
|
1747
|
+
await update(item, (record) => ({ ...record, health }));
|
|
1748
|
+
if (!healthy(health)) {
|
|
1749
|
+
throw new Error(health.detail ?? "The deployment isn't healthy");
|
|
1750
|
+
}
|
|
1751
|
+
await finishPhase(item, "ok");
|
|
1752
|
+
say(item, "info", health.detail ? `Ready. ${health.detail}` : "Ready");
|
|
1753
|
+
await enter(item, "ready");
|
|
1754
|
+
};
|
|
1755
|
+
const fail = async (item, error) => {
|
|
1756
|
+
if (error instanceof Canceled) {
|
|
1757
|
+
await finishPhase(item, "skipped");
|
|
1758
|
+
await enter(item, "canceled", { approval: null });
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
item.failure = { error };
|
|
1762
|
+
context.log(`Deployment ${item.id} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1763
|
+
await finishPhase(item, "failed");
|
|
1764
|
+
say(item, "error", errorMessage(error));
|
|
1765
|
+
const rollback = transferRollback(error);
|
|
1766
|
+
await enter(item, "error", {
|
|
1767
|
+
approval: null,
|
|
1768
|
+
error: {
|
|
1769
|
+
message: errorMessage(error),
|
|
1770
|
+
downloadRequired: requiresDownload(error),
|
|
1771
|
+
...rollback && { rollback }
|
|
1772
|
+
}
|
|
1773
|
+
});
|
|
1774
|
+
};
|
|
1775
|
+
const prune = () => withReleases(async () => {
|
|
1776
|
+
const pruned = await pruneDeployments({
|
|
1777
|
+
store,
|
|
1778
|
+
releases: state.paths.releases,
|
|
1779
|
+
deployed: await state.release(),
|
|
1780
|
+
now: context.now
|
|
1781
|
+
});
|
|
1782
|
+
if (pruned.deployments.length || pruned.releases.length) {
|
|
1783
|
+
context.log(`Removed ${pruned.deployments.length} deployments and ${pruned.releases.length} releases older than the retention`);
|
|
610
1784
|
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
1785
|
+
}).catch((error) => context.log(`Pruning deployments failed: ${errorMessage(error)}`));
|
|
1786
|
+
const waitsForPerson = (item) => recordOf(item.id).state === "awaitingApproval" && !item.approved;
|
|
1787
|
+
const settle = (item) => {
|
|
1788
|
+
if (recordOf(item.id).state === "awaitingApproval") {
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
pending.delete(item.id);
|
|
1792
|
+
const index = queue.indexOf(item);
|
|
1793
|
+
if (index >= 0) {
|
|
1794
|
+
queue.splice(index, 1);
|
|
1795
|
+
}
|
|
1796
|
+
prune();
|
|
1797
|
+
};
|
|
1798
|
+
const advance = async (item, lock) => {
|
|
1799
|
+
item.running = true;
|
|
1800
|
+
try {
|
|
1801
|
+
await lock(async () => {
|
|
1802
|
+
requireNotCanceled(item);
|
|
1803
|
+
const config = recordOf(item.id).state === "queued" ? await build(item) : (await prepare(item)).config;
|
|
1804
|
+
if (!config) {
|
|
1805
|
+
return;
|
|
626
1806
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
1807
|
+
const receipt = await apply(item, config);
|
|
1808
|
+
if (!receipt) {
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
await start(item, receipt);
|
|
1812
|
+
await verify(item, receipt);
|
|
1813
|
+
});
|
|
1814
|
+
} catch (error) {
|
|
1815
|
+
await fail(item, error).catch((failure) => context.log(`Recording deployment ${item.id}'s failure failed: ${errorMessage(failure)}`));
|
|
1816
|
+
} finally {
|
|
1817
|
+
item.running = false;
|
|
1818
|
+
}
|
|
1819
|
+
settle(item);
|
|
1820
|
+
};
|
|
1821
|
+
const advanceQueue = async () => {
|
|
1822
|
+
const [head] = queue;
|
|
1823
|
+
if (!head || waitsForPerson(head)) {
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
await advance(head, (run) => whenFree(head, run));
|
|
1827
|
+
return advanceQueue();
|
|
1828
|
+
};
|
|
1829
|
+
const drain = async () => {
|
|
1830
|
+
if (draining) {
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
draining = true;
|
|
1834
|
+
try {
|
|
1835
|
+
await advanceQueue();
|
|
1836
|
+
} finally {
|
|
1837
|
+
draining = false;
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
const create = async (release, origin, submission, waitsForApproval) => {
|
|
1841
|
+
const at = timestamp();
|
|
1842
|
+
const record = {
|
|
1843
|
+
id: store.newId(),
|
|
1844
|
+
release: release.id,
|
|
1845
|
+
build: await releaseBuild(release),
|
|
1846
|
+
createdAt: at,
|
|
1847
|
+
updatedAt: at,
|
|
1848
|
+
origin,
|
|
1849
|
+
git: submission.git,
|
|
1850
|
+
requestedBy: submission.requestedBy,
|
|
1851
|
+
mode: submission.mode,
|
|
1852
|
+
operation: submission.download ? "download" : "online-change",
|
|
1853
|
+
state: "queued",
|
|
1854
|
+
phases: [
|
|
1855
|
+
{ name: "queue", startedAt: at, finishedAt: null, outcome: "running" }
|
|
636
1856
|
],
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
1857
|
+
findings: [],
|
|
1858
|
+
approval: null,
|
|
1859
|
+
error: null,
|
|
1860
|
+
controllerIds: null,
|
|
1861
|
+
health: null,
|
|
1862
|
+
activeFrom: null,
|
|
1863
|
+
activeUntil: null
|
|
1864
|
+
};
|
|
1865
|
+
await store.create(record);
|
|
1866
|
+
const item = {
|
|
1867
|
+
id: record.id,
|
|
1868
|
+
release,
|
|
1869
|
+
credentials: submission.credentials,
|
|
1870
|
+
initializeUser: submission.initializeUser,
|
|
1871
|
+
waitsForApproval,
|
|
1872
|
+
canceled: false,
|
|
1873
|
+
approved: false,
|
|
1874
|
+
running: false,
|
|
1875
|
+
deployed: null,
|
|
1876
|
+
failure: null
|
|
1877
|
+
};
|
|
1878
|
+
pending.set(item.id, item);
|
|
1879
|
+
return item;
|
|
1880
|
+
};
|
|
1881
|
+
const announce = (item, warnings) => {
|
|
1882
|
+
for (const warning of warnings) {
|
|
1883
|
+
say(item, "warning", warning);
|
|
1884
|
+
}
|
|
1885
|
+
};
|
|
1886
|
+
const enqueue = (item, warnings) => {
|
|
1887
|
+
announce(item, warnings);
|
|
1888
|
+
queue.push(item);
|
|
1889
|
+
drain();
|
|
1890
|
+
return recordOf(item.id);
|
|
1891
|
+
};
|
|
1892
|
+
const checkSubmission = async (credentials) => {
|
|
1893
|
+
await state.requireTarget();
|
|
1894
|
+
await controllerCredentials(credentials);
|
|
1895
|
+
};
|
|
1896
|
+
const again = async (id, origin, mode, requestedBy) => {
|
|
1897
|
+
const source = recordOf(id);
|
|
1898
|
+
await checkSubmission(null);
|
|
1899
|
+
return withReleases(async () => {
|
|
1900
|
+
const release = await loadRelease(state.paths.releases, source.release).catch(() => {
|
|
1901
|
+
throw new AgentError(`The release of ${id}, ${source.release}, is no longer stored`, 409);
|
|
1902
|
+
});
|
|
1903
|
+
const item = await create(release, origin, {
|
|
1904
|
+
git: source.git,
|
|
1905
|
+
requestedBy,
|
|
1906
|
+
mode,
|
|
1907
|
+
download: false,
|
|
1908
|
+
credentials: null,
|
|
1909
|
+
initializeUser: false,
|
|
1910
|
+
warnings: []
|
|
1911
|
+
}, true);
|
|
1912
|
+
return enqueue(item, []);
|
|
643
1913
|
});
|
|
644
|
-
return { debug, handle: createDebugHandler(debug, log) };
|
|
645
1914
|
};
|
|
646
|
-
const startOrLog = () => start().catch((error) => {
|
|
647
|
-
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
648
|
-
return null;
|
|
649
|
-
});
|
|
650
|
-
let current = startOrLog();
|
|
651
1915
|
return {
|
|
652
|
-
|
|
653
|
-
const
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
1916
|
+
start: async () => {
|
|
1917
|
+
for (const record of store.list().filter((entry) => !isFinished(entry))) {
|
|
1918
|
+
await store.update(record.id, (unfinished) => ({
|
|
1919
|
+
...unfinished,
|
|
1920
|
+
state: "error",
|
|
1921
|
+
approval: null,
|
|
1922
|
+
phases: unfinished.phases.map((phase) => phase.outcome === "running" ? { ...phase, finishedAt: timestamp(), outcome: "failed" } : phase),
|
|
1923
|
+
error: {
|
|
1924
|
+
message: "The plant agent stopped before this deployment finished",
|
|
1925
|
+
downloadRequired: false
|
|
1926
|
+
}
|
|
1927
|
+
}));
|
|
658
1928
|
}
|
|
659
|
-
|
|
1929
|
+
await prune();
|
|
660
1930
|
},
|
|
661
|
-
|
|
662
|
-
|
|
1931
|
+
submit: async (upload, submission) => {
|
|
1932
|
+
await checkSubmission(submission.credentials);
|
|
1933
|
+
return withReleases(async () => {
|
|
1934
|
+
const release = await saveRelease(state.paths.releases, upload);
|
|
1935
|
+
const item = await create(release, { kind: "upload" }, submission, true);
|
|
1936
|
+
return enqueue(item, submission.warnings);
|
|
1937
|
+
});
|
|
663
1938
|
},
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
1939
|
+
redeploy: (id, mode, requestedBy) => again(id, { kind: "redeploy", from: id }, mode, requestedBy),
|
|
1940
|
+
rollback: (id, requestedBy) => again(id, { kind: "rollback", from: id }, "apply", requestedBy),
|
|
1941
|
+
approve: async (id, download, by) => {
|
|
1942
|
+
const record = recordOf(id);
|
|
1943
|
+
const item = pending.get(id);
|
|
1944
|
+
if (!item || record.state !== "awaitingApproval" || item.approved) {
|
|
1945
|
+
throw new AgentError(`Deployment ${id} isn't awaiting approval`, 409);
|
|
1946
|
+
}
|
|
1947
|
+
if (record.approval?.reason === "downloadRequired" && !download) {
|
|
1948
|
+
throw new AgentError(`Only a full download can apply deployment ${id}; approve it with a download`, 409);
|
|
1949
|
+
}
|
|
1950
|
+
item.approved = true;
|
|
1951
|
+
say(item, "info", `${by} approved it${download ? " as a full download" : ""}`);
|
|
1952
|
+
const approved = await update(item, (current) => ({
|
|
1953
|
+
...current,
|
|
1954
|
+
operation: download ? "download" : current.operation
|
|
1955
|
+
}));
|
|
1956
|
+
drain();
|
|
1957
|
+
return approved;
|
|
1958
|
+
},
|
|
1959
|
+
cancel: async (id, by) => {
|
|
1960
|
+
const record = recordOf(id);
|
|
1961
|
+
const item = pending.get(id);
|
|
1962
|
+
if (!item || !cancelable.includes(record.state)) {
|
|
1963
|
+
throw new AgentError(`Deployment ${id} is ${record.state}; a deployment can only be canceled before it applies`, 409);
|
|
1964
|
+
}
|
|
1965
|
+
item.canceled = true;
|
|
1966
|
+
say(item, "info", `${by} canceled it`);
|
|
1967
|
+
if (item.running) {
|
|
1968
|
+
return record;
|
|
1969
|
+
}
|
|
1970
|
+
const index = queue.indexOf(item);
|
|
1971
|
+
if (index >= 0) {
|
|
1972
|
+
queue.splice(index, 1);
|
|
1973
|
+
}
|
|
1974
|
+
await fail(item, new Canceled);
|
|
1975
|
+
settle(item);
|
|
1976
|
+
drain();
|
|
1977
|
+
return recordOf(id);
|
|
1978
|
+
},
|
|
1979
|
+
requireIdle: () => {
|
|
1980
|
+
const [head] = queue;
|
|
1981
|
+
if (!head) {
|
|
1982
|
+
return;
|
|
1983
|
+
}
|
|
1984
|
+
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);
|
|
1985
|
+
},
|
|
1986
|
+
runNow: async (upload, submission, onLine) => {
|
|
1987
|
+
const item = await withReleases(async () => create(await saveRelease(state.paths.releases, upload), { kind: "upload" }, submission, false));
|
|
1988
|
+
const unsubscribe = store.subscribe(item.id, (event) => {
|
|
1989
|
+
if (event.kind === "log") {
|
|
1990
|
+
onLine(event.line);
|
|
1991
|
+
}
|
|
668
1992
|
});
|
|
1993
|
+
try {
|
|
1994
|
+
announce(item, submission.warnings);
|
|
1995
|
+
await advance(item, (run) => run());
|
|
1996
|
+
await store.flush(item.id);
|
|
1997
|
+
} finally {
|
|
1998
|
+
unsubscribe();
|
|
1999
|
+
}
|
|
2000
|
+
if (item.failure) {
|
|
2001
|
+
throw item.failure.error;
|
|
2002
|
+
}
|
|
2003
|
+
if (!item.deployed) {
|
|
2004
|
+
throw new AgentError(`Deployment ${item.id} was canceled`, 409);
|
|
2005
|
+
}
|
|
2006
|
+
return item.deployed;
|
|
669
2007
|
},
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
2008
|
+
list: () => {
|
|
2009
|
+
const deployments = store.list();
|
|
2010
|
+
return { deployments, ...activeDeployments(deployments) };
|
|
2011
|
+
},
|
|
2012
|
+
get: recordOf,
|
|
2013
|
+
lines: (id, after) => {
|
|
2014
|
+
recordOf(id);
|
|
2015
|
+
return store.lines(id, after);
|
|
2016
|
+
},
|
|
2017
|
+
subscribe: (id, listener) => store.subscribe(id, listener),
|
|
2018
|
+
source: (id) => listReleaseFiles(state.paths.releases, recordOf(id).release),
|
|
2019
|
+
sourceFile: (id, path) => readReleaseFile(state.paths.releases, recordOf(id).release, path)
|
|
673
2020
|
};
|
|
674
2021
|
};
|
|
675
2022
|
|
|
676
2023
|
// packages/agent/src/deploy.ts
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
2024
|
+
var clientWarnings = async (clientTsplc) => {
|
|
2025
|
+
if (clientTsplc.version === undefined) {
|
|
2026
|
+
return [
|
|
2027
|
+
`the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`
|
|
2028
|
+
];
|
|
2029
|
+
}
|
|
2030
|
+
if (clientTsplc.version !== tsplcVersion) {
|
|
2031
|
+
throw new AgentError(versionMismatch({
|
|
2032
|
+
agent: tsplcVersion,
|
|
2033
|
+
client: clientTsplc.version,
|
|
2034
|
+
agentUpgrades: true
|
|
2035
|
+
}), 409);
|
|
2036
|
+
}
|
|
2037
|
+
if (clientTsplc.scripts !== undefined && clientTsplc.scripts !== await workerScriptsDigest()) {
|
|
2038
|
+
return [
|
|
2039
|
+
`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`
|
|
2040
|
+
];
|
|
2041
|
+
}
|
|
2042
|
+
return [];
|
|
2043
|
+
};
|
|
2044
|
+
var requester = (identity, client) => ({
|
|
2045
|
+
identity: { login: identity.login, name: identity.name, via: identity.via },
|
|
2046
|
+
user: client.user ?? null,
|
|
2047
|
+
host: client.host ?? null
|
|
2048
|
+
});
|
|
2049
|
+
var createDeployments = async (context) => {
|
|
2050
|
+
const { state } = context;
|
|
691
2051
|
const warming = (async () => {
|
|
692
2052
|
const deployed = await state.release();
|
|
693
2053
|
const target = await state.target();
|
|
@@ -701,7 +2061,48 @@ var createDeployments = (context) => {
|
|
|
701
2061
|
})().catch((error) => {
|
|
702
2062
|
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
703
2063
|
});
|
|
2064
|
+
const controller = {
|
|
2065
|
+
ready: async () => {
|
|
2066
|
+
const builder = await requireBuilder();
|
|
2067
|
+
if (await findControllerLogin(loginContainer)) {
|
|
2068
|
+
throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
|
|
2069
|
+
}
|
|
2070
|
+
return builder.kind === "unverified" ? [
|
|
2071
|
+
`${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`
|
|
2072
|
+
] : [];
|
|
2073
|
+
},
|
|
2074
|
+
settle: (config) => settleWarmController(config, deployContainer),
|
|
2075
|
+
baseline: () => controllerBaseline(state.paths.controller),
|
|
2076
|
+
review: async (config, options) => {
|
|
2077
|
+
await ensureGateway();
|
|
2078
|
+
await warming;
|
|
2079
|
+
return reviewWarmController(config, deployContainer, options);
|
|
2080
|
+
},
|
|
2081
|
+
apply: async (config, operation, options) => {
|
|
2082
|
+
await ensureGateway();
|
|
2083
|
+
await warming;
|
|
2084
|
+
return updateWarmController(config, deployContainer, operation, options);
|
|
2085
|
+
}
|
|
2086
|
+
};
|
|
2087
|
+
const runner = createDeploymentRunner({
|
|
2088
|
+
store: await openDeploymentStore({
|
|
2089
|
+
directory: state.paths.deploymentRecords,
|
|
2090
|
+
now: context.now,
|
|
2091
|
+
log: context.log
|
|
2092
|
+
}),
|
|
2093
|
+
state,
|
|
2094
|
+
operations: context.operations,
|
|
2095
|
+
codesys: context.codesys,
|
|
2096
|
+
server: context.server,
|
|
2097
|
+
controller,
|
|
2098
|
+
serverHealthUrl: context.serverHealthUrl,
|
|
2099
|
+
onActivated: () => context.debugging.restart(),
|
|
2100
|
+
now: context.now,
|
|
2101
|
+
log: context.log
|
|
2102
|
+
});
|
|
2103
|
+
await runner.start();
|
|
704
2104
|
return {
|
|
2105
|
+
runner,
|
|
705
2106
|
retire: async () => {
|
|
706
2107
|
await warming;
|
|
707
2108
|
const deployed = await state.release();
|
|
@@ -711,94 +2112,228 @@ var createDeployments = (context) => {
|
|
|
711
2112
|
}
|
|
712
2113
|
await removeContainer(deployContainer);
|
|
713
2114
|
},
|
|
714
|
-
deploy: async (readRequest, client, clientTsplc) => {
|
|
715
|
-
|
|
716
|
-
throw new AgentError(versionMismatch({
|
|
717
|
-
agent: tsplcVersion,
|
|
718
|
-
client: clientTsplc.version,
|
|
719
|
-
agentUpgrades: true
|
|
720
|
-
}), 409);
|
|
721
|
-
}
|
|
2115
|
+
deploy: async (readRequest, identity, client, clientTsplc) => {
|
|
2116
|
+
const warnings = await clientWarnings(clientTsplc);
|
|
722
2117
|
context.operations.requireIdle();
|
|
723
|
-
|
|
2118
|
+
runner.requireIdle();
|
|
2119
|
+
await requireBuilder();
|
|
724
2120
|
const { settings, upload } = await readRequest();
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
2121
|
+
await state.requireTarget();
|
|
2122
|
+
await controllerCredentials(settings.credentials);
|
|
2123
|
+
await readSecrets(upload.manifest.secrets);
|
|
2124
|
+
return context.operations.stream("a deployment", (emit) => runner.runNow(upload, {
|
|
2125
|
+
git: settings.deployment?.git ?? null,
|
|
2126
|
+
requestedBy: requester(identity, client),
|
|
2127
|
+
mode: "apply",
|
|
2128
|
+
download: settings.download,
|
|
2129
|
+
credentials: settings.credentials,
|
|
2130
|
+
initializeUser: settings.initializeUser,
|
|
2131
|
+
warnings
|
|
2132
|
+
}, (line) => {
|
|
2133
|
+
if (line.level === "error") {
|
|
2134
|
+
return;
|
|
738
2135
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
2136
|
+
emit({
|
|
2137
|
+
kind: "progress",
|
|
2138
|
+
message: line.level === "warning" ? `Warning: ${line.message}` : line.message
|
|
2139
|
+
});
|
|
2140
|
+
}), { reportsRollback: clientTsplc.version !== undefined });
|
|
2141
|
+
}
|
|
2142
|
+
};
|
|
2143
|
+
};
|
|
2144
|
+
|
|
2145
|
+
// packages/agent/src/deployments/routes.ts
|
|
2146
|
+
import { z as z6 } from "zod";
|
|
2147
|
+
var heartbeatMs = 15000;
|
|
2148
|
+
var afterSchema = z6.coerce.number().int().nonnegative();
|
|
2149
|
+
var after = (request) => afterSchema.parse(new URL(request.url).searchParams.get("after") ?? request.headers.get("last-event-id") ?? 0);
|
|
2150
|
+
var eventStream = (runner, id, from) => {
|
|
2151
|
+
runner.get(id);
|
|
2152
|
+
const encoder = new TextEncoder;
|
|
2153
|
+
const stream = {
|
|
2154
|
+
open: true,
|
|
2155
|
+
sent: from,
|
|
2156
|
+
held: [],
|
|
2157
|
+
stop: () => {}
|
|
2158
|
+
};
|
|
2159
|
+
return new Response(new ReadableStream({
|
|
2160
|
+
start: async (controller) => {
|
|
2161
|
+
const write = (text) => {
|
|
2162
|
+
if (stream.open) {
|
|
2163
|
+
controller.enqueue(encoder.encode(text));
|
|
749
2164
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
if (baseline !== "valid") {
|
|
755
|
-
throw new AgentError(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", 409, { downloadRequired: true });
|
|
2165
|
+
};
|
|
2166
|
+
const sendLine = (line) => {
|
|
2167
|
+
if (line.seq <= stream.sent) {
|
|
2168
|
+
return;
|
|
756
2169
|
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
if (serverPath) {
|
|
769
|
-
emit({ kind: "progress", message: "Starting the new server" });
|
|
2170
|
+
stream.sent = line.seq;
|
|
2171
|
+
write(`id: ${line.seq}
|
|
2172
|
+
event: log
|
|
2173
|
+
data: ${JSON.stringify(line)}
|
|
2174
|
+
|
|
2175
|
+
`);
|
|
2176
|
+
};
|
|
2177
|
+
const end = () => {
|
|
2178
|
+
if (stream.open) {
|
|
2179
|
+
stream.stop();
|
|
2180
|
+
controller.close();
|
|
770
2181
|
}
|
|
771
|
-
|
|
2182
|
+
};
|
|
2183
|
+
const sendRecord = (record) => write(`event: record
|
|
2184
|
+
data: ${JSON.stringify(record)}
|
|
2185
|
+
|
|
2186
|
+
`);
|
|
2187
|
+
const finish = () => runner.lines(id, stream.sent).then((lines) => {
|
|
2188
|
+
lines.forEach(sendLine);
|
|
2189
|
+
sendRecord(runner.get(id));
|
|
2190
|
+
end();
|
|
2191
|
+
}, end);
|
|
2192
|
+
const deliver = (event) => {
|
|
2193
|
+
if (event.kind === "log") {
|
|
2194
|
+
sendLine(event.line);
|
|
2195
|
+
return;
|
|
2196
|
+
}
|
|
2197
|
+
if (isFinished(event.record)) {
|
|
2198
|
+
finish();
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
sendRecord(event.record);
|
|
2202
|
+
};
|
|
2203
|
+
const unsubscribe = runner.subscribe(id, (event) => {
|
|
2204
|
+
if (stream.held) {
|
|
2205
|
+
stream.held.push(event);
|
|
772
2206
|
return;
|
|
773
|
-
}, (error) => errorMessage(error)) : undefined;
|
|
774
|
-
const deployed = {
|
|
775
|
-
id: release.id,
|
|
776
|
-
deployedAt: new Date().toISOString(),
|
|
777
|
-
operation: kind,
|
|
778
|
-
controllerIds: receipt.controllerIds,
|
|
779
|
-
server: serverFailure === undefined ? serverPath ?? previous?.server : previous?.server
|
|
780
|
-
};
|
|
781
|
-
await state.setRelease(deployed);
|
|
782
|
-
const debugManifest = join5(release.directory, debugManifestFile2);
|
|
783
|
-
const deployment = {
|
|
784
|
-
at: deployed.deployedAt,
|
|
785
|
-
release: release.id,
|
|
786
|
-
...existsSync4(debugManifest) && {
|
|
787
|
-
build: (await loadManifest2(debugManifest)).build.id
|
|
788
|
-
},
|
|
789
|
-
operation: kind,
|
|
790
|
-
credentials: settings.credentials ? "provided" : "stored",
|
|
791
|
-
...client
|
|
792
|
-
};
|
|
793
|
-
await appendJsonl(state.paths.deployments, deployment);
|
|
794
|
-
context.debugging.restart();
|
|
795
|
-
if (serverFailure !== undefined) {
|
|
796
|
-
throw new Error(`The controller runs release ${release.id}. ${serverFailure}`);
|
|
797
2207
|
}
|
|
798
|
-
|
|
799
|
-
}
|
|
2208
|
+
deliver(event);
|
|
2209
|
+
});
|
|
2210
|
+
const heartbeat = setInterval(() => write(`: heartbeat
|
|
2211
|
+
|
|
2212
|
+
`), heartbeatMs);
|
|
2213
|
+
stream.stop = () => {
|
|
2214
|
+
stream.open = false;
|
|
2215
|
+
clearInterval(heartbeat);
|
|
2216
|
+
unsubscribe();
|
|
2217
|
+
};
|
|
2218
|
+
if (!isFinished(runner.get(id))) {
|
|
2219
|
+
sendRecord(runner.get(id));
|
|
2220
|
+
}
|
|
2221
|
+
(await runner.lines(id, from)).forEach(sendLine);
|
|
2222
|
+
const held = stream.held ?? [];
|
|
2223
|
+
stream.held = null;
|
|
2224
|
+
held.forEach(deliver);
|
|
2225
|
+
if (isFinished(runner.get(id))) {
|
|
2226
|
+
finish();
|
|
2227
|
+
}
|
|
2228
|
+
},
|
|
2229
|
+
cancel: () => stream.stop()
|
|
2230
|
+
}), {
|
|
2231
|
+
headers: {
|
|
2232
|
+
"Content-Type": "text/event-stream",
|
|
2233
|
+
"Cache-Control": "no-cache"
|
|
800
2234
|
}
|
|
801
|
-
};
|
|
2235
|
+
});
|
|
2236
|
+
};
|
|
2237
|
+
var createDeploymentRoutes = (context) => {
|
|
2238
|
+
const { runner } = context;
|
|
2239
|
+
const created = (request, record) => Response.json({
|
|
2240
|
+
id: record.id,
|
|
2241
|
+
url: `${new URL(request.url).origin}/deployments/${record.id}`
|
|
2242
|
+
}, { status: 202 });
|
|
2243
|
+
const id = (params) => params.id ?? "";
|
|
2244
|
+
return [
|
|
2245
|
+
{
|
|
2246
|
+
method: "POST",
|
|
2247
|
+
pattern: "/api/deployments",
|
|
2248
|
+
role: "deployer",
|
|
2249
|
+
handle: async (request, { identity }) => {
|
|
2250
|
+
const warnings = await clientWarnings(clientRelease(request));
|
|
2251
|
+
const { settings, upload } = await readDeployRequest(context.releases, request);
|
|
2252
|
+
const record = await runner.submit(upload, {
|
|
2253
|
+
git: settings.deployment?.git ?? null,
|
|
2254
|
+
requestedBy: requester(identity, clientIdentity(request)),
|
|
2255
|
+
mode: settings.deployment?.mode ?? "apply",
|
|
2256
|
+
download: settings.download,
|
|
2257
|
+
credentials: settings.credentials,
|
|
2258
|
+
initializeUser: settings.initializeUser,
|
|
2259
|
+
warnings
|
|
2260
|
+
});
|
|
2261
|
+
return created(request, record);
|
|
2262
|
+
}
|
|
2263
|
+
},
|
|
2264
|
+
{
|
|
2265
|
+
method: "GET",
|
|
2266
|
+
pattern: "/api/deployments",
|
|
2267
|
+
role: "viewer",
|
|
2268
|
+
handle: async () => Response.json(runner.list())
|
|
2269
|
+
},
|
|
2270
|
+
{
|
|
2271
|
+
method: "GET",
|
|
2272
|
+
pattern: "/api/deployments/:id",
|
|
2273
|
+
role: "viewer",
|
|
2274
|
+
handle: async (_request, { params }) => Response.json(runner.get(id(params)))
|
|
2275
|
+
},
|
|
2276
|
+
{
|
|
2277
|
+
method: "GET",
|
|
2278
|
+
pattern: "/api/deployments/:id/logs",
|
|
2279
|
+
role: "viewer",
|
|
2280
|
+
handle: async (request, { params }) => Response.json({
|
|
2281
|
+
lines: await runner.lines(id(params), after(request))
|
|
2282
|
+
})
|
|
2283
|
+
},
|
|
2284
|
+
{
|
|
2285
|
+
method: "GET",
|
|
2286
|
+
pattern: "/api/deployments/:id/events",
|
|
2287
|
+
role: "viewer",
|
|
2288
|
+
handle: async (request, { params }) => eventStream(runner, id(params), after(request))
|
|
2289
|
+
},
|
|
2290
|
+
{
|
|
2291
|
+
method: "POST",
|
|
2292
|
+
pattern: "/api/deployments/:id/approve",
|
|
2293
|
+
role: "deployer",
|
|
2294
|
+
handle: async (request, { identity, params }) => {
|
|
2295
|
+
const { download } = approveSchema.parse(await request.json());
|
|
2296
|
+
return Response.json(await runner.approve(id(params), download, identity.name));
|
|
2297
|
+
}
|
|
2298
|
+
},
|
|
2299
|
+
{
|
|
2300
|
+
method: "POST",
|
|
2301
|
+
pattern: "/api/deployments/:id/cancel",
|
|
2302
|
+
role: "deployer",
|
|
2303
|
+
handle: async (_request, { identity, params }) => Response.json(await runner.cancel(id(params), identity.name))
|
|
2304
|
+
},
|
|
2305
|
+
{
|
|
2306
|
+
method: "POST",
|
|
2307
|
+
pattern: "/api/deployments/:id/redeploy",
|
|
2308
|
+
role: "deployer",
|
|
2309
|
+
handle: async (request, { identity, params }) => {
|
|
2310
|
+
const { mode } = redeploySchema.parse(await request.json());
|
|
2311
|
+
return created(request, await runner.redeploy(id(params), mode, requester(identity, clientIdentity(request))));
|
|
2312
|
+
}
|
|
2313
|
+
},
|
|
2314
|
+
{
|
|
2315
|
+
method: "POST",
|
|
2316
|
+
pattern: "/api/deployments/:id/rollback",
|
|
2317
|
+
role: "deployer",
|
|
2318
|
+
handle: async (request, { identity, params }) => created(request, await runner.rollback(id(params), requester(identity, clientIdentity(request))))
|
|
2319
|
+
},
|
|
2320
|
+
{
|
|
2321
|
+
method: "GET",
|
|
2322
|
+
pattern: "/api/deployments/:id/source",
|
|
2323
|
+
role: "viewer",
|
|
2324
|
+
handle: async (_request, { params }) => Response.json({
|
|
2325
|
+
files: await runner.source(id(params))
|
|
2326
|
+
})
|
|
2327
|
+
},
|
|
2328
|
+
{
|
|
2329
|
+
method: "GET",
|
|
2330
|
+
pattern: "/api/deployments/:id/source/*",
|
|
2331
|
+
role: "viewer",
|
|
2332
|
+
handle: async (_request, { params }) => new Response(await runner.sourceFile(id(params), params["*"] ?? ""), {
|
|
2333
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
2334
|
+
})
|
|
2335
|
+
}
|
|
2336
|
+
];
|
|
802
2337
|
};
|
|
803
2338
|
|
|
804
2339
|
// packages/agent/src/discovery.ts
|
|
@@ -853,8 +2388,136 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
853
2388
|
return found;
|
|
854
2389
|
};
|
|
855
2390
|
|
|
2391
|
+
// packages/agent/src/environment.ts
|
|
2392
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
2393
|
+
import { readFile as readFile6, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
|
|
2394
|
+
import { join as join8 } from "node:path";
|
|
2395
|
+
import { tsplcConfigSchema as tsplcConfigSchema2 } from "@tsplc/config";
|
|
2396
|
+
import { z as z7 } from "zod";
|
|
2397
|
+
var secretName = tsplcConfigSchema2.shape.secrets.unwrap().shape.names.element;
|
|
2398
|
+
var environmentFile = (state) => join8(state, "environment.json");
|
|
2399
|
+
var storedNamesSchema = z7.record(z7.string(), z7.array(secretName));
|
|
2400
|
+
var createEnvironment = (context) => {
|
|
2401
|
+
const { state, audit } = context;
|
|
2402
|
+
const storedNames = async () => existsSync7(context.file) ? storedNamesSchema.parse(JSON.parse(await readFile6(context.file, "utf8"))) : {};
|
|
2403
|
+
const writeStoredNames = async (service, update) => {
|
|
2404
|
+
const stored = await storedNames();
|
|
2405
|
+
const names = update(stored[service] ?? []);
|
|
2406
|
+
await writeFile5(`${context.file}.tmp`, JSON.stringify({ ...stored, [service]: names }, null, 2));
|
|
2407
|
+
await rename5(`${context.file}.tmp`, context.file);
|
|
2408
|
+
};
|
|
2409
|
+
const declared = async () => {
|
|
2410
|
+
const release = await state.release();
|
|
2411
|
+
const secrets = release && (await loadRelease(state.paths.releases, release.id)).manifest.secrets;
|
|
2412
|
+
return secrets ? { service: secrets.service, names: secrets.names } : { service: environmentService, names: [] };
|
|
2413
|
+
};
|
|
2414
|
+
const isSet = async (service, name) => await Bun.secrets.get({ service, name }) !== null;
|
|
2415
|
+
const entries = async () => {
|
|
2416
|
+
const { service, names } = await declared();
|
|
2417
|
+
const stored = ((await storedNames())[service] ?? []).filter((name) => !names.includes(name));
|
|
2418
|
+
const undeclared = await Promise.all(stored.map(async (name) => ({
|
|
2419
|
+
name,
|
|
2420
|
+
declared: false,
|
|
2421
|
+
set: await isSet(service, name)
|
|
2422
|
+
})));
|
|
2423
|
+
return [
|
|
2424
|
+
...await Promise.all(names.map(async (name) => ({
|
|
2425
|
+
name,
|
|
2426
|
+
declared: true,
|
|
2427
|
+
set: await isSet(service, name)
|
|
2428
|
+
}))),
|
|
2429
|
+
...undeclared.filter(({ set }) => set)
|
|
2430
|
+
];
|
|
2431
|
+
};
|
|
2432
|
+
const record = (identity, command) => audit.record({
|
|
2433
|
+
identity,
|
|
2434
|
+
command,
|
|
2435
|
+
values: {},
|
|
2436
|
+
previous: null,
|
|
2437
|
+
error: null
|
|
2438
|
+
});
|
|
2439
|
+
const routes = [
|
|
2440
|
+
{
|
|
2441
|
+
method: "GET",
|
|
2442
|
+
pattern: "/api/environment",
|
|
2443
|
+
role: "viewer",
|
|
2444
|
+
handle: async () => Response.json(await entries())
|
|
2445
|
+
},
|
|
2446
|
+
{
|
|
2447
|
+
method: "PUT",
|
|
2448
|
+
pattern: "/api/environment/:name",
|
|
2449
|
+
role: "admin",
|
|
2450
|
+
handle: async (request, { identity, params }) => {
|
|
2451
|
+
const name = secretName.parse(params.name);
|
|
2452
|
+
const { value } = environmentValueSchema.parse(await request.json());
|
|
2453
|
+
const { service, names } = await declared();
|
|
2454
|
+
await Bun.secrets.set({ service, name, value });
|
|
2455
|
+
await writeStoredNames(service, (stored) => [
|
|
2456
|
+
...stored.filter((other) => other !== name),
|
|
2457
|
+
name
|
|
2458
|
+
]);
|
|
2459
|
+
await record(identity, `environment set ${name}`);
|
|
2460
|
+
const entry = {
|
|
2461
|
+
name,
|
|
2462
|
+
declared: names.includes(name),
|
|
2463
|
+
set: true
|
|
2464
|
+
};
|
|
2465
|
+
return Response.json(entry);
|
|
2466
|
+
}
|
|
2467
|
+
},
|
|
2468
|
+
{
|
|
2469
|
+
method: "DELETE",
|
|
2470
|
+
pattern: "/api/environment/:name",
|
|
2471
|
+
role: "admin",
|
|
2472
|
+
handle: async (_request, { identity, params }) => {
|
|
2473
|
+
const name = secretName.parse(params.name);
|
|
2474
|
+
const { service, names } = await declared();
|
|
2475
|
+
if (!await Bun.secrets.delete({ service, name })) {
|
|
2476
|
+
throw new AgentError(`${name} isn't set`, 404);
|
|
2477
|
+
}
|
|
2478
|
+
await writeStoredNames(service, (stored) => stored.filter((other) => other !== name));
|
|
2479
|
+
await record(identity, `environment delete ${name}`);
|
|
2480
|
+
const entry = {
|
|
2481
|
+
name,
|
|
2482
|
+
declared: names.includes(name),
|
|
2483
|
+
set: false
|
|
2484
|
+
};
|
|
2485
|
+
return Response.json(entry);
|
|
2486
|
+
}
|
|
2487
|
+
},
|
|
2488
|
+
{
|
|
2489
|
+
method: "POST",
|
|
2490
|
+
pattern: "/api/server/restart",
|
|
2491
|
+
role: "deployer",
|
|
2492
|
+
handle: async (_request, { identity }) => {
|
|
2493
|
+
const running = context.server.status();
|
|
2494
|
+
if (!running) {
|
|
2495
|
+
throw new AgentError("The deployed release runs no server", 409);
|
|
2496
|
+
}
|
|
2497
|
+
const failure = await context.operations.exclusive("a server restart", () => context.server.replace(running.executable)).then(() => null, (error) => error);
|
|
2498
|
+
if (failure instanceof AgentError) {
|
|
2499
|
+
throw failure;
|
|
2500
|
+
}
|
|
2501
|
+
await audit.record({
|
|
2502
|
+
identity,
|
|
2503
|
+
command: "server restart",
|
|
2504
|
+
values: {},
|
|
2505
|
+
previous: null,
|
|
2506
|
+
error: failure === null ? null : errorMessage(failure)
|
|
2507
|
+
});
|
|
2508
|
+
if (failure !== null) {
|
|
2509
|
+
context.log(`Restarting the server failed: ${errorMessage(failure)}`);
|
|
2510
|
+
throw new AgentError(errorMessage(failure), 500);
|
|
2511
|
+
}
|
|
2512
|
+
return Response.json(context.server.status());
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
];
|
|
2516
|
+
return { routes };
|
|
2517
|
+
};
|
|
2518
|
+
|
|
856
2519
|
// packages/agent/src/instance.ts
|
|
857
|
-
import { z as
|
|
2520
|
+
import { z as z8 } from "zod";
|
|
858
2521
|
|
|
859
2522
|
// packages/agent/src/processes.ts
|
|
860
2523
|
var isGone = (error) => error instanceof Error && ("code" in error) && error.code === "ESRCH";
|
|
@@ -877,21 +2540,21 @@ var signalProcess = (pid, name) => {
|
|
|
877
2540
|
};
|
|
878
2541
|
|
|
879
2542
|
// packages/agent/src/instance.ts
|
|
880
|
-
var instanceSchema =
|
|
881
|
-
pid:
|
|
882
|
-
version:
|
|
883
|
-
url:
|
|
884
|
-
serve:
|
|
885
|
-
supervised:
|
|
886
|
-
startedAt:
|
|
2543
|
+
var instanceSchema = z8.strictObject({
|
|
2544
|
+
pid: z8.int().positive(),
|
|
2545
|
+
version: z8.string(),
|
|
2546
|
+
url: z8.url(),
|
|
2547
|
+
serve: z8.array(z8.string()),
|
|
2548
|
+
supervised: z8.boolean(),
|
|
2549
|
+
startedAt: z8.iso.datetime()
|
|
887
2550
|
});
|
|
888
|
-
var exitSchema =
|
|
889
|
-
server:
|
|
890
|
-
restart:
|
|
2551
|
+
var exitSchema = z8.strictObject({
|
|
2552
|
+
server: z8.enum(["leave", "stop"]),
|
|
2553
|
+
restart: z8.boolean()
|
|
891
2554
|
});
|
|
892
2555
|
|
|
893
2556
|
// packages/agent/src/login.ts
|
|
894
|
-
import { setTimeout as
|
|
2557
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
895
2558
|
import {
|
|
896
2559
|
failureReason,
|
|
897
2560
|
findControllerLogin as findControllerLogin2,
|
|
@@ -1046,7 +2709,7 @@ var createLogin = (context) => {
|
|
|
1046
2709
|
try {
|
|
1047
2710
|
const loginState = await Promise.race([
|
|
1048
2711
|
send(login, { command: "state" }),
|
|
1049
|
-
|
|
2712
|
+
delay2(loginStateTimeout, null)
|
|
1050
2713
|
]);
|
|
1051
2714
|
if (!loginState) {
|
|
1052
2715
|
return stoppedAnswering;
|
|
@@ -1072,7 +2735,7 @@ var createLogin = (context) => {
|
|
|
1072
2735
|
};
|
|
1073
2736
|
|
|
1074
2737
|
// packages/agent/src/operations.ts
|
|
1075
|
-
import { requiresDownload, transferRollback } from "@tsplc/build";
|
|
2738
|
+
import { requiresDownload as requiresDownload2, transferRollback as transferRollback2 } from "@tsplc/build";
|
|
1076
2739
|
var createOperations = (log) => {
|
|
1077
2740
|
let busy;
|
|
1078
2741
|
let held = false;
|
|
@@ -1124,11 +2787,11 @@ var createOperations = (log) => {
|
|
|
1124
2787
|
emit({ kind: "done", result: await run(emit) });
|
|
1125
2788
|
} catch (error) {
|
|
1126
2789
|
log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1127
|
-
const rollback = reportsRollback ?
|
|
2790
|
+
const rollback = reportsRollback ? transferRollback2(error) : undefined;
|
|
1128
2791
|
emit({
|
|
1129
2792
|
kind: "error",
|
|
1130
2793
|
message: errorMessage(error),
|
|
1131
|
-
downloadRequired:
|
|
2794
|
+
downloadRequired: requiresDownload2(error),
|
|
1132
2795
|
...rollback && { rollback }
|
|
1133
2796
|
});
|
|
1134
2797
|
} finally {
|
|
@@ -1147,20 +2810,49 @@ var createOperations = (log) => {
|
|
|
1147
2810
|
};
|
|
1148
2811
|
};
|
|
1149
2812
|
|
|
2813
|
+
// packages/agent/src/routes.ts
|
|
2814
|
+
var matchRoute = (routes, method, pathname) => {
|
|
2815
|
+
const parts = pathname.split("/");
|
|
2816
|
+
for (const route of routes) {
|
|
2817
|
+
const pattern = route.pattern.split("/");
|
|
2818
|
+
const rest = pattern.at(-1) === "*";
|
|
2819
|
+
if (route.method !== method || (rest ? parts.length < pattern.length : pattern.length !== parts.length)) {
|
|
2820
|
+
continue;
|
|
2821
|
+
}
|
|
2822
|
+
const params = {};
|
|
2823
|
+
const matched = pattern.every((segment, index) => {
|
|
2824
|
+
const part = parts[index] ?? "";
|
|
2825
|
+
if (rest && index === pattern.length - 1) {
|
|
2826
|
+
params["*"] = parts.slice(index).map(decodeURIComponent).join("/");
|
|
2827
|
+
return part !== "";
|
|
2828
|
+
}
|
|
2829
|
+
if (segment.startsWith(":")) {
|
|
2830
|
+
params[segment.slice(1)] = decodeURIComponent(part);
|
|
2831
|
+
return part !== "";
|
|
2832
|
+
}
|
|
2833
|
+
return segment === part;
|
|
2834
|
+
});
|
|
2835
|
+
if (matched) {
|
|
2836
|
+
return { route, params };
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
return;
|
|
2840
|
+
};
|
|
2841
|
+
|
|
1150
2842
|
// packages/agent/src/server-process.ts
|
|
1151
2843
|
import {
|
|
1152
2844
|
closeSync,
|
|
1153
|
-
existsSync as
|
|
2845
|
+
existsSync as existsSync8,
|
|
1154
2846
|
openSync,
|
|
1155
2847
|
renameSync,
|
|
1156
2848
|
statSync,
|
|
1157
2849
|
writeFileSync
|
|
1158
2850
|
} from "node:fs";
|
|
1159
|
-
import { readFile as
|
|
2851
|
+
import { readFile as readFile7, rm as rm4 } from "node:fs/promises";
|
|
1160
2852
|
import { uptime } from "node:os";
|
|
1161
|
-
import { dirname as
|
|
1162
|
-
import { setTimeout as
|
|
1163
|
-
import { z as
|
|
2853
|
+
import { dirname as dirname4 } from "node:path";
|
|
2854
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
2855
|
+
import { z as z9 } from "zod";
|
|
1164
2856
|
var healthyWithinMs = 60000;
|
|
1165
2857
|
var settleMs = 5000;
|
|
1166
2858
|
var restartDelayMs = 2000;
|
|
@@ -1168,20 +2860,20 @@ var watchMs = 2000;
|
|
|
1168
2860
|
var adoptWithinMs = 1e4;
|
|
1169
2861
|
var stopWithinMs = 1e4;
|
|
1170
2862
|
var rotateBytes2 = 10 * 2 ** 20;
|
|
1171
|
-
var recordSchema =
|
|
1172
|
-
pid:
|
|
1173
|
-
executable:
|
|
1174
|
-
startedAt:
|
|
2863
|
+
var recordSchema = z9.strictObject({
|
|
2864
|
+
pid: z9.int().positive(),
|
|
2865
|
+
executable: z9.string(),
|
|
2866
|
+
startedAt: z9.number()
|
|
1175
2867
|
});
|
|
1176
2868
|
var mayStillRun = (record, machine) => record.startedAt > machine.now - machine.uptimeSeconds * 1000 && machine.alive(record.pid);
|
|
1177
2869
|
var createServerSupervisor = (options) => {
|
|
1178
2870
|
let current;
|
|
1179
2871
|
const writeRecord = (record) => writeFileSync(options.record, JSON.stringify(record));
|
|
1180
2872
|
const readRecord = async () => {
|
|
1181
|
-
if (!
|
|
2873
|
+
if (!existsSync8(options.record)) {
|
|
1182
2874
|
return;
|
|
1183
2875
|
}
|
|
1184
|
-
return recordSchema.safeParse(await
|
|
2876
|
+
return recordSchema.safeParse(await readFile7(options.record, "utf8").then((text) => JSON.parse(text), () => {
|
|
1185
2877
|
return;
|
|
1186
2878
|
})).data;
|
|
1187
2879
|
};
|
|
@@ -1191,23 +2883,24 @@ var createServerSupervisor = (options) => {
|
|
|
1191
2883
|
return;
|
|
1192
2884
|
}
|
|
1193
2885
|
options.log(`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`);
|
|
1194
|
-
|
|
2886
|
+
delay3(restartDelayMs).then(() => {
|
|
1195
2887
|
if (current === running) {
|
|
1196
|
-
current = spawn(running.executable);
|
|
2888
|
+
current = spawn(running.executable, running.environment);
|
|
1197
2889
|
}
|
|
1198
2890
|
});
|
|
1199
2891
|
});
|
|
1200
2892
|
};
|
|
1201
|
-
const spawn = (executable) => {
|
|
2893
|
+
const spawn = (executable, environment) => {
|
|
1202
2894
|
const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
|
|
1203
|
-
if (
|
|
2895
|
+
if (existsSync8(options.output) && statSync(options.output).size >= rotateBytes2) {
|
|
1204
2896
|
renameSync(options.output, `${options.output}.1`);
|
|
1205
2897
|
}
|
|
1206
2898
|
const output = openSync(options.output, "a");
|
|
1207
2899
|
const child = (() => {
|
|
1208
2900
|
try {
|
|
1209
2901
|
return Bun.spawn(command, {
|
|
1210
|
-
cwd:
|
|
2902
|
+
cwd: dirname4(executable),
|
|
2903
|
+
env: environment,
|
|
1211
2904
|
detached: true,
|
|
1212
2905
|
stdio: ["ignore", output, output]
|
|
1213
2906
|
});
|
|
@@ -1217,6 +2910,7 @@ var createServerSupervisor = (options) => {
|
|
|
1217
2910
|
})();
|
|
1218
2911
|
const running = {
|
|
1219
2912
|
executable,
|
|
2913
|
+
environment,
|
|
1220
2914
|
pid: child.pid,
|
|
1221
2915
|
alive: () => child.exitCode === null && child.signalCode === null,
|
|
1222
2916
|
exited: child.exited
|
|
@@ -1225,7 +2919,7 @@ var createServerSupervisor = (options) => {
|
|
|
1225
2919
|
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
1226
2920
|
return running;
|
|
1227
2921
|
};
|
|
1228
|
-
const adopt = (record) => {
|
|
2922
|
+
const adopt = (record, environment) => {
|
|
1229
2923
|
const exited = Promise.withResolvers();
|
|
1230
2924
|
const watch = setInterval(() => {
|
|
1231
2925
|
if (!processAlive(record.pid)) {
|
|
@@ -1236,6 +2930,7 @@ var createServerSupervisor = (options) => {
|
|
|
1236
2930
|
watch.unref();
|
|
1237
2931
|
const running = {
|
|
1238
2932
|
executable: record.executable,
|
|
2933
|
+
environment,
|
|
1239
2934
|
pid: record.pid,
|
|
1240
2935
|
alive: () => processAlive(record.pid),
|
|
1241
2936
|
exited: exited.promise
|
|
@@ -1252,12 +2947,12 @@ var createServerSupervisor = (options) => {
|
|
|
1252
2947
|
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
1253
2948
|
return true;
|
|
1254
2949
|
}
|
|
1255
|
-
await
|
|
2950
|
+
await delay3(1000);
|
|
1256
2951
|
}
|
|
1257
2952
|
return false;
|
|
1258
2953
|
};
|
|
1259
|
-
const start = (executable) => {
|
|
1260
|
-
current = spawn(executable);
|
|
2954
|
+
const start = (executable, environment) => {
|
|
2955
|
+
current = spawn(executable, environment);
|
|
1261
2956
|
return current;
|
|
1262
2957
|
};
|
|
1263
2958
|
const stop = async () => {
|
|
@@ -1267,22 +2962,23 @@ var createServerSupervisor = (options) => {
|
|
|
1267
2962
|
return;
|
|
1268
2963
|
}
|
|
1269
2964
|
signalProcess(running.pid, "SIGTERM");
|
|
1270
|
-
await Promise.race([running.exited,
|
|
2965
|
+
await Promise.race([running.exited, delay3(stopWithinMs)]);
|
|
1271
2966
|
if (running.alive()) {
|
|
1272
2967
|
signalProcess(running.pid, "SIGKILL");
|
|
1273
2968
|
await running.exited;
|
|
1274
2969
|
}
|
|
1275
|
-
await
|
|
2970
|
+
await rm4(options.record, { force: true });
|
|
1276
2971
|
};
|
|
1277
2972
|
const healthy = async (running) => {
|
|
1278
2973
|
if (!options.healthUrl) {
|
|
1279
|
-
await
|
|
2974
|
+
await delay3(settleMs);
|
|
1280
2975
|
return running.alive();
|
|
1281
2976
|
}
|
|
1282
2977
|
return answers(running.alive, healthyWithinMs);
|
|
1283
2978
|
};
|
|
1284
2979
|
return {
|
|
1285
2980
|
resume: async (executable) => {
|
|
2981
|
+
const environment = await options.environment(executable);
|
|
1286
2982
|
const record = await readRecord();
|
|
1287
2983
|
if (record?.executable === executable && mayStillRun(record, {
|
|
1288
2984
|
now: Date.now(),
|
|
@@ -1290,20 +2986,21 @@ var createServerSupervisor = (options) => {
|
|
|
1290
2986
|
alive: processAlive
|
|
1291
2987
|
}) && await answers(() => processAlive(record.pid), adoptWithinMs)) {
|
|
1292
2988
|
options.log(`Took over the running server (process ${record.pid})`);
|
|
1293
|
-
current = adopt(record);
|
|
2989
|
+
current = adopt(record, environment);
|
|
1294
2990
|
return;
|
|
1295
2991
|
}
|
|
1296
|
-
start(executable);
|
|
2992
|
+
start(executable, environment);
|
|
1297
2993
|
},
|
|
1298
2994
|
stop,
|
|
1299
2995
|
leave: () => {
|
|
1300
2996
|
current = undefined;
|
|
1301
2997
|
},
|
|
1302
2998
|
replace: async (executable) => {
|
|
1303
|
-
const previous = current
|
|
2999
|
+
const previous = current;
|
|
3000
|
+
const environment = await options.environment(executable);
|
|
1304
3001
|
await stop();
|
|
1305
3002
|
let failure;
|
|
1306
|
-
const started = await (async () => healthy(start(executable)))().catch((error) => {
|
|
3003
|
+
const started = await (async () => healthy(start(executable, environment)))().catch((error) => {
|
|
1307
3004
|
failure = error;
|
|
1308
3005
|
return false;
|
|
1309
3006
|
});
|
|
@@ -1312,7 +3009,7 @@ var createServerSupervisor = (options) => {
|
|
|
1312
3009
|
}
|
|
1313
3010
|
await stop();
|
|
1314
3011
|
if (previous) {
|
|
1315
|
-
start(previous);
|
|
3012
|
+
start(previous.executable, previous.environment);
|
|
1316
3013
|
}
|
|
1317
3014
|
const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
1318
3015
|
throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
|
|
@@ -1325,28 +3022,29 @@ var createServerSupervisor = (options) => {
|
|
|
1325
3022
|
};
|
|
1326
3023
|
|
|
1327
3024
|
// packages/agent/src/state.ts
|
|
1328
|
-
import { existsSync as
|
|
1329
|
-
import { mkdir as
|
|
1330
|
-
import { join as
|
|
1331
|
-
var readJsonFile = async (path, schema) =>
|
|
1332
|
-
var writeJsonFile = (path, value) =>
|
|
3025
|
+
import { existsSync as existsSync9 } from "node:fs";
|
|
3026
|
+
import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile6 } from "node:fs/promises";
|
|
3027
|
+
import { join as join9 } from "node:path";
|
|
3028
|
+
var readJsonFile = async (path, schema) => existsSync9(path) ? schema.parse(JSON.parse(await readFile8(path, "utf8"))) : null;
|
|
3029
|
+
var writeJsonFile = (path, value) => writeFile6(path, JSON.stringify(value, null, 2));
|
|
1333
3030
|
var openState = async (directory) => {
|
|
1334
3031
|
const paths = {
|
|
1335
|
-
releases:
|
|
1336
|
-
controller:
|
|
1337
|
-
sources:
|
|
1338
|
-
release:
|
|
1339
|
-
target:
|
|
1340
|
-
deployments:
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
3032
|
+
releases: join9(directory, "releases"),
|
|
3033
|
+
controller: join9(directory, "controller"),
|
|
3034
|
+
sources: join9(directory, "sources"),
|
|
3035
|
+
release: join9(directory, "release.json"),
|
|
3036
|
+
target: join9(directory, "target.json"),
|
|
3037
|
+
deployments: join9(directory, "deployments.jsonl"),
|
|
3038
|
+
deploymentRecords: join9(directory, "deployments"),
|
|
3039
|
+
audit: join9(directory, "audit.jsonl"),
|
|
3040
|
+
debug: join9(directory, "debug"),
|
|
3041
|
+
server: join9(directory, "server.json"),
|
|
3042
|
+
agent: join9(directory, "agent.json"),
|
|
3043
|
+
logs: join9(directory, "logs"),
|
|
3044
|
+
serverLog: join9(directory, "logs", "server.log"),
|
|
3045
|
+
agentLog: join9(directory, "logs", "agent.log")
|
|
3046
|
+
};
|
|
3047
|
+
await mkdir4(paths.logs, { recursive: true });
|
|
1350
3048
|
const target = () => readJsonFile(paths.target, targetSchema);
|
|
1351
3049
|
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
1352
3050
|
return {
|
|
@@ -1373,23 +3071,20 @@ var openState = async (directory) => {
|
|
|
1373
3071
|
};
|
|
1374
3072
|
|
|
1375
3073
|
// packages/agent/src/agent.ts
|
|
1376
|
-
var matches = (presented, token) => {
|
|
1377
|
-
const actual = Buffer.from(presented);
|
|
1378
|
-
const expected = Buffer.from(token);
|
|
1379
|
-
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
1380
|
-
};
|
|
1381
3074
|
var createAgent = async (options) => {
|
|
1382
3075
|
const { log } = options;
|
|
1383
3076
|
const state = await openState(options.state);
|
|
3077
|
+
const environmentVariables = options.environment ?? { ...process.env };
|
|
1384
3078
|
const server = createServerSupervisor({
|
|
1385
3079
|
healthUrl: options.serverHealthUrl,
|
|
1386
3080
|
record: state.paths.server,
|
|
1387
3081
|
output: state.paths.serverLog,
|
|
3082
|
+
environment: (executable) => serverEnvironment(state.paths.releases, executable, environmentVariables),
|
|
1388
3083
|
log
|
|
1389
3084
|
});
|
|
1390
3085
|
const deployed = await state.release();
|
|
1391
3086
|
if (deployed?.server) {
|
|
1392
|
-
await server.resume(
|
|
3087
|
+
await server.resume(join10(state.paths.releases, deployed.server));
|
|
1393
3088
|
}
|
|
1394
3089
|
describeBuilder().then(log, (error) => log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`));
|
|
1395
3090
|
const operations = createOperations(log);
|
|
@@ -1407,18 +3102,48 @@ var createAgent = async (options) => {
|
|
|
1407
3102
|
readLogin: login.read,
|
|
1408
3103
|
loginStatus: login.status,
|
|
1409
3104
|
serverHealthUrl: options.serverHealthUrl,
|
|
1410
|
-
environment:
|
|
3105
|
+
environment: environmentVariables,
|
|
1411
3106
|
log
|
|
1412
3107
|
});
|
|
1413
|
-
const deployments = createDeployments({
|
|
3108
|
+
const deployments = await createDeployments({
|
|
1414
3109
|
state,
|
|
1415
3110
|
operations,
|
|
1416
3111
|
codesys,
|
|
1417
3112
|
server,
|
|
1418
3113
|
debugging,
|
|
3114
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
3115
|
+
now: () => new Date,
|
|
3116
|
+
log
|
|
3117
|
+
});
|
|
3118
|
+
const audit = createAudit({
|
|
3119
|
+
file: state.paths.audit,
|
|
3120
|
+
onRecord: (entry) => debugging.record(entry)
|
|
3121
|
+
});
|
|
3122
|
+
const access = createAccess({
|
|
3123
|
+
token: options.token,
|
|
3124
|
+
readToken: options.readToken,
|
|
3125
|
+
file: accessFile(options.state),
|
|
3126
|
+
whois: createWhois({ run: runCommand, now: Date.now, log }),
|
|
3127
|
+
audit,
|
|
3128
|
+
now: Date.now,
|
|
3129
|
+
log
|
|
3130
|
+
});
|
|
3131
|
+
const environment = createEnvironment({
|
|
3132
|
+
state,
|
|
3133
|
+
server,
|
|
3134
|
+
operations,
|
|
3135
|
+
audit,
|
|
3136
|
+
file: environmentFile(options.state),
|
|
1419
3137
|
log
|
|
1420
3138
|
});
|
|
1421
|
-
const
|
|
3139
|
+
const dashboard = createDashboard();
|
|
3140
|
+
const apiRoutes = [
|
|
3141
|
+
...createDeploymentRoutes({ runner: deployments.runner, releases }),
|
|
3142
|
+
...access.routes,
|
|
3143
|
+
...environment.routes,
|
|
3144
|
+
...audit.routes
|
|
3145
|
+
];
|
|
3146
|
+
const route = async (request, identity) => {
|
|
1422
3147
|
const { pathname } = new URL(request.url);
|
|
1423
3148
|
const key = `${request.method} ${pathname}`;
|
|
1424
3149
|
switch (key) {
|
|
@@ -1460,7 +3185,7 @@ var createAgent = async (options) => {
|
|
|
1460
3185
|
});
|
|
1461
3186
|
}
|
|
1462
3187
|
case "POST /deploy":
|
|
1463
|
-
return deployments.deploy(() => readDeployRequest(releases, request), clientIdentity(request), clientRelease(request));
|
|
3188
|
+
return deployments.deploy(() => readDeployRequest(releases, request), identity, clientIdentity(request), clientRelease(request));
|
|
1464
3189
|
case "POST /login":
|
|
1465
3190
|
return login.open(credentialsSchema.nullable().parse(await request.json()));
|
|
1466
3191
|
case "POST /login/command":
|
|
@@ -1497,8 +3222,8 @@ var createAgent = async (options) => {
|
|
|
1497
3222
|
return Response.json({ error: `No route ${key}` }, { status: 404 });
|
|
1498
3223
|
}
|
|
1499
3224
|
};
|
|
1500
|
-
const respond = async (request) => {
|
|
1501
|
-
const { pathname, search
|
|
3225
|
+
const respond = async (request, peer) => {
|
|
3226
|
+
const { pathname, search } = new URL(request.url);
|
|
1502
3227
|
const debugPath = pathname.startsWith("/debug/");
|
|
1503
3228
|
if (pathname === "/debug") {
|
|
1504
3229
|
return new Response(null, {
|
|
@@ -1509,23 +3234,43 @@ var createAgent = async (options) => {
|
|
|
1509
3234
|
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js")) {
|
|
1510
3235
|
return debugging.handle(request, pathname.slice("/debug".length));
|
|
1511
3236
|
}
|
|
1512
|
-
const
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
3237
|
+
const page = await dashboard.handle(request);
|
|
3238
|
+
if (page) {
|
|
3239
|
+
return page;
|
|
3240
|
+
}
|
|
3241
|
+
const signing = await access.handle(request);
|
|
3242
|
+
if (signing) {
|
|
3243
|
+
return signing;
|
|
3244
|
+
}
|
|
3245
|
+
const identity = await access.identify(request, peer);
|
|
3246
|
+
if (identity instanceof Response) {
|
|
3247
|
+
return identity;
|
|
3248
|
+
}
|
|
3249
|
+
const api = pathname.startsWith("/api/") ? matchRoute(apiRoutes, request.method, pathname) : undefined;
|
|
3250
|
+
const required = api ? api.route.role : debugPath || request.method === "GET" && pathname === "/status" ? "viewer" : "admin";
|
|
3251
|
+
if (!allows(identity.role, required)) {
|
|
3252
|
+
return api ? Response.json({ error: `This needs the ${required} role` }, { status: 403 }) : Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1517
3253
|
}
|
|
1518
3254
|
try {
|
|
3255
|
+
if (api) {
|
|
3256
|
+
return await api.route.handle(request, {
|
|
3257
|
+
identity,
|
|
3258
|
+
params: api.params
|
|
3259
|
+
});
|
|
3260
|
+
}
|
|
3261
|
+
if (pathname.startsWith("/api/")) {
|
|
3262
|
+
return Response.json({ error: `No route ${request.method} ${pathname}` }, { status: 404 });
|
|
3263
|
+
}
|
|
1519
3264
|
if (debugPath) {
|
|
1520
3265
|
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
1521
3266
|
}
|
|
1522
|
-
return await route(request);
|
|
3267
|
+
return await route(request, identity);
|
|
1523
3268
|
} catch (error) {
|
|
1524
3269
|
if (error instanceof AgentError) {
|
|
1525
3270
|
return Response.json({ error: error.message }, { status: error.status });
|
|
1526
3271
|
}
|
|
1527
|
-
if (error instanceof
|
|
1528
|
-
return Response.json({ error:
|
|
3272
|
+
if (error instanceof z10.ZodError) {
|
|
3273
|
+
return Response.json({ error: z10.prettifyError(error) }, { status: 400 });
|
|
1529
3274
|
}
|
|
1530
3275
|
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1531
3276
|
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
@@ -1540,8 +3285,8 @@ var createAgent = async (options) => {
|
|
|
1540
3285
|
server.leave();
|
|
1541
3286
|
};
|
|
1542
3287
|
return {
|
|
1543
|
-
fetch: async (request) => {
|
|
1544
|
-
const response = await respond(request);
|
|
3288
|
+
fetch: async (request, peer = null) => {
|
|
3289
|
+
const response = await respond(request, peer);
|
|
1545
3290
|
const headers = new Headers(response.headers);
|
|
1546
3291
|
headers.set(agentVersionHeader, tsplcVersion);
|
|
1547
3292
|
return new Response(response.body, {
|
|
@@ -1608,6 +3353,7 @@ var askCredentials = async () => ({
|
|
|
1608
3353
|
});
|
|
1609
3354
|
export {
|
|
1610
3355
|
agentDockerResources,
|
|
3356
|
+
agentVersionHeader,
|
|
1611
3357
|
ask,
|
|
1612
3358
|
askCredentials,
|
|
1613
3359
|
askSecret,
|
|
@@ -1629,5 +3375,5 @@ export {
|
|
|
1629
3375
|
variableSchema
|
|
1630
3376
|
};
|
|
1631
3377
|
|
|
1632
|
-
//# debugId=
|
|
3378
|
+
//# debugId=CA4E87DE01F4DB1B64756E2164756E21
|
|
1633
3379
|
//# sourceMappingURL=index.js.map
|