@tsplc/build 0.5.9 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,10 @@ import {
18
18
  explicitDownload,
19
19
  failureReason,
20
20
  loginCommandSchema,
21
+ type ResetKind,
21
22
  requiresDownload,
23
+ type restartReplySchema,
24
+ type reviewReplySchema,
22
25
  sameBaseline,
23
26
  TransferFailedError,
24
27
  tracebackFailure,
@@ -41,6 +44,7 @@ import {
41
44
  type CommittedObject,
42
45
  committedObjectSchema,
43
46
  describeFinding,
47
+ type OnlineChangeFinding,
44
48
  onlineChangeFindings,
45
49
  } from "./online-change-check";
46
50
  import { loadSources } from "./sources";
@@ -216,7 +220,7 @@ const crashedOnlineChange = (cause: unknown) =>
216
220
 
217
221
  /**
218
222
  * Refuses, before CODESYS runs, an online change CODESYS would refuse or apply wrongly, naming
219
- * the variable or task that causes it; reports the state the change restarts.
223
+ * the variable or task that causes it; reports the state the change restarts, and returns it.
220
224
  */
221
225
  const checkOnlineChange = (
222
226
  baseline: z.infer<typeof baselineSchema>,
@@ -233,11 +237,13 @@ const checkOnlineChange = (
233
237
  if (refusals.length) {
234
238
  throw new DownloadRequiredError(
235
239
  `This change can't be applied as an online change; ${explicitDownload}:\n${refusals.map(describeFinding).join("\n")}`,
240
+ { findings },
236
241
  );
237
242
  }
238
243
  for (const finding of findings) {
239
244
  progress(`Online change: ${describeFinding(finding)}`);
240
245
  }
246
+ return findings;
241
247
  };
242
248
 
243
249
  /** A CODESYS worker that handles the `online` request written to `requestDirectory` when `run`. */
@@ -287,6 +293,9 @@ interface SessionOptions {
287
293
  notices?: string[];
288
294
  }
289
295
 
296
+ /** An operation that ends in a receipt, and a review, which ends in tsPLC's findings. */
297
+ type SessionOperation = "download" | "online-change" | "inspect" | "review";
298
+
290
299
  /**
291
300
  * Called inside the builder container, while its output-directory flock is held or, for a warm
292
301
  * `worker`, while the agent runs nothing else. Without `credentials`, CODESYS reads the controller
@@ -295,30 +304,67 @@ interface SessionOptions {
295
304
  */
296
305
  export const runControllerSession = async (
297
306
  config: ResolvedConfig,
298
- operation: "download" | "online-change" | "inspect",
307
+ operation: Exclude<SessionOperation, "review">,
299
308
  options: SessionOptions,
300
309
  worker?: OnlineWorker,
301
310
  ) => {
302
- const session = await controllerSession(config, operation, options, worker);
311
+ const session = await receiptSession(config, operation, options, worker);
303
312
  await session.finish();
304
313
  return session.receipt;
305
314
  };
306
315
 
316
+ /** A session of an operation that ends in a receipt. */
317
+ const receiptSession = async (
318
+ config: ResolvedConfig,
319
+ operation: Exclude<SessionOperation, "review">,
320
+ options: SessionOptions,
321
+ worker?: OnlineWorker,
322
+ ) => {
323
+ const session = await controllerSession(config, operation, options, worker);
324
+ if (!("receipt" in session)) {
325
+ throw new Error(`The ${operation} ended without a receipt`);
326
+ }
327
+ return session;
328
+ };
329
+
330
+ /**
331
+ * Called inside the builder container like `runControllerSession`: goes an online change's way up
332
+ * to CODESYS's verdict on it, and returns tsPLC's findings. Refuses as the online change would,
333
+ * with a `DownloadRequiredError`; transfers, saves and commits nothing.
334
+ */
335
+ export const reviewControllerSession = async (
336
+ config: ResolvedConfig,
337
+ options: SessionOptions,
338
+ worker?: OnlineWorker,
339
+ ): Promise<OnlineChangeFinding[]> => {
340
+ const session = await controllerSession(config, "review", options, worker);
341
+ if (!("findings" in session)) {
342
+ throw new Error("The review ended with a receipt");
343
+ }
344
+ return session.findings;
345
+ };
346
+
307
347
  /**
308
348
  * Runs an operation up to the receipt of a controller that runs its application. `finish` then
309
349
  * commits the operation's project as the download baseline once CODESYS saved it, and cleans up;
310
- * until it settles, nothing else may use the worker or the output directory's baseline.
350
+ * until it settles, nothing else may use the worker or the output directory's baseline. A review
351
+ * ends at CODESYS's verdict, with tsPLC's findings, and cleans up at once.
311
352
  */
312
353
  const controllerSession = async (
313
354
  config: ResolvedConfig,
314
- operation: "download" | "online-change" | "inspect",
355
+ operation: SessionOperation,
315
356
  options: SessionOptions,
316
357
  worker?: OnlineWorker,
317
- ) => {
358
+ ): Promise<
359
+ | { receipt: ControllerResult; finish: () => Promise<void> }
360
+ | { findings: OnlineChangeFinding[] }
361
+ > => {
318
362
  const settings = config.online;
319
363
  if (!settings) {
320
364
  throw new Error("Controller operations require online settings");
321
365
  }
366
+ // A review checks everything an online change would, up to applying it.
367
+ const onlineChange = operation === "online-change" || operation === "review";
322
368
  if (options.initializeUser && operation !== "download") {
323
369
  throw new DownloadRequiredError(
324
370
  "Initial user creation requires an explicit download",
@@ -370,10 +416,7 @@ const controllerSession = async (
370
416
  );
371
417
  const deviceSettings =
372
418
  config.deviceTree && deviceTreeSettings(config.deviceTree);
373
- if (
374
- operation === "online-change" &&
375
- committed?.baseline.deviceSettings !== deviceSettings
376
- ) {
419
+ if (onlineChange && committed?.baseline.deviceSettings !== deviceSettings) {
377
420
  throw new DownloadRequiredError(
378
421
  `The device tree's adapter addresses or RPIs changed since the download; ${explicitDownload}`,
379
422
  );
@@ -606,9 +649,10 @@ const controllerSession = async (
606
649
  const baseline = previous?.baseline;
607
650
  progress("Loading the program's sources");
608
651
  const sources = operation === "inspect" ? null : await loadSources(config);
609
- if (operation === "online-change" && baseline && sources) {
610
- checkOnlineChange(baseline, sources.objects, config, progress);
611
- }
652
+ const findings =
653
+ onlineChange && baseline && sources
654
+ ? checkOnlineChange(baseline, sources.objects, config, progress)
655
+ : [];
612
656
  const request = {
613
657
  libraryReferences: config.libraryReferences,
614
658
  // Only a download without a baseline starts from the template; the others keep the downloaded project's tree.
@@ -634,6 +678,36 @@ const controllerSession = async (
634
678
  read: options.read ?? [],
635
679
  finishLater: online.finishesLater,
636
680
  };
681
+ const reply = await runConnected(request).catch(
682
+ async (failure: unknown) => {
683
+ if (
684
+ operation === "online-change" &&
685
+ failure instanceof CodesysExitedError
686
+ ) {
687
+ throw crashedOnlineChange(failure);
688
+ }
689
+ // CODESYS's refusal carries its reasons; tsPLC's findings join them.
690
+ if (onlineChange && failure instanceof DownloadRequiredError) {
691
+ throw new DownloadRequiredError(failure.message, {
692
+ cause: failure,
693
+ findings,
694
+ messages: failure.messages,
695
+ });
696
+ }
697
+ if (
698
+ operation !== "download" ||
699
+ (await workerPhase(phase)) !== "transfer"
700
+ ) {
701
+ throw failure;
702
+ }
703
+ throw await rollBack(failure);
704
+ },
705
+ );
706
+ if (operation === "review") {
707
+ z.strictObject({}).parse(reply);
708
+ await cleanUp();
709
+ return { findings };
710
+ }
637
711
  const result = z
638
712
  .object({
639
713
  applicationGuid: guid,
@@ -642,23 +716,7 @@ const controllerSession = async (
642
716
  state: z.string(),
643
717
  values: z.record(z.string(), z.string()),
644
718
  })
645
- .parse(
646
- await runConnected(request).catch(async (failure: unknown) => {
647
- if (
648
- operation === "online-change" &&
649
- failure instanceof CodesysExitedError
650
- ) {
651
- throw crashedOnlineChange(failure);
652
- }
653
- if (
654
- operation !== "download" ||
655
- (await workerPhase(phase)) !== "transfer"
656
- ) {
657
- throw failure;
658
- }
659
- throw await rollBack(failure);
660
- }),
661
- );
719
+ .parse(reply);
662
720
  const receipt = controllerResultSchema.parse({
663
721
  ...result,
664
722
  application: result.application ?? baseline?.application,
@@ -689,6 +747,30 @@ const controllerSession = async (
689
747
  }
690
748
  };
691
749
 
750
+ /**
751
+ * The worker's command that logs in to the running application from a copy of the committed
752
+ * download in `directory`: CODESYS writes into an open project, and the baseline must not change.
753
+ */
754
+ const openLoginCommand = async (
755
+ config: ResolvedConfig,
756
+ committed: Committed,
757
+ options: { directory: string; credentialsFile: string | null },
758
+ ) => {
759
+ const project = resolve(options.directory, "project");
760
+ await copyCommitted(committed, project);
761
+ const windowsPath = (path: string) =>
762
+ toWindowsPath(path, config.codesys.wine);
763
+ return {
764
+ command: "open",
765
+ project: await windowsPath(resolve(project, "Application.project")),
766
+ online: config.online,
767
+ baseline: committed.baseline,
768
+ ...(options.credentialsFile && {
769
+ credentialsFile: await windowsPath(options.credentialsFile),
770
+ }),
771
+ };
772
+ };
773
+
692
774
  /**
693
775
  * Called inside the builder container: holds one login to the running application, made
694
776
  * from the committed baseline, and serves its commands on `port` until a DELETE closes it.
@@ -707,11 +789,8 @@ export const serveControllerLogin = async (
707
789
  templateHash: sha256(await readFile(config.template)),
708
790
  target: controllerTarget(config, config.online),
709
791
  });
710
- const { baseline } = committed;
711
792
  const jobConfig = { ...config, outDir: resolve(root, "login") };
712
793
  await rm(jobConfig.outDir, { recursive: true, force: true });
713
- // CODESYS writes into an open project, and the committed baseline must not change.
714
- await copyCommitted(committed, resolve(jobConfig.outDir, "project"));
715
794
  const worker = createCodesysWorker(jobConfig);
716
795
  await withWorkerShutdown(jobConfig, worker, () =>
717
796
  withWorkerLock(jobConfig, async () => {
@@ -722,15 +801,12 @@ export const serveControllerLogin = async (
722
801
  { action: "login", arguments: command },
723
802
  config.timeouts.build,
724
803
  );
725
- await send({
726
- command: "open",
727
- project: await toWindowsPath(
728
- resolve(jobConfig.outDir, "project", "Application.project"),
729
- config.codesys.wine,
730
- ),
731
- online: config.online,
732
- baseline,
733
- });
804
+ await send(
805
+ await openLoginCommand(config, committed, {
806
+ directory: jobConfig.outDir,
807
+ credentialsFile: null,
808
+ }),
809
+ );
734
810
  const closed = Promise.withResolvers<void>();
735
811
  // The worker has one mailbox, so commands run one at a time.
736
812
  let previous: Promise<unknown> = Promise.resolve();
@@ -775,6 +851,63 @@ export const serveControllerLogin = async (
775
851
  );
776
852
  };
777
853
 
854
+ /**
855
+ * Resets the application the committed download put on the controller, warm or cold, and starts
856
+ * it again, through a login the warm worker opens from that download and closes after, so no
857
+ * engineering login has to be open. Its code stays as it is. Returns the state it runs in.
858
+ */
859
+ const restartController = async (
860
+ config: ResolvedConfig,
861
+ options: Pick<
862
+ SessionOptions,
863
+ "imageId" | "engineering" | "operationId" | "scratch" | "credentials"
864
+ > & { reset: ResetKind },
865
+ send: (command: Record<string, unknown>) => Promise<unknown>,
866
+ ) => {
867
+ if (!config.online) {
868
+ throw new Error("Controller operations require online settings");
869
+ }
870
+ const committed = await committedBaseline(
871
+ controllerDirectory(config.outDir),
872
+ {
873
+ imageId: options.imageId,
874
+ engineering: options.engineering ?? undefined,
875
+ templateHash: sha256(await readFile(config.template)),
876
+ target: controllerTarget(config, config.online),
877
+ },
878
+ );
879
+ const directory = resolve(options.scratch, "restart", options.operationId);
880
+ // Only this container reads it; the worker deletes it once CODESYS has the user.
881
+ const credentialsFile = options.credentials
882
+ ? `/tmp/tsplc-credentials-${options.operationId}.json`
883
+ : null;
884
+ try {
885
+ if (credentialsFile) {
886
+ await writeFile(credentialsFile, JSON.stringify(options.credentials), {
887
+ mode: 0o600,
888
+ });
889
+ }
890
+ await send(
891
+ await openLoginCommand(config, committed, { directory, credentialsFile }),
892
+ );
893
+ try {
894
+ await send({ command: "reset", kind: options.reset });
895
+ await send({ command: "start" });
896
+ const { state } = z
897
+ .object({ state: z.string() })
898
+ .parse(await send({ command: "state" }));
899
+ return state;
900
+ } finally {
901
+ await send({ command: "close" });
902
+ }
903
+ } finally {
904
+ if (credentialsFile) {
905
+ await rm(credentialsFile, { force: true });
906
+ }
907
+ await rm(directory, { recursive: true, force: true });
908
+ }
909
+ };
910
+
778
911
  interface WarmOperation {
779
912
  reply: Response;
780
913
  /** Commits the operation's project, once the controller runs it. */
@@ -828,8 +961,8 @@ export const warmRequests = (handlers: {
828
961
  };
829
962
 
830
963
  /**
831
- * Called inside the builder container: keeps one CODESYS worker running and serves downloads and
832
- * online changes on `port`, so each skips starting the container and CODESYS. Each POST names its
964
+ * Called inside the builder container: keeps one CODESYS worker running and serves downloads,
965
+ * online changes, reviews and restarts on `port`, so each skips starting the container and CODESYS. Each POST names its
833
966
  * own config, written for that release, and is answered once the controller runs the application;
834
967
  * its project is committed after, before the next operation starts. A GET reports whether that
835
968
  * commit still runs, which `settleWarmController` waits for. The agent runs one operation at a
@@ -905,18 +1038,60 @@ export const serveWarmController = async (
905
1038
  const operate = async (request: Request, notices: string[]) => {
906
1039
  try {
907
1040
  const body = warmOperationSchema.parse(await request.json());
908
- const reported = await controllerSession(
909
- await options.loadConfig(body.request),
1041
+ const operationConfig = await options.loadConfig(body.request);
1042
+ if (body.operation === "restart") {
1043
+ const state = await restartController(
1044
+ operationConfig,
1045
+ {
1046
+ imageId: options.imageId,
1047
+ engineering: options.engineering,
1048
+ operationId: body.operationId,
1049
+ scratch: containerScratch,
1050
+ credentials: body.credentials,
1051
+ reset: body.reset,
1052
+ },
1053
+ async (command) =>
1054
+ worker.request(
1055
+ await running(),
1056
+ { action: "login", arguments: command },
1057
+ operationConfig.timeouts.build,
1058
+ ),
1059
+ );
1060
+ return {
1061
+ reply: Response.json({
1062
+ ok: true,
1063
+ result: { state } satisfies z.input<typeof restartReplySchema>,
1064
+ }),
1065
+ finish: undefined,
1066
+ };
1067
+ }
1068
+ const sessionOptions: SessionOptions = {
1069
+ imageId: options.imageId,
1070
+ engineering: options.engineering,
1071
+ operationId: body.operationId,
1072
+ scratch: containerScratch,
1073
+ initializeUser: body.initializeUser,
1074
+ credentials: body.credentials,
1075
+ notices,
1076
+ };
1077
+ if (body.operation === "review") {
1078
+ const findings = await reviewControllerSession(
1079
+ operationConfig,
1080
+ sessionOptions,
1081
+ online,
1082
+ );
1083
+ return {
1084
+ reply: Response.json({
1085
+ ok: true,
1086
+ result: { findings } satisfies z.input<typeof reviewReplySchema>,
1087
+ }),
1088
+ finish: undefined,
1089
+ };
1090
+ }
1091
+ const reported = await receiptSession(
1092
+ operationConfig,
910
1093
  body.operation,
911
- {
912
- imageId: options.imageId,
913
- engineering: options.engineering,
914
- operationId: body.operationId,
915
- scratch: containerScratch,
916
- initializeUser: body.initializeUser,
917
- credentials: body.credentials,
918
- notices,
919
- },
1094
+ sessionOptions,
920
1095
  online,
921
1096
  ).catch((error: unknown) => {
922
1097
  // A worker that died on an online change crashed generating it.
@@ -939,6 +1114,10 @@ export const serveWarmController = async (
939
1114
  ok: false,
940
1115
  error: failureReason(error),
941
1116
  ...(requiresDownload(error) && { downloadRequired: true }),
1117
+ ...(error instanceof DownloadRequiredError && {
1118
+ findings: error.findings,
1119
+ messages: error.messages,
1120
+ }),
942
1121
  ...(rollback && { rollback }),
943
1122
  }),
944
1123
  finish: undefined,
@@ -243,6 +243,7 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
243
243
  error: z.string().optional(),
244
244
  diagnostics: z.array(compilerDiagnosticSchema).optional(),
245
245
  downloadRequired: z.literal(true).optional(),
246
+ messages: z.array(z.string()).optional(),
246
247
  id: z.literal(id),
247
248
  ok: z.boolean(),
248
249
  result: z.unknown(),
@@ -260,7 +261,9 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
260
261
  throw new CodesysCompilerError(message, response.data.diagnostics);
261
262
  }
262
263
  if (response.data.downloadRequired) {
263
- throw new DownloadRequiredError(message);
264
+ throw new DownloadRequiredError(message, {
265
+ messages: response.data.messages,
266
+ });
264
267
  }
265
268
  throw new Error(message);
266
269
  }
package/src/index.ts CHANGED
@@ -18,7 +18,10 @@ export {
18
18
  type ControllerLogin,
19
19
  findControllerLogin,
20
20
  inspectController,
21
+ type OnlineChangeReview,
21
22
  openControllerLogin,
23
+ restartWarmController,
24
+ reviewWarmController,
22
25
  settleWarmController,
23
26
  startWarmController,
24
27
  updateController,
@@ -26,12 +29,14 @@ export {
26
29
  } from "./controller-online";
27
30
  export {
28
31
  type ControllerResult,
32
+ DownloadRequiredError,
29
33
  explicitDownload,
30
34
  failureReason,
31
35
  type LoginCommand,
32
36
  type LoginResult,
33
37
  loginCommandSchema,
34
38
  loginResultSchema,
39
+ type ResetKind,
35
40
  type Rollback,
36
41
  requiresDownload,
37
42
  rollbackSchema,
@@ -63,6 +68,11 @@ export {
63
68
  libraryIndex,
64
69
  validateLibrary,
65
70
  } from "./libraries";
71
+ export {
72
+ describeFinding,
73
+ type OnlineChangeFinding,
74
+ onlineChangeFindingSchema,
75
+ } from "./online-change-check";
66
76
  export {
67
77
  checkRawSources,
68
78
  inspectProjectController,
@@ -25,15 +25,16 @@ export const committedObjectSchema: z.ZodType<CommittedObject> = z.lazy(() =>
25
25
  * refusal is what CODESYS would refuse or apply wrongly, so the deploy offers a download before
26
26
  * CODESYS runs; anything else is a warning about state the change restarts.
27
27
  */
28
- export interface OnlineChangeFinding {
29
- kind: "type" | "tasks" | "restart";
30
- refuses: boolean;
31
- object: string;
32
- variable: string | null;
33
- before: string | null;
34
- after: string | null;
35
- advice: string;
36
- }
28
+ export const onlineChangeFindingSchema = z.strictObject({
29
+ kind: z.enum(["type", "tasks", "restart"]),
30
+ refuses: z.boolean(),
31
+ object: z.string(),
32
+ variable: z.string().nullable(),
33
+ before: z.string().nullable(),
34
+ after: z.string().nullable(),
35
+ advice: z.string(),
36
+ });
37
+ export type OnlineChangeFinding = z.infer<typeof onlineChangeFindingSchema>;
37
38
 
38
39
  /** Objects whose variables keep their values across scans; a routine's own variables don't. */
39
40
  const keepsState = (kind: string) =>