@tsplc/build 0.5.8 → 0.5.10

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.
@@ -4,6 +4,7 @@ import { cp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import {
6
6
  controllerBudgets,
7
+ cyclicTasksSchema,
7
8
  type ResolvedConfig,
8
9
  sha256Digest,
9
10
  } from "@tsplc/config/build";
@@ -18,6 +19,7 @@ import {
18
19
  failureReason,
19
20
  loginCommandSchema,
20
21
  requiresDownload,
22
+ type reviewReplySchema,
21
23
  sameBaseline,
22
24
  TransferFailedError,
23
25
  tracebackFailure,
@@ -26,6 +28,7 @@ import {
26
28
  } from "./controller-protocol";
27
29
  import { deviceTreeSettings, writeDeviceTree } from "./device-tree";
28
30
  import {
31
+ CodesysExitedError,
29
32
  createCodesysWorker,
30
33
  type PhasedBudget,
31
34
  withWorkerLock,
@@ -35,6 +38,13 @@ import {
35
38
  } from "./host/codesys-worker";
36
39
  import { toWindowsPath } from "./host/windows-path";
37
40
  import { importRequest } from "./import-request";
41
+ import {
42
+ type CommittedObject,
43
+ committedObjectSchema,
44
+ describeFinding,
45
+ type OnlineChangeFinding,
46
+ onlineChangeFindings,
47
+ } from "./online-change-check";
38
48
  import { loadSources } from "./sources";
39
49
 
40
50
  // Vendor code/data IDs are .NET Guid values derived from the compiler's data;
@@ -47,7 +57,9 @@ const pointerSchema = z.strictObject({
47
57
  generation: z.uuid(),
48
58
  });
49
59
  const baselineSchema = controllerResultSchema.extend({
50
- objects: z.array(z.record(z.string(), z.unknown())),
60
+ objects: z.array(committedObjectSchema),
61
+ // The task plan the download configured, which an online change can't change.
62
+ tasks: cyclicTasksSchema.optional(),
51
63
  files: z.record(z.string(), sha256Digest),
52
64
  // The device tree's adapter settings the download wrote, which an online change can't change.
53
65
  deviceSettings: sha256Digest.optional(),
@@ -165,7 +177,7 @@ const committedBaseline = async (
165
177
  root: string,
166
178
  expected: Pick<
167
179
  z.infer<typeof baselineSchema>,
168
- "imageId" | "templateHash" | "target"
180
+ "imageId" | "engineering" | "templateHash" | "target"
169
181
  >,
170
182
  ) => {
171
183
  const committed = await readCommitted(root);
@@ -194,6 +206,44 @@ const copyCommitted = async (committed: Committed, destination: string) => {
194
206
  }
195
207
  };
196
208
 
209
+ /**
210
+ * CODESYS crashes generating an online change that moves a block holding a network client, such as
211
+ * a job with a service call. The controller keeps its running program, and a download resolves it.
212
+ */
213
+ const crashedOnlineChange = (cause: unknown) =>
214
+ new DownloadRequiredError(
215
+ `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
216
+ { cause },
217
+ );
218
+
219
+ /**
220
+ * Refuses, before CODESYS runs, an online change CODESYS would refuse or apply wrongly, naming
221
+ * the variable or task that causes it; reports the state the change restarts, and returns it.
222
+ */
223
+ const checkOnlineChange = (
224
+ baseline: z.infer<typeof baselineSchema>,
225
+ objects: readonly CommittedObject[],
226
+ config: Pick<ResolvedConfig, "tasks">,
227
+ progress: (message: string) => void,
228
+ ) => {
229
+ const findings = onlineChangeFindings({
230
+ before: baseline.objects,
231
+ after: objects,
232
+ tasks: { before: baseline.tasks ?? null, after: config.tasks ?? null },
233
+ });
234
+ const refusals = findings.filter((finding) => finding.refuses);
235
+ if (refusals.length) {
236
+ throw new DownloadRequiredError(
237
+ `This change can't be applied as an online change; ${explicitDownload}:\n${refusals.map(describeFinding).join("\n")}`,
238
+ { findings },
239
+ );
240
+ }
241
+ for (const finding of findings) {
242
+ progress(`Online change: ${describeFinding(finding)}`);
243
+ }
244
+ return findings;
245
+ };
246
+
197
247
  /** A CODESYS worker that handles the `online` request written to `requestDirectory` when `run`. */
198
248
  interface OnlineWorker {
199
249
  requestDirectory: string;
@@ -230,6 +280,8 @@ const restoreResultSchema = z.object({
230
280
 
231
281
  interface SessionOptions {
232
282
  imageId: string;
283
+ /** The image's CODESYS engineering, or null for an image that doesn't record it. */
284
+ engineering: string | null;
233
285
  operationId: string;
234
286
  scratch: string;
235
287
  initializeUser?: boolean;
@@ -239,6 +291,9 @@ interface SessionOptions {
239
291
  notices?: string[];
240
292
  }
241
293
 
294
+ /** An operation that ends in a receipt, and a review, which ends in tsPLC's findings. */
295
+ type SessionOperation = "download" | "online-change" | "inspect" | "review";
296
+
242
297
  /**
243
298
  * Called inside the builder container, while its output-directory flock is held or, for a warm
244
299
  * `worker`, while the agent runs nothing else. Without `credentials`, CODESYS reads the controller
@@ -247,30 +302,67 @@ interface SessionOptions {
247
302
  */
248
303
  export const runControllerSession = async (
249
304
  config: ResolvedConfig,
250
- operation: "download" | "online-change" | "inspect",
305
+ operation: Exclude<SessionOperation, "review">,
251
306
  options: SessionOptions,
252
307
  worker?: OnlineWorker,
253
308
  ) => {
254
- const session = await controllerSession(config, operation, options, worker);
309
+ const session = await receiptSession(config, operation, options, worker);
255
310
  await session.finish();
256
311
  return session.receipt;
257
312
  };
258
313
 
314
+ /** A session of an operation that ends in a receipt. */
315
+ const receiptSession = async (
316
+ config: ResolvedConfig,
317
+ operation: Exclude<SessionOperation, "review">,
318
+ options: SessionOptions,
319
+ worker?: OnlineWorker,
320
+ ) => {
321
+ const session = await controllerSession(config, operation, options, worker);
322
+ if (!("receipt" in session)) {
323
+ throw new Error(`The ${operation} ended without a receipt`);
324
+ }
325
+ return session;
326
+ };
327
+
328
+ /**
329
+ * Called inside the builder container like `runControllerSession`: goes an online change's way up
330
+ * to CODESYS's verdict on it, and returns tsPLC's findings. Refuses as the online change would,
331
+ * with a `DownloadRequiredError`; transfers, saves and commits nothing.
332
+ */
333
+ export const reviewControllerSession = async (
334
+ config: ResolvedConfig,
335
+ options: SessionOptions,
336
+ worker?: OnlineWorker,
337
+ ): Promise<OnlineChangeFinding[]> => {
338
+ const session = await controllerSession(config, "review", options, worker);
339
+ if (!("findings" in session)) {
340
+ throw new Error("The review ended with a receipt");
341
+ }
342
+ return session.findings;
343
+ };
344
+
259
345
  /**
260
346
  * Runs an operation up to the receipt of a controller that runs its application. `finish` then
261
347
  * 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.
348
+ * until it settles, nothing else may use the worker or the output directory's baseline. A review
349
+ * ends at CODESYS's verdict, with tsPLC's findings, and cleans up at once.
263
350
  */
264
351
  const controllerSession = async (
265
352
  config: ResolvedConfig,
266
- operation: "download" | "online-change" | "inspect",
353
+ operation: SessionOperation,
267
354
  options: SessionOptions,
268
355
  worker?: OnlineWorker,
269
- ) => {
356
+ ): Promise<
357
+ | { receipt: ControllerResult; finish: () => Promise<void> }
358
+ | { findings: OnlineChangeFinding[] }
359
+ > => {
270
360
  const settings = config.online;
271
361
  if (!settings) {
272
362
  throw new Error("Controller operations require online settings");
273
363
  }
364
+ // A review checks everything an online change would, up to applying it.
365
+ const onlineChange = operation === "online-change" || operation === "review";
274
366
  if (options.initializeUser && operation !== "download") {
275
367
  throw new DownloadRequiredError(
276
368
  "Initial user creation requires an explicit download",
@@ -283,7 +375,12 @@ const controllerSession = async (
283
375
  const templateHash = sha256(await readFile(config.template));
284
376
  // A different image, template, controller or device tree structure needs a fresh download from the template.
285
377
  const target = controllerTarget(config, settings);
286
- const expected = { imageId: options.imageId, templateHash, target };
378
+ const expected = {
379
+ imageId: options.imageId,
380
+ engineering: options.engineering ?? undefined,
381
+ templateHash,
382
+ target,
383
+ };
287
384
  const jobConfig = {
288
385
  ...config,
289
386
  outDir: jobOutput(config.outDir, options.operationId),
@@ -317,10 +414,7 @@ const controllerSession = async (
317
414
  );
318
415
  const deviceSettings =
319
416
  config.deviceTree && deviceTreeSettings(config.deviceTree);
320
- if (
321
- operation === "online-change" &&
322
- committed?.baseline.deviceSettings !== deviceSettings
323
- ) {
417
+ if (onlineChange && committed?.baseline.deviceSettings !== deviceSettings) {
324
418
  throw new DownloadRequiredError(
325
419
  `The device tree's adapter addresses or RPIs changed since the download; ${explicitDownload}`,
326
420
  );
@@ -502,6 +596,7 @@ const controllerSession = async (
502
596
  await writeJson(resolve(committedDirectory, "manifest.json"), {
503
597
  ...receipt,
504
598
  objects,
599
+ ...(config.tasks && { tasks: config.tasks }),
505
600
  files,
506
601
  deviceSettings,
507
602
  });
@@ -552,6 +647,10 @@ const controllerSession = async (
552
647
  const baseline = previous?.baseline;
553
648
  progress("Loading the program's sources");
554
649
  const sources = operation === "inspect" ? null : await loadSources(config);
650
+ const findings =
651
+ onlineChange && baseline && sources
652
+ ? checkOnlineChange(baseline, sources.objects, config, progress)
653
+ : [];
555
654
  const request = {
556
655
  libraryReferences: config.libraryReferences,
557
656
  // Only a download without a baseline starts from the template; the others keep the downloaded project's tree.
@@ -577,6 +676,36 @@ const controllerSession = async (
577
676
  read: options.read ?? [],
578
677
  finishLater: online.finishesLater,
579
678
  };
679
+ const reply = await runConnected(request).catch(
680
+ async (failure: unknown) => {
681
+ if (
682
+ operation === "online-change" &&
683
+ failure instanceof CodesysExitedError
684
+ ) {
685
+ throw crashedOnlineChange(failure);
686
+ }
687
+ // CODESYS's refusal carries its reasons; tsPLC's findings join them.
688
+ if (onlineChange && failure instanceof DownloadRequiredError) {
689
+ throw new DownloadRequiredError(failure.message, {
690
+ cause: failure,
691
+ findings,
692
+ messages: failure.messages,
693
+ });
694
+ }
695
+ if (
696
+ operation !== "download" ||
697
+ (await workerPhase(phase)) !== "transfer"
698
+ ) {
699
+ throw failure;
700
+ }
701
+ throw await rollBack(failure);
702
+ },
703
+ );
704
+ if (operation === "review") {
705
+ z.strictObject({}).parse(reply);
706
+ await cleanUp();
707
+ return { findings };
708
+ }
580
709
  const result = z
581
710
  .object({
582
711
  applicationGuid: guid,
@@ -585,17 +714,7 @@ const controllerSession = async (
585
714
  state: z.string(),
586
715
  values: z.record(z.string(), z.string()),
587
716
  })
588
- .parse(
589
- await runConnected(request).catch(async (failure: unknown) => {
590
- if (
591
- operation !== "download" ||
592
- (await workerPhase(phase)) !== "transfer"
593
- ) {
594
- throw failure;
595
- }
596
- throw await rollBack(failure);
597
- }),
598
- );
717
+ .parse(reply);
599
718
  const receipt = controllerResultSchema.parse({
600
719
  ...result,
601
720
  application: result.application ?? baseline?.application,
@@ -603,6 +722,7 @@ const controllerSession = async (
603
722
  operationId: options.operationId,
604
723
  operation,
605
724
  imageId: options.imageId,
725
+ engineering: options.engineering ?? undefined,
606
726
  templateHash,
607
727
  target,
608
728
  generation: operation === "inspect" ? baseline?.generation : generation,
@@ -631,7 +751,7 @@ const controllerSession = async (
631
751
  */
632
752
  export const serveControllerLogin = async (
633
753
  config: ResolvedConfig,
634
- options: { imageId: string; port: number },
754
+ options: { imageId: string; engineering: string | null; port: number },
635
755
  ) => {
636
756
  if (!config.online) {
637
757
  throw new Error("Controller logins require online settings");
@@ -639,6 +759,7 @@ export const serveControllerLogin = async (
639
759
  const root = controllerDirectory(config.outDir);
640
760
  const committed = await committedBaseline(root, {
641
761
  imageId: options.imageId,
762
+ engineering: options.engineering ?? undefined,
642
763
  templateHash: sha256(await readFile(config.template)),
643
764
  target: controllerTarget(config, config.online),
644
765
  });
@@ -774,6 +895,7 @@ export const serveWarmController = async (
774
895
  config: ResolvedConfig,
775
896
  options: {
776
897
  imageId: string;
898
+ engineering: string | null;
777
899
  port: number;
778
900
  loadConfig: (path: string) => Promise<ResolvedConfig>;
779
901
  },
@@ -839,31 +961,44 @@ export const serveWarmController = async (
839
961
  const operate = async (request: Request, notices: string[]) => {
840
962
  try {
841
963
  const body = warmOperationSchema.parse(await request.json());
842
- const reported = await controllerSession(
843
- await options.loadConfig(body.request),
964
+ const operationConfig = await options.loadConfig(body.request);
965
+ const sessionOptions: SessionOptions = {
966
+ imageId: options.imageId,
967
+ engineering: options.engineering,
968
+ operationId: body.operationId,
969
+ scratch: containerScratch,
970
+ initializeUser: body.initializeUser,
971
+ credentials: body.credentials,
972
+ notices,
973
+ };
974
+ if (body.operation === "review") {
975
+ const findings = await reviewControllerSession(
976
+ operationConfig,
977
+ sessionOptions,
978
+ online,
979
+ );
980
+ return {
981
+ reply: Response.json({
982
+ ok: true,
983
+ result: { findings } satisfies z.input<typeof reviewReplySchema>,
984
+ }),
985
+ finish: undefined,
986
+ };
987
+ }
988
+ const reported = await receiptSession(
989
+ operationConfig,
844
990
  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
- },
991
+ sessionOptions,
853
992
  online,
854
993
  ).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.
994
+ // A worker that died on an online change crashed generating it.
857
995
  if (
858
996
  body.operation !== "online-change" ||
859
997
  worker.alive(session.current)
860
998
  ) {
861
999
  throw error;
862
1000
  }
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 },
866
- );
1001
+ throw crashedOnlineChange(error);
867
1002
  });
868
1003
  return {
869
1004
  reply: Response.json({ ok: true, result: reported.receipt }),
@@ -876,6 +1011,10 @@ export const serveWarmController = async (
876
1011
  ok: false,
877
1012
  error: failureReason(error),
878
1013
  ...(requiresDownload(error) && { downloadRequired: true }),
1014
+ ...(error instanceof DownloadRequiredError && {
1015
+ findings: error.findings,
1016
+ messages: error.messages,
1017
+ }),
879
1018
  ...(rollback && { rollback }),
880
1019
  }),
881
1020
  finish: undefined,
@@ -104,7 +104,7 @@ const listFiles = async (
104
104
 
105
105
  /** A digest of named texts and files, which changes when a name or a file's content does. */
106
106
  const digestFiles = async (
107
- files: { name: string; path: string }[],
107
+ files: { name: string; read: () => Promise<Uint8Array | string> }[],
108
108
  texts: Record<string, string>,
109
109
  ) => {
110
110
  const hash = createHash("sha256");
@@ -113,7 +113,7 @@ const digestFiles = async (
113
113
  }
114
114
  for (const file of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
115
115
  hash.update(`${file.name}\0`);
116
- hash.update(await readFile(file.path));
116
+ hash.update(await file.read());
117
117
  hash.update("\0");
118
118
  }
119
119
  return hash.digest("hex");
@@ -134,7 +134,7 @@ export const containerCodeDigest = async () =>
134
134
  )
135
135
  ).map((name) => ({
136
136
  name: posix.join(posix.dirname(target), name),
137
- path: resolve(dirname(source), name),
137
+ read: () => readFile(resolve(dirname(source), name)),
138
138
  })),
139
139
  ),
140
140
  )
@@ -214,11 +214,38 @@ export const builderRecipe = async () =>
214
214
  digestFiles(
215
215
  (await recipeFiles()).map((name) => ({
216
216
  name,
217
- path: resolve(packageDirectory, name),
217
+ read: () => readFile(resolve(packageDirectory, name)),
218
218
  })),
219
219
  { manifest: JSON.stringify(await containerManifest()) },
220
220
  );
221
221
 
222
+ /** The Dockerfile's lines that install Bun, which runs tsPLC's own code and compiles nothing. */
223
+ const toolingLine = /\bbun\b/i;
224
+
225
+ /**
226
+ * The CODESYS engineering the builder image installs: its recipe without Bun and the third-party
227
+ * packages tsPLC's code runs on. Images with the same engineering compile a project alike, so an
228
+ * online change can follow a download made with another of them.
229
+ */
230
+ export const engineeringRecipe = async () =>
231
+ digestFiles(
232
+ (await recipeFiles()).map((name) => ({
233
+ name,
234
+ read: async () => {
235
+ const content = await readFile(resolve(packageDirectory, name));
236
+ if (name !== "docker/Dockerfile") {
237
+ return content;
238
+ }
239
+ return content
240
+ .toString("utf8")
241
+ .split("\n")
242
+ .filter((line) => !toolingLine.test(line))
243
+ .join("\n");
244
+ },
245
+ })),
246
+ {},
247
+ );
248
+
222
249
  /** The package's files `builderRecipe` covers, beside the third-party manifest. */
223
250
  export const recipeFiles = () =>
224
251
  listFiles(packageDirectory, resolve(packageDirectory, "docker"), recipeFile);
@@ -176,6 +176,9 @@ export const withWorkerLock = async <T>(
176
176
  };
177
177
 
178
178
  /** The caller holds withWorkerLock throughout a command, so the mailbox has one writer. */
179
+ /** CODESYS's process ended before it replied, which is how it crashes. */
180
+ export class CodesysExitedError extends Error {}
181
+
179
182
  export const createCodesysWorker = (config: ResolvedConfig) => {
180
183
  const host = createCodesysHost(config);
181
184
  const statePath = resolve(config.outDir, ".codesys/session.json");
@@ -240,6 +243,7 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
240
243
  error: z.string().optional(),
241
244
  diagnostics: z.array(compilerDiagnosticSchema).optional(),
242
245
  downloadRequired: z.literal(true).optional(),
246
+ messages: z.array(z.string()).optional(),
243
247
  id: z.literal(id),
244
248
  ok: z.boolean(),
245
249
  result: z.unknown(),
@@ -257,14 +261,16 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
257
261
  throw new CodesysCompilerError(message, response.data.diagnostics);
258
262
  }
259
263
  if (response.data.downloadRequired) {
260
- throw new DownloadRequiredError(message);
264
+ throw new DownloadRequiredError(message, {
265
+ messages: response.data.messages,
266
+ });
261
267
  }
262
268
  throw new Error(message);
263
269
  }
264
270
  return response.data.result;
265
271
  }
266
272
  if (!isProcessAlive(session.pid)) {
267
- throw new Error(
273
+ throw new CodesysExitedError(
268
274
  `CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,
269
275
  );
270
276
  }
package/src/images.ts CHANGED
@@ -2,7 +2,11 @@ import { copyFile, cp, mkdir, mkdtemp, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { resolve } from "node:path";
4
4
  import { dockerImage } from "@tsplc/config/build";
5
- import { builderRecipe, prepareDockerContext } from "./docker-context";
5
+ import {
6
+ builderRecipe,
7
+ engineeringRecipe,
8
+ prepareDockerContext,
9
+ } from "./docker-context";
6
10
  import { packageDirectory } from "./package-path";
7
11
 
8
12
  export const builderImage = dockerImage;
@@ -86,6 +90,8 @@ export async function buildBuilderImage(options: {
86
90
  `SETUP_PLATFORM=${options.setupPlatform}`,
87
91
  "--build-arg",
88
92
  `INSTALLER_SOURCE=${options.installer ? "installer-local" : "installer-download"}`,
93
+ "--build-arg",
94
+ `TSPLC_ENGINEERING=${await engineeringRecipe()}`,
89
95
  "--label",
90
96
  `${recipeLabel}=${await builderRecipe()}`,
91
97
  "--progress",
package/src/index.ts CHANGED
@@ -18,7 +18,9 @@ export {
18
18
  type ControllerLogin,
19
19
  findControllerLogin,
20
20
  inspectController,
21
+ type OnlineChangeReview,
21
22
  openControllerLogin,
23
+ reviewWarmController,
22
24
  settleWarmController,
23
25
  startWarmController,
24
26
  updateController,
@@ -26,6 +28,7 @@ export {
26
28
  } from "./controller-online";
27
29
  export {
28
30
  type ControllerResult,
31
+ DownloadRequiredError,
29
32
  explicitDownload,
30
33
  failureReason,
31
34
  type LoginCommand,
@@ -63,6 +66,11 @@ export {
63
66
  libraryIndex,
64
67
  validateLibrary,
65
68
  } from "./libraries";
69
+ export {
70
+ describeFinding,
71
+ type OnlineChangeFinding,
72
+ onlineChangeFindingSchema,
73
+ } from "./online-change-check";
66
74
  export {
67
75
  checkRawSources,
68
76
  inspectProjectController,