@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.
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.9",
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.9",
58
- "@tsplc/typegen": "0.5.9",
59
- "@tsplc/iec": "0.5.9"
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)
@@ -35,10 +35,12 @@ def fail_on_download_errors(engine):
35
35
  raise CompilerError(errors)
36
36
 
37
37
 
38
- def download_required(message):
39
- """A refusal only a full download resolves; the worker marks its reply so callers can offer one."""
38
+ def download_required(message, messages=()):
39
+ """A refusal only a full download resolves; the worker marks its reply so callers can offer one,
40
+ and passes on `messages`, CODESYS's reasons in its own words."""
40
41
  error = RuntimeError(message)
41
42
  error.download_required = True
43
+ error.messages = list(messages)
42
44
  return error
43
45
 
44
46
 
@@ -46,7 +48,8 @@ CANNOT_APPLY = 'CODESYS cannot apply this source as an online change; use an exp
46
48
 
47
49
 
48
50
  def refusal_with_reasons(diagnostics):
49
- return download_required('\n'.join([CANNOT_APPLY + ':'] + [item['text'] for item in diagnostics]))
51
+ reasons = [item['text'] for item in diagnostics]
52
+ return download_required('\n'.join([CANNOT_APPLY + ':'] + reasons), reasons)
50
53
 
51
54
 
52
55
  def fail_on_online_change_errors(engine):
@@ -476,7 +479,8 @@ def run_online(engine, request, log, prepared=None, keep=None):
476
479
  """`log` is CODESYS's output, where it writes the prompts it answers. `prepared` is a project a
477
480
  warm worker opened ahead; an online change of that project uses it. A request to finish later
478
481
  replies once the controller runs the application, and hands `keep` the open project and its newly
479
- generated tree, for `finish_online` to save."""
482
+ generated tree, for `finish_online` to save. A review goes the online change's way up to CODESYS's
483
+ verdict, refusing as it would, and then logs out, having transferred nothing."""
480
484
  progress = request_progress(request)
481
485
  progress('Starting; processor count {0}'.format(Environment.ProcessorCount))
482
486
  if request.get('finishLater') and keep is None:
@@ -486,6 +490,7 @@ def run_online(engine, request, log, prepared=None, keep=None):
486
490
  prepared.close()
487
491
  return restore_previous(engine, request, log, progress)
488
492
  previous = request.get('baseline')
493
+ changes_online = request['operation'] in ('online-change', 'review')
489
494
  project, complete_tree = open_operation_project(engine, request, prepared, progress)
490
495
  application = project.active_application
491
496
  online_app = None
@@ -510,7 +515,7 @@ def run_online(engine, request, log, prepared=None, keep=None):
510
515
  online_app = engine.online.create_online_application(application)
511
516
  core = core_application(online_app)
512
517
  if not previous or str(application.guid) != previous['applicationGuid']:
513
- if request['operation'] == 'online-change':
518
+ if changes_online:
514
519
  raise download_required('Online change requires the saved downloaded application; use an explicit download')
515
520
  raise RuntimeError('Online change requires the saved downloaded application')
516
521
  progress('Checking downloaded controller identity and state')
@@ -524,7 +529,7 @@ def run_online(engine, request, log, prepared=None, keep=None):
524
529
  raise download_required('Downloaded compiler reference differs from the controller; use an explicit download')
525
530
  progress('Downloaded compiler reference loaded')
526
531
  state = controller_state(core)
527
- if request['operation'] == 'online-change' and state != 'run':
532
+ if changes_online and state != 'run':
528
533
  raise RuntimeError('Online change requires a running application')
529
534
  if request['operation'] == 'inspect':
530
535
  return {'applicationGuid': str(application.guid), 'controllerIds': observed,
@@ -577,10 +582,15 @@ def run_online(engine, request, log, prepared=None, keep=None):
577
582
  if controller_ids(core) != previous['controllerIds']:
578
583
  raise RuntimeError('Controller application changed before the online change')
579
584
  expected = controller_ids(core)
580
- if not application.is_uptodate:
581
- if not application.is_online_change_possible:
582
- raise download_required(CANNOT_APPLY + '. CODESYS gave no reason; the usual causes are a '
583
- 'changed task configuration, a variable whose type changed, or a changed device.')
585
+ changed = not application.is_uptodate
586
+ if changed and not application.is_online_change_possible:
587
+ raise download_required(CANNOT_APPLY + '. CODESYS gave no reason; the usual causes are a '
588
+ 'changed task configuration, a variable whose type changed, or a changed device.')
589
+ if request['operation'] == 'review':
590
+ progress('CODESYS can apply this as an online change; the review transferred nothing')
591
+ core.Logout()
592
+ return {}
593
+ if changed:
584
594
  progress('Generating online-change code')
585
595
  generate_online_code(application)
586
596
  fail_on_online_code_errors(engine)
package/python/worker.py CHANGED
@@ -147,6 +147,7 @@ def serve(engine, directory):
147
147
  response["diagnostics"] = error.diagnostics
148
148
  if getattr(error, "download_required", False):
149
149
  response["downloadRequired"] = True
150
+ response["messages"] = getattr(error, "messages", [])
150
151
  write_json(engine, os.path.join(directory, command["id"] + ".json"), response)
151
152
  if command["action"] == "stop":
152
153
  return
@@ -18,7 +18,9 @@ import {
18
18
  imageIdSchema,
19
19
  type LoginCommand,
20
20
  loginResultSchema,
21
- requiresDownload,
21
+ type ResetKind,
22
+ restartReplySchema,
23
+ reviewReplySchema,
22
24
  rollbackSchema,
23
25
  sameBaseline,
24
26
  TransferFailedError,
@@ -39,6 +41,10 @@ import {
39
41
  writeOperationRequest,
40
42
  } from "./docker-run";
41
43
  import { builderImage } from "./images";
44
+ import {
45
+ type OnlineChangeFinding,
46
+ onlineChangeFindingSchema,
47
+ } from "./online-change-check";
42
48
 
43
49
  /** Where an operation reads the controller user's environment variables from; this process's environment by default. */
44
50
  export interface CredentialSource {
@@ -205,6 +211,8 @@ const loginReplySchema = z.discriminatedUnion("ok", [
205
211
  ok: z.literal(false),
206
212
  error: z.string(),
207
213
  downloadRequired: z.literal(true).optional(),
214
+ findings: z.array(onlineChangeFindingSchema).optional(),
215
+ messages: z.array(z.string()).optional(),
208
216
  rollback: rollbackSchema.optional(),
209
217
  }),
210
218
  ]);
@@ -276,7 +284,10 @@ const callContainer = async (
276
284
  }
277
285
  // Builder images from before `downloadRequired` existed only end such a refusal with these words.
278
286
  throw reply.downloadRequired || reply.error.endsWith(explicitDownload)
279
- ? new DownloadRequiredError(reply.error)
287
+ ? new DownloadRequiredError(reply.error, {
288
+ findings: reply.findings,
289
+ messages: reply.messages,
290
+ })
280
291
  : new Error(reply.error);
281
292
  }
282
293
  return reply.result;
@@ -540,23 +551,33 @@ export const startWarmController = async (
540
551
  );
541
552
  };
542
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
+
560
+ /** What a warm operation takes beside its config: the controller user and where its progress goes. */
561
+ interface WarmOptions {
562
+ credentials?: ControllerCredentials;
563
+ /** Receives each step CODESYS reports while the operation runs. */
564
+ onProgress?: (message: string) => void;
565
+ }
566
+
543
567
  /**
544
- * A download or online change in builder container `name`, which keeps CODESYS running between
568
+ * Runs `operation` in warm builder container `name`, which keeps CODESYS running between
545
569
  * operations so each skips starting the container, Wine and CODESYS. The first operation, or one
546
- * with a new image, tsPLC installation, target or Docker settings, starts it. Credentials go to CODESYS for this
547
- * operation only. A download that fails mid-transfer throws a `TransferFailedError` naming its rollback.
570
+ * with a new image, tsPLC installation, target or Docker settings, starts it. Credentials go to
571
+ * CODESYS for this operation only. Returns the container's result, unchecked, and what it was run
572
+ * against; a refusal only a download resolves throws a `DownloadRequiredError` with its reasons.
548
573
  */
549
- export const updateWarmController = async (
574
+ const warmOperation = async (
550
575
  config: ResolvedConfig,
551
576
  name: string,
552
- operation: "download" | "online-change",
553
- options: {
554
- initializeUser?: boolean;
555
- credentials?: ControllerCredentials;
556
- /** Receives each step CODESYS reports while this operation runs. */
557
- onProgress?: (message: string) => void;
558
- } = {},
559
- ): Promise<ControllerResult> => {
577
+ /** What to run, beside the config and the controller user the request carries. */
578
+ operation: WarmOperationKind,
579
+ options: WarmOptions,
580
+ ) => {
560
581
  const report = options.onProgress ?? (() => {});
561
582
  const connection = await controllerConnection(config);
562
583
  const operationId = randomUUID();
@@ -583,10 +604,9 @@ export const updateWarmController = async (
583
604
  : async () => {};
584
605
  try {
585
606
  const result = await callContainer(name, warmPort, "POST", {
586
- operation,
607
+ ...operation,
587
608
  operationId,
588
609
  request,
589
- initializeUser: options.initializeUser ?? false,
590
610
  credentials: options.credentials,
591
611
  } satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {
592
612
  const message = `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`;
@@ -594,23 +614,123 @@ export const updateWarmController = async (
594
614
  if (rollback) {
595
615
  throw new TransferFailedError(message, rollback, { cause: error });
596
616
  }
597
- throw requiresDownload(error)
598
- ? new DownloadRequiredError(message, { cause: error })
617
+ throw error instanceof DownloadRequiredError
618
+ ? new DownloadRequiredError(message, {
619
+ cause: error,
620
+ findings: error.findings,
621
+ messages: error.messages,
622
+ })
599
623
  : new Error(message, { cause: error });
600
624
  });
601
- return checkReceipt(
602
- controllerResultSchema.parse(result),
603
- {
604
- operationId,
605
- operation,
606
- imageId: connection.imageId,
607
- templateHash: connection.templateHash,
608
- target: connection.target,
609
- },
610
- diagnostics,
611
- );
625
+ return { result, connection, operationId, diagnostics };
612
626
  } finally {
613
627
  await stopFollowing();
614
628
  await rm(directory, { recursive: true, force: true });
615
629
  }
616
630
  };
631
+
632
+ /**
633
+ * What an online change to `config`'s sources would do, found without applying it: tsPLC's check
634
+ * of the sources against the committed download, then CODESYS's own verdict from an incremental
635
+ * build against the controller's downloaded reference. The controller and its baseline are left
636
+ * as they were.
637
+ */
638
+ export interface OnlineChangeReview {
639
+ /** Whether CODESYS can apply the sources as an online change. */
640
+ possible: boolean;
641
+ /** tsPLC's findings: what it refuses, and what the change restarts. */
642
+ findings: OnlineChangeFinding[];
643
+ /**
644
+ * Why it can't, beside the findings: CODESYS's reasons in its own words when it gave them, else
645
+ * the refusal itself, such as a committed download this change can't follow. Empty when it can,
646
+ * or when the findings say why.
647
+ */
648
+ messages: string[];
649
+ }
650
+
651
+ /**
652
+ * Reviews an online change in warm builder container `name`: everything `updateWarmController`
653
+ * does up to CODESYS's verdict, which logs in to the controller and out again. Nothing is
654
+ * transferred to the controller and no download baseline is committed.
655
+ */
656
+ export const reviewWarmController = async (
657
+ config: ResolvedConfig,
658
+ name: string,
659
+ options: WarmOptions,
660
+ ): Promise<OnlineChangeReview> => {
661
+ try {
662
+ const { result } = await warmOperation(
663
+ config,
664
+ name,
665
+ { operation: "review", initializeUser: false },
666
+ options,
667
+ );
668
+ return {
669
+ possible: true,
670
+ findings: reviewReplySchema.parse(result).findings,
671
+ messages: [],
672
+ };
673
+ } catch (error) {
674
+ if (!(error instanceof DownloadRequiredError)) {
675
+ throw error;
676
+ }
677
+ const explained =
678
+ error.messages.length > 0 ||
679
+ error.findings.some((finding) => finding.refuses);
680
+ return {
681
+ possible: false,
682
+ findings: error.findings,
683
+ messages: explained ? error.messages : [failureReason(error.cause)],
684
+ };
685
+ }
686
+ };
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
+
709
+ /**
710
+ * A download or online change in warm builder container `name` (see `warmOperation`). A download
711
+ * that fails mid-transfer throws a `TransferFailedError` naming its rollback.
712
+ */
713
+ export const updateWarmController = async (
714
+ config: ResolvedConfig,
715
+ name: string,
716
+ operation: "download" | "online-change",
717
+ options: WarmOptions & { initializeUser?: boolean } = {},
718
+ ): Promise<ControllerResult> => {
719
+ const { result, connection, operationId, diagnostics } = await warmOperation(
720
+ config,
721
+ name,
722
+ { operation, initializeUser: options.initializeUser ?? false },
723
+ options,
724
+ );
725
+ return checkReceipt(
726
+ controllerResultSchema.parse(result),
727
+ {
728
+ operationId,
729
+ operation,
730
+ imageId: connection.imageId,
731
+ templateHash: connection.templateHash,
732
+ target: connection.target,
733
+ },
734
+ diagnostics,
735
+ );
736
+ };
@@ -1,5 +1,6 @@
1
1
  // What the host and the builder container exchange for controller operations: the receipt,
2
- // the target a baseline is bound to, warm and login commands, and how failures are worded.
2
+ // the target a baseline is bound to, warm and login commands, a review's reply, and how failures
3
+ // are worded.
3
4
  import {
4
5
  controllerSchema,
5
6
  type ResolvedConfig,
@@ -8,6 +9,10 @@ import {
8
9
  } from "@tsplc/config/build";
9
10
  import { z } from "zod";
10
11
  import { deviceTreeStructure } from "./device-tree";
12
+ import {
13
+ type OnlineChangeFinding,
14
+ onlineChangeFindingSchema,
15
+ } from "./online-change-check";
11
16
 
12
17
  export const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
13
18
  const endpointSchema = z.strictObject({
@@ -46,14 +51,33 @@ export const controllerCredentialsSchema = z.strictObject({
46
51
  });
47
52
  export type ControllerCredentials = z.infer<typeof controllerCredentialsSchema>;
48
53
 
49
- /** One operation for the warm builder container; `request` is the container path of its config. */
50
- export const warmOperationSchema = z.strictObject({
51
- operation: z.enum(["download", "online-change"]),
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 = {
52
59
  operationId: z.uuid(),
53
60
  request: z.string().nonempty(),
54
- initializeUser: z.boolean(),
55
61
  credentials: controllerCredentialsSchema.optional(),
56
- });
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
+ ]);
57
81
 
58
82
  /**
59
83
  * The failure a Python traceback ends with, as `Type: message`: everything after its last frame, so
@@ -117,14 +141,40 @@ export const sameBaseline = (state: Baseline, expected: Baseline) =>
117
141
  /** Ends the message of every refusal that only a full download resolves. */
118
142
  export const explicitDownload = "use an explicit download";
119
143
 
144
+ /** Why only a full download will do: tsPLC's findings and CODESYS's reasons, in its own words. */
145
+ export interface DownloadReasons {
146
+ findings: OnlineChangeFinding[];
147
+ messages: string[];
148
+ }
149
+
120
150
  /**
121
151
  * A refusal that only a full download resolves, so callers can offer one instead of failing.
122
- * Worker and container replies carry it as `downloadRequired: true`.
152
+ * Worker and container replies carry it as `downloadRequired: true`, with the reasons they have.
123
153
  */
124
154
  export class DownloadRequiredError extends Error {
125
155
  readonly downloadRequired = true;
156
+ /** tsPLC's findings about the change, refusals and restarts, when its check ran. */
157
+ readonly findings: OnlineChangeFinding[];
158
+ /** CODESYS's reasons, when it gave them. */
159
+ readonly messages: string[];
160
+ constructor(
161
+ message: string,
162
+ options: ErrorOptions & Partial<DownloadReasons> = {},
163
+ ) {
164
+ super(message, options);
165
+ this.findings = options.findings ?? [];
166
+ this.messages = options.messages ?? [];
167
+ }
126
168
  }
127
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
+
173
+ /** What a warm container replies once a review finds CODESYS can apply the change. */
174
+ export const reviewReplySchema = z.strictObject({
175
+ findings: z.array(onlineChangeFindingSchema),
176
+ });
177
+
128
178
  /**
129
179
  * What became of the controller after a download failed mid-transfer: it still ran the previous
130
180
  * application (`intact`), runs it again from the last committed download (`restored`), or may hold
@@ -180,10 +230,7 @@ export const loginCommandSchema = z.discriminatedUnion("command", [
180
230
  restore: z.boolean(),
181
231
  }),
182
232
  z.strictObject({ command: z.enum(["start", "stop"]) }),
183
- z.strictObject({
184
- command: z.literal("reset"),
185
- kind: z.enum(["Warm", "Cold"]),
186
- }),
233
+ z.strictObject({ command: z.literal("reset"), kind: resetKindSchema }),
187
234
  ]);
188
235
  export type LoginCommand = z.infer<typeof loginCommandSchema>;
189
236
  export const loginResultSchema = z.union([