@tsplc/compiler 0.5.6 → 0.5.8

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 (49) hide show
  1. package/dist/bun-runtime.js +139 -30
  2. package/dist/bun-runtime.js.map +8 -7
  3. package/dist/cli.js +24 -9
  4. package/dist/cli.js.map +6 -6
  5. package/dist/codesys.js +3237 -1957
  6. package/dist/codesys.js.map +19 -18
  7. package/dist/index.js +54 -6
  8. package/dist/index.js.map +8 -8
  9. package/dist/ir.js +1645 -1326
  10. package/dist/ir.js.map +13 -12
  11. package/dist/project.js +12 -6
  12. package/dist/project.js.map +4 -4
  13. package/package.json +9 -9
  14. package/src/codesys/debug.ts +17 -2
  15. package/src/codesys/emit.ts +40 -12
  16. package/src/codesys/explain.ts +1465 -0
  17. package/src/codesys/global-lists.ts +21 -9
  18. package/src/codesys/http.ts +125 -71
  19. package/src/codesys/instrumentation.ts +161 -9
  20. package/src/codesys/manifest.ts +29 -12
  21. package/src/codesys/numeric.ts +5 -3
  22. package/src/codesys/plan.ts +22 -6
  23. package/src/codesys/programs.ts +2 -0
  24. package/src/codesys/routines.ts +39 -9
  25. package/src/codesys/st-files.ts +73 -6
  26. package/src/codesys/telemetry.ts +70 -35
  27. package/src/frontend/elaborate/index.ts +16 -1
  28. package/src/frontend/elaborate/storage.ts +56 -1
  29. package/src/frontend/expressions.ts +2 -2
  30. package/src/frontend/intrinsics.ts +1 -2
  31. package/src/frontend/statements.ts +3 -2
  32. package/src/frontend/typescript.ts +3 -0
  33. package/src/ir/conditions.ts +895 -0
  34. package/src/ir/core-model.ts +2 -2
  35. package/src/ir/fold.ts +15 -107
  36. package/src/ir/index.ts +10 -11
  37. package/src/ir/link.ts +1 -0
  38. package/src/ir/model.ts +16 -79
  39. package/src/ir/numeric.ts +5 -41
  40. package/src/ir/ranges.ts +8 -14
  41. package/src/ir/scalars.ts +6 -4
  42. package/src/project/debugger.ts +9 -0
  43. package/src/project/project.ts +6 -0
  44. package/src/project/release.ts +7 -4
  45. package/src/runtime/async.ts +15 -12
  46. package/src/runtime/launch.ts +11 -4
  47. package/src/runtime/runtime.ts +26 -23
  48. package/src/runtime/telemetry.ts +14 -6
  49. package/src/runtime/transport.ts +172 -0
@@ -13,13 +13,19 @@ import { now } from "../../stdlib/clock";
13
13
  import { clamp, max, min } from "../../stdlib/math";
14
14
  import { retain } from "../../stdlib/retain";
15
15
  import { onTelemetry, telemetry } from "../../stdlib/telemetry";
16
- import { createAsync, httpCall, oneLaunchAtATime, unsupported } from "./async";
16
+ import {
17
+ createAsync,
18
+ type HttpSettings,
19
+ oneLaunchAtATime,
20
+ unsupported,
21
+ } from "./async";
17
22
  import { type Launch, runtimeDirectory, runtimeFiles } from "./launch";
18
23
  import { loadProgram } from "./program";
19
24
  import { createRetention } from "./retain";
20
25
  import { createStorage } from "./storage";
21
26
  import { plcGlobals, scalarPaths } from "./symbols";
22
27
  import { createTelemetry } from "./telemetry";
28
+ import { httpTransport, opcuaSlots, readServiceChannels } from "./transport";
23
29
 
24
30
  /** Where the runtime publishes OPC UA: the local CODESYS runtime's address and port. */
25
31
  export const runtimeEndpoint = { host: "127.0.0.1", port: 4840 } as const;
@@ -55,8 +61,8 @@ const projectSource = (root: string, source: unknown) => {
55
61
  /**
56
62
  * Runs a project's PLC program in this Bun process, as `tsplc run --bun` does: each task's programs
57
63
  * scan to completion on the task's cycle, services and telemetry go to the project's server over
58
- * HTTP as the compiled program sends them, and the development publication is served over OPC UA
59
- * as the local CODESYS runtime serves it. Reads the last build's artifacts.
64
+ * `server.transport` as the compiled program sends them, and the development publication is served
65
+ * over OPC UA as the local CODESYS runtime serves it. Reads the last build's artifacts.
60
66
  */
61
67
  export const startRuntime = async (options: RuntimeOptions) => {
62
68
  const { launch, log } = options;
@@ -69,22 +75,13 @@ export const startRuntime = async (options: RuntimeOptions) => {
69
75
  if (!compiler || !tasks) {
70
76
  throw new Error("The Bun runtime runs a TypeScript program.");
71
77
  }
72
- if (config.server?.transport === "opcua") {
73
- throw new Error(
74
- "The Bun runtime calls services over HTTP; this program calls them through the OPC UA gateway.",
75
- );
76
- }
77
78
  const st = resolve(root, emittedStDirectory);
78
79
  const manifest = debugManifest.parse(
79
80
  JSON.parse(await readFile(join(st, debugManifestFile), "utf8")),
80
81
  );
81
82
  const globals = plcGlobals(await readDeclarations(st));
82
83
 
83
- const baseUrlEnv = config.server?.baseUrlEnv;
84
- const baseUrl = (baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "")) || null;
85
- const http = {
86
- baseUrl,
87
- routes: launch.services,
84
+ const http: HttpSettings = {
88
85
  tokens: new Map(
89
86
  (config.codesys?.http?.credentials ?? []).flatMap(
90
87
  ({ originEnv, bearerTokenEnv }) => {
@@ -96,6 +93,16 @@ export const startRuntime = async (options: RuntimeOptions) => {
96
93
  ),
97
94
  timeoutMs: config.codesys?.http?.timeoutMs ?? 2000,
98
95
  };
96
+ const baseUrlEnv = config.server?.baseUrlEnv;
97
+ const baseUrl = (baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "")) || null;
98
+ // Over OPC UA the app server's gateway serves the slots this process publishes, as it serves a PLC's.
99
+ const slots =
100
+ config.server?.transport === "opcua"
101
+ ? opcuaSlots(await readServiceChannels(st), http.timeoutMs)
102
+ : null;
103
+ const transport =
104
+ slots?.transport ??
105
+ (baseUrl === null ? null : httpTransport(http, baseUrl));
99
106
 
100
107
  /** The task whose scan runs, or last ran: continuations run in their caller's task. */
101
108
  const current = { task: tasks[0]?.name ?? "", scan: 0, scanning: false };
@@ -103,14 +110,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
103
110
  const records = createTelemetry({
104
111
  build: manifest.build.id,
105
112
  capacity: config.telemetry?.capacity ?? 64,
106
- post:
107
- baseUrl === null
108
- ? null
109
- : (body) =>
110
- httpCall(http, `${baseUrl}/tsplc/telemetry`, {
111
- method: "POST",
112
- body,
113
- }),
113
+ post: transport ? (body) => transport.call("/tsplc/telemetry", body) : null,
114
114
  clock: now,
115
115
  });
116
116
  const stopTelemetry = onTelemetry((record) =>
@@ -161,7 +161,10 @@ export const startRuntime = async (options: RuntimeOptions) => {
161
161
  "@tsplc/compiler/retain": { retain },
162
162
  "@tsplc/compiler/telemetry": { telemetry, onTelemetry },
163
163
  "@tsplc/compiler/math": { min, max, clamp },
164
- "@tsplc/compiler/async": createAsync(http, diagnostics),
164
+ "@tsplc/compiler/async": createAsync(
165
+ { http, services: { routes: launch.services, transport } },
166
+ diagnostics,
167
+ ),
165
168
  "@tsplc/compiler/config": {
166
169
  env: (name: string) => {
167
170
  const value = env[name];
@@ -190,7 +193,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
190
193
  const scalars = new Map<string, PublishedScalar>();
191
194
  const bound = (global: (typeof globals.published)[number]) =>
192
195
  scalarPaths(global).every(({ path }) => {
193
- const scalar = storage.scalar(path);
196
+ const scalar = storage.scalar(path) ?? slots?.scalar(path);
194
197
  if (scalar) {
195
198
  scalars.set(path, scalar);
196
199
  }
@@ -1,3 +1,4 @@
1
+ import { httpErrors } from "@tsplc/compiler/ir";
1
2
  import { plcBufferBytes } from "@tsplc/server/wire";
2
3
 
3
4
  /** A record as the program's telemetry calls make it; see `telemetryRecord` in `@tsplc/server`. */
@@ -21,7 +22,7 @@ export const createTelemetry = (options: {
21
22
  /** The build id, as the debug manifest names it. */
22
23
  build: string;
23
24
  capacity: number;
24
- /** Posts a batch's JSON; null when the program has no server to send to, which drops records. */
25
+ /** Posts a batch's JSON, rejecting with a job error code; null when the program has no server to send to, which drops records. */
25
26
  post: ((body: string) => Promise<unknown>) | null;
26
27
  clock: () => number;
27
28
  }) => {
@@ -106,12 +107,19 @@ export const createTelemetry = (options: {
106
107
  }
107
108
  const sent = state.queued.slice(0, batch.count);
108
109
  state.sending = true;
110
+ const settle = () => {
111
+ state.queued = state.queued.filter((queued) => !sent.includes(queued));
112
+ state.waitingSince = options.clock();
113
+ };
109
114
  post(batch.body)
110
- .then(() => {
111
- state.queued = state.queued.filter((queued) => !sent.includes(queued));
112
- state.waitingSince = options.clock();
113
- })
114
- .catch(() => {
115
+ .then(settle)
116
+ .catch((reason: unknown) => {
117
+ // The server can't take these records, so they are dropped rather than sent forever.
118
+ if (reason === httpErrors.base + 400) {
119
+ state.dropped += sent.length;
120
+ settle();
121
+ return;
122
+ }
115
123
  state.waitingSince = options.clock();
116
124
  })
117
125
  .finally(() => {
@@ -0,0 +1,172 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { httpErrors, jobError } from "@tsplc/compiler/ir";
4
+ import { emittedFiles } from "@tsplc/config/project-files";
5
+ import type { PublishedScalar } from "@tsplc/opcua/server";
6
+ import { plcBufferBytes } from "@tsplc/server/wire";
7
+ import { z } from "zod";
8
+ import { type HttpSettings, httpCall } from "./async";
9
+
10
+ /**
11
+ * How the program's service calls and telemetry reach the app server, as `server.transport`
12
+ * compiled them. A call rejects with the compiled call's error code, a number, never an Error.
13
+ */
14
+ export interface Transport {
15
+ /** Sends a JSON body to a route, such as a procedure's `/tsplc/services/…` or `/tsplc/telemetry`. */
16
+ call: (route: string, body: string) => Promise<unknown>;
17
+ }
18
+
19
+ /** POSTs each body to the route under the server's base URL, with its origin's bearer token. */
20
+ export const httpTransport = (
21
+ settings: HttpSettings,
22
+ baseUrl: string,
23
+ ): Transport => ({
24
+ call: (route, body) =>
25
+ httpCall(settings, `${baseUrl}${route}`, { method: "POST", body }),
26
+ });
27
+
28
+ /** One slot of a route, as the build lists it in `machines.ts`: the global symbols it is exchanged through. */
29
+ const serviceChannel = z.strictObject({
30
+ path: z.string(),
31
+ request: z.string(),
32
+ requestId: z.string(),
33
+ reply: z.string(),
34
+ replyId: z.string(),
35
+ epoch: z.string(),
36
+ });
37
+ export type ServiceChannel = z.infer<typeof serviceChannel>;
38
+
39
+ /** The slots the build compiled, from the emitted `machines.ts`. */
40
+ export const readServiceChannels = async (
41
+ st: string,
42
+ ): Promise<ServiceChannel[]> => {
43
+ const text = await readFile(join(st, emittedFiles.machines), "utf8");
44
+ const listed = /export const serviceChannels=([\s\S]*?) as const;/.exec(text);
45
+ if (!listed?.[1]) {
46
+ throw new Error(`${emittedFiles.machines} lists no service channels.`);
47
+ }
48
+ return z.array(serviceChannel).parse(JSON.parse(listed[1]));
49
+ };
50
+
51
+ /** A slot's sequence is a UDINT; wrapping to 0 retires its epoch, as the compiled block does. */
52
+ const sequenceLimit = 2 ** 32;
53
+
54
+ /** How often a waiting call looks for its reply; the gateway itself polls every 20 ms. */
55
+ const replyPollMs = 5;
56
+
57
+ /** A reply's body after its identity: `0|<json>`, `4|…` for a request the server refused, else a failure. */
58
+ const decodeReply = (rest: string): unknown => {
59
+ if (Buffer.byteLength(rest, "utf8") < 4) {
60
+ throw jobError.malformedResponse;
61
+ }
62
+ if (rest.startsWith("4|")) {
63
+ throw httpErrors.base + 400;
64
+ }
65
+ if (!rest.startsWith("0|")) {
66
+ throw jobError.network;
67
+ }
68
+ try {
69
+ return JSON.parse(rest.slice(2));
70
+ } catch {
71
+ throw jobError.malformedResponse;
72
+ }
73
+ };
74
+
75
+ /**
76
+ * The OPC UA slots a compiled program exchanges its calls through, held in this process and
77
+ * published as the program's globals are, so the app server's gateway serves them as it serves a
78
+ * PLC's. Each call claims a free slot of its route whose epoch the gateway has set, writes its
79
+ * request and then commits it with its identity, and waits for the reply that names it.
80
+ */
81
+ export const opcuaSlots = (
82
+ channels: readonly ServiceChannel[],
83
+ timeoutMs: number,
84
+ ) => {
85
+ const values = new Map<string, string>(
86
+ channels.flatMap((channel) =>
87
+ [
88
+ channel.request,
89
+ channel.requestId,
90
+ channel.reply,
91
+ channel.replyId,
92
+ channel.epoch,
93
+ ].map((path) => [path, ""] as const),
94
+ ),
95
+ );
96
+ const read = (path: string) => values.get(path) ?? "";
97
+ const slots = new Map(
98
+ channels.map((channel) => [channel, { inUse: false, sequence: 0 }]),
99
+ );
100
+
101
+ const awaitReply = async (
102
+ channel: ServiceChannel,
103
+ epoch: string,
104
+ identity: string,
105
+ deadline: number,
106
+ ): Promise<unknown> => {
107
+ const prefix = `${identity}|`;
108
+ for (;;) {
109
+ if (performance.now() >= deadline) {
110
+ throw jobError.timeout;
111
+ }
112
+ if (read(channel.epoch) !== epoch) {
113
+ throw jobError.network;
114
+ }
115
+ const reply = read(channel.reply);
116
+ if (read(channel.replyId) === identity && reply.startsWith(prefix)) {
117
+ return decodeReply(reply.slice(prefix.length));
118
+ }
119
+ await Bun.sleep(replyPollMs);
120
+ }
121
+ };
122
+
123
+ const call = async (route: string, body: string): Promise<unknown> => {
124
+ const deadline = performance.now() + timeoutMs;
125
+ const channel = channels.find(
126
+ (candidate) =>
127
+ candidate.path === route &&
128
+ read(candidate.epoch) !== "" &&
129
+ !slots.get(candidate)?.inUse,
130
+ );
131
+ const slot = channel && slots.get(channel);
132
+ if (!channel || !slot) {
133
+ throw jobError.noRequestSlot;
134
+ }
135
+ slot.inUse = true;
136
+ try {
137
+ slot.sequence = (slot.sequence + 1) % sequenceLimit;
138
+ if (slot.sequence === 0) {
139
+ values.set(channel.epoch, "");
140
+ throw jobError.network;
141
+ }
142
+ const epoch = read(channel.epoch);
143
+ const identity = `${epoch}:${slot.sequence}`;
144
+ const request = `${identity}|${body}`;
145
+ if (Buffer.byteLength(request, "utf8") > plcBufferBytes) {
146
+ throw jobError.tooLarge;
147
+ }
148
+ values.set(channel.request, request);
149
+ // The identity commits the request: the gateway ignores a request it doesn't name.
150
+ values.set(channel.requestId, identity);
151
+ return await awaitReply(channel, epoch, identity, deadline);
152
+ } finally {
153
+ values.set(channel.requestId, "");
154
+ values.set(channel.request, "");
155
+ slot.inUse = false;
156
+ }
157
+ };
158
+
159
+ return {
160
+ transport: { call } satisfies Transport,
161
+ /** The published scalar of a slot's symbol, or undefined for any other path. */
162
+ scalar: (path: string): PublishedScalar | undefined =>
163
+ values.has(path)
164
+ ? {
165
+ read: () => read(path),
166
+ write: (value) => {
167
+ values.set(path, String(value));
168
+ },
169
+ }
170
+ : undefined,
171
+ };
172
+ };