Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

observability.ts

839 lines25.4 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import type * as Exit from "effect/Exit";
5import * as ExitRuntime from "effect/Exit";
6import * as Option from "effect/Option";
7import * as Queue from "effect/Queue";
8import * as Result from "effect/Result";
9import * as Semaphore from "effect/Semaphore";
10import * as Schema from "effect/Schema";
11import * as SchemaIssue from "effect/SchemaIssue";
12import * as SchemaTransformation from "effect/SchemaTransformation";
13import * as Tracer from "effect/Tracer";
14import { OtlpResource, OtlpTracer, OtlpSerialization } from "effect/observability";
15​
16import { makeAsyncRotatingFileSink } from "./logging.ts";
17​
18export const OtlpProtocol = Schema.Literals(["http/json", "http/protobuf"]);
19export type OtlpProtocol = typeof OtlpProtocol.Type;
20export const layerOtlpSerialization = (protocol: OtlpProtocol) =>
21 protocol === "http/protobuf" ? OtlpSerialization.layerProtobuf : OtlpSerialization.layerJson;
22​
23export interface SignalExport {
24 readonly protocol: OtlpProtocol;
25 readonly headers: Readonly<Record<string, string>> | undefined;
26 readonly exportIntervalMs: number;
28​
29/**
30 * `process.runtime.*` resource attributes for a Node process, matching the
31 * OpenTelemetry Node process detector. Electron embeds Node, so an Electron
32 * process reports Node and names Electron in the description.
33 */
34export const nodeProcessRuntimeAttributes = (): Record<string, string> => ({
35 "process.runtime.name": "nodejs",
36 "process.runtime.version": process.versions.node,
37 "process.runtime.description": process.versions.electron
38 ? `Electron ${process.versions.electron}`
39 : "Node.js",
40});
41let generatedServiceInstanceId: string | undefined;
42​
43/**
44 * `service.instance.id` shared by every resource this process exports. Effect lets code
45 * attributes beat `OTEL_RESOURCE_ATTRIBUTES`, so callers pass the operator's in to keep it winning.
46 */
47export const processServiceInstanceId = (
48 operatorAttributes: Readonly<Record<string, string>> = {},
49): string => {
50 if (operatorAttributes["service.instance.id"]) return operatorAttributes["service.instance.id"];
51 // @effect-diagnostics-next-line cryptoRandomUUID:off -- Resources are built synchronously, outside any Effect.
52 generatedServiceInstanceId ??= crypto.randomUUID();
53 return generatedServiceInstanceId;
54};
55​
56export const DEFAULT_SIGNAL_EXPORT: SignalExport = {
57 protocol: "http/json",
58 headers: undefined,
59 exportIntervalMs: 10_000,
60};
61​
62const FLUSH_BUFFER_THRESHOLD = 256;
63​
64export type TraceAttributes = Readonly<Record<string, unknown>>;
65​
66export interface TraceRecordEvent {
67 readonly name: string;
68 readonly timeUnixNano: string;
69 readonly attributes: Readonly<Record<string, unknown>>;
71​
72export interface TraceRecordLink {
73 readonly traceId: string;
74 readonly spanId: string;
75 readonly attributes: Readonly<Record<string, unknown>>;
77​
78interface BaseTraceRecord {
79 readonly name: string;
80 readonly kind: string;
81 readonly traceId: string;
82 readonly spanId: string;
83 readonly parentSpanId?: string;
84 readonly sampled: boolean;
85 readonly startTimeUnixNano: string;
86 readonly endTimeUnixNano: string;
87 readonly durationMs: number;
88 readonly attributes: Readonly<Record<string, unknown>>;
89 readonly events: ReadonlyArray<TraceRecordEvent>;
90 readonly links: ReadonlyArray<TraceRecordLink>;
92​
93export interface EffectTraceRecord extends BaseTraceRecord {
94 readonly type: "effect-span";
95 readonly exit:
96 | {
97 readonly _tag: "Success";
98 }
99 | {
100 readonly _tag: "Interrupted";
101 readonly cause: string;
102 }
103 | {
104 readonly _tag: "Failure";
105 readonly cause: string;
106 };
108​
109export interface OtlpTraceRecord extends BaseTraceRecord {
110 readonly type: "otlp-span";
111 readonly resourceAttributes: Readonly<Record<string, unknown>>;
112 readonly scope: Readonly<{
113 readonly name?: string;
114 readonly version?: string;
115 readonly attributes: Readonly<Record<string, unknown>>;
116 }>;
117 readonly status?:
118 | {
119 readonly code?: string;
120 readonly message?: string;
121 }
122 | undefined;
124​
125export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
126​
127function isStructuralTag(value: unknown): value is string {
128 return (
129 typeof value === "string" &&
130 value.length > 0 &&
131 value.length <= 128 &&
132 /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)
133 );
135​
136export function errorTag(error: unknown): string {
137 try {
138 if (typeof error === "object" && error !== null && "_tag" in error) {
139 return isStructuralTag(error._tag) ? error._tag : "TaggedError";
140 }
141 if (error instanceof Error) {
142 return isStructuralTag(error.name) ? error.name : "Error";
143 }
144 } catch {
145 return "UnknownError";
146 }
147 return typeof error;
149​
150export function causeErrorTag(cause: Cause.Cause<unknown>): string {
151 const failure = Cause.findErrorOption(cause);
152 if (Option.isSome(failure)) {
153 return errorTag(failure.value);
154 }
155 return cause.reasons[0]?._tag ?? "Empty";
157​
158export interface TraceSinkOptions {
159 readonly filePath: string;
160 readonly maxBytes: number;
161 readonly maxFiles: number;
162 readonly batchWindowMs: number;
163 readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
165​
166export interface TraceSinkFlushStats {
167 readonly logicalWriteBytes: number;
168 readonly count: number;
169 readonly durationMs: number;
171​
172export interface TraceSink {
173 readonly filePath: string;
174 push: (record: TraceRecord) => void;
175 flush: Effect.Effect<void>;
176 close: () => Effect.Effect<void>;
178​
179export interface LocalFileTracerOptions extends TraceSinkOptions {
180 readonly delegate?: Tracer.Tracer;
181 readonly sink?: TraceSink;
183​
184type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
185type OtlpSpanEvent = OtlpSpan["events"][number];
186type OtlpSpanLink = OtlpSpan["links"][number];
187type OtlpSpanStatus = OtlpSpan["status"];
188​
189interface SerializableSpan {
190 readonly name: string;
191 readonly traceId: string;
192 readonly spanId: string;
193 readonly parent: Option.Option<Tracer.AnySpan>;
194 readonly status: Tracer.SpanStatus;
195 readonly sampled: boolean;
196 readonly kind: Tracer.SpanKind;
197 readonly attributes: ReadonlyMap<string, unknown>;
198 readonly links: ReadonlyArray<Tracer.SpanLink>;
199 readonly events: ReadonlyArray<
200 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
201 >;
203​
204function isPlainObject(value: unknown): value is Record<string, unknown> {
205 return typeof value === "object" && value !== null && !Array.isArray(value);
207​
208// Repeated references expand once per path, so a small shared graph can grow exponentially.
209const TRACE_ATTRIBUTE_MAX_NODES = 10_000;
210​
211interface NormalizeState {
212 // Only the current ancestors, so a value repeated under two keys is not a cycle.
213 readonly seen: WeakSet<object>;
214 remainingNodes: number;
216​
217function enterNode(value: object, state: NormalizeState): string | undefined {
218 if (state.seen.has(value)) {
219 return "[Circular]";
220 }
221 if (state.remainingNodes <= 0) {
222 return "[Truncated]";
223 }
224 state.remainingNodes--;
225 state.seen.add(value);
226 return undefined;
228​
229function normalizeJsonValue(value: unknown, state: NormalizeState): unknown {
230 if (
231 value === null ||
232 value === undefined ||
233 typeof value === "string" ||
234 typeof value === "number" ||
235 typeof value === "boolean"
236 ) {
237 return value ?? null;
238 }
239 if (typeof value === "bigint") {
240 return value.toString();
241 }
242 if (value instanceof Date) {
243 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
244 }
245 if (value instanceof Error) {
246 return {
247 name: value.name,
248 message: value.message,
249 ...(value.stack ? { stack: value.stack } : {}),
250 };
251 }
252 if (Array.isArray(value)) {
253 const marker = enterNode(value, state);
254 if (marker) {
255 return marker;
256 }
257 const normalized = value.map((entry) => normalizeJsonValue(entry, state));
258 state.seen.delete(value);
259 return normalized;
260 }
261 if (value instanceof Map) {
262 const marker = enterNode(value, state);
263 if (marker) {
264 return marker;
265 }
266 const normalized = Object.fromEntries(
267 Array.from(value.entries(), ([key, entryValue]) => [
268 String(key),
269 normalizeJsonValue(entryValue, state),
270 ]),
271 );
272 state.seen.delete(value);
273 return normalized;
274 }
275 if (value instanceof Set) {
276 const marker = enterNode(value, state);
277 if (marker) {
278 return marker;
279 }
280 const normalized = Array.from(value.values(), (entry) => normalizeJsonValue(entry, state));
281 state.seen.delete(value);
282 return normalized;
283 }
284 if (!isPlainObject(value)) {
285 return String(value);
286 }
287 const marker = enterNode(value, state);
288 if (marker) {
289 return marker;
290 }
291 const normalized = Object.fromEntries(
292 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, state)]),
293 );
294 state.seen.delete(value);
295 return normalized;
297​
298export function compactTraceAttributes(
299 attributes: Readonly<Record<string, unknown>>,
300): TraceAttributes {
301 const state: NormalizeState = { seen: new WeakSet(), remainingNodes: TRACE_ATTRIBUTE_MAX_NODES };
302 const entries: Array<[string, unknown]> = [];
303 for (const [key, value] of Object.entries(attributes)) {
304 if (value !== undefined) {
305 entries.push([key, normalizeJsonValue(value, state)]);
306 }
307 }
308 return Object.fromEntries(entries);
310​
311function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
312 if (ExitRuntime.isSuccess(exit)) {
313 return { _tag: "Success" };
314 }
315 if (Cause.hasInterruptsOnly(exit.cause)) {
316 return {
317 _tag: "Interrupted",
318 cause: Cause.pretty(exit.cause),
319 };
320 }
321 return {
322 _tag: "Failure",
323 cause: Cause.pretty(exit.cause),
324 };
326​
327const TRACE_ATTRIBUTE_MAX_LENGTH = 500;
328const TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;
329const TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = "…[truncated]";
330const ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set(["db.query.text"]);
331​
332function truncateNestedValue(value: unknown): unknown {
333 if (typeof value === "string") {
334 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
335 ? value
336 : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
337 }
338 if (Array.isArray(value)) {
339 const truncated = value.map(truncateNestedValue);
340 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
341 }
342 if (isPlainObject(value)) {
343 let truncated: Record<string, unknown> | undefined;
344 for (const [key, entry] of Object.entries(value)) {
345 const next = truncateNestedValue(entry);
346 if (next === entry) continue;
347 truncated ??= { ...value };
348 truncated[key] = next;
349 }
350 return truncated ?? value;
351 }
352 return value;
354​
355/** Clones only when clamping; never mutates attributes shared with other tracers. */
356export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
357 let truncated: Record<string, unknown> | undefined;
358 for (const [key, value] of Object.entries(attributes)) {
359 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
360 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
361 truncated ??= { ...attributes };
362 truncated[key] =
363 `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
364 continue;
365 }
366 const next = truncateNestedValue(value);
367 if (next === value) continue;
368 truncated ??= { ...attributes };
369 truncated[key] = next;
370 }
371 return truncated ?? attributes;
373​
374function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
375 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
376 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
377​
378 return {
379 type: "effect-span",
380 name: span.name,
381 traceId: span.traceId,
382 spanId: span.spanId,
383 ...(parentSpanId ? { parentSpanId } : {}),
384 sampled: span.sampled,
385 kind: span.kind,
386 startTimeUnixNano: String(status.startTime),
387 endTimeUnixNano: String(status.endTime),
388 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
389 attributes: truncateTraceAttributes(
390 compactTraceAttributes(Object.fromEntries(span.attributes)),
391 ),
392 events: span.events.map(([name, startTime, attributes]) => ({
393 name,
394 timeUnixNano: String(startTime),
395 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
396 })),
397 links: span.links.map((link) => ({
398 traceId: link.span.traceId,
399 spanId: link.span.spanId,
400 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
401 })),
402 exit: formatTraceExit(status.exit),
403 };
405​
406export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
407 const sink = yield* makeAsyncRotatingFileSink({
408 filePath: options.filePath,
409 maxBytes: options.maxBytes,
410 maxFiles: options.maxFiles,
411 }).pipe(Effect.orDie);
412​
413 let buffer: Array<{ readonly text: string; readonly bytes: number }> = [];
414 let bufferBytes = 0;
415 const maxBufferBytes = Math.max(options.maxBytes, 4 * 1024 * 1024);
416 const flushRequests = yield* Queue.sliding<void>(1);
417 const flushSemaphore = yield* Semaphore.make(1);
418 let writeFailing = false;
419 let droppedCount = 0;
420 let failureReported = false;
421 let pendingFlushStats: TraceSinkFlushStats = {
422 logicalWriteBytes: 0,
423 count: 0,
424 durationMs: 0,
425 };
426​
427 const flushBuffered = Effect.gen(function* () {
428 if (buffer.length === 0) {
429 return;
430 }
431​
432 const records = buffer;
433 buffer = [];
434 bufferBytes = 0;
435 let persistedCount = 0;
436​
437 while (persistedCount < records.length) {
438 const firstRecordBytes = records[persistedCount]!.bytes;
439 let nextIndex = persistedCount + 1;
440 let chunkBytes = firstRecordBytes;
441 while (nextIndex < records.length) {
442 const nextRecordBytes = records[nextIndex]!.bytes;
443 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
444 chunkBytes += nextRecordBytes;
445 nextIndex += 1;
446 }
447​
448 const chunk = records
449 .slice(persistedCount, nextIndex)
450 .map((record) => record.text)
451 .join("");
452 const startedAt = performance.now();
453 const written = yield* sink.write(chunk).pipe(Effect.result);
454 if (Result.isFailure(written)) {
455 // Drop the batch after disk failure to avoid an ever-growing retry backlog.
456 writeFailing = true;
457 droppedCount += records.length - persistedCount;
458 return;
459 }
460 writeFailing = false;
461 pendingFlushStats = {
462 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
463 count: pendingFlushStats.count + nextIndex - persistedCount,
464 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
465 };
466 persistedCount = nextIndex;
467 }
468 });
469​
470 const flush = flushSemaphore
471 .withPermits(1)(
472 Effect.gen(function* () {
473 const droppedAtStart = droppedCount;
474 yield* flushBuffered;
475 const stats = pendingFlushStats;
476 pendingFlushStats = {
477 logicalWriteBytes: 0,
478 count: 0,
479 durationMs: 0,
480 };
481 if (stats.count > 0 && options.onFlush) {
482 yield* options.onFlush(stats).pipe(Effect.ignore);
483 }
484 if (droppedCount > 0 && !failureReported) {
485 failureReported = true;
486 yield* Effect.logWarning(
487 "Trace writer could not keep up, dropping records until it recovers",
488 {
489 filePath: options.filePath,
490 },
491 );
492 } else if (failureReported && !writeFailing && droppedCount === droppedAtStart) {
493 yield* Effect.logInfo("Trace writes recovered", {
494 filePath: options.filePath,
495 droppedCount,
496 });
497 failureReported = false;
498 droppedCount = 0;
499 }
500 }),
501 )
502 .pipe(
503 // Cancelled OS writes still finish; await completion before rotation or finalizer drain.
504 Effect.uninterruptible,
505 Effect.withTracerEnabled(false),
506 // Drop the ended makeTraceSink parent span so timed-fiber logs cannot accumulate on it.
507 Effect.updateContext(Context.omit(Tracer.ParentSpan)<never>),
508 );
509​
510 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
511 yield* Effect.forkScoped(
512 Queue.take(flushRequests).pipe(
513 Effect.timeoutOption(`${options.batchWindowMs} millis`),
514 Effect.andThen(flush),
515 Effect.forever,
516 ),
517 );
518​
519 return {
520 filePath: options.filePath,
521 push(record) {
522 try {
523 const text = `${JSON.stringify(record)}\n`;
524 const bytes = Buffer.byteLength(text);
525 if (bytes > options.maxBytes) return;
526 if (bufferBytes + bytes > maxBufferBytes) {
527 droppedCount++;
528 return;
529 }
530 buffer.push({ text, bytes });
531 bufferBytes += bytes;
532 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
533 Queue.offerUnsafe(flushRequests, undefined);
534 }
535 } catch {
536 return;
537 }
538 },
539 flush,
540 close: () => flush,
541 } satisfies TraceSink;
542});
543​
544class LocalFileSpan implements Tracer.Span {
545 readonly _tag = "Span";
546 readonly name: string;
547 readonly spanId: string;
548 readonly traceId: string;
549 readonly parent: Option.Option<Tracer.AnySpan>;
550 readonly annotations: Tracer.Span["annotations"];
551 readonly links: Array<Tracer.SpanLink>;
552 readonly sampled: boolean;
553 readonly kind: Tracer.SpanKind;
554​
555 status: Tracer.SpanStatus;
556 attributes: Map<string, unknown>;
557 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
558 private readonly delegate: Tracer.Span;
559 private readonly push: (record: EffectTraceRecord) => void;
560​
561 constructor(
562 options: Parameters<Tracer.Tracer["span"]>[0],
563 delegate: Tracer.Span,
564 push: (record: EffectTraceRecord) => void,
565 ) {
566 this.delegate = delegate;
567 this.push = push;
568 this.name = delegate.name;
569 this.spanId = delegate.spanId;
570 this.traceId = delegate.traceId;
571 this.parent = options.parent;
572 this.annotations = options.annotations;
573 this.links = [...options.links];
574 this.sampled = delegate.sampled;
575 this.kind = delegate.kind;
576 this.status = {
577 _tag: "Started",
578 startTime: options.startTime,
579 };
580 this.attributes = new Map();
581 this.events = [];
582 }
583​
584 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
585 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
586 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
587 this.status = {
588 _tag: "Ended",
589 startTime: this.status.startTime,
590 endTime,
591 exit: traceExit,
592 };
593 this.delegate.end(endTime, traceExit);
594​
595 if (this.sampled) {
596 this.push(spanToTraceRecord(this));
597 }
598 }
599​
600 attribute(key: string, value: unknown): void {
601 this.attributes.set(key, value);
602 this.delegate.attribute(key, value);
603 }
604​
605 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
606 const nextAttributes = attributes ?? {};
607 this.events.push([name, startTime, nextAttributes]);
608 this.delegate.event(name, startTime, nextAttributes);
609 }
610​
611 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
612 this.links.push(...links);
613 this.delegate.addLinks(links);
614 }
616​
617export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
618 options: LocalFileTracerOptions,
619) {
620 const sink =
621 options.sink ??
622 (yield* makeTraceSink({
623 filePath: options.filePath,
624 maxBytes: options.maxBytes,
625 maxFiles: options.maxFiles,
626 batchWindowMs: options.batchWindowMs,
627 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
628 }));
629​
630 const delegate =
631 options.delegate ??
632 Tracer.make({
633 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
634 });
635​
636 return Tracer.make({
637 span(spanOptions) {
638 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
639 },
640 ...(delegate.context ? { context: delegate.context } : {}),
641 });
642});
643​
644const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
645 1: "internal",
646 2: "server",
647 3: "client",
648 4: "producer",
649 5: "consumer",
650};
651​
652export function decodeOtlpTraceRecords(
653 payload: OtlpTracer.TraceData,
654): ReadonlyArray<OtlpTraceRecord> {
655 const records: Array<OtlpTraceRecord> = [];
656​
657 for (const resourceSpan of payload.resourceSpans) {
658 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
659​
660 for (const scopeSpan of resourceSpan.scopeSpans) {
661 for (const span of scopeSpan.spans) {
662 records.push(
663 otlpSpanToTraceRecord({
664 resourceAttributes,
665 scopeAttributes: decodeAttributes(
666 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
667 ? scopeSpan.scope.attributes
668 : [],
669 ),
670 scopeName: scopeSpan.scope.name,
671 scopeVersion:
672 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
673 ? scopeSpan.scope.version
674 : undefined,
675 span,
676 }),
677 );
678 }
679 }
680 }
681​
682 return records;
684​
685function otlpSpanToTraceRecord(input: {
686 readonly resourceAttributes: Readonly<Record<string, unknown>>;
687 readonly scopeAttributes: Readonly<Record<string, unknown>>;
688 readonly scopeName: string | undefined;
689 readonly scopeVersion: string | undefined;
690 readonly span: OtlpSpan;
691}): OtlpTraceRecord {
692 return {
693 type: "otlp-span",
694 name: input.span.name,
695 traceId: input.span.traceId,
696 spanId: input.span.spanId,
697 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
698 sampled: true,
699 kind: normalizeSpanKind(input.span.kind),
700 startTimeUnixNano: input.span.startTimeUnixNano,
701 endTimeUnixNano: input.span.endTimeUnixNano,
702 durationMs:
703 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
704 1_000_000,
705 attributes: decodeAttributes(input.span.attributes),
706 resourceAttributes: input.resourceAttributes,
707 scope: {
708 ...(input.scopeName ? { name: input.scopeName } : {}),
709 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
710 attributes: input.scopeAttributes,
711 },
712 events: decodeEvents(input.span.events),
713 links: decodeLinks(input.span.links),
714 status: decodeStatus(input.span.status),
715 };
717​
718function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
719 const code = String(input.code);
720 const message = input.message;
721​
722 return {
723 code,
724 ...(message ? { message } : {}),
725 };
727​
728function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
729 return input.map((current) => ({
730 name: current.name,
731 timeUnixNano: current.timeUnixNano,
732 attributes: decodeAttributes(current.attributes),
733 }));
735​
736function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
737 return input.flatMap((current) => {
738 const traceId = current.traceId;
739 const spanId = current.spanId;
740 return {
741 traceId,
742 spanId,
743 attributes: decodeAttributes(current.attributes),
744 };
745 });
747​
748function decodeAttributes(
749 input: ReadonlyArray<OtlpResource.KeyValue>,
750): Readonly<Record<string, unknown>> {
751 const entries: Record<string, unknown> = {};
752​
753 for (const attribute of input) {
754 entries[attribute.key] = decodeValue(attribute.value);
755 }
756​
757 return truncateTraceAttributes(compactTraceAttributes(entries));
759​
760function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
761 if (input == null) {
762 return null;
763 }
764 if ("stringValue" in input) {
765 return input.stringValue;
766 }
767 if ("boolValue" in input) {
768 return input.boolValue;
769 }
770 if ("intValue" in input) {
771 return input.intValue;
772 }
773 if ("doubleValue" in input) {
774 return input.doubleValue;
775 }
776 if ("bytesValue" in input) {
777 return input.bytesValue;
778 }
779 if (input.arrayValue) {
780 return input.arrayValue.values.map((entry) => decodeValue(entry));
781 }
782 if (input.kvlistValue) {
783 return decodeAttributes(input.kvlistValue.values);
784 }
785 return null;
787​
788function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
789 return SPAN_KIND_MAP[input] || "internal";
791​
792function parseBigInt(input: string): bigint {
793 try {
794 return BigInt(input);
795 } catch {
796 return 0n;
797 }
799​
800export const OtlpHeadersFromString = Schema.String.pipe(
801 Schema.decodeTo(
802 Schema.Record(Schema.String, Schema.String),
803 SchemaTransformation.transformEffect({
804 decode: (input) => {
805 const headers: Record<string, string> = {};
806 for (const pair of input.split(",")) {
807 if (pair.trim() === "") {
808 continue;
809 }
810 const separator = pair.indexOf("=");
811 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
812 if (key === "") {
813 return Effect.fail(
814 new SchemaIssue.InvalidValue({
815 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
816 }),
817 );
818 }
819 try {
820 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
821 } catch {
822 return Effect.fail(
823 new SchemaIssue.InvalidValue({
824 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
825 }),
826 );
827 }
828 }
829 return Effect.succeed(headers);
830 },
831 encode: (headers) =>
832 Effect.succeed(
833 Object.entries(headers)
834 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
835 .join(","),
836 ),
837 }),
838 ),
839);