@tsplc/compiler 0.2.14 → 0.2.17

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 (54) hide show
  1. package/backends/codesys/debug.ts +509 -0
  2. package/backends/codesys/emit.ts +701 -9
  3. package/backends/codesys/http.ts +110 -34
  4. package/backends/codesys/index.ts +2 -1
  5. package/backends/codesys/io-paths.ts +3 -1
  6. package/backends/codesys/manifest.ts +312 -0
  7. package/backends/codesys/plan.ts +39 -9
  8. package/backends/codesys/publication.ts +2 -2
  9. package/backends/codesys/storage.ts +10 -3
  10. package/backends/codesys/task-access.ts +51 -1
  11. package/backends/codesys/telemetry.ts +593 -0
  12. package/backends/codesys/types.ts +2 -1
  13. package/dist/cli.js +190 -33
  14. package/dist/cli.js.map +6 -6
  15. package/dist/codesys.js +2148 -432
  16. package/dist/codesys.js.map +14 -11
  17. package/dist/elaborate-capture.js +7 -1
  18. package/dist/elaborate-capture.js.map +3 -3
  19. package/dist/index.js +877 -459
  20. package/dist/index.js.map +16 -15
  21. package/dist/ir.js +87 -23
  22. package/dist/ir.js.map +10 -9
  23. package/dist/project.js +42 -9
  24. package/dist/project.js.map +3 -3
  25. package/dist/telemetry.js +83 -0
  26. package/dist/telemetry.js.map +12 -0
  27. package/ir/core-model.ts +13 -0
  28. package/ir/core.ts +1 -0
  29. package/ir/errors.ts +20 -0
  30. package/ir/index.ts +1 -0
  31. package/ir/link.ts +17 -8
  32. package/ir/model.ts +39 -0
  33. package/ir/routine.ts +62 -29
  34. package/ir/types.ts +7 -1
  35. package/package.json +12 -6
  36. package/project/cli.ts +96 -6
  37. package/project/plant.ts +58 -9
  38. package/project/project.ts +56 -10
  39. package/src/frontend/async.ts +284 -195
  40. package/src/frontend/configuration.ts +7 -21
  41. package/src/frontend/const-functions.ts +44 -38
  42. package/src/frontend/elaborate/capture.ts +7 -0
  43. package/src/frontend/elaborate/index.ts +135 -61
  44. package/src/frontend/elaborate/layouts.ts +8 -0
  45. package/src/frontend/elaborate/model.ts +13 -0
  46. package/src/frontend/elaborate/specialize.ts +302 -111
  47. package/src/frontend/exposure.ts +28 -26
  48. package/src/frontend/positions.ts +272 -0
  49. package/src/frontend/promises.ts +52 -47
  50. package/src/frontend/services.ts +16 -26
  51. package/src/frontend/types.ts +14 -0
  52. package/src/frontend/typescript.ts +185 -65
  53. package/stdlib/telemetry.ts +72 -0
  54. package/types/telemetry.d.ts +44 -0
@@ -8,9 +8,16 @@ interface GlobalList {
8
8
  variables: Variable[];
9
9
  }
10
10
 
11
- /** The source module that owns a module-level variable: its file name without extension. */
11
+ /**
12
+ * The module that declares a module-level variable, from its id. Spans point at what the user
13
+ * wrote, which for elaborated storage is not the module the elaborator made for it.
14
+ */
15
+ export const moduleFile = (variable: Variable): string =>
16
+ variable.id.slice(0, variable.id.indexOf(":"));
17
+
18
+ /** The module's name: its file name without extension. */
12
19
  export const moduleName = (variable: Variable): string =>
13
- basename(variable.span.file).replace(/\.[^.]+$/, "");
20
+ basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
14
21
 
15
22
  /** CODESYS promotes an enclosing instance when private child state is retained. */
16
23
  export function storageLayout(core: VerifiedCoreModule) {
@@ -51,7 +58,7 @@ export function storageLayout(core: VerifiedCoreModule) {
51
58
  : retainedVariables.has(variable.id)
52
59
  ? "retained"
53
60
  : "state";
54
- const id = `${variable.span.file}:${storage}`;
61
+ const id = `${moduleFile(variable)}:${storage}`;
55
62
  let group = groups.get(id);
56
63
  if (!group) {
57
64
  group = { id, module: moduleName(variable), storage, variables: [] };
@@ -1,9 +1,11 @@
1
- import { instancedBlock } from "@tsplc/compiler/ir";
1
+ import { instancedBlock, nestedBodies, telemetryOperands } from "@tsplc/compiler/ir";
2
2
  import type {
3
3
  CoreExpression,
4
4
  CoreFunction,
5
+ CoreFunctionBlock,
5
6
  CorePath,
6
7
  CoreStatement,
8
+ Deployment,
7
9
  PlcProgram,
8
10
  SourceSpan,
9
11
  Task,
@@ -12,6 +14,53 @@ import type {
12
14
 
13
15
  type Report = (message: string, span?: SourceSpan) => void;
14
16
 
17
+ /** The task that runs each function and block; undefined for one more than one task runs. */
18
+ export function routineTasks(
19
+ core: VerifiedCoreModule,
20
+ deployment: Deployment,
21
+ ): Map<string, string | undefined> {
22
+ const tasks = new Map<string, string | undefined>();
23
+ const types = new Map(core.types.map((type) => [type.id, type]));
24
+ const routines = new Map<string, CoreFunction | CoreFunctionBlock>(
25
+ [...core.functions, ...core.blocks].map((routine) => [routine.id, routine]),
26
+ );
27
+ const variables = new Map(
28
+ [
29
+ ...core.variables,
30
+ ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
31
+ ...core.blocks.flatMap((block) => [
32
+ ...block.inputs,
33
+ ...block.outputs,
34
+ ...block.state,
35
+ ...block.locals,
36
+ ]),
37
+ ].map((variable) => [variable.id, variable]),
38
+ );
39
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
40
+ for (const task of deployment.tasks)
41
+ for (const name of task.programs) {
42
+ const seen = new Set<string>();
43
+ const visit = (id: string): void => {
44
+ if (seen.has(id)) return;
45
+ seen.add(id);
46
+ tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
47
+ const inspect = (items: readonly CoreStatement[]): void => {
48
+ for (const item of items) {
49
+ if (item.kind === "invoke") visit(item.function);
50
+ if (item.kind === "blockUpdate") {
51
+ const block = instancedBlock(variables.get(item.instance)!.type, types);
52
+ if (block) visit(block.block);
53
+ }
54
+ for (const body of nestedBodies(item)) inspect(body);
55
+ }
56
+ };
57
+ inspect(routines.get(id)?.body ?? []);
58
+ };
59
+ visit(programs.get(name)!.entry);
60
+ }
61
+ return tasks;
62
+ }
63
+
15
64
  export function schedulePrograms(
16
65
  core: VerifiedCoreModule,
17
66
  tasks: readonly Task[],
@@ -162,6 +211,7 @@ export function accessedStorage(
162
211
  body(item.body);
163
212
  }
164
213
  if (item.kind === "return" && item.value) expression(item.value);
214
+ if (item.kind === "telemetry") telemetryOperands(item).forEach(expression);
165
215
  if (item.kind === "invoke") {
166
216
  if (item.instance && item !== scheduledCall) result.add(item.instance);
167
217
  if (item.index) expression(item.index);
@@ -0,0 +1,593 @@
1
+ import {
2
+ errorName,
3
+ httpErrors,
4
+ jobErrors,
5
+ nestedBodies,
6
+ type CoreStatement,
7
+ type Deployment,
8
+ type GeneratedObject,
9
+ type PlcType,
10
+ type SourceSpan,
11
+ type VerifiedCoreModule,
12
+ } from "@tsplc/compiler/ir";
13
+ import { telemetrySchema, type ResolvedTelemetryConfig } from "@tsplc/config";
14
+ import type { CodesysOptions } from "./config.ts";
15
+ import { blockInstances, type InstancePath } from "./debug.ts";
16
+ import {
17
+ httpCertificateVerifier,
18
+ httpMethods,
19
+ jsonScalar,
20
+ nativeHttp,
21
+ quote,
22
+ resolveHttpEndpoint,
23
+ type HttpEndpoint,
24
+ } from "./http.ts";
25
+ import { Sources } from "./manifest.ts";
26
+ import { routineTasks } from "./task-access.ts";
27
+ import type { CodesysTypes } from "./types.ts";
28
+
29
+ /** The sender's key in `CodesysPlan.http`, and its HTTP block's id. */
30
+ export const telemetryClient = "tsplc:telemetry";
31
+ /** Where each task posts its records, below the server's base URL. */
32
+ export const telemetryPath = "/tsplc/telemetry";
33
+ /** A sender waits this long for a batch to fill. */
34
+ const sendIntervalMs = 200;
35
+ /** The HTTP body buffer a batch must fit. */
36
+ const batchBytes = 2048;
37
+ /** The longest task name a batch carries, as the wire allows. */
38
+ const taskBytes = 64;
39
+
40
+ type TelemetryStatement = Extract<CoreStatement, { kind: "telemetry" }>;
41
+
42
+ /** A telemetry call: `record` is the JSON its method writes before the properties' values. */
43
+ interface CallSite {
44
+ id: number;
45
+ task: string;
46
+ record: string;
47
+ call: TelemetryStatement;
48
+ }
49
+
50
+ /** A root job's unhandled failure; its source is that of the step it failed at. */
51
+ interface FailureSite {
52
+ id: number;
53
+ task: string;
54
+ record: string;
55
+ sources: readonly { source: string; steps: readonly number[] }[];
56
+ }
57
+
58
+ export interface TelemetryPlan extends ResolvedTelemetryConfig {
59
+ calls: ReadonlyMap<CoreStatement, CallSite>;
60
+ /** By job block id. */
61
+ failures: ReadonlyMap<string, FailureSite>;
62
+ /** `debug.trace`'s operand count, when the trace is on. */
63
+ traceOperands?: number;
64
+ }
65
+
66
+ /** A string as JSON text in ASCII, so it can sit in an ST literal. */
67
+ const json = (value: string) =>
68
+ JSON.stringify(value).replace(
69
+ /[^ -~]/g,
70
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`,
71
+ );
72
+
73
+ /** Compiler-made jobs, such as a service call's own, carry this prefix. */
74
+ export const generated = (name: string) => name.startsWith("tsplc");
75
+
76
+ const maximum = (values: readonly number[]) => values.reduce((a, b) => Math.max(a, b), 0);
77
+
78
+ /** `Commit` ends every record with the task's scan and clock. */
79
+ const commitSize = ',"scan":,"time":}'.length + 2 * 10;
80
+ /** `ErrorName` names a known error code. */
81
+ const errorNames = Object.entries(jobErrors).filter(([code]) => Number(code) < httpErrors.base);
82
+ const codeSize =
83
+ ',"code":'.length +
84
+ 10 +
85
+ ',"name":'.length +
86
+ maximum([...errorNames.map(([, name]) => json(name).length), json("HTTP 999").length]);
87
+
88
+ /** The most bytes a property's value takes. */
89
+ function valueSize(type: PlcType, text: boolean): number {
90
+ if (text && type.kind === "array") return type.length * 6 + 2;
91
+ if (type.kind === "enum")
92
+ return maximum([4, ...type.members.map((member) => json(member.text ?? member.name).length)]);
93
+ if (type.kind === "float") return type.bits === 32 ? 16 : 25;
94
+ const scalar = jsonScalar(type, "");
95
+ if (!scalar) throw new Error(`Unverified telemetry value type ${type.id}.`);
96
+ return scalar.size;
97
+ }
98
+
99
+ const traceRecord = (operands: number) => ({
100
+ prefix: '{"kind":"trace","site":',
101
+ size:
102
+ '{"kind":"trace","site":,"value":,"operands":[]'.length + 5 + 11 + operands * 12 + commitSize,
103
+ });
104
+
105
+ /**
106
+ * Whether a build has telemetry: the program calls `@tsplc/compiler/telemetry`, `telemetry` is
107
+ * configured, or `debug.trace` is on. Then every task with something to record gets a ring and
108
+ * a sender, root jobs' unhandled failures included; otherwise nothing is added.
109
+ */
110
+ export function planTelemetry(
111
+ core: VerifiedCoreModule,
112
+ deployment: Deployment,
113
+ options: CodesysOptions,
114
+ project: {
115
+ root: string;
116
+ telemetry?: ResolvedTelemetryConfig;
117
+ trace?: { capacity: number; operands: number } | false;
118
+ server?: { transport: "http" | "opcua"; baseUrlEnv?: string };
119
+ },
120
+ report: (message: string, span?: SourceSpan) => void,
121
+ ): { telemetry?: TelemetryPlan; endpoint?: HttpEndpoint } {
122
+ const types = new Map(core.types.map((type) => [type.id, type]));
123
+ const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
124
+ const statements: { routine: string; call: TelemetryStatement }[] = [];
125
+ const find = (routine: string, items: readonly CoreStatement[]): void => {
126
+ for (const item of items) {
127
+ if (item.kind === "telemetry") statements.push({ routine, call: item });
128
+ for (const body of nestedBodies(item)) find(routine, body);
129
+ }
130
+ };
131
+ for (const routine of routines) find(routine.id, routine.body);
132
+ if (!statements.length && !project.telemetry && !project.trace) return {};
133
+
134
+ const settings = project.telemetry ?? telemetrySchema.parse({});
135
+ const sources = new Sources(project.root);
136
+ const location = (span: SourceSpan) => {
137
+ const range = sources.range(span);
138
+ return range ? `${sources.files[range.file]}:${range.line}` : "";
139
+ };
140
+ const tasks = routineTasks(core, deployment);
141
+ const tooLarge = (size: number, what: string, span?: SourceSpan) => {
142
+ if (size > settings.recordBytes)
143
+ report(
144
+ `${what} can take ${size} bytes of JSON, more than telemetry.recordBytes (${settings.recordBytes}). Use fewer or shorter properties, smaller STRING or byte array bounds, or raise recordBytes.`,
145
+ span,
146
+ );
147
+ };
148
+
149
+ const calls = new Map<CoreStatement, CallSite>();
150
+ for (const { routine, call } of statements) {
151
+ const task = tasks.get(routine);
152
+ if (!task) {
153
+ report(
154
+ "Telemetry calls must be in code that one task runs: each task writes its own records.",
155
+ call.span,
156
+ );
157
+ continue;
158
+ }
159
+ const source = json(location(call.span));
160
+ const { record } = call;
161
+ const head =
162
+ record.kind === "event"
163
+ ? `{"kind":"event","event":${json(record.event)}`
164
+ : record.kind === "log"
165
+ ? `{"kind":"log","level":"${record.level}","message":${json(record.message)}`
166
+ : '{"kind":"exception","handled":true';
167
+ const prefix = `${head},"source":${source},"properties":{`;
168
+ const size =
169
+ prefix.length +
170
+ call.properties.reduce(
171
+ (total, { name, value, length }, index) =>
172
+ total +
173
+ (index ? 1 : 0) +
174
+ json(name).length +
175
+ 1 +
176
+ valueSize(types.get(value.type)!, length !== undefined),
177
+ 0,
178
+ ) +
179
+ 1 +
180
+ (record.kind === "exception" ? codeSize : 0) +
181
+ commitSize;
182
+ tooLarge(size, "This telemetry record", call.span);
183
+ calls.set(call, { id: calls.size + 1, task, record: prefix, call });
184
+ }
185
+
186
+ // A root job is one no other job awaits; a job it starts reports its failure to it.
187
+ const failures = new Map<string, FailureSite>();
188
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
189
+ const instances = blockInstances(core);
190
+ const awaited = (path: InstancePath) =>
191
+ path.slice(0, -1).some(({ variable }) => {
192
+ const type = types.get(variable.type);
193
+ const element = type?.kind === "array" ? types.get(type.element) : type;
194
+ return element?.kind === "block" && blocks.get(element.block)?.job;
195
+ });
196
+ for (const block of core.blocks) {
197
+ const { job } = block;
198
+ const task = tasks.get(block.id);
199
+ const paths = instances.get(block.id)!;
200
+ // A job run by more than one task, or by none, has no ring to record into.
201
+ if (!job || !task || !paths.length || paths.some(awaited)) continue;
202
+ // `void work()` runs `work` in a compiler-made job; its failure is the work's.
203
+ const children = block.state.flatMap((child) => {
204
+ const type = types.get(child.type);
205
+ const called = type?.kind === "block" ? blocks.get(type.block)?.job : undefined;
206
+ return called && !generated(called.name) ? [called] : [];
207
+ });
208
+ const named = generated(job.name) && children.length === 1 ? children[0]! : job;
209
+ const fallback = location(job.span);
210
+ const steps = new Map<string, number[]>();
211
+ for (const step of job.steps) {
212
+ const source = location(step.span) || fallback;
213
+ steps.set(source, [...(steps.get(source) ?? []), step.step]);
214
+ }
215
+ const record = `{"kind":"exception","handled":false,"function":${json(named.name)},${named.instance ? `"instance":${json(named.instance)},` : ""}"properties":{}`;
216
+ tooLarge(
217
+ record.length +
218
+ codeSize +
219
+ ',"source":""'.length +
220
+ maximum([...steps.keys(), fallback].map((source) => json(source).length - 2)) +
221
+ commitSize,
222
+ `The failure record of ${named.name}`,
223
+ job.span,
224
+ );
225
+ failures.set(block.id, {
226
+ id: failures.size + 1,
227
+ task,
228
+ record,
229
+ sources: [...steps].map(([source, numbers]) => ({ source, steps: numbers })),
230
+ });
231
+ }
232
+
233
+ if (project.trace)
234
+ tooLarge(traceRecord(project.trace.operands).size, "A debug.trace record with its operands");
235
+
236
+ const server = project.server;
237
+ const base = server?.baseUrlEnv && process.env[server.baseUrlEnv];
238
+ if (server?.transport === "opcua") {
239
+ report(
240
+ `Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`,
241
+ );
242
+ return {};
243
+ }
244
+ if (!base) {
245
+ report(
246
+ `Telemetry posts to the app server: set server.baseUrlEnv and that environment variable to its base URL.`,
247
+ );
248
+ return {};
249
+ }
250
+ try {
251
+ return {
252
+ telemetry: {
253
+ ...settings,
254
+ // One ring per task holds the trace too.
255
+ capacity: Math.max(settings.capacity, project.trace ? project.trace.capacity : 0),
256
+ calls,
257
+ failures,
258
+ ...(project.trace && { traceOperands: project.trace.operands }),
259
+ },
260
+ endpoint: resolveHttpEndpoint(`${base.replace(/\/+$/, "")}${telemetryPath}`, options.http),
261
+ };
262
+ } catch (cause) {
263
+ report(cause instanceof Error ? cause.message : String(cause));
264
+ return {};
265
+ }
266
+ }
267
+
268
+ /** A call's method parameters, in declaration order: `p<n>` for each property, `code` for an exception. */
269
+ export const callParameters = ({ record, properties }: TelemetryStatement) => [
270
+ ...properties.flatMap(({ value, length }, index) => [
271
+ { name: `p${index}`, value, text: length !== undefined },
272
+ ...(length ? [{ name: `p${index}Length`, value: length, text: false }] : []),
273
+ ]),
274
+ ...(record.kind === "exception" ? [{ name: "code", value: record.code, text: false }] : []),
275
+ ];
276
+
277
+ /** The batch header's literal parts, before and after the task's name. */
278
+ const header = (build: string) => ({
279
+ start: `{"build":${json(build)},"task":"`,
280
+ rest: ['","now":', ',"scan":', ',"first":', ',"dropped":', ',"records":['],
281
+ });
282
+
283
+ /** Records that always fit a batch beside its header: a sender with this many unsent sends at once. */
284
+ const batchRecords = (recordBytes: number) => {
285
+ const { start, rest } = header("0".repeat(16));
286
+ const fixed = start.length + taskBytes + rest.join("").length + 2 * 10 + 2 * 20 + "]}".length;
287
+ return Math.max(1, Math.floor((batchBytes - fixed) / (recordBytes + 1)));
288
+ };
289
+
290
+ /**
291
+ * The ring and sender of a task, `FB_TsplcTelemetry`: one method per call site and root job, a
292
+ * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
293
+ * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
294
+ */
295
+ export function telemetryObjects({
296
+ plan,
297
+ names,
298
+ target,
299
+ endpoint,
300
+ network,
301
+ build,
302
+ types,
303
+ }: {
304
+ plan: TelemetryPlan;
305
+ names: { writer: string; record: string; client: string };
306
+ target: CodesysTypes;
307
+ endpoint: HttpEndpoint;
308
+ network: string;
309
+ build: string;
310
+ types: ReadonlyMap<string, PlcType>;
311
+ }): GeneratedObject[] {
312
+ const writer = "tsplc:telemetryWriter";
313
+ const { capacity, recordBytes } = plan;
314
+ const method = (
315
+ name: string,
316
+ declaration: string,
317
+ implementation: string,
318
+ access = "",
319
+ ): GeneratedObject => ({
320
+ id: `${writer}:${name}`,
321
+ parent: writer,
322
+ kind: "method",
323
+ name,
324
+ declaration: `METHOD ${access}${name}\n${declaration}`,
325
+ implementation,
326
+ });
327
+ const encode = (type: PlcType, parameter: string, text: boolean): string => {
328
+ if (text && type.kind === "array")
329
+ return `WriteText(ADR(${parameter}), LINT_TO_DINT(LIMIT(0, TO_LINT(${parameter}Length), ${type.length})));`;
330
+ if (type.kind === "enum")
331
+ return `CASE ${parameter} OF ${type.members.map((member) => `${target.name(type.id)}.${target.field(type.id, member.name)}: Append(${quote(json(member.text ?? member.name))});`).join(" ")} ELSE Append('null'); END_CASE;`;
332
+ if (type.kind === "float") {
333
+ const iec = type.bits === 32 ? "REAL" : "LREAL";
334
+ return `IF ${parameter} = ${parameter} AND ABS(${parameter}) < ${iec}#${type.bits === 32 ? "3.4E38" : "1.7E308"} THEN Append(${iec}_TO_STRING(${parameter})); ELSE Append('null'); END_IF;`;
335
+ }
336
+ return jsonScalar(type, parameter)!.code;
337
+ };
338
+
339
+ const calls = [...plan.calls.values()].map(({ id, record, call }) => {
340
+ const parameters = callParameters(call);
341
+ const inputs = parameters.filter((parameter) => !parameter.text);
342
+ const references = parameters.filter((parameter) => parameter.text);
343
+ const properties = call.properties.map(({ name, value, length }, index) => {
344
+ const code = encode(types.get(value.type)!, `p${index}`, length !== undefined);
345
+ return `Append(${quote(`${index ? "," : ""}${json(name)}:`)});\n${code}`;
346
+ });
347
+ return method(
348
+ `Record${id}`,
349
+ [
350
+ ...(inputs.length
351
+ ? [
352
+ "VAR_INPUT",
353
+ ...inputs.map((input) => ` ${input.name} : ${target.name(input.value.type)};`),
354
+ "END_VAR",
355
+ ]
356
+ : []),
357
+ ...(references.length
358
+ ? [
359
+ "VAR_IN_OUT",
360
+ ...references.map((input) => ` ${input.name} : ${target.name(input.value.type)};`),
361
+ "END_VAR",
362
+ ]
363
+ : []),
364
+ ]
365
+ .map((line) => `${line}\n`)
366
+ .join(""),
367
+ [
368
+ "payload := '';",
369
+ `Append(${quote(record)});`,
370
+ ...properties,
371
+ "Append('}');",
372
+ ...(call.record.kind === "exception"
373
+ ? ["Append(',\"code\":');", "Append(UDINT_TO_STRING(code));", "ErrorName(code);"]
374
+ : []),
375
+ "Commit();",
376
+ ].join("\n") + "\n",
377
+ );
378
+ });
379
+
380
+ const failures = [...plan.failures.values()].map(({ id, record, sources }) =>
381
+ method(
382
+ `Failure${id}`,
383
+ "VAR_INPUT\n code : UDINT;\n step : UINT;\nEND_VAR\n",
384
+ [
385
+ "payload := '';",
386
+ `Append(${quote(`${record},"code":`)});`,
387
+ "Append(UDINT_TO_STRING(code));",
388
+ "ErrorName(code);",
389
+ `Append(',"source":"');`,
390
+ "CASE step OF",
391
+ ...sources.map(
392
+ ({ source, steps }) =>
393
+ `${steps.join(", ")}: Append(${quote(json(source).slice(1, -1))});`,
394
+ ),
395
+ "END_CASE;",
396
+ "Append('\"');",
397
+ "Commit();",
398
+ ].join("\n") + "\n",
399
+ ),
400
+ );
401
+
402
+ const operands = plan.traceOperands;
403
+ const trace =
404
+ operands === undefined
405
+ ? []
406
+ : [
407
+ method(
408
+ "Trace",
409
+ [
410
+ "VAR_INPUT",
411
+ " site : UINT;",
412
+ " value : DINT;",
413
+ " operands : USINT;",
414
+ ...Array.from({ length: operands }, (_, index) => ` operand${index} : DINT;`),
415
+ "END_VAR",
416
+ ].join("\n") + "\n",
417
+ [
418
+ "payload := '';",
419
+ `Append(${quote(traceRecord(operands).prefix)});`,
420
+ "Append(UINT_TO_STRING(site));",
421
+ `Append(',"value":');`,
422
+ "Append(DINT_TO_STRING(value));",
423
+ `Append(',"operands":[');`,
424
+ ...Array.from(
425
+ { length: operands },
426
+ (_, index) =>
427
+ `IF operands > ${index} THEN ${index ? "Append(','); " : ""}Append(DINT_TO_STRING(operand${index})); END_IF;`,
428
+ ),
429
+ "Append(']');",
430
+ "Commit();",
431
+ ].join("\n") + "\n",
432
+ ),
433
+ ];
434
+
435
+ const { start, rest } = header(build);
436
+ const helpers = httpMethods(writer).filter((item) =>
437
+ ["ByteLength", "Append", "WriteString"].includes(item.name),
438
+ );
439
+ const client = nativeHttp({
440
+ id: telemetryClient,
441
+ name: names.client,
442
+ ports:
443
+ "VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(2048);\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR",
444
+ port: (label) => label,
445
+ endpoint,
446
+ network,
447
+ method: "POST",
448
+ json: true,
449
+ body: "Append(body);",
450
+ decode: "",
451
+ });
452
+ return [
453
+ {
454
+ id: "tsplc:telemetryRecord",
455
+ kind: "dataType",
456
+ name: names.record,
457
+ declaration: `TYPE ${names.record} :\nSTRUCT\n sequence : ULINT;\n json : STRING(${recordBytes});\nEND_STRUCT\nEND_TYPE\n`,
458
+ },
459
+ {
460
+ id: writer,
461
+ kind: "functionBlock",
462
+ name: names.writer,
463
+ declaration: `FUNCTION_BLOCK ${names.writer}
464
+ VAR_INPUT
465
+ task : STRING(${taskBytes});
466
+ END_VAR
467
+ VAR_OUTPUT
468
+ scan : UDINT;
469
+ now : UDINT;
470
+ END_VAR
471
+ VAR
472
+ head : ULINT;
473
+ sent : ULINT;
474
+ dropped : ULINT;
475
+ records : ARRAY[0..${capacity - 1}] OF ${names.record};
476
+ payload : STRING(2048);
477
+ malformed : BOOL;
478
+ text : STRING(${recordBytes});
479
+ batch : STRING(2048);
480
+ batched : ULINT;
481
+ sending : BOOL;
482
+ lastSend : UDINT;
483
+ client : ${names.client};
484
+ END_VAR
485
+ `,
486
+ // Idle, a scan costs the clock and two comparisons. A 400 means the server can't take
487
+ // these records, so they are dropped rather than sent forever.
488
+ implementation: `scan := scan + 1;
489
+ now := TIME_TO_UDINT(TIME());
490
+ IF sending THEN
491
+ client(start := TRUE, cancel := FALSE, body := batch);
492
+ IF client.done THEN
493
+ IF client.error = ${httpErrors.base + 400} THEN
494
+ dropped := dropped + (batched - sent);
495
+ END_IF;
496
+ IF client.error = 0 OR client.error = ${httpErrors.base + 400} THEN
497
+ sent := batched;
498
+ END_IF;
499
+ sending := FALSE;
500
+ lastSend := now;
501
+ client(start := FALSE, cancel := FALSE, body := batch);
502
+ END_IF;
503
+ ELSIF head <> sent AND_THEN (head - sent >= ${batchRecords(recordBytes)} OR now - lastSend >= ${sendIntervalMs}) THEN
504
+ Send();
505
+ END_IF;
506
+ `,
507
+ },
508
+ method(
509
+ "Send",
510
+ "VAR\n slot : UDINT;\nEND_VAR\n",
511
+ `IF head - sent > ${capacity} THEN
512
+ dropped := dropped + (head - sent - ${capacity});
513
+ sent := head - ${capacity};
514
+ END_IF;
515
+ payload := '';
516
+ Append(${quote(start)});
517
+ Append(task);
518
+ Append(${quote(rest[0]!)});
519
+ Append(UDINT_TO_STRING(now));
520
+ Append(${quote(rest[1]!)});
521
+ Append(UDINT_TO_STRING(scan));
522
+ Append(${quote(rest[2]!)});
523
+ Append(ULINT_TO_STRING(sent + 1));
524
+ Append(${quote(rest[3]!)});
525
+ Append(ULINT_TO_STRING(dropped));
526
+ Append(${quote(rest[4]!)});
527
+ batched := sent;
528
+ WHILE batched <> head DO
529
+ slot := ULINT_TO_UDINT((batched + 1) MOD ${capacity});
530
+ IF ByteLength(payload) + ByteLength(records[slot].json) + 3 > ${batchBytes} THEN
531
+ EXIT;
532
+ END_IF;
533
+ IF batched <> sent THEN
534
+ Append(',');
535
+ END_IF;
536
+ Append(records[slot].json);
537
+ batched := batched + 1;
538
+ END_WHILE;
539
+ Append(']}');
540
+ batch := payload;
541
+ sending := TRUE;
542
+ client(start := TRUE, cancel := FALSE, body := batch);
543
+ `,
544
+ "PRIVATE ",
545
+ ),
546
+ // The whole record is written before \`head\` moves, so a reader of the ring can tell a torn one.
547
+ method(
548
+ "Commit",
549
+ "VAR\n slot : UDINT;\nEND_VAR\n",
550
+ `Append(',"scan":');
551
+ Append(UDINT_TO_STRING(scan));
552
+ Append(',"time":');
553
+ Append(UDINT_TO_STRING(now));
554
+ Append('}');
555
+ slot := ULINT_TO_UDINT((head + 1) MOD ${capacity});
556
+ records[slot].json := payload;
557
+ records[slot].sequence := head + 1;
558
+ head := head + 1;
559
+ `,
560
+ "PRIVATE ",
561
+ ),
562
+ method(
563
+ "ErrorName",
564
+ "VAR_INPUT\n code : UDINT;\nEND_VAR\n",
565
+ `CASE code OF
566
+ ${errorNames.map(([code]) => `${code}: Append(${quote(`,"name":${json(errorName(Number(code))!)}`)});`).join("\n")}
567
+ ${httpErrors.base + 1}..${httpErrors.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
568
+ END_CASE;
569
+ `,
570
+ "PRIVATE ",
571
+ ),
572
+ method(
573
+ "WriteText",
574
+ "VAR_INPUT\n data : POINTER TO BYTE;\n length : DINT;\nEND_VAR\nVAR\n index : DINT;\nEND_VAR\n",
575
+ `index := 0;
576
+ WHILE index < length AND_THEN data[index] <> 0 DO
577
+ text[index] := data[index];
578
+ index := index + 1;
579
+ END_WHILE;
580
+ text[index] := 0;
581
+ WriteString(text);
582
+ `,
583
+ "PRIVATE ",
584
+ ),
585
+ ...helpers,
586
+ ...calls,
587
+ ...failures,
588
+ ...trace,
589
+ client,
590
+ ...httpMethods(telemetryClient),
591
+ ...httpCertificateVerifier(telemetryClient, names.client, endpoint),
592
+ ];
593
+ }