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