@tsplc/tmp-debug 0.0.0-stage → 0.6.3

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 (78) hide show
  1. package/README.md +38 -2
  2. package/dist/api.js +744 -0
  3. package/dist/api.js.map +12 -0
  4. package/dist/constant.js +33 -0
  5. package/dist/constant.js.map +10 -0
  6. package/dist/explain-file.js +468 -0
  7. package/dist/explain-file.js.map +11 -0
  8. package/dist/explain.js +1310 -0
  9. package/dist/explain.js.map +19 -0
  10. package/dist/format.js +214 -0
  11. package/dist/format.js.map +12 -0
  12. package/dist/index.js +4066 -0
  13. package/dist/index.js.map +44 -0
  14. package/dist/manifest.js +240 -0
  15. package/dist/manifest.js.map +10 -0
  16. package/dist/paths.js +242 -0
  17. package/dist/paths.js.map +10 -0
  18. package/package.json +72 -4
  19. package/src/adapter.ts +77 -0
  20. package/src/api.ts +446 -0
  21. package/src/app-server.ts +151 -0
  22. package/src/build-files.ts +46 -0
  23. package/src/constant.ts +41 -0
  24. package/src/debugger.ts +237 -0
  25. package/src/errors.ts +13 -0
  26. package/src/explain-expressions.ts +484 -0
  27. package/src/explain-file.ts +325 -0
  28. package/src/explain-frames.ts +155 -0
  29. package/src/explain-loops.ts +151 -0
  30. package/src/explain-operations.ts +232 -0
  31. package/src/explain-tables.ts +345 -0
  32. package/src/explain-value.ts +203 -0
  33. package/src/explain-verdicts.ts +548 -0
  34. package/src/explain.ts +82 -0
  35. package/src/hardware.ts +159 -0
  36. package/src/http.ts +218 -0
  37. package/src/index.ts +44 -0
  38. package/src/jobs.ts +139 -0
  39. package/src/login-value.ts +165 -0
  40. package/src/login.ts +315 -0
  41. package/src/manifest.ts +328 -0
  42. package/src/opcua.ts +80 -0
  43. package/src/paths.ts +363 -0
  44. package/src/requests.ts +99 -0
  45. package/src/server-cursor.ts +22 -0
  46. package/src/shown.ts +229 -0
  47. package/src/telemetry.ts +125 -0
  48. package/src/timeline.ts +148 -0
  49. package/src/trace.ts +62 -0
  50. package/src/ui/bits.ts +48 -0
  51. package/src/ui/client.ts +87 -0
  52. package/src/ui/dom.ts +61 -0
  53. package/src/ui/explain-read.ts +105 -0
  54. package/src/ui/format.ts +261 -0
  55. package/src/ui/hardware.ts +425 -0
  56. package/src/ui/header.ts +207 -0
  57. package/src/ui/health.ts +64 -0
  58. package/src/ui/index.ts +27 -0
  59. package/src/ui/jobs.ts +263 -0
  60. package/src/ui/links.ts +59 -0
  61. package/src/ui/live-value.ts +85 -0
  62. package/src/ui/main.ts +76 -0
  63. package/src/ui/overview.ts +178 -0
  64. package/src/ui/page.ts +286 -0
  65. package/src/ui/pages.ts +64 -0
  66. package/src/ui/recent-window.ts +49 -0
  67. package/src/ui/recent.ts +355 -0
  68. package/src/ui/request-trace.ts +38 -0
  69. package/src/ui/requests.ts +80 -0
  70. package/src/ui/routes.ts +98 -0
  71. package/src/ui/store.ts +295 -0
  72. package/src/ui/success-cache.ts +11 -0
  73. package/src/ui/tree.ts +162 -0
  74. package/src/ui/variables.ts +597 -0
  75. package/src/ui/why-watch.ts +11 -0
  76. package/src/ui/why.ts +694 -0
  77. package/src/values.ts +170 -0
  78. package/src/watch.ts +32 -0
package/src/adapter.ts ADDED
@@ -0,0 +1,77 @@
1
+ import type { Quality } from "@tsplc/opcua/contract";
2
+ import type { ConnectionState } from "./api";
3
+ import type { DebugType } from "./manifest";
4
+
5
+ /** One target's value, before the debugger names it by TypeScript path and decodes it. */
6
+ export interface TargetSample {
7
+ value: unknown;
8
+ quality: Quality;
9
+ status: string;
10
+ receivedAt: string;
11
+ /**
12
+ * The controller read that returned it: samples with the same `read` were copied in one call.
13
+ * Absent from an adapter that doesn't read in batches.
14
+ */
15
+ read?: number;
16
+ }
17
+
18
+ /** A target to read, with its type in the manifest, which an adapter may need to parse it. */
19
+ export interface TargetRead {
20
+ target: string;
21
+ type: DebugType;
22
+ }
23
+
24
+ export const scalarRead = (target: string, iec: string): TargetRead => ({
25
+ target,
26
+ type: { kind: "scalar", iec },
27
+ });
28
+
29
+ const qualityRank: Record<Quality, number> = {
30
+ good: 0,
31
+ uncertain: 1,
32
+ bad: 2,
33
+ unavailable: 3,
34
+ };
35
+
36
+ /** The worst of these qualities; nothing read is unavailable. */
37
+ export const worstQuality = (
38
+ samples: readonly (TargetSample | undefined)[],
39
+ ): Quality =>
40
+ samples.reduce<Quality>((worst, sample) => {
41
+ const quality = sample?.quality ?? "unavailable";
42
+ return qualityRank[quality] > qualityRank[worst] ? quality : worst;
43
+ }, "good");
44
+
45
+ export interface Connection {
46
+ state: ConnectionState;
47
+ since: string;
48
+ error?: string;
49
+ }
50
+
51
+ /**
52
+ * Reads one vendor's controller. Only the adapter interprets `target` strings, which come from
53
+ * the manifest (for CODESYS, IEC symbol paths). It never writes.
54
+ */
55
+ export interface TargetAdapter {
56
+ /** How it reads, for display, such as "engineering login". */
57
+ readonly method: string;
58
+ /** Where it reads, for display. */
59
+ readonly endpoint: string;
60
+ /** How often subscribed targets are read; a value is at most about this old while connected. */
61
+ readonly samplingMs: number;
62
+ connection(): Connection;
63
+ onConnection(listener: (connection: Connection) => void): () => void;
64
+ /** Reads targets now; fails while disconnected. Targets that can't be read come back bad or unavailable. */
65
+ read(targets: readonly TargetRead[]): Promise<Map<string, TargetSample>>;
66
+ /**
67
+ * Calls `listener` with each target's value, about every `intervalMs` (`samplingMs` by
68
+ * default) or on every change, across reconnects, until the returned function is called. While
69
+ * disconnected each target is reported unavailable or bad.
70
+ */
71
+ subscribe(
72
+ targets: readonly TargetRead[],
73
+ listener: (target: string, sample: TargetSample) => void,
74
+ intervalMs?: number,
75
+ ): () => void;
76
+ close(): Promise<void>;
77
+ }
package/src/api.ts ADDED
@@ -0,0 +1,446 @@
1
+ import { qualitySchema } from "@tsplc/opcua/contract";
2
+ import { serviceCall } from "@tsplc/server/requests";
3
+ import { type AppRecord, appRecord } from "@tsplc/server/telemetry";
4
+ import { z } from "zod";
5
+ import { explainFile, explainFlags } from "./explain-file";
6
+ import { debugIo, debugManifest, sourceRange } from "./manifest";
7
+
8
+ /**
9
+ * The debugger API's response shapes, shared by the host, the browser UI and the VS Code extension,
10
+ * which validate what they receive against them. Routes are listed in `createDebugHandler` (http.ts);
11
+ * streams are Server-Sent Events whose event names are the keys of `streamEventSchemas`.
12
+ */
13
+
14
+ /**
15
+ * The header the debugger's and the agent dashboard's pages send on anything but `GET`. Another site
16
+ * can make a browser send a cookie, but not a custom header, so the agent refuses a change signed in
17
+ * by cookie, Tailscale or from its own PC without it.
18
+ */
19
+ export const dashboardHeader = "x-tsplc-dashboard";
20
+
21
+ /** The query parameter that carries a page's token to the API, since EventSource cannot send headers. */
22
+ export const tokenQueryParameter = "token";
23
+
24
+ /** The body of every 4xx and 5xx reply. */
25
+ export const errorBodySchema = z.object({ error: z.string() });
26
+ export type ErrorBody = z.infer<typeof errorBodySchema>;
27
+
28
+ export { type Quality, qualitySchema } from "@tsplc/opcua/contract";
29
+
30
+ /** One value as read. Values of different paths may come from different scans. */
31
+ export const sampleSchema = z.object({
32
+ path: z.string(),
33
+ value: z.unknown(),
34
+ quality: qualitySchema,
35
+ status: z.string(),
36
+ /** When the debugger host received it; the controller reports no time of its own. */
37
+ receivedAt: z.string(),
38
+ /** The controller read that returned it; samples with the same `read` were read together. */
39
+ read: z.number().int().optional(),
40
+ });
41
+ export type Sample = z.infer<typeof sampleSchema>;
42
+
43
+ /** `unavailable`: nothing to read through, such as no engineering login open. */
44
+ export const connectionStateSchema = z.enum([
45
+ "connecting",
46
+ "connected",
47
+ "lost",
48
+ "failed",
49
+ "unavailable",
50
+ ]);
51
+ export type ConnectionState = z.infer<typeof connectionStateSchema>;
52
+
53
+ export const sessionSchema = z.object({
54
+ build: z.object({
55
+ manifest: z.string().nullable(),
56
+ controller: z.string().nullable(),
57
+ matches: z.boolean(),
58
+ }),
59
+ connection: z.object({
60
+ state: connectionStateSchema,
61
+ since: z.string(),
62
+ endpoint: z.string(),
63
+ error: z.string().optional(),
64
+ }),
65
+ /** How live values are read, such as "engineering login", and how often. */
66
+ reading: z.object({ method: z.string(), intervalMs: z.number() }),
67
+ /** From the tasks' telemetry batches; `dropped` counts records overwritten before they were sent. */
68
+ tasks: z.array(
69
+ z.object({
70
+ name: z.string(),
71
+ scan: z.number().nullable(),
72
+ scansPerSecond: z.number().nullable(),
73
+ dropped: z.number(),
74
+ }),
75
+ ),
76
+ /** PLC clock minus the app server's clock, estimated from telemetry batches. */
77
+ clock: z
78
+ .object({ offsetMs: z.number(), uncertaintyMs: z.number() })
79
+ .nullable(),
80
+ release: z
81
+ .object({ id: z.string(), deployedAt: z.string(), operation: z.string() })
82
+ .optional(),
83
+ /** The project directory on the host, when served by `tsplc debug`. */
84
+ projectRoot: z.string().optional(),
85
+ });
86
+ export type Session = z.infer<typeof sessionSchema>;
87
+
88
+ /** A trace record, decoded through the manifest's event sites. */
89
+ export const traceEventSchema = z.object({
90
+ sequence: z.number(),
91
+ task: z.string(),
92
+ scan: z.number(),
93
+ plcTime: z.number(),
94
+ site: z.number(),
95
+ value: z.unknown(),
96
+ /** The site's guard operands, in the site's order. */
97
+ operands: z.array(
98
+ z.object({
99
+ text: z.string(),
100
+ path: z.string().optional(),
101
+ stable: z.boolean(),
102
+ value: z.unknown(),
103
+ }),
104
+ ),
105
+ });
106
+ export type TraceEvent = z.infer<typeof traceEventSchema>;
107
+
108
+ export type { AppRecord };
109
+
110
+ /** One PLC service call, as the app server traced it. */
111
+ export const requestTraceSchema = serviceCall;
112
+ export type RequestTrace = z.infer<typeof requestTraceSchema>;
113
+
114
+ /**
115
+ * A job as last seen. `busy` is null until it is known: from the trace's start and finish
116
+ * records, or read through the login while a page shows the job. The rest is read only while it
117
+ * is busy and shown.
118
+ */
119
+ export const jobStateSchema = z.object({
120
+ id: z.number(),
121
+ /** Of the `busy` reading; a traced job's is good. */
122
+ quality: qualitySchema,
123
+ busy: z.boolean().nullable(),
124
+ cancelling: z.boolean().optional(),
125
+ step: z.number().optional(),
126
+ current: z
127
+ .object({ kind: z.string(), range: sourceRange, text: z.string() })
128
+ .optional(),
129
+ startedAt: z.string().optional(),
130
+ elapsedMs: z.number().optional(),
131
+ request: z
132
+ .object({
133
+ service: z.string(),
134
+ sequence: z.number(),
135
+ trace: requestTraceSchema.optional(),
136
+ })
137
+ .optional(),
138
+ /** Busy, but over the number of jobs whose details are read on each poll. */
139
+ unread: z.literal(true).optional(),
140
+ /** The last failure nothing caught, from the program's `exception` records. */
141
+ failure: z
142
+ .object({
143
+ at: z.string(),
144
+ code: z.number(),
145
+ name: z.string().optional(),
146
+ source: z.string(),
147
+ })
148
+ .optional(),
149
+ });
150
+ export type JobState = z.infer<typeof jobStateSchema>;
151
+
152
+ /** "unknown" unless the driver's own state was read. */
153
+ export const healthStateSchema = z.enum(["unknown", "ok", "fault", "stale"]);
154
+ export type HealthState = z.infer<typeof healthStateSchema>;
155
+
156
+ export const deviceStateSchema = z.object({
157
+ id: z.string(),
158
+ health: z.object({
159
+ state: healthStateSchema,
160
+ value: z.number().optional(),
161
+ name: z.string().optional(),
162
+ diagnostic: z.boolean().optional(),
163
+ message: z.string().optional(),
164
+ quality: qualitySchema,
165
+ }),
166
+ assemblies: z.array(
167
+ z.object({
168
+ direction: z.enum(["input", "output"]),
169
+ address: z.string().optional(),
170
+ bytes: z.array(z.number()).nullable(),
171
+ quality: qualitySchema,
172
+ }),
173
+ ),
174
+ /** Channels bound to TypeScript I/O paths, by channel id. */
175
+ channels: z.array(
176
+ z.object({
177
+ id: z.string(),
178
+ path: z.string(),
179
+ value: z.unknown(),
180
+ quality: qualitySchema,
181
+ }),
182
+ ),
183
+ /** The device's hand-configured status symbols, by label. */
184
+ status: z.record(
185
+ z.string(),
186
+ z.object({ value: z.unknown(), quality: qualitySchema }),
187
+ ),
188
+ });
189
+ export type DeviceState = z.infer<typeof deviceStateSchema>;
190
+
191
+ export const timelineSourceSchema = z.enum([
192
+ "plc",
193
+ "server",
194
+ "agent",
195
+ "debugger",
196
+ ]);
197
+ export type TimelineSource = z.infer<typeof timelineSourceSchema>;
198
+
199
+ const timelinePlacement = {
200
+ at: z.string(),
201
+ /** Placed through another clock (the PLC's, or the app server's), so its order is approximate. */
202
+ approximate: z.boolean(),
203
+ source: timelineSourceSchema,
204
+ /**
205
+ * Where a client resumes, with `GET /api/timeline?after=<cursor>` rather than `since`: entries
206
+ * arrive late and are placed by `at`, so the timeline is in time order, not cursor order. A
207
+ * client resumes from the cursor on the entry it received last. An entry that changes, such as
208
+ * a call that ends, takes a new cursor and is served again. A host started since the cursor was
209
+ * issued, such as by a deploy, answers it with its whole timeline.
210
+ */
211
+ cursor: z.string().optional(),
212
+ };
213
+
214
+ /** An entry of the "Recent" view: the server's recent window, merged with the agent's logs. */
215
+ export const timelineEntrySchema = z.discriminatedUnion("kind", [
216
+ z.object({
217
+ ...timelinePlacement,
218
+ kind: z.literal("app"),
219
+ task: z.string(),
220
+ sequence: z.number(),
221
+ record: appRecord,
222
+ }),
223
+ z.object({
224
+ ...timelinePlacement,
225
+ kind: z.literal("trace"),
226
+ trace: traceEventSchema,
227
+ }),
228
+ z.object({
229
+ ...timelinePlacement,
230
+ kind: z.literal("request"),
231
+ request: requestTraceSchema,
232
+ }),
233
+ z.object({
234
+ ...timelinePlacement,
235
+ kind: z.literal("deploy"),
236
+ release: z.string(),
237
+ operation: z.string(),
238
+ build: z.string().optional(),
239
+ user: z.string().optional(),
240
+ host: z.string().optional(),
241
+ }),
242
+ z.object({
243
+ ...timelinePlacement,
244
+ kind: z.literal("audit"),
245
+ /** As typed after `tsplc`, such as `force` or `reset cold`. */
246
+ command: z.string(),
247
+ /** Expressions written or forced, with their values; unforced expressions map to "". */
248
+ values: z.record(z.string(), z.string()),
249
+ /** The values read just before a write or force. */
250
+ previous: z.record(z.string(), z.string()).optional(),
251
+ user: z.string().optional(),
252
+ host: z.string().optional(),
253
+ release: z.string().optional(),
254
+ error: z.string().optional(),
255
+ }),
256
+ z.object({
257
+ ...timelinePlacement,
258
+ kind: z.literal("connection"),
259
+ state: connectionStateSchema,
260
+ error: z.string().optional(),
261
+ }),
262
+ ]);
263
+ export type TimelineEntry = z.infer<typeof timelineEntrySchema>;
264
+
265
+ export const watchGroupsSchema = z.strictObject({
266
+ groups: z.record(z.string().nonempty(), z.array(z.string().nonempty())),
267
+ });
268
+ export type WatchGroups = z.infer<typeof watchGroupsSchema>;
269
+
270
+ /**
271
+ * What a page shows, so the host reads only that: `watch` paths, `jobs` by id, the health of
272
+ * `health` devices, and everything of `devices`. Stream query parameters, comma-separated.
273
+ */
274
+ export interface Interest {
275
+ watch: string[];
276
+ jobs: number[];
277
+ health: string[];
278
+ devices: string[];
279
+ /** Tasks whose PLC clock to read with the watched values, as `clockSample(task)` samples. */
280
+ clocks: string[];
281
+ /** `writers` entries whose last-writer slot to read with the watched values, as `slotSample(index)` samples. */
282
+ slots: number[];
283
+ }
284
+
285
+ /**
286
+ * The sample path of a task's PLC clock and of a last-writer slot. TypeScript paths never contain
287
+ * a colon, so these can't name a variable.
288
+ */
289
+ export const clockSample = (task: string) => `tsplc:clock/${task}`;
290
+ export const slotSample = (writer: number) => `tsplc:writer/${writer}`;
291
+
292
+ /** A stream's query for `interest`: each non-empty list, deduplicated, sorted and comma-separated. */
293
+ export const interestQuery = (
294
+ interest: Partial<Interest>,
295
+ ): Record<string, string> =>
296
+ Object.fromEntries(
297
+ Object.entries(interest).flatMap(([name, values]) => {
298
+ const list = [...new Set(values.map(String))].sort().join(",");
299
+ return list ? [[name, list]] : [];
300
+ }),
301
+ );
302
+
303
+ /** Each stream event's data, by event name. Clients ignore names not listed here. */
304
+ export const streamEventSchemas = {
305
+ session: sessionSchema,
306
+ sample: sampleSchema,
307
+ job: jobStateSchema,
308
+ request: requestTraceSchema,
309
+ device: deviceStateSchema,
310
+ timeline: timelineEntrySchema,
311
+ };
312
+ export type StreamEvents = {
313
+ [Name in keyof typeof streamEventSchemas]: z.infer<
314
+ (typeof streamEventSchemas)[Name]
315
+ >;
316
+ };
317
+
318
+ type NamedStreamEvent<Name extends keyof StreamEvents> = {
319
+ [Event in Name]: { name: Event; data: StreamEvents[Event] };
320
+ }[Name];
321
+ export type StreamEvent = NamedStreamEvent<keyof StreamEvents>;
322
+
323
+ const isStreamEventName = (name: string): name is keyof StreamEvents =>
324
+ Object.hasOwn(streamEventSchemas, name);
325
+
326
+ const decodeNamed = <Name extends keyof StreamEvents>(
327
+ name: Name,
328
+ data: string,
329
+ ): NamedStreamEvent<Name> => {
330
+ // Typed per event, so `schemas[name]` stays paired with `Name` rather than widening to every schema.
331
+ const schemas: {
332
+ [Event in keyof StreamEvents]: z.ZodType<StreamEvents[Event]>;
333
+ } = streamEventSchemas;
334
+ const parsed = schemas[name].safeParse(JSON.parse(data));
335
+ if (!parsed.success) {
336
+ throw new Error(
337
+ `The debugger sent a malformed ${name} event: ${z.prettifyError(parsed.error)}`,
338
+ );
339
+ }
340
+ return { name, data: parsed.data };
341
+ };
342
+
343
+ /**
344
+ * Decodes one stream event's data, or returns undefined for an event this client doesn't know,
345
+ * so a newer host's events are ignored. Data that doesn't match a known event's shape throws.
346
+ */
347
+ export const decodeStreamEvent = (
348
+ name: string,
349
+ data: string,
350
+ ): StreamEvent | undefined =>
351
+ isStreamEventName(name) ? decodeNamed(name, data) : undefined;
352
+
353
+ /** The statements that can write a path, with the chains of calls each runs through. */
354
+ export const explanationSchema = z.object({
355
+ path: z.string(),
356
+ type: z.string(),
357
+ writers: z.array(
358
+ z.object({
359
+ assignment: z.number().int(),
360
+ /** The path's index for each `[*]` of the writer's pattern. */
361
+ indexes: z.array(z.number().int()),
362
+ chains: z.array(
363
+ z.object({
364
+ task: z.string(),
365
+ entry: z.number().int(),
366
+ calls: z.array(z.number().int()),
367
+ }),
368
+ ),
369
+ }),
370
+ ),
371
+ flags: explainFlags.omit({ path: true }),
372
+ io: debugIo.nullable(),
373
+ });
374
+ export type ExplanationResponse = z.infer<typeof explanationSchema>;
375
+
376
+ /** The paths the controller forces, or null when the forced state isn't known, as of `at`. */
377
+ export const forcedSchema = z.object({
378
+ forced: z.array(z.string()).nullable(),
379
+ at: z.string(),
380
+ });
381
+ export type Forced = z.infer<typeof forcedSchema>;
382
+
383
+ /** Response bodies by route; errors are `errorBodySchema`. */
384
+ export const apiResponseSchemas = {
385
+ "GET /api/session": sessionSchema,
386
+ "GET /api/manifest": debugManifest,
387
+ "GET /api/values": z.array(sampleSchema),
388
+ "GET /api/jobs": z.array(jobStateSchema),
389
+ "GET /api/hardware": z.array(deviceStateSchema),
390
+ "GET /api/timeline": z.array(timelineEntrySchema),
391
+ "GET /api/watch": watchGroupsSchema,
392
+ "PUT /api/watch": watchGroupsSchema,
393
+ "GET /api/explain": explanationSchema,
394
+ "GET /api/explain-file": explainFile,
395
+ "GET /api/forced": forcedSchema,
396
+ };
397
+ export type ApiResponses = {
398
+ [Route in keyof typeof apiResponseSchemas]: z.infer<
399
+ (typeof apiResponseSchemas)[Route]
400
+ >;
401
+ };
402
+
403
+ export interface ServerSentEvent {
404
+ event: string;
405
+ data: string;
406
+ }
407
+
408
+ /**
409
+ * Parses a `text/event-stream` body by the HTML field rules, with lines ended by CR, LF or CRLF.
410
+ * Comments, `id` and `retry` are skipped.
411
+ */
412
+ export async function* parseEventStream(
413
+ chunks: AsyncIterable<string>,
414
+ ): AsyncGenerator<ServerSentEvent> {
415
+ let buffer = "";
416
+ let event = "";
417
+ let data: string[] = [];
418
+ for await (const chunk of chunks) {
419
+ buffer += chunk;
420
+ // A trailing CR may be the first half of a CRLF split across chunks.
421
+ const end = buffer.endsWith("\r") ? buffer.length - 1 : buffer.length;
422
+ const lines = buffer.slice(0, end).split(/\r\n|\r|\n/);
423
+ buffer = lines.splice(-1).join("") + buffer.slice(end);
424
+ for (const line of lines) {
425
+ if (!line) {
426
+ if (data.length) {
427
+ yield { event: event || "message", data: data.join("\n") };
428
+ }
429
+ event = "";
430
+ data = [];
431
+ continue;
432
+ }
433
+ if (line.startsWith(":")) {
434
+ continue;
435
+ }
436
+ const colon = line.indexOf(":");
437
+ const field = colon < 0 ? line : line.slice(0, colon);
438
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
439
+ if (field === "event") {
440
+ event = value;
441
+ } else if (field === "data") {
442
+ data.push(value);
443
+ }
444
+ }
445
+ }
446
+ }
@@ -0,0 +1,151 @@
1
+ import { sleep } from "@tsplc/opcua";
2
+ import { requestsPath, requestsReply } from "@tsplc/server/requests";
3
+ import { telemetryPath, telemetryReply } from "@tsplc/server/telemetry";
4
+ import type { StreamEvent, TimelineEntry } from "./api";
5
+ import { errorMessage } from "./errors";
6
+ import type { DebugManifest } from "./manifest";
7
+ import { type createRequestFollower, taggedCall } from "./requests";
8
+ import type { createShownReads } from "./shown";
9
+ import type { createTelemetryFollower, ReceivedRecord } from "./telemetry";
10
+ import { timelineEntries } from "./timeline";
11
+ import type { createTraceDecoder } from "./trace";
12
+
13
+ const pullMs = 1000;
14
+
15
+ /**
16
+ * Pulls the app server's telemetry and request trace every second until `signal` aborts: records
17
+ * go to the timeline, and the jobs they name are updated. A failing pull is logged when its
18
+ * reason changes.
19
+ */
20
+ export const followAppServer = (context: {
21
+ server: { url: string; token: string };
22
+ manifest: DebugManifest;
23
+ telemetry: ReturnType<typeof createTelemetryFollower>;
24
+ requests: ReturnType<typeof createRequestFollower>;
25
+ trace: ReturnType<typeof createTraceDecoder>;
26
+ shown: ReturnType<typeof createShownReads>;
27
+ emit: (event: StreamEvent) => void;
28
+ /** Adds an entry to the timeline. */
29
+ record: (entry: TimelineEntry) => void;
30
+ /** Sends again an entry of the timeline that has changed. */
31
+ recordChange: (entry: TimelineEntry) => void;
32
+ /** The build the controller runs, as the telemetry reports it. */
33
+ setBuild: (build: string) => void;
34
+ /** Sends the session, whose scan rates and clock estimate the telemetry changes. */
35
+ sessionChanged: () => void;
36
+ signal: AbortSignal;
37
+ log: (message: string) => void;
38
+ }) => {
39
+ const { server, manifest, telemetry, requests, trace, shown, signal } =
40
+ context;
41
+
42
+ const receive = (received: ReceivedRecord) => {
43
+ const { record, at } = received;
44
+ if (record.kind === "trace") {
45
+ const traced = { ...received, record };
46
+ const event = trace.decode(traced);
47
+ if (event) {
48
+ context.record(timelineEntries.trace(at, event));
49
+ }
50
+ const site = trace.job(traced);
51
+ if (site) {
52
+ shown.traced(site.job, site.started, at);
53
+ }
54
+ return;
55
+ }
56
+ context.record(
57
+ timelineEntries.app(at, received.task, received.sequence, record),
58
+ );
59
+ if (record.kind !== "exception" || record.handled) {
60
+ return;
61
+ }
62
+ const job = manifest.jobs.find(
63
+ ({ name, instance }) =>
64
+ name === record.function && instance === record.instance,
65
+ );
66
+ if (job) {
67
+ shown.failed(job, {
68
+ at,
69
+ code: record.code,
70
+ ...(record.name && { name: record.name }),
71
+ source: record.source,
72
+ });
73
+ }
74
+ };
75
+
76
+ const pull = async (path: string, since: number) => {
77
+ const url = new URL(path, server.url);
78
+ url.searchParams.set("since", String(since));
79
+ const response = await fetch(url, {
80
+ headers: { authorization: `Bearer ${server.token}` },
81
+ signal,
82
+ });
83
+ if (!response.ok) {
84
+ throw new Error(`The server answered ${response.status}`);
85
+ }
86
+ return response.json();
87
+ };
88
+
89
+ const pullTelemetry = async () => {
90
+ const reply = telemetryReply.parse(
91
+ await pull(telemetryPath, telemetry.since()),
92
+ );
93
+ for (const item of telemetry.accept(reply)) {
94
+ receive(item);
95
+ }
96
+ const build = telemetry.build();
97
+ if (build) {
98
+ context.setBuild(build);
99
+ }
100
+ if (reply.batches.length) {
101
+ context.sessionChanged();
102
+ }
103
+ };
104
+
105
+ const pullRequests = async () => {
106
+ const reply = requestsReply.parse(
107
+ await pull(requestsPath, requests.since()),
108
+ );
109
+ requests.accept(reply, ({ request, entry, added }) => {
110
+ context.emit({ name: "request", data: request });
111
+ if (added) {
112
+ context.record(entry);
113
+ } else {
114
+ context.recordChange(entry);
115
+ }
116
+ const call = taggedCall(request);
117
+ if (!call) {
118
+ return;
119
+ }
120
+ const job = manifest.jobs.find(({ id }) => id === call.job);
121
+ if (job) {
122
+ shown.updateJob(job);
123
+ }
124
+ });
125
+ };
126
+
127
+ const repeat = async (name: string, work: () => Promise<void>) => {
128
+ let failure: string | undefined;
129
+ while (!signal.aborted) {
130
+ try {
131
+ await work();
132
+ failure = undefined;
133
+ } catch (error) {
134
+ if (signal.aborted) {
135
+ return;
136
+ }
137
+ const message = errorMessage(error);
138
+ if (message !== failure) {
139
+ context.log(`${name} failed: ${message}`);
140
+ }
141
+ failure = message;
142
+ }
143
+ await sleep(pullMs, signal);
144
+ }
145
+ };
146
+
147
+ return Promise.all([
148
+ repeat("Reading the server's telemetry", pullTelemetry),
149
+ repeat("Reading the server's requests", pullRequests),
150
+ ]);
151
+ };