@tsplc/compiler 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,593 +0,0 @@
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
- }