@tsplc/agent 0.5.9 → 0.5.12
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 +2660 -525
- package/dist/cli.js.map +32 -18
- package/dist/client.js +262 -37
- package/dist/client.js.map +4 -4
- package/dist/index.js +2325 -415
- package/dist/index.js.map +27 -14
- package/package.json +6 -5
- package/src/access.ts +276 -0
- package/src/agent.ts +130 -29
- package/src/audit.ts +64 -0
- package/src/cli.ts +81 -5
- package/src/client.ts +204 -36
- package/src/controller.ts +60 -0
- package/src/dashboard/index.ts +118 -0
- package/src/dashboard/ui/access.ts +192 -0
- package/src/dashboard/ui/actions.ts +192 -0
- package/src/dashboard/ui/api.ts +158 -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 +19 -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 +326 -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 +192 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/deploy.ts +174 -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 +284 -0
- package/src/index.ts +4 -0
- package/src/login.ts +17 -0
- package/src/operations.ts +6 -1
- package/src/protocol.ts +259 -2
- package/src/releases.ts +73 -1
- package/src/routes.ts +52 -0
- package/src/secrets.ts +74 -4
- 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,17 @@
|
|
|
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 {
|
|
4
|
+
import { plantAgentEnv } from "@tsplc/server/plant-agent";
|
|
5
|
+
import { z as z10 } from "zod";
|
|
6
6
|
|
|
7
|
-
// packages/agent/src/
|
|
7
|
+
// packages/agent/src/access.ts
|
|
8
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
11
|
+
import { isIP as isIP2 } from "node:net";
|
|
8
12
|
import { join } from "node:path";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
captureDocker,
|
|
12
|
-
gatewayImage,
|
|
13
|
-
setupReason
|
|
14
|
-
} from "@tsplc/build";
|
|
15
|
-
import { resolveConfig } from "@tsplc/config/build";
|
|
13
|
+
import { dashboardHeader } from "@tsplc/debug/api";
|
|
14
|
+
import { controllerRestartPath } from "@tsplc/server/plant-agent";
|
|
16
15
|
|
|
17
16
|
// packages/agent/src/errors.ts
|
|
18
17
|
class AgentError extends Error {
|
|
@@ -26,139 +25,13 @@ class AgentError extends Error {
|
|
|
26
25
|
}
|
|
27
26
|
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
28
27
|
|
|
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
28
|
// packages/agent/src/protocol.ts
|
|
156
|
-
import { rollbackSchema } from "@tsplc/build";
|
|
157
|
-
import { tsplcConfigSchema } from "@tsplc/config";
|
|
29
|
+
import { onlineChangeFindingSchema, rollbackSchema } from "@tsplc/build";
|
|
30
|
+
import { secretValue, tsplcConfigSchema } from "@tsplc/config";
|
|
158
31
|
import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
|
|
159
32
|
import { z } from "zod";
|
|
160
33
|
// packages/agent/package.json
|
|
161
|
-
var version = "0.5.
|
|
34
|
+
var version = "0.5.12";
|
|
162
35
|
|
|
163
36
|
// packages/agent/src/protocol.ts
|
|
164
37
|
var tsplcVersion = version;
|
|
@@ -185,6 +58,8 @@ var variableSchema = z.strictObject({
|
|
|
185
58
|
path: z.string(),
|
|
186
59
|
type: z.string()
|
|
187
60
|
});
|
|
61
|
+
var targetValuesSchema = tsplcConfigSchema.shape.targets.unwrap().valueType.shape.values;
|
|
62
|
+
var variableName = tsplcConfigSchema.shape.secrets.unwrap().shape.names.element;
|
|
188
63
|
var releaseManifestSchema = z.strictObject({
|
|
189
64
|
config: z.record(z.string(), z.unknown()).superRefine((config, context) => {
|
|
190
65
|
const release = releaseConfigSchema.safeParse(config);
|
|
@@ -199,13 +74,15 @@ var releaseManifestSchema = z.strictObject({
|
|
|
199
74
|
server: z.string().nonempty().optional(),
|
|
200
75
|
debug: tsplcConfigSchema.shape.debug,
|
|
201
76
|
serverTokenEnv: z.string().nonempty().optional(),
|
|
202
|
-
secrets: tsplcConfigSchema.shape.secrets
|
|
77
|
+
secrets: tsplcConfigSchema.shape.secrets,
|
|
78
|
+
values: targetValuesSchema
|
|
203
79
|
});
|
|
204
80
|
var uploadEncoding = "gzip";
|
|
205
81
|
var deployOptionsSchema = z.strictObject({
|
|
206
82
|
credentials: credentialsSchema.nullable(),
|
|
207
83
|
download: z.boolean(),
|
|
208
|
-
initializeUser: z.boolean()
|
|
84
|
+
initializeUser: z.boolean(),
|
|
85
|
+
deployment: z.lazy(() => deploymentRequestSchema).optional()
|
|
209
86
|
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
210
87
|
var releaseBuckets = 256;
|
|
211
88
|
var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
|
|
@@ -269,50 +146,744 @@ var clientIdentity = (request) => {
|
|
|
269
146
|
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
270
147
|
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
271
148
|
};
|
|
272
|
-
var clientRelease = (request) => ({
|
|
273
|
-
version: request.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,
|
|
274
|
-
scripts: request.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined
|
|
275
|
-
});
|
|
276
|
-
var deploymentSchema = z.strictObject({
|
|
277
|
-
at: z.iso.datetime(),
|
|
278
|
-
release: z.string(),
|
|
279
|
-
build: z.string().optional(),
|
|
280
|
-
operation: deployOperationSchema,
|
|
281
|
-
credentials: z.enum(["provided", "stored"]).optional(),
|
|
282
|
-
user: z.string().optional(),
|
|
283
|
-
host: z.string().optional()
|
|
284
|
-
});
|
|
285
|
-
var auditSchema = z.strictObject({
|
|
286
|
-
at: z.iso.datetime(),
|
|
287
|
-
command: z.string(),
|
|
288
|
-
values: z.record(z.string(), z.string()),
|
|
289
|
-
previous: z.record(z.string(), z.string()).optional(),
|
|
290
|
-
user: z.string().optional(),
|
|
291
|
-
host: z.string().optional(),
|
|
292
|
-
release: z.string().optional(),
|
|
293
|
-
error: z.string().optional()
|
|
294
|
-
});
|
|
149
|
+
var clientRelease = (request) => ({
|
|
150
|
+
version: request.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,
|
|
151
|
+
scripts: request.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined
|
|
152
|
+
});
|
|
153
|
+
var deploymentSchema = z.strictObject({
|
|
154
|
+
at: z.iso.datetime(),
|
|
155
|
+
release: z.string(),
|
|
156
|
+
build: z.string().optional(),
|
|
157
|
+
operation: deployOperationSchema,
|
|
158
|
+
credentials: z.enum(["provided", "stored"]).optional(),
|
|
159
|
+
user: z.string().optional(),
|
|
160
|
+
host: z.string().optional()
|
|
161
|
+
});
|
|
162
|
+
var auditSchema = z.strictObject({
|
|
163
|
+
at: z.iso.datetime(),
|
|
164
|
+
command: z.string(),
|
|
165
|
+
values: z.record(z.string(), z.string()),
|
|
166
|
+
previous: z.record(z.string(), z.string()).optional(),
|
|
167
|
+
user: z.string().optional(),
|
|
168
|
+
host: z.string().optional(),
|
|
169
|
+
release: z.string().optional(),
|
|
170
|
+
error: z.string().optional()
|
|
171
|
+
});
|
|
172
|
+
var roles = ["viewer", "deployer", "admin"];
|
|
173
|
+
var roleSchema = z.enum(roles);
|
|
174
|
+
var allows = (role, required) => roles.indexOf(role) >= roles.indexOf(required);
|
|
175
|
+
var identitySchema = z.strictObject({
|
|
176
|
+
login: z.string().nullable(),
|
|
177
|
+
name: z.string(),
|
|
178
|
+
role: roleSchema,
|
|
179
|
+
via: z.enum(["tailscale", "token", "local", "server"])
|
|
180
|
+
});
|
|
181
|
+
var gitSourceSchema = z.strictObject({
|
|
182
|
+
commit: z.string().nonempty(),
|
|
183
|
+
branch: z.string().nullable(),
|
|
184
|
+
dirty: z.boolean(),
|
|
185
|
+
message: z.string().nullable()
|
|
186
|
+
});
|
|
187
|
+
var deploymentModeSchema = z.enum(["apply", "review"]);
|
|
188
|
+
var deploymentStateSchema = z.enum([
|
|
189
|
+
"queued",
|
|
190
|
+
"building",
|
|
191
|
+
"awaitingApproval",
|
|
192
|
+
"applying",
|
|
193
|
+
"starting",
|
|
194
|
+
"verifying",
|
|
195
|
+
"ready",
|
|
196
|
+
"error",
|
|
197
|
+
"canceled"
|
|
198
|
+
]);
|
|
199
|
+
var deploymentPhaseNameSchema = z.enum([
|
|
200
|
+
"queue",
|
|
201
|
+
"build",
|
|
202
|
+
"review",
|
|
203
|
+
"apply",
|
|
204
|
+
"server",
|
|
205
|
+
"health"
|
|
206
|
+
]);
|
|
207
|
+
var deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
|
|
208
|
+
var deploymentRecordSchema = z.strictObject({
|
|
209
|
+
id: deploymentIdSchema,
|
|
210
|
+
release: z.string(),
|
|
211
|
+
build: z.string().nullable(),
|
|
212
|
+
createdAt: z.iso.datetime(),
|
|
213
|
+
updatedAt: z.iso.datetime(),
|
|
214
|
+
origin: z.discriminatedUnion("kind", [
|
|
215
|
+
z.strictObject({ kind: z.literal("upload") }),
|
|
216
|
+
z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
|
|
217
|
+
z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema })
|
|
218
|
+
]),
|
|
219
|
+
git: gitSourceSchema.nullable(),
|
|
220
|
+
requestedBy: z.strictObject({
|
|
221
|
+
identity: identitySchema.omit({ role: true }),
|
|
222
|
+
user: z.string().nullable(),
|
|
223
|
+
host: z.string().nullable()
|
|
224
|
+
}),
|
|
225
|
+
mode: deploymentModeSchema,
|
|
226
|
+
operation: deployOperationSchema,
|
|
227
|
+
state: deploymentStateSchema,
|
|
228
|
+
phases: z.array(z.strictObject({
|
|
229
|
+
name: deploymentPhaseNameSchema,
|
|
230
|
+
startedAt: z.iso.datetime(),
|
|
231
|
+
finishedAt: z.iso.datetime().nullable(),
|
|
232
|
+
outcome: z.enum(["running", "ok", "failed", "skipped"])
|
|
233
|
+
})),
|
|
234
|
+
findings: z.array(onlineChangeFindingSchema),
|
|
235
|
+
approval: z.strictObject({
|
|
236
|
+
reason: z.enum(["review", "downloadRequired"]),
|
|
237
|
+
message: z.string()
|
|
238
|
+
}).nullable(),
|
|
239
|
+
error: z.strictObject({
|
|
240
|
+
message: z.string(),
|
|
241
|
+
downloadRequired: z.boolean(),
|
|
242
|
+
rollback: rollbackSchema.optional()
|
|
243
|
+
}).nullable(),
|
|
244
|
+
controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }).nullable(),
|
|
245
|
+
health: z.strictObject({
|
|
246
|
+
controller: z.enum(["ok", "failed"]),
|
|
247
|
+
server: z.enum(["ok", "failed", "none"]),
|
|
248
|
+
plc: z.enum(["ok", "failed", "unknown"]),
|
|
249
|
+
detail: z.string().nullable()
|
|
250
|
+
}).nullable(),
|
|
251
|
+
activeFrom: z.iso.datetime().nullable(),
|
|
252
|
+
activeUntil: z.iso.datetime().nullable()
|
|
253
|
+
});
|
|
254
|
+
var deploymentLogLineSchema = z.strictObject({
|
|
255
|
+
seq: z.number().int().positive(),
|
|
256
|
+
at: z.iso.datetime(),
|
|
257
|
+
level: z.enum(["info", "warning", "error"]),
|
|
258
|
+
phase: deploymentPhaseNameSchema.nullable(),
|
|
259
|
+
message: z.string()
|
|
260
|
+
});
|
|
261
|
+
var deploymentRequestSchema = z.strictObject({
|
|
262
|
+
mode: deploymentModeSchema,
|
|
263
|
+
git: gitSourceSchema.nullable()
|
|
264
|
+
});
|
|
265
|
+
var deploymentCreatedSchema = z.strictObject({
|
|
266
|
+
id: deploymentIdSchema,
|
|
267
|
+
url: z.string()
|
|
268
|
+
});
|
|
269
|
+
var deploymentListSchema = z.strictObject({
|
|
270
|
+
deployments: z.array(deploymentRecordSchema),
|
|
271
|
+
current: deploymentIdSchema.nullable(),
|
|
272
|
+
lastGood: deploymentIdSchema.nullable()
|
|
273
|
+
});
|
|
274
|
+
var approveSchema = z.strictObject({ download: z.boolean() });
|
|
275
|
+
var redeploySchema = z.strictObject({ mode: deploymentModeSchema });
|
|
276
|
+
var deploymentSourceSchema = z.strictObject({
|
|
277
|
+
files: z.array(z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }))
|
|
278
|
+
});
|
|
279
|
+
var environmentEntrySchema = z.strictObject({
|
|
280
|
+
name: z.string(),
|
|
281
|
+
declared: z.boolean(),
|
|
282
|
+
set: z.boolean()
|
|
283
|
+
});
|
|
284
|
+
var environmentSchema = z.strictObject({
|
|
285
|
+
values: targetValuesSchema,
|
|
286
|
+
variables: z.record(variableName, z.string()),
|
|
287
|
+
secrets: z.array(environmentEntrySchema)
|
|
288
|
+
});
|
|
289
|
+
var accessConfigSchema = z.strictObject({
|
|
290
|
+
roles: z.record(z.string().nonempty(), roleSchema),
|
|
291
|
+
tailnetDefault: roleSchema.nullable()
|
|
292
|
+
});
|
|
293
|
+
var sessionRequestSchema = z.strictObject({ token: z.string() });
|
|
294
|
+
var plainValue = z.string().nonempty("is empty").regex(/^[^\0]*$/, "holds a NUL");
|
|
295
|
+
var environmentValueSchema = z.discriminatedUnion("secret", [
|
|
296
|
+
z.strictObject({ secret: z.literal(false), value: plainValue }),
|
|
297
|
+
z.strictObject({ secret: z.literal(true), value: secretValue })
|
|
298
|
+
]);
|
|
299
|
+
var plantVariablesSchema = z.strictObject({
|
|
300
|
+
service: z.string().nonempty(),
|
|
301
|
+
values: z.record(variableName, z.string()),
|
|
302
|
+
secrets: z.array(variableName)
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
// packages/agent/src/sessions.ts
|
|
306
|
+
import { randomBytes } from "node:crypto";
|
|
307
|
+
var sessionCookie = "tsplc_session";
|
|
308
|
+
var sessionLifetimeMs = 12 * 60 * 60 * 1000;
|
|
309
|
+
var createSessions = (now) => {
|
|
310
|
+
const sessions = new Map;
|
|
311
|
+
const sessionId = (request) => new Bun.CookieMap(request.headers.get("cookie") ?? "").get(sessionCookie);
|
|
312
|
+
const cookie = (value, maxAgeMs) => new Bun.Cookie(sessionCookie, value, {
|
|
313
|
+
httpOnly: true,
|
|
314
|
+
sameSite: "strict",
|
|
315
|
+
path: "/",
|
|
316
|
+
maxAge: Math.floor(maxAgeMs / 1000)
|
|
317
|
+
}).serialize();
|
|
318
|
+
return {
|
|
319
|
+
open: (identity) => {
|
|
320
|
+
const time = now();
|
|
321
|
+
for (const [id, { expires }] of sessions) {
|
|
322
|
+
if (expires <= time) {
|
|
323
|
+
sessions.delete(id);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const id = randomBytes(32).toString("base64url");
|
|
327
|
+
sessions.set(id, { identity, expires: time + sessionLifetimeMs });
|
|
328
|
+
return cookie(id, sessionLifetimeMs);
|
|
329
|
+
},
|
|
330
|
+
find: (request) => {
|
|
331
|
+
const id = sessionId(request);
|
|
332
|
+
const session = id === null ? undefined : sessions.get(id);
|
|
333
|
+
if (!session || session.expires <= now()) {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
return session.identity;
|
|
337
|
+
},
|
|
338
|
+
close: (request) => {
|
|
339
|
+
const id = sessionId(request);
|
|
340
|
+
if (id !== null) {
|
|
341
|
+
sessions.delete(id);
|
|
342
|
+
}
|
|
343
|
+
return cookie("", 0);
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
// packages/agent/src/tailscale.ts
|
|
349
|
+
import { BlockList, isIP } from "node:net";
|
|
350
|
+
import { z as z2 } from "zod";
|
|
351
|
+
var tailnet = new BlockList;
|
|
352
|
+
tailnet.addSubnet("100.64.0.0", 10, "ipv4");
|
|
353
|
+
tailnet.addSubnet("fd7a:115c:a1e0::", 48, "ipv6");
|
|
354
|
+
var loopback = new BlockList;
|
|
355
|
+
loopback.addSubnet("127.0.0.0", 8, "ipv4");
|
|
356
|
+
loopback.addAddress("::1", "ipv6");
|
|
357
|
+
var peerKind = (address) => {
|
|
358
|
+
const version = isIP(address);
|
|
359
|
+
if (version === 0) {
|
|
360
|
+
return "other";
|
|
361
|
+
}
|
|
362
|
+
const family = version === 6 ? "ipv6" : "ipv4";
|
|
363
|
+
if (loopback.check(address, family)) {
|
|
364
|
+
return "loopback";
|
|
365
|
+
}
|
|
366
|
+
return tailnet.check(address, family) ? "tailnet" : "other";
|
|
367
|
+
};
|
|
368
|
+
var whoisSchema = z2.object({
|
|
369
|
+
UserProfile: z2.object({
|
|
370
|
+
LoginName: z2.string().nonempty(),
|
|
371
|
+
DisplayName: z2.string()
|
|
372
|
+
})
|
|
373
|
+
});
|
|
374
|
+
var runCommand = async (command) => {
|
|
375
|
+
const child = Bun.spawn(command, {
|
|
376
|
+
stdout: "pipe",
|
|
377
|
+
stderr: "ignore",
|
|
378
|
+
timeout: 5000
|
|
379
|
+
});
|
|
380
|
+
const [stdout, exitCode] = await Promise.all([
|
|
381
|
+
new Response(child.stdout).text(),
|
|
382
|
+
child.exited
|
|
383
|
+
]);
|
|
384
|
+
return { stdout, exitCode };
|
|
385
|
+
};
|
|
386
|
+
var whoisCacheMs = 60000;
|
|
387
|
+
var createWhois = (context) => {
|
|
388
|
+
const cache = new Map;
|
|
389
|
+
const lookUp = async (address) => {
|
|
390
|
+
try {
|
|
391
|
+
const { exitCode, stdout } = await context.run([
|
|
392
|
+
"tailscale",
|
|
393
|
+
"whois",
|
|
394
|
+
"--json",
|
|
395
|
+
address
|
|
396
|
+
]);
|
|
397
|
+
if (exitCode !== 0) {
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
const { UserProfile } = whoisSchema.parse(JSON.parse(stdout));
|
|
401
|
+
return {
|
|
402
|
+
login: UserProfile.LoginName,
|
|
403
|
+
name: UserProfile.DisplayName || UserProfile.LoginName
|
|
404
|
+
};
|
|
405
|
+
} catch (error) {
|
|
406
|
+
context.log(`tailscale whois ${address} failed: ${errorMessage(error)}`);
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
return (address) => {
|
|
411
|
+
const now = context.now();
|
|
412
|
+
for (const [cached, { expires }] of cache) {
|
|
413
|
+
if (expires <= now) {
|
|
414
|
+
cache.delete(cached);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const known = cache.get(address);
|
|
418
|
+
if (known) {
|
|
419
|
+
return known.user;
|
|
420
|
+
}
|
|
421
|
+
const user = lookUp(address);
|
|
422
|
+
cache.set(address, { expires: now + whoisCacheMs, user });
|
|
423
|
+
return user;
|
|
424
|
+
};
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
// packages/agent/src/access.ts
|
|
428
|
+
var accessFile = (state) => join(state, "access.json");
|
|
429
|
+
var noAccess = { roles: {}, tailnetDefault: null };
|
|
430
|
+
var readAccessConfig = async (file) => existsSync(file) ? accessConfigSchema.parse(JSON.parse(await readFile(file, "utf8"))) : noAccess;
|
|
431
|
+
var writeAccessConfig = async (file, config) => {
|
|
432
|
+
await writeFile(`${file}.tmp`, JSON.stringify(config, null, 2));
|
|
433
|
+
await rename(`${file}.tmp`, file);
|
|
434
|
+
};
|
|
435
|
+
var matches = (presented, token) => timingSafeEqual(createHash("sha256").update(presented).digest(), createHash("sha256").update(token).digest());
|
|
436
|
+
var refuse = (status, error) => Response.json({ error }, { status });
|
|
437
|
+
var unauthorized = () => refuse(401, "Unauthorized");
|
|
438
|
+
var forwardingHeaders = [
|
|
439
|
+
"forwarded",
|
|
440
|
+
"x-forwarded-for",
|
|
441
|
+
"tailscale-user-login"
|
|
442
|
+
];
|
|
443
|
+
var namesAgentDirectly = (request) => {
|
|
444
|
+
const host = new URL(request.url).hostname.replace(/^\[(.*)\]$/, "$1");
|
|
445
|
+
return isIP2(host) !== 0 || !host.includes(".") || host.endsWith(".ts.net") || host === "localhost";
|
|
446
|
+
};
|
|
447
|
+
var changes = (request) => request.method !== "GET";
|
|
448
|
+
var fromDashboard = (request) => request.headers.get(dashboardHeader) === "1";
|
|
449
|
+
var crossSite = () => refuse(403, `A browser's request that changes something needs the ${dashboardHeader}: 1 header`);
|
|
450
|
+
var createAccess = (options) => {
|
|
451
|
+
const sessions = createSessions(options.now);
|
|
452
|
+
const tokenIdentity = (presented) => {
|
|
453
|
+
if (matches(presented, options.token)) {
|
|
454
|
+
return { login: null, name: "Agent token", role: "admin", via: "token" };
|
|
455
|
+
}
|
|
456
|
+
if (options.readToken !== undefined && matches(presented, options.readToken)) {
|
|
457
|
+
return {
|
|
458
|
+
login: null,
|
|
459
|
+
name: "Read token",
|
|
460
|
+
role: "viewer",
|
|
461
|
+
via: "token"
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
return null;
|
|
465
|
+
};
|
|
466
|
+
const serverIdentity = {
|
|
467
|
+
login: null,
|
|
468
|
+
name: "Line server",
|
|
469
|
+
role: "deployer",
|
|
470
|
+
via: "server"
|
|
471
|
+
};
|
|
472
|
+
const peerIdentity = async (request, peer) => {
|
|
473
|
+
if (!peer || !namesAgentDirectly(request) || forwardingHeaders.some((name) => request.headers.has(name))) {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
const kind = peerKind(peer.address);
|
|
477
|
+
if (kind === "loopback") {
|
|
478
|
+
return { login: null, name: "This PC", role: "admin", via: "local" };
|
|
479
|
+
}
|
|
480
|
+
if (kind !== "tailnet") {
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
const user = await options.whois(peer.address);
|
|
484
|
+
if (!user) {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
const config = await readAccessConfig(options.file).catch((error) => {
|
|
488
|
+
options.log(`Can't read ${options.file}: ${errorMessage(error)}`);
|
|
489
|
+
return noAccess;
|
|
490
|
+
});
|
|
491
|
+
const role = config.roles[user.login] ?? config.tailnetDefault;
|
|
492
|
+
return role && { login: user.login, name: user.name, role, via: "tailscale" };
|
|
493
|
+
};
|
|
494
|
+
const identify = async (request, peer) => {
|
|
495
|
+
const { searchParams, pathname } = new URL(request.url);
|
|
496
|
+
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (pathname.startsWith("/debug/") ? searchParams.get("token") : null);
|
|
497
|
+
if (presented !== null) {
|
|
498
|
+
if (options.serverToken !== null && matches(presented, options.serverToken)) {
|
|
499
|
+
return request.method === "POST" && pathname === controllerRestartPath ? serverIdentity : refuse(403, "The server's token only restarts the controller");
|
|
500
|
+
}
|
|
501
|
+
return tokenIdentity(presented) ?? unauthorized();
|
|
502
|
+
}
|
|
503
|
+
const browserRoute = pathname.startsWith("/api/") || pathname.startsWith("/debug/") || request.method === "GET" && pathname === "/status";
|
|
504
|
+
if (!browserRoute) {
|
|
505
|
+
return unauthorized();
|
|
506
|
+
}
|
|
507
|
+
const identity = sessions.find(request) ?? await peerIdentity(request, peer);
|
|
508
|
+
if (!identity) {
|
|
509
|
+
return unauthorized();
|
|
510
|
+
}
|
|
511
|
+
return changes(request) && !fromDashboard(request) ? crossSite() : identity;
|
|
512
|
+
};
|
|
513
|
+
const handle = async (request) => {
|
|
514
|
+
const { pathname } = new URL(request.url);
|
|
515
|
+
if (pathname !== "/api/session" || request.method !== "POST" && request.method !== "DELETE") {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
if (!fromDashboard(request)) {
|
|
519
|
+
return crossSite();
|
|
520
|
+
}
|
|
521
|
+
if (request.method === "DELETE") {
|
|
522
|
+
return new Response(null, {
|
|
523
|
+
status: 204,
|
|
524
|
+
headers: { "Set-Cookie": sessions.close(request) }
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
const body = sessionRequestSchema.safeParse(await request.json().catch(() => null));
|
|
528
|
+
if (!body.success) {
|
|
529
|
+
return Response.json({ error: "Send { token }" }, { status: 400 });
|
|
530
|
+
}
|
|
531
|
+
const identity = tokenIdentity(body.data.token);
|
|
532
|
+
if (!identity) {
|
|
533
|
+
return unauthorized();
|
|
534
|
+
}
|
|
535
|
+
return Response.json(identity, {
|
|
536
|
+
headers: { "Set-Cookie": sessions.open(identity) }
|
|
537
|
+
});
|
|
538
|
+
};
|
|
539
|
+
const routes = [
|
|
540
|
+
{
|
|
541
|
+
method: "GET",
|
|
542
|
+
pattern: "/api/session",
|
|
543
|
+
role: "viewer",
|
|
544
|
+
handle: async (_request, { identity }) => Response.json(identity)
|
|
545
|
+
},
|
|
546
|
+
{
|
|
547
|
+
method: "GET",
|
|
548
|
+
pattern: "/api/access",
|
|
549
|
+
role: "admin",
|
|
550
|
+
handle: async () => Response.json(await readAccessConfig(options.file))
|
|
551
|
+
},
|
|
552
|
+
{
|
|
553
|
+
method: "PUT",
|
|
554
|
+
pattern: "/api/access",
|
|
555
|
+
role: "admin",
|
|
556
|
+
handle: async (request, { identity }) => {
|
|
557
|
+
const config = accessConfigSchema.parse(await request.json());
|
|
558
|
+
const previous = await readAccessConfig(options.file);
|
|
559
|
+
await writeAccessConfig(options.file, config);
|
|
560
|
+
await options.audit.record({
|
|
561
|
+
identity,
|
|
562
|
+
command: "access",
|
|
563
|
+
values: auditedAccess(config),
|
|
564
|
+
previous: auditedAccess(previous),
|
|
565
|
+
error: null
|
|
566
|
+
});
|
|
567
|
+
return Response.json(config);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
];
|
|
571
|
+
return { identify, handle, routes };
|
|
572
|
+
};
|
|
573
|
+
var auditedAccess = (config) => ({
|
|
574
|
+
...config.roles,
|
|
575
|
+
"(tailnet default)": config.tailnetDefault ?? "none"
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
// packages/agent/src/audit.ts
|
|
579
|
+
import { z as z3 } from "zod";
|
|
580
|
+
|
|
581
|
+
// packages/agent/src/logs.ts
|
|
582
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
583
|
+
import { open, readFile as readFile2, rename as rename2, stat } from "node:fs/promises";
|
|
584
|
+
var rotateBytes = 5 * 2 ** 20;
|
|
585
|
+
var appendJsonl = async (file, value) => {
|
|
586
|
+
if (existsSync2(file) && (await stat(file)).size >= rotateBytes) {
|
|
587
|
+
await rename2(file, `${file}.1`);
|
|
588
|
+
}
|
|
589
|
+
const log = await open(file, "a+");
|
|
590
|
+
try {
|
|
591
|
+
const { size } = await log.stat();
|
|
592
|
+
const last = Buffer.alloc(1);
|
|
593
|
+
if (size) {
|
|
594
|
+
await log.read(last, 0, 1, size - 1);
|
|
595
|
+
}
|
|
596
|
+
const separator = size && last[0] !== 10 ? `
|
|
597
|
+
` : "";
|
|
598
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
599
|
+
`);
|
|
600
|
+
} finally {
|
|
601
|
+
await log.close();
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
var readJsonl = async (file, schema, limit) => {
|
|
605
|
+
if (!existsSync2(file)) {
|
|
606
|
+
return [];
|
|
607
|
+
}
|
|
608
|
+
return (await readFile2(file, "utf8")).split(`
|
|
609
|
+
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
610
|
+
try {
|
|
611
|
+
return [schema.parse(JSON.parse(line))];
|
|
612
|
+
} catch {
|
|
613
|
+
return [];
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
// packages/agent/src/audit.ts
|
|
619
|
+
var auditLimits = { default: 100, max: 1000 };
|
|
620
|
+
var auditQuerySchema = z3.object({
|
|
621
|
+
limit: z3.coerce.number().int().positive().max(auditLimits.max).default(auditLimits.default)
|
|
622
|
+
});
|
|
623
|
+
var createAudit = (context) => {
|
|
624
|
+
const record = async (change) => {
|
|
625
|
+
const entry = {
|
|
626
|
+
at: new Date().toISOString(),
|
|
627
|
+
command: change.command,
|
|
628
|
+
values: change.values,
|
|
629
|
+
...change.previous && { previous: change.previous },
|
|
630
|
+
user: change.identity.login ?? change.identity.name,
|
|
631
|
+
...change.error !== null && { error: change.error }
|
|
632
|
+
};
|
|
633
|
+
await appendJsonl(context.file, entry);
|
|
634
|
+
await context.onRecord(entry);
|
|
635
|
+
};
|
|
636
|
+
const routes = [
|
|
637
|
+
{
|
|
638
|
+
method: "GET",
|
|
639
|
+
pattern: "/api/audit",
|
|
640
|
+
role: "viewer",
|
|
641
|
+
handle: async (request) => {
|
|
642
|
+
const { limit } = auditQuerySchema.parse(Object.fromEntries(new URL(request.url).searchParams));
|
|
643
|
+
return Response.json((await readJsonl(context.file, auditSchema, limit)).reverse());
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
];
|
|
647
|
+
return { record, routes };
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
// packages/agent/src/codesys.ts
|
|
651
|
+
import { join as join2 } from "node:path";
|
|
652
|
+
import {
|
|
653
|
+
builderImageStatus,
|
|
654
|
+
captureDocker,
|
|
655
|
+
gatewayImage,
|
|
656
|
+
setupReason
|
|
657
|
+
} from "@tsplc/build";
|
|
658
|
+
import { resolveConfig } from "@tsplc/config/build";
|
|
659
|
+
var network = "tsplc-agent";
|
|
660
|
+
var codesysNetwork = "tsplc-agent-codesys";
|
|
661
|
+
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
662
|
+
var loginContainer = "tsplc-agent-login";
|
|
663
|
+
var deployContainer = "tsplc-agent-deploy";
|
|
664
|
+
var agentDockerResources = {
|
|
665
|
+
containers: [gateway.host, deployContainer, loginContainer],
|
|
666
|
+
networks: [network, codesysNetwork]
|
|
667
|
+
};
|
|
668
|
+
var credentialNames = {
|
|
669
|
+
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
670
|
+
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
671
|
+
};
|
|
672
|
+
var dockerTimeout = 60000;
|
|
673
|
+
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
674
|
+
var ensureNetwork = async (name, ...options) => {
|
|
675
|
+
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
676
|
+
await docker("network", "create", ...options, name);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
var setupNeeded = async () => {
|
|
680
|
+
const status = await builderImageStatus();
|
|
681
|
+
const reason = setupReason(status) ?? (await docker("image", "ls", "--quiet", gatewayImage) ? null : `the CODESYS gateway image ${gatewayImage} is missing`);
|
|
682
|
+
return { status, reason };
|
|
683
|
+
};
|
|
684
|
+
var requireBuilder = async () => {
|
|
685
|
+
const { status, reason } = await setupNeeded().catch((cause) => {
|
|
686
|
+
throw new AgentError(`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`, 503);
|
|
687
|
+
});
|
|
688
|
+
if (reason) {
|
|
689
|
+
throw new AgentError(`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`, 409);
|
|
690
|
+
}
|
|
691
|
+
return status;
|
|
692
|
+
};
|
|
693
|
+
var describeBuilder = async () => {
|
|
694
|
+
const { status, reason } = await setupNeeded();
|
|
695
|
+
if (reason) {
|
|
696
|
+
return `Deployments and logins need tsplc-agent setup first: ${reason}`;
|
|
697
|
+
}
|
|
698
|
+
if (status.kind === "unverified") {
|
|
699
|
+
return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
|
|
700
|
+
}
|
|
701
|
+
return "The CODESYS images match this tsPLC";
|
|
702
|
+
};
|
|
703
|
+
var removeContainer = (name) => docker("rm", "--force", name);
|
|
704
|
+
var ensureGateway = async () => {
|
|
705
|
+
await ensureNetwork(network);
|
|
706
|
+
await ensureNetwork(codesysNetwork, "--internal");
|
|
707
|
+
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
708
|
+
await docker("rm", "--force", gateway.host);
|
|
709
|
+
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
710
|
+
}
|
|
711
|
+
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
712
|
+
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
713
|
+
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
var credentialEnvironment = (credentials) => ({
|
|
717
|
+
[credentialNames.usernameEnv]: credentials.username,
|
|
718
|
+
[credentialNames.passwordEnv]: credentials.password
|
|
719
|
+
});
|
|
720
|
+
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
721
|
+
...resolveConfig({
|
|
722
|
+
...release.manifest.config,
|
|
723
|
+
...settings.bulkImport && { bulkImport: true },
|
|
724
|
+
online: {
|
|
725
|
+
network: codesysNetwork,
|
|
726
|
+
gateway,
|
|
727
|
+
device: target,
|
|
728
|
+
credentials: credentialNames
|
|
729
|
+
}
|
|
730
|
+
}, join2(release.directory, "manifest.json")),
|
|
731
|
+
outDir: controllerDirectory
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
// packages/agent/src/controller.ts
|
|
735
|
+
import {
|
|
736
|
+
controllerRestartPath as controllerRestartPath2,
|
|
737
|
+
controllerRestartSchema
|
|
738
|
+
} from "@tsplc/server/plant-agent";
|
|
739
|
+
var createControllerRoutes = (context) => [
|
|
740
|
+
{
|
|
741
|
+
method: "POST",
|
|
742
|
+
pattern: controllerRestartPath2,
|
|
743
|
+
role: "deployer",
|
|
744
|
+
handle: async (request, { identity }) => {
|
|
745
|
+
const { reset } = controllerRestartSchema.parse(await request.json());
|
|
746
|
+
const restart = await context.login.isOpen() ? context.login.restart : context.warm;
|
|
747
|
+
const outcome = await restart(reset === "warm" ? "Warm" : "Cold").then((reply) => ({ reply, failure: null }), (failure) => ({ reply: null, failure }));
|
|
748
|
+
if (outcome.failure instanceof AgentError) {
|
|
749
|
+
throw outcome.failure;
|
|
750
|
+
}
|
|
751
|
+
await context.audit.record({
|
|
752
|
+
identity,
|
|
753
|
+
command: reset === "warm" ? "restart" : "restart --cold",
|
|
754
|
+
values: {},
|
|
755
|
+
previous: null,
|
|
756
|
+
error: outcome.failure === null ? null : errorMessage(outcome.failure)
|
|
757
|
+
});
|
|
758
|
+
if (outcome.reply === null) {
|
|
759
|
+
context.log(`Restarting the controller failed: ${errorMessage(outcome.failure)}`);
|
|
760
|
+
throw new AgentError(errorMessage(outcome.failure), 500);
|
|
761
|
+
}
|
|
762
|
+
return Response.json(outcome.reply);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
];
|
|
766
|
+
|
|
767
|
+
// packages/agent/src/dashboard/index.ts
|
|
768
|
+
import { createRequire } from "node:module";
|
|
769
|
+
import { basename, dirname, resolve } from "node:path";
|
|
770
|
+
import { controllerRestartPath as controllerRestartPath3 } from "@tsplc/server/plant-agent";
|
|
771
|
+
var pages = ["/", "/deployments", "/environment", "/audit", "/access"];
|
|
772
|
+
var dashboardAssets = "/dashboard-assets/";
|
|
773
|
+
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>`;
|
|
774
|
+
var contract = {
|
|
775
|
+
roles,
|
|
776
|
+
controllerRestartPath: controllerRestartPath3,
|
|
777
|
+
permissions: Object.fromEntries(roles.map((role) => [
|
|
778
|
+
role,
|
|
779
|
+
Object.fromEntries(roles.map((required) => [required, allows(role, required)]))
|
|
780
|
+
]))
|
|
781
|
+
};
|
|
782
|
+
var bundle = async () => {
|
|
783
|
+
const sources = resolve(dirname(createRequire(import.meta.url).resolve("@tsplc/agent")), "../src/dashboard/ui");
|
|
784
|
+
const result = await Bun.build({
|
|
785
|
+
entrypoints: [
|
|
786
|
+
resolve(sources, "main.ts"),
|
|
787
|
+
resolve(sources, "dashboard.css")
|
|
788
|
+
],
|
|
789
|
+
target: "browser",
|
|
790
|
+
conditions: ["bun"],
|
|
791
|
+
minify: true,
|
|
792
|
+
naming: "[name].[ext]",
|
|
793
|
+
define: { TSPLC_CONTRACT: JSON.stringify(contract) }
|
|
794
|
+
});
|
|
795
|
+
if (!result.success) {
|
|
796
|
+
throw new Error(`Bundling the dashboard failed:
|
|
797
|
+
${result.logs.map(String).join(`
|
|
798
|
+
`)}`);
|
|
799
|
+
}
|
|
800
|
+
const assets = new Map;
|
|
801
|
+
for (const output of result.outputs) {
|
|
802
|
+
assets.set(basename(output.path), {
|
|
803
|
+
text: await output.text(),
|
|
804
|
+
type: output.type
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
return assets;
|
|
808
|
+
};
|
|
809
|
+
var isPage = (pathname) => pages.some((path) => pathname === path || path !== "/" && pathname.startsWith(`${path}/`));
|
|
810
|
+
var createDashboard = () => {
|
|
811
|
+
let assets;
|
|
812
|
+
return {
|
|
813
|
+
handle: async (request) => {
|
|
814
|
+
const { pathname } = new URL(request.url);
|
|
815
|
+
if (request.method !== "GET") {
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (isPage(pathname)) {
|
|
819
|
+
return new Response(page, {
|
|
820
|
+
headers: {
|
|
821
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
822
|
+
"Cache-Control": "no-cache"
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
if (!pathname.startsWith(dashboardAssets)) {
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
assets ??= bundle();
|
|
830
|
+
try {
|
|
831
|
+
const asset = (await assets).get(pathname.slice(dashboardAssets.length));
|
|
832
|
+
if (!asset) {
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
return new Response(asset.text, {
|
|
836
|
+
headers: { "Content-Type": asset.type, "Cache-Control": "no-cache" }
|
|
837
|
+
});
|
|
838
|
+
} catch (error) {
|
|
839
|
+
assets = undefined;
|
|
840
|
+
return new Response(errorMessage(error), { status: 500 });
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
// packages/agent/src/debugging.ts
|
|
847
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
848
|
+
import { join as join5 } from "node:path";
|
|
849
|
+
import {
|
|
850
|
+
createDebugger,
|
|
851
|
+
createDebugHandler,
|
|
852
|
+
createLoginAdapter,
|
|
853
|
+
loadExplanations,
|
|
854
|
+
loadManifest,
|
|
855
|
+
timelineEntries
|
|
856
|
+
} from "@tsplc/debug";
|
|
857
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
295
858
|
|
|
296
859
|
// packages/agent/src/releases.ts
|
|
297
|
-
import { createHash as
|
|
298
|
-
import { existsSync as
|
|
860
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
861
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
299
862
|
import {
|
|
300
863
|
mkdir,
|
|
301
864
|
mkdtemp,
|
|
302
865
|
readdir,
|
|
303
|
-
readFile as
|
|
304
|
-
rename as
|
|
866
|
+
readFile as readFile3,
|
|
867
|
+
rename as rename3,
|
|
305
868
|
rm,
|
|
306
869
|
stat as stat2,
|
|
307
|
-
writeFile
|
|
870
|
+
writeFile as writeFile2
|
|
308
871
|
} from "node:fs/promises";
|
|
309
|
-
import {
|
|
310
|
-
|
|
872
|
+
import {
|
|
873
|
+
dirname as dirname2,
|
|
874
|
+
isAbsolute,
|
|
875
|
+
join as join3,
|
|
876
|
+
posix,
|
|
877
|
+
relative,
|
|
878
|
+
resolve as resolve2,
|
|
879
|
+
sep
|
|
880
|
+
} from "node:path";
|
|
881
|
+
import { z as z4 } from "zod";
|
|
311
882
|
|
|
312
883
|
// packages/agent/src/transfer.ts
|
|
313
|
-
import { createHash } from "node:crypto";
|
|
314
|
-
var shortDigest = (data) =>
|
|
315
|
-
var fileBucket = (path) =>
|
|
884
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
885
|
+
var shortDigest = (data) => createHash2("sha256").update(data).digest("hex").slice(0, 16);
|
|
886
|
+
var fileBucket = (path) => createHash2("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
|
|
316
887
|
var bucketDigests = (files) => {
|
|
317
888
|
const buckets = Array.from({ length: releaseBuckets }, () => []);
|
|
318
889
|
for (const { path, digest } of files) {
|
|
@@ -368,10 +939,10 @@ var readUpload = async (form) => {
|
|
|
368
939
|
if (form.get("encoding") !== uploadEncoding) {
|
|
369
940
|
throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
|
|
370
941
|
}
|
|
371
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(
|
|
942
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(z4.string().parse(form.get("manifest"))));
|
|
372
943
|
const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
|
|
373
944
|
path: releasePath(name.slice(filePrefix.length)),
|
|
374
|
-
content: Bun.gunzipSync(await
|
|
945
|
+
content: Bun.gunzipSync(await z4.instanceof(File).parse(value).bytes())
|
|
375
946
|
})));
|
|
376
947
|
const upload = { manifest, files };
|
|
377
948
|
checkServer(upload);
|
|
@@ -390,31 +961,31 @@ var readDeployRequest = async (releases, request) => {
|
|
|
390
961
|
if (type.startsWith("multipart/form-data")) {
|
|
391
962
|
const form = await request.formData();
|
|
392
963
|
return {
|
|
393
|
-
settings: deployOptionsSchema.parse(JSON.parse(
|
|
964
|
+
settings: deployOptionsSchema.parse(JSON.parse(z4.string().parse(form.get("options")))),
|
|
394
965
|
upload: await readUpload(form)
|
|
395
966
|
};
|
|
396
967
|
}
|
|
397
968
|
throw new AgentError(`Unsupported deployment content type ${type}`, 415);
|
|
398
969
|
};
|
|
399
970
|
var saveRelease = async (releases, { manifest, files }) => {
|
|
400
|
-
const hash =
|
|
971
|
+
const hash = createHash3("sha256").update(JSON.stringify(manifest));
|
|
401
972
|
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
402
|
-
hash.update(file.path).update(
|
|
973
|
+
hash.update(file.path).update(createHash3("sha256").update(file.content).digest("hex"));
|
|
403
974
|
}
|
|
404
975
|
const id = hash.digest("hex").slice(0, 16);
|
|
405
|
-
const directory =
|
|
406
|
-
if (!
|
|
976
|
+
const directory = join3(releases, id);
|
|
977
|
+
if (!existsSync3(directory)) {
|
|
407
978
|
await mkdir(releases, { recursive: true });
|
|
408
|
-
const staging = await mkdtemp(
|
|
979
|
+
const staging = await mkdtemp(join3(releases, ".upload-"));
|
|
409
980
|
try {
|
|
410
981
|
for (const file of files) {
|
|
411
|
-
await mkdir(
|
|
412
|
-
await
|
|
982
|
+
await mkdir(dirname2(join3(staging, file.path)), { recursive: true });
|
|
983
|
+
await writeFile2(join3(staging, file.path), file.content, {
|
|
413
984
|
mode: file.path === manifest.server ? 493 : 420
|
|
414
985
|
});
|
|
415
986
|
}
|
|
416
|
-
await
|
|
417
|
-
await
|
|
987
|
+
await writeFile2(join3(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
988
|
+
await rename3(staging, directory);
|
|
418
989
|
} catch (cause) {
|
|
419
990
|
await rm(staging, { recursive: true, force: true });
|
|
420
991
|
throw cause;
|
|
@@ -423,14 +994,53 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
423
994
|
return { id, directory, manifest };
|
|
424
995
|
};
|
|
425
996
|
var loadRelease = async (releases, id) => {
|
|
426
|
-
const directory =
|
|
427
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(await
|
|
997
|
+
const directory = join3(releases, id);
|
|
998
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile3(join3(directory, "manifest.json"), "utf8")));
|
|
428
999
|
return { id, directory, manifest };
|
|
429
1000
|
};
|
|
1001
|
+
var listReleaseFiles = async (releases, id) => {
|
|
1002
|
+
const directory = join3(releases, id);
|
|
1003
|
+
if (!existsSync3(join3(directory, "manifest.json"))) {
|
|
1004
|
+
throw new AgentError(`The release ${id} is no longer stored`, 404);
|
|
1005
|
+
}
|
|
1006
|
+
const files = [];
|
|
1007
|
+
for await (const found of new Bun.Glob("**/*").scan({
|
|
1008
|
+
cwd: directory,
|
|
1009
|
+
dot: true
|
|
1010
|
+
})) {
|
|
1011
|
+
files.push({
|
|
1012
|
+
path: found.split(sep).join("/"),
|
|
1013
|
+
size: (await stat2(join3(directory, found))).size
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
return files.sort((left, right) => left.path.localeCompare(right.path));
|
|
1017
|
+
};
|
|
1018
|
+
var readReleaseFile = async (releases, id, path) => {
|
|
1019
|
+
const directory = resolve2(releases, id);
|
|
1020
|
+
const file = resolve2(directory, path);
|
|
1021
|
+
const inside = relative(directory, file);
|
|
1022
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
|
|
1023
|
+
throw new AgentError(`${path} isn't a path in a release`, 400);
|
|
1024
|
+
}
|
|
1025
|
+
if (!await stat2(file).then((found) => found.isFile(), () => false)) {
|
|
1026
|
+
throw new AgentError(`The release ${id} has no file ${path}`, 404);
|
|
1027
|
+
}
|
|
1028
|
+
return Bun.file(file);
|
|
1029
|
+
};
|
|
1030
|
+
var pruneReleases = async (releases, kept) => {
|
|
1031
|
+
if (!existsSync3(releases)) {
|
|
1032
|
+
return [];
|
|
1033
|
+
}
|
|
1034
|
+
const removed = (await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !kept.has(entry.name)).map((entry) => entry.name);
|
|
1035
|
+
for (const id of removed) {
|
|
1036
|
+
await rm(join3(releases, id), { recursive: true, force: true });
|
|
1037
|
+
}
|
|
1038
|
+
return removed;
|
|
1039
|
+
};
|
|
430
1040
|
var createReleaseStore = (releases) => {
|
|
431
1041
|
const indexes = new Map;
|
|
432
1042
|
const readIndex = async (id) => {
|
|
433
|
-
const directory =
|
|
1043
|
+
const directory = join3(releases, id);
|
|
434
1044
|
const files = new Map;
|
|
435
1045
|
for await (const found of new Bun.Glob("**/*").scan({
|
|
436
1046
|
cwd: directory,
|
|
@@ -438,7 +1048,7 @@ var createReleaseStore = (releases) => {
|
|
|
438
1048
|
})) {
|
|
439
1049
|
const path = found.split(sep).join("/");
|
|
440
1050
|
if (path !== "manifest.json") {
|
|
441
|
-
files.set(path, shortDigest(await
|
|
1051
|
+
files.set(path, shortDigest(await readFile3(join3(directory, found))));
|
|
442
1052
|
}
|
|
443
1053
|
}
|
|
444
1054
|
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
@@ -455,12 +1065,12 @@ var createReleaseStore = (releases) => {
|
|
|
455
1065
|
return reading;
|
|
456
1066
|
};
|
|
457
1067
|
const newest = async () => {
|
|
458
|
-
if (!
|
|
1068
|
+
if (!existsSync3(releases)) {
|
|
459
1069
|
return;
|
|
460
1070
|
}
|
|
461
1071
|
const stored = await Promise.all((await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map(async ({ name }) => ({
|
|
462
1072
|
name,
|
|
463
|
-
created: (await stat2(
|
|
1073
|
+
created: (await stat2(join3(releases, name))).mtimeMs
|
|
464
1074
|
})));
|
|
465
1075
|
return stored.sort((left, right) => right.created - left.created)[0]?.name;
|
|
466
1076
|
};
|
|
@@ -468,7 +1078,7 @@ var createReleaseStore = (releases) => {
|
|
|
468
1078
|
compare: async (buckets, deployed) => {
|
|
469
1079
|
const candidates = [
|
|
470
1080
|
...new Set([deployed, await newest()].filter((id) => id != null))
|
|
471
|
-
].filter((id) =>
|
|
1081
|
+
].filter((id) => existsSync3(join3(releases, id, "manifest.json")));
|
|
472
1082
|
const compared = await Promise.all(candidates.map(async (id) => {
|
|
473
1083
|
const { files, buckets: stored } = await index(id);
|
|
474
1084
|
const changed = buckets.flatMap((digest, bucket) => stored[bucket] === digest ? [] : [bucket]);
|
|
@@ -496,13 +1106,13 @@ var createReleaseStore = (releases) => {
|
|
|
496
1106
|
throw new AgentError("The release upload sends a file twice", 400);
|
|
497
1107
|
}
|
|
498
1108
|
if (base !== null) {
|
|
499
|
-
if (!
|
|
1109
|
+
if (!existsSync3(join3(releases, base, "manifest.json"))) {
|
|
500
1110
|
throw new AgentError(`The release ${base} this upload builds on is gone; deploy again`, 409);
|
|
501
1111
|
}
|
|
502
1112
|
const removed = new Set(remove);
|
|
503
1113
|
const reused = [...(await index(base)).files.keys()].filter((path) => !removed.has(path) && !files.has(path));
|
|
504
1114
|
for (const path of reused) {
|
|
505
|
-
files.set(path, new Uint8Array(await
|
|
1115
|
+
files.set(path, new Uint8Array(await readFile3(join3(releases, base, path))));
|
|
506
1116
|
}
|
|
507
1117
|
}
|
|
508
1118
|
const assembled = bucketDigests([...files].map(([path, content]) => ({
|
|
@@ -523,11 +1133,15 @@ var createReleaseStore = (releases) => {
|
|
|
523
1133
|
};
|
|
524
1134
|
|
|
525
1135
|
// packages/agent/src/secrets.ts
|
|
526
|
-
import { mkdir as mkdir2, readFile as
|
|
527
|
-
import { dirname as
|
|
528
|
-
import {
|
|
1136
|
+
import { mkdir as mkdir2, readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
1137
|
+
import { dirname as dirname3, join as join4, relative as relative2, sep as sep2 } from "node:path";
|
|
1138
|
+
import {
|
|
1139
|
+
secretPlaceholder,
|
|
1140
|
+
secretValue as secretValue2
|
|
1141
|
+
} from "@tsplc/config";
|
|
529
1142
|
import { escapeString } from "@tsplc/iec/st";
|
|
530
1143
|
var agentService = "tsplc-agent";
|
|
1144
|
+
var environmentService = "tsplc-agent-env";
|
|
531
1145
|
var controllerSecretNames = {
|
|
532
1146
|
username: "controller-username",
|
|
533
1147
|
password: "controller-password"
|
|
@@ -561,7 +1175,7 @@ var readSecrets = async (secrets) => {
|
|
|
561
1175
|
const missing = [];
|
|
562
1176
|
for (const name of secrets.names) {
|
|
563
1177
|
const value = await Bun.secrets.get({ service, name });
|
|
564
|
-
const valid =
|
|
1178
|
+
const valid = secretValue2.safeParse(value);
|
|
565
1179
|
if (!value) {
|
|
566
1180
|
missing.push(name);
|
|
567
1181
|
} else if (!valid.success) {
|
|
@@ -575,7 +1189,31 @@ var readSecrets = async (secrets) => {
|
|
|
575
1189
|
}
|
|
576
1190
|
return values;
|
|
577
1191
|
};
|
|
578
|
-
var releaseVariable = async (manifest, name, environment) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : environment[name];
|
|
1192
|
+
var releaseVariable = async (manifest, name, environment) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : manifest.values[name] ?? environment[name];
|
|
1193
|
+
var storedSecrets = async (secrets) => {
|
|
1194
|
+
if (!secrets) {
|
|
1195
|
+
return {};
|
|
1196
|
+
}
|
|
1197
|
+
const stored = await Promise.all(secrets.names.map(async (name) => ({
|
|
1198
|
+
name,
|
|
1199
|
+
value: await Bun.secrets.get({ service: secrets.service, name })
|
|
1200
|
+
})));
|
|
1201
|
+
return Object.fromEntries(stored.flatMap(({ name, value }) => value === null ? [] : [[name, value]]));
|
|
1202
|
+
};
|
|
1203
|
+
var serverEnvironment = async (releases, executable, environment) => {
|
|
1204
|
+
const [id = ""] = relative2(releases, executable).split(sep2);
|
|
1205
|
+
const manifest = await loadRelease(releases, id).then((release) => release.manifest, () => {
|
|
1206
|
+
return;
|
|
1207
|
+
});
|
|
1208
|
+
if (!manifest) {
|
|
1209
|
+
return environment;
|
|
1210
|
+
}
|
|
1211
|
+
return {
|
|
1212
|
+
...environment,
|
|
1213
|
+
...manifest.values,
|
|
1214
|
+
...await storedSecrets(manifest.secrets)
|
|
1215
|
+
};
|
|
1216
|
+
};
|
|
579
1217
|
var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
|
|
580
1218
|
var withSecrets = async (config, secrets, directory) => {
|
|
581
1219
|
await rm2(directory, { recursive: true, force: true });
|
|
@@ -583,14 +1221,14 @@ var withSecrets = async (config, secrets, directory) => {
|
|
|
583
1221
|
cwd: config.sourceDir,
|
|
584
1222
|
dot: true
|
|
585
1223
|
})) {
|
|
586
|
-
const file =
|
|
587
|
-
await mkdir2(
|
|
588
|
-
await
|
|
1224
|
+
const file = join4(directory, path);
|
|
1225
|
+
await mkdir2(dirname3(file), { recursive: true });
|
|
1226
|
+
await writeFile3(file, fillSecrets(await readFile4(join4(config.sourceDir, path), "utf8"), secrets));
|
|
589
1227
|
}
|
|
590
1228
|
return {
|
|
591
1229
|
...config,
|
|
592
1230
|
sourceDir: directory,
|
|
593
|
-
entry:
|
|
1231
|
+
entry: join4(directory, relative2(config.sourceDir, config.entry))
|
|
594
1232
|
};
|
|
595
1233
|
};
|
|
596
1234
|
|
|
@@ -604,8 +1242,8 @@ var createDebugging = (context) => {
|
|
|
604
1242
|
return null;
|
|
605
1243
|
}
|
|
606
1244
|
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
607
|
-
const manifestFile =
|
|
608
|
-
if (!
|
|
1245
|
+
const manifestFile = join5(directory, debugManifestFile);
|
|
1246
|
+
if (!existsSync4(manifestFile)) {
|
|
609
1247
|
return null;
|
|
610
1248
|
}
|
|
611
1249
|
const manifest = await loadManifest(manifestFile);
|
|
@@ -634,60 +1272,853 @@ var createDebugging = (context) => {
|
|
|
634
1272
|
...(await readJsonl(state.paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
635
1273
|
...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
636
1274
|
],
|
|
637
|
-
explanations: await loadExplanations(manifestFile, manifest),
|
|
638
|
-
forced: async () => {
|
|
639
|
-
const login = await context.loginStatus();
|
|
640
|
-
return login && "forced" in login ? login.forced : null;
|
|
641
|
-
},
|
|
642
|
-
log
|
|
1275
|
+
explanations: await loadExplanations(manifestFile, manifest),
|
|
1276
|
+
forced: async () => {
|
|
1277
|
+
const login = await context.loginStatus();
|
|
1278
|
+
return login && "forced" in login ? login.forced : null;
|
|
1279
|
+
},
|
|
1280
|
+
log
|
|
1281
|
+
});
|
|
1282
|
+
return { debug, handle: createDebugHandler(debug, log) };
|
|
1283
|
+
};
|
|
1284
|
+
const startOrLog = () => start().catch((error) => {
|
|
1285
|
+
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
1286
|
+
return null;
|
|
1287
|
+
});
|
|
1288
|
+
let current = startOrLog();
|
|
1289
|
+
return {
|
|
1290
|
+
handle: async (request, route) => {
|
|
1291
|
+
const debugging = await current;
|
|
1292
|
+
if (!debugging) {
|
|
1293
|
+
return Response.json({
|
|
1294
|
+
error: "The deployed release has no debug manifest, or the debugger failed to start"
|
|
1295
|
+
}, { status: 503 });
|
|
1296
|
+
}
|
|
1297
|
+
return debugging.handle(request, route);
|
|
1298
|
+
},
|
|
1299
|
+
record: async ({ at, ...audit }) => {
|
|
1300
|
+
(await current)?.debug.record(timelineEntries.audit(at, audit));
|
|
1301
|
+
},
|
|
1302
|
+
restart: () => {
|
|
1303
|
+
current = current.then(async (debugging) => {
|
|
1304
|
+
await debugging?.debug.close();
|
|
1305
|
+
return startOrLog();
|
|
1306
|
+
});
|
|
1307
|
+
},
|
|
1308
|
+
close: async () => {
|
|
1309
|
+
await (await current)?.debug.close();
|
|
1310
|
+
}
|
|
1311
|
+
};
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
// packages/agent/src/deploy.ts
|
|
1315
|
+
import {
|
|
1316
|
+
controllerBaseline,
|
|
1317
|
+
findControllerLogin,
|
|
1318
|
+
restartWarmController,
|
|
1319
|
+
reviewWarmController,
|
|
1320
|
+
settleWarmController,
|
|
1321
|
+
startWarmController,
|
|
1322
|
+
updateWarmController,
|
|
1323
|
+
workerScriptsDigest
|
|
1324
|
+
} from "@tsplc/build";
|
|
1325
|
+
|
|
1326
|
+
// packages/agent/src/deployments/runner.ts
|
|
1327
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
1328
|
+
import { join as join7 } from "node:path";
|
|
1329
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1330
|
+
import {
|
|
1331
|
+
DownloadRequiredError,
|
|
1332
|
+
describeFinding,
|
|
1333
|
+
requiresDownload,
|
|
1334
|
+
transferRollback
|
|
1335
|
+
} from "@tsplc/build";
|
|
1336
|
+
import { loadManifest as loadManifest2 } from "@tsplc/debug";
|
|
1337
|
+
import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
|
|
1338
|
+
|
|
1339
|
+
// packages/agent/src/deployments/health.ts
|
|
1340
|
+
import { z as z5 } from "zod";
|
|
1341
|
+
var serverHealthSchema = z5.looseObject({ plcConnected: z5.boolean() });
|
|
1342
|
+
var healthTimeoutMs = 5000;
|
|
1343
|
+
var plcHealth = (body) => {
|
|
1344
|
+
const parsed = serverHealthSchema.safeParse(body);
|
|
1345
|
+
if (!parsed.success) {
|
|
1346
|
+
return "unknown";
|
|
1347
|
+
}
|
|
1348
|
+
return parsed.data.plcConnected ? "ok" : "failed";
|
|
1349
|
+
};
|
|
1350
|
+
var serverHealth = async (healthUrl, server) => {
|
|
1351
|
+
if (!healthUrl) {
|
|
1352
|
+
return {
|
|
1353
|
+
server: server.status()?.running ? "ok" : "failed",
|
|
1354
|
+
plc: "unknown"
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
const response = await fetch(healthUrl, {
|
|
1358
|
+
signal: AbortSignal.timeout(healthTimeoutMs)
|
|
1359
|
+
}).catch(() => null);
|
|
1360
|
+
if (!response?.ok) {
|
|
1361
|
+
return { server: "failed", plc: "unknown" };
|
|
1362
|
+
}
|
|
1363
|
+
return {
|
|
1364
|
+
server: "ok",
|
|
1365
|
+
plc: plcHealth(await response.json().catch(() => null))
|
|
1366
|
+
};
|
|
1367
|
+
};
|
|
1368
|
+
var noServer = {
|
|
1369
|
+
server: "none",
|
|
1370
|
+
plc: "unknown"
|
|
1371
|
+
};
|
|
1372
|
+
var checkHealth = async (options) => {
|
|
1373
|
+
const controller = options.controllerState === "run" ? "ok" : "failed";
|
|
1374
|
+
const { server, plc } = options.hasServer ? await serverHealth(options.healthUrl, options.server) : noServer;
|
|
1375
|
+
const problems = [
|
|
1376
|
+
controller === "failed" && `The controller's application is in state ${options.controllerState}`,
|
|
1377
|
+
server === "failed" && "The server isn't running",
|
|
1378
|
+
plc === "failed" && "The server isn't connected to the PLC"
|
|
1379
|
+
].filter((problem) => typeof problem === "string");
|
|
1380
|
+
return {
|
|
1381
|
+
controller,
|
|
1382
|
+
server,
|
|
1383
|
+
plc,
|
|
1384
|
+
detail: problems.length ? problems.join(". ") : null
|
|
1385
|
+
};
|
|
1386
|
+
};
|
|
1387
|
+
var healthy = (health) => health.controller === "ok" && health.server !== "failed";
|
|
1388
|
+
|
|
1389
|
+
// packages/agent/src/deployments/store.ts
|
|
1390
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1391
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
1392
|
+
import {
|
|
1393
|
+
appendFile,
|
|
1394
|
+
mkdir as mkdir3,
|
|
1395
|
+
readdir as readdir2,
|
|
1396
|
+
readFile as readFile5,
|
|
1397
|
+
rename as rename4,
|
|
1398
|
+
rm as rm3,
|
|
1399
|
+
writeFile as writeFile4
|
|
1400
|
+
} from "node:fs/promises";
|
|
1401
|
+
import { join as join6 } from "node:path";
|
|
1402
|
+
var finalStates = ["ready", "error", "canceled"];
|
|
1403
|
+
var isFinished = (record) => finalStates.includes(record.state);
|
|
1404
|
+
var activeDeployments = (records) => {
|
|
1405
|
+
const running = records.filter((record) => record.activeFrom !== null);
|
|
1406
|
+
const newest = (candidates) => candidates.reduce((best, record) => best && (best.activeFrom ?? "") >= (record.activeFrom ?? "") ? best : record, null)?.id ?? null;
|
|
1407
|
+
return {
|
|
1408
|
+
current: newest(running.filter((record) => record.activeUntil === null)),
|
|
1409
|
+
lastGood: newest(running.filter((record) => record.state === "ready"))
|
|
1410
|
+
};
|
|
1411
|
+
};
|
|
1412
|
+
var parseJson = (text) => {
|
|
1413
|
+
try {
|
|
1414
|
+
return JSON.parse(text);
|
|
1415
|
+
} catch {
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
};
|
|
1419
|
+
var newId = () => `dpl_${[...randomBytes2(20)].map((byte) => (byte % 36).toString(36)).join("")}`;
|
|
1420
|
+
var openDeploymentStore = async (options) => {
|
|
1421
|
+
const { directory } = options;
|
|
1422
|
+
const records = new Map;
|
|
1423
|
+
const sequences = new Map;
|
|
1424
|
+
const writes = new Map;
|
|
1425
|
+
const listeners = new Map;
|
|
1426
|
+
await mkdir3(directory, { recursive: true });
|
|
1427
|
+
for (const entry of await readdir2(directory, { withFileTypes: true })) {
|
|
1428
|
+
const file = join6(directory, entry.name, "record.json");
|
|
1429
|
+
if (!entry.isDirectory() || !existsSync5(file)) {
|
|
1430
|
+
continue;
|
|
1431
|
+
}
|
|
1432
|
+
const parsed = deploymentRecordSchema.safeParse(parseJson(await readFile5(file, "utf8")));
|
|
1433
|
+
if (parsed.success && parsed.data.id === entry.name) {
|
|
1434
|
+
records.set(parsed.data.id, parsed.data);
|
|
1435
|
+
} else {
|
|
1436
|
+
options.log(`Skipping the unreadable deployment record ${file}`);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
const recordDirectory = (id) => join6(directory, id);
|
|
1440
|
+
const logFile = (id) => join6(recordDirectory(id), "log.jsonl");
|
|
1441
|
+
const inTurn = (id, write) => {
|
|
1442
|
+
const next = (writes.get(id) ?? Promise.resolve()).then(write);
|
|
1443
|
+
writes.set(id, next.then(() => {
|
|
1444
|
+
return;
|
|
1445
|
+
}, (error) => options.log(`Writing deployment ${id} failed: ${errorMessage(error)}`)));
|
|
1446
|
+
return next;
|
|
1447
|
+
};
|
|
1448
|
+
const emit = (id, event) => {
|
|
1449
|
+
for (const listener of listeners.get(id) ?? []) {
|
|
1450
|
+
listener(event);
|
|
1451
|
+
}
|
|
1452
|
+
};
|
|
1453
|
+
const readLines = async (id) => {
|
|
1454
|
+
const file = logFile(id);
|
|
1455
|
+
if (!existsSync5(file)) {
|
|
1456
|
+
return [];
|
|
1457
|
+
}
|
|
1458
|
+
return (await readFile5(file, "utf8")).split(`
|
|
1459
|
+
`).filter(Boolean).flatMap((line) => {
|
|
1460
|
+
const parsed = deploymentLogLineSchema.safeParse(parseJson(line));
|
|
1461
|
+
return parsed.success ? [parsed.data] : [];
|
|
1462
|
+
});
|
|
1463
|
+
};
|
|
1464
|
+
const writeRecord = (record) => inTurn(record.id, async () => {
|
|
1465
|
+
const latest = records.get(record.id);
|
|
1466
|
+
if (!latest) {
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
const file = join6(recordDirectory(record.id), "record.json");
|
|
1470
|
+
const temporary = `${file}.tmp`;
|
|
1471
|
+
await mkdir3(recordDirectory(record.id), { recursive: true });
|
|
1472
|
+
await writeFile4(temporary, JSON.stringify(latest, null, 2));
|
|
1473
|
+
await rename4(temporary, file);
|
|
1474
|
+
});
|
|
1475
|
+
const existing = (id) => {
|
|
1476
|
+
const record = records.get(id);
|
|
1477
|
+
if (!record) {
|
|
1478
|
+
throw new Error(`No deployment ${id}`);
|
|
1479
|
+
}
|
|
1480
|
+
return record;
|
|
1481
|
+
};
|
|
1482
|
+
return {
|
|
1483
|
+
newId,
|
|
1484
|
+
get: (id) => records.get(id),
|
|
1485
|
+
list: () => [...records.values()].sort((left, right) => right.createdAt.localeCompare(left.createdAt)),
|
|
1486
|
+
create: async (record) => {
|
|
1487
|
+
records.set(record.id, record);
|
|
1488
|
+
sequences.set(record.id, 0);
|
|
1489
|
+
await writeRecord(record);
|
|
1490
|
+
return record;
|
|
1491
|
+
},
|
|
1492
|
+
update: async (id, change) => {
|
|
1493
|
+
const record = {
|
|
1494
|
+
...change(existing(id)),
|
|
1495
|
+
updatedAt: options.now().toISOString()
|
|
1496
|
+
};
|
|
1497
|
+
records.set(id, record);
|
|
1498
|
+
emit(id, { kind: "record", record });
|
|
1499
|
+
await writeRecord(record);
|
|
1500
|
+
return record;
|
|
1501
|
+
},
|
|
1502
|
+
log: (id, entry) => inTurn(id, async () => {
|
|
1503
|
+
const last = sequences.get(id) ?? (await readLines(id)).reduce((highest, line) => Math.max(highest, line.seq), 0);
|
|
1504
|
+
const line = {
|
|
1505
|
+
seq: last + 1,
|
|
1506
|
+
at: options.now().toISOString(),
|
|
1507
|
+
...entry
|
|
1508
|
+
};
|
|
1509
|
+
sequences.set(id, line.seq);
|
|
1510
|
+
await mkdir3(recordDirectory(id), { recursive: true });
|
|
1511
|
+
await appendFile(logFile(id), `${JSON.stringify(line)}
|
|
1512
|
+
`);
|
|
1513
|
+
emit(id, { kind: "log", line });
|
|
1514
|
+
return line;
|
|
1515
|
+
}),
|
|
1516
|
+
flush: async (id) => {
|
|
1517
|
+
await writes.get(id);
|
|
1518
|
+
},
|
|
1519
|
+
lines: async (id, after) => {
|
|
1520
|
+
await writes.get(id);
|
|
1521
|
+
return (await readLines(id)).filter((line) => line.seq > after);
|
|
1522
|
+
},
|
|
1523
|
+
subscribe: (id, listener) => {
|
|
1524
|
+
const subscribed = listeners.get(id) ?? new Set;
|
|
1525
|
+
subscribed.add(listener);
|
|
1526
|
+
listeners.set(id, subscribed);
|
|
1527
|
+
return () => {
|
|
1528
|
+
subscribed.delete(listener);
|
|
1529
|
+
};
|
|
1530
|
+
},
|
|
1531
|
+
remove: (id) => inTurn(id, async () => {
|
|
1532
|
+
records.delete(id);
|
|
1533
|
+
sequences.delete(id);
|
|
1534
|
+
await rm3(recordDirectory(id), { recursive: true, force: true });
|
|
1535
|
+
})
|
|
1536
|
+
};
|
|
1537
|
+
};
|
|
1538
|
+
|
|
1539
|
+
// packages/agent/src/deployments/retention.ts
|
|
1540
|
+
var retentionMs = 14 * 24 * 60 * 60 * 1000;
|
|
1541
|
+
var pruneDeployments = async (options) => {
|
|
1542
|
+
const { store } = options;
|
|
1543
|
+
const records = store.list();
|
|
1544
|
+
const { current, lastGood } = activeDeployments(records);
|
|
1545
|
+
const cutoff = options.now().getTime() - retentionMs;
|
|
1546
|
+
const expired = records.filter((record) => Date.parse(record.createdAt) < cutoff && record.id !== current && record.id !== lastGood && isFinished(record));
|
|
1547
|
+
for (const record of expired) {
|
|
1548
|
+
await store.remove(record.id);
|
|
1549
|
+
}
|
|
1550
|
+
const kept = new Set(store.list().map((record) => record.release));
|
|
1551
|
+
if (options.deployed) {
|
|
1552
|
+
kept.add(options.deployed.id);
|
|
1553
|
+
const server = options.deployed.server?.split("/")[0];
|
|
1554
|
+
if (server) {
|
|
1555
|
+
kept.add(server);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
return {
|
|
1559
|
+
deployments: expired.map((record) => record.id),
|
|
1560
|
+
releases: await pruneReleases(options.releases, kept)
|
|
1561
|
+
};
|
|
1562
|
+
};
|
|
1563
|
+
|
|
1564
|
+
// packages/agent/src/deployments/runner.ts
|
|
1565
|
+
class Canceled extends Error {
|
|
1566
|
+
}
|
|
1567
|
+
var cancelable = [
|
|
1568
|
+
"queued",
|
|
1569
|
+
"building",
|
|
1570
|
+
"awaitingApproval"
|
|
1571
|
+
];
|
|
1572
|
+
var retryMs = 1000;
|
|
1573
|
+
var releaseBuild = async (release) => {
|
|
1574
|
+
const file = join7(release.directory, debugManifestFile2);
|
|
1575
|
+
return existsSync6(file) ? (await loadManifest2(file)).build.id : null;
|
|
1576
|
+
};
|
|
1577
|
+
var createDeploymentRunner = (context) => {
|
|
1578
|
+
const { store, state, operations, controller } = context;
|
|
1579
|
+
const pending = new Map;
|
|
1580
|
+
const queue = [];
|
|
1581
|
+
let draining = false;
|
|
1582
|
+
let releasesTurn = Promise.resolve();
|
|
1583
|
+
const withReleases = (run) => {
|
|
1584
|
+
const next = releasesTurn.then(run);
|
|
1585
|
+
releasesTurn = next.catch(() => {
|
|
1586
|
+
return;
|
|
1587
|
+
});
|
|
1588
|
+
return next;
|
|
1589
|
+
};
|
|
1590
|
+
const timestamp = () => context.now().toISOString();
|
|
1591
|
+
const recordOf = (id) => {
|
|
1592
|
+
const record = store.get(id);
|
|
1593
|
+
if (!record) {
|
|
1594
|
+
throw new AgentError(`No deployment ${id}`, 404);
|
|
1595
|
+
}
|
|
1596
|
+
return record;
|
|
1597
|
+
};
|
|
1598
|
+
const say = (item, level, message) => {
|
|
1599
|
+
const phase = recordOf(item.id).phases.find((entry) => entry.outcome === "running")?.name ?? null;
|
|
1600
|
+
store.log(item.id, { level, phase, message }).catch(() => {
|
|
1601
|
+
return;
|
|
1602
|
+
});
|
|
1603
|
+
};
|
|
1604
|
+
const update = (item, change) => store.update(item.id, change);
|
|
1605
|
+
const startPhase = (item, name) => update(item, (record) => ({
|
|
1606
|
+
...record,
|
|
1607
|
+
phases: [
|
|
1608
|
+
...record.phases,
|
|
1609
|
+
{ name, startedAt: timestamp(), finishedAt: null, outcome: "running" }
|
|
1610
|
+
]
|
|
1611
|
+
}));
|
|
1612
|
+
const finishPhase = (item, outcome) => update(item, (record) => ({
|
|
1613
|
+
...record,
|
|
1614
|
+
phases: record.phases.map((phase) => phase.outcome === "running" ? { ...phase, finishedAt: timestamp(), outcome } : phase)
|
|
1615
|
+
}));
|
|
1616
|
+
const skipPhase = (item, name) => update(item, (record) => ({
|
|
1617
|
+
...record,
|
|
1618
|
+
phases: [
|
|
1619
|
+
...record.phases,
|
|
1620
|
+
{
|
|
1621
|
+
name,
|
|
1622
|
+
startedAt: timestamp(),
|
|
1623
|
+
finishedAt: timestamp(),
|
|
1624
|
+
outcome: "skipped"
|
|
1625
|
+
}
|
|
1626
|
+
]
|
|
1627
|
+
}));
|
|
1628
|
+
const enter = (item, state, changes = {}) => update(item, (record) => ({ ...record, ...changes, state }));
|
|
1629
|
+
const requireNotCanceled = (item) => {
|
|
1630
|
+
if (item.canceled) {
|
|
1631
|
+
throw new Canceled;
|
|
1632
|
+
}
|
|
1633
|
+
};
|
|
1634
|
+
const blocker = () => operations.held() ? "the plant agent's upgrade" : operations.busy();
|
|
1635
|
+
const whenFree = async (item, run) => {
|
|
1636
|
+
const waitingFor = blocker();
|
|
1637
|
+
if (waitingFor) {
|
|
1638
|
+
say(item, "info", `Waiting for ${waitingFor} to finish`);
|
|
1639
|
+
}
|
|
1640
|
+
while (blocker()) {
|
|
1641
|
+
requireNotCanceled(item);
|
|
1642
|
+
await delay(retryMs);
|
|
1643
|
+
}
|
|
1644
|
+
return operations.exclusive("a deployment", run);
|
|
1645
|
+
};
|
|
1646
|
+
const awaitApproval = async (item, reason, message) => {
|
|
1647
|
+
if (!item.waitsForApproval) {
|
|
1648
|
+
throw new AgentError(message, 409, {
|
|
1649
|
+
downloadRequired: reason === "downloadRequired"
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1652
|
+
item.approved = false;
|
|
1653
|
+
item.running = false;
|
|
1654
|
+
say(item, "warning", message);
|
|
1655
|
+
await enter(item, "awaitingApproval", { approval: { reason, message } });
|
|
1656
|
+
return null;
|
|
1657
|
+
};
|
|
1658
|
+
const prepare = async (item) => {
|
|
1659
|
+
const warnings = await controller.ready();
|
|
1660
|
+
const target = await state.requireTarget();
|
|
1661
|
+
const config = await withSecrets(controllerConfig(item.release, target, state.paths.controller, context.codesys), await readSecrets(item.release.manifest.secrets), state.paths.sources);
|
|
1662
|
+
await controller.settle(config);
|
|
1663
|
+
return { config, warnings };
|
|
1664
|
+
};
|
|
1665
|
+
const progress = (item) => (message) => say(item, "info", message);
|
|
1666
|
+
const review = async (item, config) => {
|
|
1667
|
+
const { mode } = recordOf(item.id);
|
|
1668
|
+
await startPhase(item, "review");
|
|
1669
|
+
const result = await controller.review(config, {
|
|
1670
|
+
credentials: await controllerCredentials(item.credentials),
|
|
1671
|
+
onProgress: progress(item)
|
|
1672
|
+
});
|
|
1673
|
+
await update(item, (record) => ({ ...record, findings: result.findings }));
|
|
1674
|
+
await finishPhase(item, "ok");
|
|
1675
|
+
for (const finding of result.findings) {
|
|
1676
|
+
say(item, finding.refuses ? "warning" : "info", describeFinding(finding));
|
|
1677
|
+
}
|
|
1678
|
+
requireNotCanceled(item);
|
|
1679
|
+
if (!result.possible) {
|
|
1680
|
+
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`);
|
|
1681
|
+
}
|
|
1682
|
+
if (mode === "review") {
|
|
1683
|
+
return awaitApproval(item, "review", "Review the online change's findings, then approve it to apply");
|
|
1684
|
+
}
|
|
1685
|
+
return config;
|
|
1686
|
+
};
|
|
1687
|
+
const build = async (item) => {
|
|
1688
|
+
await finishPhase(item, "ok");
|
|
1689
|
+
await enter(item, "building");
|
|
1690
|
+
await startPhase(item, "build");
|
|
1691
|
+
const { config, warnings } = await prepare(item);
|
|
1692
|
+
for (const warning of warnings) {
|
|
1693
|
+
say(item, "warning", warning);
|
|
1694
|
+
}
|
|
1695
|
+
const { operation, mode } = recordOf(item.id);
|
|
1696
|
+
const baseline = operation === "download" ? "valid" : await controller.baseline();
|
|
1697
|
+
await finishPhase(item, "ok");
|
|
1698
|
+
requireNotCanceled(item);
|
|
1699
|
+
if (baseline !== "valid") {
|
|
1700
|
+
await skipPhase(item, "review");
|
|
1701
|
+
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");
|
|
1702
|
+
}
|
|
1703
|
+
if (operation === "online-change") {
|
|
1704
|
+
return review(item, config);
|
|
1705
|
+
}
|
|
1706
|
+
await skipPhase(item, "review");
|
|
1707
|
+
if (mode === "review") {
|
|
1708
|
+
return awaitApproval(item, "review", "Approve it to apply as a full download, which stops the application");
|
|
1709
|
+
}
|
|
1710
|
+
return config;
|
|
1711
|
+
};
|
|
1712
|
+
const apply = async (item, config) => {
|
|
1713
|
+
requireNotCanceled(item);
|
|
1714
|
+
const { operation } = recordOf(item.id);
|
|
1715
|
+
await enter(item, "applying", { approval: null });
|
|
1716
|
+
await startPhase(item, "apply");
|
|
1717
|
+
say(item, "info", `Starting the ${operation}`);
|
|
1718
|
+
const receipt = await controller.apply(config, operation, {
|
|
1719
|
+
initializeUser: item.initializeUser,
|
|
1720
|
+
credentials: await controllerCredentials(item.credentials),
|
|
1721
|
+
onProgress: progress(item)
|
|
1722
|
+
}).catch(async (error) => {
|
|
1723
|
+
if (operation === "download" || !requiresDownload(error)) {
|
|
1724
|
+
throw error;
|
|
1725
|
+
}
|
|
1726
|
+
await finishPhase(item, "failed");
|
|
1727
|
+
if (error instanceof DownloadRequiredError) {
|
|
1728
|
+
await update(item, (record) => ({
|
|
1729
|
+
...record,
|
|
1730
|
+
findings: error.findings
|
|
1731
|
+
}));
|
|
1732
|
+
}
|
|
1733
|
+
return awaitApproval(item, "downloadRequired", errorMessage(error));
|
|
1734
|
+
});
|
|
1735
|
+
if (!receipt) {
|
|
1736
|
+
return null;
|
|
1737
|
+
}
|
|
1738
|
+
await update(item, (record) => ({
|
|
1739
|
+
...record,
|
|
1740
|
+
controllerIds: receipt.controllerIds
|
|
1741
|
+
}));
|
|
1742
|
+
await finishPhase(item, "ok");
|
|
1743
|
+
return receipt;
|
|
1744
|
+
};
|
|
1745
|
+
const startServer = async (item, serverPath) => {
|
|
1746
|
+
if (!serverPath) {
|
|
1747
|
+
await skipPhase(item, "server");
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
await startPhase(item, "server");
|
|
1751
|
+
say(item, "info", "Starting the new server");
|
|
1752
|
+
const failure = await context.server.replace(join7(state.paths.releases, serverPath)).then(() => {
|
|
1753
|
+
return;
|
|
1754
|
+
}, (error) => errorMessage(error));
|
|
1755
|
+
await finishPhase(item, failure === undefined ? "ok" : "failed");
|
|
1756
|
+
return failure;
|
|
1757
|
+
};
|
|
1758
|
+
const activate = async (item) => {
|
|
1759
|
+
const at = timestamp();
|
|
1760
|
+
const { current } = activeDeployments(store.list());
|
|
1761
|
+
if (current && current !== item.id) {
|
|
1762
|
+
await store.update(current, (record) => ({
|
|
1763
|
+
...record,
|
|
1764
|
+
activeUntil: at
|
|
1765
|
+
}));
|
|
1766
|
+
}
|
|
1767
|
+
await update(item, (record) => ({
|
|
1768
|
+
...record,
|
|
1769
|
+
activeFrom: at,
|
|
1770
|
+
activeUntil: null
|
|
1771
|
+
}));
|
|
1772
|
+
};
|
|
1773
|
+
const start = async (item, receipt) => {
|
|
1774
|
+
const { release } = item;
|
|
1775
|
+
const record = recordOf(item.id);
|
|
1776
|
+
await enter(item, "starting");
|
|
1777
|
+
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
1778
|
+
const previous = await state.release();
|
|
1779
|
+
const serverFailure = await startServer(item, serverPath);
|
|
1780
|
+
const deployed = {
|
|
1781
|
+
id: release.id,
|
|
1782
|
+
deployedAt: timestamp(),
|
|
1783
|
+
operation: record.operation,
|
|
1784
|
+
controllerIds: receipt.controllerIds,
|
|
1785
|
+
server: serverFailure === undefined ? serverPath ?? previous?.server : previous?.server
|
|
1786
|
+
};
|
|
1787
|
+
await state.setRelease(deployed);
|
|
1788
|
+
item.deployed = deployed;
|
|
1789
|
+
const line = {
|
|
1790
|
+
at: deployed.deployedAt,
|
|
1791
|
+
release: release.id,
|
|
1792
|
+
...record.build !== null && { build: record.build },
|
|
1793
|
+
operation: record.operation,
|
|
1794
|
+
credentials: item.credentials ? "provided" : "stored",
|
|
1795
|
+
...record.requestedBy.user !== null && {
|
|
1796
|
+
user: record.requestedBy.user
|
|
1797
|
+
},
|
|
1798
|
+
...record.requestedBy.host !== null && {
|
|
1799
|
+
host: record.requestedBy.host
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
await appendJsonl(state.paths.deployments, line);
|
|
1803
|
+
await activate(item);
|
|
1804
|
+
context.onActivated();
|
|
1805
|
+
if (serverFailure !== undefined) {
|
|
1806
|
+
throw new Error(`The controller runs release ${release.id}. ${serverFailure}`);
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
const verify = async (item, receipt) => {
|
|
1810
|
+
await enter(item, "verifying");
|
|
1811
|
+
await startPhase(item, "health");
|
|
1812
|
+
const health = await checkHealth({
|
|
1813
|
+
controllerState: receipt.state,
|
|
1814
|
+
hasServer: item.release.manifest.server !== undefined,
|
|
1815
|
+
healthUrl: context.serverHealthUrl,
|
|
1816
|
+
server: context.server
|
|
1817
|
+
});
|
|
1818
|
+
await update(item, (record) => ({ ...record, health }));
|
|
1819
|
+
if (!healthy(health)) {
|
|
1820
|
+
throw new Error(health.detail ?? "The deployment isn't healthy");
|
|
1821
|
+
}
|
|
1822
|
+
await finishPhase(item, "ok");
|
|
1823
|
+
say(item, "info", health.detail ? `Ready. ${health.detail}` : "Ready");
|
|
1824
|
+
await enter(item, "ready");
|
|
1825
|
+
};
|
|
1826
|
+
const fail = async (item, error) => {
|
|
1827
|
+
if (error instanceof Canceled) {
|
|
1828
|
+
await finishPhase(item, "skipped");
|
|
1829
|
+
await enter(item, "canceled", { approval: null });
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
item.failure = { error };
|
|
1833
|
+
context.log(`Deployment ${item.id} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1834
|
+
await finishPhase(item, "failed");
|
|
1835
|
+
say(item, "error", errorMessage(error));
|
|
1836
|
+
const rollback = transferRollback(error);
|
|
1837
|
+
await enter(item, "error", {
|
|
1838
|
+
approval: null,
|
|
1839
|
+
error: {
|
|
1840
|
+
message: errorMessage(error),
|
|
1841
|
+
downloadRequired: requiresDownload(error),
|
|
1842
|
+
...rollback && { rollback }
|
|
1843
|
+
}
|
|
1844
|
+
});
|
|
1845
|
+
};
|
|
1846
|
+
const prune = () => withReleases(async () => {
|
|
1847
|
+
const pruned = await pruneDeployments({
|
|
1848
|
+
store,
|
|
1849
|
+
releases: state.paths.releases,
|
|
1850
|
+
deployed: await state.release(),
|
|
1851
|
+
now: context.now
|
|
1852
|
+
});
|
|
1853
|
+
if (pruned.deployments.length || pruned.releases.length) {
|
|
1854
|
+
context.log(`Removed ${pruned.deployments.length} deployments and ${pruned.releases.length} releases older than the retention`);
|
|
1855
|
+
}
|
|
1856
|
+
}).catch((error) => context.log(`Pruning deployments failed: ${errorMessage(error)}`));
|
|
1857
|
+
const waitsForPerson = (item) => recordOf(item.id).state === "awaitingApproval" && !item.approved;
|
|
1858
|
+
const settle = (item) => {
|
|
1859
|
+
if (recordOf(item.id).state === "awaitingApproval") {
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
pending.delete(item.id);
|
|
1863
|
+
const index = queue.indexOf(item);
|
|
1864
|
+
if (index >= 0) {
|
|
1865
|
+
queue.splice(index, 1);
|
|
1866
|
+
}
|
|
1867
|
+
prune();
|
|
1868
|
+
};
|
|
1869
|
+
const advance = async (item, lock) => {
|
|
1870
|
+
item.running = true;
|
|
1871
|
+
try {
|
|
1872
|
+
await lock(async () => {
|
|
1873
|
+
requireNotCanceled(item);
|
|
1874
|
+
const config = recordOf(item.id).state === "queued" ? await build(item) : (await prepare(item)).config;
|
|
1875
|
+
if (!config) {
|
|
1876
|
+
return;
|
|
1877
|
+
}
|
|
1878
|
+
const receipt = await apply(item, config);
|
|
1879
|
+
if (!receipt) {
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
await start(item, receipt);
|
|
1883
|
+
await verify(item, receipt);
|
|
1884
|
+
});
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
await fail(item, error).catch((failure) => context.log(`Recording deployment ${item.id}'s failure failed: ${errorMessage(failure)}`));
|
|
1887
|
+
} finally {
|
|
1888
|
+
item.running = false;
|
|
1889
|
+
}
|
|
1890
|
+
settle(item);
|
|
1891
|
+
};
|
|
1892
|
+
const advanceQueue = async () => {
|
|
1893
|
+
const [head] = queue;
|
|
1894
|
+
if (!head || waitsForPerson(head)) {
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
await advance(head, (run) => whenFree(head, run));
|
|
1898
|
+
return advanceQueue();
|
|
1899
|
+
};
|
|
1900
|
+
const drain = async () => {
|
|
1901
|
+
if (draining) {
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
draining = true;
|
|
1905
|
+
try {
|
|
1906
|
+
await advanceQueue();
|
|
1907
|
+
} finally {
|
|
1908
|
+
draining = false;
|
|
1909
|
+
}
|
|
1910
|
+
};
|
|
1911
|
+
const create = async (release, origin, submission, waitsForApproval) => {
|
|
1912
|
+
const at = timestamp();
|
|
1913
|
+
const record = {
|
|
1914
|
+
id: store.newId(),
|
|
1915
|
+
release: release.id,
|
|
1916
|
+
build: await releaseBuild(release),
|
|
1917
|
+
createdAt: at,
|
|
1918
|
+
updatedAt: at,
|
|
1919
|
+
origin,
|
|
1920
|
+
git: submission.git,
|
|
1921
|
+
requestedBy: submission.requestedBy,
|
|
1922
|
+
mode: submission.mode,
|
|
1923
|
+
operation: submission.download ? "download" : "online-change",
|
|
1924
|
+
state: "queued",
|
|
1925
|
+
phases: [
|
|
1926
|
+
{ name: "queue", startedAt: at, finishedAt: null, outcome: "running" }
|
|
1927
|
+
],
|
|
1928
|
+
findings: [],
|
|
1929
|
+
approval: null,
|
|
1930
|
+
error: null,
|
|
1931
|
+
controllerIds: null,
|
|
1932
|
+
health: null,
|
|
1933
|
+
activeFrom: null,
|
|
1934
|
+
activeUntil: null
|
|
1935
|
+
};
|
|
1936
|
+
await store.create(record);
|
|
1937
|
+
const item = {
|
|
1938
|
+
id: record.id,
|
|
1939
|
+
release,
|
|
1940
|
+
credentials: submission.credentials,
|
|
1941
|
+
initializeUser: submission.initializeUser,
|
|
1942
|
+
waitsForApproval,
|
|
1943
|
+
canceled: false,
|
|
1944
|
+
approved: false,
|
|
1945
|
+
running: false,
|
|
1946
|
+
deployed: null,
|
|
1947
|
+
failure: null
|
|
1948
|
+
};
|
|
1949
|
+
pending.set(item.id, item);
|
|
1950
|
+
return item;
|
|
1951
|
+
};
|
|
1952
|
+
const announce = (item, warnings) => {
|
|
1953
|
+
for (const warning of warnings) {
|
|
1954
|
+
say(item, "warning", warning);
|
|
1955
|
+
}
|
|
1956
|
+
};
|
|
1957
|
+
const enqueue = (item, warnings) => {
|
|
1958
|
+
announce(item, warnings);
|
|
1959
|
+
queue.push(item);
|
|
1960
|
+
drain();
|
|
1961
|
+
return recordOf(item.id);
|
|
1962
|
+
};
|
|
1963
|
+
const checkSubmission = async (credentials) => {
|
|
1964
|
+
await state.requireTarget();
|
|
1965
|
+
await controllerCredentials(credentials);
|
|
1966
|
+
};
|
|
1967
|
+
const again = async (id, origin, mode, requestedBy) => {
|
|
1968
|
+
const source = recordOf(id);
|
|
1969
|
+
await checkSubmission(null);
|
|
1970
|
+
return withReleases(async () => {
|
|
1971
|
+
const release = await loadRelease(state.paths.releases, source.release).catch(() => {
|
|
1972
|
+
throw new AgentError(`The release of ${id}, ${source.release}, is no longer stored`, 409);
|
|
1973
|
+
});
|
|
1974
|
+
const item = await create(release, origin, {
|
|
1975
|
+
git: source.git,
|
|
1976
|
+
requestedBy,
|
|
1977
|
+
mode,
|
|
1978
|
+
download: false,
|
|
1979
|
+
credentials: null,
|
|
1980
|
+
initializeUser: false,
|
|
1981
|
+
warnings: []
|
|
1982
|
+
}, true);
|
|
1983
|
+
return enqueue(item, []);
|
|
643
1984
|
});
|
|
644
|
-
return { debug, handle: createDebugHandler(debug, log) };
|
|
645
1985
|
};
|
|
646
|
-
const startOrLog = () => start().catch((error) => {
|
|
647
|
-
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
648
|
-
return null;
|
|
649
|
-
});
|
|
650
|
-
let current = startOrLog();
|
|
651
1986
|
return {
|
|
652
|
-
|
|
653
|
-
const
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
1987
|
+
start: async () => {
|
|
1988
|
+
for (const record of store.list().filter((entry) => !isFinished(entry))) {
|
|
1989
|
+
await store.update(record.id, (unfinished) => ({
|
|
1990
|
+
...unfinished,
|
|
1991
|
+
state: "error",
|
|
1992
|
+
approval: null,
|
|
1993
|
+
phases: unfinished.phases.map((phase) => phase.outcome === "running" ? { ...phase, finishedAt: timestamp(), outcome: "failed" } : phase),
|
|
1994
|
+
error: {
|
|
1995
|
+
message: "The plant agent stopped before this deployment finished",
|
|
1996
|
+
downloadRequired: false
|
|
1997
|
+
}
|
|
1998
|
+
}));
|
|
658
1999
|
}
|
|
659
|
-
|
|
2000
|
+
await prune();
|
|
660
2001
|
},
|
|
661
|
-
|
|
662
|
-
|
|
2002
|
+
submit: async (upload, submission) => {
|
|
2003
|
+
await checkSubmission(submission.credentials);
|
|
2004
|
+
return withReleases(async () => {
|
|
2005
|
+
const release = await saveRelease(state.paths.releases, upload);
|
|
2006
|
+
const item = await create(release, { kind: "upload" }, submission, true);
|
|
2007
|
+
return enqueue(item, submission.warnings);
|
|
2008
|
+
});
|
|
663
2009
|
},
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
2010
|
+
redeploy: (id, mode, requestedBy) => again(id, { kind: "redeploy", from: id }, mode, requestedBy),
|
|
2011
|
+
rollback: (id, requestedBy) => again(id, { kind: "rollback", from: id }, "apply", requestedBy),
|
|
2012
|
+
approve: async (id, download, by) => {
|
|
2013
|
+
const record = recordOf(id);
|
|
2014
|
+
const item = pending.get(id);
|
|
2015
|
+
if (!item || record.state !== "awaitingApproval" || item.approved) {
|
|
2016
|
+
throw new AgentError(`Deployment ${id} isn't awaiting approval`, 409);
|
|
2017
|
+
}
|
|
2018
|
+
if (record.approval?.reason === "downloadRequired" && !download) {
|
|
2019
|
+
throw new AgentError(`Only a full download can apply deployment ${id}; approve it with a download`, 409);
|
|
2020
|
+
}
|
|
2021
|
+
item.approved = true;
|
|
2022
|
+
say(item, "info", `${by} approved it${download ? " as a full download" : ""}`);
|
|
2023
|
+
const approved = await update(item, (current) => ({
|
|
2024
|
+
...current,
|
|
2025
|
+
operation: download ? "download" : current.operation
|
|
2026
|
+
}));
|
|
2027
|
+
drain();
|
|
2028
|
+
return approved;
|
|
2029
|
+
},
|
|
2030
|
+
cancel: async (id, by) => {
|
|
2031
|
+
const record = recordOf(id);
|
|
2032
|
+
const item = pending.get(id);
|
|
2033
|
+
if (!item || !cancelable.includes(record.state)) {
|
|
2034
|
+
throw new AgentError(`Deployment ${id} is ${record.state}; a deployment can only be canceled before it applies`, 409);
|
|
2035
|
+
}
|
|
2036
|
+
item.canceled = true;
|
|
2037
|
+
say(item, "info", `${by} canceled it`);
|
|
2038
|
+
if (item.running) {
|
|
2039
|
+
return record;
|
|
2040
|
+
}
|
|
2041
|
+
const index = queue.indexOf(item);
|
|
2042
|
+
if (index >= 0) {
|
|
2043
|
+
queue.splice(index, 1);
|
|
2044
|
+
}
|
|
2045
|
+
await fail(item, new Canceled);
|
|
2046
|
+
settle(item);
|
|
2047
|
+
drain();
|
|
2048
|
+
return recordOf(id);
|
|
2049
|
+
},
|
|
2050
|
+
requireIdle: () => {
|
|
2051
|
+
const [head] = queue;
|
|
2052
|
+
if (!head) {
|
|
2053
|
+
return;
|
|
2054
|
+
}
|
|
2055
|
+
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);
|
|
2056
|
+
},
|
|
2057
|
+
runNow: async (upload, submission, onLine) => {
|
|
2058
|
+
const item = await withReleases(async () => create(await saveRelease(state.paths.releases, upload), { kind: "upload" }, submission, false));
|
|
2059
|
+
const unsubscribe = store.subscribe(item.id, (event) => {
|
|
2060
|
+
if (event.kind === "log") {
|
|
2061
|
+
onLine(event.line);
|
|
2062
|
+
}
|
|
668
2063
|
});
|
|
2064
|
+
try {
|
|
2065
|
+
announce(item, submission.warnings);
|
|
2066
|
+
await advance(item, (run) => run());
|
|
2067
|
+
await store.flush(item.id);
|
|
2068
|
+
} finally {
|
|
2069
|
+
unsubscribe();
|
|
2070
|
+
}
|
|
2071
|
+
if (item.failure) {
|
|
2072
|
+
throw item.failure.error;
|
|
2073
|
+
}
|
|
2074
|
+
if (!item.deployed) {
|
|
2075
|
+
throw new AgentError(`Deployment ${item.id} was canceled`, 409);
|
|
2076
|
+
}
|
|
2077
|
+
return item.deployed;
|
|
669
2078
|
},
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
2079
|
+
list: () => {
|
|
2080
|
+
const deployments = store.list();
|
|
2081
|
+
return { deployments, ...activeDeployments(deployments) };
|
|
2082
|
+
},
|
|
2083
|
+
get: recordOf,
|
|
2084
|
+
lines: (id, after) => {
|
|
2085
|
+
recordOf(id);
|
|
2086
|
+
return store.lines(id, after);
|
|
2087
|
+
},
|
|
2088
|
+
subscribe: (id, listener) => store.subscribe(id, listener),
|
|
2089
|
+
source: (id) => listReleaseFiles(state.paths.releases, recordOf(id).release),
|
|
2090
|
+
sourceFile: (id, path) => readReleaseFile(state.paths.releases, recordOf(id).release, path)
|
|
673
2091
|
};
|
|
674
2092
|
};
|
|
675
2093
|
|
|
676
2094
|
// packages/agent/src/deploy.ts
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
2095
|
+
var clientWarnings = async (clientTsplc) => {
|
|
2096
|
+
if (clientTsplc.version === undefined) {
|
|
2097
|
+
return [
|
|
2098
|
+
`the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`
|
|
2099
|
+
];
|
|
2100
|
+
}
|
|
2101
|
+
if (clientTsplc.version !== tsplcVersion) {
|
|
2102
|
+
throw new AgentError(versionMismatch({
|
|
2103
|
+
agent: tsplcVersion,
|
|
2104
|
+
client: clientTsplc.version,
|
|
2105
|
+
agentUpgrades: true
|
|
2106
|
+
}), 409);
|
|
2107
|
+
}
|
|
2108
|
+
if (clientTsplc.scripts !== undefined && clientTsplc.scripts !== await workerScriptsDigest()) {
|
|
2109
|
+
return [
|
|
2110
|
+
`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`
|
|
2111
|
+
];
|
|
2112
|
+
}
|
|
2113
|
+
return [];
|
|
2114
|
+
};
|
|
2115
|
+
var requester = (identity, client) => ({
|
|
2116
|
+
identity: { login: identity.login, name: identity.name, via: identity.via },
|
|
2117
|
+
user: client.user ?? null,
|
|
2118
|
+
host: client.host ?? null
|
|
2119
|
+
});
|
|
2120
|
+
var createDeployments = async (context) => {
|
|
2121
|
+
const { state } = context;
|
|
691
2122
|
const warming = (async () => {
|
|
692
2123
|
const deployed = await state.release();
|
|
693
2124
|
const target = await state.target();
|
|
@@ -701,7 +2132,68 @@ var createDeployments = (context) => {
|
|
|
701
2132
|
})().catch((error) => {
|
|
702
2133
|
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
703
2134
|
});
|
|
2135
|
+
const controller = {
|
|
2136
|
+
ready: async () => {
|
|
2137
|
+
const builder = await requireBuilder();
|
|
2138
|
+
if (await findControllerLogin(loginContainer)) {
|
|
2139
|
+
throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
|
|
2140
|
+
}
|
|
2141
|
+
return builder.kind === "unverified" ? [
|
|
2142
|
+
`${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`
|
|
2143
|
+
] : [];
|
|
2144
|
+
},
|
|
2145
|
+
settle: (config) => settleWarmController(config, deployContainer),
|
|
2146
|
+
baseline: () => controllerBaseline(state.paths.controller),
|
|
2147
|
+
review: async (config, options) => {
|
|
2148
|
+
await ensureGateway();
|
|
2149
|
+
await warming;
|
|
2150
|
+
return reviewWarmController(config, deployContainer, options);
|
|
2151
|
+
},
|
|
2152
|
+
apply: async (config, operation, options) => {
|
|
2153
|
+
await ensureGateway();
|
|
2154
|
+
await warming;
|
|
2155
|
+
return updateWarmController(config, deployContainer, operation, options);
|
|
2156
|
+
}
|
|
2157
|
+
};
|
|
2158
|
+
const runner = createDeploymentRunner({
|
|
2159
|
+
store: await openDeploymentStore({
|
|
2160
|
+
directory: state.paths.deploymentRecords,
|
|
2161
|
+
now: context.now,
|
|
2162
|
+
log: context.log
|
|
2163
|
+
}),
|
|
2164
|
+
state,
|
|
2165
|
+
operations: context.operations,
|
|
2166
|
+
codesys: context.codesys,
|
|
2167
|
+
server: context.server,
|
|
2168
|
+
controller,
|
|
2169
|
+
serverHealthUrl: context.serverHealthUrl,
|
|
2170
|
+
onActivated: () => context.debugging.restart(),
|
|
2171
|
+
now: context.now,
|
|
2172
|
+
log: context.log
|
|
2173
|
+
});
|
|
2174
|
+
await runner.start();
|
|
2175
|
+
const deployedConfig = async () => {
|
|
2176
|
+
const deployed = await state.release();
|
|
2177
|
+
const target = await state.target();
|
|
2178
|
+
if (!deployed || !target) {
|
|
2179
|
+
throw new AgentError("Nothing is deployed to the controller yet", 409);
|
|
2180
|
+
}
|
|
2181
|
+
return controllerConfig(await loadRelease(state.paths.releases, deployed.id), target, state.paths.controller, context.codesys);
|
|
2182
|
+
};
|
|
704
2183
|
return {
|
|
2184
|
+
runner,
|
|
2185
|
+
restart: (reset) => context.operations.exclusive("a controller restart", async () => {
|
|
2186
|
+
if (await findControllerLogin(loginContainer)) {
|
|
2187
|
+
throw new AgentError("A login opened meanwhile; restart again to use it", 409);
|
|
2188
|
+
}
|
|
2189
|
+
const config = await deployedConfig();
|
|
2190
|
+
await requireBuilder();
|
|
2191
|
+
await ensureGateway();
|
|
2192
|
+
await warming;
|
|
2193
|
+
return restartWarmController(config, deployContainer, reset, {
|
|
2194
|
+
credentials: await controllerCredentials(null)
|
|
2195
|
+
});
|
|
2196
|
+
}),
|
|
705
2197
|
retire: async () => {
|
|
706
2198
|
await warming;
|
|
707
2199
|
const deployed = await state.release();
|
|
@@ -711,94 +2203,228 @@ var createDeployments = (context) => {
|
|
|
711
2203
|
}
|
|
712
2204
|
await removeContainer(deployContainer);
|
|
713
2205
|
},
|
|
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
|
-
}
|
|
2206
|
+
deploy: async (readRequest, identity, client, clientTsplc) => {
|
|
2207
|
+
const warnings = await clientWarnings(clientTsplc);
|
|
722
2208
|
context.operations.requireIdle();
|
|
723
|
-
|
|
2209
|
+
runner.requireIdle();
|
|
2210
|
+
await requireBuilder();
|
|
724
2211
|
const { settings, upload } = await readRequest();
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
2212
|
+
await state.requireTarget();
|
|
2213
|
+
await controllerCredentials(settings.credentials);
|
|
2214
|
+
await readSecrets(upload.manifest.secrets);
|
|
2215
|
+
return context.operations.stream("a deployment", (emit) => runner.runNow(upload, {
|
|
2216
|
+
git: settings.deployment?.git ?? null,
|
|
2217
|
+
requestedBy: requester(identity, client),
|
|
2218
|
+
mode: "apply",
|
|
2219
|
+
download: settings.download,
|
|
2220
|
+
credentials: settings.credentials,
|
|
2221
|
+
initializeUser: settings.initializeUser,
|
|
2222
|
+
warnings
|
|
2223
|
+
}, (line) => {
|
|
2224
|
+
if (line.level === "error") {
|
|
2225
|
+
return;
|
|
738
2226
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
2227
|
+
emit({
|
|
2228
|
+
kind: "progress",
|
|
2229
|
+
message: line.level === "warning" ? `Warning: ${line.message}` : line.message
|
|
2230
|
+
});
|
|
2231
|
+
}), { reportsRollback: clientTsplc.version !== undefined });
|
|
2232
|
+
}
|
|
2233
|
+
};
|
|
2234
|
+
};
|
|
2235
|
+
|
|
2236
|
+
// packages/agent/src/deployments/routes.ts
|
|
2237
|
+
import { z as z6 } from "zod";
|
|
2238
|
+
var heartbeatMs = 15000;
|
|
2239
|
+
var afterSchema = z6.coerce.number().int().nonnegative();
|
|
2240
|
+
var after = (request) => afterSchema.parse(new URL(request.url).searchParams.get("after") ?? request.headers.get("last-event-id") ?? 0);
|
|
2241
|
+
var eventStream = (runner, id, from) => {
|
|
2242
|
+
runner.get(id);
|
|
2243
|
+
const encoder = new TextEncoder;
|
|
2244
|
+
const stream = {
|
|
2245
|
+
open: true,
|
|
2246
|
+
sent: from,
|
|
2247
|
+
held: [],
|
|
2248
|
+
stop: () => {}
|
|
2249
|
+
};
|
|
2250
|
+
return new Response(new ReadableStream({
|
|
2251
|
+
start: async (controller) => {
|
|
2252
|
+
const write = (text) => {
|
|
2253
|
+
if (stream.open) {
|
|
2254
|
+
controller.enqueue(encoder.encode(text));
|
|
749
2255
|
}
|
|
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 });
|
|
2256
|
+
};
|
|
2257
|
+
const sendLine = (line) => {
|
|
2258
|
+
if (line.seq <= stream.sent) {
|
|
2259
|
+
return;
|
|
756
2260
|
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
if (serverPath) {
|
|
769
|
-
emit({ kind: "progress", message: "Starting the new server" });
|
|
2261
|
+
stream.sent = line.seq;
|
|
2262
|
+
write(`id: ${line.seq}
|
|
2263
|
+
event: log
|
|
2264
|
+
data: ${JSON.stringify(line)}
|
|
2265
|
+
|
|
2266
|
+
`);
|
|
2267
|
+
};
|
|
2268
|
+
const end = () => {
|
|
2269
|
+
if (stream.open) {
|
|
2270
|
+
stream.stop();
|
|
2271
|
+
controller.close();
|
|
770
2272
|
}
|
|
771
|
-
|
|
2273
|
+
};
|
|
2274
|
+
const sendRecord = (record) => write(`event: record
|
|
2275
|
+
data: ${JSON.stringify(record)}
|
|
2276
|
+
|
|
2277
|
+
`);
|
|
2278
|
+
const finish = () => runner.lines(id, stream.sent).then((lines) => {
|
|
2279
|
+
lines.forEach(sendLine);
|
|
2280
|
+
sendRecord(runner.get(id));
|
|
2281
|
+
end();
|
|
2282
|
+
}, end);
|
|
2283
|
+
const deliver = (event) => {
|
|
2284
|
+
if (event.kind === "log") {
|
|
2285
|
+
sendLine(event.line);
|
|
2286
|
+
return;
|
|
2287
|
+
}
|
|
2288
|
+
if (isFinished(event.record)) {
|
|
2289
|
+
finish();
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
sendRecord(event.record);
|
|
2293
|
+
};
|
|
2294
|
+
const unsubscribe = runner.subscribe(id, (event) => {
|
|
2295
|
+
if (stream.held) {
|
|
2296
|
+
stream.held.push(event);
|
|
772
2297
|
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
2298
|
}
|
|
798
|
-
|
|
799
|
-
}
|
|
2299
|
+
deliver(event);
|
|
2300
|
+
});
|
|
2301
|
+
const heartbeat = setInterval(() => write(`: heartbeat
|
|
2302
|
+
|
|
2303
|
+
`), heartbeatMs);
|
|
2304
|
+
stream.stop = () => {
|
|
2305
|
+
stream.open = false;
|
|
2306
|
+
clearInterval(heartbeat);
|
|
2307
|
+
unsubscribe();
|
|
2308
|
+
};
|
|
2309
|
+
if (!isFinished(runner.get(id))) {
|
|
2310
|
+
sendRecord(runner.get(id));
|
|
2311
|
+
}
|
|
2312
|
+
(await runner.lines(id, from)).forEach(sendLine);
|
|
2313
|
+
const held = stream.held ?? [];
|
|
2314
|
+
stream.held = null;
|
|
2315
|
+
held.forEach(deliver);
|
|
2316
|
+
if (isFinished(runner.get(id))) {
|
|
2317
|
+
finish();
|
|
2318
|
+
}
|
|
2319
|
+
},
|
|
2320
|
+
cancel: () => stream.stop()
|
|
2321
|
+
}), {
|
|
2322
|
+
headers: {
|
|
2323
|
+
"Content-Type": "text/event-stream",
|
|
2324
|
+
"Cache-Control": "no-cache"
|
|
800
2325
|
}
|
|
801
|
-
};
|
|
2326
|
+
});
|
|
2327
|
+
};
|
|
2328
|
+
var createDeploymentRoutes = (context) => {
|
|
2329
|
+
const { runner } = context;
|
|
2330
|
+
const created = (request, record) => Response.json({
|
|
2331
|
+
id: record.id,
|
|
2332
|
+
url: `${new URL(request.url).origin}/deployments/${record.id}`
|
|
2333
|
+
}, { status: 202 });
|
|
2334
|
+
const id = (params) => params.id ?? "";
|
|
2335
|
+
return [
|
|
2336
|
+
{
|
|
2337
|
+
method: "POST",
|
|
2338
|
+
pattern: "/api/deployments",
|
|
2339
|
+
role: "deployer",
|
|
2340
|
+
handle: async (request, { identity }) => {
|
|
2341
|
+
const warnings = await clientWarnings(clientRelease(request));
|
|
2342
|
+
const { settings, upload } = await readDeployRequest(context.releases, request);
|
|
2343
|
+
const record = await runner.submit(upload, {
|
|
2344
|
+
git: settings.deployment?.git ?? null,
|
|
2345
|
+
requestedBy: requester(identity, clientIdentity(request)),
|
|
2346
|
+
mode: settings.deployment?.mode ?? "apply",
|
|
2347
|
+
download: settings.download,
|
|
2348
|
+
credentials: settings.credentials,
|
|
2349
|
+
initializeUser: settings.initializeUser,
|
|
2350
|
+
warnings
|
|
2351
|
+
});
|
|
2352
|
+
return created(request, record);
|
|
2353
|
+
}
|
|
2354
|
+
},
|
|
2355
|
+
{
|
|
2356
|
+
method: "GET",
|
|
2357
|
+
pattern: "/api/deployments",
|
|
2358
|
+
role: "viewer",
|
|
2359
|
+
handle: async () => Response.json(runner.list())
|
|
2360
|
+
},
|
|
2361
|
+
{
|
|
2362
|
+
method: "GET",
|
|
2363
|
+
pattern: "/api/deployments/:id",
|
|
2364
|
+
role: "viewer",
|
|
2365
|
+
handle: async (_request, { params }) => Response.json(runner.get(id(params)))
|
|
2366
|
+
},
|
|
2367
|
+
{
|
|
2368
|
+
method: "GET",
|
|
2369
|
+
pattern: "/api/deployments/:id/logs",
|
|
2370
|
+
role: "viewer",
|
|
2371
|
+
handle: async (request, { params }) => Response.json({
|
|
2372
|
+
lines: await runner.lines(id(params), after(request))
|
|
2373
|
+
})
|
|
2374
|
+
},
|
|
2375
|
+
{
|
|
2376
|
+
method: "GET",
|
|
2377
|
+
pattern: "/api/deployments/:id/events",
|
|
2378
|
+
role: "viewer",
|
|
2379
|
+
handle: async (request, { params }) => eventStream(runner, id(params), after(request))
|
|
2380
|
+
},
|
|
2381
|
+
{
|
|
2382
|
+
method: "POST",
|
|
2383
|
+
pattern: "/api/deployments/:id/approve",
|
|
2384
|
+
role: "deployer",
|
|
2385
|
+
handle: async (request, { identity, params }) => {
|
|
2386
|
+
const { download } = approveSchema.parse(await request.json());
|
|
2387
|
+
return Response.json(await runner.approve(id(params), download, identity.name));
|
|
2388
|
+
}
|
|
2389
|
+
},
|
|
2390
|
+
{
|
|
2391
|
+
method: "POST",
|
|
2392
|
+
pattern: "/api/deployments/:id/cancel",
|
|
2393
|
+
role: "deployer",
|
|
2394
|
+
handle: async (_request, { identity, params }) => Response.json(await runner.cancel(id(params), identity.name))
|
|
2395
|
+
},
|
|
2396
|
+
{
|
|
2397
|
+
method: "POST",
|
|
2398
|
+
pattern: "/api/deployments/:id/redeploy",
|
|
2399
|
+
role: "deployer",
|
|
2400
|
+
handle: async (request, { identity, params }) => {
|
|
2401
|
+
const { mode } = redeploySchema.parse(await request.json());
|
|
2402
|
+
return created(request, await runner.redeploy(id(params), mode, requester(identity, clientIdentity(request))));
|
|
2403
|
+
}
|
|
2404
|
+
},
|
|
2405
|
+
{
|
|
2406
|
+
method: "POST",
|
|
2407
|
+
pattern: "/api/deployments/:id/rollback",
|
|
2408
|
+
role: "deployer",
|
|
2409
|
+
handle: async (request, { identity, params }) => created(request, await runner.rollback(id(params), requester(identity, clientIdentity(request))))
|
|
2410
|
+
},
|
|
2411
|
+
{
|
|
2412
|
+
method: "GET",
|
|
2413
|
+
pattern: "/api/deployments/:id/source",
|
|
2414
|
+
role: "viewer",
|
|
2415
|
+
handle: async (_request, { params }) => Response.json({
|
|
2416
|
+
files: await runner.source(id(params))
|
|
2417
|
+
})
|
|
2418
|
+
},
|
|
2419
|
+
{
|
|
2420
|
+
method: "GET",
|
|
2421
|
+
pattern: "/api/deployments/:id/source/*",
|
|
2422
|
+
role: "viewer",
|
|
2423
|
+
handle: async (_request, { params }) => new Response(await runner.sourceFile(id(params), params["*"] ?? ""), {
|
|
2424
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
2425
|
+
})
|
|
2426
|
+
}
|
|
2427
|
+
];
|
|
802
2428
|
};
|
|
803
2429
|
|
|
804
2430
|
// packages/agent/src/discovery.ts
|
|
@@ -853,8 +2479,184 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
853
2479
|
return found;
|
|
854
2480
|
};
|
|
855
2481
|
|
|
2482
|
+
// packages/agent/src/environment.ts
|
|
2483
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
2484
|
+
import { readFile as readFile6, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
|
|
2485
|
+
import { join as join8 } from "node:path";
|
|
2486
|
+
import { z as z7 } from "zod";
|
|
2487
|
+
var environmentFile = (state) => join8(state, "environment.json");
|
|
2488
|
+
var variablesFile = (state) => join8(state, "variables.json");
|
|
2489
|
+
var storedNamesSchema = z7.record(z7.string(), z7.array(variableName));
|
|
2490
|
+
var storedVariablesSchema = z7.record(variableName, z7.string());
|
|
2491
|
+
var readJson = async (file, schema, empty) => existsSync7(file) ? schema.parse(JSON.parse(await readFile6(file, "utf8"))) : empty;
|
|
2492
|
+
var writeJson = async (file, value) => {
|
|
2493
|
+
await writeFile5(`${file}.tmp`, JSON.stringify(value, null, 2));
|
|
2494
|
+
await rename5(`${file}.tmp`, file);
|
|
2495
|
+
};
|
|
2496
|
+
var createEnvironment = (context) => {
|
|
2497
|
+
const { state, audit } = context;
|
|
2498
|
+
const storedNames = () => readJson(context.file, storedNamesSchema, {});
|
|
2499
|
+
const writeStoredNames = async (service, update) => {
|
|
2500
|
+
const stored = await storedNames();
|
|
2501
|
+
await writeJson(context.file, {
|
|
2502
|
+
...stored,
|
|
2503
|
+
[service]: update(stored[service] ?? [])
|
|
2504
|
+
});
|
|
2505
|
+
};
|
|
2506
|
+
const storedVariables = () => readJson(context.variables, storedVariablesSchema, {});
|
|
2507
|
+
const deployedManifest = async () => {
|
|
2508
|
+
const release = await state.release();
|
|
2509
|
+
return release ? (await loadRelease(state.paths.releases, release.id)).manifest : undefined;
|
|
2510
|
+
};
|
|
2511
|
+
const declared = async () => {
|
|
2512
|
+
const secrets = (await deployedManifest())?.secrets;
|
|
2513
|
+
return secrets ? { service: secrets.service, names: secrets.names } : { service: environmentService, names: [] };
|
|
2514
|
+
};
|
|
2515
|
+
const isSet = async (service, name) => await Bun.secrets.get({ service, name }) !== null;
|
|
2516
|
+
const entries = async () => {
|
|
2517
|
+
const { service, names } = await declared();
|
|
2518
|
+
const stored = ((await storedNames())[service] ?? []).filter((name) => !names.includes(name));
|
|
2519
|
+
const undeclared = await Promise.all(stored.map(async (name) => ({
|
|
2520
|
+
name,
|
|
2521
|
+
declared: false,
|
|
2522
|
+
set: await isSet(service, name)
|
|
2523
|
+
})));
|
|
2524
|
+
return [
|
|
2525
|
+
...await Promise.all(names.map(async (name) => ({
|
|
2526
|
+
name,
|
|
2527
|
+
declared: true,
|
|
2528
|
+
set: await isSet(service, name)
|
|
2529
|
+
}))),
|
|
2530
|
+
...undeclared.filter(({ set }) => set)
|
|
2531
|
+
];
|
|
2532
|
+
};
|
|
2533
|
+
const listing = async () => ({
|
|
2534
|
+
values: (await deployedManifest())?.values ?? {},
|
|
2535
|
+
variables: await storedVariables(),
|
|
2536
|
+
secrets: await entries()
|
|
2537
|
+
});
|
|
2538
|
+
const forRelease = async (service) => {
|
|
2539
|
+
const held = (await storedNames())[service] ?? [];
|
|
2540
|
+
const set = await Promise.all(held.map(async (name) => await isSet(service, name) ? [name] : []));
|
|
2541
|
+
return { service, values: await storedVariables(), secrets: set.flat() };
|
|
2542
|
+
};
|
|
2543
|
+
const record = (identity, command, change) => audit.record({
|
|
2544
|
+
identity,
|
|
2545
|
+
command,
|
|
2546
|
+
values: change.values,
|
|
2547
|
+
previous: change.previous,
|
|
2548
|
+
error: null
|
|
2549
|
+
});
|
|
2550
|
+
const nameOnly = { values: {}, previous: null };
|
|
2551
|
+
const withoutVariable = async (name) => {
|
|
2552
|
+
const { [name]: removed, ...rest } = await storedVariables();
|
|
2553
|
+
if (removed !== undefined) {
|
|
2554
|
+
await writeJson(context.variables, rest);
|
|
2555
|
+
}
|
|
2556
|
+
return removed;
|
|
2557
|
+
};
|
|
2558
|
+
const routes = [
|
|
2559
|
+
{
|
|
2560
|
+
method: "GET",
|
|
2561
|
+
pattern: "/api/environment",
|
|
2562
|
+
role: "viewer",
|
|
2563
|
+
handle: async () => Response.json(await listing())
|
|
2564
|
+
},
|
|
2565
|
+
{
|
|
2566
|
+
method: "GET",
|
|
2567
|
+
pattern: "/api/environment/release",
|
|
2568
|
+
role: "deployer",
|
|
2569
|
+
handle: async (request) => Response.json(await forRelease(new URL(request.url).searchParams.get("service") || environmentService))
|
|
2570
|
+
},
|
|
2571
|
+
{
|
|
2572
|
+
method: "PUT",
|
|
2573
|
+
pattern: "/api/environment/:name",
|
|
2574
|
+
role: "admin",
|
|
2575
|
+
handle: async (request, { identity, params }) => {
|
|
2576
|
+
const name = variableName.parse(params.name);
|
|
2577
|
+
const change = environmentValueSchema.parse(await request.json());
|
|
2578
|
+
const { service } = await declared();
|
|
2579
|
+
if (change.secret) {
|
|
2580
|
+
await Bun.secrets.set({ service, name, value: change.value });
|
|
2581
|
+
await writeStoredNames(service, (stored) => [
|
|
2582
|
+
...stored.filter((other) => other !== name),
|
|
2583
|
+
name
|
|
2584
|
+
]);
|
|
2585
|
+
await withoutVariable(name);
|
|
2586
|
+
await record(identity, `environment set ${name}`, nameOnly);
|
|
2587
|
+
return Response.json(await listing());
|
|
2588
|
+
}
|
|
2589
|
+
const previous = (await storedVariables())[name];
|
|
2590
|
+
await writeJson(context.variables, {
|
|
2591
|
+
...await storedVariables(),
|
|
2592
|
+
[name]: change.value
|
|
2593
|
+
});
|
|
2594
|
+
if (await Bun.secrets.delete({ service, name })) {
|
|
2595
|
+
await writeStoredNames(service, (stored) => stored.filter((other) => other !== name));
|
|
2596
|
+
}
|
|
2597
|
+
await record(identity, `environment set ${name}`, {
|
|
2598
|
+
values: { [name]: change.value },
|
|
2599
|
+
previous: previous === undefined ? null : { [name]: previous }
|
|
2600
|
+
});
|
|
2601
|
+
return Response.json(await listing());
|
|
2602
|
+
}
|
|
2603
|
+
},
|
|
2604
|
+
{
|
|
2605
|
+
method: "DELETE",
|
|
2606
|
+
pattern: "/api/environment/:name",
|
|
2607
|
+
role: "admin",
|
|
2608
|
+
handle: async (_request, { identity, params }) => {
|
|
2609
|
+
const name = variableName.parse(params.name);
|
|
2610
|
+
const removed = await withoutVariable(name);
|
|
2611
|
+
if (removed !== undefined) {
|
|
2612
|
+
await record(identity, `environment delete ${name}`, {
|
|
2613
|
+
values: {},
|
|
2614
|
+
previous: { [name]: removed }
|
|
2615
|
+
});
|
|
2616
|
+
return Response.json(await listing());
|
|
2617
|
+
}
|
|
2618
|
+
const { service } = await declared();
|
|
2619
|
+
if (!await Bun.secrets.delete({ service, name })) {
|
|
2620
|
+
throw new AgentError(`${name} isn't set`, 404);
|
|
2621
|
+
}
|
|
2622
|
+
await writeStoredNames(service, (stored) => stored.filter((other) => other !== name));
|
|
2623
|
+
await record(identity, `environment delete ${name}`, nameOnly);
|
|
2624
|
+
return Response.json(await listing());
|
|
2625
|
+
}
|
|
2626
|
+
},
|
|
2627
|
+
{
|
|
2628
|
+
method: "POST",
|
|
2629
|
+
pattern: "/api/server/restart",
|
|
2630
|
+
role: "deployer",
|
|
2631
|
+
handle: async (_request, { identity }) => {
|
|
2632
|
+
const running = context.server.status();
|
|
2633
|
+
if (!running) {
|
|
2634
|
+
throw new AgentError("The deployed release runs no server", 409);
|
|
2635
|
+
}
|
|
2636
|
+
const failure = await context.operations.exclusive("a server restart", () => context.server.replace(running.executable)).then(() => null, (error) => error);
|
|
2637
|
+
if (failure instanceof AgentError) {
|
|
2638
|
+
throw failure;
|
|
2639
|
+
}
|
|
2640
|
+
await audit.record({
|
|
2641
|
+
identity,
|
|
2642
|
+
command: "server restart",
|
|
2643
|
+
values: {},
|
|
2644
|
+
previous: null,
|
|
2645
|
+
error: failure === null ? null : errorMessage(failure)
|
|
2646
|
+
});
|
|
2647
|
+
if (failure !== null) {
|
|
2648
|
+
context.log(`Restarting the server failed: ${errorMessage(failure)}`);
|
|
2649
|
+
throw new AgentError(errorMessage(failure), 500);
|
|
2650
|
+
}
|
|
2651
|
+
return Response.json(context.server.status());
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
];
|
|
2655
|
+
return { routes };
|
|
2656
|
+
};
|
|
2657
|
+
|
|
856
2658
|
// packages/agent/src/instance.ts
|
|
857
|
-
import { z as
|
|
2659
|
+
import { z as z8 } from "zod";
|
|
858
2660
|
|
|
859
2661
|
// packages/agent/src/processes.ts
|
|
860
2662
|
var isGone = (error) => error instanceof Error && ("code" in error) && error.code === "ESRCH";
|
|
@@ -877,21 +2679,21 @@ var signalProcess = (pid, name) => {
|
|
|
877
2679
|
};
|
|
878
2680
|
|
|
879
2681
|
// packages/agent/src/instance.ts
|
|
880
|
-
var instanceSchema =
|
|
881
|
-
pid:
|
|
882
|
-
version:
|
|
883
|
-
url:
|
|
884
|
-
serve:
|
|
885
|
-
supervised:
|
|
886
|
-
startedAt:
|
|
2682
|
+
var instanceSchema = z8.strictObject({
|
|
2683
|
+
pid: z8.int().positive(),
|
|
2684
|
+
version: z8.string(),
|
|
2685
|
+
url: z8.url(),
|
|
2686
|
+
serve: z8.array(z8.string()),
|
|
2687
|
+
supervised: z8.boolean(),
|
|
2688
|
+
startedAt: z8.iso.datetime()
|
|
887
2689
|
});
|
|
888
|
-
var exitSchema =
|
|
889
|
-
server:
|
|
890
|
-
restart:
|
|
2690
|
+
var exitSchema = z8.strictObject({
|
|
2691
|
+
server: z8.enum(["leave", "stop"]),
|
|
2692
|
+
restart: z8.boolean()
|
|
891
2693
|
});
|
|
892
2694
|
|
|
893
2695
|
// packages/agent/src/login.ts
|
|
894
|
-
import { setTimeout as
|
|
2696
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
895
2697
|
import {
|
|
896
2698
|
failureReason,
|
|
897
2699
|
findControllerLogin as findControllerLogin2,
|
|
@@ -1034,6 +2836,17 @@ var createLogin = (context) => {
|
|
|
1034
2836
|
}
|
|
1035
2837
|
});
|
|
1036
2838
|
},
|
|
2839
|
+
restart: async (reset) => {
|
|
2840
|
+
const login = await requireLogin();
|
|
2841
|
+
return enqueue(async () => {
|
|
2842
|
+
await login.send({ command: "reset", kind: reset });
|
|
2843
|
+
const started = await login.send({ command: "start" });
|
|
2844
|
+
if (!("state" in started)) {
|
|
2845
|
+
throw new Error("The login answered a start without the state");
|
|
2846
|
+
}
|
|
2847
|
+
return { state: started.state };
|
|
2848
|
+
});
|
|
2849
|
+
},
|
|
1037
2850
|
isOpen: async () => await findControllerLogin2(loginContainer) !== undefined,
|
|
1038
2851
|
status: async () => {
|
|
1039
2852
|
const login = await findControllerLogin2(loginContainer);
|
|
@@ -1046,7 +2859,7 @@ var createLogin = (context) => {
|
|
|
1046
2859
|
try {
|
|
1047
2860
|
const loginState = await Promise.race([
|
|
1048
2861
|
send(login, { command: "state" }),
|
|
1049
|
-
|
|
2862
|
+
delay2(loginStateTimeout, null)
|
|
1050
2863
|
]);
|
|
1051
2864
|
if (!loginState) {
|
|
1052
2865
|
return stoppedAnswering;
|
|
@@ -1072,7 +2885,7 @@ var createLogin = (context) => {
|
|
|
1072
2885
|
};
|
|
1073
2886
|
|
|
1074
2887
|
// packages/agent/src/operations.ts
|
|
1075
|
-
import { requiresDownload, transferRollback } from "@tsplc/build";
|
|
2888
|
+
import { requiresDownload as requiresDownload2, transferRollback as transferRollback2 } from "@tsplc/build";
|
|
1076
2889
|
var createOperations = (log) => {
|
|
1077
2890
|
let busy;
|
|
1078
2891
|
let held = false;
|
|
@@ -1124,11 +2937,11 @@ var createOperations = (log) => {
|
|
|
1124
2937
|
emit({ kind: "done", result: await run(emit) });
|
|
1125
2938
|
} catch (error) {
|
|
1126
2939
|
log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1127
|
-
const rollback = reportsRollback ?
|
|
2940
|
+
const rollback = reportsRollback ? transferRollback2(error) : undefined;
|
|
1128
2941
|
emit({
|
|
1129
2942
|
kind: "error",
|
|
1130
2943
|
message: errorMessage(error),
|
|
1131
|
-
downloadRequired:
|
|
2944
|
+
downloadRequired: requiresDownload2(error),
|
|
1132
2945
|
...rollback && { rollback }
|
|
1133
2946
|
});
|
|
1134
2947
|
} finally {
|
|
@@ -1147,20 +2960,49 @@ var createOperations = (log) => {
|
|
|
1147
2960
|
};
|
|
1148
2961
|
};
|
|
1149
2962
|
|
|
2963
|
+
// packages/agent/src/routes.ts
|
|
2964
|
+
var matchRoute = (routes, method, pathname) => {
|
|
2965
|
+
const parts = pathname.split("/");
|
|
2966
|
+
for (const route of routes) {
|
|
2967
|
+
const pattern = route.pattern.split("/");
|
|
2968
|
+
const rest = pattern.at(-1) === "*";
|
|
2969
|
+
if (route.method !== method || (rest ? parts.length < pattern.length : pattern.length !== parts.length)) {
|
|
2970
|
+
continue;
|
|
2971
|
+
}
|
|
2972
|
+
const params = {};
|
|
2973
|
+
const matched = pattern.every((segment, index) => {
|
|
2974
|
+
const part = parts[index] ?? "";
|
|
2975
|
+
if (rest && index === pattern.length - 1) {
|
|
2976
|
+
params["*"] = parts.slice(index).map(decodeURIComponent).join("/");
|
|
2977
|
+
return part !== "";
|
|
2978
|
+
}
|
|
2979
|
+
if (segment.startsWith(":")) {
|
|
2980
|
+
params[segment.slice(1)] = decodeURIComponent(part);
|
|
2981
|
+
return part !== "";
|
|
2982
|
+
}
|
|
2983
|
+
return segment === part;
|
|
2984
|
+
});
|
|
2985
|
+
if (matched) {
|
|
2986
|
+
return { route, params };
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
return;
|
|
2990
|
+
};
|
|
2991
|
+
|
|
1150
2992
|
// packages/agent/src/server-process.ts
|
|
1151
2993
|
import {
|
|
1152
2994
|
closeSync,
|
|
1153
|
-
existsSync as
|
|
2995
|
+
existsSync as existsSync8,
|
|
1154
2996
|
openSync,
|
|
1155
2997
|
renameSync,
|
|
1156
2998
|
statSync,
|
|
1157
2999
|
writeFileSync
|
|
1158
3000
|
} from "node:fs";
|
|
1159
|
-
import { readFile as
|
|
3001
|
+
import { readFile as readFile7, rm as rm4 } from "node:fs/promises";
|
|
1160
3002
|
import { uptime } from "node:os";
|
|
1161
|
-
import { dirname as
|
|
1162
|
-
import { setTimeout as
|
|
1163
|
-
import { z as
|
|
3003
|
+
import { dirname as dirname4 } from "node:path";
|
|
3004
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
3005
|
+
import { z as z9 } from "zod";
|
|
1164
3006
|
var healthyWithinMs = 60000;
|
|
1165
3007
|
var settleMs = 5000;
|
|
1166
3008
|
var restartDelayMs = 2000;
|
|
@@ -1168,20 +3010,20 @@ var watchMs = 2000;
|
|
|
1168
3010
|
var adoptWithinMs = 1e4;
|
|
1169
3011
|
var stopWithinMs = 1e4;
|
|
1170
3012
|
var rotateBytes2 = 10 * 2 ** 20;
|
|
1171
|
-
var recordSchema =
|
|
1172
|
-
pid:
|
|
1173
|
-
executable:
|
|
1174
|
-
startedAt:
|
|
3013
|
+
var recordSchema = z9.strictObject({
|
|
3014
|
+
pid: z9.int().positive(),
|
|
3015
|
+
executable: z9.string(),
|
|
3016
|
+
startedAt: z9.number()
|
|
1175
3017
|
});
|
|
1176
3018
|
var mayStillRun = (record, machine) => record.startedAt > machine.now - machine.uptimeSeconds * 1000 && machine.alive(record.pid);
|
|
1177
3019
|
var createServerSupervisor = (options) => {
|
|
1178
3020
|
let current;
|
|
1179
3021
|
const writeRecord = (record) => writeFileSync(options.record, JSON.stringify(record));
|
|
1180
3022
|
const readRecord = async () => {
|
|
1181
|
-
if (!
|
|
3023
|
+
if (!existsSync8(options.record)) {
|
|
1182
3024
|
return;
|
|
1183
3025
|
}
|
|
1184
|
-
return recordSchema.safeParse(await
|
|
3026
|
+
return recordSchema.safeParse(await readFile7(options.record, "utf8").then((text) => JSON.parse(text), () => {
|
|
1185
3027
|
return;
|
|
1186
3028
|
})).data;
|
|
1187
3029
|
};
|
|
@@ -1191,23 +3033,24 @@ var createServerSupervisor = (options) => {
|
|
|
1191
3033
|
return;
|
|
1192
3034
|
}
|
|
1193
3035
|
options.log(`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`);
|
|
1194
|
-
|
|
3036
|
+
delay3(restartDelayMs).then(() => {
|
|
1195
3037
|
if (current === running) {
|
|
1196
|
-
current = spawn(running.executable);
|
|
3038
|
+
current = spawn(running.executable, running.environment);
|
|
1197
3039
|
}
|
|
1198
3040
|
});
|
|
1199
3041
|
});
|
|
1200
3042
|
};
|
|
1201
|
-
const spawn = (executable) => {
|
|
3043
|
+
const spawn = (executable, environment) => {
|
|
1202
3044
|
const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
|
|
1203
|
-
if (
|
|
3045
|
+
if (existsSync8(options.output) && statSync(options.output).size >= rotateBytes2) {
|
|
1204
3046
|
renameSync(options.output, `${options.output}.1`);
|
|
1205
3047
|
}
|
|
1206
3048
|
const output = openSync(options.output, "a");
|
|
1207
3049
|
const child = (() => {
|
|
1208
3050
|
try {
|
|
1209
3051
|
return Bun.spawn(command, {
|
|
1210
|
-
cwd:
|
|
3052
|
+
cwd: dirname4(executable),
|
|
3053
|
+
env: environment,
|
|
1211
3054
|
detached: true,
|
|
1212
3055
|
stdio: ["ignore", output, output]
|
|
1213
3056
|
});
|
|
@@ -1217,6 +3060,7 @@ var createServerSupervisor = (options) => {
|
|
|
1217
3060
|
})();
|
|
1218
3061
|
const running = {
|
|
1219
3062
|
executable,
|
|
3063
|
+
environment,
|
|
1220
3064
|
pid: child.pid,
|
|
1221
3065
|
alive: () => child.exitCode === null && child.signalCode === null,
|
|
1222
3066
|
exited: child.exited
|
|
@@ -1225,7 +3069,7 @@ var createServerSupervisor = (options) => {
|
|
|
1225
3069
|
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
1226
3070
|
return running;
|
|
1227
3071
|
};
|
|
1228
|
-
const adopt = (record) => {
|
|
3072
|
+
const adopt = (record, environment) => {
|
|
1229
3073
|
const exited = Promise.withResolvers();
|
|
1230
3074
|
const watch = setInterval(() => {
|
|
1231
3075
|
if (!processAlive(record.pid)) {
|
|
@@ -1236,6 +3080,7 @@ var createServerSupervisor = (options) => {
|
|
|
1236
3080
|
watch.unref();
|
|
1237
3081
|
const running = {
|
|
1238
3082
|
executable: record.executable,
|
|
3083
|
+
environment,
|
|
1239
3084
|
pid: record.pid,
|
|
1240
3085
|
alive: () => processAlive(record.pid),
|
|
1241
3086
|
exited: exited.promise
|
|
@@ -1252,12 +3097,12 @@ var createServerSupervisor = (options) => {
|
|
|
1252
3097
|
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
1253
3098
|
return true;
|
|
1254
3099
|
}
|
|
1255
|
-
await
|
|
3100
|
+
await delay3(1000);
|
|
1256
3101
|
}
|
|
1257
3102
|
return false;
|
|
1258
3103
|
};
|
|
1259
|
-
const start = (executable) => {
|
|
1260
|
-
current = spawn(executable);
|
|
3104
|
+
const start = (executable, environment) => {
|
|
3105
|
+
current = spawn(executable, environment);
|
|
1261
3106
|
return current;
|
|
1262
3107
|
};
|
|
1263
3108
|
const stop = async () => {
|
|
@@ -1267,22 +3112,23 @@ var createServerSupervisor = (options) => {
|
|
|
1267
3112
|
return;
|
|
1268
3113
|
}
|
|
1269
3114
|
signalProcess(running.pid, "SIGTERM");
|
|
1270
|
-
await Promise.race([running.exited,
|
|
3115
|
+
await Promise.race([running.exited, delay3(stopWithinMs)]);
|
|
1271
3116
|
if (running.alive()) {
|
|
1272
3117
|
signalProcess(running.pid, "SIGKILL");
|
|
1273
3118
|
await running.exited;
|
|
1274
3119
|
}
|
|
1275
|
-
await
|
|
3120
|
+
await rm4(options.record, { force: true });
|
|
1276
3121
|
};
|
|
1277
3122
|
const healthy = async (running) => {
|
|
1278
3123
|
if (!options.healthUrl) {
|
|
1279
|
-
await
|
|
3124
|
+
await delay3(settleMs);
|
|
1280
3125
|
return running.alive();
|
|
1281
3126
|
}
|
|
1282
3127
|
return answers(running.alive, healthyWithinMs);
|
|
1283
3128
|
};
|
|
1284
3129
|
return {
|
|
1285
3130
|
resume: async (executable) => {
|
|
3131
|
+
const environment = await options.environment(executable);
|
|
1286
3132
|
const record = await readRecord();
|
|
1287
3133
|
if (record?.executable === executable && mayStillRun(record, {
|
|
1288
3134
|
now: Date.now(),
|
|
@@ -1290,20 +3136,21 @@ var createServerSupervisor = (options) => {
|
|
|
1290
3136
|
alive: processAlive
|
|
1291
3137
|
}) && await answers(() => processAlive(record.pid), adoptWithinMs)) {
|
|
1292
3138
|
options.log(`Took over the running server (process ${record.pid})`);
|
|
1293
|
-
current = adopt(record);
|
|
3139
|
+
current = adopt(record, environment);
|
|
1294
3140
|
return;
|
|
1295
3141
|
}
|
|
1296
|
-
start(executable);
|
|
3142
|
+
start(executable, environment);
|
|
1297
3143
|
},
|
|
1298
3144
|
stop,
|
|
1299
3145
|
leave: () => {
|
|
1300
3146
|
current = undefined;
|
|
1301
3147
|
},
|
|
1302
3148
|
replace: async (executable) => {
|
|
1303
|
-
const previous = current
|
|
3149
|
+
const previous = current;
|
|
3150
|
+
const environment = await options.environment(executable);
|
|
1304
3151
|
await stop();
|
|
1305
3152
|
let failure;
|
|
1306
|
-
const started = await (async () => healthy(start(executable)))().catch((error) => {
|
|
3153
|
+
const started = await (async () => healthy(start(executable, environment)))().catch((error) => {
|
|
1307
3154
|
failure = error;
|
|
1308
3155
|
return false;
|
|
1309
3156
|
});
|
|
@@ -1312,7 +3159,7 @@ var createServerSupervisor = (options) => {
|
|
|
1312
3159
|
}
|
|
1313
3160
|
await stop();
|
|
1314
3161
|
if (previous) {
|
|
1315
|
-
start(previous);
|
|
3162
|
+
start(previous.executable, previous.environment);
|
|
1316
3163
|
}
|
|
1317
3164
|
const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
1318
3165
|
throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
|
|
@@ -1325,28 +3172,29 @@ var createServerSupervisor = (options) => {
|
|
|
1325
3172
|
};
|
|
1326
3173
|
|
|
1327
3174
|
// 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) =>
|
|
3175
|
+
import { existsSync as existsSync9 } from "node:fs";
|
|
3176
|
+
import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile6 } from "node:fs/promises";
|
|
3177
|
+
import { join as join9 } from "node:path";
|
|
3178
|
+
var readJsonFile = async (path, schema) => existsSync9(path) ? schema.parse(JSON.parse(await readFile8(path, "utf8"))) : null;
|
|
3179
|
+
var writeJsonFile = (path, value) => writeFile6(path, JSON.stringify(value, null, 2));
|
|
1333
3180
|
var openState = async (directory) => {
|
|
1334
3181
|
const paths = {
|
|
1335
|
-
releases:
|
|
1336
|
-
controller:
|
|
1337
|
-
sources:
|
|
1338
|
-
release:
|
|
1339
|
-
target:
|
|
1340
|
-
deployments:
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
3182
|
+
releases: join9(directory, "releases"),
|
|
3183
|
+
controller: join9(directory, "controller"),
|
|
3184
|
+
sources: join9(directory, "sources"),
|
|
3185
|
+
release: join9(directory, "release.json"),
|
|
3186
|
+
target: join9(directory, "target.json"),
|
|
3187
|
+
deployments: join9(directory, "deployments.jsonl"),
|
|
3188
|
+
deploymentRecords: join9(directory, "deployments"),
|
|
3189
|
+
audit: join9(directory, "audit.jsonl"),
|
|
3190
|
+
debug: join9(directory, "debug"),
|
|
3191
|
+
server: join9(directory, "server.json"),
|
|
3192
|
+
agent: join9(directory, "agent.json"),
|
|
3193
|
+
logs: join9(directory, "logs"),
|
|
3194
|
+
serverLog: join9(directory, "logs", "server.log"),
|
|
3195
|
+
agentLog: join9(directory, "logs", "agent.log")
|
|
3196
|
+
};
|
|
3197
|
+
await mkdir4(paths.logs, { recursive: true });
|
|
1350
3198
|
const target = () => readJsonFile(paths.target, targetSchema);
|
|
1351
3199
|
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
1352
3200
|
return {
|
|
@@ -1373,23 +3221,26 @@ var openState = async (directory) => {
|
|
|
1373
3221
|
};
|
|
1374
3222
|
|
|
1375
3223
|
// 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
3224
|
var createAgent = async (options) => {
|
|
1382
3225
|
const { log } = options;
|
|
1383
3226
|
const state = await openState(options.state);
|
|
3227
|
+
const environmentVariables = options.environment ?? { ...process.env };
|
|
1384
3228
|
const server = createServerSupervisor({
|
|
1385
3229
|
healthUrl: options.serverHealthUrl,
|
|
1386
3230
|
record: state.paths.server,
|
|
1387
3231
|
output: state.paths.serverLog,
|
|
3232
|
+
environment: async (executable) => ({
|
|
3233
|
+
...await serverEnvironment(state.paths.releases, executable, environmentVariables),
|
|
3234
|
+
...options.serverAccess && {
|
|
3235
|
+
[plantAgentEnv.url]: options.serverAccess.url,
|
|
3236
|
+
[plantAgentEnv.token]: options.serverAccess.token
|
|
3237
|
+
}
|
|
3238
|
+
}),
|
|
1388
3239
|
log
|
|
1389
3240
|
});
|
|
1390
3241
|
const deployed = await state.release();
|
|
1391
3242
|
if (deployed?.server) {
|
|
1392
|
-
await server.resume(
|
|
3243
|
+
await server.resume(join10(state.paths.releases, deployed.server));
|
|
1393
3244
|
}
|
|
1394
3245
|
describeBuilder().then(log, (error) => log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`));
|
|
1395
3246
|
const operations = createOperations(log);
|
|
@@ -1407,18 +3258,56 @@ var createAgent = async (options) => {
|
|
|
1407
3258
|
readLogin: login.read,
|
|
1408
3259
|
loginStatus: login.status,
|
|
1409
3260
|
serverHealthUrl: options.serverHealthUrl,
|
|
1410
|
-
environment:
|
|
3261
|
+
environment: environmentVariables,
|
|
1411
3262
|
log
|
|
1412
3263
|
});
|
|
1413
|
-
const deployments = createDeployments({
|
|
3264
|
+
const deployments = await createDeployments({
|
|
1414
3265
|
state,
|
|
1415
3266
|
operations,
|
|
1416
3267
|
codesys,
|
|
1417
3268
|
server,
|
|
1418
3269
|
debugging,
|
|
3270
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
3271
|
+
now: () => new Date,
|
|
1419
3272
|
log
|
|
1420
3273
|
});
|
|
1421
|
-
const
|
|
3274
|
+
const audit = createAudit({
|
|
3275
|
+
file: state.paths.audit,
|
|
3276
|
+
onRecord: (entry) => debugging.record(entry)
|
|
3277
|
+
});
|
|
3278
|
+
const access = createAccess({
|
|
3279
|
+
token: options.token,
|
|
3280
|
+
readToken: options.readToken,
|
|
3281
|
+
serverToken: options.serverAccess?.token ?? null,
|
|
3282
|
+
file: accessFile(options.state),
|
|
3283
|
+
whois: createWhois({ run: runCommand, now: Date.now, log }),
|
|
3284
|
+
audit,
|
|
3285
|
+
now: Date.now,
|
|
3286
|
+
log
|
|
3287
|
+
});
|
|
3288
|
+
const environment = createEnvironment({
|
|
3289
|
+
state,
|
|
3290
|
+
server,
|
|
3291
|
+
operations,
|
|
3292
|
+
audit,
|
|
3293
|
+
file: environmentFile(options.state),
|
|
3294
|
+
variables: variablesFile(options.state),
|
|
3295
|
+
log
|
|
3296
|
+
});
|
|
3297
|
+
const dashboard = createDashboard();
|
|
3298
|
+
const apiRoutes = [
|
|
3299
|
+
...createDeploymentRoutes({ runner: deployments.runner, releases }),
|
|
3300
|
+
...access.routes,
|
|
3301
|
+
...environment.routes,
|
|
3302
|
+
...createControllerRoutes({
|
|
3303
|
+
login,
|
|
3304
|
+
warm: deployments.restart,
|
|
3305
|
+
audit,
|
|
3306
|
+
log
|
|
3307
|
+
}),
|
|
3308
|
+
...audit.routes
|
|
3309
|
+
];
|
|
3310
|
+
const route = async (request, identity) => {
|
|
1422
3311
|
const { pathname } = new URL(request.url);
|
|
1423
3312
|
const key = `${request.method} ${pathname}`;
|
|
1424
3313
|
switch (key) {
|
|
@@ -1460,7 +3349,7 @@ var createAgent = async (options) => {
|
|
|
1460
3349
|
});
|
|
1461
3350
|
}
|
|
1462
3351
|
case "POST /deploy":
|
|
1463
|
-
return deployments.deploy(() => readDeployRequest(releases, request), clientIdentity(request), clientRelease(request));
|
|
3352
|
+
return deployments.deploy(() => readDeployRequest(releases, request), identity, clientIdentity(request), clientRelease(request));
|
|
1464
3353
|
case "POST /login":
|
|
1465
3354
|
return login.open(credentialsSchema.nullable().parse(await request.json()));
|
|
1466
3355
|
case "POST /login/command":
|
|
@@ -1497,8 +3386,8 @@ var createAgent = async (options) => {
|
|
|
1497
3386
|
return Response.json({ error: `No route ${key}` }, { status: 404 });
|
|
1498
3387
|
}
|
|
1499
3388
|
};
|
|
1500
|
-
const respond = async (request) => {
|
|
1501
|
-
const { pathname, search
|
|
3389
|
+
const respond = async (request, peer) => {
|
|
3390
|
+
const { pathname, search } = new URL(request.url);
|
|
1502
3391
|
const debugPath = pathname.startsWith("/debug/");
|
|
1503
3392
|
if (pathname === "/debug") {
|
|
1504
3393
|
return new Response(null, {
|
|
@@ -1509,23 +3398,43 @@ var createAgent = async (options) => {
|
|
|
1509
3398
|
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js")) {
|
|
1510
3399
|
return debugging.handle(request, pathname.slice("/debug".length));
|
|
1511
3400
|
}
|
|
1512
|
-
const
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
3401
|
+
const page = await dashboard.handle(request);
|
|
3402
|
+
if (page) {
|
|
3403
|
+
return page;
|
|
3404
|
+
}
|
|
3405
|
+
const signing = await access.handle(request);
|
|
3406
|
+
if (signing) {
|
|
3407
|
+
return signing;
|
|
3408
|
+
}
|
|
3409
|
+
const identity = await access.identify(request, peer);
|
|
3410
|
+
if (identity instanceof Response) {
|
|
3411
|
+
return identity;
|
|
3412
|
+
}
|
|
3413
|
+
const api = pathname.startsWith("/api/") ? matchRoute(apiRoutes, request.method, pathname) : undefined;
|
|
3414
|
+
const required = api ? api.route.role : debugPath || request.method === "GET" && pathname === "/status" ? "viewer" : "admin";
|
|
3415
|
+
if (!allows(identity.role, required)) {
|
|
3416
|
+
return api ? Response.json({ error: `This needs the ${required} role` }, { status: 403 }) : Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1517
3417
|
}
|
|
1518
3418
|
try {
|
|
3419
|
+
if (api) {
|
|
3420
|
+
return await api.route.handle(request, {
|
|
3421
|
+
identity,
|
|
3422
|
+
params: api.params
|
|
3423
|
+
});
|
|
3424
|
+
}
|
|
3425
|
+
if (pathname.startsWith("/api/")) {
|
|
3426
|
+
return Response.json({ error: `No route ${request.method} ${pathname}` }, { status: 404 });
|
|
3427
|
+
}
|
|
1519
3428
|
if (debugPath) {
|
|
1520
3429
|
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
1521
3430
|
}
|
|
1522
|
-
return await route(request);
|
|
3431
|
+
return await route(request, identity);
|
|
1523
3432
|
} catch (error) {
|
|
1524
3433
|
if (error instanceof AgentError) {
|
|
1525
3434
|
return Response.json({ error: error.message }, { status: error.status });
|
|
1526
3435
|
}
|
|
1527
|
-
if (error instanceof
|
|
1528
|
-
return Response.json({ error:
|
|
3436
|
+
if (error instanceof z10.ZodError) {
|
|
3437
|
+
return Response.json({ error: z10.prettifyError(error) }, { status: 400 });
|
|
1529
3438
|
}
|
|
1530
3439
|
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1531
3440
|
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
@@ -1540,8 +3449,8 @@ var createAgent = async (options) => {
|
|
|
1540
3449
|
server.leave();
|
|
1541
3450
|
};
|
|
1542
3451
|
return {
|
|
1543
|
-
fetch: async (request) => {
|
|
1544
|
-
const response = await respond(request);
|
|
3452
|
+
fetch: async (request, peer = null) => {
|
|
3453
|
+
const response = await respond(request, peer);
|
|
1545
3454
|
const headers = new Headers(response.headers);
|
|
1546
3455
|
headers.set(agentVersionHeader, tsplcVersion);
|
|
1547
3456
|
return new Response(response.body, {
|
|
@@ -1608,6 +3517,7 @@ var askCredentials = async () => ({
|
|
|
1608
3517
|
});
|
|
1609
3518
|
export {
|
|
1610
3519
|
agentDockerResources,
|
|
3520
|
+
agentVersionHeader,
|
|
1611
3521
|
ask,
|
|
1612
3522
|
askCredentials,
|
|
1613
3523
|
askSecret,
|
|
@@ -1629,5 +3539,5 @@ export {
|
|
|
1629
3539
|
variableSchema
|
|
1630
3540
|
};
|
|
1631
3541
|
|
|
1632
|
-
//# debugId=
|
|
3542
|
+
//# debugId=5E0A3D082AABCB2264756E2164756E21
|
|
1633
3543
|
//# sourceMappingURL=index.js.map
|