@tsplc/build 0.2.17 → 0.2.18

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.
Files changed (51) hide show
  1. package/dist/cli.js +628 -352
  2. package/dist/cli.js.map +30 -28
  3. package/dist/index.js +548 -387
  4. package/dist/index.js.map +27 -25
  5. package/dist/libraries.js +68 -27
  6. package/dist/libraries.js.map +3 -3
  7. package/docker/Dockerfile +2 -0
  8. package/docker/Dockerfile.dockerignore +4 -1
  9. package/docker/Dockerfile.source +3 -0
  10. package/docker/config.ts +10 -5
  11. package/docker/runner.ts +140 -127
  12. package/package.json +54 -53
  13. package/python/build.py +183 -124
  14. package/python/codesys_online.py +44 -45
  15. package/python/hardware.py +9 -9
  16. package/python/test_build.py +3 -3
  17. package/python/test_codesys_online.py +18 -12
  18. package/python/test_installer_packages.py +1 -0
  19. package/python/worker.py +11 -7
  20. package/src/artifacts.ts +82 -60
  21. package/src/build.ts +71 -62
  22. package/src/cli.ts +109 -100
  23. package/src/controller-online.ts +400 -425
  24. package/src/controller-protocol.ts +140 -0
  25. package/src/controller-session.ts +466 -397
  26. package/src/device-tree.ts +19 -15
  27. package/src/diagnostics.ts +59 -49
  28. package/src/docker-build.ts +217 -156
  29. package/src/docker-context.ts +49 -27
  30. package/src/docker-run.ts +137 -111
  31. package/src/engineering-settings.ts +42 -0
  32. package/src/host/codesys-command.ts +35 -34
  33. package/src/host/codesys-host.ts +157 -129
  34. package/src/host/codesys-worker.ts +318 -301
  35. package/src/host/windows-path.ts +63 -59
  36. package/src/import-request.ts +24 -0
  37. package/src/index.ts +37 -31
  38. package/src/io.ts +152 -116
  39. package/src/libraries.ts +214 -146
  40. package/src/package-path.ts +3 -1
  41. package/src/run.ts +132 -108
  42. package/src/runtime-status.ts +25 -19
  43. package/src/sources.ts +264 -225
  44. package/src/st/declarations.ts +181 -193
  45. package/src/st/lexer.ts +102 -118
  46. package/src/st/parse.ts +193 -171
  47. package/src/st/reader.ts +47 -42
  48. package/src/__tests__/fixtures/xml/fb-simple.xml +0 -40
  49. package/src/__tests__/fixtures/xml/fb-state-machine.xml +0 -86
  50. package/src/__tests__/fixtures/xml/prg-cyclic.xml +0 -44
  51. package/src/config.ts +0 -12
@@ -2,117 +2,136 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { cp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { z } from "zod";
5
- import type { ResolvedConfig } from "./config";
5
+ import { sha256Digest, type ResolvedConfig } from "@tsplc/config/build";
6
6
  import {
7
- type ControllerCredentials,
8
- controllerResultSchema,
9
- controllerTarget,
10
- explicitDownload,
11
- failureReason,
12
- loginCommandSchema,
13
- warmOperationSchema,
14
- } from "./controller-online";
7
+ type ControllerCredentials,
8
+ controllerResultSchema,
9
+ controllerTarget,
10
+ explicitDownload,
11
+ failureReason,
12
+ loginCommandSchema,
13
+ sameBaseline,
14
+ tracebackFailure,
15
+ warmOperationSchema,
16
+ } from "./controller-protocol";
15
17
  import {
16
- createCodesysWorker,
17
- withWorkerLock,
18
- withWorkerShutdown,
19
- writeJson,
18
+ createCodesysWorker,
19
+ withWorkerLock,
20
+ withWorkerShutdown,
21
+ writeJson,
20
22
  } from "./host/codesys-worker";
23
+ import { importRequest } from "./import-request";
21
24
  import { writeDeviceTree } from "./device-tree";
22
25
  import { toWindowsPath } from "./host/windows-path";
23
26
  import { loadSources } from "./sources";
24
27
 
25
28
  // Vendor code/data IDs are .NET Guid values derived from the compiler's data;
26
29
  // they do not carry RFC UUID version/variant bits.
27
- const guid = z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i);
28
- const hash = z.string().regex(/^[a-f0-9]{64}$/);
30
+ const guid = z
31
+ .string()
32
+ .regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i);
29
33
  const pointerSchema = z.strictObject({
30
- schemaVersion: z.literal(1),
31
- generation: z.uuid(),
34
+ schemaVersion: z.literal(1),
35
+ generation: z.uuid(),
32
36
  });
33
37
  const baselineSchema = controllerResultSchema.extend({
34
- objects: z.array(z.record(z.string(), z.unknown())),
35
- files: z.record(z.string(), hash),
38
+ objects: z.array(z.record(z.string(), z.unknown())),
39
+ files: z.record(z.string(), sha256Digest),
36
40
  });
37
- const sha256 = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
41
+ const sha256 = (data: Uint8Array) =>
42
+ createHash("sha256").update(data).digest("hex");
38
43
 
39
44
  const guidBytes = (value: string): Buffer => {
40
- const bytes = Buffer.from(value.replaceAll("-", ""), "hex");
41
- bytes.subarray(0, 4).reverse();
42
- bytes.subarray(4, 6).reverse();
43
- bytes.subarray(6, 8).reverse();
44
- return bytes;
45
+ const bytes = Buffer.from(value.replaceAll("-", ""), "hex");
46
+ bytes.subarray(0, 4).reverse();
47
+ bytes.subarray(4, 6).reverse();
48
+ bytes.subarray(6, 8).reverse();
49
+ return bytes;
45
50
  };
46
51
 
47
52
  /** Hash the complete project directory, including the vendor's downloaded reference. */
48
- const projectFiles = async (directory: string): Promise<Record<string, string>> => {
49
- const files: Record<string, string> = {};
50
- const visit = async (folder: string, prefix: string) => {
51
- for (const item of await readdir(folder, { withFileTypes: true })) {
52
- const name = prefix + item.name;
53
- if (item.isSymbolicLink()) {
54
- throw new Error(`Online project state contains a symlink: ${name}`);
55
- }
56
- if (item.isDirectory()) {
57
- await visit(resolve(folder, item.name), `${name}/`);
58
- } else if (item.isFile()) {
59
- files[name] = sha256(await readFile(resolve(folder, item.name)));
60
- }
61
- }
62
- };
63
- await visit(directory, "");
64
- return Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
53
+ const projectFiles = async (
54
+ directory: string,
55
+ ): Promise<Record<string, string>> => {
56
+ const files: Record<string, string> = {};
57
+ const visit = async (folder: string, prefix: string) => {
58
+ for (const item of await readdir(folder, { withFileTypes: true })) {
59
+ const name = prefix + item.name;
60
+ if (item.isSymbolicLink()) {
61
+ throw new Error(`Online project state contains a symlink: ${name}`);
62
+ }
63
+ if (item.isDirectory()) {
64
+ await visit(resolve(folder, item.name), `${name}/`);
65
+ } else if (item.isFile()) {
66
+ files[name] = sha256(await readFile(resolve(folder, item.name)));
67
+ }
68
+ }
69
+ };
70
+ await visit(directory, "");
71
+ return Object.fromEntries(
72
+ Object.entries(files).sort(([a], [b]) => a.localeCompare(b)),
73
+ );
65
74
  };
66
75
 
67
76
  /** Load the committed generation and prove it still matches this image, template and target. */
68
77
  const readBaseline = async (
69
- root: string,
70
- expected: Pick<z.infer<typeof baselineSchema>, "imageId" | "templateHash" | "target">,
78
+ root: string,
79
+ expected: Pick<
80
+ z.infer<typeof baselineSchema>,
81
+ "imageId" | "templateHash" | "target"
82
+ >,
71
83
  ) => {
72
- const pointer = pointerSchema.parse(
73
- JSON.parse(await readFile(resolve(root, "current.json"), "utf8")),
74
- );
75
- const previous = resolve(root, "generations", pointer.generation);
76
- const baseline = baselineSchema.parse(
77
- JSON.parse(await readFile(resolve(previous, "manifest.json"), "utf8")),
78
- );
79
- if (
80
- baseline.generation !== pointer.generation ||
81
- baseline.imageId !== expected.imageId ||
82
- baseline.templateHash !== expected.templateHash ||
83
- JSON.stringify(baseline.target) !== JSON.stringify(expected.target)
84
- ) {
85
- throw new Error(
86
- `Downloaded baseline uses a different image, template, controller or device tree; ${explicitDownload}`,
87
- );
88
- }
89
- const project = resolve(previous, "project");
90
- if (JSON.stringify(await projectFiles(project)) !== JSON.stringify(baseline.files)) {
91
- throw new Error(`Saved online project/reference files changed; ${explicitDownload}`);
92
- }
93
- return { baseline, project };
84
+ const pointer = pointerSchema.parse(
85
+ JSON.parse(await readFile(resolve(root, "current.json"), "utf8")),
86
+ );
87
+ const previous = resolve(root, "generations", pointer.generation);
88
+ const baseline = baselineSchema.parse(
89
+ JSON.parse(await readFile(resolve(previous, "manifest.json"), "utf8")),
90
+ );
91
+ if (
92
+ baseline.generation !== pointer.generation ||
93
+ !sameBaseline(baseline, expected)
94
+ ) {
95
+ throw new Error(
96
+ `Downloaded baseline uses a different image, template, controller or device tree; ${explicitDownload}`,
97
+ );
98
+ }
99
+ const project = resolve(previous, "project");
100
+ if (
101
+ JSON.stringify(await projectFiles(project)) !==
102
+ JSON.stringify(baseline.files)
103
+ ) {
104
+ throw new Error(
105
+ `Saved online project/reference files changed; ${explicitDownload}`,
106
+ );
107
+ }
108
+ return { baseline, project };
94
109
  };
95
110
 
96
111
  /** A CODESYS worker that handles the `online` request written to `requestDirectory` when `run`. */
97
112
  interface OnlineWorker {
98
- requestDirectory: string;
99
- run: () => Promise<unknown>;
100
- /** A candidate generation copied from baseline generation `baseline`, which the worker has open. */
101
- prepared?: { baseline: string; generation: string };
113
+ requestDirectory: string;
114
+ run: () => Promise<unknown>;
115
+ /** A candidate generation copied from baseline generation `baseline`, which the worker has open. */
116
+ prepared?: { baseline: string; generation: string };
102
117
  }
103
118
 
104
119
  /** A worker started for one operation and stopped after it. */
105
120
  const oneShotWorker = (config: ResolvedConfig): OnlineWorker => {
106
- const worker = createCodesysWorker(config);
107
- return {
108
- requestDirectory: resolve(config.outDir, ".codesys/controller"),
109
- run: () =>
110
- withWorkerShutdown(config, worker, () =>
111
- withWorkerLock(config, async () =>
112
- worker.request(await worker.launch(), { action: "online" }, config.timeouts.build),
113
- ),
114
- ),
115
- };
121
+ const worker = createCodesysWorker(config);
122
+ return {
123
+ requestDirectory: resolve(config.outDir, ".codesys/controller"),
124
+ run: () =>
125
+ withWorkerShutdown(config, worker, () =>
126
+ withWorkerLock(config, async () =>
127
+ worker.request(
128
+ await worker.launch(),
129
+ { action: "online" },
130
+ config.timeouts.build,
131
+ ),
132
+ ),
133
+ ),
134
+ };
116
135
  };
117
136
 
118
137
  /**
@@ -121,179 +140,196 @@ const oneShotWorker = (config: ResolvedConfig): OnlineWorker => {
121
140
  * user from the environment variables `config.online` names.
122
141
  */
123
142
  export const runControllerSession = async (
124
- config: ResolvedConfig,
125
- operation: "download" | "online-change" | "inspect",
126
- options: {
127
- imageId: string;
128
- operationId: string;
129
- initializeUser?: boolean;
130
- read?: string[];
131
- credentials?: ControllerCredentials;
132
- },
133
- worker?: OnlineWorker,
143
+ config: ResolvedConfig,
144
+ operation: "download" | "online-change" | "inspect",
145
+ options: {
146
+ imageId: string;
147
+ operationId: string;
148
+ initializeUser?: boolean;
149
+ read?: string[];
150
+ credentials?: ControllerCredentials;
151
+ },
152
+ worker?: OnlineWorker,
134
153
  ) => {
135
- if (!config.online) {
136
- throw new Error("Controller operations require online settings");
137
- }
138
- const root = resolve(config.outDir, ".codesys/controller");
139
- await mkdir(root, { recursive: true });
140
- const resultPath = resolve(root, "result.json");
141
- await rm(resultPath, { force: true });
142
- const templateHash = sha256(await readFile(config.template));
143
- // A different image, template, controller or device tree needs a fresh download from the template.
144
- const target = controllerTarget(config, config.online);
145
- const expected = { imageId: options.imageId, templateHash, target };
146
- // A download reuses the baseline when it still fits, and imports only what changed since.
147
- const previous =
148
- operation === "download"
149
- ? await readBaseline(root, expected).catch(() => undefined)
150
- : await readBaseline(root, expected);
151
- const baseline = previous?.baseline;
152
- if (options.initializeUser && operation !== "download") {
153
- throw new Error("Initial user creation requires an explicit download");
154
- }
155
- const opened = worker?.prepared;
156
- const prepared =
157
- operation !== "inspect" && opened?.baseline === baseline?.generation ? opened : undefined;
158
- const generation = prepared?.generation ?? randomUUID();
159
- const candidate = resolve(root, "generations", generation);
160
- const project = resolve(candidate, "project", "Application.project");
161
- await mkdir(resolve(candidate, "project"), { recursive: true });
162
- // Opens a copy of the baseline unless the worker opened one ahead; a download without a baseline saves the template here.
163
- if (previous && !prepared) {
164
- await cp(previous.project, resolve(candidate, "project"), {
165
- recursive: true,
166
- });
167
- }
168
- const jobConfig = {
169
- ...config,
170
- outDir: resolve(root, "jobs", options.operationId),
171
- };
172
- // The job directory keeps this operation's progress and descriptions; the worker its mailbox.
173
- const jobDirectory = resolve(jobConfig.outDir, ".codesys/controller");
174
- const online = worker ?? oneShotWorker(jobConfig);
175
- const { requestDirectory } = online;
176
- await mkdir(jobDirectory, { recursive: true });
177
- await mkdir(requestDirectory, { recursive: true });
178
- await rm(resolve(requestDirectory, "result.json"), { force: true });
179
- // Only this container reads it; the worker deletes it once CODESYS has the user.
180
- const credentialsFile =
181
- options.credentials && `/tmp/tsplc-credentials-${options.operationId}.json`;
182
- if (credentialsFile) {
183
- await writeFile(credentialsFile, JSON.stringify(options.credentials), { mode: 0o600 });
184
- }
185
- const sources = operation === "inspect" ? undefined : await loadSources(config);
186
- const request = {
187
- libraryReferences: config.libraryReferences,
188
- // Only a download without a baseline starts from the template; the others keep the downloaded project's tree.
189
- ...(operation === "download" &&
190
- !previous && {
191
- template: await toWindowsPath(config.template, config.codesys.wine),
192
- templateHash,
193
- // Kept across jobs: generating a device tree takes minutes, and the same inputs make the same one.
194
- caches: await toWindowsPath(root, config.codesys.wine),
195
- ...(config.deviceTree && {
196
- deviceTree: await writeDeviceTree(config.deviceTree, jobDirectory),
197
- devices: await toWindowsPath(jobDirectory, config.codesys.wine),
198
- }),
199
- }),
200
- libraries: await Promise.all(
201
- (config.libraries ?? []).map(async (library) => ({
202
- ...library,
203
- path: await toWindowsPath(library.path, config.codesys.wine),
204
- })),
205
- ),
206
- ...sources,
207
- task: config.task,
208
- ...(config.tasks && { tasks: config.tasks }),
209
- removeObjects: config.removeObjects,
210
- symbols: config.symbols,
211
- operation,
212
- initializeUser: options.initializeUser ?? false,
213
- online: config.online,
214
- controller: config.controller,
215
- project: await toWindowsPath(project, config.codesys.wine),
216
- progress: await toWindowsPath(resolve(jobDirectory, "progress.log"), config.codesys.wine),
217
- ...(credentialsFile && {
218
- credentialsFile: await toWindowsPath(credentialsFile, config.codesys.wine),
219
- }),
220
- baseline,
221
- read: options.read ?? [],
222
- };
223
- await writeFile(resolve(requestDirectory, "request.json"), JSON.stringify(request, null, 2));
224
- try {
225
- await online.run();
226
- const result = z
227
- .object({
228
- applicationGuid: guid,
229
- application: z.string().optional(),
230
- controllerIds: z.strictObject({ codeId: guid, dataId: guid }),
231
- state: z.string(),
232
- values: z.record(z.string(), z.string()),
233
- })
234
- .parse(JSON.parse(await readFile(resolve(requestDirectory, "result.json"), "utf8")));
235
- const receipt = controllerResultSchema.parse({
236
- ...result,
237
- application: result.application ?? baseline?.application,
238
- schemaVersion: 1,
239
- operationId: options.operationId,
240
- operation,
241
- imageId: options.imageId,
242
- templateHash,
243
- target,
244
- generation: operation === "inspect" ? baseline?.generation : generation,
245
- });
246
- if (operation !== "inspect") {
247
- const files = await projectFiles(resolve(candidate, "project"));
248
- if (!Object.keys(files).some((name) => name.endsWith(".compileinfo"))) {
249
- throw new Error(
250
- "CODESYS acknowledged the operation but no downloaded compiler reference was saved; candidate is retained for recovery",
251
- );
252
- }
253
- const bootIds = Object.keys(files).filter((name) =>
254
- name.endsWith(`.${receipt.applicationGuid}.bootinfo_guids`),
255
- );
256
- const expectedBootIds = Buffer.concat([
257
- guidBytes(receipt.controllerIds.codeId),
258
- guidBytes(receipt.controllerIds.dataId),
259
- ]);
260
- const bootReference = bootIds[0]?.replace(/_guids$/, "") ?? "";
261
- const downloadedReference = bootReference.replace(/\.bootinfo$/, ".compileinfo");
262
- if (
263
- bootIds.length !== 1 ||
264
- !files[bootReference] ||
265
- files[bootReference] === sha256(new Uint8Array()) ||
266
- files[bootReference] !== files[downloadedReference] ||
267
- !(await readFile(resolve(candidate, "project", bootIds[0] ?? ""))).equals(expectedBootIds)
268
- ) {
269
- throw new Error(
270
- "CODESYS acknowledged the operation but matching boot reference was not saved; candidate is retained for recovery",
271
- );
272
- }
273
- await writeJson(resolve(candidate, "manifest.json"), {
274
- ...receipt,
275
- objects: sources?.objects,
276
- files,
277
- });
278
- // Each generation is immutable. A single atomic pointer commits it only
279
- // after controller acknowledgement and matching downloaded/boot references.
280
- await writeJson(resolve(root, "current.json"), {
281
- schemaVersion: 1,
282
- generation,
283
- });
284
- }
285
- await writeJson(resultPath, receipt);
286
- return receipt;
287
- } finally {
288
- if (credentialsFile) await rm(credentialsFile, { force: true });
289
- // The worker closed an opened project this operation didn't use.
290
- if (opened && opened !== prepared) {
291
- await rm(resolve(root, "generations", opened.generation), { recursive: true, force: true });
292
- }
293
- if (operation === "inspect") {
294
- await rm(candidate, { recursive: true, force: true });
295
- }
296
- }
154
+ if (!config.online) {
155
+ throw new Error("Controller operations require online settings");
156
+ }
157
+ const root = resolve(config.outDir, ".codesys/controller");
158
+ await mkdir(root, { recursive: true });
159
+ const resultPath = resolve(root, "result.json");
160
+ await rm(resultPath, { force: true });
161
+ const templateHash = sha256(await readFile(config.template));
162
+ // A different image, template, controller or device tree needs a fresh download from the template.
163
+ const target = controllerTarget(config, config.online);
164
+ const expected = { imageId: options.imageId, templateHash, target };
165
+ // A download reuses the baseline when it still fits, and imports only what changed since.
166
+ const previous =
167
+ operation === "download"
168
+ ? await readBaseline(root, expected).catch(() => undefined)
169
+ : await readBaseline(root, expected);
170
+ const baseline = previous?.baseline;
171
+ if (options.initializeUser && operation !== "download") {
172
+ throw new Error("Initial user creation requires an explicit download");
173
+ }
174
+ const opened = worker?.prepared;
175
+ const prepared =
176
+ operation !== "inspect" && opened?.baseline === baseline?.generation
177
+ ? opened
178
+ : undefined;
179
+ const generation = prepared?.generation ?? randomUUID();
180
+ const candidate = resolve(root, "generations", generation);
181
+ const project = resolve(candidate, "project", "Application.project");
182
+ await mkdir(resolve(candidate, "project"), { recursive: true });
183
+ // Opens a copy of the baseline unless the worker opened one ahead; a download without a baseline saves the template here.
184
+ if (previous && !prepared) {
185
+ await cp(previous.project, resolve(candidate, "project"), {
186
+ recursive: true,
187
+ });
188
+ }
189
+ const jobConfig = {
190
+ ...config,
191
+ outDir: resolve(root, "jobs", options.operationId),
192
+ };
193
+ // The job directory keeps this operation's progress and descriptions; the worker its mailbox.
194
+ const jobDirectory = resolve(jobConfig.outDir, ".codesys/controller");
195
+ const online = worker ?? oneShotWorker(jobConfig);
196
+ const { requestDirectory } = online;
197
+ await mkdir(jobDirectory, { recursive: true });
198
+ await mkdir(requestDirectory, { recursive: true });
199
+ await rm(resolve(requestDirectory, "result.json"), { force: true });
200
+ // Only this container reads it; the worker deletes it once CODESYS has the user.
201
+ const credentialsFile =
202
+ options.credentials && `/tmp/tsplc-credentials-${options.operationId}.json`;
203
+ if (credentialsFile) {
204
+ await writeFile(credentialsFile, JSON.stringify(options.credentials), {
205
+ mode: 0o600,
206
+ });
207
+ }
208
+ const sources = operation === "inspect" ? null : await loadSources(config);
209
+ const request = {
210
+ libraryReferences: config.libraryReferences,
211
+ // Only a download without a baseline starts from the template; the others keep the downloaded project's tree.
212
+ ...(operation === "download" &&
213
+ !previous && {
214
+ template: await toWindowsPath(config.template, config.codesys.wine),
215
+ templateHash,
216
+ // Kept across jobs: generating a device tree takes minutes, and the same inputs make the same one.
217
+ caches: await toWindowsPath(root, config.codesys.wine),
218
+ ...(config.deviceTree && {
219
+ deviceTree: await writeDeviceTree(config.deviceTree, jobDirectory),
220
+ devices: await toWindowsPath(jobDirectory, config.codesys.wine),
221
+ }),
222
+ }),
223
+ ...(await importRequest(config, sources)),
224
+ operation,
225
+ initializeUser: options.initializeUser ?? false,
226
+ online: config.online,
227
+ controller: config.controller,
228
+ project: await toWindowsPath(project, config.codesys.wine),
229
+ progress: await toWindowsPath(
230
+ resolve(jobDirectory, "progress.log"),
231
+ config.codesys.wine,
232
+ ),
233
+ ...(credentialsFile && {
234
+ credentialsFile: await toWindowsPath(
235
+ credentialsFile,
236
+ config.codesys.wine,
237
+ ),
238
+ }),
239
+ baseline,
240
+ read: options.read ?? [],
241
+ };
242
+ await writeFile(
243
+ resolve(requestDirectory, "request.json"),
244
+ JSON.stringify(request, null, 2),
245
+ );
246
+ try {
247
+ await online.run();
248
+ const result = z
249
+ .object({
250
+ applicationGuid: guid,
251
+ application: z.string().optional(),
252
+ controllerIds: z.strictObject({ codeId: guid, dataId: guid }),
253
+ state: z.string(),
254
+ values: z.record(z.string(), z.string()),
255
+ })
256
+ .parse(
257
+ JSON.parse(
258
+ await readFile(resolve(requestDirectory, "result.json"), "utf8"),
259
+ ),
260
+ );
261
+ const receipt = controllerResultSchema.parse({
262
+ ...result,
263
+ application: result.application ?? baseline?.application,
264
+ schemaVersion: 1,
265
+ operationId: options.operationId,
266
+ operation,
267
+ imageId: options.imageId,
268
+ templateHash,
269
+ target,
270
+ generation: operation === "inspect" ? baseline?.generation : generation,
271
+ });
272
+ if (operation !== "inspect") {
273
+ const files = await projectFiles(resolve(candidate, "project"));
274
+ if (!Object.keys(files).some((name) => name.endsWith(".compileinfo"))) {
275
+ throw new Error(
276
+ "CODESYS acknowledged the operation but no downloaded compiler reference was saved; candidate is retained for recovery",
277
+ );
278
+ }
279
+ const bootIds = Object.keys(files).filter((name) =>
280
+ name.endsWith(`.${receipt.applicationGuid}.bootinfo_guids`),
281
+ );
282
+ const expectedBootIds = Buffer.concat([
283
+ guidBytes(receipt.controllerIds.codeId),
284
+ guidBytes(receipt.controllerIds.dataId),
285
+ ]);
286
+ const bootReference = bootIds[0]?.replace(/_guids$/, "") ?? "";
287
+ const downloadedReference = bootReference.replace(
288
+ /\.bootinfo$/,
289
+ ".compileinfo",
290
+ );
291
+ if (
292
+ bootIds.length !== 1 ||
293
+ !files[bootReference] ||
294
+ files[bootReference] === sha256(new Uint8Array()) ||
295
+ files[bootReference] !== files[downloadedReference] ||
296
+ !(
297
+ await readFile(resolve(candidate, "project", bootIds[0] ?? ""))
298
+ ).equals(expectedBootIds)
299
+ ) {
300
+ throw new Error(
301
+ "CODESYS acknowledged the operation but matching boot reference was not saved; candidate is retained for recovery",
302
+ );
303
+ }
304
+ await writeJson(resolve(candidate, "manifest.json"), {
305
+ ...receipt,
306
+ objects: sources?.objects,
307
+ files,
308
+ });
309
+ // Each generation is immutable. A single atomic pointer commits it only
310
+ // after controller acknowledgement and matching downloaded/boot references.
311
+ await writeJson(resolve(root, "current.json"), {
312
+ schemaVersion: 1,
313
+ generation,
314
+ });
315
+ }
316
+ await writeJson(resultPath, receipt);
317
+ return receipt;
318
+ } finally {
319
+ if (credentialsFile) {
320
+ await rm(credentialsFile, { force: true });
321
+ }
322
+ // The worker closed an opened project this operation didn't use.
323
+ if (opened && opened !== prepared) {
324
+ await rm(resolve(root, "generations", opened.generation), {
325
+ recursive: true,
326
+ force: true,
327
+ });
328
+ }
329
+ if (operation === "inspect") {
330
+ await rm(candidate, { recursive: true, force: true });
331
+ }
332
+ }
297
333
  };
298
334
 
299
335
  /**
@@ -301,70 +337,83 @@ export const runControllerSession = async (
301
337
  * from the committed baseline, and serves its commands on `port` until a DELETE closes it.
302
338
  */
303
339
  export const serveControllerLogin = async (
304
- config: ResolvedConfig,
305
- options: { imageId: string; port: number },
340
+ config: ResolvedConfig,
341
+ options: { imageId: string; port: number },
306
342
  ) => {
307
- if (!config.online) {
308
- throw new Error("Controller logins require online settings");
309
- }
310
- const root = resolve(config.outDir, ".codesys/controller");
311
- const { baseline, project } = await readBaseline(root, {
312
- imageId: options.imageId,
313
- templateHash: sha256(await readFile(config.template)),
314
- target: controllerTarget(config, config.online),
315
- });
316
- const jobConfig = { ...config, outDir: resolve(root, "login") };
317
- await rm(jobConfig.outDir, { recursive: true, force: true });
318
- // CODESYS writes into an open project, and the committed baseline must not change.
319
- await cp(project, resolve(jobConfig.outDir, "project"), { recursive: true });
320
- const worker = createCodesysWorker(jobConfig);
321
- await withWorkerShutdown(jobConfig, worker, () =>
322
- withWorkerLock(jobConfig, async () => {
323
- const session = await worker.launch();
324
- const send = (command: Record<string, unknown>) =>
325
- worker.request(session, { action: "login", arguments: command }, config.timeouts.build);
326
- await send({
327
- command: "open",
328
- project: await toWindowsPath(
329
- resolve(jobConfig.outDir, "project", "Application.project"),
330
- config.codesys.wine,
331
- ),
332
- online: config.online,
333
- baseline,
334
- });
335
- const closed = Promise.withResolvers<void>();
336
- // The worker has one mailbox, so commands run one at a time.
337
- let previous: Promise<unknown> = Promise.resolve();
338
- const server = Bun.serve({
339
- // The agent calls through `docker exec`, so nothing else on the network can.
340
- hostname: "127.0.0.1",
341
- port: options.port,
342
- idleTimeout: 0,
343
- fetch: async (request) => {
344
- if (request.method === "GET") return Response.json({ ok: true });
345
- const close = request.method === "DELETE";
346
- const command = close
347
- ? { command: "close" }
348
- : loginCommandSchema.parse(await request.json());
349
- const result = previous.then(() => send(command));
350
- previous = result.catch(() => undefined);
351
- try {
352
- return Response.json({ ok: true, result: await result });
353
- } catch (error) {
354
- // The login raises a RuntimeError to tell the user something; any other error comes
355
- // from CODESYS, and only its traceback shows which call failed.
356
- const traceback = error instanceof Error ? error.message : String(error);
357
- const raised = traceback.trim().split("\n").at(-1)?.startsWith("RuntimeError: ");
358
- return Response.json({ ok: false, error: raised ? failureReason(error) : traceback });
359
- } finally {
360
- if (close) closed.resolve();
361
- }
362
- },
363
- });
364
- await closed.promise;
365
- await server.stop();
366
- }),
367
- );
343
+ if (!config.online) {
344
+ throw new Error("Controller logins require online settings");
345
+ }
346
+ const root = resolve(config.outDir, ".codesys/controller");
347
+ const { baseline, project } = await readBaseline(root, {
348
+ imageId: options.imageId,
349
+ templateHash: sha256(await readFile(config.template)),
350
+ target: controllerTarget(config, config.online),
351
+ });
352
+ const jobConfig = { ...config, outDir: resolve(root, "login") };
353
+ await rm(jobConfig.outDir, { recursive: true, force: true });
354
+ // CODESYS writes into an open project, and the committed baseline must not change.
355
+ await cp(project, resolve(jobConfig.outDir, "project"), { recursive: true });
356
+ const worker = createCodesysWorker(jobConfig);
357
+ await withWorkerShutdown(jobConfig, worker, () =>
358
+ withWorkerLock(jobConfig, async () => {
359
+ const session = await worker.launch();
360
+ const send = (command: Record<string, unknown>) =>
361
+ worker.request(
362
+ session,
363
+ { action: "login", arguments: command },
364
+ config.timeouts.build,
365
+ );
366
+ await send({
367
+ command: "open",
368
+ project: await toWindowsPath(
369
+ resolve(jobConfig.outDir, "project", "Application.project"),
370
+ config.codesys.wine,
371
+ ),
372
+ online: config.online,
373
+ baseline,
374
+ });
375
+ const closed = Promise.withResolvers<void>();
376
+ // The worker has one mailbox, so commands run one at a time.
377
+ let previous: Promise<unknown> = Promise.resolve();
378
+ const server = Bun.serve({
379
+ // The agent calls through `docker exec`, so nothing else on the network can.
380
+ hostname: "127.0.0.1",
381
+ port: options.port,
382
+ idleTimeout: 0,
383
+ fetch: async (request) => {
384
+ if (request.method === "GET") {
385
+ return Response.json({ ok: true });
386
+ }
387
+ const close = request.method === "DELETE";
388
+ const command = close
389
+ ? { command: "close" }
390
+ : loginCommandSchema.parse(await request.json());
391
+ const result = previous.then(() => send(command));
392
+ previous = result.catch(() => undefined);
393
+ try {
394
+ return Response.json({ ok: true, result: await result });
395
+ } catch (error) {
396
+ // The login raises a RuntimeError to tell the user something; any other error comes
397
+ // from CODESYS, and only its traceback shows which call failed.
398
+ const traceback =
399
+ error instanceof Error ? error.message : String(error);
400
+ const raised =
401
+ tracebackFailure(traceback).startsWith("RuntimeError: ");
402
+ return Response.json({
403
+ ok: false,
404
+ error: raised ? failureReason(error) : traceback,
405
+ });
406
+ } finally {
407
+ if (close) {
408
+ closed.resolve();
409
+ }
410
+ }
411
+ },
412
+ });
413
+ await closed.promise;
414
+ await server.stop();
415
+ }),
416
+ );
368
417
  };
369
418
 
370
419
  /**
@@ -374,87 +423,107 @@ export const serveControllerLogin = async (
374
423
  * none while a login is open, so this container doesn't hold the output directory's flock.
375
424
  */
376
425
  export const serveWarmController = async (
377
- config: ResolvedConfig,
378
- options: {
379
- imageId: string;
380
- port: number;
381
- loadConfig: (path: string) => Promise<ResolvedConfig>;
382
- },
426
+ config: ResolvedConfig,
427
+ options: {
428
+ imageId: string;
429
+ port: number;
430
+ loadConfig: (path: string) => Promise<ResolvedConfig>;
431
+ },
383
432
  ) => {
384
- const warmConfig = { ...config, outDir: resolve(config.outDir, ".codesys/controller/warm") };
385
- // One container owns this directory at a time; a stopped one can leave its worker session behind.
386
- await rm(warmConfig.outDir, { recursive: true, force: true });
387
- const worker = createCodesysWorker(warmConfig);
388
- const session = await worker.launch();
389
- const root = resolve(config.outDir, ".codesys/controller");
390
- const online: OnlineWorker = {
391
- requestDirectory: resolve(warmConfig.outDir, ".codesys/controller"),
392
- run: () => worker.request(session, { action: "online" }, config.timeouts.build),
393
- };
394
- /** Opens a copy of the committed baseline, so the next online change needn't open one. */
395
- const prepare = async () => {
396
- const pointer = await readFile(resolve(root, "current.json"), "utf8").catch(() => undefined);
397
- if (!pointer) return;
398
- const baseline = pointerSchema.parse(JSON.parse(pointer)).generation;
399
- const generation = randomUUID();
400
- const project = resolve(root, "generations", generation, "project");
401
- await cp(resolve(root, "generations", baseline, "project"), project, { recursive: true });
402
- await worker.request(
403
- session,
404
- {
405
- action: "prepare",
406
- project: await toWindowsPath(resolve(project, "Application.project"), config.codesys.wine),
407
- },
408
- config.timeouts.build,
409
- );
410
- online.prepared = { baseline, generation };
411
- };
412
- // A failed prepare only costs the next operation the time to open the project itself.
413
- const prepareNext = () =>
414
- prepare().catch((error: unknown) => {
415
- console.error(`Could not open the next project ahead: ${failureReason(error)}`);
416
- });
417
- let preparing = prepareNext();
418
- Bun.serve({
419
- hostname: "127.0.0.1",
420
- port: options.port,
421
- idleTimeout: 0,
422
- fetch: async (request) => {
423
- if (request.method === "GET")
424
- return Response.json(
425
- worker.alive(session) ? { ok: true } : { ok: false, error: "CODESYS exited" },
426
- );
427
- await preparing;
428
- try {
429
- const body = warmOperationSchema.parse(await request.json());
430
- const result = await runControllerSession(
431
- await options.loadConfig(body.request),
432
- body.operation,
433
- {
434
- imageId: options.imageId,
435
- operationId: body.operationId,
436
- initializeUser: body.initializeUser,
437
- credentials: body.credentials,
438
- },
439
- online,
440
- ).catch((error: unknown) => {
441
- // CODESYS crashes generating an online change that moves a block holding a network
442
- // client, such as a job with a service call. The controller keeps its running program.
443
- if (body.operation !== "online-change" || worker.alive(session)) throw error;
444
- throw new Error(
445
- `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
446
- { cause: error },
447
- );
448
- });
449
- return Response.json({ ok: true, result });
450
- } catch (error) {
451
- return Response.json({ ok: false, error: failureReason(error) });
452
- } finally {
453
- online.prepared = undefined;
454
- preparing = prepareNext();
455
- }
456
- },
457
- });
458
- // Serves until the container stops; the next one clears what this one leaves behind.
459
- await new Promise(() => {});
433
+ const warmConfig = {
434
+ ...config,
435
+ outDir: resolve(config.outDir, ".codesys/controller/warm"),
436
+ };
437
+ // One container owns this directory at a time; a stopped one can leave its worker session behind.
438
+ await rm(warmConfig.outDir, { recursive: true, force: true });
439
+ const worker = createCodesysWorker(warmConfig);
440
+ const session = await worker.launch();
441
+ const root = resolve(config.outDir, ".codesys/controller");
442
+ const online: OnlineWorker = {
443
+ requestDirectory: resolve(warmConfig.outDir, ".codesys/controller"),
444
+ run: () =>
445
+ worker.request(session, { action: "online" }, config.timeouts.build),
446
+ };
447
+ /** Opens a copy of the committed baseline, so the next online change needn't open one. */
448
+ const prepare = async () => {
449
+ const pointer = await readFile(resolve(root, "current.json"), "utf8").catch(
450
+ () => undefined,
451
+ );
452
+ if (!pointer) {
453
+ return;
454
+ }
455
+ const baseline = pointerSchema.parse(JSON.parse(pointer)).generation;
456
+ const generation = randomUUID();
457
+ const project = resolve(root, "generations", generation, "project");
458
+ await cp(resolve(root, "generations", baseline, "project"), project, {
459
+ recursive: true,
460
+ });
461
+ await worker.request(
462
+ session,
463
+ {
464
+ action: "prepare",
465
+ project: await toWindowsPath(
466
+ resolve(project, "Application.project"),
467
+ config.codesys.wine,
468
+ ),
469
+ },
470
+ config.timeouts.build,
471
+ );
472
+ online.prepared = { baseline, generation };
473
+ };
474
+ // A failed prepare only costs the next operation the time to open the project itself.
475
+ const prepareNext = () =>
476
+ prepare().catch((error: unknown) => {
477
+ console.error(
478
+ `Could not open the next project ahead: ${failureReason(error)}`,
479
+ );
480
+ });
481
+ let preparing = prepareNext();
482
+ Bun.serve({
483
+ hostname: "127.0.0.1",
484
+ port: options.port,
485
+ idleTimeout: 0,
486
+ fetch: async (request) => {
487
+ if (request.method === "GET") {
488
+ return Response.json(
489
+ worker.alive(session)
490
+ ? { ok: true }
491
+ : { ok: false, error: "CODESYS exited" },
492
+ );
493
+ }
494
+ await preparing;
495
+ try {
496
+ const body = warmOperationSchema.parse(await request.json());
497
+ const result = await runControllerSession(
498
+ await options.loadConfig(body.request),
499
+ body.operation,
500
+ {
501
+ imageId: options.imageId,
502
+ operationId: body.operationId,
503
+ initializeUser: body.initializeUser,
504
+ credentials: body.credentials,
505
+ },
506
+ online,
507
+ ).catch((error: unknown) => {
508
+ // CODESYS crashes generating an online change that moves a block holding a network
509
+ // client, such as a job with a service call. The controller keeps its running program.
510
+ if (body.operation !== "online-change" || worker.alive(session)) {
511
+ throw error;
512
+ }
513
+ throw new Error(
514
+ `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
515
+ { cause: error },
516
+ );
517
+ });
518
+ return Response.json({ ok: true, result });
519
+ } catch (error) {
520
+ return Response.json({ ok: false, error: failureReason(error) });
521
+ } finally {
522
+ online.prepared = undefined;
523
+ preparing = prepareNext();
524
+ }
525
+ },
526
+ });
527
+ // Serves until the container stops; the next one clears what this one leaves behind.
528
+ await new Promise(() => {});
460
529
  };