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

observability.ts

924 lines28.9 KB

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