@tsplc/agent 0.2.13 → 0.2.16

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/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  // packages/agent/src/agent.ts
2
2
  import { execFile } from "node:child_process";
3
3
  import { timingSafeEqual } from "node:crypto";
4
- import { existsSync as existsSync2 } from "node:fs";
5
- import { mkdir as mkdir2, readdir, readFile as readFile2, stat, writeFile as writeFile2 } from "node:fs/promises";
4
+ import { existsSync as existsSync3 } from "node:fs";
5
+ import { mkdir as mkdir2, readdir, readFile as readFile3, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
6
6
  import { join as join2 } from "node:path";
7
7
  import { setTimeout as delay2 } from "node:timers/promises";
8
8
  import { promisify } from "node:util";
9
9
  import {
10
10
  explicitDownload,
11
+ failureReason,
11
12
  findControllerLogin,
12
13
  gatewayImage,
13
14
  loginCommandSchema,
@@ -16,6 +17,15 @@ import {
16
17
  startWarmController,
17
18
  updateWarmController
18
19
  } from "@tsplc/build";
20
+ import {
21
+ createDebugger,
22
+ createDebugHandler,
23
+ createLoginAdapter,
24
+ loadManifest,
25
+ LoginUnavailable,
26
+ noLogin,
27
+ timelineEntries
28
+ } from "@tsplc/debug";
19
29
  import { z as z3 } from "zod";
20
30
 
21
31
  // packages/agent/src/discovery.ts
@@ -68,6 +78,7 @@ var discoverControllers = async (network, port = runtimePort) => {
68
78
  };
69
79
 
70
80
  // packages/agent/src/protocol.ts
81
+ import { tsplcConfigSchema } from "@tsplc/config";
71
82
  import { z } from "zod";
72
83
  var targetSchema = z.strictObject({
73
84
  host: z.string().nonempty(),
@@ -91,7 +102,9 @@ var variableSchema = z.strictObject({ path: z.string(), type: z.string() });
91
102
  var releaseManifestSchema = z.strictObject({
92
103
  config: z.record(z.string(), z.unknown()),
93
104
  variables: z.array(variableSchema),
94
- server: z.string().nonempty().optional()
105
+ server: z.string().nonempty().optional(),
106
+ debug: tsplcConfigSchema.shape.debug,
107
+ serverTokenEnv: z.string().nonempty().optional()
95
108
  });
96
109
  var uploadEncoding = "gzip";
97
110
  var deployOptionsSchema = z.strictObject({
@@ -119,13 +132,70 @@ var statusSchema = z.strictObject({
119
132
  target: targetSchema.nullable(),
120
133
  release: releaseSchema.nullable(),
121
134
  server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
122
- login: z.strictObject({ state: z.string(), forced: z.array(z.string()) }).nullable()
135
+ login: z.union([
136
+ z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
137
+ z.strictObject({ error: z.string() })
138
+ ]).nullable()
139
+ });
140
+ var logoutSchema = z.strictObject({ failure: z.string().optional() });
141
+ var clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" };
142
+ var deploymentSchema = z.strictObject({
143
+ at: z.iso.datetime(),
144
+ release: z.string(),
145
+ build: z.string().optional(),
146
+ operation: z.enum(["download", "online-change"]),
147
+ user: z.string().optional(),
148
+ host: z.string().optional()
149
+ });
150
+ var auditSchema = z.strictObject({
151
+ at: z.iso.datetime(),
152
+ command: z.string(),
153
+ values: z.record(z.string(), z.string()),
154
+ previous: z.record(z.string(), z.string()).optional(),
155
+ user: z.string().optional(),
156
+ host: z.string().optional(),
157
+ release: z.string().optional(),
158
+ error: z.string().optional()
123
159
  });
124
160
 
161
+ // packages/agent/src/logs.ts
162
+ import { existsSync } from "node:fs";
163
+ import { open, readFile, rename, stat } from "node:fs/promises";
164
+ var rotateBytes = 5 * 2 ** 20;
165
+ var appendJsonl = async (file, value) => {
166
+ if (existsSync(file) && (await stat(file)).size >= rotateBytes)
167
+ await rename(file, `${file}.1`);
168
+ const log = await open(file, "a+");
169
+ try {
170
+ const { size } = await log.stat();
171
+ const last = Buffer.alloc(1);
172
+ if (size)
173
+ await log.read(last, 0, 1, size - 1);
174
+ const separator = size && last[0] !== 10 ? `
175
+ ` : "";
176
+ await log.writeFile(`${separator}${JSON.stringify(value)}
177
+ `);
178
+ } finally {
179
+ await log.close();
180
+ }
181
+ };
182
+ var readJsonl = async (file, schema, limit) => {
183
+ if (!existsSync(file))
184
+ return [];
185
+ return (await readFile(file, "utf8")).split(`
186
+ `).filter(Boolean).slice(-limit).flatMap((line) => {
187
+ try {
188
+ return [schema.parse(JSON.parse(line))];
189
+ } catch {
190
+ return [];
191
+ }
192
+ });
193
+ };
194
+
125
195
  // packages/agent/src/releases.ts
126
196
  import { createHash } from "node:crypto";
127
- import { existsSync } from "node:fs";
128
- import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
197
+ import { existsSync as existsSync2 } from "node:fs";
198
+ import { mkdir, mkdtemp, readFile as readFile2, rename as rename2, rm, writeFile } from "node:fs/promises";
129
199
  import { dirname, join, posix } from "node:path";
130
200
  import { z as z2 } from "zod";
131
201
  var filePrefix = "files/";
@@ -153,7 +223,7 @@ var saveRelease = async (releases, { manifest, files }) => {
153
223
  hash.update(file.path).update(createHash("sha256").update(file.content).digest("hex"));
154
224
  const id = hash.digest("hex").slice(0, 16);
155
225
  const directory = join(releases, id);
156
- if (!existsSync(directory)) {
226
+ if (!existsSync2(directory)) {
157
227
  await mkdir(releases, { recursive: true });
158
228
  const staging = await mkdtemp(join(releases, ".upload-"));
159
229
  try {
@@ -164,7 +234,7 @@ var saveRelease = async (releases, { manifest, files }) => {
164
234
  });
165
235
  }
166
236
  await writeFile(join(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
167
- await rename(staging, directory);
237
+ await rename2(staging, directory);
168
238
  } catch (cause) {
169
239
  await rm(staging, { recursive: true, force: true });
170
240
  throw cause;
@@ -174,7 +244,7 @@ var saveRelease = async (releases, { manifest, files }) => {
174
244
  };
175
245
  var loadRelease = async (releases, id) => {
176
246
  const directory = join(releases, id);
177
- const manifest = releaseManifestSchema.parse(JSON.parse(await readFile(join(directory, "manifest.json"), "utf8")));
247
+ const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(join(directory, "manifest.json"), "utf8")));
178
248
  return { id, directory, manifest };
179
249
  };
180
250
 
@@ -273,7 +343,40 @@ class AgentError extends Error {
273
343
  }
274
344
  }
275
345
  var json = (body, status = 200) => Response.json(body, { status });
276
- var readJson = async (path, schema) => existsSync2(path) ? schema.parse(JSON.parse(await readFile2(path, "utf8"))) : null;
346
+ var message = (error) => error instanceof Error ? error.message : String(error);
347
+ var loginStateTimeout = 30000;
348
+ var stoppedAnswering = { error: "The login stopped answering" };
349
+ var recentEntries = 500;
350
+ var clientOf = (request) => {
351
+ const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
352
+ return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
353
+ };
354
+ var auditOf = (command) => {
355
+ switch (command.command) {
356
+ case "write":
357
+ case "force":
358
+ return { command: command.command, values: command.values };
359
+ case "unforce":
360
+ return {
361
+ command: command.restore ? "unforce --restore" : "unforce",
362
+ values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
363
+ };
364
+ case "start":
365
+ case "stop":
366
+ return { command: command.command, values: {} };
367
+ case "reset":
368
+ return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
369
+ case "state":
370
+ case "read":
371
+ return;
372
+ }
373
+ };
374
+ var matches = (presented, token) => {
375
+ const actual = Buffer.from(presented);
376
+ const expected = Buffer.from(token);
377
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
378
+ };
379
+ var readJson = async (path, schema) => existsSync3(path) ? schema.parse(JSON.parse(await readFile3(path, "utf8"))) : null;
277
380
  var docker = (...args) => execute("docker", args).then(({ stdout }) => stdout.trim());
278
381
  var ensureNetwork = async (name, ...options) => {
279
382
  if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
@@ -309,16 +412,16 @@ var followProgress = (controller, emit) => {
309
412
  let offset = 0;
310
413
  while (following) {
311
414
  await delay2(2000);
312
- if (!log && existsSync2(jobs)) {
415
+ if (!log && existsSync3(jobs)) {
313
416
  for (const job of await readdir(jobs)) {
314
417
  const path = join2(jobs, job, ".codesys/controller/progress.log");
315
- if (existsSync2(path) && (await stat(path)).mtimeMs >= since)
418
+ if (existsSync3(path) && (await stat2(path)).mtimeMs >= since)
316
419
  log = path;
317
420
  }
318
421
  }
319
422
  if (!log)
320
423
  continue;
321
- const text = await readFile2(log, "utf8");
424
+ const text = await readFile3(log, "utf8");
322
425
  for (const line of text.slice(offset).split(`
323
426
  `).filter(Boolean))
324
427
  emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
@@ -335,7 +438,10 @@ var createAgent = async (options) => {
335
438
  releases: join2(options.state, "releases"),
336
439
  controller: join2(options.state, "controller"),
337
440
  release: join2(options.state, "release.json"),
338
- target: join2(options.state, "target.json")
441
+ target: join2(options.state, "target.json"),
442
+ deployments: join2(options.state, "deployments.jsonl"),
443
+ audit: join2(options.state, "audit.jsonl"),
444
+ debug: join2(options.state, "debug")
339
445
  };
340
446
  await mkdir2(options.state, { recursive: true });
341
447
  const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
@@ -372,6 +478,78 @@ var createAgent = async (options) => {
372
478
  })().catch((error) => {
373
479
  options.log(`Starting CODESYS failed: ${error instanceof Error ? error.message : String(error)}`);
374
480
  });
481
+ let loginGeneration = 0;
482
+ let commands = Promise.resolve();
483
+ const enqueue = (run) => {
484
+ const generation = loginGeneration;
485
+ const sent = commands.then(() => {
486
+ if (generation !== loginGeneration)
487
+ throw new AgentError("The login was closed", 409);
488
+ return run();
489
+ });
490
+ commands = sent.catch(() => {
491
+ return;
492
+ });
493
+ return sent;
494
+ };
495
+ const send = (login, loginCommand) => enqueue(() => login.send(loginCommand));
496
+ const readLogin = async ([first, ...rest]) => {
497
+ if (busy === "a login")
498
+ throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
499
+ if (busy)
500
+ throw new LoginUnavailable(`Live values pause during ${busy}`);
501
+ const login = await findControllerLogin(loginContainer);
502
+ if (!login)
503
+ throw new LoginUnavailable(noLogin);
504
+ if (!first)
505
+ return {};
506
+ const result = await send(login, { command: "read", expressions: [first, ...rest] });
507
+ if (!("values" in result))
508
+ throw new Error("The login answered a read without values");
509
+ return result.values;
510
+ };
511
+ const startDebugger = async () => {
512
+ const release = await readJson(paths.release, releaseSchema);
513
+ if (!release)
514
+ return null;
515
+ const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
516
+ const manifestFile = join2(directory, "debug.json");
517
+ if (!existsSync3(manifestFile))
518
+ return null;
519
+ const manifest = await loadManifest(manifestFile);
520
+ const serverToken = releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
521
+ const debug = await createDebugger({
522
+ manifest,
523
+ adapter: createLoginAdapter({
524
+ read: readLogin,
525
+ probe: manifest.build.target,
526
+ endpoint: "the agent's login"
527
+ }),
528
+ stateDirectory: paths.debug,
529
+ watch: releaseManifest.debug?.watch ?? {},
530
+ ...options.serverHealthUrl && serverToken && {
531
+ server: { url: new URL(options.serverHealthUrl).origin, token: serverToken }
532
+ },
533
+ release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
534
+ timeline: [
535
+ ...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
536
+ ...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
537
+ ],
538
+ log: options.log
539
+ });
540
+ return { debug, handle: createDebugHandler(debug, options.log) };
541
+ };
542
+ const debuggerFailed = (error) => {
543
+ options.log(`Starting the debugger failed: ${message(error)}`);
544
+ return null;
545
+ };
546
+ let debugging = startDebugger().catch(debuggerFailed);
547
+ const restartDebugger = () => {
548
+ debugging = debugging.then(async (current) => {
549
+ await current?.debug.close();
550
+ return startDebugger().catch(debuggerFailed);
551
+ });
552
+ };
375
553
  const operation = (name, run) => {
376
554
  if (busy)
377
555
  throw new AgentError(`The agent is busy with ${busy}`, 409);
@@ -409,7 +587,7 @@ var createAgent = async (options) => {
409
587
  }
410
588
  }), { headers: { "Content-Type": "application/x-ndjson" } });
411
589
  };
412
- const deploy = async (form) => {
590
+ const deploy = async (form, client) => {
413
591
  const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
414
592
  const upload = await readUpload(form);
415
593
  const target = await requireTarget();
@@ -418,7 +596,7 @@ var createAgent = async (options) => {
418
596
  return operation("a deployment", async (emit) => {
419
597
  const release = await saveRelease(paths.releases, upload);
420
598
  const config = controllerConfig(release, target);
421
- if (!settings.download && !existsSync2(join2(paths.controller, ".codesys/controller/current.json")))
599
+ if (!settings.download && !existsSync3(join2(paths.controller, ".codesys/controller/current.json")))
422
600
  throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, true);
423
601
  const previous = await readJson(paths.release, releaseSchema);
424
602
  const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
@@ -449,6 +627,16 @@ var createAgent = async (options) => {
449
627
  server: serverPath ?? previous?.server
450
628
  };
451
629
  await writeFile2(paths.release, JSON.stringify(deployedRelease, null, 2));
630
+ const debugManifest = join2(release.directory, "debug.json");
631
+ const deployment = {
632
+ at: deployedRelease.deployedAt,
633
+ release: release.id,
634
+ ...existsSync3(debugManifest) && { build: (await loadManifest(debugManifest)).build.id },
635
+ operation: kind,
636
+ ...client
637
+ };
638
+ await appendJsonl(paths.deployments, deployment);
639
+ restartDebugger();
452
640
  return deployedRelease;
453
641
  });
454
642
  };
@@ -461,25 +649,79 @@ var createAgent = async (options) => {
461
649
  emit({ kind: "progress", message: "Logging in; CODESYS takes minutes to start" });
462
650
  await ensureGateway();
463
651
  const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
464
- return login.send({ command: "state" });
652
+ return send(login, { command: "state" });
465
653
  });
466
654
  };
467
655
  const requireLogin = async () => {
656
+ if (busy)
657
+ throw new AgentError(`The agent is busy with ${busy}`, 409);
658
+ const generation = loginGeneration;
468
659
  const login = await findControllerLogin(loginContainer);
660
+ if (generation !== loginGeneration)
661
+ throw new AgentError("The login was closed", 409);
662
+ if (busy)
663
+ throw new AgentError(`The agent is busy with ${busy}`, 409);
469
664
  if (!login)
470
665
  throw new AgentError("No login is open: tsplc login", 409);
471
666
  return login;
472
667
  };
473
- const status = async () => {
668
+ const command = async (loginCommand, client) => {
669
+ const login = await requireLogin();
670
+ const change = auditOf(loginCommand);
671
+ if (!change)
672
+ return send(login, loginCommand);
673
+ return enqueue(async () => {
674
+ const [first, ...rest] = Object.keys(change.values);
675
+ const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
676
+ return;
677
+ }) : undefined;
678
+ const audit = async (error) => {
679
+ const entry = {
680
+ at: new Date().toISOString(),
681
+ ...change,
682
+ ...previous && { previous },
683
+ ...client,
684
+ release: (await readJson(paths.release, releaseSchema))?.id,
685
+ ...error !== undefined && { error: message(error) }
686
+ };
687
+ await appendJsonl(paths.audit, entry);
688
+ const { at, ...details } = entry;
689
+ (await debugging)?.debug.record(timelineEntries.audit(at, details));
690
+ };
691
+ try {
692
+ const result = await login.send(loginCommand);
693
+ await audit();
694
+ return result;
695
+ } catch (error) {
696
+ await audit(error);
697
+ throw error;
698
+ }
699
+ });
700
+ };
701
+ const loginStatus = async () => {
474
702
  const login = await findControllerLogin(loginContainer);
475
- const state = login && await login.ready() && await login.send({ command: "state" });
476
- return {
477
- target: await readJson(paths.target, targetSchema),
478
- release: await readJson(paths.release, releaseSchema),
479
- server: server.status() ?? null,
480
- login: state && "state" in state ? state : null
481
- };
703
+ if (!login)
704
+ return null;
705
+ if (!await login.ready())
706
+ return busy === "a login" ? null : stoppedAnswering;
707
+ try {
708
+ const state = await Promise.race([
709
+ send(login, { command: "state" }),
710
+ delay2(loginStateTimeout, null)
711
+ ]);
712
+ if (!state)
713
+ return stoppedAnswering;
714
+ return "state" in state ? state : null;
715
+ } catch (error) {
716
+ return { error: failureReason(error) };
717
+ }
482
718
  };
719
+ const status = async () => ({
720
+ target: await readJson(paths.target, targetSchema),
721
+ release: await readJson(paths.release, releaseSchema),
722
+ server: server.status() ?? null,
723
+ login: await loginStatus()
724
+ });
483
725
  const route = async (request) => {
484
726
  const { pathname } = new URL(request.url);
485
727
  const key = `${request.method} ${pathname}`;
@@ -503,25 +745,51 @@ var createAgent = async (options) => {
503
745
  case "GET /variables":
504
746
  return json((await currentRelease()).manifest.variables);
505
747
  case "POST /deploy":
506
- return deploy(await request.formData());
748
+ return deploy(await request.formData(), clientOf(request));
507
749
  case "POST /login":
508
750
  return openLogin(credentialsSchema.parse(await request.json()));
509
751
  case "POST /login/command":
510
- return json(await (await requireLogin()).send(loginCommandSchema.parse(await request.json())));
511
- case "DELETE /login":
512
- await (await requireLogin()).close();
513
- return json({});
752
+ return json(await command(loginCommandSchema.parse(await request.json()), clientOf(request)));
753
+ case "DELETE /login": {
754
+ const login = await requireLogin();
755
+ busy = "a logout";
756
+ loginGeneration++;
757
+ try {
758
+ const failure = await login.close();
759
+ commands = Promise.resolve();
760
+ if (failure)
761
+ options.log(`The login couldn't log out (${failure}); its container was removed`);
762
+ return json(failure ? { failure } : {});
763
+ } finally {
764
+ busy = undefined;
765
+ }
766
+ }
514
767
  default:
515
768
  return json({ error: `No route ${key}` }, 404);
516
769
  }
517
770
  };
518
- const expected = Buffer.from(`Bearer ${options.token}`);
771
+ const debugRoute = async (request, route) => {
772
+ const current = await debugging;
773
+ if (!current)
774
+ return json({ error: "The deployed release has no debug manifest, or the debugger failed to start" }, 503);
775
+ return current.handle(request, route);
776
+ };
519
777
  return {
520
778
  fetch: async (request) => {
521
- const actual = Buffer.from(request.headers.get("authorization") ?? "");
522
- if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
779
+ const { pathname, search, searchParams } = new URL(request.url);
780
+ const debugPath = pathname.startsWith("/debug/");
781
+ if (pathname === "/debug")
782
+ return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
783
+ if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
784
+ return debugRoute(request, pathname.slice("/debug".length));
785
+ const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (debugPath ? searchParams.get("token") : null) ?? "";
786
+ const full = matches(presented, options.token);
787
+ const read = options.readToken !== undefined && matches(presented, options.readToken) && (debugPath || request.method === "GET" && pathname === "/status");
788
+ if (!full && !read)
523
789
  return json({ error: "Unauthorized" }, 401);
524
790
  try {
791
+ if (debugPath)
792
+ return await debugRoute(request, pathname.slice("/debug".length));
525
793
  return await route(request);
526
794
  } catch (error) {
527
795
  if (error instanceof AgentError)
@@ -532,15 +800,22 @@ var createAgent = async (options) => {
532
800
  return json({ error: error instanceof Error ? error.message : String(error) }, 500);
533
801
  }
534
802
  },
535
- stop: () => server.stop()
803
+ stop: async () => {
804
+ await (await debugging)?.debug.close();
805
+ await server.stop();
806
+ }
536
807
  };
537
808
  };
538
809
  export {
810
+ auditSchema,
811
+ clientHeaders,
539
812
  controllerSchema,
540
813
  createAgent,
541
814
  credentialsSchema,
542
815
  deployOptionsSchema,
816
+ deploymentSchema,
543
817
  eventSchema,
818
+ logoutSchema,
544
819
  networkInterfaceSchema,
545
820
  releaseManifestSchema,
546
821
  releaseSchema,
@@ -550,5 +825,5 @@ export {
550
825
  variableSchema
551
826
  };
552
827
 
553
- //# debugId=792CE80FD19F96F164756E2164756E21
828
+ //# debugId=1614B96D4F00471464756E2164756E21
554
829
  //# sourceMappingURL=index.js.map