@tsplc/compiler 0.2.17 → 0.2.19

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
@@ -0,0 +1,732 @@
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 {
14
+ type Environment,
15
+ telemetrySchema,
16
+ type ResolvedTelemetryConfig,
17
+ } from "@tsplc/config";
18
+ import { plcBufferBytes } from "@tsplc/server/wire";
19
+ import type { CodesysOptions } from "./config.ts";
20
+ import { blockInstances, type InstancePath } from "./debug.ts";
21
+ import {
22
+ httpCertificateVerifier,
23
+ httpMethods,
24
+ jsonScalar,
25
+ nativeHttp,
26
+ resolveHttpEndpoint,
27
+ type HttpEndpoint,
28
+ } from "./http.ts";
29
+ import { Sources } from "./sources.ts";
30
+ import { routineTasks } from "./task-access.ts";
31
+ import { type CodesysTypes, stStringLiteral } from "./types.ts";
32
+
33
+ /** The sender's key in `CodesysPlan.http`, and its HTTP block's id. */
34
+ export const telemetryClient = "tsplc:telemetry";
35
+ /** Where each task posts its records, below the server's base URL. */
36
+ export const telemetryPath = "/tsplc/telemetry";
37
+ /** A sender waits this long for a batch to fill. */
38
+ const sendIntervalMs = 200;
39
+ /** The longest task name a batch carries, as the wire allows. */
40
+ const taskBytes = 64;
41
+
42
+ type TelemetryStatement = Extract<CoreStatement, { kind: "telemetry" }>;
43
+
44
+ /** A telemetry call: `record` is the JSON its method writes before the properties' values. */
45
+ interface CallSite {
46
+ id: number;
47
+ task: string;
48
+ record: string;
49
+ call: TelemetryStatement;
50
+ }
51
+
52
+ /** A root job's unhandled failure; its source is that of the step it failed at. */
53
+ interface FailureSite {
54
+ id: number;
55
+ task: string;
56
+ record: string;
57
+ sources: readonly { source: string; steps: readonly number[] }[];
58
+ }
59
+
60
+ export interface TelemetryPlan extends ResolvedTelemetryConfig {
61
+ calls: ReadonlyMap<CoreStatement, CallSite>;
62
+ /** By job block id. */
63
+ failures: ReadonlyMap<string, FailureSite>;
64
+ /** `debug.trace`'s operand count, when the trace is on. */
65
+ traceOperands?: number;
66
+ }
67
+
68
+ /** A string as JSON text in ASCII, so it can sit in an ST literal. */
69
+ const asciiJson = (value: string) =>
70
+ JSON.stringify(value).replace(
71
+ /[^ -~]/g,
72
+ (character) =>
73
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`,
74
+ );
75
+
76
+ /** Compiler-made jobs, such as a service call's own, carry this prefix. */
77
+ export const generated = (name: string) => name.startsWith("tsplc");
78
+
79
+ const maximum = (values: readonly number[]) =>
80
+ values.reduce((a, b) => Math.max(a, b), 0);
81
+
82
+ /** `Commit` ends every record with the task's scan and clock. */
83
+ const commitSize = ',"scan":,"time":}'.length + 2 * 10;
84
+ /** `ErrorName` names a known error code. */
85
+ const errorNames = Object.keys(jobErrors).flatMap((code) => {
86
+ const name = errorName(Number(code));
87
+ return name === undefined ? [] : [[code, name] as const];
88
+ });
89
+ const codeSize =
90
+ ',"code":'.length +
91
+ 10 +
92
+ ',"name":'.length +
93
+ maximum([
94
+ ...errorNames.map(([, name]) => asciiJson(name).length),
95
+ asciiJson("HTTP 999").length,
96
+ ]);
97
+
98
+ /** The most bytes a property's value takes. */
99
+ function valueSize(type: PlcType, text: boolean): number {
100
+ if (text && type.kind === "array") {
101
+ return type.length * 6 + 2;
102
+ }
103
+ if (type.kind === "enum") {
104
+ return maximum([
105
+ 4,
106
+ ...type.members.map(
107
+ (member) => asciiJson(member.text ?? member.name).length,
108
+ ),
109
+ ]);
110
+ }
111
+ if (type.kind === "float") {
112
+ return type.bits === 32 ? 16 : 25;
113
+ }
114
+ const scalar = jsonScalar(type, "");
115
+ if (!scalar) {
116
+ throw new Error(`Unverified telemetry value type ${type.id}.`);
117
+ }
118
+ return scalar.size;
119
+ }
120
+
121
+ /** A call's record up to its source: its kind and what it names. */
122
+ const recordHead = (record: TelemetryStatement["record"]): string => {
123
+ switch (record.kind) {
124
+ case "event":
125
+ return `{"kind":"event","event":${asciiJson(record.event)}`;
126
+ case "log":
127
+ return `{"kind":"log","level":"${record.level}","message":${asciiJson(record.message)}`;
128
+ case "exception":
129
+ return '{"kind":"exception","handled":true';
130
+ }
131
+ };
132
+
133
+ const traceRecord = (operands: number) => ({
134
+ prefix: '{"kind":"trace","site":',
135
+ size:
136
+ '{"kind":"trace","site":,"value":,"operands":[]'.length +
137
+ 5 +
138
+ 11 +
139
+ operands * 12 +
140
+ commitSize,
141
+ });
142
+
143
+ export function telemetryCalls(core: VerifiedCoreModule) {
144
+ const routines = [
145
+ ...core.functions,
146
+ ...core.blocks.filter((block) => !block.standard),
147
+ ];
148
+ const statements: { routine: string; call: TelemetryStatement }[] = [];
149
+ const find = (routine: string, items: readonly CoreStatement[]): void => {
150
+ for (const item of items) {
151
+ if (item.kind === "telemetry") {
152
+ statements.push({ routine, call: item });
153
+ }
154
+ for (const body of nestedBodies(item)) {
155
+ find(routine, body);
156
+ }
157
+ }
158
+ };
159
+ for (const routine of routines) {
160
+ find(routine.id, routine.body);
161
+ }
162
+ return statements;
163
+ }
164
+
165
+ interface JobFailure {
166
+ task: string;
167
+ function: string;
168
+ instance?: string;
169
+ span: SourceSpan;
170
+ sources: { source: string; steps: readonly number[] }[];
171
+ fallback: string;
172
+ }
173
+
174
+ /** Root jobs own the unhandled record. Awaiting jobs own their children's errors. */
175
+ export function planJobFailures(
176
+ core: VerifiedCoreModule,
177
+ tasks: ReadonlyMap<string, string | undefined>,
178
+ location: (span: SourceSpan) => string,
179
+ ): ReadonlyMap<string, JobFailure> {
180
+ const types = new Map(core.types.map((type) => [type.id, type]));
181
+ const failures = new Map<string, JobFailure>();
182
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
183
+ const instances = blockInstances(core);
184
+ const awaited = (path: InstancePath) =>
185
+ path.slice(0, -1).some(({ variable }) => {
186
+ const type = types.get(variable.type);
187
+ const element = type?.kind === "array" ? types.get(type.element) : type;
188
+ return element?.kind === "block" && blocks.get(element.block)?.job;
189
+ });
190
+
191
+ for (const block of core.blocks) {
192
+ const { job } = block;
193
+ const task = tasks.get(block.id);
194
+ const paths = instances.get(block.id)!;
195
+ if (!job || !task || !paths.length || paths.some(awaited)) {
196
+ continue;
197
+ }
198
+
199
+ // A generated detached wrapper reports its one authored child by name.
200
+ const children = block.state.flatMap((child) => {
201
+ const type = types.get(child.type);
202
+ const called =
203
+ type?.kind === "block" ? blocks.get(type.block)?.job : undefined;
204
+ return called && !generated(called.name) ? [called] : [];
205
+ });
206
+ const [onlyChild] = children;
207
+ const named =
208
+ generated(job.name) && children.length === 1 && onlyChild
209
+ ? onlyChild
210
+ : job;
211
+ const fallback = location(job.span);
212
+ const steps = new Map<string, number[]>();
213
+ for (const step of job.steps) {
214
+ const source = location(step.span) || fallback;
215
+ steps.set(source, [...(steps.get(source) ?? []), step.step]);
216
+ }
217
+ failures.set(block.id, {
218
+ task,
219
+ function: named.name,
220
+ ...(named.instance && { instance: named.instance }),
221
+ span: job.span,
222
+ sources: [...steps].map(([source, numbers]) => ({
223
+ source,
224
+ steps: numbers,
225
+ })),
226
+ fallback,
227
+ });
228
+ }
229
+
230
+ return failures;
231
+ }
232
+
233
+ /**
234
+ * Whether a build has telemetry: the program calls `@tsplc/compiler/telemetry`, `telemetry` is
235
+ * configured, or `debug.trace` is on. Then every task with something to record gets a ring and
236
+ * a sender, root jobs' unhandled failures included; otherwise nothing is added.
237
+ */
238
+ export function planTelemetry(
239
+ core: VerifiedCoreModule,
240
+ deployment: Deployment,
241
+ options: CodesysOptions,
242
+ project: {
243
+ root: string;
244
+ telemetry?: ResolvedTelemetryConfig;
245
+ trace?: { capacity: number; operands: number } | false;
246
+ server?: { transport: "http" | "opcua"; baseUrlEnv?: string };
247
+ env: Environment;
248
+ },
249
+ report: (message: string, span?: SourceSpan) => void,
250
+ ): { telemetry?: TelemetryPlan; endpoint?: HttpEndpoint } {
251
+ const types = new Map(core.types.map((type) => [type.id, type]));
252
+ const statements = telemetryCalls(core);
253
+ if (!statements.length && !project.telemetry && !project.trace) {
254
+ return {};
255
+ }
256
+
257
+ const settings = project.telemetry ?? telemetrySchema.parse({});
258
+ const sources = new Sources(project.root);
259
+ const location = (span: SourceSpan) => {
260
+ const range = sources.range(span);
261
+ return range ? `${sources.files[range.file]}:${range.line}` : "";
262
+ };
263
+ const tasks = routineTasks(core, deployment);
264
+ const tooLarge = (size: number, what: string, span?: SourceSpan) => {
265
+ if (size > settings.recordBytes) {
266
+ report(
267
+ `${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.`,
268
+ span,
269
+ );
270
+ }
271
+ };
272
+
273
+ const calls = new Map<CoreStatement, CallSite>();
274
+ for (const { routine, call } of statements) {
275
+ const task = tasks.get(routine);
276
+ if (!task) {
277
+ report(
278
+ "Telemetry calls must be in code that one task runs: each task writes its own records.",
279
+ call.span,
280
+ );
281
+ continue;
282
+ }
283
+ const source = asciiJson(location(call.span));
284
+ const { record } = call;
285
+ const prefix = `${recordHead(record)},"source":${source},"properties":{`;
286
+ const size =
287
+ prefix.length +
288
+ call.properties.reduce(
289
+ (total, { name, value, length }, index) =>
290
+ total +
291
+ (index ? 1 : 0) +
292
+ asciiJson(name).length +
293
+ 1 +
294
+ valueSize(types.get(value.type)!, length !== undefined),
295
+ 0,
296
+ ) +
297
+ 1 +
298
+ (record.kind === "exception" ? codeSize : 0) +
299
+ commitSize;
300
+ tooLarge(size, "This telemetry record", call.span);
301
+ calls.set(call, { id: calls.size + 1, task, record: prefix, call });
302
+ }
303
+
304
+ const failures = new Map<string, FailureSite>();
305
+ for (const [block, job] of planJobFailures(core, tasks, location)) {
306
+ const record = `{"kind":"exception","handled":false,"function":${asciiJson(job.function)},${job.instance ? `"instance":${asciiJson(job.instance)},` : ""}"properties":{}`;
307
+ tooLarge(
308
+ record.length +
309
+ codeSize +
310
+ ',"source":""'.length +
311
+ maximum(
312
+ [...job.sources.map(({ source }) => source), job.fallback].map(
313
+ (source) => asciiJson(source).length - 2,
314
+ ),
315
+ ) +
316
+ commitSize,
317
+ `The failure record of ${job.function}`,
318
+ job.span,
319
+ );
320
+ failures.set(block, {
321
+ id: failures.size + 1,
322
+ task: job.task,
323
+ record,
324
+ sources: job.sources,
325
+ });
326
+ }
327
+
328
+ if (project.trace) {
329
+ tooLarge(
330
+ traceRecord(project.trace.operands).size,
331
+ "A debug.trace record with its operands",
332
+ );
333
+ }
334
+
335
+ const server = project.server;
336
+ const base = server?.baseUrlEnv && project.env[server.baseUrlEnv];
337
+ if (server?.transport === "opcua") {
338
+ report(
339
+ `Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`,
340
+ );
341
+ return {};
342
+ }
343
+ if (!base) {
344
+ report(
345
+ `Telemetry posts to the app server: set server.baseUrlEnv and that environment variable to its base URL.`,
346
+ );
347
+ return {};
348
+ }
349
+ try {
350
+ return {
351
+ telemetry: {
352
+ ...settings,
353
+ // One ring per task holds the trace too.
354
+ capacity: Math.max(
355
+ settings.capacity,
356
+ project.trace ? project.trace.capacity : 0,
357
+ ),
358
+ calls,
359
+ failures,
360
+ ...(project.trace && { traceOperands: project.trace.operands }),
361
+ },
362
+ endpoint: resolveHttpEndpoint(
363
+ `${base.replace(/\/+$/, "")}${telemetryPath}`,
364
+ options.http,
365
+ project.env,
366
+ ),
367
+ };
368
+ } catch (cause) {
369
+ report(cause instanceof Error ? cause.message : String(cause));
370
+ return {};
371
+ }
372
+ }
373
+
374
+ /** A call's method parameters, in declaration order: `p<n>` for each property, `code` for an exception. */
375
+ export const callParameters = ({ record, properties }: TelemetryStatement) => [
376
+ ...properties.flatMap(({ value, length }, index) => [
377
+ { name: `p${index}`, value, text: length !== undefined },
378
+ ...(length
379
+ ? [{ name: `p${index}Length`, value: length, text: false }]
380
+ : []),
381
+ ]),
382
+ ...(record.kind === "exception"
383
+ ? [{ name: "code", value: record.code, text: false }]
384
+ : []),
385
+ ];
386
+
387
+ /** The batch header's literal parts, before and after the task's name. */
388
+ const header = (build: string) => ({
389
+ start: `{"build":${asciiJson(build)},"task":"`,
390
+ rest: [
391
+ '","now":',
392
+ ',"scan":',
393
+ ',"first":',
394
+ ',"dropped":',
395
+ ',"records":[',
396
+ ] as const,
397
+ });
398
+
399
+ /** Records that always fit a batch beside its header: a sender with this many unsent sends at once. */
400
+ const batchRecords = (recordBytes: number) => {
401
+ const { start, rest } = header("0".repeat(16));
402
+ const fixed =
403
+ start.length +
404
+ taskBytes +
405
+ rest.join("").length +
406
+ 2 * 10 +
407
+ 2 * 20 +
408
+ "]}".length;
409
+ return Math.max(1, Math.floor((plcBufferBytes - fixed) / (recordBytes + 1)));
410
+ };
411
+
412
+ /**
413
+ * The ring and sender of a task, `FB_TsplcTelemetry`: one method per call site and root job, a
414
+ * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
415
+ * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
416
+ */
417
+ export function telemetryObjects({
418
+ plan,
419
+ names,
420
+ target,
421
+ endpoint,
422
+ network,
423
+ build,
424
+ types,
425
+ }: {
426
+ plan: TelemetryPlan;
427
+ names: { writer: string; record: string; client: string };
428
+ target: CodesysTypes;
429
+ endpoint: HttpEndpoint;
430
+ network: string;
431
+ build: string;
432
+ types: ReadonlyMap<string, PlcType>;
433
+ }): GeneratedObject[] {
434
+ const writer = "tsplc:telemetryWriter";
435
+ const { capacity, recordBytes } = plan;
436
+ const method = (
437
+ name: string,
438
+ declaration: string,
439
+ implementation: string,
440
+ access = "",
441
+ ): GeneratedObject => ({
442
+ id: `${writer}:${name}`,
443
+ parent: writer,
444
+ kind: "method",
445
+ name,
446
+ declaration: `METHOD ${access}${name}\n${declaration}`,
447
+ implementation,
448
+ });
449
+ const encode = (type: PlcType, parameter: string, text: boolean): string => {
450
+ if (text && type.kind === "array") {
451
+ return `WriteText(ADR(${parameter}), LINT_TO_DINT(LIMIT(0, TO_LINT(${parameter}Length), ${type.length})));`;
452
+ }
453
+ if (type.kind === "enum") {
454
+ return `CASE ${parameter} OF ${type.members.map((member) => `${target.name(type.id)}.${target.field(type.id, member.name)}: Append(${stStringLiteral(asciiJson(member.text ?? member.name))});`).join(" ")} ELSE Append('null'); END_CASE;`;
455
+ }
456
+ if (type.kind === "float") {
457
+ return `IF ${parameter} = ${parameter} AND ABS(${parameter}) < ${type.id}#${type.bits === 32 ? "3.4E38" : "1.7E308"} THEN Append(${type.id}_TO_STRING(${parameter})); ELSE Append('null'); END_IF;`;
458
+ }
459
+ return jsonScalar(type, parameter)!.code;
460
+ };
461
+
462
+ const calls = [...plan.calls.values()].map(({ id, record, call }) => {
463
+ const parameters = callParameters(call);
464
+ const inputs = parameters.filter((parameter) => !parameter.text);
465
+ const references = parameters.filter((parameter) => parameter.text);
466
+ const properties = call.properties.map(({ name, value, length }, index) => {
467
+ const code = encode(
468
+ types.get(value.type)!,
469
+ `p${index}`,
470
+ length !== undefined,
471
+ );
472
+ return `Append(${stStringLiteral(`${index ? "," : ""}${asciiJson(name)}:`)});\n${code}`;
473
+ });
474
+ return method(
475
+ `Record${id}`,
476
+ [
477
+ ...(inputs.length
478
+ ? [
479
+ "VAR_INPUT",
480
+ ...inputs.map(
481
+ (input) =>
482
+ ` ${input.name} : ${target.name(input.value.type)};`,
483
+ ),
484
+ "END_VAR",
485
+ ]
486
+ : []),
487
+ ...(references.length
488
+ ? [
489
+ "VAR_IN_OUT",
490
+ ...references.map(
491
+ (input) =>
492
+ ` ${input.name} : ${target.name(input.value.type)};`,
493
+ ),
494
+ "END_VAR",
495
+ ]
496
+ : []),
497
+ ]
498
+ .map((line) => `${line}\n`)
499
+ .join(""),
500
+ [
501
+ "payload := '';",
502
+ `Append(${stStringLiteral(record)});`,
503
+ ...properties,
504
+ "Append('}');",
505
+ ...(call.record.kind === "exception"
506
+ ? [
507
+ "Append(',\"code\":');",
508
+ "Append(UDINT_TO_STRING(code));",
509
+ "ErrorName(code);",
510
+ ]
511
+ : []),
512
+ "Commit();",
513
+ ].join("\n") + "\n",
514
+ );
515
+ });
516
+
517
+ const failures = [...plan.failures.values()].map(({ id, record, sources }) =>
518
+ method(
519
+ `Failure${id}`,
520
+ "VAR_INPUT\n code : UDINT;\n step : UINT;\nEND_VAR\n",
521
+ [
522
+ "payload := '';",
523
+ `Append(${stStringLiteral(`${record},"code":`)});`,
524
+ "Append(UDINT_TO_STRING(code));",
525
+ "ErrorName(code);",
526
+ `Append(',"source":"');`,
527
+ "CASE step OF",
528
+ ...sources.map(
529
+ ({ source, steps }) =>
530
+ `${steps.join(", ")}: Append(${stStringLiteral(asciiJson(source).slice(1, -1))});`,
531
+ ),
532
+ "END_CASE;",
533
+ "Append('\"');",
534
+ "Commit();",
535
+ ].join("\n") + "\n",
536
+ ),
537
+ );
538
+
539
+ const operands = plan.traceOperands;
540
+ const trace =
541
+ operands === undefined
542
+ ? []
543
+ : [
544
+ method(
545
+ "Trace",
546
+ [
547
+ "VAR_INPUT",
548
+ " site : UINT;",
549
+ " value : DINT;",
550
+ " operands : USINT;",
551
+ ...Array.from(
552
+ { length: operands },
553
+ (_, index) => ` operand${index} : DINT;`,
554
+ ),
555
+ "END_VAR",
556
+ ].join("\n") + "\n",
557
+ [
558
+ "payload := '';",
559
+ `Append(${stStringLiteral(traceRecord(operands).prefix)});`,
560
+ "Append(UINT_TO_STRING(site));",
561
+ `Append(',"value":');`,
562
+ "Append(DINT_TO_STRING(value));",
563
+ `Append(',"operands":[');`,
564
+ ...Array.from(
565
+ { length: operands },
566
+ (_, index) =>
567
+ `IF operands > ${index} THEN ${index ? "Append(','); " : ""}Append(DINT_TO_STRING(operand${index})); END_IF;`,
568
+ ),
569
+ "Append(']');",
570
+ "Commit();",
571
+ ].join("\n") + "\n",
572
+ ),
573
+ ];
574
+
575
+ const { start, rest } = header(build);
576
+ const helpers = httpMethods(writer).filter((item) =>
577
+ ["ByteLength", "Append", "WriteString"].includes(item.name),
578
+ );
579
+ const client = nativeHttp({
580
+ id: telemetryClient,
581
+ name: names.client,
582
+ ports: `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`,
583
+ port: (label) => label,
584
+ endpoint,
585
+ network,
586
+ method: "POST",
587
+ json: true,
588
+ body: "Append(body);",
589
+ decode: "",
590
+ });
591
+ return [
592
+ {
593
+ id: "tsplc:telemetryRecord",
594
+ kind: "dataType",
595
+ name: names.record,
596
+ declaration: `TYPE ${names.record} :\nSTRUCT\n sequence : ULINT;\n json : STRING(${recordBytes});\nEND_STRUCT\nEND_TYPE\n`,
597
+ },
598
+ {
599
+ id: writer,
600
+ kind: "functionBlock",
601
+ name: names.writer,
602
+ declaration: `FUNCTION_BLOCK ${names.writer}
603
+ VAR_INPUT
604
+ task : STRING(${taskBytes});
605
+ END_VAR
606
+ VAR_OUTPUT
607
+ scan : UDINT;
608
+ now : UDINT;
609
+ END_VAR
610
+ VAR
611
+ head : ULINT;
612
+ sent : ULINT;
613
+ dropped : ULINT;
614
+ records : ARRAY[0..${capacity - 1}] OF ${names.record};
615
+ payload : STRING(${plcBufferBytes});
616
+ malformed : BOOL;
617
+ text : STRING(${recordBytes});
618
+ batch : STRING(${plcBufferBytes});
619
+ batched : ULINT;
620
+ sending : BOOL;
621
+ lastSend : UDINT;
622
+ client : ${names.client};
623
+ END_VAR
624
+ `,
625
+ // Idle, a scan costs the clock and two comparisons. A 400 means the server can't take
626
+ // these records, so they are dropped rather than sent forever.
627
+ implementation: `scan := scan + 1;
628
+ now := TIME_TO_UDINT(TIME());
629
+ IF sending THEN
630
+ client(start := TRUE, cancel := FALSE, body := batch);
631
+ IF client.done THEN
632
+ IF client.error = ${httpErrors.base + 400} THEN
633
+ dropped := dropped + (batched - sent);
634
+ END_IF;
635
+ IF client.error = 0 OR client.error = ${httpErrors.base + 400} THEN
636
+ sent := batched;
637
+ END_IF;
638
+ sending := FALSE;
639
+ lastSend := now;
640
+ client(start := FALSE, cancel := FALSE, body := batch);
641
+ END_IF;
642
+ ELSIF head <> sent AND_THEN (head - sent >= ${batchRecords(recordBytes)} OR now - lastSend >= ${sendIntervalMs}) THEN
643
+ Send();
644
+ END_IF;
645
+ `,
646
+ },
647
+ method(
648
+ "Send",
649
+ "VAR\n slot : UDINT;\nEND_VAR\n",
650
+ `IF head - sent > ${capacity} THEN
651
+ dropped := dropped + (head - sent - ${capacity});
652
+ sent := head - ${capacity};
653
+ END_IF;
654
+ payload := '';
655
+ Append(${stStringLiteral(start)});
656
+ Append(task);
657
+ Append(${stStringLiteral(rest[0])});
658
+ Append(UDINT_TO_STRING(now));
659
+ Append(${stStringLiteral(rest[1])});
660
+ Append(UDINT_TO_STRING(scan));
661
+ Append(${stStringLiteral(rest[2])});
662
+ Append(ULINT_TO_STRING(sent + 1));
663
+ Append(${stStringLiteral(rest[3])});
664
+ Append(ULINT_TO_STRING(dropped));
665
+ Append(${stStringLiteral(rest[4])});
666
+ batched := sent;
667
+ WHILE batched <> head DO
668
+ slot := ULINT_TO_UDINT((batched + 1) MOD ${capacity});
669
+ IF ByteLength(payload) + ByteLength(records[slot].json) + 3 > ${plcBufferBytes} THEN
670
+ EXIT;
671
+ END_IF;
672
+ IF batched <> sent THEN
673
+ Append(',');
674
+ END_IF;
675
+ Append(records[slot].json);
676
+ batched := batched + 1;
677
+ END_WHILE;
678
+ Append(']}');
679
+ batch := payload;
680
+ sending := TRUE;
681
+ client(start := TRUE, cancel := FALSE, body := batch);
682
+ `,
683
+ "PRIVATE ",
684
+ ),
685
+ // The whole record is written before \`head\` moves, so a reader of the ring can tell a torn one.
686
+ method(
687
+ "Commit",
688
+ "VAR\n slot : UDINT;\nEND_VAR\n",
689
+ `Append(',"scan":');
690
+ Append(UDINT_TO_STRING(scan));
691
+ Append(',"time":');
692
+ Append(UDINT_TO_STRING(now));
693
+ Append('}');
694
+ slot := ULINT_TO_UDINT((head + 1) MOD ${capacity});
695
+ records[slot].json := payload;
696
+ records[slot].sequence := head + 1;
697
+ head := head + 1;
698
+ `,
699
+ "PRIVATE ",
700
+ ),
701
+ method(
702
+ "ErrorName",
703
+ "VAR_INPUT\n code : UDINT;\nEND_VAR\n",
704
+ `CASE code OF
705
+ ${errorNames.map(([code, name]) => `${code}: Append(${stStringLiteral(`,"name":${asciiJson(name)}`)});`).join("\n")}
706
+ ${httpErrors.base + 1}..${httpErrors.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
707
+ END_CASE;
708
+ `,
709
+ "PRIVATE ",
710
+ ),
711
+ method(
712
+ "WriteText",
713
+ "VAR_INPUT\n data : POINTER TO BYTE;\n length : DINT;\nEND_VAR\nVAR\n index : DINT;\nEND_VAR\n",
714
+ `index := 0;
715
+ WHILE index < length AND_THEN data[index] <> 0 DO
716
+ text[index] := data[index];
717
+ index := index + 1;
718
+ END_WHILE;
719
+ text[index] := 0;
720
+ WriteString(text);
721
+ `,
722
+ "PRIVATE ",
723
+ ),
724
+ ...helpers,
725
+ ...calls,
726
+ ...failures,
727
+ ...trace,
728
+ client,
729
+ ...httpMethods(telemetryClient),
730
+ ...httpCertificateVerifier(telemetryClient, names.client, endpoint),
731
+ ];
732
+ }