@tsplc/build 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "url": "git+https://github.com/rip-technologies/tsplc.git",
16
16
  "directory": "packages/build"
17
17
  },
18
- "version": "0.5.10",
18
+ "version": "0.5.12",
19
19
  "type": "module",
20
20
  "exports": {
21
21
  ".": {
@@ -54,9 +54,9 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "zod": "4.3.6",
57
- "@tsplc/config": "0.5.10",
58
- "@tsplc/typegen": "0.5.10",
59
- "@tsplc/iec": "0.5.10"
57
+ "@tsplc/config": "0.5.12",
58
+ "@tsplc/typegen": "0.5.12",
59
+ "@tsplc/iec": "0.5.12"
60
60
  },
61
61
  "bin": {
62
62
  "tsplc-build": "./dist/cli.js"
@@ -9,7 +9,8 @@ def open_login(engine, request):
9
9
  """Log in to the controller's running application without changing it.
10
10
 
11
11
  The project is a copy of the downloaded baseline, so the login never offers
12
- a download: the controller and the compiler reference must both match it.
12
+ a download: the controller and the compiler reference must both match it. A warm
13
+ worker's login names the file it wrote the controller user to.
13
14
  """
14
15
  baseline = request['baseline']
15
16
  project = engine.projects.open(request['project'], primary=True)
@@ -18,7 +19,7 @@ def open_login(engine, request):
18
19
  application = project.active_application
19
20
  if application is None or str(application.guid) != baseline['applicationGuid']:
20
21
  raise RuntimeError('The saved project does not contain the downloaded application')
21
- connect_controller(engine, application, request['online'])
22
+ connect_controller(engine, application, request['online'], request.get('credentialsFile'))
22
23
  online_app = engine.online.create_online_application(application)
23
24
  core = core_application(online_app)
24
25
  session_login(core)
@@ -18,6 +18,8 @@ import {
18
18
  imageIdSchema,
19
19
  type LoginCommand,
20
20
  loginResultSchema,
21
+ type ResetKind,
22
+ restartReplySchema,
21
23
  reviewReplySchema,
22
24
  rollbackSchema,
23
25
  sameBaseline,
@@ -549,6 +551,12 @@ export const startWarmController = async (
549
551
  );
550
552
  };
551
553
 
554
+ /** One warm operation's own fields, without the request's config and controller user. */
555
+ type WarmOperationKind<Request = z.input<typeof warmOperationSchema>> =
556
+ Request extends unknown
557
+ ? Omit<Request, "operationId" | "request" | "credentials">
558
+ : never;
559
+
552
560
  /** What a warm operation takes beside its config: the controller user and where its progress goes. */
553
561
  interface WarmOptions {
554
562
  credentials?: ControllerCredentials;
@@ -566,8 +574,9 @@ interface WarmOptions {
566
574
  const warmOperation = async (
567
575
  config: ResolvedConfig,
568
576
  name: string,
569
- operation: z.input<typeof warmOperationSchema>["operation"],
570
- options: WarmOptions & { initializeUser: boolean },
577
+ /** What to run, beside the config and the controller user the request carries. */
578
+ operation: WarmOperationKind,
579
+ options: WarmOptions,
571
580
  ) => {
572
581
  const report = options.onProgress ?? (() => {});
573
582
  const connection = await controllerConnection(config);
@@ -595,10 +604,9 @@ const warmOperation = async (
595
604
  : async () => {};
596
605
  try {
597
606
  const result = await callContainer(name, warmPort, "POST", {
598
- operation,
607
+ ...operation,
599
608
  operationId,
600
609
  request,
601
- initializeUser: options.initializeUser,
602
610
  credentials: options.credentials,
603
611
  } satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {
604
612
  const message = `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`;
@@ -651,10 +659,12 @@ export const reviewWarmController = async (
651
659
  options: WarmOptions,
652
660
  ): Promise<OnlineChangeReview> => {
653
661
  try {
654
- const { result } = await warmOperation(config, name, "review", {
655
- ...options,
656
- initializeUser: false,
657
- });
662
+ const { result } = await warmOperation(
663
+ config,
664
+ name,
665
+ { operation: "review", initializeUser: false },
666
+ options,
667
+ );
658
668
  return {
659
669
  possible: true,
660
670
  findings: reviewReplySchema.parse(result).findings,
@@ -675,6 +685,27 @@ export const reviewWarmController = async (
675
685
  }
676
686
  };
677
687
 
688
+ /**
689
+ * Resets the application the committed download put on the controller and starts it again, in
690
+ * warm builder container `name`: a warm reset keeps the retain variables, a cold one resets them
691
+ * too. The code and the download baseline stay as they are, and no login has to be open. Returns
692
+ * the state the application runs in.
693
+ */
694
+ export const restartWarmController = async (
695
+ config: ResolvedConfig,
696
+ name: string,
697
+ reset: ResetKind,
698
+ options: WarmOptions,
699
+ ) => {
700
+ const { result } = await warmOperation(
701
+ config,
702
+ name,
703
+ { operation: "restart", reset },
704
+ options,
705
+ );
706
+ return restartReplySchema.parse(result);
707
+ };
708
+
678
709
  /**
679
710
  * A download or online change in warm builder container `name` (see `warmOperation`). A download
680
711
  * that fails mid-transfer throws a `TransferFailedError` naming its rollback.
@@ -688,8 +719,8 @@ export const updateWarmController = async (
688
719
  const { result, connection, operationId, diagnostics } = await warmOperation(
689
720
  config,
690
721
  name,
691
- operation,
692
- { ...options, initializeUser: options.initializeUser ?? false },
722
+ { operation, initializeUser: options.initializeUser ?? false },
723
+ options,
693
724
  );
694
725
  return checkReceipt(
695
726
  controllerResultSchema.parse(result),
@@ -51,17 +51,33 @@ export const controllerCredentialsSchema = z.strictObject({
51
51
  });
52
52
  export type ControllerCredentials = z.infer<typeof controllerCredentialsSchema>;
53
53
 
54
- /**
55
- * One operation for the warm builder container; `request` is the container path of its config. A
56
- * `review` goes an online change's way up to CODESYS's verdict and changes nothing.
57
- */
58
- export const warmOperationSchema = z.strictObject({
59
- operation: z.enum(["download", "online-change", "review"]),
54
+ /** How a reset reinitializes the application: a warm one keeps its retain variables. */
55
+ export const resetKindSchema = z.enum(["Warm", "Cold"]);
56
+ export type ResetKind = z.infer<typeof resetKindSchema>;
57
+
58
+ const warmRequest = {
60
59
  operationId: z.uuid(),
61
60
  request: z.string().nonempty(),
62
- initializeUser: z.boolean(),
63
61
  credentials: controllerCredentialsSchema.optional(),
64
- });
62
+ };
63
+
64
+ /**
65
+ * One operation for the warm builder container; `request` is the container path of its config. A
66
+ * `review` goes an online change's way up to CODESYS's verdict and changes nothing. A `restart`
67
+ * resets the running application and starts it again, changing nothing of its code.
68
+ */
69
+ export const warmOperationSchema = z.discriminatedUnion("operation", [
70
+ z.strictObject({
71
+ operation: z.enum(["download", "online-change", "review"]),
72
+ ...warmRequest,
73
+ initializeUser: z.boolean(),
74
+ }),
75
+ z.strictObject({
76
+ operation: z.literal("restart"),
77
+ ...warmRequest,
78
+ reset: resetKindSchema,
79
+ }),
80
+ ]);
65
81
 
66
82
  /**
67
83
  * The failure a Python traceback ends with, as `Type: message`: everything after its last frame, so
@@ -151,6 +167,9 @@ export class DownloadRequiredError extends Error {
151
167
  }
152
168
  }
153
169
 
170
+ /** What a warm container replies once a restart has the application running again: its state. */
171
+ export const restartReplySchema = z.strictObject({ state: z.string() });
172
+
154
173
  /** What a warm container replies once a review finds CODESYS can apply the change. */
155
174
  export const reviewReplySchema = z.strictObject({
156
175
  findings: z.array(onlineChangeFindingSchema),
@@ -211,10 +230,7 @@ export const loginCommandSchema = z.discriminatedUnion("command", [
211
230
  restore: z.boolean(),
212
231
  }),
213
232
  z.strictObject({ command: z.enum(["start", "stop"]) }),
214
- z.strictObject({
215
- command: z.literal("reset"),
216
- kind: z.enum(["Warm", "Cold"]),
217
- }),
233
+ z.strictObject({ command: z.literal("reset"), kind: resetKindSchema }),
218
234
  ]);
219
235
  export type LoginCommand = z.infer<typeof loginCommandSchema>;
220
236
  export const loginResultSchema = z.union([
@@ -18,7 +18,9 @@ import {
18
18
  explicitDownload,
19
19
  failureReason,
20
20
  loginCommandSchema,
21
+ type ResetKind,
21
22
  requiresDownload,
23
+ type restartReplySchema,
22
24
  type reviewReplySchema,
23
25
  sameBaseline,
24
26
  TransferFailedError,
@@ -745,6 +747,30 @@ const controllerSession = async (
745
747
  }
746
748
  };
747
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
+
748
774
  /**
749
775
  * Called inside the builder container: holds one login to the running application, made
750
776
  * from the committed baseline, and serves its commands on `port` until a DELETE closes it.
@@ -763,11 +789,8 @@ export const serveControllerLogin = async (
763
789
  templateHash: sha256(await readFile(config.template)),
764
790
  target: controllerTarget(config, config.online),
765
791
  });
766
- const { baseline } = committed;
767
792
  const jobConfig = { ...config, outDir: resolve(root, "login") };
768
793
  await rm(jobConfig.outDir, { recursive: true, force: true });
769
- // CODESYS writes into an open project, and the committed baseline must not change.
770
- await copyCommitted(committed, resolve(jobConfig.outDir, "project"));
771
794
  const worker = createCodesysWorker(jobConfig);
772
795
  await withWorkerShutdown(jobConfig, worker, () =>
773
796
  withWorkerLock(jobConfig, async () => {
@@ -778,15 +801,12 @@ export const serveControllerLogin = async (
778
801
  { action: "login", arguments: command },
779
802
  config.timeouts.build,
780
803
  );
781
- await send({
782
- command: "open",
783
- project: await toWindowsPath(
784
- resolve(jobConfig.outDir, "project", "Application.project"),
785
- config.codesys.wine,
786
- ),
787
- online: config.online,
788
- baseline,
789
- });
804
+ await send(
805
+ await openLoginCommand(config, committed, {
806
+ directory: jobConfig.outDir,
807
+ credentialsFile: null,
808
+ }),
809
+ );
790
810
  const closed = Promise.withResolvers<void>();
791
811
  // The worker has one mailbox, so commands run one at a time.
792
812
  let previous: Promise<unknown> = Promise.resolve();
@@ -831,6 +851,63 @@ export const serveControllerLogin = async (
831
851
  );
832
852
  };
833
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
+
834
911
  interface WarmOperation {
835
912
  reply: Response;
836
913
  /** Commits the operation's project, once the controller runs it. */
@@ -884,8 +961,8 @@ export const warmRequests = (handlers: {
884
961
  };
885
962
 
886
963
  /**
887
- * Called inside the builder container: keeps one CODESYS worker running and serves downloads and
888
- * 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
889
966
  * own config, written for that release, and is answered once the controller runs the application;
890
967
  * its project is committed after, before the next operation starts. A GET reports whether that
891
968
  * commit still runs, which `settleWarmController` waits for. The agent runs one operation at a
@@ -962,6 +1039,32 @@ export const serveWarmController = async (
962
1039
  try {
963
1040
  const body = warmOperationSchema.parse(await request.json());
964
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
+ }
965
1068
  const sessionOptions: SessionOptions = {
966
1069
  imageId: options.imageId,
967
1070
  engineering: options.engineering,
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ export {
20
20
  inspectController,
21
21
  type OnlineChangeReview,
22
22
  openControllerLogin,
23
+ restartWarmController,
23
24
  reviewWarmController,
24
25
  settleWarmController,
25
26
  startWarmController,
@@ -35,6 +36,7 @@ export {
35
36
  type LoginResult,
36
37
  loginCommandSchema,
37
38
  loginResultSchema,
39
+ type ResetKind,
38
40
  type Rollback,
39
41
  requiresDownload,
40
42
  rollbackSchema,