@tsplc/compiler 0.5.6 → 0.5.7
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.
- package/dist/bun-runtime.js +139 -30
- package/dist/bun-runtime.js.map +8 -7
- package/dist/cli.js +8 -5
- package/dist/cli.js.map +3 -3
- package/dist/codesys.js +216 -85
- package/dist/codesys.js.map +8 -8
- package/dist/project.js +8 -5
- package/dist/project.js.map +3 -3
- package/package.json +9 -9
- package/src/codesys/emit.ts +8 -2
- package/src/codesys/http.ts +114 -72
- package/src/codesys/instrumentation.ts +30 -6
- package/src/codesys/routines.ts +39 -9
- package/src/codesys/st-files.ts +73 -6
- package/src/codesys/telemetry.ts +70 -35
- package/src/runtime/async.ts +15 -12
- package/src/runtime/launch.ts +11 -4
- package/src/runtime/runtime.ts +26 -23
- package/src/runtime/telemetry.ts +14 -6
- package/src/runtime/transport.ts +172 -0
package/src/codesys/st-files.ts
CHANGED
|
@@ -129,17 +129,84 @@ function objectPaths(
|
|
|
129
129
|
);
|
|
130
130
|
return `${objectPath(owner)}/methods/${object.name}`;
|
|
131
131
|
}
|
|
132
|
+
const folders = required(placed.get(object));
|
|
133
|
+
return [folderPath(folders), object.name].filter(Boolean).join("/");
|
|
134
|
+
};
|
|
135
|
+
const placedFolders = (object: GeneratedObject): string[] => {
|
|
132
136
|
const folders = sourceFolders(plan.project.root, sourceModule(object));
|
|
133
137
|
if (!folders) {
|
|
134
|
-
return
|
|
138
|
+
return [generatedFolder(object)];
|
|
135
139
|
}
|
|
136
140
|
// A DUT directory can also contain sibling input/output layouts. Keep
|
|
137
141
|
// that directory for every DUT, or its primary type would block the folder.
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
: folders;
|
|
142
|
-
return [...kept, object.name].join("/");
|
|
142
|
+
return object.kind !== "dataType" && folders.at(-1) === object.name
|
|
143
|
+
? folders.slice(0, -1)
|
|
144
|
+
: folders;
|
|
143
145
|
};
|
|
146
|
+
const placed = new Map(
|
|
147
|
+
objects
|
|
148
|
+
.filter((object) => object.kind !== "method")
|
|
149
|
+
.map((object) => [object, placedFolders(object)]),
|
|
150
|
+
);
|
|
151
|
+
const folderPath = separatedFolders(
|
|
152
|
+
[...placed].map(([object, folders]) => ({ folders, name: object.name })),
|
|
153
|
+
);
|
|
144
154
|
return objectPath;
|
|
145
155
|
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Each folder's path once no folder shares its name with an object beside it. CODESYS refuses that,
|
|
159
|
+
* ignoring case, as when a module's folder is named like an object another module places next to it:
|
|
160
|
+
* the folder takes the next free numbered name. Folders only organize the project, so no IEC name changes.
|
|
161
|
+
*/
|
|
162
|
+
export function separatedFolders(
|
|
163
|
+
objects: readonly { folders: readonly string[]; name: string }[],
|
|
164
|
+
): (folders: readonly string[]) => string {
|
|
165
|
+
const childrenOf = (entries: Iterable<readonly [string, string]>) => {
|
|
166
|
+
const children = new Map<string, Set<string>>();
|
|
167
|
+
for (const [parent, name] of entries) {
|
|
168
|
+
const names = children.get(parent) ?? new Set<string>();
|
|
169
|
+
names.add(name.toLowerCase());
|
|
170
|
+
children.set(parent, names);
|
|
171
|
+
}
|
|
172
|
+
return (parent: string) => children.get(parent) ?? new Set<string>();
|
|
173
|
+
};
|
|
174
|
+
const objectsIn = childrenOf(
|
|
175
|
+
objects.map(({ folders, name }) => [folders.join("/"), name] as const),
|
|
176
|
+
);
|
|
177
|
+
const foldersIn = childrenOf(
|
|
178
|
+
objects.flatMap(({ folders }) =>
|
|
179
|
+
folders.map((name, depth) => [folders.slice(0, depth).join("/"), name]),
|
|
180
|
+
),
|
|
181
|
+
);
|
|
182
|
+
const renamed = new Map<string, string>();
|
|
183
|
+
const given = new Map<string, Set<string>>();
|
|
184
|
+
const folderPath = (folders: readonly string[]): string => {
|
|
185
|
+
const key = folders.join("/");
|
|
186
|
+
const known = renamed.get(key);
|
|
187
|
+
if (known !== undefined) {
|
|
188
|
+
return known;
|
|
189
|
+
}
|
|
190
|
+
if (folders.length === 0) {
|
|
191
|
+
return "";
|
|
192
|
+
}
|
|
193
|
+
const parentKey = folders.slice(0, -1).join("/");
|
|
194
|
+
const name = required(folders.at(-1));
|
|
195
|
+
const taken = given.get(parentKey) ?? new Set<string>();
|
|
196
|
+
given.set(parentKey, taken);
|
|
197
|
+
const blocked = (candidate: string) =>
|
|
198
|
+
objectsIn(parentKey).has(candidate.toLowerCase()) ||
|
|
199
|
+
taken.has(candidate.toLowerCase()) ||
|
|
200
|
+
(candidate !== name && foldersIn(parentKey).has(candidate.toLowerCase()));
|
|
201
|
+
const free = (count: number): string =>
|
|
202
|
+
blocked(`${name}_${count}`) ? free(count + 1) : `${name}_${count}`;
|
|
203
|
+
const chosen = blocked(name) ? free(2) : name;
|
|
204
|
+
taken.add(chosen.toLowerCase());
|
|
205
|
+
const path = [folderPath(folders.slice(0, -1)), chosen]
|
|
206
|
+
.filter(Boolean)
|
|
207
|
+
.join("/");
|
|
208
|
+
renamed.set(key, path);
|
|
209
|
+
return path;
|
|
210
|
+
};
|
|
211
|
+
return folderPath;
|
|
212
|
+
}
|
package/src/codesys/telemetry.ts
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
httpMethods,
|
|
22
22
|
jsonScalar,
|
|
23
23
|
nativeHttp,
|
|
24
|
+
opcuaClient,
|
|
24
25
|
resolveHttpEndpoint,
|
|
25
26
|
} from "./http";
|
|
26
27
|
import { Sources } from "./sources";
|
|
@@ -361,11 +362,31 @@ export function planTelemetry(
|
|
|
361
362
|
|
|
362
363
|
const server = project.server;
|
|
363
364
|
const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
|
|
365
|
+
const plan: TelemetryPlan = {
|
|
366
|
+
...settings,
|
|
367
|
+
// One ring per task holds the trace too.
|
|
368
|
+
capacity: Math.max(
|
|
369
|
+
settings.capacity,
|
|
370
|
+
project.trace ? project.trace.capacity : 0,
|
|
371
|
+
),
|
|
372
|
+
calls,
|
|
373
|
+
failures,
|
|
374
|
+
...(project.trace && { traceOperands: project.trace.operands }),
|
|
375
|
+
};
|
|
364
376
|
if (server?.transport === "opcua") {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
377
|
+
return {
|
|
378
|
+
telemetry: plan,
|
|
379
|
+
endpoint: {
|
|
380
|
+
transport: "opcua",
|
|
381
|
+
host: "",
|
|
382
|
+
port: 0,
|
|
383
|
+
authority: "",
|
|
384
|
+
path: telemetryPath,
|
|
385
|
+
token: "",
|
|
386
|
+
timeoutMs: options.http.timeoutMs,
|
|
387
|
+
tls: false,
|
|
388
|
+
},
|
|
389
|
+
};
|
|
369
390
|
}
|
|
370
391
|
if (!base) {
|
|
371
392
|
report(
|
|
@@ -375,17 +396,7 @@ export function planTelemetry(
|
|
|
375
396
|
}
|
|
376
397
|
try {
|
|
377
398
|
return {
|
|
378
|
-
telemetry:
|
|
379
|
-
...settings,
|
|
380
|
-
// One ring per task holds the trace too.
|
|
381
|
-
capacity: Math.max(
|
|
382
|
-
settings.capacity,
|
|
383
|
-
project.trace ? project.trace.capacity : 0,
|
|
384
|
-
),
|
|
385
|
-
calls,
|
|
386
|
-
failures,
|
|
387
|
-
...(project.trace && { traceOperands: project.trace.operands }),
|
|
388
|
-
},
|
|
399
|
+
telemetry: plan,
|
|
389
400
|
endpoint: resolveHttpEndpoint(
|
|
390
401
|
`${base.replace(/\/+$/, "")}${telemetryPath}`,
|
|
391
402
|
options.http,
|
|
@@ -452,20 +463,23 @@ const batchRecords = (recordBytes: number) => {
|
|
|
452
463
|
* shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
|
|
453
464
|
* sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
|
|
454
465
|
*/
|
|
466
|
+
/** How the sender reaches the server: its HTTP client's endpoint and network, or the OPC UA slots it posts through. */
|
|
467
|
+
export type TelemetryTransport =
|
|
468
|
+
| { kind: "http"; endpoint: HttpEndpoint; network: string }
|
|
469
|
+
| { kind: "opcua"; timeoutMs: number; rpcGlobal: string };
|
|
470
|
+
|
|
455
471
|
export function telemetryObjects({
|
|
456
472
|
plan,
|
|
457
473
|
names,
|
|
458
474
|
target,
|
|
459
|
-
|
|
460
|
-
network,
|
|
475
|
+
transport,
|
|
461
476
|
build,
|
|
462
477
|
types,
|
|
463
478
|
}: {
|
|
464
479
|
plan: TelemetryPlan;
|
|
465
480
|
names: { writer: string; record: string; client: string };
|
|
466
481
|
target: CodesysTypes;
|
|
467
|
-
|
|
468
|
-
network: string;
|
|
482
|
+
transport: TelemetryTransport;
|
|
469
483
|
build: string;
|
|
470
484
|
types: ReadonlyMap<string, PlcType>;
|
|
471
485
|
}): GeneratedObject[] {
|
|
@@ -623,18 +637,42 @@ export function telemetryObjects({
|
|
|
623
637
|
const helpers = httpMethods(writer).filter((item) =>
|
|
624
638
|
["ByteLength", "Append", "WriteString"].includes(item.name),
|
|
625
639
|
);
|
|
626
|
-
const
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
640
|
+
const clientPorts = `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`;
|
|
641
|
+
const clientObjects =
|
|
642
|
+
transport.kind === "opcua"
|
|
643
|
+
? [
|
|
644
|
+
opcuaClient({
|
|
645
|
+
id: telemetryClient,
|
|
646
|
+
name: names.client,
|
|
647
|
+
ports: clientPorts,
|
|
648
|
+
port: (label) => label,
|
|
649
|
+
timeoutMs: transport.timeoutMs,
|
|
650
|
+
rpcGlobal: transport.rpcGlobal,
|
|
651
|
+
body: "Append(body);",
|
|
652
|
+
decode: "",
|
|
653
|
+
}),
|
|
654
|
+
...httpMethods(telemetryClient, "opcua"),
|
|
655
|
+
]
|
|
656
|
+
: [
|
|
657
|
+
...nativeHttp({
|
|
658
|
+
id: telemetryClient,
|
|
659
|
+
name: names.client,
|
|
660
|
+
ports: clientPorts,
|
|
661
|
+
port: (label) => label,
|
|
662
|
+
endpoint: transport.endpoint,
|
|
663
|
+
network: transport.network,
|
|
664
|
+
method: "POST",
|
|
665
|
+
json: true,
|
|
666
|
+
body: "Append(body);",
|
|
667
|
+
decode: "",
|
|
668
|
+
}),
|
|
669
|
+
...httpMethods(telemetryClient),
|
|
670
|
+
...httpCertificateVerifier(
|
|
671
|
+
telemetryClient,
|
|
672
|
+
names.client,
|
|
673
|
+
transport.endpoint,
|
|
674
|
+
),
|
|
675
|
+
];
|
|
638
676
|
return [
|
|
639
677
|
{
|
|
640
678
|
id: "tsplc:telemetryRecord",
|
|
@@ -772,9 +810,6 @@ WriteString(text);
|
|
|
772
810
|
...calls,
|
|
773
811
|
...failures,
|
|
774
812
|
...trace,
|
|
775
|
-
|
|
776
|
-
...clientLifecycle,
|
|
777
|
-
...httpMethods(telemetryClient),
|
|
778
|
-
...httpCertificateVerifier(telemetryClient, names.client, endpoint),
|
|
813
|
+
...clientObjects,
|
|
779
814
|
];
|
|
780
815
|
}
|
package/src/runtime/async.ts
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
import { httpErrors, jobError } from "@tsplc/compiler/ir";
|
|
2
2
|
import { plcBufferBytes } from "@tsplc/server/wire";
|
|
3
|
+
import type { Transport } from "./transport";
|
|
3
4
|
|
|
4
5
|
/** How the program's HTTP calls reach their servers, as the build compiled them. */
|
|
5
6
|
export interface HttpSettings {
|
|
6
|
-
/** The services' base URL, from `server.baseUrlEnv`; null without a server. */
|
|
7
|
-
baseUrl: string | null;
|
|
8
|
-
/** Each service procedure's route, by its path such as `catalog.resolve`. */
|
|
9
|
-
routes: Readonly<Record<string, string>>;
|
|
10
7
|
/** Bearer tokens by the exact origin they are sent to. */
|
|
11
8
|
tokens: ReadonlyMap<string, string>;
|
|
12
9
|
timeoutMs: number;
|
|
13
10
|
}
|
|
14
11
|
|
|
12
|
+
/** How the program's service calls reach the app server. */
|
|
13
|
+
export interface ServiceSettings {
|
|
14
|
+
/** Each service procedure's route, by its path such as `catalog.resolve`. */
|
|
15
|
+
routes: Readonly<Record<string, string>>;
|
|
16
|
+
/** The configured transport; null when HTTP has no server base URL to send to. */
|
|
17
|
+
transport: Transport | null;
|
|
18
|
+
}
|
|
19
|
+
|
|
15
20
|
/** Why the program's call failed, as a compiled call reports it: a job error code. */
|
|
16
21
|
const failure = (cause: unknown) => {
|
|
17
22
|
if (cause instanceof Error && cause.name === "TimeoutError") {
|
|
@@ -89,20 +94,18 @@ export const unsupported = (name: string) => () => {
|
|
|
89
94
|
|
|
90
95
|
/** What the program's `@tsplc/compiler/async` does in the Bun runtime. */
|
|
91
96
|
export const createAsync = (
|
|
92
|
-
settings: HttpSettings,
|
|
97
|
+
settings: { http: HttpSettings; services: ServiceSettings },
|
|
93
98
|
diagnostics: { count: number; lastError: number },
|
|
94
99
|
) => {
|
|
95
100
|
const call = (path: string, input: unknown) => {
|
|
96
|
-
const route = settings.routes[path];
|
|
97
|
-
|
|
101
|
+
const route = settings.services.routes[path];
|
|
102
|
+
const { transport } = settings.services;
|
|
103
|
+
if (!route || !transport) {
|
|
98
104
|
return Promise.reject(
|
|
99
105
|
new Error(`The build compiled no call to the service ${path}.`),
|
|
100
106
|
);
|
|
101
107
|
}
|
|
102
|
-
return
|
|
103
|
-
method: "POST",
|
|
104
|
-
body: JSON.stringify(input),
|
|
105
|
-
});
|
|
108
|
+
return transport.call(route, JSON.stringify(input));
|
|
106
109
|
};
|
|
107
110
|
/** A service client: any property is a deeper procedure path, and calling one calls that procedure. */
|
|
108
111
|
const client = (path: readonly string[]): unknown =>
|
|
@@ -114,7 +117,7 @@ export const createAsync = (
|
|
|
114
117
|
return {
|
|
115
118
|
createServiceClient: () => client([]),
|
|
116
119
|
fetch: (url: string, options: { method?: string; json?: unknown } = {}) =>
|
|
117
|
-
httpCall(settings, url, {
|
|
120
|
+
httpCall(settings.http, url, {
|
|
118
121
|
method: options.method ?? "GET",
|
|
119
122
|
...(options.json !== undefined && {
|
|
120
123
|
body: JSON.stringify(options.json),
|
package/src/runtime/launch.ts
CHANGED
|
@@ -35,14 +35,21 @@ export const runtimeStateSchema = z.strictObject({
|
|
|
35
35
|
});
|
|
36
36
|
export type RuntimeState = z.infer<typeof runtimeStateSchema>;
|
|
37
37
|
|
|
38
|
+
/** A service block's route: its URL's path over HTTP, the path its slots carry over OPC UA. */
|
|
39
|
+
const blockRoute = (
|
|
40
|
+
runtime: VerifiedCoreModule["blocks"][number]["runtime"],
|
|
41
|
+
) => {
|
|
42
|
+
if (runtime?.kind === "http") {
|
|
43
|
+
return URL.parse(runtime.url)?.pathname;
|
|
44
|
+
}
|
|
45
|
+
return runtime?.kind === "rpc" ? runtime.path : undefined;
|
|
46
|
+
};
|
|
47
|
+
|
|
38
48
|
/** The route each service call the program makes goes to, as the build compiled it. */
|
|
39
49
|
export const serviceRoutes = (core: VerifiedCoreModule) =>
|
|
40
50
|
Object.fromEntries(
|
|
41
51
|
core.blocks.flatMap((block) => {
|
|
42
|
-
|
|
43
|
-
return [];
|
|
44
|
-
}
|
|
45
|
-
const route = URL.parse(block.runtime.url)?.pathname;
|
|
52
|
+
const route = blockRoute(block.runtime);
|
|
46
53
|
const procedure = route && serviceOfPath(route);
|
|
47
54
|
return route && procedure ? [[procedure, route] as const] : [];
|
|
48
55
|
}),
|
package/src/runtime/runtime.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
*
|
|
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
|
|
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(
|
|
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
|
}
|
package/src/runtime/telemetry.ts
CHANGED
|
@@ -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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
+
};
|