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

observability.ts

929 lines29.1 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 truncateTraceString(value: string, length: number): string {
340 const last = value.charCodeAt(length - 1);
341 const end = length - (last >= 0xd800 && last <= 0xdbff ? 1 : 0);
342 return `${value.slice(0, end)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
344​
345function truncateNestedValue(value: unknown): unknown {
346 if (typeof value === "string") {
347 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
348 ? value
349 : truncateTraceString(value, TRACE_ATTRIBUTE_MAX_LENGTH);
350 }
351 if (Array.isArray(value)) {
352 const truncated = value.map(truncateNestedValue);
353 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
354 }
355 if (isPlainObject(value)) {
356 let truncated: Record<string, unknown> | undefined;
357 for (const [key, entry] of Object.entries(value)) {
358 const next = truncateNestedValue(entry);
359 if (next === entry) continue;
360 truncated ??= { ...value };
361 truncated[key] = next;
362 }
363 return truncated ?? value;
364 }
365 return value;
367​
368/** Clones only when clamping; never mutates attributes shared with other tracers. */
369export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
370 let truncated: Record<string, unknown> | undefined;
371 for (const [key, value] of Object.entries(attributes)) {
372 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
373 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
374 truncated ??= { ...attributes };
375 truncated[key] = truncateTraceString(value, TRACE_ATTRIBUTE_TRUNCATED_LENGTH);
376 continue;
377 }
378 const next = truncateNestedValue(value);
379 if (next === value) continue;
380 truncated ??= { ...attributes };
381 truncated[key] = next;
382 }
383 return truncated ?? attributes;
385​
386function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
387 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
388 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
389​
390 return {
391 type: "effect-span",
392 name: span.name,
393 traceId: span.traceId,
394 spanId: span.spanId,
395 ...(parentSpanId ? { parentSpanId } : {}),
396 sampled: span.sampled,
397 kind: span.kind,
398 startTimeUnixNano: String(status.startTime),
399 endTimeUnixNano: String(status.endTime),
400 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
401 attributes: truncateTraceAttributes(
402 compactTraceAttributes(Object.fromEntries(span.attributes)),
403 ),
404 events: span.events.map(([name, startTime, attributes]) => ({
405 name,
406 timeUnixNano: String(startTime),
407 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
408 })),
409 links: span.links.map((link) => ({
410 traceId: link.span.traceId,
411 spanId: link.span.spanId,
412 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
413 })),
414 exit: formatTraceExit(status.exit),
415 };
417​
418// WebSocket tickets and their DPoP proofs ride in URL queries and stay valid after the request.
419const URL_CREDENTIAL_PARAMS = /(^|[?&"\s])(wsTicket|dpop)=[^&#"\\\s]*/g;
420​
421const redactUrlCredentials = (text: string) =>
422 text.replace(URL_CREDENTIAL_PARAMS, "$1$2=<redacted>");
423​
424export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
425 const sink = yield* makeAsyncRotatingFileSink({
426 filePath: options.filePath,
427 maxBytes: options.maxBytes,
428 maxFiles: options.maxFiles,
429 }).pipe(Effect.orDie);
430​
431 let buffer: Array<{ readonly text: string; readonly bytes: number }> = [];
432 let bufferBytes = 0;
433 const maxBufferBytes = Math.max(options.maxBytes, 4 * 1024 * 1024);
434 const flushRequests = yield* Queue.sliding<void>(1);
435 const flushSemaphore = yield* Semaphore.make(1);
436 let writeFailing = false;
437 let droppedCount = 0;
438 let failureReported = false;
439 let pendingFlushStats: TraceSinkFlushStats = {
440 logicalWriteBytes: 0,
441 count: 0,
442 durationMs: 0,
443 };
444​
445 const flushBuffered = Effect.gen(function* () {
446 if (buffer.length === 0) {
447 return;
448 }
449​
450 const records = buffer;
451 buffer = [];
452 bufferBytes = 0;
453 let persistedCount = 0;
454​
455 while (persistedCount < records.length) {
456 const firstRecordBytes = records[persistedCount]!.bytes;
457 let nextIndex = persistedCount + 1;
458 let chunkBytes = firstRecordBytes;
459 while (nextIndex < records.length) {
460 const nextRecordBytes = records[nextIndex]!.bytes;
461 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
462 chunkBytes += nextRecordBytes;
463 nextIndex += 1;
464 }
465​
466 const chunk = records
467 .slice(persistedCount, nextIndex)
468 .map((record) => record.text)
469 .join("");
470 const startedAt = performance.now();
471 const written = yield* sink.write(chunk).pipe(Effect.result);
472 if (Result.isFailure(written)) {
473 // Drop the batch after disk failure to avoid an ever-growing retry backlog.
474 writeFailing = true;
475 droppedCount += records.length - persistedCount;
476 return;
477 }
478 writeFailing = false;
479 pendingFlushStats = {
480 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
481 count: pendingFlushStats.count + nextIndex - persistedCount,
482 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
483 };
484 persistedCount = nextIndex;
485 }
486 });
487​
488 const flush = flushSemaphore
489 .withPermits(1)(
490 Effect.gen(function* () {
491 const droppedAtStart = droppedCount;
492 yield* flushBuffered;
493 const stats = pendingFlushStats;
494 pendingFlushStats = {
495 logicalWriteBytes: 0,
496 count: 0,
497 durationMs: 0,
498 };
499 if (stats.count > 0 && options.onFlush) {
500 yield* options.onFlush(stats).pipe(Effect.ignore);
501 }
502 if (droppedCount > 0 && !failureReported) {
503 failureReported = true;
504 yield* Effect.logWarning(
505 "Trace writer could not keep up, dropping records until it recovers",
506 {
507 filePath: options.filePath,
508 },
509 );
510 } else if (failureReported && !writeFailing && droppedCount === droppedAtStart) {
511 yield* Effect.logInfo("Trace writes recovered", {
512 filePath: options.filePath,
513 droppedCount,
514 });
515 failureReported = false;
516 droppedCount = 0;
517 }
518 }),
519 )
520 .pipe(
521 // Cancelled OS writes still finish; await completion before rotation or finalizer drain.
522 Effect.uninterruptible,
523 Effect.withTracerEnabled(false),
524 // Drop the ended makeTraceSink parent span so timed-fiber logs cannot accumulate on it.
525 Effect.updateContext(Context.omit(Tracer.ParentSpan)<never>),
526 );
527​
528 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
529 yield* Effect.forkScoped(
530 Queue.take(flushRequests).pipe(
531 Effect.timeoutOption(`${options.batchWindowMs} millis`),
532 Effect.andThen(flush),
533 Effect.forever,
534 ),
535 );
536​
537 return {
538 filePath: options.filePath,
539 push(record) {
540 try {
541 const text = `${redactUrlCredentials(JSON.stringify(record))}\n`;
542 const bytes = Buffer.byteLength(text);
543 if (bytes > options.maxBytes) return;
544 if (bufferBytes + bytes > maxBufferBytes) {
545 droppedCount++;
546 return;
547 }
548 buffer.push({ text, bytes });
549 bufferBytes += bytes;
550 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
551 Queue.offerUnsafe(flushRequests, undefined);
552 }
553 } catch {
554 return;
555 }
556 },
557 flush,
558 flushSync() {
559 if (buffer.length === 0) return;
560 const text = buffer.map((record) => record.text).join("");
561 buffer = [];
562 bufferBytes = 0;
563 try {
564 NodeFS.appendFileSync(options.filePath, text);
565 } catch {
566 return;
567 }
568 },
569 close: () => flush,
570 } satisfies TraceSink;
571});
572​
573// Effect's HTTP errors, including failed upgrades, put the request URL in their message.
574export function redactCauseCredentials(cause: Cause.Cause<unknown>): Cause.Cause<unknown> {
575 if (cause.reasons.length === 0 || Cause.hasInterruptsOnly(cause)) {
576 return cause;
577 }
578 const pretty = Cause.pretty(cause);
579 const redacted = redactUrlCredentials(pretty);
580 return redacted === pretty ? cause : Cause.die(new Error(redacted));
582​
583function redactExitCredentials(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {
584 if (ExitRuntime.isSuccess(exit)) {
585 return exit;
586 }
587 const cause = redactCauseCredentials(exit.cause);
588 return cause === exit.cause ? exit : ExitRuntime.failCause(cause);
590​
591const ROUTINE_ATTRIBUTE = "t3.trace.routine";
592/** Marks high-volume bookkeeping spans the local trace file may sample. SQLite spans count without it. */
593export const routineSpan = { [ROUTINE_ATTRIBUTE]: true } as const;
594​
595/** Runs real work that a routine context (such as the workflow engine) calls without the routine marker. */
596export const withoutRoutineSpans = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
597 Effect.updateService(effect, References.TracerSpanAnnotations, (annotations) => {
598 const { [ROUTINE_ATTRIBUTE]: _, ...rest } = annotations;
599 return rest;
600 });
601​
602const SLOW_ROUTINE_SPAN_NANOS = 10_000_000n;
603​
604class LocalFileSpan implements Tracer.Span {
605 readonly _tag = "Span";
606 readonly name: string;
607 readonly spanId: string;
608 readonly traceId: string;
609 readonly parent: Option.Option<Tracer.AnySpan>;
610 readonly annotations: Tracer.Span["annotations"];
611 readonly links: Array<Tracer.SpanLink>;
612 readonly sampled: boolean;
613 readonly kind: Tracer.SpanKind;
614​
615 status: Tracer.SpanStatus;
616 attributes: Map<string, unknown>;
617 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
618 private readonly delegate: Tracer.Span;
619 private readonly sampleRoutineSpans: boolean;
620 private readonly push: (record: EffectTraceRecord) => void;
621​
622 constructor(
623 options: Parameters<Tracer.Tracer["span"]>[0],
624 delegate: Tracer.Span,
625 push: (record: EffectTraceRecord) => void,
626 sampleRoutineSpans: boolean,
627 ) {
628 this.delegate = delegate;
629 this.sampleRoutineSpans = sampleRoutineSpans;
630 this.push = push;
631 this.name = delegate.name;
632 this.spanId = delegate.spanId;
633 this.traceId = delegate.traceId;
634 this.parent = options.parent;
635 this.annotations = options.annotations;
636 this.links = [...options.links];
637 this.sampled = delegate.sampled;
638 this.kind = delegate.kind;
639 this.status = {
640 _tag: "Started",
641 startTime: options.startTime,
642 };
643 this.attributes = new Map();
644 this.events = [];
645 }
646​
647 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
648 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
649 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
650 this.status = {
651 _tag: "Ended",
652 startTime: this.status.startTime,
653 endTime,
654 exit: traceExit,
655 };
656 this.delegate.end(endTime, redactExitCredentials(traceExit));
657​
658 if (this.sampled && !(this.sampleRoutineSpans && this.isDroppableRoutine(endTime, traceExit))) {
659 this.push(spanToTraceRecord(this));
660 }
661 }
662​
663 // Keyed per span: background fibers share the boot trace, and recurring ticks reuse one parent span.
664 private isDroppableRoutine(endTime: bigint, exit: Exit.Exit<unknown, unknown>): boolean {
665 return (
666 (this.attributes.get("db.system.name") === "sqlite" ||
667 this.attributes.get(ROUTINE_ATTRIBUTE) === true) &&
668 ExitRuntime.isSuccess(exit) &&
669 this.events.length === 0 &&
670 endTime - this.status.startTime < SLOW_ROUTINE_SPAN_NANOS &&
671 !this.spanId.endsWith("00")
672 );
673 }
674​
675 attribute(key: string, value: unknown): void {
676 const recorded =
677 (key === "url.full" || key === "url.query") && typeof value === "string"
678 ? redactUrlCredentials(value)
679 : value;
680 this.attributes.set(key, recorded);
681 this.delegate.attribute(key, recorded);
682 }
683​
684 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
685 const cause = attributes?.["effect.cause"];
686 const nextAttributes =
687 typeof cause === "string"
688 ? { ...attributes, "effect.cause": redactUrlCredentials(cause) }
689 : (attributes ?? {});
690 this.events.push([name, startTime, nextAttributes]);
691 this.delegate.event(name, startTime, nextAttributes);
692 }
693​
694 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
695 this.links.push(...links);
696 this.delegate.addLinks(links);
697 }
699​
700export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
701 options: LocalFileTracerOptions,
702) {
703 const sink =
704 options.sink ??
705 (yield* makeTraceSink({
706 filePath: options.filePath,
707 maxBytes: options.maxBytes,
708 maxFiles: options.maxFiles,
709 batchWindowMs: options.batchWindowMs,
710 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
711 }));
712​
713 const delegate =
714 options.delegate ??
715 Tracer.make({
716 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
717 });
718​
719 return Tracer.make({
720 span(spanOptions) {
721 return new LocalFileSpan(
722 spanOptions,
723 delegate.span(spanOptions),
724 sink.push,
725 options.sampleRoutineSpans === true,
726 );
727 },
728 ...(delegate.context ? { context: delegate.context } : {}),
729 });
730});
731​
732const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
733 1: "internal",
734 2: "server",
735 3: "client",
736 4: "producer",
737 5: "consumer",
738};
739​
740export function decodeOtlpTraceRecords(
741 payload: OtlpTracer.TraceData,
742): ReadonlyArray<OtlpTraceRecord> {
743 const records: Array<OtlpTraceRecord> = [];
744​
745 // OTLP/JSON follows protobuf JSON, which omits unset and empty fields, so a
746 // valid batch can leave out any field read here.
747 for (const resourceSpan of payload.resourceSpans ?? []) {
748 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes);
749​
750 for (const scopeSpan of resourceSpan.scopeSpans ?? []) {
751 const scope: Partial<OtlpScope> = scopeSpan.scope ?? {};
752 for (const span of scopeSpan.spans ?? []) {
753 records.push(
754 otlpSpanToTraceRecord({
755 resourceAttributes,
756 scopeAttributes: decodeAttributes(
757 "attributes" in scope && Array.isArray(scope.attributes) ? scope.attributes : [],
758 ),
759 scopeName: scope.name,
760 scopeVersion: typeof scope.version === "string" ? scope.version : undefined,
761 span,
762 }),
763 );
764 }
765 }
766 }
767​
768 return records;
770​
771function otlpSpanToTraceRecord(input: {
772 readonly resourceAttributes: Readonly<Record<string, unknown>>;
773 readonly scopeAttributes: Readonly<Record<string, unknown>>;
774 readonly scopeName: string | undefined;
775 readonly scopeVersion: string | undefined;
776 readonly span: OtlpSpan;
777}): OtlpTraceRecord {
778 return {
779 type: "otlp-span",
780 name: input.span.name,
781 traceId: input.span.traceId,
782 spanId: input.span.spanId,
783 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
784 sampled: true,
785 kind: normalizeSpanKind(input.span.kind),
786 startTimeUnixNano: input.span.startTimeUnixNano,
787 endTimeUnixNano: input.span.endTimeUnixNano,
788 durationMs:
789 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
790 1_000_000,
791 attributes: decodeAttributes(input.span.attributes),
792 resourceAttributes: input.resourceAttributes,
793 scope: {
794 ...(input.scopeName ? { name: input.scopeName } : {}),
795 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
796 attributes: input.scopeAttributes,
797 },
798 events: decodeEvents(input.span.events),
799 links: decodeLinks(input.span.links),
800 status: decodeStatus(input.span.status),
801 };
803​
804function decodeStatus(input: OtlpSpanStatus | undefined): OtlpTraceRecord["status"] {
805 const code = String(input?.code ?? 0);
806 const message = input?.message;
807​
808 return {
809 code,
810 ...(message ? { message } : {}),
811 };
813​
814function decodeEvents(
815 input: ReadonlyArray<OtlpSpanEvent> | undefined,
816): ReadonlyArray<TraceRecordEvent> {
817 return (input ?? []).map((current) => ({
818 name: current.name,
819 timeUnixNano: current.timeUnixNano,
820 attributes: decodeAttributes(current.attributes),
821 }));
823​
824function decodeLinks(
825 input: ReadonlyArray<OtlpSpanLink> | undefined,
826): ReadonlyArray<TraceRecordLink> {
827 return (input ?? []).flatMap((current) => {
828 const traceId = current.traceId;
829 const spanId = current.spanId;
830 return {
831 traceId,
832 spanId,
833 attributes: decodeAttributes(current.attributes),
834 };
835 });
837​
838function decodeAttributes(
839 input: ReadonlyArray<OtlpResource.KeyValue> | undefined,
840): Readonly<Record<string, unknown>> {
841 const entries: Record<string, unknown> = {};
842​
843 for (const attribute of input ?? []) {
844 entries[attribute.key] = decodeValue(attribute.value);
845 }
846​
847 return truncateTraceAttributes(compactTraceAttributes(entries));
849​
850function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
851 if (input == null) {
852 return null;
853 }
854 if ("stringValue" in input) {
855 return input.stringValue;
856 }
857 if ("boolValue" in input) {
858 return input.boolValue;
859 }
860 if ("intValue" in input) {
861 return input.intValue;
862 }
863 if ("doubleValue" in input) {
864 return input.doubleValue;
865 }
866 if ("bytesValue" in input) {
867 return input.bytesValue;
868 }
869 if (input.arrayValue) {
870 return (input.arrayValue.values ?? []).map((entry) => decodeValue(entry));
871 }
872 if (input.kvlistValue) {
873 return decodeAttributes(input.kvlistValue.values);
874 }
875 return null;
877​
878function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
879 return SPAN_KIND_MAP[input] || "internal";
881​
882function parseBigInt(input: string): bigint {
883 try {
884 return BigInt(input);
885 } catch {
886 return 0n;
887 }
889​
890export const OtlpHeadersFromString = Schema.String.pipe(
891 Schema.decodeTo(
892 Schema.Record(Schema.String, Schema.String),
893 SchemaTransformation.transformEffect({
894 decode: (input) => {
895 const headers: Record<string, string> = {};
896 for (const pair of input.split(",")) {
897 if (pair.trim() === "") {
898 continue;
899 }
900 const separator = pair.indexOf("=");
901 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
902 if (key === "") {
903 return Effect.fail(
904 new SchemaIssue.InvalidValue({
905 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
906 }),
907 );
908 }
909 try {
910 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
911 } catch {
912 return Effect.fail(
913 new SchemaIssue.InvalidValue({
914 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
915 }),
916 );
917 }
918 }
919 return Effect.succeed(headers);
920 },
921 encode: (headers) =>
922 Effect.succeed(
923 Object.entries(headers)
924 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
925 .join(","),
926 ),
927 }),
928 ),
929);