@tsplc/build 0.2.21 → 0.4.0

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/README.md +2 -2
  2. package/dist/cli.js +1052 -836
  3. package/dist/cli.js.map +27 -24
  4. package/dist/images.js +165 -0
  5. package/dist/images.js.map +12 -0
  6. package/dist/index.js +888 -668
  7. package/dist/index.js.map +23 -20
  8. package/dist/libraries.js +4 -3
  9. package/dist/libraries.js.map +3 -3
  10. package/docker/Dockerfile.dockerignore +0 -4
  11. package/docker/Dockerfile.source +5 -0
  12. package/docker/build-image +30 -26
  13. package/docker/config.ts +1 -1
  14. package/docker/install/wine-signal/README.md +1 -1
  15. package/docker/runner.ts +9 -7
  16. package/package.json +24 -8
  17. package/python/build.py +231 -20
  18. package/python/codesys_online.py +121 -10
  19. package/python/worker.py +2 -0
  20. package/src/artifacts.ts +9 -7
  21. package/src/build.ts +9 -4
  22. package/src/cli.ts +11 -20
  23. package/src/controller-online.ts +145 -61
  24. package/src/controller-protocol.ts +48 -5
  25. package/src/controller-session.ts +386 -147
  26. package/src/device-tree.ts +1 -1
  27. package/src/docker-build.ts +80 -98
  28. package/src/docker-context.ts +56 -3
  29. package/src/docker-run.ts +56 -3
  30. package/src/engineering-settings.ts +3 -3
  31. package/src/host/codesys-host.ts +3 -3
  32. package/src/host/codesys-worker.ts +77 -3
  33. package/src/images.ts +105 -0
  34. package/src/import-request.ts +1 -0
  35. package/src/index.ts +30 -16
  36. package/src/io.ts +1 -1
  37. package/src/libraries.ts +3 -2
  38. package/src/project-operations.ts +48 -0
  39. package/src/run.ts +9 -6
  40. package/src/sources.ts +2 -2
  41. package/docker/install/wine-signal/check.sh +0 -34
  42. package/docker/install/wine-signal/tests/avx-registers.c +0 -53
  43. package/docker/install/wine-signal/tests/frame-and-handler.c +0 -192
  44. package/docker/install/wine-signal/tests/loader-i386.c +0 -8
  45. package/docker/install/wine-signal/tests/signal-return.c +0 -47
  46. package/python/test_build.py +0 -579
  47. package/python/test_codesys_login.py +0 -139
  48. package/python/test_codesys_online.py +0 -259
  49. package/python/test_installer_packages.py +0 -217
  50. package/python/test_installer_verification.py +0 -307
  51. package/python/test_worker.py +0 -154
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
- import { buildFiles } from "./artifacts";
5
4
  import type { ResolvedConfig } from "@tsplc/config/build";
5
+ import { buildFiles } from "./artifacts";
6
6
 
7
7
  /** Writes each adapter's EDS into `directory`, where CODESYS imports it, and returns the tree the worker reads. */
8
8
  export const writeDeviceTree = async (
@@ -1,42 +1,56 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { cp, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
2
+ import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { resolve } from "node:path";
5
+ import type { ResolvedConfig } from "@tsplc/config/build";
5
6
  import { z } from "zod";
6
7
  import { readBuild } from "./artifacts";
7
- import { dockerImage, type ResolvedConfig } from "@tsplc/config/build";
8
- import { prepareDockerContext } from "./docker-context.ts";
9
8
  import {
10
9
  buildFailureFile,
11
10
  buildFailureSchema,
12
11
  CodesysCompilerError,
13
12
  } from "./diagnostics.ts";
14
- import { captureDocker, prepareContainerRun, runDocker } from "./docker-run.ts";
13
+ import {
14
+ captureDocker,
15
+ type ProgressOptions,
16
+ type ProgressStream,
17
+ prepareContainerRun,
18
+ progressLog,
19
+ runDocker,
20
+ } from "./docker-run.ts";
21
+ import {
22
+ buildBuilderImage,
23
+ builderImage,
24
+ buildGatewayImage,
25
+ gatewayImage,
26
+ publishedImage,
27
+ runtimeImage,
28
+ setupPlatformFor,
29
+ } from "./images.ts";
15
30
  import { packageDirectory } from "./package-path.ts";
16
31
 
17
- /** Each tsPLC version's images, published so that setup pulls them instead of installing CODESYS. */
18
- export const publishedImage = async (image: string) => {
19
- const { version } = z
32
+ const packageVersion = async () =>
33
+ z
20
34
  .object({ version: z.string() })
21
35
  .parse(
22
36
  JSON.parse(
23
37
  await readFile(resolve(packageDirectory, "package.json"), "utf8"),
24
38
  ),
25
- );
26
- return `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
27
- };
39
+ ).version;
28
40
 
29
41
  /** Pulls this version's published `image`; false when it isn't available, so the caller builds it. */
30
- const pullPublished = async (image: string) => {
31
- const published = await publishedImage(image);
32
- console.log(`Pulling ${published}`);
42
+ const pullPublished = async (image: string, progress: ProgressStream) => {
43
+ const published = publishedImage(image, await packageVersion());
44
+ const output = { progress, environment: {} };
45
+ progressLog(progress)(`Pulling ${published}`);
33
46
  try {
34
47
  await runDocker(
35
48
  ["pull", "--platform", "linux/amd64", published],
36
49
  (status) => `Docker pull failed (${status})`,
50
+ output,
37
51
  );
38
52
  } catch {
39
- console.log(
53
+ progressLog(progress)(
40
54
  `${published} is not available; building ${image} locally instead.`,
41
55
  );
42
56
  return false;
@@ -44,13 +58,16 @@ const pullPublished = async (image: string) => {
44
58
  await runDocker(
45
59
  ["tag", published, image],
46
60
  (status) => `Docker tag failed (${status})`,
61
+ output,
47
62
  );
48
63
  return true;
49
64
  };
50
65
 
51
66
  /** Install the IDE and its prerequisites in the Docker builder image. */
52
- export const configureDocker = async () => {
53
- const image = dockerImage;
67
+ export const configureDocker = async ({
68
+ progress = "stdout",
69
+ }: ProgressOptions = {}) => {
70
+ const image = builderImage;
54
71
  const { stdout } = await captureDocker(
55
72
  ["info", "--format", "{{.OSType}}/{{.Architecture}}"],
56
73
  30_000,
@@ -62,76 +79,40 @@ export const configureDocker = async () => {
62
79
  },
63
80
  );
64
81
  });
65
- const architecture = stdout.trim();
66
- const arm =
67
- architecture === "linux/aarch64" || architecture === "linux/arm64";
68
- if (
69
- !arm &&
70
- architecture !== "linux/x86_64" &&
71
- architecture !== "linux/amd64"
72
- ) {
82
+ const setupPlatform = setupPlatformFor(stdout.trim());
83
+ if (!setupPlatform) {
73
84
  throw new Error(
74
85
  "The builder requires a Linux Docker server on ARM64 or AMD64",
75
86
  );
76
87
  }
77
- if (await pullPublished(image)) {
78
- return image;
79
- }
80
- const context = await mkdtemp(resolve(tmpdir(), "codesys-installer-"));
81
- let buildContext: string | undefined;
82
- try {
83
- buildContext = await prepareDockerContext();
84
- const cache = resolve(context, "winetricks");
85
- await mkdir(cache);
86
- if (process.env["CODESYS_WINETRICKS_CACHE"]) {
87
- await cp(process.env["CODESYS_WINETRICKS_CACHE"], cache, {
88
- recursive: true,
89
- });
90
- }
91
- console.log(
92
- `Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`,
93
- );
94
- await runDocker(
95
- [
96
- "build",
97
- "--platform",
98
- "linux/amd64",
99
- "--build-arg",
100
- `SETUP_BASE=${arm ? "arm-setup" : "base"}`,
101
- "--build-arg",
102
- `SETUP_PLATFORM=${arm ? "linux/arm64" : "linux/amd64"}`,
103
- "--build-arg",
104
- "INSTALLER_SOURCE=installer-download",
105
- "--progress",
106
- "plain",
107
- "--build-context",
108
- `installer=${context}`,
109
- "-f",
110
- resolve(buildContext, "docker/Dockerfile"),
111
- "-t",
112
- image,
113
- buildContext,
114
- ],
115
- (status) =>
116
- `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`,
117
- );
88
+ if (await pullPublished(image, progress)) {
118
89
  return image;
119
- } finally {
120
- await Promise.all([
121
- rm(context, { recursive: true, force: true }),
122
- ...(buildContext
123
- ? [rm(buildContext, { recursive: true, force: true })]
124
- : []),
125
- ]);
126
90
  }
91
+ progressLog(progress)(
92
+ `Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`,
93
+ );
94
+ await buildBuilderImage({
95
+ tag: image,
96
+ setupPlatform,
97
+ installer: null,
98
+ winetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,
99
+ docker: (args) =>
100
+ runDocker(
101
+ args,
102
+ (status) =>
103
+ `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`,
104
+ { progress, environment: {} },
105
+ ),
106
+ });
107
+ return image;
127
108
  };
128
109
 
129
- export const runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
130
-
131
110
  /** Build the local CODESYS Control for Linux SL runtime, the same device as a production build. */
132
- export const configureRuntime = async () => {
111
+ export const configureRuntime = async ({
112
+ progress = "stdout",
113
+ }: ProgressOptions = {}) => {
133
114
  const context = resolve(packageDirectory, "docker/control-linux-sl");
134
- console.log(`Preparing the local PLC runtime (${runtimeImage}).`);
115
+ progressLog(progress)(`Preparing the local PLC runtime (${runtimeImage}).`);
135
116
  await runDocker(
136
117
  [
137
118
  "build",
@@ -145,37 +126,37 @@ export const configureRuntime = async () => {
145
126
  ],
146
127
  (status) =>
147
128
  `Runtime image build failed (${status}). Review the image-build output`,
129
+ { progress, environment: {} },
148
130
  );
149
131
  return runtimeImage;
150
132
  };
151
133
 
152
- export const gatewayImage = "tsplc-edge-gateway:4.22.0.0";
153
-
154
134
  /** Build the CODESYS Edge Gateway that builder containers reach a plant controller through. */
155
- export const configureGateway = async () => {
156
- if (await pullPublished(gatewayImage)) {
135
+ export const configureGateway = async ({
136
+ progress = "stdout",
137
+ }: ProgressOptions = {}) => {
138
+ if (await pullPublished(gatewayImage, progress)) {
157
139
  return gatewayImage;
158
140
  }
159
- const context = resolve(packageDirectory, "docker/edge-gateway");
160
- console.log(`Preparing the CODESYS gateway (${gatewayImage}).`);
161
- await runDocker(
162
- [
163
- "build",
164
- "--platform",
165
- "linux/amd64",
166
- "--progress",
167
- "plain",
168
- "-t",
169
- gatewayImage,
170
- context,
171
- ],
172
- (status) =>
173
- `Gateway image build failed (${status}). Review the image-build output`,
174
- );
141
+ progressLog(progress)(`Preparing the CODESYS gateway (${gatewayImage}).`);
142
+ await buildGatewayImage({
143
+ tag: gatewayImage,
144
+ docker: (args) =>
145
+ runDocker(
146
+ args,
147
+ (status) =>
148
+ `Gateway image build failed (${status}). Review the image-build output`,
149
+ { progress, environment: {} },
150
+ ),
151
+ });
175
152
  return gatewayImage;
176
153
  };
177
154
 
178
- export const buildInDocker = async (config: ResolvedConfig, image: string) => {
155
+ export const buildInDocker = async (
156
+ config: ResolvedConfig,
157
+ image: string,
158
+ progress: ProgressStream,
159
+ ) => {
179
160
  const requestDirectory = await mkdtemp(resolve(tmpdir(), "codesys-docker-"));
180
161
  try {
181
162
  const operationId = randomUUID();
@@ -195,12 +176,13 @@ export const buildInDocker = async (config: ResolvedConfig, image: string) => {
195
176
  "--operation-id",
196
177
  operationId,
197
178
  ];
198
- console.log(`Building with Docker (${image})`);
179
+ progressLog(progress)(`Building with Docker (${image})`);
199
180
  try {
200
181
  await runDocker(
201
182
  args,
202
183
  (status) =>
203
184
  `Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`,
185
+ { progress, environment: {} },
204
186
  );
205
187
  } catch (cause) {
206
188
  const message = cause instanceof Error ? cause.message : String(cause);
@@ -1,9 +1,21 @@
1
- import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
1
+ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { createRequire } from "node:module";
3
3
  import { tmpdir } from "node:os";
4
- import { dirname, resolve } from "node:path";
4
+ import { basename, dirname, resolve } from "node:path";
5
+ import { z } from "zod";
5
6
  import { packageDirectory } from "./package-path.ts";
6
7
 
8
+ const includeSource = (source: string) => {
9
+ const name = basename(source);
10
+ return (
11
+ name !== "__pycache__" &&
12
+ !name.endsWith(".pyc") &&
13
+ !name.endsWith(".test.ts") &&
14
+ !name.endsWith(".fixtures.ts") &&
15
+ !(name.startsWith("test_") && name.endsWith(".py"))
16
+ );
17
+ };
18
+
7
19
  /** The workspace packages container code imports, each copied with the files Bun runs it from. */
8
20
  const containerPackages = [
9
21
  {
@@ -18,6 +30,43 @@ const containerPackages = [
18
30
  },
19
31
  ];
20
32
 
33
+ const manifestDependencies = z.object({
34
+ name: z.string(),
35
+ dependencies: z.record(z.string(), z.string()).default({}),
36
+ });
37
+
38
+ /**
39
+ * The third-party packages the image installs: what this package and each package the
40
+ * context carries depend on, at the versions their manifests pin.
41
+ */
42
+ export function containerDependencies(
43
+ manifests: z.infer<typeof manifestDependencies>[],
44
+ ) {
45
+ const selected = new Map<string, { version: string; owner: string }>();
46
+ for (const manifest of manifests) {
47
+ for (const [name, version] of Object.entries(manifest.dependencies)) {
48
+ if (name.startsWith("@tsplc/")) {
49
+ continue;
50
+ }
51
+ const existing = selected.get(name);
52
+ if (existing && existing.version !== version) {
53
+ throw new Error(
54
+ `The builder image cannot install ${name}: ${existing.owner} pins ${existing.version} and ${manifest.name} pins ${version}.`,
55
+ );
56
+ }
57
+ selected.set(name, { version, owner: manifest.name });
58
+ }
59
+ }
60
+ return Object.fromEntries(
61
+ [...selected].map(([name, { version }]) => [name, version]),
62
+ );
63
+ }
64
+
65
+ const readManifest = async (directory: string) =>
66
+ manifestDependencies.parse(
67
+ JSON.parse(await readFile(resolve(directory, "package.json"), "utf8")),
68
+ );
69
+
21
70
  export async function prepareDockerContext() {
22
71
  const context = await mkdtemp(resolve(tmpdir(), "tsplc-docker-"));
23
72
  try {
@@ -27,18 +76,22 @@ export async function prepareDockerContext() {
27
76
  resolve(context, directory),
28
77
  {
29
78
  recursive: true,
79
+ filter: includeSource,
30
80
  },
31
81
  );
32
82
  }
83
+ const manifests = [await readManifest(packageDirectory)];
33
84
  for (const { entry, directory, files } of containerPackages) {
34
85
  const root = resolve(
35
86
  dirname(createRequire(import.meta.url).resolve(entry)),
36
87
  "..",
37
88
  );
89
+ manifests.push(await readManifest(root));
38
90
  await mkdir(resolve(context, directory));
39
91
  for (const file of files) {
40
92
  await cp(resolve(root, file), resolve(context, directory, file), {
41
93
  recursive: true,
94
+ filter: includeSource,
42
95
  });
43
96
  }
44
97
  }
@@ -46,7 +99,7 @@ export async function prepareDockerContext() {
46
99
  resolve(context, "package.json"),
47
100
  JSON.stringify({
48
101
  type: "module",
49
- dependencies: { zod: "4.3.6", jiti: "2.7.0" },
102
+ dependencies: containerDependencies(manifests),
50
103
  }),
51
104
  );
52
105
  return context;
package/src/docker-run.ts CHANGED
@@ -7,22 +7,75 @@ import type { ResolvedConfig } from "@tsplc/config/build";
7
7
 
8
8
  const execute = promisify(execFile);
9
9
 
10
+ /**
11
+ * Where an operation reports progress, the Docker client's output included: standard output,
12
+ * or standard error when standard output carries a machine-readable result.
13
+ */
14
+ export type ProgressStream = "stdout" | "stderr";
15
+
16
+ /** The operation-scoped settings of a command that reports progress. */
17
+ export interface ProgressOptions {
18
+ progress?: ProgressStream;
19
+ }
20
+
21
+ export const progressLog = (stream: ProgressStream) =>
22
+ stream === "stderr" ? console.error : console.log;
23
+
24
+ /**
25
+ * Variables a Docker client command passes to its container by name (`--env NAME`), added to
26
+ * the client's own environment so their values never appear in its arguments.
27
+ */
28
+ export type ContainerEnvironment = Readonly<Record<string, string>>;
29
+
30
+ const clientEnvironment = (environment: ContainerEnvironment) => ({
31
+ ...process.env,
32
+ ...environment,
33
+ });
34
+
10
35
  /** Run a Docker client command with its output captured instead of shown on this terminal. */
11
- export const captureDocker = (args: string[], timeout: number) =>
12
- execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
36
+ export const captureDocker = (
37
+ args: string[],
38
+ timeout: number,
39
+ environment: ContainerEnvironment = {},
40
+ ) =>
41
+ execute("docker", args, {
42
+ timeout,
43
+ maxBuffer: 8 * 1024 * 1024,
44
+ env: clientEnvironment(environment),
45
+ });
46
+
47
+ /**
48
+ * Run a Docker client command with `input` on its standard input, which keeps a request that can
49
+ * hold credentials out of its arguments, and capture its output.
50
+ */
51
+ export const pipeDocker = async (args: string[], input: string | null) => {
52
+ const child = Bun.spawn(["docker", ...args], {
53
+ stdin: input === null ? "ignore" : new Blob([input]),
54
+ stdout: "pipe",
55
+ stderr: "pipe",
56
+ });
57
+ const [stdout, stderr, status] = await Promise.all([
58
+ new Response(child.stdout).text(),
59
+ new Response(child.stderr).text(),
60
+ child.exited,
61
+ ]);
62
+ return { stdout, stderr, status };
63
+ };
13
64
 
14
65
  /** Run a Docker client command attached to this terminal and forward interruption to it. */
15
66
  export const runDocker = (
16
67
  args: string[],
17
68
  failure: (status: string | number | null) => string,
69
+ output: { progress: ProgressStream; environment: ContainerEnvironment },
18
70
  ) =>
19
71
  new Promise<void>((accept, reject) => {
20
72
  const child = spawn("docker", args, {
21
73
  stdio: [
22
74
  "inherit",
23
- process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
75
+ output.progress === "stderr" ? 2 : "inherit",
24
76
  "inherit",
25
77
  ],
78
+ env: clientEnvironment(output.environment),
26
79
  });
27
80
  const interrupt = () => child.kill("SIGINT");
28
81
  const terminate = () => child.kill("SIGTERM");
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  controllerFor,
3
- type loadTsplcConfig,
3
+ type LoadedConfig,
4
4
  rawBuildConfig,
5
5
  simulationConfig,
6
6
  } from "@tsplc/config";
7
+ import { resolveConfig } from "@tsplc/config/build";
7
8
  import { deviceTree } from "@tsplc/typegen";
8
9
  import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
9
- import { resolveConfig } from "@tsplc/config/build";
10
10
  import { installLibraries } from "./libraries.ts";
11
11
 
12
12
  /**
@@ -16,7 +16,7 @@ import { installLibraries } from "./libraries.ts";
16
16
  * the inputs instead.
17
17
  */
18
18
  export const rawEngineeringSettings = async (
19
- { config, configFile, root }: Awaited<ReturnType<typeof loadTsplcConfig>>,
19
+ { config, configFile, root }: LoadedConfig,
20
20
  options: {
21
21
  command: "build" | "run" | "download" | "online-change";
22
22
  frozenLockfile?: boolean;
@@ -3,8 +3,8 @@ import { appendFileSync, constants, renameSync, writeFileSync } from "node:fs";
3
3
  import { access, open, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { delimiter, resolve } from "node:path";
5
5
  import { promisify } from "node:util";
6
- import { z } from "zod";
7
6
  import type { ResolvedConfig } from "@tsplc/config/build";
7
+ import { z } from "zod";
8
8
  import {
9
9
  codesysCommand,
10
10
  codesysCommandFilename,
@@ -44,7 +44,7 @@ export const createCodesysHost = (config: ResolvedConfig) => {
44
44
  },
45
45
  );
46
46
  });
47
- const candidates = (process.env["PATH"] ?? "").split(delimiter);
47
+ const candidates = (process.env.PATH ?? "").split(delimiter);
48
48
  const available = await Promise.all(
49
49
  candidates.map((path) =>
50
50
  access(resolve(path, "script"), constants.X_OK).then(
@@ -141,7 +141,7 @@ export const createCodesysHost = (config: ResolvedConfig) => {
141
141
  const logPath = resolve(directory, "codesys.log");
142
142
  const log = (await readFile(logPath, "utf8"))
143
143
  // Terminal color escapes must not hide a native assertion signature.
144
- // eslint-disable-next-line no-control-regex
144
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Match the terminal ESC character before inspecting diagnostics.
145
145
  .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "")
146
146
  .replace(/\r/g, "");
147
147
  // A Wine helper can abort under Rosetta while the main launcher returns 0.
@@ -13,8 +13,9 @@ import {
13
13
  } from "node:fs/promises";
14
14
  import { resolve } from "node:path";
15
15
  import { setTimeout as delay } from "node:timers/promises";
16
- import { z } from "zod";
17
16
  import type { ResolvedConfig } from "@tsplc/config/build";
17
+ import { z } from "zod";
18
+ import { DownloadRequiredError } from "../controller-protocol";
18
19
  import { CodesysCompilerError, compilerDiagnosticSchema } from "../diagnostics";
19
20
  import { packageDirectory } from "../package-path";
20
21
  import { codesysCommand, getHostCommand } from "./codesys-command";
@@ -30,6 +31,23 @@ const workerScripts = [
30
31
  "codesys_login.py",
31
32
  ];
32
33
 
34
+ /**
35
+ * A digest of the CODESYS scripts this installation runs. Two installations of one tsPLC version
36
+ * differ in it when one is a local build, whose script fixes the other doesn't run.
37
+ */
38
+ export const workerScriptsDigest = async () =>
39
+ createHash("sha256")
40
+ .update(
41
+ JSON.stringify(
42
+ await Promise.all(
43
+ workerScripts.map((script) =>
44
+ readFile(resolve(pythonDirectory, script), "utf8"),
45
+ ),
46
+ ),
47
+ ),
48
+ )
49
+ .digest("hex");
50
+
33
51
  const sessionSchema = z.object({
34
52
  directory: z.string(),
35
53
  fingerprint: z.string(),
@@ -43,6 +61,35 @@ type WorkerCommand =
43
61
  | { action: "prepare"; project: string }
44
62
  | { action: "login"; arguments: Record<string, unknown> };
45
63
 
64
+ const phaseSchema = z.enum(["prepare", "transfer"]);
65
+ /** Where a controller operation is: preparing, with the controller untouched, or transferring to it. */
66
+ export type WorkerPhase = z.infer<typeof phaseSchema>;
67
+
68
+ /**
69
+ * A controller operation's budgets, by the phase the worker writes to `file` as it enters it. A
70
+ * `prepare` that runs out stops the worker, which leaves the controller as it was. A `transfer`
71
+ * that runs out is reported to `overdue` each time it runs out again and is never interrupted:
72
+ * stopping CODESYS mid-transfer can leave the controller without an application.
73
+ */
74
+ export interface PhasedBudget {
75
+ file: string;
76
+ prepare: number;
77
+ transfer: number;
78
+ overdue: (message: string) => void;
79
+ }
80
+
81
+ /** The phase the worker last wrote to `file`; `prepare` until it writes one. */
82
+ export const workerPhase = async (file: string): Promise<WorkerPhase> =>
83
+ phaseSchema.catch("prepare").parse(
84
+ await readFile(file, "utf8").then(
85
+ (text) => text.trim(),
86
+ () => undefined,
87
+ ),
88
+ );
89
+
90
+ const minutes = (milliseconds: number) =>
91
+ `${Math.round(milliseconds / 60_000)} min`;
92
+
46
93
  const hasCode = (error: unknown, code: string) =>
47
94
  error instanceof Error && "code" in error && error.code === code;
48
95
 
@@ -167,10 +214,11 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
167
214
  }
168
215
  };
169
216
 
217
+ /** Sends `command` and waits for its reply within `budget`: milliseconds, or one per phase. */
170
218
  const request = async (
171
219
  session: Session,
172
220
  command: WorkerCommand,
173
- timeoutMs: number,
221
+ budget: number | PhasedBudget,
174
222
  ) => {
175
223
  const id = randomUUID();
176
224
  const reply = resolve(session.directory, `${id}.json`);
@@ -178,7 +226,11 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
178
226
  ...command,
179
227
  id,
180
228
  });
181
- const deadline = Date.now() + timeoutMs;
229
+ const started = Date.now();
230
+ const timeoutMs = typeof budget === "number" ? budget : budget.prepare;
231
+ const deadline = started + timeoutMs;
232
+ // When the worker entered its transfer, and how many transfer budgets it has used since.
233
+ const transfer: { since?: number; reported: number } = { reported: 0 };
182
234
  while (true) {
183
235
  const result = await readJson(reply);
184
236
  if (result !== undefined) {
@@ -187,6 +239,7 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
187
239
  .object({
188
240
  error: z.string().optional(),
189
241
  diagnostics: z.array(compilerDiagnosticSchema).optional(),
242
+ downloadRequired: z.literal(true).optional(),
190
243
  id: z.literal(id),
191
244
  ok: z.boolean(),
192
245
  result: z.unknown(),
@@ -203,6 +256,9 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
203
256
  if (response.data.diagnostics) {
204
257
  throw new CodesysCompilerError(message, response.data.diagnostics);
205
258
  }
259
+ if (response.data.downloadRequired) {
260
+ throw new DownloadRequiredError(message);
261
+ }
206
262
  throw new Error(message);
207
263
  }
208
264
  return response.data.result;
@@ -212,6 +268,24 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
212
268
  `CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,
213
269
  );
214
270
  }
271
+ if (typeof budget !== "number") {
272
+ transfer.since ??=
273
+ (await workerPhase(budget.file)) === "transfer"
274
+ ? Date.now()
275
+ : undefined;
276
+ }
277
+ if (typeof budget !== "number" && transfer.since !== undefined) {
278
+ const elapsed = Date.now() - transfer.since;
279
+ const used = Math.floor(elapsed / budget.transfer);
280
+ if (used > transfer.reported) {
281
+ transfer.reported = used;
282
+ budget.overdue(
283
+ `The transfer has run ${minutes(elapsed)}, past its ${minutes(budget.transfer)} budget; waiting for it, since stopping CODESYS mid-transfer could leave the controller without an application`,
284
+ );
285
+ }
286
+ await delay(200);
287
+ continue;
288
+ }
215
289
  if (Date.now() >= deadline) {
216
290
  // A saved PID can belong to another process after a reboot. Only kill
217
291
  // a process we launched or whose worker answered in this invocation.