@tsplc/build 0.2.16 → 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
@@ -1,258 +1,177 @@
1
- import { execFile } from "node:child_process";
2
1
  import { existsSync } from "node:fs";
3
2
  import { createHash, randomUUID } from "node:crypto";
4
3
  import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
5
4
  import { tmpdir } from "node:os";
6
5
  import { posix, resolve } from "node:path";
7
6
  import { setTimeout as delay } from "node:timers/promises";
8
- import { promisify } from "node:util";
9
7
  import { z } from "zod";
10
- import { controllerSchema, dockerImage, type ResolvedConfig } from "./config";
8
+ import { dockerImage, type ResolvedConfig } from "@tsplc/config/build";
9
+ import {
10
+ type Baseline,
11
+ type ControllerCredentials,
12
+ type ControllerResult,
13
+ controllerResultSchema,
14
+ controllerTarget,
15
+ failureReason,
16
+ imageIdSchema,
17
+ type LoginCommand,
18
+ loginResultSchema,
19
+ sameBaseline,
20
+ tracebackFailure,
21
+ type warmOperationSchema,
22
+ } from "./controller-protocol.ts";
11
23
  import { controllerFailureFile } from "./diagnostics.ts";
12
- import { prepareContainerRun, runDocker, writeOperationRequest } from "./docker-run.ts";
24
+ import {
25
+ captureDocker,
26
+ prepareContainerRun,
27
+ runDocker,
28
+ writeOperationRequest,
29
+ } from "./docker-run.ts";
13
30
 
14
- const execute = promisify(execFile);
15
- const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
16
- const endpointSchema = z.strictObject({
17
- host: z.string().nonempty(),
18
- port: z.number().int().min(1).max(65535),
19
- });
20
- export const controllerResultSchema = z.strictObject({
21
- schemaVersion: z.literal(1),
22
- operationId: z.uuid(),
23
- operation: z.enum(["download", "online-change", "inspect"]),
24
- imageId: imageIdSchema,
25
- templateHash: z.string().regex(/^[a-f0-9]{64}$/),
26
- target: z.strictObject({
27
- network: z.string().nonempty(),
28
- gateway: endpointSchema,
29
- device: endpointSchema,
30
- controller: controllerSchema.optional(),
31
- deviceTree: z
32
- .string()
33
- .regex(/^[a-f0-9]{64}$/)
34
- .optional(),
35
- }),
36
- generation: z.string().nonempty(),
37
- application: z.string().nonempty(),
38
- applicationGuid: z.string().nonempty(),
39
- controllerIds: z.strictObject({
40
- codeId: z.string().nonempty(),
41
- dataId: z.string().nonempty(),
42
- }),
43
- state: z.string().nonempty(),
44
- values: z.record(z.string(), z.string()),
45
- });
46
- export type ControllerResult = z.infer<typeof controllerResultSchema>;
47
- export const controllerCredentialsSchema = z.strictObject({
48
- username: z.string().nonempty(),
49
- password: z.string().nonempty(),
50
- });
51
- export type ControllerCredentials = z.infer<typeof controllerCredentialsSchema>;
52
-
53
- /** One operation for the warm builder container; `request` is the container path of its config. */
54
- export const warmOperationSchema = z.strictObject({
55
- operation: z.enum(["download", "online-change"]),
56
- operationId: z.uuid(),
57
- request: z.string().nonempty(),
58
- initializeUser: z.boolean(),
59
- credentials: controllerCredentialsSchema.optional(),
60
- });
61
-
62
- /** The worker reports a Python traceback; its last line names the failure. */
63
- export const failureReason = (error: unknown) => {
64
- const message = error instanceof Error ? error.message : String(error);
65
- return (message.trim().split("\n").at(-1) ?? message).replace(/^\w+: /, "");
66
- };
67
-
68
- export type ControllerUpdateOptions = {
69
- initializeUser?: boolean;
70
- read?: string[];
71
- };
72
-
73
- /**
74
- * What a download binds the controller to. An online change needs the same connection, controller
75
- * and device tree, because it only recompiles the program into the downloaded project.
76
- */
77
- export const controllerTarget = (
78
- config: ResolvedConfig,
79
- online: NonNullable<ResolvedConfig["online"]>,
80
- ) => ({
81
- network: online.network,
82
- gateway: online.gateway,
83
- device: online.device,
84
- controller: config.controller,
85
- ...(config.deviceTree && {
86
- deviceTree: createHash("sha256").update(JSON.stringify(config.deviceTree)).digest("hex"),
87
- }),
88
- });
31
+ export interface ControllerUpdateOptions {
32
+ initializeUser?: boolean;
33
+ read?: string[];
34
+ }
89
35
 
90
36
  /** The controller user's environment variables, which a container started now passes to CODESYS. */
91
37
  const credentialEnvironment = (config: ResolvedConfig) => {
92
- const names = config.online?.credentials
93
- ? [config.online.credentials.usernameEnv, config.online.credentials.passwordEnv]
94
- : [];
95
- for (const name of names) {
96
- if (process.env[name] === undefined) {
97
- throw new Error(`Controller credential environment variable ${name} is not set`);
98
- }
99
- }
100
- return names;
38
+ const names = config.online?.credentials
39
+ ? [
40
+ config.online.credentials.usernameEnv,
41
+ config.online.credentials.passwordEnv,
42
+ ]
43
+ : [];
44
+ for (const name of names) {
45
+ if (process.env[name] === undefined) {
46
+ throw new Error(
47
+ `Controller credential environment variable ${name} is not set`,
48
+ );
49
+ }
50
+ }
51
+ return names;
101
52
  };
102
53
 
103
54
  /** Checks the settings every engineering connection needs and names its builder image and target. */
104
55
  const controllerConnection = async (config: ResolvedConfig) => {
105
- if (!config.docker || !config.online) {
106
- throw new Error(
107
- "Docker image and online gateway/device configuration are required for controller operations",
108
- );
109
- }
110
- const { stdout } = await execute(
111
- "docker",
112
- ["image", "inspect", "--format", "{{.Id}}", dockerImage],
113
- { timeout: config.timeouts.hostCommand },
114
- ).catch((cause: unknown) => {
115
- throw new Error(
116
- `Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,
117
- { cause },
118
- );
119
- });
120
- return {
121
- imageId: imageIdSchema.parse(stdout.trim()),
122
- templateHash: createHash("sha256")
123
- .update(await readFile(config.template))
124
- .digest("hex"),
125
- target: controllerTarget(config, config.online),
126
- };
56
+ if (!config.docker || !config.online) {
57
+ throw new Error(
58
+ "Docker image and online gateway/device configuration are required for controller operations",
59
+ );
60
+ }
61
+ const { stdout } = await captureDocker(
62
+ ["image", "inspect", "--format", "{{.Id}}", dockerImage],
63
+ config.timeouts.hostCommand,
64
+ ).catch((cause: unknown) => {
65
+ throw new Error(
66
+ `Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,
67
+ { cause },
68
+ );
69
+ });
70
+ return {
71
+ imageId: imageIdSchema.parse(stdout.trim()),
72
+ templateHash: createHash("sha256")
73
+ .update(await readFile(config.template))
74
+ .digest("hex"),
75
+ target: controllerTarget(config, config.online),
76
+ };
127
77
  };
128
78
 
129
79
  const checkReceipt = (
130
- result: ControllerResult,
131
- expected: Pick<
132
- ControllerResult,
133
- "operationId" | "operation" | "imageId" | "templateHash" | "target"
134
- >,
135
- diagnostics: string,
80
+ result: ControllerResult,
81
+ expected: Baseline & Pick<ControllerResult, "operationId" | "operation">,
82
+ diagnostics: string,
136
83
  ) => {
137
- if (
138
- result.operationId !== expected.operationId ||
139
- result.operation !== expected.operation ||
140
- result.imageId !== expected.imageId ||
141
- result.templateHash !== expected.templateHash ||
142
- JSON.stringify(result.target) !== JSON.stringify(expected.target)
143
- ) {
144
- throw new Error(
145
- `Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`,
146
- );
147
- }
148
- return result;
84
+ if (
85
+ result.operationId !== expected.operationId ||
86
+ result.operation !== expected.operation ||
87
+ !sameBaseline(result, expected)
88
+ ) {
89
+ throw new Error(
90
+ `Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`,
91
+ );
92
+ }
93
+ return result;
149
94
  };
150
95
 
151
96
  const controllerOperation = async (
152
- config: ResolvedConfig,
153
- operation: ControllerResult["operation"],
154
- options: ControllerUpdateOptions,
97
+ config: ResolvedConfig,
98
+ operation: ControllerResult["operation"],
99
+ options: ControllerUpdateOptions,
155
100
  ): Promise<ControllerResult> => {
156
- const environmentNames = credentialEnvironment(config);
157
- const { imageId, templateHash, target } = await controllerConnection(config);
158
- const operationId = randomUUID();
159
- const requestDirectory = await mkdtemp(resolve(tmpdir(), "codesys-controller-"));
160
- const diagnostics = resolve(config.outDir, ".codesys/controller");
161
- const failure = resolve(config.outDir, controllerFailureFile);
162
- try {
163
- await mkdir(config.outDir, { recursive: true });
164
- await rm(failure, { force: true });
165
- await runDocker(
166
- [
167
- "run",
168
- "--rm",
169
- ...(await prepareContainerRun(config, requestDirectory, {
170
- network: target.network,
171
- environment: environmentNames,
172
- sources: operation !== "inspect",
173
- })),
174
- imageId,
175
- operation,
176
- "--request",
177
- "/input/config.json",
178
- "--operation-id",
179
- operationId,
180
- "--image-id",
181
- imageId,
182
- ...(options.initializeUser ? ["--initialize-user"] : []),
183
- ...(options.read ? ["--read", JSON.stringify(options.read)] : []),
184
- ],
185
- (status) =>
186
- `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`,
187
- ).catch(async (cause: unknown) => {
188
- if (!existsSync(failure)) throw cause;
189
- // A CODESYS failure arrives as a Python traceback, whose last line names it.
190
- const reason = (await readFile(failure, "utf8")).trim().split("\n").at(-1);
191
- throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, { cause });
192
- });
193
- const result = await readFile(resolve(diagnostics, "result.json"), "utf8")
194
- .then((content) => controllerResultSchema.parse(JSON.parse(content)))
195
- .catch((cause: unknown) => {
196
- throw new Error(
197
- `Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`,
198
- { cause },
199
- );
200
- });
201
- return checkReceipt(
202
- result,
203
- { operationId, operation, imageId, templateHash, target },
204
- diagnostics,
205
- );
206
- } finally {
207
- await rm(requestDirectory, { recursive: true, force: true });
208
- }
101
+ const environmentNames = credentialEnvironment(config);
102
+ const { imageId, templateHash, target } = await controllerConnection(config);
103
+ const operationId = randomUUID();
104
+ const requestDirectory = await mkdtemp(
105
+ resolve(tmpdir(), "codesys-controller-"),
106
+ );
107
+ const diagnostics = resolve(config.outDir, ".codesys/controller");
108
+ const failure = resolve(config.outDir, controllerFailureFile);
109
+ try {
110
+ await mkdir(config.outDir, { recursive: true });
111
+ await rm(failure, { force: true });
112
+ await runDocker(
113
+ [
114
+ "run",
115
+ "--rm",
116
+ ...(await prepareContainerRun(config, requestDirectory, {
117
+ network: target.network,
118
+ environment: environmentNames,
119
+ sources: operation !== "inspect",
120
+ })),
121
+ imageId,
122
+ operation,
123
+ "--request",
124
+ "/input/config.json",
125
+ "--operation-id",
126
+ operationId,
127
+ "--image-id",
128
+ imageId,
129
+ ...(options.initializeUser ? ["--initialize-user"] : []),
130
+ ...(options.read ? ["--read", JSON.stringify(options.read)] : []),
131
+ ],
132
+ (status) =>
133
+ `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`,
134
+ ).catch(async (cause: unknown) => {
135
+ if (!existsSync(failure)) {
136
+ throw cause;
137
+ }
138
+ const reason = tracebackFailure(await readFile(failure, "utf8"));
139
+ throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
140
+ cause,
141
+ });
142
+ });
143
+ const result = await readFile(resolve(diagnostics, "result.json"), "utf8")
144
+ .then((content) => controllerResultSchema.parse(JSON.parse(content)))
145
+ .catch((cause: unknown) => {
146
+ throw new Error(
147
+ `Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`,
148
+ { cause },
149
+ );
150
+ });
151
+ return checkReceipt(
152
+ result,
153
+ { operationId, operation, imageId, templateHash, target },
154
+ diagnostics,
155
+ );
156
+ } finally {
157
+ await rm(requestDirectory, { recursive: true, force: true });
158
+ }
209
159
  };
210
160
 
211
161
  /** Download or apply an online change using the original CODESYS Docker compiler. */
212
162
  export const updateController = (
213
- config: ResolvedConfig,
214
- operation: "download" | "online-change",
215
- options: ControllerUpdateOptions = {},
163
+ config: ResolvedConfig,
164
+ operation: "download" | "online-change",
165
+ options: ControllerUpdateOptions = {},
216
166
  ) => controllerOperation(config, operation, options);
217
167
 
218
168
  /** Read the controller using the runner's saved compilation baseline. */
219
169
  export const inspectController = (config: ResolvedConfig, read?: string[]) =>
220
- controllerOperation(config, "inspect", { read });
221
-
222
- /**
223
- * Ends every refusal that only a full download resolves, so callers can offer one. The Python
224
- * online operations end theirs with the same words.
225
- */
226
- export const explicitDownload = "use an explicit download";
170
+ controllerOperation(config, "inspect", { read });
227
171
 
228
- export const loginCommandSchema = z.discriminatedUnion("command", [
229
- z.strictObject({ command: z.literal("state") }),
230
- z.strictObject({
231
- command: z.literal("read"),
232
- expressions: z.array(z.string().nonempty()).nonempty(),
233
- }),
234
- z.strictObject({
235
- command: z.enum(["write", "force"]),
236
- values: z.record(z.string().nonempty(), z.string().nonempty()),
237
- }),
238
- // No expressions unforces everything; `restore` puts back the value from before forcing.
239
- z.strictObject({
240
- command: z.literal("unforce"),
241
- expressions: z.array(z.string().nonempty()),
242
- restore: z.boolean(),
243
- }),
244
- z.strictObject({ command: z.enum(["start", "stop"]) }),
245
- z.strictObject({ command: z.literal("reset"), kind: z.enum(["Warm", "Cold"]) }),
246
- ]);
247
- export type LoginCommand = z.infer<typeof loginCommandSchema>;
248
- export const loginResultSchema = z.union([
249
- z.strictObject({ values: z.record(z.string(), z.string()) }),
250
- z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
251
- ]);
252
- export type LoginResult = z.infer<typeof loginResultSchema>;
253
172
  const loginReplySchema = z.discriminatedUnion("ok", [
254
- z.strictObject({ ok: z.literal(true), result: z.unknown() }),
255
- z.strictObject({ ok: z.literal(false), error: z.string() }),
173
+ z.strictObject({ ok: z.literal(true), result: z.unknown() }),
174
+ z.strictObject({ ok: z.literal(false), error: z.string() }),
256
175
  ]);
257
176
 
258
177
  /** The ports login and warm containers serve on, inside the container. */
@@ -260,10 +179,19 @@ const loginPort = 4851;
260
179
  const warmPort = 4852;
261
180
 
262
181
  const docker = (args: string[], timeout: number) =>
263
- execute("docker", args, { timeout }).then(({ stdout }) => stdout.trim());
182
+ captureDocker(args, timeout).then(({ stdout }) => stdout.trim());
183
+
184
+ /** The end of container `name`'s output, which shows why it stopped. */
185
+ const recentLogs = async (name: string, timeout: number) => {
186
+ const logs = await captureDocker(["logs", "--tail", "40", name], timeout);
187
+ return `${logs.stdout}${logs.stderr}`;
188
+ };
264
189
 
265
190
  const isRunning = async (name: string, timeout: number) =>
266
- (await docker(["container", "ls", "--quiet", "--filter", `name=^${name}$`], timeout)) !== "";
191
+ (await docker(
192
+ ["container", "ls", "--quiet", "--filter", `name=^${name}$`],
193
+ timeout,
194
+ )) !== "";
267
195
 
268
196
  /**
269
197
  * Calls the server builder container `name` runs on `port`. The container's internal network
@@ -271,197 +199,238 @@ const isRunning = async (name: string, timeout: number) =>
271
199
  * credentials, through its standard input.
272
200
  */
273
201
  const callContainer = async (
274
- name: string,
275
- port: number,
276
- method: "GET" | "POST" | "DELETE",
277
- body?: unknown,
202
+ name: string,
203
+ port: number,
204
+ method: "GET" | "POST" | "DELETE",
205
+ body?: unknown,
278
206
  ) => {
279
- const child = Bun.spawn(
280
- [
281
- "docker",
282
- "exec",
283
- ...(body === undefined ? [] : ["--interactive"]),
284
- name,
285
- "curl",
286
- "--silent",
287
- "--show-error",
288
- ...(method === "GET" ? ["--max-time", "5"] : []),
289
- "--request",
290
- method,
291
- ...(body === undefined
292
- ? []
293
- : ["--header", "Content-Type: application/json", "--data-binary", "@-"]),
294
- `http://127.0.0.1:${port}/`,
295
- ],
296
- {
297
- stdin: body === undefined ? "ignore" : new Blob([JSON.stringify(body)]),
298
- stdout: "pipe",
299
- stderr: "pipe",
300
- },
301
- );
302
- const [output, errors, code] = await Promise.all([
303
- new Response(child.stdout).text(),
304
- new Response(child.stderr).text(),
305
- child.exited,
306
- ]);
307
- if (code !== 0) throw new Error(errors.trim() || `docker exec failed (${code})`);
308
- const reply = loginReplySchema.parse(JSON.parse(output));
309
- if (!reply.ok) throw new Error(reply.error);
310
- return reply.result;
207
+ const child = Bun.spawn(
208
+ [
209
+ "docker",
210
+ "exec",
211
+ ...(body === undefined ? [] : ["--interactive"]),
212
+ name,
213
+ "curl",
214
+ "--silent",
215
+ "--show-error",
216
+ ...(method === "GET" ? ["--max-time", "5"] : []),
217
+ "--request",
218
+ method,
219
+ ...(body === undefined
220
+ ? []
221
+ : [
222
+ "--header",
223
+ "Content-Type: application/json",
224
+ "--data-binary",
225
+ "@-",
226
+ ]),
227
+ `http://127.0.0.1:${port}/`,
228
+ ],
229
+ {
230
+ stdin: body === undefined ? "ignore" : new Blob([JSON.stringify(body)]),
231
+ stdout: "pipe",
232
+ stderr: "pipe",
233
+ },
234
+ );
235
+ const [output, errors, code] = await Promise.all([
236
+ new Response(child.stdout).text(),
237
+ new Response(child.stderr).text(),
238
+ child.exited,
239
+ ]);
240
+ if (code !== 0) {
241
+ throw new Error(errors.trim() || `docker exec failed (${code})`);
242
+ }
243
+ const reply = loginReplySchema.parse(JSON.parse(output));
244
+ if (!reply.ok) {
245
+ throw new Error(reply.error);
246
+ }
247
+ return reply.result;
311
248
  };
312
249
 
313
250
  /** The container answers once its server listens, which for a login is once CODESYS has logged in. */
314
251
  const answers = (name: string, port: number) =>
315
- callContainer(name, port, "GET").then(
316
- () => true,
317
- () => false,
318
- );
252
+ callContainer(name, port, "GET").then(
253
+ () => true,
254
+ () => false,
255
+ );
319
256
 
320
257
  /** A logout takes seconds; one still running after this waits on a worker that stopped answering. */
321
258
  const logoutTimeout = 60_000;
322
259
 
323
260
  /** A login held open in builder container `name`; it ends with `close` or when the container stops. */
324
261
  const attachLogin = (name: string, timeout: number) => ({
325
- name,
326
- ready: () => answers(name, loginPort),
327
- send: async (command: LoginCommand) =>
328
- loginResultSchema.parse(await callContainer(name, loginPort, "POST", command)),
329
- /**
330
- * Logs out and removes the container. A login that can't log out, such as one whose CODESYS
331
- * worker died, still has its container removed, and returns why it couldn't.
332
- */
333
- close: async () => {
334
- const logout = async () => {
335
- await callContainer(name, loginPort, "DELETE");
336
- await docker(["wait", name], timeout);
337
- };
338
- const failure = await Promise.race([
339
- logout().then(() => undefined, failureReason),
340
- delay(logoutTimeout, `The login didn't log out within ${logoutTimeout / 1000} s`),
341
- ]);
342
- await docker(["rm", "--force", name], timeout);
343
- return failure;
344
- },
262
+ name,
263
+ ready: () => answers(name, loginPort),
264
+ send: async (command: LoginCommand) =>
265
+ loginResultSchema.parse(
266
+ await callContainer(name, loginPort, "POST", command),
267
+ ),
268
+ /**
269
+ * Logs out and removes the container. A login that can't log out, such as one whose CODESYS
270
+ * worker died, still has its container removed, and returns why it couldn't.
271
+ */
272
+ close: async () => {
273
+ const logout = async () => {
274
+ await callContainer(name, loginPort, "DELETE");
275
+ await docker(["wait", name], timeout);
276
+ };
277
+ const failure = await Promise.race([
278
+ logout().then(() => undefined, failureReason),
279
+ delay(
280
+ logoutTimeout,
281
+ `The login didn't log out within ${logoutTimeout / 1000} s`,
282
+ ),
283
+ ]);
284
+ await docker(["rm", "--force", name], timeout);
285
+ return failure;
286
+ },
345
287
  });
346
288
  export type ControllerLogin = ReturnType<typeof attachLogin>;
347
289
 
348
290
  /** The login in container `name`, if one is running; it outlives the process that opened it. */
349
291
  export const findControllerLogin = async (name: string) =>
350
- (await isRunning(name, 15_000)) ? attachLogin(name, 15_000) : undefined;
292
+ (await isRunning(name, 15_000)) ? attachLogin(name, 15_000) : undefined;
351
293
 
352
294
  /**
353
295
  * Logs in to the running application from the saved download baseline, in a detached builder
354
296
  * container named `name`. Commands then take seconds instead of a CODESYS start each.
355
297
  */
356
- export const openControllerLogin = async (config: ResolvedConfig, name: string) => {
357
- const environmentNames = credentialEnvironment(config);
358
- const { imageId, target } = await controllerConnection(config);
359
- const timeout = config.timeouts.hostCommand;
360
- // A login that failed to open leaves its stopped container for diagnostics until the next one.
361
- await docker(["rm", "--force", name], timeout);
362
- // The request is overwritten in place: a bind mount of a recreated directory can still show
363
- // Docker Desktop's cached, empty view of the deleted one.
364
- const requestDirectory = resolve(config.outDir, ".codesys/login-request");
365
- await mkdir(requestDirectory, { recursive: true });
366
- await docker(
367
- [
368
- "run",
369
- "--detach",
370
- "--name",
371
- name,
372
- ...(await prepareContainerRun(config, requestDirectory, {
373
- network: target.network,
374
- environment: environmentNames,
375
- sources: false,
376
- })),
377
- imageId,
378
- "login",
379
- "--request",
380
- "/input/config.json",
381
- "--image-id",
382
- imageId,
383
- "--port",
384
- String(loginPort),
385
- ],
386
- timeout,
387
- );
388
- const login = attachLogin(name, timeout);
389
- const deadline = Date.now() + config.timeouts.startup + config.timeouts.build;
390
- while (Date.now() < deadline) {
391
- if (!(await isRunning(name, timeout))) {
392
- const logs = await execute("docker", ["logs", "--tail", "40", name], { timeout });
393
- throw new Error(`The controller login failed:\n${logs.stdout}${logs.stderr}`);
394
- }
395
- if (await login.ready()) return login;
396
- await delay(2000);
397
- }
398
- await docker(["rm", "--force", name], timeout);
399
- throw new Error("The controller login did not open in time");
298
+ export const openControllerLogin = async (
299
+ config: ResolvedConfig,
300
+ name: string,
301
+ ) => {
302
+ const environmentNames = credentialEnvironment(config);
303
+ const { imageId, target } = await controllerConnection(config);
304
+ const timeout = config.timeouts.hostCommand;
305
+ // A login that failed to open leaves its stopped container for diagnostics until the next one.
306
+ await docker(["rm", "--force", name], timeout);
307
+ // The request is overwritten in place: a bind mount of a recreated directory can still show
308
+ // Docker Desktop's cached, empty view of the deleted one.
309
+ const requestDirectory = resolve(config.outDir, ".codesys/login-request");
310
+ await mkdir(requestDirectory, { recursive: true });
311
+ await docker(
312
+ [
313
+ "run",
314
+ "--detach",
315
+ "--name",
316
+ name,
317
+ ...(await prepareContainerRun(config, requestDirectory, {
318
+ network: target.network,
319
+ environment: environmentNames,
320
+ sources: false,
321
+ })),
322
+ imageId,
323
+ "login",
324
+ "--request",
325
+ "/input/config.json",
326
+ "--image-id",
327
+ imageId,
328
+ "--port",
329
+ String(loginPort),
330
+ ],
331
+ timeout,
332
+ );
333
+ const login = attachLogin(name, timeout);
334
+ const deadline = Date.now() + config.timeouts.startup + config.timeouts.build;
335
+ while (Date.now() < deadline) {
336
+ if (!(await isRunning(name, timeout))) {
337
+ throw new Error(
338
+ `The controller login failed:\n${await recentLogs(name, timeout)}`,
339
+ );
340
+ }
341
+ if (await login.ready()) {
342
+ return login;
343
+ }
344
+ await delay(2000);
345
+ }
346
+ await docker(["rm", "--force", name], timeout);
347
+ throw new Error("The controller login did not open in time");
400
348
  };
401
349
 
402
350
  /** Builder container `name`, running warm on this image, target and settings, started if needed. */
403
351
  const warmController = async (
404
- config: ResolvedConfig,
405
- name: string,
406
- connection: Awaited<ReturnType<typeof controllerConnection>>,
352
+ config: ResolvedConfig,
353
+ name: string,
354
+ connection: Awaited<ReturnType<typeof controllerConnection>>,
407
355
  ) => {
408
- const timeout = config.timeouts.hostCommand;
409
- const { imageId, target } = connection;
410
- const settings = createHash("sha256")
411
- .update(JSON.stringify({ imageId, target, timeouts: config.timeouts, docker: config.docker }))
412
- .digest("hex");
413
- const label = `tsplc.warm=${settings}`;
414
- const running = async () =>
415
- (await docker(
416
- ["container", "ls", "--quiet", "--filter", `name=^${name}$`, "--filter", `label=${label}`],
417
- timeout,
418
- )) !== "";
419
- // One whose CODESYS died, which its server reports, is replaced too.
420
- if (!(await running()) || !(await answers(name, warmPort))) {
421
- await docker(["rm", "--force", name], timeout);
422
- // Its own request: the operations' configs come later, one per release.
423
- const requestDirectory = resolve(config.outDir, ".codesys/warm-request");
424
- await mkdir(requestDirectory, { recursive: true });
425
- await docker(
426
- [
427
- "run",
428
- "--detach",
429
- "--name",
430
- name,
431
- "--label",
432
- label,
433
- ...(await prepareContainerRun(config, requestDirectory, {
434
- network: target.network,
435
- sources: false,
436
- })),
437
- imageId,
438
- "warm",
439
- "--request",
440
- "/input/config.json",
441
- "--image-id",
442
- imageId,
443
- "--port",
444
- String(warmPort),
445
- ],
446
- timeout,
447
- );
448
- }
449
- const deadline = Date.now() + config.timeouts.startup;
450
- while (Date.now() < deadline) {
451
- if (!(await running())) {
452
- const logs = await execute("docker", ["logs", "--tail", "40", name], { timeout });
453
- throw new Error(`CODESYS failed to start:\n${logs.stdout}${logs.stderr}`);
454
- }
455
- if (await answers(name, warmPort)) return;
456
- await delay(2000);
457
- }
458
- await docker(["rm", "--force", name], timeout);
459
- throw new Error("CODESYS did not start in time");
356
+ const timeout = config.timeouts.hostCommand;
357
+ const { imageId, target } = connection;
358
+ const settings = createHash("sha256")
359
+ .update(
360
+ JSON.stringify({
361
+ imageId,
362
+ target,
363
+ timeouts: config.timeouts,
364
+ docker: config.docker,
365
+ }),
366
+ )
367
+ .digest("hex");
368
+ const label = `tsplc.warm=${settings}`;
369
+ const running = async () =>
370
+ (await docker(
371
+ [
372
+ "container",
373
+ "ls",
374
+ "--quiet",
375
+ "--filter",
376
+ `name=^${name}$`,
377
+ "--filter",
378
+ `label=${label}`,
379
+ ],
380
+ timeout,
381
+ )) !== "";
382
+ // One whose CODESYS died, which its server reports, is replaced too.
383
+ if (!(await running()) || !(await answers(name, warmPort))) {
384
+ await docker(["rm", "--force", name], timeout);
385
+ // Its own request: the operations' configs come later, one per release.
386
+ const requestDirectory = resolve(config.outDir, ".codesys/warm-request");
387
+ await mkdir(requestDirectory, { recursive: true });
388
+ await docker(
389
+ [
390
+ "run",
391
+ "--detach",
392
+ "--name",
393
+ name,
394
+ "--label",
395
+ label,
396
+ ...(await prepareContainerRun(config, requestDirectory, {
397
+ network: target.network,
398
+ sources: false,
399
+ })),
400
+ imageId,
401
+ "warm",
402
+ "--request",
403
+ "/input/config.json",
404
+ "--image-id",
405
+ imageId,
406
+ "--port",
407
+ String(warmPort),
408
+ ],
409
+ timeout,
410
+ );
411
+ }
412
+ const deadline = Date.now() + config.timeouts.startup;
413
+ while (Date.now() < deadline) {
414
+ if (!(await running())) {
415
+ throw new Error(
416
+ `CODESYS failed to start:\n${await recentLogs(name, timeout)}`,
417
+ );
418
+ }
419
+ if (await answers(name, warmPort)) {
420
+ return;
421
+ }
422
+ await delay(2000);
423
+ }
424
+ await docker(["rm", "--force", name], timeout);
425
+ throw new Error("CODESYS did not start in time");
460
426
  };
461
427
 
462
428
  /** Starts warm builder container `name` ahead of the first operation, unless it already runs. */
463
- export const startWarmController = async (config: ResolvedConfig, name: string) => {
464
- await warmController(config, name, await controllerConnection(config));
429
+ export const startWarmController = async (
430
+ config: ResolvedConfig,
431
+ name: string,
432
+ ) => {
433
+ await warmController(config, name, await controllerConnection(config));
465
434
  };
466
435
 
467
436
  /**
@@ -470,45 +439,51 @@ export const startWarmController = async (config: ResolvedConfig, name: string)
470
439
  * with a new image, target or settings, starts it. Credentials go to CODESYS for this operation only.
471
440
  */
472
441
  export const updateWarmController = async (
473
- config: ResolvedConfig,
474
- name: string,
475
- operation: "download" | "online-change",
476
- options: { initializeUser?: boolean; credentials?: ControllerCredentials } = {},
442
+ config: ResolvedConfig,
443
+ name: string,
444
+ operation: "download" | "online-change",
445
+ options: {
446
+ initializeUser?: boolean;
447
+ credentials?: ControllerCredentials;
448
+ } = {},
477
449
  ): Promise<ControllerResult> => {
478
- const connection = await controllerConnection(config);
479
- await warmController(config, name, connection);
480
- const operationId = randomUUID();
481
- const diagnostics = resolve(config.outDir, ".codesys/controller");
482
- const directory = resolve(config.outDir, ".codesys/requests", operationId);
483
- try {
484
- const request = await writeOperationRequest(
485
- config,
486
- directory,
487
- posix.join("/output/.codesys/requests", operationId),
488
- );
489
- const result = await callContainer(name, warmPort, "POST", {
490
- operation,
491
- operationId,
492
- request,
493
- initializeUser: options.initializeUser ?? false,
494
- credentials: options.credentials,
495
- } satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {
496
- throw new Error(`${failureReason(error)}. Inspect ${diagnostics} for diagnostics`, {
497
- cause: error,
498
- });
499
- });
500
- return checkReceipt(
501
- controllerResultSchema.parse(result),
502
- {
503
- operationId,
504
- operation,
505
- imageId: connection.imageId,
506
- templateHash: connection.templateHash,
507
- target: connection.target,
508
- },
509
- diagnostics,
510
- );
511
- } finally {
512
- await rm(directory, { recursive: true, force: true });
513
- }
450
+ const connection = await controllerConnection(config);
451
+ await warmController(config, name, connection);
452
+ const operationId = randomUUID();
453
+ const diagnostics = resolve(config.outDir, ".codesys/controller");
454
+ const directory = resolve(config.outDir, ".codesys/requests", operationId);
455
+ try {
456
+ const request = await writeOperationRequest(
457
+ config,
458
+ directory,
459
+ posix.join("/output/.codesys/requests", operationId),
460
+ );
461
+ const result = await callContainer(name, warmPort, "POST", {
462
+ operation,
463
+ operationId,
464
+ request,
465
+ initializeUser: options.initializeUser ?? false,
466
+ credentials: options.credentials,
467
+ } satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {
468
+ throw new Error(
469
+ `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`,
470
+ {
471
+ cause: error,
472
+ },
473
+ );
474
+ });
475
+ return checkReceipt(
476
+ controllerResultSchema.parse(result),
477
+ {
478
+ operationId,
479
+ operation,
480
+ imageId: connection.imageId,
481
+ templateHash: connection.templateHash,
482
+ target: connection.target,
483
+ },
484
+ diagnostics,
485
+ );
486
+ } finally {
487
+ await rm(directory, { recursive: true, force: true });
488
+ }
514
489
  };