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

observability.ts

685 lines19.6 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import type * as Exit from "effect/Exit";
4import * as ExitRuntime from "effect/Exit";
5import * as Option from "effect/Option";
6import * as Tracer from "effect/Tracer";
7import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
8​
9import { RotatingFileSink } from "./logging.ts";
10​
11const FLUSH_BUFFER_THRESHOLD = 256;
12const textEncoder = new TextEncoder();
13​
14export type TraceAttributes = Readonly<Record<string, unknown>>;
15​
16export interface TraceRecordEvent {
17 readonly name: string;
18 readonly timeUnixNano: string;
19 readonly attributes: Readonly<Record<string, unknown>>;
21​
22export interface TraceRecordLink {
23 readonly traceId: string;
24 readonly spanId: string;
25 readonly attributes: Readonly<Record<string, unknown>>;
27​
28interface BaseTraceRecord {
29 readonly name: string;
30 readonly kind: string;
31 readonly traceId: string;
32 readonly spanId: string;
33 readonly parentSpanId?: string;
34 readonly sampled: boolean;
35 readonly startTimeUnixNano: string;
36 readonly endTimeUnixNano: string;
37 readonly durationMs: number;
38 readonly attributes: Readonly<Record<string, unknown>>;
39 readonly events: ReadonlyArray<TraceRecordEvent>;
40 readonly links: ReadonlyArray<TraceRecordLink>;
42​
43export interface EffectTraceRecord extends BaseTraceRecord {
44 readonly type: "effect-span";
45 readonly exit:
46 | {
47 readonly _tag: "Success";
48 }
49 | {
50 readonly _tag: "Interrupted";
51 readonly cause: string;
52 }
53 | {
54 readonly _tag: "Failure";
55 readonly cause: string;
56 };
58​
59export interface OtlpTraceRecord extends BaseTraceRecord {
60 readonly type: "otlp-span";
61 readonly resourceAttributes: Readonly<Record<string, unknown>>;
62 readonly scope: Readonly<{
63 readonly name?: string;
64 readonly version?: string;
65 readonly attributes: Readonly<Record<string, unknown>>;
66 }>;
67 readonly status?:
68 | {
69 readonly code?: string;
70 readonly message?: string;
71 }
72 | undefined;
74​
75export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
76​
77function isStructuralTag(value: unknown): value is string {
78 return (
79 typeof value === "string" &&
80 value.length > 0 &&
81 value.length <= 128 &&
82 /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)
83 );
85​
86export function errorTag(error: unknown): string {
87 try {
88 if (typeof error === "object" && error !== null && "_tag" in error) {
89 return isStructuralTag(error._tag) ? error._tag : "TaggedError";
90 }
91 if (error instanceof Error) {
92 return isStructuralTag(error.name) ? error.name : "Error";
93 }
94 } catch {
95 return "UnknownError";
96 }
97 return typeof error;
99​
100export function causeErrorTag(cause: Cause.Cause<unknown>): string {
101 const failure = Cause.findErrorOption(cause);
102 if (Option.isSome(failure)) {
103 return errorTag(failure.value);
104 }
105 return cause.reasons[0]?._tag ?? "Empty";
107​
108export interface TraceSinkOptions {
109 readonly filePath: string;
110 readonly maxBytes: number;
111 readonly maxFiles: number;
112 readonly batchWindowMs: number;
113 readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
115​
116export interface TraceSinkFlushStats {
117 readonly logicalWriteBytes: number;
118 readonly count: number;
119 readonly durationMs: number;
121​
122export interface TraceSink {
123 readonly filePath: string;
124 push: (record: TraceRecord) => void;
125 flush: Effect.Effect<void>;
126 close: () => Effect.Effect<void>;
128​
129export interface LocalFileTracerOptions extends TraceSinkOptions {
130 readonly delegate?: Tracer.Tracer;
131 readonly sink?: TraceSink;
133​
134type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
135type OtlpSpanEvent = OtlpSpan["events"][number];
136type OtlpSpanLink = OtlpSpan["links"][number];
137type OtlpSpanStatus = OtlpSpan["status"];
138​
139interface SerializableSpan {
140 readonly name: string;
141 readonly traceId: string;
142 readonly spanId: string;
143 readonly parent: Option.Option<Tracer.AnySpan>;
144 readonly status: Tracer.SpanStatus;
145 readonly sampled: boolean;
146 readonly kind: Tracer.SpanKind;
147 readonly attributes: ReadonlyMap<string, unknown>;
148 readonly links: ReadonlyArray<Tracer.SpanLink>;
149 readonly events: ReadonlyArray<
150 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
151 >;
153​
154function isPlainObject(value: unknown): value is Record<string, unknown> {
155 return typeof value === "object" && value !== null && !Array.isArray(value);
157​
158function markSeen(value: object, seen: WeakSet<object>): boolean {
159 if (seen.has(value)) {
160 return true;
161 }
162 seen.add(value);
163 return false;
165​
166function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
167 if (
168 value === null ||
169 value === undefined ||
170 typeof value === "string" ||
171 typeof value === "number" ||
172 typeof value === "boolean"
173 ) {
174 return value ?? null;
175 }
176 if (typeof value === "bigint") {
177 return value.toString();
178 }
179 if (value instanceof Date) {
180 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
181 }
182 if (value instanceof Error) {
183 return {
184 name: value.name,
185 message: value.message,
186 ...(value.stack ? { stack: value.stack } : {}),
187 };
188 }
189 if (Array.isArray(value)) {
190 if (markSeen(value, seen)) {
191 return "[Circular]";
192 }
193 return value.map((entry) => normalizeJsonValue(entry, seen));
194 }
195 if (value instanceof Map) {
196 if (markSeen(value, seen)) {
197 return "[Circular]";
198 }
199 return Object.fromEntries(
200 Array.from(value.entries(), ([key, entryValue]) => [
201 String(key),
202 normalizeJsonValue(entryValue, seen),
203 ]),
204 );
205 }
206 if (value instanceof Set) {
207 if (markSeen(value, seen)) {
208 return "[Circular]";
209 }
210 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
211 }
212 if (!isPlainObject(value)) {
213 return String(value);
214 }
215 if (markSeen(value, seen)) {
216 return "[Circular]";
217 }
218 return Object.fromEntries(
219 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
220 );
222​
223export function compactTraceAttributes(
224 attributes: Readonly<Record<string, unknown>>,
225): TraceAttributes {
226 const entries: Array<[string, unknown]> = [];
227 for (const [key, value] of Object.entries(attributes)) {
228 if (value !== undefined) {
229 entries.push([key, normalizeJsonValue(value)]);
230 }
231 }
232 return Object.fromEntries(entries);
234​
235function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
236 if (ExitRuntime.isSuccess(exit)) {
237 return { _tag: "Success" };
238 }
239 if (Cause.hasInterruptsOnly(exit.cause)) {
240 return {
241 _tag: "Interrupted",
242 cause: Cause.pretty(exit.cause),
243 };
244 }
245 return {
246 _tag: "Failure",
247 cause: Cause.pretty(exit.cause),
248 };
250​
251const TRACE_ATTRIBUTE_MAX_LENGTH = 500;
252const TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;
253const TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = "…[truncated]";
254const ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set(["db.query.text"]);
255​
256// Clamps strings nested inside already-normalized attribute values (arrays and
257// plain objects from normalizeJsonValue, e.g. an Error's `stack`). Returns the
258// input reference when nothing was clamped.
259function truncateNestedValue(value: unknown): unknown {
260 if (typeof value === "string") {
261 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
262 ? value
263 : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
264 }
265 if (Array.isArray(value)) {
266 const truncated = value.map(truncateNestedValue);
267 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
268 }
269 if (isPlainObject(value)) {
270 let truncated: Record<string, unknown> | undefined;
271 for (const [key, entry] of Object.entries(value)) {
272 const next = truncateNestedValue(entry);
273 if (next === entry) continue;
274 truncated ??= { ...value };
275 truncated[key] = next;
276 }
277 return truncated ?? value;
278 }
279 return value;
281​
282/**
283 * Clamps oversized attribute values on the serialized trace record so the file
284 * sink stays small, including strings nested inside arrays and objects (e.g.
285 * error stacks). Returns a new record when anything was clamped; never
286 * mutates the input (the live span's attributes are shared with other tracers).
287 */
288export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
289 let truncated: Record<string, unknown> | undefined;
290 for (const [key, value] of Object.entries(attributes)) {
291 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
292 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
293 truncated ??= { ...attributes };
294 truncated[key] =
295 `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
296 continue;
297 }
298 const next = truncateNestedValue(value);
299 if (next === value) continue;
300 truncated ??= { ...attributes };
301 truncated[key] = next;
302 }
303 return truncated ?? attributes;
305​
306export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
307 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
308 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
309​
310 return {
311 type: "effect-span",
312 name: span.name,
313 traceId: span.traceId,
314 spanId: span.spanId,
315 ...(parentSpanId ? { parentSpanId } : {}),
316 sampled: span.sampled,
317 kind: span.kind,
318 startTimeUnixNano: String(status.startTime),
319 endTimeUnixNano: String(status.endTime),
320 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
321 attributes: truncateTraceAttributes(
322 compactTraceAttributes(Object.fromEntries(span.attributes)),
323 ),
324 events: span.events.map(([name, startTime, attributes]) => ({
325 name,
326 timeUnixNano: String(startTime),
327 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
328 })),
329 links: span.links.map((link) => ({
330 traceId: link.span.traceId,
331 spanId: link.span.spanId,
332 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
333 })),
334 exit: formatTraceExit(status.exit),
335 };
337​
338export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
339 const sink = new RotatingFileSink({
340 filePath: options.filePath,
341 maxBytes: options.maxBytes,
342 maxFiles: options.maxFiles,
343 throwOnError: true,
344 });
345​
346 let buffer: Array<string> = [];
347 let pendingFlushStats: TraceSinkFlushStats = {
348 logicalWriteBytes: 0,
349 count: 0,
350 durationMs: 0,
351 };
352​
353 const flushUnsafe = () => {
354 if (buffer.length === 0) {
355 return;
356 }
357​
358 const records = buffer;
359 buffer = [];
360 let persistedCount = 0;
361​
362 while (persistedCount < records.length) {
363 const firstRecordBytes = textEncoder.encode(records[persistedCount]).byteLength;
364 if (firstRecordBytes > options.maxBytes) {
365 persistedCount += 1;
366 continue;
367 }
368​
369 let nextIndex = persistedCount + 1;
370 let chunkBytes = firstRecordBytes;
371 while (nextIndex < records.length) {
372 const nextRecordBytes = textEncoder.encode(records[nextIndex]).byteLength;
373 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
374 chunkBytes += nextRecordBytes;
375 nextIndex += 1;
376 }
377​
378 const chunk = records.slice(persistedCount, nextIndex).join("");
379 const startedAt = performance.now();
380 try {
381 sink.write(chunk);
382 } catch {
383 buffer.unshift(...records.slice(persistedCount));
384 return;
385 }
386 pendingFlushStats = {
387 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
388 count: pendingFlushStats.count + nextIndex - persistedCount,
389 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
390 };
391 persistedCount = nextIndex;
392 }
393 };
394​
395 const flush = Effect.sync(() => {
396 flushUnsafe();
397 const stats = pendingFlushStats;
398 pendingFlushStats = {
399 logicalWriteBytes: 0,
400 count: 0,
401 durationMs: 0,
402 };
403 return stats;
404 }).pipe(
405 Effect.flatMap((stats) =>
406 stats.count > 0 && options.onFlush ? options.onFlush(stats).pipe(Effect.ignore) : Effect.void,
407 ),
408 Effect.withTracerEnabled(false),
409 );
410​
411 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
412 yield* Effect.forkScoped(
413 Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
414 );
415​
416 return {
417 filePath: options.filePath,
418 push(record) {
419 try {
420 buffer.push(`${JSON.stringify(record)}\n`);
421 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
422 flushUnsafe();
423 }
424 } catch {
425 return;
426 }
427 },
428 flush,
429 close: () => flush,
430 } satisfies TraceSink;
431});
432​
433class LocalFileSpan implements Tracer.Span {
434 readonly _tag = "Span";
435 readonly name: string;
436 readonly spanId: string;
437 readonly traceId: string;
438 readonly parent: Option.Option<Tracer.AnySpan>;
439 readonly annotations: Tracer.Span["annotations"];
440 readonly links: Array<Tracer.SpanLink>;
441 readonly sampled: boolean;
442 readonly kind: Tracer.SpanKind;
443​
444 status: Tracer.SpanStatus;
445 attributes: Map<string, unknown>;
446 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
447 private readonly delegate: Tracer.Span;
448 private readonly push: (record: EffectTraceRecord) => void;
449​
450 constructor(
451 options: Parameters<Tracer.Tracer["span"]>[0],
452 delegate: Tracer.Span,
453 push: (record: EffectTraceRecord) => void,
454 ) {
455 this.delegate = delegate;
456 this.push = push;
457 this.name = delegate.name;
458 this.spanId = delegate.spanId;
459 this.traceId = delegate.traceId;
460 this.parent = options.parent;
461 this.annotations = options.annotations;
462 this.links = [...options.links];
463 this.sampled = delegate.sampled;
464 this.kind = delegate.kind;
465 this.status = {
466 _tag: "Started",
467 startTime: options.startTime,
468 };
469 this.attributes = new Map();
470 this.events = [];
471 }
472​
473 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
474 this.status = {
475 _tag: "Ended",
476 startTime: this.status.startTime,
477 endTime,
478 exit,
479 };
480 this.delegate.end(endTime, exit);
481​
482 if (this.sampled) {
483 this.push(spanToTraceRecord(this));
484 }
485 }
486​
487 attribute(key: string, value: unknown): void {
488 this.attributes.set(key, value);
489 this.delegate.attribute(key, value);
490 }
491​
492 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
493 const nextAttributes = attributes ?? {};
494 this.events.push([name, startTime, nextAttributes]);
495 this.delegate.event(name, startTime, nextAttributes);
496 }
497​
498 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
499 this.links.push(...links);
500 this.delegate.addLinks(links);
501 }
503​
504export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
505 options: LocalFileTracerOptions,
506) {
507 const sink =
508 options.sink ??
509 (yield* makeTraceSink({
510 filePath: options.filePath,
511 maxBytes: options.maxBytes,
512 maxFiles: options.maxFiles,
513 batchWindowMs: options.batchWindowMs,
514 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
515 }));
516​
517 const delegate =
518 options.delegate ??
519 Tracer.make({
520 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
521 });
522​
523 return Tracer.make({
524 span(spanOptions) {
525 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
526 },
527 ...(delegate.context ? { context: delegate.context } : {}),
528 });
529});
530​
531const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
532 1: "internal",
533 2: "server",
534 3: "client",
535 4: "producer",
536 5: "consumer",
537};
538​
539export function decodeOtlpTraceRecords(
540 payload: OtlpTracer.TraceData,
541): ReadonlyArray<OtlpTraceRecord> {
542 const records: Array<OtlpTraceRecord> = [];
543​
544 for (const resourceSpan of payload.resourceSpans) {
545 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
546​
547 for (const scopeSpan of resourceSpan.scopeSpans) {
548 for (const span of scopeSpan.spans) {
549 records.push(
550 otlpSpanToTraceRecord({
551 resourceAttributes,
552 scopeAttributes: decodeAttributes(
553 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
554 ? scopeSpan.scope.attributes
555 : [],
556 ),
557 scopeName: scopeSpan.scope.name,
558 scopeVersion:
559 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
560 ? scopeSpan.scope.version
561 : undefined,
562 span,
563 }),
564 );
565 }
566 }
567 }
568​
569 return records;
571​
572function otlpSpanToTraceRecord(input: {
573 readonly resourceAttributes: Readonly<Record<string, unknown>>;
574 readonly scopeAttributes: Readonly<Record<string, unknown>>;
575 readonly scopeName: string | undefined;
576 readonly scopeVersion: string | undefined;
577 readonly span: OtlpSpan;
578}): OtlpTraceRecord {
579 return {
580 type: "otlp-span",
581 name: input.span.name,
582 traceId: input.span.traceId,
583 spanId: input.span.spanId,
584 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
585 sampled: true,
586 kind: normalizeSpanKind(input.span.kind),
587 startTimeUnixNano: input.span.startTimeUnixNano,
588 endTimeUnixNano: input.span.endTimeUnixNano,
589 durationMs:
590 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
591 1_000_000,
592 attributes: decodeAttributes(input.span.attributes),
593 resourceAttributes: input.resourceAttributes,
594 scope: {
595 ...(input.scopeName ? { name: input.scopeName } : {}),
596 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
597 attributes: input.scopeAttributes,
598 },
599 events: decodeEvents(input.span.events),
600 links: decodeLinks(input.span.links),
601 status: decodeStatus(input.span.status),
602 };
604​
605function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
606 const code = String(input.code);
607 const message = input.message;
608​
609 return {
610 code,
611 ...(message ? { message } : {}),
612 };
614​
615function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
616 return input.map((current) => ({
617 name: current.name,
618 timeUnixNano: current.timeUnixNano,
619 attributes: decodeAttributes(current.attributes),
620 }));
622​
623function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
624 return input.flatMap((current) => {
625 const traceId = current.traceId;
626 const spanId = current.spanId;
627 return {
628 traceId,
629 spanId,
630 attributes: decodeAttributes(current.attributes),
631 };
632 });
634​
635function decodeAttributes(
636 input: ReadonlyArray<OtlpResource.KeyValue>,
637): Readonly<Record<string, unknown>> {
638 const entries: Record<string, unknown> = {};
639​
640 for (const attribute of input) {
641 entries[attribute.key] = decodeValue(attribute.value);
642 }
643​
644 return compactTraceAttributes(entries);
646​
647function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
648 if (input == null) {
649 return null;
650 }
651 if ("stringValue" in input) {
652 return input.stringValue;
653 }
654 if ("boolValue" in input) {
655 return input.boolValue;
656 }
657 if ("intValue" in input) {
658 return input.intValue;
659 }
660 if ("doubleValue" in input) {
661 return input.doubleValue;
662 }
663 if ("bytesValue" in input) {
664 return input.bytesValue;
665 }
666 if (input.arrayValue) {
667 return input.arrayValue.values.map((entry) => decodeValue(entry));
668 }
669 if (input.kvlistValue) {
670 return decodeAttributes(input.kvlistValue.values);
671 }
672 return null;
674​
675function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
676 return SPAN_KIND_MAP[input] || "internal";
678​
679function parseBigInt(input: string): bigint {
680 try {
681 return BigInt(input);
682 } catch {
683 return 0n;
684 }