@tsplc/build 0.4.0 → 0.4.2

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.
@@ -10,6 +10,7 @@ import {
10
10
  import { z } from "zod";
11
11
  import {
12
12
  type ControllerCredentials,
13
+ type ControllerResult,
13
14
  controllerResultSchema,
14
15
  controllerTarget,
15
16
  DownloadRequiredError,
@@ -23,7 +24,7 @@ import {
23
24
  transferRollback,
24
25
  warmOperationSchema,
25
26
  } from "./controller-protocol";
26
- import { writeDeviceTree } from "./device-tree";
27
+ import { deviceTreeSettings, writeDeviceTree } from "./device-tree";
27
28
  import {
28
29
  createCodesysWorker,
29
30
  type PhasedBudget,
@@ -48,6 +49,8 @@ const pointerSchema = z.strictObject({
48
49
  const baselineSchema = controllerResultSchema.extend({
49
50
  objects: z.array(z.record(z.string(), z.unknown())),
50
51
  files: z.record(z.string(), sha256Digest),
52
+ // The device tree's adapter settings the download wrote, which an online change can't change.
53
+ deviceSettings: sha256Digest.optional(),
51
54
  });
52
55
  const sha256 = (data: Uint8Array) =>
53
56
  createHash("sha256").update(data).digest("hex");
@@ -197,6 +200,11 @@ interface OnlineWorker {
197
200
  run: (budget: PhasedBudget) => Promise<unknown>;
198
201
  /** A verified copy of baseline generation `baseline` in the scratch directory, which the worker has open. */
199
202
  prepared?: { baseline: string; generation: string };
203
+ /**
204
+ * Whether the worker outlives the operation, so it can reply once the controller runs the
205
+ * application and save the project, which waits for the downloaded reference, on a later request.
206
+ */
207
+ finishesLater: boolean;
200
208
  }
201
209
 
202
210
  /** A worker started for one operation and stopped after it. */
@@ -210,6 +218,7 @@ const oneShotWorker = (config: ResolvedConfig): OnlineWorker => {
210
218
  worker.request(await worker.launch(), { action: "online" }, budget),
211
219
  ),
212
220
  ),
221
+ finishesLater: false,
213
222
  };
214
223
  };
215
224
 
@@ -219,6 +228,17 @@ const restoreResultSchema = z.object({
219
228
  state: z.string(),
220
229
  });
221
230
 
231
+ interface SessionOptions {
232
+ imageId: string;
233
+ operationId: string;
234
+ scratch: string;
235
+ initializeUser?: boolean;
236
+ read?: string[];
237
+ credentials?: ControllerCredentials;
238
+ /** What an earlier operation left to report, which this one's progress starts with. */
239
+ notices?: string[];
240
+ }
241
+
222
242
  /**
223
243
  * Called inside the builder container, while its output-directory flock is held or, for a warm
224
244
  * `worker`, while the agent runs nothing else. Without `credentials`, CODESYS reads the controller
@@ -228,14 +248,23 @@ const restoreResultSchema = z.object({
228
248
  export const runControllerSession = async (
229
249
  config: ResolvedConfig,
230
250
  operation: "download" | "online-change" | "inspect",
231
- options: {
232
- imageId: string;
233
- operationId: string;
234
- scratch: string;
235
- initializeUser?: boolean;
236
- read?: string[];
237
- credentials?: ControllerCredentials;
238
- },
251
+ options: SessionOptions,
252
+ worker?: OnlineWorker,
253
+ ) => {
254
+ const session = await controllerSession(config, operation, options, worker);
255
+ await session.finish();
256
+ return session.receipt;
257
+ };
258
+
259
+ /**
260
+ * Runs an operation up to the receipt of a controller that runs its application. `finish` then
261
+ * commits the operation's project as the download baseline once CODESYS saved it, and cleans up;
262
+ * until it settles, nothing else may use the worker or the output directory's baseline.
263
+ */
264
+ const controllerSession = async (
265
+ config: ResolvedConfig,
266
+ operation: "download" | "online-change" | "inspect",
267
+ options: SessionOptions,
239
268
  worker?: OnlineWorker,
240
269
  ) => {
241
270
  const settings = config.online;
@@ -252,7 +281,7 @@ export const runControllerSession = async (
252
281
  const resultPath = resolve(root, "result.json");
253
282
  await rm(resultPath, { force: true });
254
283
  const templateHash = sha256(await readFile(config.template));
255
- // A different image, template, controller or device tree needs a fresh download from the template.
284
+ // A different image, template, controller or device tree structure needs a fresh download from the template.
256
285
  const target = controllerTarget(config, settings);
257
286
  const expected = { imageId: options.imageId, templateHash, target };
258
287
  const jobConfig = {
@@ -269,6 +298,9 @@ export const runControllerSession = async (
269
298
  progressLog,
270
299
  `${new Date().toISOString().replace(/\.\d+Z$/, "Z")} ${message}\n`,
271
300
  );
301
+ for (const notice of options.notices ?? []) {
302
+ progress(notice);
303
+ }
272
304
  const online = worker ?? oneShotWorker(jobConfig);
273
305
  const { requestDirectory } = online;
274
306
  await mkdir(requestDirectory, { recursive: true });
@@ -283,6 +315,16 @@ export const runControllerSession = async (
283
315
  throw error;
284
316
  },
285
317
  );
318
+ const deviceSettings =
319
+ config.deviceTree && deviceTreeSettings(config.deviceTree);
320
+ if (
321
+ operation === "online-change" &&
322
+ committed?.baseline.deviceSettings !== deviceSettings
323
+ ) {
324
+ throw new DownloadRequiredError(
325
+ `The device tree's adapter addresses or RPIs changed since the download; ${explicitDownload}`,
326
+ );
327
+ }
286
328
  const prepared =
287
329
  operation !== "inspect" &&
288
330
  committed &&
@@ -315,7 +357,6 @@ export const runControllerSession = async (
315
357
  const runRequest = async (request: Record<string, unknown>) => {
316
358
  await rm(resolve(requestDirectory, "result.json"), { force: true });
317
359
  await rm(phase, { force: true });
318
- await writeCredentials();
319
360
  await writeFile(
320
361
  resolve(requestDirectory, "request.json"),
321
362
  JSON.stringify(
@@ -324,9 +365,6 @@ export const runControllerSession = async (
324
365
  online: settings,
325
366
  progress: await windowsPath(progressLog),
326
367
  phase: await windowsPath(phase),
327
- ...(credentialsFile && {
328
- credentialsFile: await windowsPath(credentialsFile),
329
- }),
330
368
  },
331
369
  null,
332
370
  2,
@@ -337,6 +375,16 @@ export const runControllerSession = async (
337
375
  await readFile(resolve(requestDirectory, "result.json"), "utf8"),
338
376
  );
339
377
  };
378
+ /** Runs a request that logs in to the controller, with the controller user CODESYS reads once. */
379
+ const runConnected = async (request: Record<string, unknown>) => {
380
+ await writeCredentials();
381
+ return runRequest({
382
+ ...request,
383
+ ...(credentialsFile && {
384
+ credentialsFile: await windowsPath(credentialsFile),
385
+ }),
386
+ });
387
+ };
340
388
  /**
341
389
  * After a download failed mid-transfer, the controller may hold neither application. Downloads
342
390
  * the committed one again unless the controller still runs it, and describes the outcome. One
@@ -366,7 +414,7 @@ export const runControllerSession = async (
366
414
  );
367
415
  await copyCommitted(previous, resolve(restore, "project"));
368
416
  const restored = restoreResultSchema.parse(
369
- await runRequest({
417
+ await runConnected({
370
418
  operation: "restore",
371
419
  project: await windowsPath(
372
420
  resolve(restore, "project", "Application.project"),
@@ -399,6 +447,86 @@ export const runControllerSession = async (
399
447
  await rm(restore, { recursive: true, force: true });
400
448
  }
401
449
  };
450
+ /** Commits the candidate once CODESYS saved it with its downloaded reference, and writes the receipt. */
451
+ const commit = async (receipt: ControllerResult, objects: unknown) => {
452
+ if (operation !== "inspect") {
453
+ if (online.finishesLater) {
454
+ await runRequest({ operation: "finish" });
455
+ }
456
+ const committedDirectory = resolve(root, "generations", generation);
457
+ /** Keeps the candidate in the output directory, where it outlives the container. */
458
+ const retain = async (message: string) => {
459
+ await cp(candidateProject, resolve(committedDirectory, "project"), {
460
+ recursive: true,
461
+ });
462
+ return new Error(
463
+ `${message}; candidate is retained for recovery in ${committedDirectory}`,
464
+ );
465
+ };
466
+ const files = await projectFiles(candidateProject);
467
+ if (!Object.keys(files).some((name) => name.endsWith(".compileinfo"))) {
468
+ throw await retain(
469
+ "CODESYS acknowledged the operation but no downloaded compiler reference was saved",
470
+ );
471
+ }
472
+ const bootIds = Object.keys(files).filter((name) =>
473
+ name.endsWith(`.${receipt.applicationGuid}.bootinfo_guids`),
474
+ );
475
+ const expectedBootIds = Buffer.concat([
476
+ guidBytes(receipt.controllerIds.codeId),
477
+ guidBytes(receipt.controllerIds.dataId),
478
+ ]);
479
+ const bootReference = bootIds[0]?.replace(/_guids$/, "") ?? "";
480
+ const downloadedReference = bootReference.replace(
481
+ /\.bootinfo$/,
482
+ ".compileinfo",
483
+ );
484
+ if (
485
+ bootIds.length !== 1 ||
486
+ !files[bootReference] ||
487
+ files[bootReference] === sha256(new Uint8Array()) ||
488
+ files[bootReference] !== files[downloadedReference] ||
489
+ !(await readFile(resolve(candidateProject, bootIds[0] ?? ""))).equals(
490
+ expectedBootIds,
491
+ )
492
+ ) {
493
+ throw await retain(
494
+ "CODESYS acknowledged the operation but matching boot reference was not saved",
495
+ );
496
+ }
497
+ progress("Committing the downloaded project");
498
+ await rm(committedDirectory, { recursive: true, force: true });
499
+ await cp(candidateProject, resolve(committedDirectory, "project"), {
500
+ recursive: true,
501
+ });
502
+ await writeJson(resolve(committedDirectory, "manifest.json"), {
503
+ ...receipt,
504
+ objects,
505
+ files,
506
+ deviceSettings,
507
+ });
508
+ // Each generation is immutable. A single atomic pointer commits it only
509
+ // after controller acknowledgement and matching downloaded/boot references.
510
+ await writeJson(resolve(root, "current.json"), {
511
+ schemaVersion: 1,
512
+ generation,
513
+ });
514
+ }
515
+ await writeJson(resultPath, receipt);
516
+ };
517
+ /** Removes what only this operation used: CODESYS closed the candidate, and an opened project it didn't use. */
518
+ const cleanUp = async () => {
519
+ if (credentialsFile) {
520
+ await rm(credentialsFile, { force: true });
521
+ }
522
+ await rm(candidate, { recursive: true, force: true });
523
+ if (opened && opened !== prepared) {
524
+ await rm(resolve(options.scratch, "generations", opened.generation), {
525
+ recursive: true,
526
+ force: true,
527
+ });
528
+ }
529
+ };
402
530
  try {
403
531
  // Opens a copy of the baseline unless the worker opened one ahead; a download without one saves the template here.
404
532
  const previous =
@@ -431,12 +559,14 @@ export const runControllerSession = async (
431
559
  !previous && {
432
560
  template: await windowsPath(config.template),
433
561
  templateHash,
434
- // Kept across jobs: generating a device tree takes minutes, and the same inputs make the same one.
562
+ // Kept across jobs: generating a device tree takes minutes, and the same structure makes the same one.
435
563
  caches: await windowsPath(root),
436
- ...(config.deviceTree && {
437
- deviceTree: await writeDeviceTree(config.deviceTree, jobDirectory),
438
- devices: await windowsPath(jobDirectory),
439
- }),
564
+ }),
565
+ // Every tree an operation opens, generated or downloaded, takes this one's channel mappings.
566
+ ...(operation !== "inspect" &&
567
+ config.deviceTree && {
568
+ deviceTree: await writeDeviceTree(config.deviceTree, jobDirectory),
569
+ devices: await windowsPath(jobDirectory),
440
570
  }),
441
571
  ...(await importRequest(config, sources)),
442
572
  operation,
@@ -445,6 +575,7 @@ export const runControllerSession = async (
445
575
  project: await windowsPath(project),
446
576
  baseline,
447
577
  read: options.read ?? [],
578
+ finishLater: online.finishesLater,
448
579
  };
449
580
  const result = z
450
581
  .object({
@@ -455,7 +586,7 @@ export const runControllerSession = async (
455
586
  values: z.record(z.string(), z.string()),
456
587
  })
457
588
  .parse(
458
- await runRequest(request).catch(async (failure: unknown) => {
589
+ await runConnected(request).catch(async (failure: unknown) => {
459
590
  if (
460
591
  operation !== "download" ||
461
592
  (await workerPhase(phase)) !== "transfer"
@@ -476,79 +607,21 @@ export const runControllerSession = async (
476
607
  target,
477
608
  generation: operation === "inspect" ? baseline?.generation : generation,
478
609
  });
479
- if (operation !== "inspect") {
480
- const committedDirectory = resolve(root, "generations", generation);
481
- /** Keeps the candidate in the output directory, where it outlives the container. */
482
- const retain = async (message: string) => {
483
- await cp(candidateProject, resolve(committedDirectory, "project"), {
484
- recursive: true,
485
- });
486
- return new Error(
487
- `${message}; candidate is retained for recovery in ${committedDirectory}`,
488
- );
489
- };
490
- const files = await projectFiles(candidateProject);
491
- if (!Object.keys(files).some((name) => name.endsWith(".compileinfo"))) {
492
- throw await retain(
493
- "CODESYS acknowledged the operation but no downloaded compiler reference was saved",
494
- );
495
- }
496
- const bootIds = Object.keys(files).filter((name) =>
497
- name.endsWith(`.${receipt.applicationGuid}.bootinfo_guids`),
498
- );
499
- const expectedBootIds = Buffer.concat([
500
- guidBytes(receipt.controllerIds.codeId),
501
- guidBytes(receipt.controllerIds.dataId),
502
- ]);
503
- const bootReference = bootIds[0]?.replace(/_guids$/, "") ?? "";
504
- const downloadedReference = bootReference.replace(
505
- /\.bootinfo$/,
506
- ".compileinfo",
507
- );
508
- if (
509
- bootIds.length !== 1 ||
510
- !files[bootReference] ||
511
- files[bootReference] === sha256(new Uint8Array()) ||
512
- files[bootReference] !== files[downloadedReference] ||
513
- !(await readFile(resolve(candidateProject, bootIds[0] ?? ""))).equals(
514
- expectedBootIds,
515
- )
516
- ) {
517
- throw await retain(
518
- "CODESYS acknowledged the operation but matching boot reference was not saved",
519
- );
520
- }
521
- progress("Committing the downloaded project");
522
- await rm(committedDirectory, { recursive: true, force: true });
523
- await cp(candidateProject, resolve(committedDirectory, "project"), {
524
- recursive: true,
525
- });
526
- await writeJson(resolve(committedDirectory, "manifest.json"), {
527
- ...receipt,
528
- objects: sources?.objects,
529
- files,
530
- });
531
- // Each generation is immutable. A single atomic pointer commits it only
532
- // after controller acknowledgement and matching downloaded/boot references.
533
- await writeJson(resolve(root, "current.json"), {
534
- schemaVersion: 1,
535
- generation,
536
- });
537
- }
538
- await writeJson(resultPath, receipt);
539
- return receipt;
540
- } finally {
610
+ // Credentials are only for the controller; a later finish no longer needs them on disk.
541
611
  if (credentialsFile) {
542
612
  await rm(credentialsFile, { force: true });
543
613
  }
544
- // CODESYS closed the candidate, and an opened project this operation didn't use.
545
- await rm(candidate, { recursive: true, force: true });
546
- if (opened && opened !== prepared) {
547
- await rm(resolve(options.scratch, "generations", opened.generation), {
548
- recursive: true,
549
- force: true,
550
- });
551
- }
614
+ const finish = async () => {
615
+ try {
616
+ await commit(receipt, sources?.objects);
617
+ } finally {
618
+ await cleanUp();
619
+ }
620
+ };
621
+ return { receipt, finish };
622
+ } catch (error) {
623
+ await cleanUp();
624
+ throw error;
552
625
  }
553
626
  };
554
627
 
@@ -637,11 +710,65 @@ export const serveControllerLogin = async (
637
710
  );
638
711
  };
639
712
 
713
+ interface WarmOperation {
714
+ reply: Response;
715
+ /** Commits the operation's project, once the controller runs it. */
716
+ finish: (() => Promise<void>) | undefined;
717
+ }
718
+
719
+ /**
720
+ * How a warm container answers: a POST runs one operation, answered once the controller runs the
721
+ * application, and its `finish` runs after the reply; the next POST waits for it and for the next
722
+ * project opened ahead. A GET reports whether a finish still runs. A finish that fails leaves the
723
+ * download before it as the baseline while the controller runs the reported application, so the
724
+ * next online change finds the two differ and asks for a full download; the next operation
725
+ * reports why first.
726
+ */
727
+ export const warmRequests = (handlers: {
728
+ alive: () => boolean;
729
+ operate: (request: Request, notices: string[]) => Promise<WarmOperation>;
730
+ prepareNext: () => Promise<void>;
731
+ }) => {
732
+ const finishing = { now: false };
733
+ const notices: string[] = [];
734
+ const finishThenPrepare = async (finish: WarmOperation["finish"]) => {
735
+ if (finish) {
736
+ finishing.now = true;
737
+ await finish().catch((error: unknown) => {
738
+ const message = `Committing the last deployment's project failed, so the download baseline is still the one before it: ${failureReason(error)}`;
739
+ console.error(message);
740
+ notices.push(message);
741
+ });
742
+ finishing.now = false;
743
+ }
744
+ await handlers.prepareNext();
745
+ };
746
+ const queue = { preparing: handlers.prepareNext() };
747
+ return async (request: Request) => {
748
+ if (request.method === "GET") {
749
+ return Response.json(
750
+ handlers.alive()
751
+ ? { ok: true, result: { finishing: finishing.now } }
752
+ : { ok: false, error: "CODESYS exited" },
753
+ );
754
+ }
755
+ await queue.preparing;
756
+ const { reply, finish } = await handlers.operate(
757
+ request,
758
+ notices.splice(0),
759
+ );
760
+ queue.preparing = finishThenPrepare(finish);
761
+ return reply;
762
+ };
763
+ };
764
+
640
765
  /**
641
766
  * Called inside the builder container: keeps one CODESYS worker running and serves downloads and
642
- * online changes on `port`, so each skips starting the container and CODESYS. Each
643
- * POST names its own config, written for that release. The agent runs one operation at a time, and
644
- * none while a login is open, so this container doesn't hold the output directory's flock.
767
+ * online changes on `port`, so each skips starting the container and CODESYS. Each POST names its
768
+ * own config, written for that release, and is answered once the controller runs the application;
769
+ * its project is committed after, before the next operation starts. A GET reports whether that
770
+ * commit still runs, which `settleWarmController` waits for. The agent runs one operation at a
771
+ * time, and none while a login is open, so this container doesn't hold the output directory's flock.
645
772
  */
646
773
  export const serveWarmController = async (
647
774
  config: ResolvedConfig,
@@ -672,6 +799,7 @@ export const serveWarmController = async (
672
799
  requestDirectory: controllerDirectory(warmConfig.outDir),
673
800
  run: async (budget) =>
674
801
  worker.request(await running(), { action: "online" }, budget),
802
+ finishesLater: true,
675
803
  };
676
804
  /** Opens a verified copy of the committed baseline, so the next operation needn't copy and open one. */
677
805
  const prepare = async () => {
@@ -707,61 +835,65 @@ export const serveWarmController = async (
707
835
  `Could not open the next project ahead: ${failureReason(error)}`,
708
836
  );
709
837
  });
710
- let preparing = prepareNext();
711
- Bun.serve({
712
- hostname: "127.0.0.1",
713
- port: options.port,
714
- idleTimeout: 0,
715
- fetch: async (request) => {
716
- if (request.method === "GET") {
717
- return Response.json(
838
+ /** Runs one posted operation: its reply, and once the controller runs it, how to commit it. */
839
+ const operate = async (request: Request, notices: string[]) => {
840
+ try {
841
+ const body = warmOperationSchema.parse(await request.json());
842
+ const reported = await controllerSession(
843
+ await options.loadConfig(body.request),
844
+ body.operation,
845
+ {
846
+ imageId: options.imageId,
847
+ operationId: body.operationId,
848
+ scratch: containerScratch,
849
+ initializeUser: body.initializeUser,
850
+ credentials: body.credentials,
851
+ notices,
852
+ },
853
+ online,
854
+ ).catch((error: unknown) => {
855
+ // CODESYS crashes generating an online change that moves a block holding a network
856
+ // client, such as a job with a service call. The controller keeps its running program.
857
+ if (
858
+ body.operation !== "online-change" ||
718
859
  worker.alive(session.current)
719
- ? { ok: true }
720
- : { ok: false, error: "CODESYS exited" },
860
+ ) {
861
+ throw error;
862
+ }
863
+ throw new DownloadRequiredError(
864
+ `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
865
+ { cause: error },
721
866
  );
722
- }
723
- await preparing;
724
- try {
725
- const body = warmOperationSchema.parse(await request.json());
726
- const result = await runControllerSession(
727
- await options.loadConfig(body.request),
728
- body.operation,
729
- {
730
- imageId: options.imageId,
731
- operationId: body.operationId,
732
- scratch: containerScratch,
733
- initializeUser: body.initializeUser,
734
- credentials: body.credentials,
735
- },
736
- online,
737
- ).catch((error: unknown) => {
738
- // CODESYS crashes generating an online change that moves a block holding a network
739
- // client, such as a job with a service call. The controller keeps its running program.
740
- if (
741
- body.operation !== "online-change" ||
742
- worker.alive(session.current)
743
- ) {
744
- throw error;
745
- }
746
- throw new DownloadRequiredError(
747
- `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
748
- { cause: error },
749
- );
750
- });
751
- return Response.json({ ok: true, result });
752
- } catch (error) {
753
- const rollback = transferRollback(error);
754
- return Response.json({
867
+ });
868
+ return {
869
+ reply: Response.json({ ok: true, result: reported.receipt }),
870
+ finish: reported.finish,
871
+ };
872
+ } catch (error) {
873
+ const rollback = transferRollback(error);
874
+ return {
875
+ reply: Response.json({
755
876
  ok: false,
756
877
  error: failureReason(error),
757
878
  ...(requiresDownload(error) && { downloadRequired: true }),
758
879
  ...(rollback && { rollback }),
759
- });
760
- } finally {
880
+ }),
881
+ finish: undefined,
882
+ };
883
+ }
884
+ };
885
+ Bun.serve({
886
+ hostname: "127.0.0.1",
887
+ port: options.port,
888
+ idleTimeout: 0,
889
+ fetch: warmRequests({
890
+ alive: () => worker.alive(session.current),
891
+ operate,
892
+ prepareNext: async () => {
761
893
  online.prepared = undefined;
762
- preparing = prepareNext();
763
- }
764
- },
894
+ await prepareNext();
895
+ },
896
+ }),
765
897
  });
766
898
  // Serves until the container stops; the next one clears what this one leaves behind.
767
899
  await new Promise(() => {});
@@ -4,24 +4,64 @@ import { resolve } from "node:path";
4
4
  import type { ResolvedConfig } from "@tsplc/config/build";
5
5
  import { buildFiles } from "./artifacts";
6
6
 
7
+ type DeviceTree = NonNullable<ResolvedConfig["deviceTree"]>;
8
+
9
+ const sha256 = (text: string) =>
10
+ createHash("sha256").update(text).digest("hex");
11
+
12
+ /**
13
+ * The digest of what generating `tree` builds into a project, which keys the cached generated tree
14
+ * and the target a download binds the controller to. It leaves out what the worker writes into a
15
+ * generated tree it opens: the channels' mappings and comments, and the values of the adapter
16
+ * settings in `deviceTreeSettings`. Whether an adapter has each setting counts, since a generated
17
+ * one can't be put back to its EDS default. Everything else counts, including fields added later,
18
+ * so a change the worker can't make in place always generates a new tree.
19
+ */
20
+ export const deviceTreeStructure = (tree: DeviceTree) => {
21
+ const { mappings: _mappings, ...structure } = tree;
22
+ return sha256(
23
+ JSON.stringify({
24
+ ...structure,
25
+ devices: structure.devices.map(
26
+ ({ comments: _comments, address, rpiMicroseconds, ...device }) => ({
27
+ ...device,
28
+ address: address !== undefined,
29
+ rpiMicroseconds: rpiMicroseconds !== undefined,
30
+ }),
31
+ ),
32
+ }),
33
+ );
34
+ };
35
+
36
+ /**
37
+ * The digest of the adapter settings the worker writes into a generated tree in place: each
38
+ * adapter's address, which its Modbus server shares, and its RPI. A download takes them. An online
39
+ * change doesn't: nothing shows that the scanner reconnects an adapter whose settings changed
40
+ * without restarting the application, so it could keep running on the old ones.
41
+ */
42
+ export const deviceTreeSettings = (tree: DeviceTree) =>
43
+ sha256(
44
+ JSON.stringify(
45
+ tree.devices.map(({ name, address, rpiMicroseconds }) => ({
46
+ name,
47
+ address,
48
+ rpiMicroseconds,
49
+ })),
50
+ ),
51
+ );
52
+
7
53
  /** Writes each adapter's EDS into `directory`, where CODESYS imports it, and returns the tree the worker reads. */
8
- export const writeDeviceTree = async (
9
- deviceTree: NonNullable<ResolvedConfig["deviceTree"]>,
10
- directory: string,
11
- ) => {
54
+ export const writeDeviceTree = async (tree: DeviceTree, directory: string) => {
12
55
  await mkdir(resolve(directory, buildFiles.devices), { recursive: true });
13
56
  return {
14
- ...deviceTree,
57
+ ...tree,
58
+ structure: deviceTreeStructure(tree),
15
59
  devices: await Promise.all(
16
- deviceTree.devices.map(async (device) => {
60
+ tree.devices.map(async (device) => {
17
61
  const eds = `${buildFiles.devices}/${device.name}.eds`;
18
62
  await writeFile(resolve(directory, eds), device.eds);
19
- // The digest keys project reuse on the description's content.
20
- return {
21
- ...device,
22
- eds,
23
- sha256: createHash("sha256").update(device.eds).digest("hex"),
24
- };
63
+ // The digest keys a build's reuse of its last project on the description's content.
64
+ return { ...device, eds, sha256: sha256(device.eds) };
25
65
  }),
26
66
  ),
27
67
  };
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ export {
14
14
  findControllerLogin,
15
15
  inspectController,
16
16
  openControllerLogin,
17
+ settleWarmController,
17
18
  startWarmController,
18
19
  updateController,
19
20
  updateWarmController,