@tsplc/agent 0.2.21 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +367 -152
- package/dist/cli.js.map +16 -15
- package/dist/client.js +121 -20
- package/dist/client.js.map +6 -5
- package/dist/index.js +352 -144
- package/dist/index.js.map +14 -13
- package/package.json +16 -6
- package/src/agent.ts +94 -54
- package/src/cli.ts +12 -5
- package/src/client.ts +114 -23
- package/src/codesys.ts +23 -24
- package/src/debugging.ts +8 -2
- package/src/deploy.ts +141 -125
- package/src/index.ts +4 -4
- package/src/login.ts +8 -5
- package/src/operations.ts +11 -6
- package/src/protocol.ts +91 -4
- package/src/releases.ts +219 -11
- package/src/secrets.ts +3 -2
- package/src/server-process.ts +1 -1
- package/src/transfer.ts +94 -0
package/dist/cli.js
CHANGED
|
@@ -6,13 +6,14 @@ import { homedir } from "os";
|
|
|
6
6
|
import { join as join8 } from "path";
|
|
7
7
|
import { parseArgs } from "util";
|
|
8
8
|
import { configureDocker, configureGateway } from "@tsplc/build";
|
|
9
|
-
import {
|
|
9
|
+
import { tcpPort as tcpPort2 } from "@tsplc/config/build";
|
|
10
|
+
import { z as z4 } from "zod";
|
|
10
11
|
|
|
11
12
|
// packages/agent/src/agent.ts
|
|
12
13
|
import { timingSafeEqual } from "node:crypto";
|
|
13
14
|
import { join as join7 } from "node:path";
|
|
14
15
|
import { loginCommandSchema } from "@tsplc/build";
|
|
15
|
-
import { z as
|
|
16
|
+
import { z as z3 } from "zod";
|
|
16
17
|
|
|
17
18
|
// packages/agent/src/debugging.ts
|
|
18
19
|
import { existsSync as existsSync3 } from "node:fs";
|
|
@@ -24,6 +25,7 @@ import {
|
|
|
24
25
|
loadManifest,
|
|
25
26
|
timelineEntries
|
|
26
27
|
} from "@tsplc/debug";
|
|
28
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
27
29
|
|
|
28
30
|
// packages/agent/src/errors.ts
|
|
29
31
|
class AgentError extends Error {
|
|
@@ -75,9 +77,15 @@ var readJsonl = async (file, schema, limit) => {
|
|
|
75
77
|
};
|
|
76
78
|
|
|
77
79
|
// packages/agent/src/protocol.ts
|
|
80
|
+
import { rollbackSchema } from "@tsplc/build";
|
|
78
81
|
import { tsplcConfigSchema } from "@tsplc/config";
|
|
79
|
-
import { tcpPort } from "@tsplc/config/build";
|
|
82
|
+
import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
|
|
80
83
|
import { z } from "zod";
|
|
84
|
+
// packages/agent/package.json
|
|
85
|
+
var version = "0.4.0";
|
|
86
|
+
|
|
87
|
+
// packages/agent/src/protocol.ts
|
|
88
|
+
var tsplcVersion = version;
|
|
81
89
|
var targetSchema = z.strictObject({
|
|
82
90
|
host: z.string().nonempty(),
|
|
83
91
|
port: tcpPort
|
|
@@ -102,7 +110,15 @@ var variableSchema = z.strictObject({
|
|
|
102
110
|
type: z.string()
|
|
103
111
|
});
|
|
104
112
|
var releaseManifestSchema = z.strictObject({
|
|
105
|
-
config: z.record(z.string(), z.unknown()),
|
|
113
|
+
config: z.record(z.string(), z.unknown()).superRefine((config, context) => {
|
|
114
|
+
const release = releaseConfigSchema.safeParse(config);
|
|
115
|
+
if (!release.success) {
|
|
116
|
+
context.addIssue({
|
|
117
|
+
code: "custom",
|
|
118
|
+
message: `Invalid release config: ${z.prettifyError(release.error)}`
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}),
|
|
106
122
|
variables: z.array(variableSchema),
|
|
107
123
|
server: z.string().nonempty().optional(),
|
|
108
124
|
debug: tsplcConfigSchema.shape.debug,
|
|
@@ -115,13 +131,34 @@ var deployOptionsSchema = z.strictObject({
|
|
|
115
131
|
download: z.boolean(),
|
|
116
132
|
initializeUser: z.boolean()
|
|
117
133
|
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
134
|
+
var releaseBuckets = 256;
|
|
135
|
+
var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
|
|
136
|
+
var compareRequestSchema = z.strictObject({
|
|
137
|
+
buckets: z.array(shortHex).length(releaseBuckets)
|
|
138
|
+
});
|
|
139
|
+
var comparisonSchema = z.strictObject({
|
|
140
|
+
base: shortHex.nullable(),
|
|
141
|
+
changed: z.array(z.strictObject({
|
|
142
|
+
bucket: z.number().int().min(0).max(releaseBuckets - 1),
|
|
143
|
+
files: z.record(z.string(), shortHex)
|
|
144
|
+
}))
|
|
145
|
+
});
|
|
146
|
+
var releaseUploadType = "application/vnd.tsplc.release+zstd";
|
|
147
|
+
var releaseUploadSchema = z.strictObject({
|
|
148
|
+
manifest: releaseManifestSchema,
|
|
149
|
+
options: deployOptionsSchema,
|
|
150
|
+
base: shortHex.nullable(),
|
|
151
|
+
buckets: compareRequestSchema.shape.buckets,
|
|
152
|
+
remove: z.array(z.string())
|
|
153
|
+
});
|
|
118
154
|
var eventSchema = z.discriminatedUnion("kind", [
|
|
119
155
|
z.strictObject({ kind: z.literal("progress"), message: z.string() }),
|
|
120
156
|
z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
|
|
121
157
|
z.strictObject({
|
|
122
158
|
kind: z.literal("error"),
|
|
123
159
|
message: z.string(),
|
|
124
|
-
downloadRequired: z.boolean()
|
|
160
|
+
downloadRequired: z.boolean(),
|
|
161
|
+
rollback: rollbackSchema.optional()
|
|
125
162
|
})
|
|
126
163
|
]);
|
|
127
164
|
var errorSchema = z.object({ error: z.string() });
|
|
@@ -146,12 +183,20 @@ var statusSchema = z.strictObject({
|
|
|
146
183
|
var logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
147
184
|
var clientHeaders = {
|
|
148
185
|
user: "x-tsplc-user",
|
|
149
|
-
host: "x-tsplc-host"
|
|
186
|
+
host: "x-tsplc-host",
|
|
187
|
+
version: "x-tsplc-version",
|
|
188
|
+
scripts: "x-tsplc-scripts"
|
|
150
189
|
};
|
|
190
|
+
var agentVersionHeader = "x-tsplc-agent-version";
|
|
191
|
+
var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: update the plant agent to ${versions.client} and run tsplc-agent setup there${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
|
|
151
192
|
var clientIdentity = (request) => {
|
|
152
193
|
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
153
194
|
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
154
195
|
};
|
|
196
|
+
var clientRelease = (request) => ({
|
|
197
|
+
version: request.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,
|
|
198
|
+
scripts: request.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined
|
|
199
|
+
});
|
|
155
200
|
var deploymentSchema = z.strictObject({
|
|
156
201
|
at: z.iso.datetime(),
|
|
157
202
|
release: z.string(),
|
|
@@ -173,44 +218,112 @@ var auditSchema = z.strictObject({
|
|
|
173
218
|
});
|
|
174
219
|
|
|
175
220
|
// packages/agent/src/releases.ts
|
|
176
|
-
import { createHash } from "node:crypto";
|
|
221
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
177
222
|
import { existsSync as existsSync2 } from "node:fs";
|
|
178
223
|
import {
|
|
179
224
|
mkdir,
|
|
180
225
|
mkdtemp,
|
|
226
|
+
readdir,
|
|
181
227
|
readFile as readFile2,
|
|
182
228
|
rename as rename2,
|
|
183
229
|
rm,
|
|
230
|
+
stat as stat2,
|
|
184
231
|
writeFile
|
|
185
232
|
} from "node:fs/promises";
|
|
186
|
-
import { dirname, join, posix } from "node:path";
|
|
233
|
+
import { dirname, join, posix, sep } from "node:path";
|
|
187
234
|
import { z as z2 } from "zod";
|
|
235
|
+
|
|
236
|
+
// packages/agent/src/transfer.ts
|
|
237
|
+
import { createHash } from "node:crypto";
|
|
238
|
+
var shortDigest = (data) => createHash("sha256").update(data).digest("hex").slice(0, 16);
|
|
239
|
+
var fileBucket = (path) => createHash("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
|
|
240
|
+
var bucketDigests = (files) => {
|
|
241
|
+
const buckets = Array.from({ length: releaseBuckets }, () => []);
|
|
242
|
+
for (const { path, digest } of files) {
|
|
243
|
+
buckets[fileBucket(path)]?.push(`${path}\x00${digest}`);
|
|
244
|
+
}
|
|
245
|
+
return buckets.map((entries) => shortDigest(entries.sort().join(`
|
|
246
|
+
`)));
|
|
247
|
+
};
|
|
248
|
+
var lengthBytes = 4;
|
|
249
|
+
var decodeUpload = async (compressed) => {
|
|
250
|
+
const body = new Uint8Array(await Bun.zstdDecompress(compressed));
|
|
251
|
+
const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
|
252
|
+
const frames = [];
|
|
253
|
+
let offset = 0;
|
|
254
|
+
while (offset < body.length) {
|
|
255
|
+
if (offset + lengthBytes > body.length) {
|
|
256
|
+
throw new Error("The release upload ends inside a frame");
|
|
257
|
+
}
|
|
258
|
+
const end = offset + lengthBytes + view.getUint32(offset);
|
|
259
|
+
if (end > body.length) {
|
|
260
|
+
throw new Error("The release upload ends inside a frame");
|
|
261
|
+
}
|
|
262
|
+
frames.push(body.subarray(offset + lengthBytes, end));
|
|
263
|
+
offset = end;
|
|
264
|
+
}
|
|
265
|
+
const [header, ...rest] = frames;
|
|
266
|
+
if (!header || rest.length % 2 !== 0) {
|
|
267
|
+
throw new Error("The release upload has no header or a file without content");
|
|
268
|
+
}
|
|
269
|
+
const decoder = new TextDecoder;
|
|
270
|
+
const files = Array.from({ length: rest.length / 2 }, (_, index) => ({
|
|
271
|
+
path: decoder.decode(rest[2 * index]),
|
|
272
|
+
content: rest[2 * index + 1] ?? new Uint8Array
|
|
273
|
+
}));
|
|
274
|
+
return { header: JSON.parse(decoder.decode(header)), files };
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
// packages/agent/src/releases.ts
|
|
188
278
|
var filePrefix = "files/";
|
|
189
279
|
var releasePath = (name) => {
|
|
190
|
-
const path = posix.normalize(name
|
|
280
|
+
const path = posix.normalize(name);
|
|
191
281
|
if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
|
|
192
282
|
throw new Error(`Invalid release file name: ${name}`);
|
|
193
283
|
}
|
|
194
284
|
return path;
|
|
195
285
|
};
|
|
286
|
+
var checkServer = ({ manifest, files }) => {
|
|
287
|
+
if (manifest.server && !files.some((file) => file.path === manifest.server)) {
|
|
288
|
+
throw new Error(`The release names a server ${manifest.server} it doesn't contain`);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
196
291
|
var readUpload = async (form) => {
|
|
197
292
|
if (form.get("encoding") !== uploadEncoding) {
|
|
198
293
|
throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
|
|
199
294
|
}
|
|
200
295
|
const manifest = releaseManifestSchema.parse(JSON.parse(z2.string().parse(form.get("manifest"))));
|
|
201
296
|
const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
|
|
202
|
-
path: releasePath(name),
|
|
297
|
+
path: releasePath(name.slice(filePrefix.length)),
|
|
203
298
|
content: Bun.gunzipSync(await z2.instanceof(File).parse(value).bytes())
|
|
204
299
|
})));
|
|
205
|
-
|
|
206
|
-
|
|
300
|
+
const upload = { manifest, files };
|
|
301
|
+
checkServer(upload);
|
|
302
|
+
return upload;
|
|
303
|
+
};
|
|
304
|
+
var readDeployRequest = async (releases, request) => {
|
|
305
|
+
const type = request.headers.get("content-type") ?? "";
|
|
306
|
+
if (type.split(";")[0]?.trim() === releaseUploadType) {
|
|
307
|
+
const { header, files } = await decodeUpload(await request.bytes());
|
|
308
|
+
const upload = releaseUploadSchema.parse(header);
|
|
309
|
+
return {
|
|
310
|
+
settings: upload.options,
|
|
311
|
+
upload: await releases.assemble(upload, files)
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
if (type.startsWith("multipart/form-data")) {
|
|
315
|
+
const form = await request.formData();
|
|
316
|
+
return {
|
|
317
|
+
settings: deployOptionsSchema.parse(JSON.parse(z2.string().parse(form.get("options")))),
|
|
318
|
+
upload: await readUpload(form)
|
|
319
|
+
};
|
|
207
320
|
}
|
|
208
|
-
|
|
321
|
+
throw new AgentError(`Unsupported deployment content type ${type}`, 415);
|
|
209
322
|
};
|
|
210
323
|
var saveRelease = async (releases, { manifest, files }) => {
|
|
211
|
-
const hash =
|
|
324
|
+
const hash = createHash2("sha256").update(JSON.stringify(manifest));
|
|
212
325
|
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
213
|
-
hash.update(file.path).update(
|
|
326
|
+
hash.update(file.path).update(createHash2("sha256").update(file.content).digest("hex"));
|
|
214
327
|
}
|
|
215
328
|
const id = hash.digest("hex").slice(0, 16);
|
|
216
329
|
const directory = join(releases, id);
|
|
@@ -238,6 +351,100 @@ var loadRelease = async (releases, id) => {
|
|
|
238
351
|
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(join(directory, "manifest.json"), "utf8")));
|
|
239
352
|
return { id, directory, manifest };
|
|
240
353
|
};
|
|
354
|
+
var createReleaseStore = (releases) => {
|
|
355
|
+
const indexes = new Map;
|
|
356
|
+
const readIndex = async (id) => {
|
|
357
|
+
const directory = join(releases, id);
|
|
358
|
+
const files = new Map;
|
|
359
|
+
for await (const found of new Bun.Glob("**/*").scan({
|
|
360
|
+
cwd: directory,
|
|
361
|
+
dot: true
|
|
362
|
+
})) {
|
|
363
|
+
const path = found.split(sep).join("/");
|
|
364
|
+
if (path !== "manifest.json") {
|
|
365
|
+
files.set(path, shortDigest(await readFile2(join(directory, found))));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
369
|
+
return { files, buckets: bucketDigests(digests) };
|
|
370
|
+
};
|
|
371
|
+
const index = (id) => {
|
|
372
|
+
const known = indexes.get(id);
|
|
373
|
+
if (known) {
|
|
374
|
+
return known;
|
|
375
|
+
}
|
|
376
|
+
const reading = readIndex(id);
|
|
377
|
+
indexes.set(id, reading);
|
|
378
|
+
reading.catch(() => indexes.delete(id));
|
|
379
|
+
return reading;
|
|
380
|
+
};
|
|
381
|
+
const newest = async () => {
|
|
382
|
+
if (!existsSync2(releases)) {
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const stored = await Promise.all((await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map(async ({ name }) => ({
|
|
386
|
+
name,
|
|
387
|
+
created: (await stat2(join(releases, name))).mtimeMs
|
|
388
|
+
})));
|
|
389
|
+
return stored.sort((left, right) => right.created - left.created)[0]?.name;
|
|
390
|
+
};
|
|
391
|
+
return {
|
|
392
|
+
compare: async (buckets, deployed) => {
|
|
393
|
+
const candidates = [
|
|
394
|
+
...new Set([deployed, await newest()].filter((id) => id != null))
|
|
395
|
+
].filter((id) => existsSync2(join(releases, id, "manifest.json")));
|
|
396
|
+
const compared = await Promise.all(candidates.map(async (id) => {
|
|
397
|
+
const { files, buckets: stored } = await index(id);
|
|
398
|
+
const changed = buckets.flatMap((digest, bucket) => stored[bucket] === digest ? [] : [bucket]);
|
|
399
|
+
return { id, files, changed };
|
|
400
|
+
}));
|
|
401
|
+
const [best] = compared.sort((left, right) => left.changed.length - right.changed.length);
|
|
402
|
+
if (!best) {
|
|
403
|
+
return { base: null, changed: [] };
|
|
404
|
+
}
|
|
405
|
+
const changed = new Map(best.changed.map((bucket) => [bucket, {}]));
|
|
406
|
+
for (const [path, digest] of best.files) {
|
|
407
|
+
const held = changed.get(fileBucket(path));
|
|
408
|
+
if (held) {
|
|
409
|
+
held[path] = digest;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return {
|
|
413
|
+
base: best.id,
|
|
414
|
+
changed: [...changed].map(([bucket, files]) => ({ bucket, files }))
|
|
415
|
+
};
|
|
416
|
+
},
|
|
417
|
+
assemble: async ({ manifest, base, buckets, remove }, uploaded) => {
|
|
418
|
+
const files = new Map(uploaded.map(({ path, content }) => [releasePath(path), content]));
|
|
419
|
+
if (files.size !== uploaded.length) {
|
|
420
|
+
throw new AgentError("The release upload sends a file twice", 400);
|
|
421
|
+
}
|
|
422
|
+
if (base !== null) {
|
|
423
|
+
if (!existsSync2(join(releases, base, "manifest.json"))) {
|
|
424
|
+
throw new AgentError(`The release ${base} this upload builds on is gone; deploy again`, 409);
|
|
425
|
+
}
|
|
426
|
+
const removed = new Set(remove);
|
|
427
|
+
const reused = [...(await index(base)).files.keys()].filter((path) => !removed.has(path) && !files.has(path));
|
|
428
|
+
for (const path of reused) {
|
|
429
|
+
files.set(path, new Uint8Array(await readFile2(join(releases, base, path))));
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
const assembled = bucketDigests([...files].map(([path, content]) => ({
|
|
433
|
+
path,
|
|
434
|
+
digest: shortDigest(content)
|
|
435
|
+
})));
|
|
436
|
+
if (assembled.some((digest, bucket) => digest !== buckets[bucket])) {
|
|
437
|
+
throw new AgentError("The release upload doesn't match the release it describes; deploy again", 400);
|
|
438
|
+
}
|
|
439
|
+
const upload = {
|
|
440
|
+
manifest,
|
|
441
|
+
files: [...files].map(([path, content]) => ({ path, content }))
|
|
442
|
+
};
|
|
443
|
+
checkServer(upload);
|
|
444
|
+
return upload;
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
};
|
|
241
448
|
|
|
242
449
|
// packages/agent/src/secrets.ts
|
|
243
450
|
import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
@@ -292,7 +499,7 @@ var readSecrets = async (secrets) => {
|
|
|
292
499
|
}
|
|
293
500
|
return values;
|
|
294
501
|
};
|
|
295
|
-
var releaseVariable = async (manifest, name) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) :
|
|
502
|
+
var releaseVariable = async (manifest, name, environment) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : environment[name];
|
|
296
503
|
var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
|
|
297
504
|
var withSecrets = async (config, secrets, directory) => {
|
|
298
505
|
await rm2(directory, { recursive: true, force: true });
|
|
@@ -321,12 +528,12 @@ var createDebugging = (context) => {
|
|
|
321
528
|
return null;
|
|
322
529
|
}
|
|
323
530
|
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
324
|
-
const manifestFile = join3(directory,
|
|
531
|
+
const manifestFile = join3(directory, debugManifestFile);
|
|
325
532
|
if (!existsSync3(manifestFile)) {
|
|
326
533
|
return null;
|
|
327
534
|
}
|
|
328
535
|
const manifest = await loadManifest(manifestFile);
|
|
329
|
-
const serverToken = releaseManifest.serverTokenEnv && await releaseVariable(releaseManifest, releaseManifest.serverTokenEnv);
|
|
536
|
+
const serverToken = releaseManifest.serverTokenEnv && await releaseVariable(releaseManifest, releaseManifest.serverTokenEnv, context.environment);
|
|
330
537
|
const debug = await createDebugger({
|
|
331
538
|
manifest,
|
|
332
539
|
adapter: createLoginAdapter({
|
|
@@ -387,22 +594,21 @@ var createDebugging = (context) => {
|
|
|
387
594
|
|
|
388
595
|
// packages/agent/src/deploy.ts
|
|
389
596
|
import { existsSync as existsSync4 } from "node:fs";
|
|
390
|
-
import { readdir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
|
|
391
597
|
import { join as join5 } from "node:path";
|
|
392
|
-
import { setTimeout as delay } from "node:timers/promises";
|
|
393
598
|
import {
|
|
599
|
+
controllerBaseline,
|
|
394
600
|
findControllerLogin,
|
|
395
601
|
startWarmController,
|
|
396
|
-
updateWarmController
|
|
602
|
+
updateWarmController,
|
|
603
|
+
workerScriptsDigest
|
|
397
604
|
} from "@tsplc/build";
|
|
398
605
|
import { loadManifest as loadManifest2 } from "@tsplc/debug";
|
|
399
|
-
import {
|
|
606
|
+
import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
|
|
400
607
|
|
|
401
608
|
// packages/agent/src/codesys.ts
|
|
402
|
-
import { execFile } from "node:child_process";
|
|
403
609
|
import { join as join4 } from "node:path";
|
|
404
|
-
import {
|
|
405
|
-
import {
|
|
610
|
+
import { captureDocker, gatewayImage } from "@tsplc/build";
|
|
611
|
+
import { resolveConfig } from "@tsplc/config/build";
|
|
406
612
|
var network = "tsplc-agent";
|
|
407
613
|
var codesysNetwork = "tsplc-agent-codesys";
|
|
408
614
|
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
@@ -412,10 +618,8 @@ var credentialNames = {
|
|
|
412
618
|
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
413
619
|
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
414
620
|
};
|
|
415
|
-
var
|
|
416
|
-
|
|
417
|
-
return stdout.trim();
|
|
418
|
-
};
|
|
621
|
+
var dockerTimeout = 60000;
|
|
622
|
+
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
419
623
|
var ensureNetwork = async (name, ...options) => {
|
|
420
624
|
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
421
625
|
await docker("network", "create", ...options, name);
|
|
@@ -433,19 +637,14 @@ var ensureGateway = async () => {
|
|
|
433
637
|
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
434
638
|
}
|
|
435
639
|
};
|
|
436
|
-
var
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
} finally {
|
|
442
|
-
delete process.env[credentialNames.usernameEnv];
|
|
443
|
-
delete process.env[credentialNames.passwordEnv];
|
|
444
|
-
}
|
|
445
|
-
};
|
|
446
|
-
var controllerConfig = (release, target, controllerDirectory) => ({
|
|
640
|
+
var credentialEnvironment = (credentials) => ({
|
|
641
|
+
[credentialNames.usernameEnv]: credentials.username,
|
|
642
|
+
[credentialNames.passwordEnv]: credentials.password
|
|
643
|
+
});
|
|
644
|
+
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
447
645
|
...resolveConfig({
|
|
448
646
|
...release.manifest.config,
|
|
647
|
+
...settings.bulkImport && { bulkImport: true },
|
|
449
648
|
online: {
|
|
450
649
|
network: codesysNetwork,
|
|
451
650
|
gateway,
|
|
@@ -457,39 +656,6 @@ var controllerConfig = (release, target, controllerDirectory) => ({
|
|
|
457
656
|
});
|
|
458
657
|
|
|
459
658
|
// packages/agent/src/deploy.ts
|
|
460
|
-
var followProgress = (controller, emit) => {
|
|
461
|
-
const jobs = join5(controller, ".codesys/controller/jobs");
|
|
462
|
-
const since = Date.now();
|
|
463
|
-
let following = true;
|
|
464
|
-
const done = (async () => {
|
|
465
|
-
let log;
|
|
466
|
-
let offset = 0;
|
|
467
|
-
while (following) {
|
|
468
|
-
await delay(2000);
|
|
469
|
-
if (!log && existsSync4(jobs)) {
|
|
470
|
-
for (const job of await readdir(jobs)) {
|
|
471
|
-
const path = join5(jobs, job, ".codesys/controller/progress.log");
|
|
472
|
-
if (existsSync4(path) && (await stat2(path)).mtimeMs >= since) {
|
|
473
|
-
log = path;
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
if (!log) {
|
|
478
|
-
continue;
|
|
479
|
-
}
|
|
480
|
-
const text = await readFile4(log, "utf8");
|
|
481
|
-
for (const line of text.slice(offset).split(`
|
|
482
|
-
`).filter(Boolean)) {
|
|
483
|
-
emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
|
|
484
|
-
}
|
|
485
|
-
offset = text.length;
|
|
486
|
-
}
|
|
487
|
-
})();
|
|
488
|
-
return async () => {
|
|
489
|
-
following = false;
|
|
490
|
-
await done;
|
|
491
|
-
};
|
|
492
|
-
};
|
|
493
659
|
var createDeployments = (context) => {
|
|
494
660
|
const { state, server } = context;
|
|
495
661
|
const warming = (async () => {
|
|
@@ -500,56 +666,67 @@ var createDeployments = (context) => {
|
|
|
500
666
|
}
|
|
501
667
|
await ensureGateway();
|
|
502
668
|
const release = await loadRelease(state.paths.releases, deployed.id);
|
|
503
|
-
await startWarmController(controllerConfig(release, target, state.paths.controller), deployContainer);
|
|
669
|
+
await startWarmController(controllerConfig(release, target, state.paths.controller, context.codesys), deployContainer);
|
|
504
670
|
})().catch((error) => {
|
|
505
671
|
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
506
672
|
});
|
|
507
673
|
return {
|
|
508
|
-
deploy: async (
|
|
509
|
-
|
|
510
|
-
|
|
674
|
+
deploy: async (readRequest, client, clientTsplc) => {
|
|
675
|
+
if (clientTsplc.version !== undefined && clientTsplc.version !== tsplcVersion) {
|
|
676
|
+
throw new AgentError(versionMismatch({ agent: tsplcVersion, client: clientTsplc.version }), 409);
|
|
677
|
+
}
|
|
678
|
+
const { settings, upload } = await readRequest();
|
|
511
679
|
const target = await state.requireTarget();
|
|
512
680
|
if (await findControllerLogin(loginContainer)) {
|
|
513
681
|
throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
|
|
514
682
|
}
|
|
515
683
|
const credentials = await controllerCredentials(settings.credentials);
|
|
516
684
|
const secrets = await readSecrets(upload.manifest.secrets);
|
|
685
|
+
const scripts = await workerScriptsDigest();
|
|
517
686
|
return context.operations.stream("a deployment", async (emit) => {
|
|
687
|
+
if (clientTsplc.version === undefined) {
|
|
688
|
+
emit({
|
|
689
|
+
kind: "progress",
|
|
690
|
+
message: `Warning: the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`
|
|
691
|
+
});
|
|
692
|
+
} else if (clientTsplc.scripts !== undefined && clientTsplc.scripts !== scripts) {
|
|
693
|
+
emit({
|
|
694
|
+
kind: "progress",
|
|
695
|
+
message: `Warning: 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`
|
|
696
|
+
});
|
|
697
|
+
}
|
|
518
698
|
const release = await saveRelease(state.paths.releases, upload);
|
|
519
|
-
|
|
520
|
-
|
|
699
|
+
const baseline = settings.download ? "valid" : await controllerBaseline(state.paths.controller);
|
|
700
|
+
if (baseline !== "valid") {
|
|
701
|
+
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 });
|
|
521
702
|
}
|
|
522
|
-
const config = await withSecrets(controllerConfig(release, target, state.paths.controller), secrets, state.paths.sources);
|
|
703
|
+
const config = await withSecrets(controllerConfig(release, target, state.paths.controller, context.codesys), secrets, state.paths.sources);
|
|
523
704
|
const previous = await state.release();
|
|
524
|
-
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
525
|
-
if (serverPath) {
|
|
526
|
-
emit({ kind: "progress", message: "Starting the new server" });
|
|
527
|
-
await server.replace(join5(state.paths.releases, serverPath));
|
|
528
|
-
}
|
|
529
705
|
const kind = settings.download ? "download" : "online-change";
|
|
530
706
|
emit({ kind: "progress", message: `Starting the ${kind}` });
|
|
531
707
|
await ensureGateway();
|
|
532
708
|
await warming;
|
|
533
|
-
const
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
709
|
+
const receipt = await updateWarmController(config, deployContainer, kind, {
|
|
710
|
+
initializeUser: settings.initializeUser,
|
|
711
|
+
credentials,
|
|
712
|
+
onProgress: (message) => emit({ kind: "progress", message })
|
|
713
|
+
});
|
|
714
|
+
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
715
|
+
if (serverPath) {
|
|
716
|
+
emit({ kind: "progress", message: "Starting the new server" });
|
|
717
|
+
}
|
|
718
|
+
const serverFailure = serverPath ? await server.replace(join5(state.paths.releases, serverPath)).then(() => {
|
|
719
|
+
return;
|
|
720
|
+
}, (error) => errorMessage(error)) : undefined;
|
|
544
721
|
const deployed = {
|
|
545
722
|
id: release.id,
|
|
546
723
|
deployedAt: new Date().toISOString(),
|
|
547
724
|
operation: kind,
|
|
548
725
|
controllerIds: receipt.controllerIds,
|
|
549
|
-
server: serverPath ?? previous?.server
|
|
726
|
+
server: serverFailure === undefined ? serverPath ?? previous?.server : previous?.server
|
|
550
727
|
};
|
|
551
728
|
await state.setRelease(deployed);
|
|
552
|
-
const debugManifest = join5(release.directory,
|
|
729
|
+
const debugManifest = join5(release.directory, debugManifestFile2);
|
|
553
730
|
const deployment = {
|
|
554
731
|
at: deployed.deployedAt,
|
|
555
732
|
release: release.id,
|
|
@@ -562,8 +739,11 @@ var createDeployments = (context) => {
|
|
|
562
739
|
};
|
|
563
740
|
await appendJsonl(state.paths.deployments, deployment);
|
|
564
741
|
context.debugging.restart();
|
|
742
|
+
if (serverFailure !== undefined) {
|
|
743
|
+
throw new Error(`The controller runs release ${release.id}. ${serverFailure}`);
|
|
744
|
+
}
|
|
565
745
|
return deployed;
|
|
566
|
-
});
|
|
746
|
+
}, { reportsRollback: clientTsplc.version !== undefined });
|
|
567
747
|
}
|
|
568
748
|
};
|
|
569
749
|
};
|
|
@@ -621,7 +801,7 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
621
801
|
};
|
|
622
802
|
|
|
623
803
|
// packages/agent/src/login.ts
|
|
624
|
-
import { setTimeout as
|
|
804
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
625
805
|
import {
|
|
626
806
|
failureReason,
|
|
627
807
|
findControllerLogin as findControllerLogin2,
|
|
@@ -711,7 +891,7 @@ var createLogin = (context) => {
|
|
|
711
891
|
open: async (sent) => {
|
|
712
892
|
const credentials = await controllerCredentials(sent);
|
|
713
893
|
context.log(`Opening a login with the ${sent ? "provided" : "stored"} controller user`);
|
|
714
|
-
const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller);
|
|
894
|
+
const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller, context.codesys);
|
|
715
895
|
return operations.stream("a login", async (emit) => {
|
|
716
896
|
if (await findControllerLogin2(loginContainer)) {
|
|
717
897
|
throw new AgentError("A login is already open", 409);
|
|
@@ -721,7 +901,9 @@ var createLogin = (context) => {
|
|
|
721
901
|
message: "Logging in; CODESYS takes minutes to start"
|
|
722
902
|
});
|
|
723
903
|
await ensureGateway();
|
|
724
|
-
const login = await
|
|
904
|
+
const login = await openControllerLogin(config, loginContainer, {
|
|
905
|
+
environment: credentialEnvironment(credentials)
|
|
906
|
+
});
|
|
725
907
|
return send(login, { command: "state" });
|
|
726
908
|
});
|
|
727
909
|
},
|
|
@@ -769,7 +951,7 @@ var createLogin = (context) => {
|
|
|
769
951
|
try {
|
|
770
952
|
const loginState = await Promise.race([
|
|
771
953
|
send(login, { command: "state" }),
|
|
772
|
-
|
|
954
|
+
delay(loginStateTimeout, null)
|
|
773
955
|
]);
|
|
774
956
|
if (!loginState) {
|
|
775
957
|
return stoppedAnswering;
|
|
@@ -795,7 +977,7 @@ var createLogin = (context) => {
|
|
|
795
977
|
};
|
|
796
978
|
|
|
797
979
|
// packages/agent/src/operations.ts
|
|
798
|
-
import {
|
|
980
|
+
import { requiresDownload, transferRollback } from "@tsplc/build";
|
|
799
981
|
var createOperations = (log) => {
|
|
800
982
|
let busy;
|
|
801
983
|
const requireIdle = () => {
|
|
@@ -815,7 +997,7 @@ var createOperations = (log) => {
|
|
|
815
997
|
busy = undefined;
|
|
816
998
|
}
|
|
817
999
|
},
|
|
818
|
-
stream: (operation, run) => {
|
|
1000
|
+
stream: (operation, run, { reportsRollback = false } = {}) => {
|
|
819
1001
|
requireIdle();
|
|
820
1002
|
busy = operation;
|
|
821
1003
|
const encoder = new TextEncoder;
|
|
@@ -835,10 +1017,12 @@ var createOperations = (log) => {
|
|
|
835
1017
|
emit({ kind: "done", result: await run(emit) });
|
|
836
1018
|
} catch (error) {
|
|
837
1019
|
log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1020
|
+
const rollback = reportsRollback ? transferRollback(error) : undefined;
|
|
838
1021
|
emit({
|
|
839
1022
|
kind: "error",
|
|
840
1023
|
message: errorMessage(error),
|
|
841
|
-
downloadRequired: error
|
|
1024
|
+
downloadRequired: requiresDownload(error),
|
|
1025
|
+
...rollback && { rollback }
|
|
842
1026
|
});
|
|
843
1027
|
} finally {
|
|
844
1028
|
clearInterval(heartbeat);
|
|
@@ -858,7 +1042,7 @@ var createOperations = (log) => {
|
|
|
858
1042
|
|
|
859
1043
|
// packages/agent/src/server-process.ts
|
|
860
1044
|
import { dirname as dirname3 } from "node:path";
|
|
861
|
-
import { setTimeout as
|
|
1045
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
862
1046
|
var healthyWithinMs = 60000;
|
|
863
1047
|
var settleMs = 5000;
|
|
864
1048
|
var restartDelayMs = 2000;
|
|
@@ -874,7 +1058,7 @@ var createServerSupervisor = (options) => {
|
|
|
874
1058
|
return;
|
|
875
1059
|
}
|
|
876
1060
|
options.log(`Server exited (${code}); restarting it in ${restartDelayMs / 1000} s`);
|
|
877
|
-
|
|
1061
|
+
delay2(restartDelayMs).then(() => {
|
|
878
1062
|
if (current?.process === child) {
|
|
879
1063
|
current = { executable, process: spawn(executable) };
|
|
880
1064
|
}
|
|
@@ -898,7 +1082,7 @@ var createServerSupervisor = (options) => {
|
|
|
898
1082
|
};
|
|
899
1083
|
const healthy = async (child) => {
|
|
900
1084
|
if (!options.healthUrl) {
|
|
901
|
-
await
|
|
1085
|
+
await delay2(settleMs);
|
|
902
1086
|
return child.exitCode === null;
|
|
903
1087
|
}
|
|
904
1088
|
const deadline = Date.now() + healthyWithinMs;
|
|
@@ -906,7 +1090,7 @@ var createServerSupervisor = (options) => {
|
|
|
906
1090
|
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
907
1091
|
return true;
|
|
908
1092
|
}
|
|
909
|
-
await
|
|
1093
|
+
await delay2(1000);
|
|
910
1094
|
}
|
|
911
1095
|
return false;
|
|
912
1096
|
};
|
|
@@ -940,9 +1124,9 @@ var createServerSupervisor = (options) => {
|
|
|
940
1124
|
|
|
941
1125
|
// packages/agent/src/state.ts
|
|
942
1126
|
import { existsSync as existsSync5 } from "node:fs";
|
|
943
|
-
import { mkdir as mkdir3, readFile as
|
|
1127
|
+
import { mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
|
|
944
1128
|
import { join as join6 } from "node:path";
|
|
945
|
-
var readJsonFile = async (path, schema) => existsSync5(path) ? schema.parse(JSON.parse(await
|
|
1129
|
+
var readJsonFile = async (path, schema) => existsSync5(path) ? schema.parse(JSON.parse(await readFile4(path, "utf8"))) : null;
|
|
946
1130
|
var writeJsonFile = (path, value) => writeFile3(path, JSON.stringify(value, null, 2));
|
|
947
1131
|
var openState = async (directory) => {
|
|
948
1132
|
const paths = {
|
|
@@ -999,9 +1183,12 @@ var createAgent = async (options) => {
|
|
|
999
1183
|
server.start(join7(state.paths.releases, deployed.server));
|
|
1000
1184
|
}
|
|
1001
1185
|
const operations = createOperations(log);
|
|
1186
|
+
const codesys = { bulkImport: options.bulkImport ?? false };
|
|
1187
|
+
const releases = createReleaseStore(state.paths.releases);
|
|
1002
1188
|
const login = createLogin({
|
|
1003
1189
|
state,
|
|
1004
1190
|
operations,
|
|
1191
|
+
codesys,
|
|
1005
1192
|
onAudit: (entry) => debugging.record(entry),
|
|
1006
1193
|
log
|
|
1007
1194
|
});
|
|
@@ -1009,11 +1196,13 @@ var createAgent = async (options) => {
|
|
|
1009
1196
|
state,
|
|
1010
1197
|
readLogin: login.read,
|
|
1011
1198
|
serverHealthUrl: options.serverHealthUrl,
|
|
1199
|
+
environment: options.environment ?? { ...process.env },
|
|
1012
1200
|
log
|
|
1013
1201
|
});
|
|
1014
1202
|
const deployments = createDeployments({
|
|
1015
1203
|
state,
|
|
1016
1204
|
operations,
|
|
1205
|
+
codesys,
|
|
1017
1206
|
server,
|
|
1018
1207
|
debugging,
|
|
1019
1208
|
log
|
|
@@ -1049,8 +1238,18 @@ var createAgent = async (options) => {
|
|
|
1049
1238
|
}
|
|
1050
1239
|
case "GET /variables":
|
|
1051
1240
|
return Response.json((await state.requireRelease()).manifest.variables);
|
|
1241
|
+
case "POST /releases/compare": {
|
|
1242
|
+
const { buckets } = compareRequestSchema.parse(await request.json());
|
|
1243
|
+
const comparison = await releases.compare(buckets, (await state.release())?.id ?? null);
|
|
1244
|
+
return new Response(Bun.gzipSync(JSON.stringify(comparison)), {
|
|
1245
|
+
headers: {
|
|
1246
|
+
"Content-Type": "application/json",
|
|
1247
|
+
"Content-Encoding": "gzip"
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1052
1251
|
case "POST /deploy":
|
|
1053
|
-
return deployments.deploy(
|
|
1252
|
+
return deployments.deploy(() => readDeployRequest(releases, request), clientIdentity(request), clientRelease(request));
|
|
1054
1253
|
case "POST /login":
|
|
1055
1254
|
return login.open(credentialsSchema.nullable().parse(await request.json()));
|
|
1056
1255
|
case "POST /login/command":
|
|
@@ -1061,40 +1260,50 @@ var createAgent = async (options) => {
|
|
|
1061
1260
|
return Response.json({ error: `No route ${key}` }, { status: 404 });
|
|
1062
1261
|
}
|
|
1063
1262
|
};
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1263
|
+
const respond = async (request) => {
|
|
1264
|
+
const { pathname, search, searchParams } = new URL(request.url);
|
|
1265
|
+
const debugPath = pathname.startsWith("/debug/");
|
|
1266
|
+
if (pathname === "/debug") {
|
|
1267
|
+
return new Response(null, {
|
|
1268
|
+
status: 308,
|
|
1269
|
+
headers: { Location: `/debug/${search}` }
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js")) {
|
|
1273
|
+
return debugging.handle(request, pathname.slice("/debug".length));
|
|
1274
|
+
}
|
|
1275
|
+
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (debugPath ? searchParams.get("token") : null) ?? "";
|
|
1276
|
+
const full = matches(presented, options.token);
|
|
1277
|
+
const read = options.readToken !== undefined && matches(presented, options.readToken) && (debugPath || request.method === "GET" && pathname === "/status");
|
|
1278
|
+
if (!full && !read) {
|
|
1279
|
+
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1280
|
+
}
|
|
1281
|
+
try {
|
|
1282
|
+
if (debugPath) {
|
|
1283
|
+
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
1076
1284
|
}
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1285
|
+
return await route(request);
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
if (error instanceof AgentError) {
|
|
1288
|
+
return Response.json({ error: error.message }, { status: error.status });
|
|
1082
1289
|
}
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
1086
|
-
}
|
|
1087
|
-
return await route(request);
|
|
1088
|
-
} catch (error) {
|
|
1089
|
-
if (error instanceof AgentError) {
|
|
1090
|
-
return Response.json({ error: error.message }, { status: error.status });
|
|
1091
|
-
}
|
|
1092
|
-
if (error instanceof z4.ZodError) {
|
|
1093
|
-
return Response.json({ error: z4.prettifyError(error) }, { status: 400 });
|
|
1094
|
-
}
|
|
1095
|
-
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1096
|
-
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
1290
|
+
if (error instanceof z3.ZodError) {
|
|
1291
|
+
return Response.json({ error: z3.prettifyError(error) }, { status: 400 });
|
|
1097
1292
|
}
|
|
1293
|
+
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1294
|
+
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
return {
|
|
1298
|
+
fetch: async (request) => {
|
|
1299
|
+
const response = await respond(request);
|
|
1300
|
+
const headers = new Headers(response.headers);
|
|
1301
|
+
headers.set(agentVersionHeader, tsplcVersion);
|
|
1302
|
+
return new Response(response.body, {
|
|
1303
|
+
status: response.status,
|
|
1304
|
+
statusText: response.statusText,
|
|
1305
|
+
headers
|
|
1306
|
+
});
|
|
1098
1307
|
},
|
|
1099
1308
|
stop: async () => {
|
|
1100
1309
|
await debugging.close();
|
|
@@ -1167,7 +1376,7 @@ var askCredentials = async () => ({
|
|
|
1167
1376
|
});
|
|
1168
1377
|
|
|
1169
1378
|
// packages/agent/src/cli.ts
|
|
1170
|
-
var usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [--server-health url]
|
|
1379
|
+
var usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [--server-health url] [--bulk-import]
|
|
1171
1380
|
tsplc-agent secrets set|delete <name> [--service ${agentService2}]
|
|
1172
1381
|
tsplc-agent secrets set-controller
|
|
1173
1382
|
|
|
@@ -1177,6 +1386,8 @@ serve Serves deployments and logins. --listen is required: use the machine's T
|
|
|
1177
1386
|
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
1178
1387
|
TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.
|
|
1179
1388
|
Each comes from its environment variable, or else from \`secrets set\` under ${agentService2}.
|
|
1389
|
+
--bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
|
|
1390
|
+
in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
|
|
1180
1391
|
secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
|
|
1181
1392
|
--service, or deletes it. set-controller stores the controller user, which deployments
|
|
1182
1393
|
and logins then use when they send none. Run it as the user the agent runs as.`;
|
|
@@ -1187,6 +1398,7 @@ var { values, positionals } = parseArgs({
|
|
|
1187
1398
|
listen: { type: "string" },
|
|
1188
1399
|
state: { type: "string" },
|
|
1189
1400
|
"server-health": { type: "string" },
|
|
1401
|
+
"bulk-import": { type: "boolean" },
|
|
1190
1402
|
service: { type: "string" }
|
|
1191
1403
|
}
|
|
1192
1404
|
});
|
|
@@ -1202,24 +1414,27 @@ if (command === "setup") {
|
|
|
1202
1414
|
await configureDocker();
|
|
1203
1415
|
await configureGateway();
|
|
1204
1416
|
} else if (command === "serve") {
|
|
1205
|
-
const [, hostname,
|
|
1206
|
-
|
|
1207
|
-
|
|
1417
|
+
const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
|
|
1418
|
+
const port = tcpPort2.safeParse(Number(portText));
|
|
1419
|
+
if (!hostname || !port.success) {
|
|
1420
|
+
throw new Error("--listen host:port is required, with a TCP port.");
|
|
1208
1421
|
}
|
|
1209
|
-
const token =
|
|
1422
|
+
const token = z4.string({
|
|
1210
1423
|
error: "Set TSPLC_AGENT_TOKEN, or store it with tsplc-agent secrets set TSPLC_AGENT_TOKEN"
|
|
1211
1424
|
}).min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters").parse(await agentSetting("TSPLC_AGENT_TOKEN"));
|
|
1212
|
-
const readToken =
|
|
1425
|
+
const readToken = z4.string().min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters").refine((value) => value !== token, "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN").optional().parse(await agentSetting("TSPLC_AGENT_READ_TOKEN"));
|
|
1213
1426
|
const agent = await createAgent({
|
|
1214
1427
|
state: values.state ?? join8(homedir(), ".tsplc-agent"),
|
|
1215
1428
|
token,
|
|
1216
1429
|
readToken,
|
|
1217
1430
|
serverHealthUrl: values["server-health"],
|
|
1431
|
+
bulkImport: values["bulk-import"] ?? false,
|
|
1432
|
+
environment: process.env,
|
|
1218
1433
|
log: (message) => console.log(`${new Date().toISOString()} ${message}`)
|
|
1219
1434
|
});
|
|
1220
1435
|
const server = Bun.serve({
|
|
1221
1436
|
hostname,
|
|
1222
|
-
port:
|
|
1437
|
+
port: port.data,
|
|
1223
1438
|
fetch: agent.fetch,
|
|
1224
1439
|
idleTimeout: 0,
|
|
1225
1440
|
maxRequestBodySize: 2 ** 30
|
|
@@ -1262,5 +1477,5 @@ if (command === "setup") {
|
|
|
1262
1477
|
throw new Error(`Unknown command ${command}.`);
|
|
1263
1478
|
}
|
|
1264
1479
|
|
|
1265
|
-
//# debugId=
|
|
1480
|
+
//# debugId=4C831D41846ACDFC64756E2164756E21
|
|
1266
1481
|
//# sourceMappingURL=cli.js.map
|