@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/otlp.js ADDED
@@ -0,0 +1,634 @@
1
+ // Spec: 0001-telemetry FR-004
2
+ /**
3
+ * OTLP/HTTP with JSON, both ways (commons 0001-telemetry FR-004): export requests of traces, logs and metrics as the OTLP specification's
4
+ * JSON encoding writes them (camel-case field names, trace and span ids as hexadecimal, 64-bit integers as decimal strings, enumerations as
5
+ * integers, bytes as base64, signals grouped by resource and scope), the export responses with their partial success, and the decoding of
6
+ * each back to the values of `./otel.ts`: a failure is a `Result` naming the path, a 64-bit integer is read from a JSON number or a string,
7
+ * an enumeration from its number or its name, and a field the decoder does not know is ignored.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { decodeTraces, encodeTraces } from "./otlp.ts";
12
+ * const request = encodeTraces([{ resource: { attributes: { "service.name": "build" } }, scope: { name: "ifc" }, spans: [] }]);
13
+ * decodeTraces(JSON.parse(JSON.stringify(request))); // { kind: "ok", value: [ ...the same batch ] }
14
+ * ```
15
+ *
16
+ * @module
17
+ */
18
+ import { absurd, describe, err, ok } from "@intellectual-frontiers/core";
19
+ import { fromBase64, toBase64 } from "@intellectual-frontiers/formats/base64";
20
+ import { formatTracestate, isSeverityNumber, parseSpanId, parseTraceId, parseTracestate, } from "./otel.js";
21
+ // ---------------------------------------------------------------------------------------------------------------------------------
22
+ // Encoding
23
+ // ---------------------------------------------------------------------------------------------------------------------------------
24
+ const SPAN_KINDS = ["internal", "server", "client", "producer", "consumer"];
25
+ function encodeDouble(n) {
26
+ if (Number.isNaN(n))
27
+ return "NaN";
28
+ if (n === Infinity)
29
+ return "Infinity";
30
+ if (n === -Infinity)
31
+ return "-Infinity";
32
+ return n;
33
+ }
34
+ /** A value as OTLP's JSON `AnyValue`. */
35
+ export function encodeAnyValue(value) {
36
+ if (typeof value === "string")
37
+ return { stringValue: value };
38
+ if (typeof value === "boolean")
39
+ return { boolValue: value };
40
+ if (typeof value === "bigint")
41
+ return { intValue: value.toString() };
42
+ if (typeof value === "number")
43
+ return { doubleValue: encodeDouble(value) };
44
+ if (value instanceof Uint8Array)
45
+ return { bytesValue: toBase64(value) };
46
+ if (Array.isArray(value))
47
+ return { arrayValue: { values: value.map((v) => encodeAnyValue(v)) } };
48
+ return { kvlistValue: { values: Object.entries(value).map(([key, v]) => ({ key, value: encodeAnyValue(v) })) } };
49
+ }
50
+ /** Attributes as OTLP's JSON list of `KeyValue`. */
51
+ export function encodeAttributes(attributes) {
52
+ return Object.entries(attributes).map(([key, value]) => ({ key, value: encodeAnyValue(value) }));
53
+ }
54
+ function encodeResource(resource) {
55
+ return { attributes: encodeAttributes(resource.attributes) };
56
+ }
57
+ function encodeScope(scope) {
58
+ const out = { name: scope.name };
59
+ if (scope.version !== undefined)
60
+ out["version"] = scope.version;
61
+ if (scope.attributes !== undefined)
62
+ out["attributes"] = encodeAttributes(scope.attributes);
63
+ return out;
64
+ }
65
+ function withDropped(out, field, count) {
66
+ if (count !== 0)
67
+ out[field] = count;
68
+ }
69
+ function encodeEvent(e) {
70
+ const out = { timeUnixNano: e.time.toString(), name: e.name, attributes: encodeAttributes(e.attributes) };
71
+ withDropped(out, "droppedAttributesCount", e.droppedAttributesCount);
72
+ return out;
73
+ }
74
+ function encodeLink(l) {
75
+ const out = {
76
+ traceId: l.traceId,
77
+ spanId: l.spanId,
78
+ attributes: encodeAttributes(l.attributes),
79
+ flags: l.traceFlags,
80
+ };
81
+ if (l.traceState.length > 0)
82
+ out["traceState"] = formatTracestate(l.traceState);
83
+ withDropped(out, "droppedAttributesCount", l.droppedAttributesCount);
84
+ return out;
85
+ }
86
+ function encodeStatus(s) {
87
+ switch (s.kind) {
88
+ case "unset":
89
+ return { code: 0 };
90
+ case "ok":
91
+ return { code: 1 };
92
+ case "error":
93
+ return s.message === "" ? { code: 2 } : { code: 2, message: s.message };
94
+ default:
95
+ return absurd(s);
96
+ }
97
+ }
98
+ /** A finished span as OTLP's JSON `Span`. */
99
+ export function encodeSpan(s) {
100
+ const out = { traceId: s.context.traceId, spanId: s.context.spanId };
101
+ if (s.context.traceState.length > 0)
102
+ out["traceState"] = formatTracestate(s.context.traceState);
103
+ if (s.parentSpanId !== undefined)
104
+ out["parentSpanId"] = s.parentSpanId;
105
+ out["flags"] = s.context.traceFlags;
106
+ out["name"] = s.name;
107
+ out["kind"] = SPAN_KINDS.indexOf(s.kind) + 1;
108
+ out["startTimeUnixNano"] = s.startTime.toString();
109
+ out["endTimeUnixNano"] = s.endTime.toString();
110
+ out["attributes"] = encodeAttributes(s.attributes);
111
+ withDropped(out, "droppedAttributesCount", s.droppedAttributesCount);
112
+ out["events"] = s.events.map(encodeEvent);
113
+ withDropped(out, "droppedEventsCount", s.droppedEventsCount);
114
+ out["links"] = s.links.map(encodeLink);
115
+ withDropped(out, "droppedLinksCount", s.droppedLinksCount);
116
+ out["status"] = encodeStatus(s.status);
117
+ return out;
118
+ }
119
+ /** A log record as OTLP's JSON `LogRecord`. */
120
+ export function encodeLogRecord(r) {
121
+ const out = {
122
+ timeUnixNano: r.time.toString(),
123
+ observedTimeUnixNano: r.observedTime.toString(),
124
+ severityNumber: r.severityNumber,
125
+ severityText: r.severityText,
126
+ };
127
+ if (r.body !== undefined)
128
+ out["body"] = encodeAnyValue(r.body);
129
+ out["attributes"] = encodeAttributes(r.attributes);
130
+ withDropped(out, "droppedAttributesCount", r.droppedAttributesCount);
131
+ if (r.traceFlags !== undefined)
132
+ out["flags"] = r.traceFlags;
133
+ if (r.traceId !== undefined)
134
+ out["traceId"] = r.traceId;
135
+ if (r.spanId !== undefined)
136
+ out["spanId"] = r.spanId;
137
+ if (r.eventName !== undefined)
138
+ out["eventName"] = r.eventName;
139
+ return out;
140
+ }
141
+ function temporalityNumber(t) {
142
+ return t === "delta" ? 1 : 2;
143
+ }
144
+ function encodeNumberPoint(p) {
145
+ return {
146
+ attributes: encodeAttributes(p.attributes),
147
+ startTimeUnixNano: p.startTime.toString(),
148
+ timeUnixNano: p.time.toString(),
149
+ ...(typeof p.value === "bigint" ? { asInt: p.value.toString() } : { asDouble: encodeDouble(p.value) }),
150
+ };
151
+ }
152
+ function encodeHistogramPoint(p) {
153
+ const out = {
154
+ attributes: encodeAttributes(p.attributes),
155
+ startTimeUnixNano: p.startTime.toString(),
156
+ timeUnixNano: p.time.toString(),
157
+ count: String(p.count),
158
+ };
159
+ if (p.sum !== undefined)
160
+ out["sum"] = encodeDouble(p.sum);
161
+ out["bucketCounts"] = p.bucketCounts.map(String);
162
+ out["explicitBounds"] = p.bounds.map(encodeDouble);
163
+ if (p.min !== undefined)
164
+ out["min"] = encodeDouble(p.min);
165
+ if (p.max !== undefined)
166
+ out["max"] = encodeDouble(p.max);
167
+ return out;
168
+ }
169
+ function encodeMetricData(d) {
170
+ switch (d.kind) {
171
+ case "sum":
172
+ return {
173
+ sum: {
174
+ dataPoints: d.points.map(encodeNumberPoint),
175
+ aggregationTemporality: temporalityNumber(d.temporality),
176
+ isMonotonic: d.monotonic,
177
+ },
178
+ };
179
+ case "gauge":
180
+ return { gauge: { dataPoints: d.points.map(encodeNumberPoint) } };
181
+ case "histogram":
182
+ return { histogram: { dataPoints: d.points.map(encodeHistogramPoint), aggregationTemporality: temporalityNumber(d.temporality) } };
183
+ default:
184
+ return absurd(d);
185
+ }
186
+ }
187
+ /** A metric as OTLP's JSON `Metric`. */
188
+ export function encodeMetric(m) {
189
+ return { name: m.name, description: m.description, unit: m.unit, ...encodeMetricData(m.data) };
190
+ }
191
+ /** A canonical text of a JSON value, keys in order, to tell equal resources and scopes. */
192
+ function canonical(value) {
193
+ if (value === null || typeof value !== "object")
194
+ return JSON.stringify(value);
195
+ if (isJsonArray(value))
196
+ return `[${value.map((v) => canonical(v)).join(",")}]`;
197
+ const keys = Object.keys(value).sort();
198
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(value[k] ?? null)}`).join(",")}}`;
199
+ }
200
+ function isJsonArray(value) {
201
+ return Array.isArray(value);
202
+ }
203
+ /** Batches grouped as OTLP groups them: one entry per distinct resource, one per distinct scope within it, in first-seen order. */
204
+ function group(batches, items, resourceField, scopeField, itemsField) {
205
+ const resources = new Map();
206
+ for (const b of batches) {
207
+ const resource = encodeResource(b.resource);
208
+ const rk = canonical(resource);
209
+ let r = resources.get(rk);
210
+ if (r === undefined) {
211
+ r = { resource, scopes: new Map() };
212
+ resources.set(rk, r);
213
+ }
214
+ const scope = encodeScope(b.scope);
215
+ const sk = canonical(scope);
216
+ let s = r.scopes.get(sk);
217
+ if (s === undefined) {
218
+ s = { scope, items: [] };
219
+ r.scopes.set(sk, s);
220
+ }
221
+ s.items.push(...items(b));
222
+ }
223
+ return {
224
+ [resourceField]: [...resources.values()].map((r) => ({
225
+ resource: r.resource,
226
+ [scopeField]: [...r.scopes.values()].map((s) => ({ scope: s.scope, [itemsField]: s.items })),
227
+ })),
228
+ };
229
+ }
230
+ /** Trace batches as an OTLP/JSON `ExportTraceServiceRequest`. */
231
+ export function encodeTraces(batches) {
232
+ return group(batches, (b) => b.spans.map(encodeSpan), "resourceSpans", "scopeSpans", "spans");
233
+ }
234
+ /** Log batches as an OTLP/JSON `ExportLogsServiceRequest`. */
235
+ export function encodeLogs(batches) {
236
+ return group(batches, (b) => b.records.map(encodeLogRecord), "resourceLogs", "scopeLogs", "logRecords");
237
+ }
238
+ /** Metric batches as an OTLP/JSON `ExportMetricsServiceRequest`. */
239
+ export function encodeMetrics(batches) {
240
+ return group(batches, (b) => b.metrics.map(encodeMetric), "resourceMetrics", "scopeMetrics", "metrics");
241
+ }
242
+ const REJECTED_FIELD = {
243
+ traces: "rejectedSpans",
244
+ logs: "rejectedLogRecords",
245
+ metrics: "rejectedDataPoints",
246
+ };
247
+ /** An export response as OTLP/JSON: `{}` for full success, else `partialSuccess` with the rejected count (a decimal string) and the message. */
248
+ export function encodeResponse(signal, response) {
249
+ if (response.rejected === 0 && response.errorMessage === "")
250
+ return {};
251
+ return { partialSuccess: { [REJECTED_FIELD[signal]]: String(response.rejected), errorMessage: response.errorMessage } };
252
+ }
253
+ // ---------------------------------------------------------------------------------------------------------------------------------
254
+ // Decoding
255
+ // ---------------------------------------------------------------------------------------------------------------------------------
256
+ /** Thrown inside this module only, by a field reader, and caught by `message`; never seen outside. */
257
+ class Failure extends Error {
258
+ error;
259
+ constructor(error) {
260
+ super(error.path);
261
+ this.error = error;
262
+ }
263
+ }
264
+ function failure(path, expected, input) {
265
+ return { kind: "decode", path, expected, found: describe(input) };
266
+ }
267
+ function message(build) {
268
+ return (input, path = "$") => {
269
+ if (typeof input !== "object" || input === null || Array.isArray(input))
270
+ return err(failure(path, "an object", input));
271
+ const read = (key, decoder) => {
272
+ const r = decoder(Reflect.get(input, key), `${path}.${key}`);
273
+ if (r.kind === "err")
274
+ throw new Failure(r.error);
275
+ return r.value;
276
+ };
277
+ const f = {
278
+ req: read,
279
+ opt: (key, decoder, fallback) => {
280
+ const v = Reflect.get(input, key);
281
+ return v === undefined || v === null ? fallback : read(key, decoder);
282
+ },
283
+ };
284
+ try {
285
+ return ok(build(f, path));
286
+ }
287
+ catch (e) {
288
+ if (e instanceof Failure)
289
+ return err(e.error);
290
+ throw e;
291
+ }
292
+ };
293
+ }
294
+ function list(element) {
295
+ return (input, path = "$") => {
296
+ if (!Array.isArray(input))
297
+ return err(failure(path, "an array", input));
298
+ const out = [];
299
+ for (const [i, value] of input.entries()) {
300
+ const r = element(value, `${path}[${i}]`);
301
+ if (r.kind === "err")
302
+ return r;
303
+ out.push(r.value);
304
+ }
305
+ return ok(out);
306
+ };
307
+ }
308
+ const str = (input, path = "$") => (typeof input === "string" ? ok(input) : err(failure(path, "a string", input)));
309
+ const bool = (input, path = "$") => (typeof input === "boolean" ? ok(input) : err(failure(path, "a boolean", input)));
310
+ /** A 64-bit integer from a JSON number or a decimal string. */
311
+ const int64 = (input, path = "$") => {
312
+ if (typeof input === "number" && Number.isInteger(input))
313
+ return ok(BigInt(input));
314
+ if (typeof input === "string" && /^-?[0-9]+$/.test(input))
315
+ return ok(BigInt(input));
316
+ return err(failure(path, "a 64-bit integer (a number or a decimal string)", input));
317
+ };
318
+ /** A non-negative count: an integer from a number or a decimal string, within the safe integers. */
319
+ const count = (input, path = "$") => {
320
+ const r = int64(input, path);
321
+ if (r.kind === "err")
322
+ return r;
323
+ return r.value >= 0n && r.value <= BigInt(Number.MAX_SAFE_INTEGER) ? ok(Number(r.value)) : err(failure(path, "a count", input));
324
+ };
325
+ /** A double from a number, or the strings `NaN`, `Infinity` and `-Infinity` of proto3 JSON. */
326
+ const double = (input, path = "$") => {
327
+ if (typeof input === "number")
328
+ return ok(input);
329
+ if (input === "NaN")
330
+ return ok(NaN);
331
+ if (input === "Infinity")
332
+ return ok(Infinity);
333
+ if (input === "-Infinity")
334
+ return ok(-Infinity);
335
+ return err(failure(path, "a double", input));
336
+ };
337
+ const bytes = (input, path = "$") => {
338
+ if (typeof input !== "string")
339
+ return err(failure(path, "base64", input));
340
+ const r = fromBase64(input);
341
+ return r.kind === "ok" ? r : err(failure(path, "base64", input));
342
+ };
343
+ const traceId = (input, path = "$") => {
344
+ const r = typeof input === "string" ? parseTraceId(input.toLowerCase()) : err("");
345
+ return r.kind === "ok" ? r : err(failure(path, "a trace id (32 hexadecimal digits, not all zeros)", input));
346
+ };
347
+ const spanId = (input, path = "$") => {
348
+ const r = typeof input === "string" ? parseSpanId(input.toLowerCase()) : err("");
349
+ return r.kind === "ok" ? r : err(failure(path, "a span id (16 hexadecimal digits, not all zeros)", input));
350
+ };
351
+ /** An enumeration from its number or its name; `names[i]` is the name of `i`. */
352
+ function enumeration(names) {
353
+ return (input, path = "$") => {
354
+ if (typeof input === "number" && Number.isInteger(input) && input >= 0 && input < names.length)
355
+ return ok(input);
356
+ if (typeof input === "string") {
357
+ const i = names.indexOf(input);
358
+ if (i >= 0)
359
+ return ok(i);
360
+ }
361
+ return err(failure(path, `one of ${names.join(", ")} or its number`, input));
362
+ };
363
+ }
364
+ const spanKindEnum = enumeration([
365
+ "SPAN_KIND_UNSPECIFIED",
366
+ "SPAN_KIND_INTERNAL",
367
+ "SPAN_KIND_SERVER",
368
+ "SPAN_KIND_CLIENT",
369
+ "SPAN_KIND_PRODUCER",
370
+ "SPAN_KIND_CONSUMER",
371
+ ]);
372
+ const statusCodeEnum = enumeration(["STATUS_CODE_UNSET", "STATUS_CODE_OK", "STATUS_CODE_ERROR"]);
373
+ const temporalityEnum = enumeration([
374
+ "AGGREGATION_TEMPORALITY_UNSPECIFIED",
375
+ "AGGREGATION_TEMPORALITY_DELTA",
376
+ "AGGREGATION_TEMPORALITY_CUMULATIVE",
377
+ ]);
378
+ const SEVERITY_NAMES = ["SEVERITY_NUMBER_UNSPECIFIED"].concat(["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"].flatMap((r) => ["", "2", "3", "4"].map((n) => `SEVERITY_NUMBER_${r}${n}`)));
379
+ const severityEnum = (input, path = "$") => {
380
+ const r = enumeration(SEVERITY_NAMES)(input, path);
381
+ if (r.kind === "err")
382
+ return r;
383
+ return isSeverityNumber(r.value) ? ok(r.value) : err(failure(path, "a severity number from 1 to 24", input));
384
+ };
385
+ /** OTLP's JSON `AnyValue` as a value; an `AnyValue` that holds none is refused. */
386
+ export const decodeAnyValue = (input, path = "$") => {
387
+ if (typeof input !== "object" || input === null || Array.isArray(input))
388
+ return err(failure(path, "an AnyValue object", input));
389
+ const has = (key) => {
390
+ const v = Reflect.get(input, key);
391
+ return v !== undefined && v !== null;
392
+ };
393
+ const at = (key) => Reflect.get(input, key);
394
+ if (has("stringValue"))
395
+ return str(at("stringValue"), `${path}.stringValue`);
396
+ if (has("boolValue"))
397
+ return bool(at("boolValue"), `${path}.boolValue`);
398
+ if (has("intValue"))
399
+ return int64(at("intValue"), `${path}.intValue`);
400
+ if (has("doubleValue"))
401
+ return double(at("doubleValue"), `${path}.doubleValue`);
402
+ if (has("bytesValue"))
403
+ return bytes(at("bytesValue"), `${path}.bytesValue`);
404
+ if (has("arrayValue"))
405
+ return message((f) => f.opt("values", list(decodeAnyValue), []))(at("arrayValue"), `${path}.arrayValue`);
406
+ if (has("kvlistValue")) {
407
+ return message((f) => {
408
+ const out = {};
409
+ for (const kv of f.opt("values", list(keyValue(decodeAnyValue)), [])) {
410
+ Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
411
+ }
412
+ return out;
413
+ })(at("kvlistValue"), `${path}.kvlistValue`);
414
+ }
415
+ return err(failure(path, "an AnyValue holding a value", input));
416
+ };
417
+ function keyValue(value) {
418
+ return message((f) => ({ key: f.req("key", str), value: f.req("value", value) }));
419
+ }
420
+ /** An `AnyValue` that is an attribute value: a primitive, or an array of primitives of one type. */
421
+ export const decodeAttributeValue = (input, path = "$") => {
422
+ const r = decodeAnyValue(input, path);
423
+ if (r.kind === "err")
424
+ return r;
425
+ const v = r.value;
426
+ if (typeof v !== "object" || v instanceof Uint8Array)
427
+ return ok(v);
428
+ if (Array.isArray(v)) {
429
+ const values = v;
430
+ if (values.every((e) => typeof e === "string"))
431
+ return ok(values.filter((e) => typeof e === "string"));
432
+ if (values.every((e) => typeof e === "boolean"))
433
+ return ok(values.filter((e) => typeof e === "boolean"));
434
+ if (values.every((e) => typeof e === "bigint"))
435
+ return ok(values.filter((e) => typeof e === "bigint"));
436
+ if (values.every((e) => typeof e === "number"))
437
+ return ok(values.filter((e) => typeof e === "number"));
438
+ }
439
+ return err(failure(path, "an attribute value (a primitive or a homogeneous array of primitives)", input));
440
+ };
441
+ /** OTLP's JSON list of `KeyValue` as attributes. */
442
+ export const decodeAttributes = (input, path = "$") => {
443
+ const r = list(keyValue(decodeAttributeValue))(input, path);
444
+ if (r.kind === "err")
445
+ return r;
446
+ const out = {};
447
+ for (const kv of r.value)
448
+ Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
449
+ return ok(out);
450
+ };
451
+ const resource = message((f) => ({ attributes: f.opt("attributes", decodeAttributes, {}) }));
452
+ const scope = message((f) => {
453
+ const version = f.opt("version", str, undefined);
454
+ const attributes = f.opt("attributes", decodeAttributes, undefined);
455
+ return {
456
+ name: f.opt("name", str, ""),
457
+ ...(version === undefined ? {} : { version }),
458
+ ...(attributes === undefined ? {} : { attributes }),
459
+ };
460
+ });
461
+ const event = message((f) => ({
462
+ name: f.opt("name", str, ""),
463
+ time: f.opt("timeUnixNano", int64, 0n),
464
+ attributes: f.opt("attributes", decodeAttributes, {}),
465
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
466
+ }));
467
+ const link = message((f) => ({
468
+ traceId: f.req("traceId", traceId),
469
+ spanId: f.req("spanId", spanId),
470
+ traceState: parseTracestate(f.opt("traceState", str, "")),
471
+ traceFlags: f.opt("flags", count, 0) & 0xff,
472
+ attributes: f.opt("attributes", decodeAttributes, {}),
473
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
474
+ }));
475
+ const status = message((f) => {
476
+ const code = f.opt("code", statusCodeEnum, 0);
477
+ if (code === 1)
478
+ return { kind: "ok" };
479
+ if (code === 2)
480
+ return { kind: "error", message: f.opt("message", str, "") };
481
+ return { kind: "unset" };
482
+ });
483
+ const optionalSpanId = (input, path = "$") => (input === "" ? ok(undefined) : spanId(input, path));
484
+ /** OTLP's JSON `Span` as a finished span. */
485
+ export const decodeSpan = message((f) => {
486
+ const parentSpanId = f.opt("parentSpanId", optionalSpanId, undefined);
487
+ const kind = f.opt("kind", spanKindEnum, 1);
488
+ return {
489
+ name: f.opt("name", str, ""),
490
+ context: {
491
+ traceId: f.req("traceId", traceId),
492
+ spanId: f.req("spanId", spanId),
493
+ traceFlags: f.opt("flags", count, 0) & 0xff,
494
+ traceState: parseTracestate(f.opt("traceState", str, "")),
495
+ isRemote: false,
496
+ },
497
+ ...(parentSpanId === undefined ? {} : { parentSpanId }),
498
+ kind: SPAN_KINDS[kind - 1] ?? "internal",
499
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
500
+ endTime: f.opt("endTimeUnixNano", int64, 0n),
501
+ attributes: f.opt("attributes", decodeAttributes, {}),
502
+ events: f.opt("events", list(event), []),
503
+ links: f.opt("links", list(link), []),
504
+ status: f.opt("status", status, { kind: "unset" }),
505
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
506
+ droppedEventsCount: f.opt("droppedEventsCount", count, 0),
507
+ droppedLinksCount: f.opt("droppedLinksCount", count, 0),
508
+ };
509
+ });
510
+ const optionalTraceId = (input, path = "$") => (input === "" ? ok(undefined) : traceId(input, path));
511
+ /** OTLP's JSON `LogRecord` as a log record; its severity number must be 1 to 24. */
512
+ export const decodeLogRecord = message((f) => {
513
+ const body = f.opt("body", decodeAnyValue, undefined);
514
+ const traceFlags = f.opt("flags", count, undefined);
515
+ const tid = f.opt("traceId", optionalTraceId, undefined);
516
+ const sid = f.opt("spanId", optionalSpanId, undefined);
517
+ const eventName = f.opt("eventName", str, undefined);
518
+ return {
519
+ time: f.opt("timeUnixNano", int64, 0n),
520
+ observedTime: f.opt("observedTimeUnixNano", int64, 0n),
521
+ severityNumber: f.req("severityNumber", severityEnum),
522
+ severityText: f.opt("severityText", str, ""),
523
+ ...(body === undefined ? {} : { body }),
524
+ attributes: f.opt("attributes", decodeAttributes, {}),
525
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
526
+ ...(eventName === undefined ? {} : { eventName }),
527
+ ...(tid === undefined ? {} : { traceId: tid }),
528
+ ...(sid === undefined ? {} : { spanId: sid }),
529
+ ...(traceFlags === undefined ? {} : { traceFlags: traceFlags & 0xff }),
530
+ };
531
+ });
532
+ const numberPoint = message((f, path) => {
533
+ const asInt = f.opt("asInt", int64, undefined);
534
+ const asDouble = f.opt("asDouble", double, undefined);
535
+ const value = asInt ?? asDouble;
536
+ if (value === undefined)
537
+ throw new Failure(failure(`${path}.asDouble`, "asInt or asDouble", undefined));
538
+ return {
539
+ attributes: f.opt("attributes", decodeAttributes, {}),
540
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
541
+ time: f.opt("timeUnixNano", int64, 0n),
542
+ value,
543
+ };
544
+ });
545
+ const histogramPoint = message((f, path) => {
546
+ const sum = f.opt("sum", double, undefined);
547
+ const min = f.opt("min", double, undefined);
548
+ const max = f.opt("max", double, undefined);
549
+ const bounds = f.opt("explicitBounds", list(double), []);
550
+ const bucketCounts = f.opt("bucketCounts", list(count), []);
551
+ if (bucketCounts.length !== 0 && bucketCounts.length !== bounds.length + 1) {
552
+ throw new Failure(failure(`${path}.bucketCounts`, `${bounds.length + 1} bucket counts`, bucketCounts.length));
553
+ }
554
+ return {
555
+ attributes: f.opt("attributes", decodeAttributes, {}),
556
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
557
+ time: f.opt("timeUnixNano", int64, 0n),
558
+ count: f.opt("count", count, 0),
559
+ ...(sum === undefined ? {} : { sum }),
560
+ ...(min === undefined ? {} : { min }),
561
+ ...(max === undefined ? {} : { max }),
562
+ bounds,
563
+ bucketCounts,
564
+ };
565
+ });
566
+ function temporalityOf(n) {
567
+ return n === 1 ? "delta" : "cumulative";
568
+ }
569
+ /** OTLP's JSON `Metric` as a metric: a sum, a gauge or a histogram (other data is refused). */
570
+ export const decodeMetric = message((f, path) => {
571
+ const head = { name: f.opt("name", str, ""), description: f.opt("description", str, ""), unit: f.opt("unit", str, "") };
572
+ const sum = f.opt("sum", message((g) => ({
573
+ kind: "sum",
574
+ points: g.opt("dataPoints", list(numberPoint), []),
575
+ temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2)),
576
+ monotonic: g.opt("isMonotonic", bool, false),
577
+ })), undefined);
578
+ if (sum !== undefined)
579
+ return { ...head, data: sum };
580
+ const gauge = f.opt("gauge", message((g) => ({ kind: "gauge", points: g.opt("dataPoints", list(numberPoint), []) })), undefined);
581
+ if (gauge !== undefined)
582
+ return { ...head, data: gauge };
583
+ const histogram = f.opt("histogram", message((g) => ({
584
+ kind: "histogram",
585
+ points: g.opt("dataPoints", list(histogramPoint), []),
586
+ temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2)),
587
+ })), undefined);
588
+ if (histogram !== undefined)
589
+ return { ...head, data: histogram };
590
+ throw new Failure(failure(`${path}.sum`, "a sum, a gauge or a histogram", undefined));
591
+ });
592
+ function ungroup(resourceField, scopeField, itemsField, item) {
593
+ return message((f) => f
594
+ .opt(resourceField, list(message((r) => {
595
+ const res = r.opt("resource", resource, { attributes: {} });
596
+ return r
597
+ .opt(scopeField, list(message((s) => ({ scope: s.opt("scope", scope, { name: "" }), items: s.opt(itemsField, list(item), []) }))), [])
598
+ .map((s) => ({ resource: res, ...s }));
599
+ })), [])
600
+ .flat());
601
+ }
602
+ /** An OTLP/JSON `ExportTraceServiceRequest` as trace batches, one for each scope of each resource; a failure names its path. */
603
+ export function decodeTraces(input) {
604
+ const r = ungroup("resourceSpans", "scopeSpans", "spans", decodeSpan)(input);
605
+ return r.kind === "err" ? r : ok(r.value.map((b) => ({ resource: b.resource, scope: b.scope, spans: b.items })));
606
+ }
607
+ /** An OTLP/JSON `ExportLogsServiceRequest` as log batches, one for each scope of each resource; a failure names its path. */
608
+ export function decodeLogs(input) {
609
+ const r = ungroup("resourceLogs", "scopeLogs", "logRecords", decodeLogRecord)(input);
610
+ return r.kind === "err" ? r : ok(r.value.map((b) => ({ resource: b.resource, scope: b.scope, records: b.items })));
611
+ }
612
+ /** An OTLP/JSON `ExportMetricsServiceRequest` as metric batches, one for each scope of each resource; a failure names its path. */
613
+ export function decodeMetrics(input) {
614
+ const r = ungroup("resourceMetrics", "scopeMetrics", "metrics", decodeMetric)(input);
615
+ return r.kind === "err" ? r : ok(r.value.map((b) => ({ resource: b.resource, scope: b.scope, metrics: b.items })));
616
+ }
617
+ /** An OTLP/JSON export response; an absent `partialSuccess` is full success. */
618
+ export function decodeResponse(signal, input) {
619
+ return message((f) => f.opt("partialSuccess", message((p) => ({ rejected: p.opt(REJECTED_FIELD[signal], count, 0), errorMessage: p.opt("errorMessage", str, "") })), { rejected: 0, errorMessage: "" }))(input);
620
+ }
621
+ /** The number of signals in trace, log or metric batches: spans, log records, or data points (what a partial success counts). */
622
+ export function countSignals(batches) {
623
+ let n = 0;
624
+ for (const b of batches) {
625
+ if ("spans" in b)
626
+ n += b.spans.length;
627
+ else if ("records" in b)
628
+ n += b.records.length;
629
+ else
630
+ for (const m of b.metrics)
631
+ n += m.data.points.length;
632
+ }
633
+ return n;
634
+ }