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

observability.ts

557 lines15.2 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 = 32;
12​
13export type TraceAttributes = Readonly<Record<string, unknown>>;
14​
15export interface TraceRecordEvent {
16 readonly name: string;
17 readonly timeUnixNano: string;
18 readonly attributes: Readonly<Record<string, unknown>>;
20​
21export interface TraceRecordLink {
22 readonly traceId: string;
23 readonly spanId: string;
24 readonly attributes: Readonly<Record<string, unknown>>;
26​
27interface BaseTraceRecord {
28 readonly name: string;
29 readonly kind: string;
30 readonly traceId: string;
31 readonly spanId: string;
32 readonly parentSpanId?: string;
33 readonly sampled: boolean;
34 readonly startTimeUnixNano: string;
35 readonly endTimeUnixNano: string;
36 readonly durationMs: number;
37 readonly attributes: Readonly<Record<string, unknown>>;
38 readonly events: ReadonlyArray<TraceRecordEvent>;
39 readonly links: ReadonlyArray<TraceRecordLink>;
41​
42export interface EffectTraceRecord extends BaseTraceRecord {
43 readonly type: "effect-span";
44 readonly exit:
45 | {
46 readonly _tag: "Success";
47 }
48 | {
49 readonly _tag: "Interrupted";
50 readonly cause: string;
51 }
52 | {
53 readonly _tag: "Failure";
54 readonly cause: string;
55 };
57​
58export interface OtlpTraceRecord extends BaseTraceRecord {
59 readonly type: "otlp-span";
60 readonly resourceAttributes: Readonly<Record<string, unknown>>;
61 readonly scope: Readonly<{
62 readonly name?: string;
63 readonly version?: string;
64 readonly attributes: Readonly<Record<string, unknown>>;
65 }>;
66 readonly status?:
67 | {
68 readonly code?: string;
69 readonly message?: string;
70 }
71 | undefined;
73​
74export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
75​
76function taggedErrorName(error: unknown): string {
77 return typeof error === "object" && error !== null && "_tag" in error
78 ? String(error._tag)
79 : error instanceof Error
80 ? error.name
81 : typeof error;
83​
84export function causeErrorTag(cause: Cause.Cause<unknown>): string {
85 const failure = Cause.findErrorOption(cause);
86 if (Option.isSome(failure)) {
87 return taggedErrorName(failure.value);
88 }
89 return cause.reasons[0]?._tag ?? "Empty";
91​
92export interface TraceSinkOptions {
93 readonly filePath: string;
94 readonly maxBytes: number;
95 readonly maxFiles: number;
96 readonly batchWindowMs: number;
98​
99export interface TraceSink {
100 readonly filePath: string;
101 push: (record: TraceRecord) => void;
102 flush: Effect.Effect<void>;
103 close: () => Effect.Effect<void>;
105​
106export interface LocalFileTracerOptions extends TraceSinkOptions {
107 readonly delegate?: Tracer.Tracer;
108 readonly sink?: TraceSink;
110​
111type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
112type OtlpSpanEvent = OtlpSpan["events"][number];
113type OtlpSpanLink = OtlpSpan["links"][number];
114type OtlpSpanStatus = OtlpSpan["status"];
115​
116interface SerializableSpan {
117 readonly name: string;
118 readonly traceId: string;
119 readonly spanId: string;
120 readonly parent: Option.Option<Tracer.AnySpan>;
121 readonly status: Tracer.SpanStatus;
122 readonly sampled: boolean;
123 readonly kind: Tracer.SpanKind;
124 readonly attributes: ReadonlyMap<string, unknown>;
125 readonly links: ReadonlyArray<Tracer.SpanLink>;
126 readonly events: ReadonlyArray<
127 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
128 >;
130​
131function isPlainObject(value: unknown): value is Record<string, unknown> {
132 return typeof value === "object" && value !== null && !Array.isArray(value);
134​
135function markSeen(value: object, seen: WeakSet<object>): boolean {
136 if (seen.has(value)) {
137 return true;
138 }
139 seen.add(value);
140 return false;
142​
143function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
144 if (
145 value === null ||
146 value === undefined ||
147 typeof value === "string" ||
148 typeof value === "number" ||
149 typeof value === "boolean"
150 ) {
151 return value ?? null;
152 }
153 if (typeof value === "bigint") {
154 return value.toString();
155 }
156 if (value instanceof Date) {
157 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
158 }
159 if (value instanceof Error) {
160 return {
161 name: value.name,
162 message: value.message,
163 ...(value.stack ? { stack: value.stack } : {}),
164 };
165 }
166 if (Array.isArray(value)) {
167 if (markSeen(value, seen)) {
168 return "[Circular]";
169 }
170 return value.map((entry) => normalizeJsonValue(entry, seen));
171 }
172 if (value instanceof Map) {
173 if (markSeen(value, seen)) {
174 return "[Circular]";
175 }
176 return Object.fromEntries(
177 Array.from(value.entries(), ([key, entryValue]) => [
178 String(key),
179 normalizeJsonValue(entryValue, seen),
180 ]),
181 );
182 }
183 if (value instanceof Set) {
184 if (markSeen(value, seen)) {
185 return "[Circular]";
186 }
187 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
188 }
189 if (!isPlainObject(value)) {
190 return String(value);
191 }
192 if (markSeen(value, seen)) {
193 return "[Circular]";
194 }
195 return Object.fromEntries(
196 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
197 );
199​
200export function compactTraceAttributes(
201 attributes: Readonly<Record<string, unknown>>,
202): TraceAttributes {
203 const entries: Array<[string, unknown]> = [];
204 for (const [key, value] of Object.entries(attributes)) {
205 if (value !== undefined) {
206 entries.push([key, normalizeJsonValue(value)]);
207 }
208 }
209 return Object.fromEntries(entries);
211​
212function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
213 if (ExitRuntime.isSuccess(exit)) {
214 return { _tag: "Success" };
215 }
216 if (Cause.hasInterruptsOnly(exit.cause)) {
217 return {
218 _tag: "Interrupted",
219 cause: Cause.pretty(exit.cause),
220 };
221 }
222 return {
223 _tag: "Failure",
224 cause: Cause.pretty(exit.cause),
225 };
227​
228export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
229 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
230 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
231​
232 return {
233 type: "effect-span",
234 name: span.name,
235 traceId: span.traceId,
236 spanId: span.spanId,
237 ...(parentSpanId ? { parentSpanId } : {}),
238 sampled: span.sampled,
239 kind: span.kind,
240 startTimeUnixNano: String(status.startTime),
241 endTimeUnixNano: String(status.endTime),
242 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
243 attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
244 events: span.events.map(([name, startTime, attributes]) => ({
245 name,
246 timeUnixNano: String(startTime),
247 attributes: compactTraceAttributes(attributes),
248 })),
249 links: span.links.map((link) => ({
250 traceId: link.span.traceId,
251 spanId: link.span.spanId,
252 attributes: compactTraceAttributes(link.attributes),
253 })),
254 exit: formatTraceExit(status.exit),
255 };
257​
258export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
259 const sink = new RotatingFileSink({
260 filePath: options.filePath,
261 maxBytes: options.maxBytes,
262 maxFiles: options.maxFiles,
263 });
264​
265 let buffer: Array<string> = [];
266​
267 const flushUnsafe = () => {
268 if (buffer.length === 0) {
269 return;
270 }
271​
272 const chunk = buffer.join("");
273 buffer = [];
274​
275 try {
276 sink.write(chunk);
277 } catch {
278 buffer.unshift(chunk);
279 }
280 };
281​
282 const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
283​
284 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
285 yield* Effect.forkScoped(
286 Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
287 );
288​
289 return {
290 filePath: options.filePath,
291 push(record) {
292 try {
293 buffer.push(`${JSON.stringify(record)}\n`);
294 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
295 flushUnsafe();
296 }
297 } catch {
298 return;
299 }
300 },
301 flush,
302 close: () => flush,
303 } satisfies TraceSink;
304});
305​
306class LocalFileSpan implements Tracer.Span {
307 readonly _tag = "Span";
308 readonly name: string;
309 readonly spanId: string;
310 readonly traceId: string;
311 readonly parent: Option.Option<Tracer.AnySpan>;
312 readonly annotations: Tracer.Span["annotations"];
313 readonly links: Array<Tracer.SpanLink>;
314 readonly sampled: boolean;
315 readonly kind: Tracer.SpanKind;
316​
317 status: Tracer.SpanStatus;
318 attributes: Map<string, unknown>;
319 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
320 private readonly delegate: Tracer.Span;
321 private readonly push: (record: EffectTraceRecord) => void;
322​
323 constructor(
324 options: Parameters<Tracer.Tracer["span"]>[0],
325 delegate: Tracer.Span,
326 push: (record: EffectTraceRecord) => void,
327 ) {
328 this.delegate = delegate;
329 this.push = push;
330 this.name = delegate.name;
331 this.spanId = delegate.spanId;
332 this.traceId = delegate.traceId;
333 this.parent = options.parent;
334 this.annotations = options.annotations;
335 this.links = [...options.links];
336 this.sampled = delegate.sampled;
337 this.kind = delegate.kind;
338 this.status = {
339 _tag: "Started",
340 startTime: options.startTime,
341 };
342 this.attributes = new Map();
343 this.events = [];
344 }
345​
346 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
347 this.status = {
348 _tag: "Ended",
349 startTime: this.status.startTime,
350 endTime,
351 exit,
352 };
353 this.delegate.end(endTime, exit);
354​
355 if (this.sampled) {
356 this.push(spanToTraceRecord(this));
357 }
358 }
359​
360 attribute(key: string, value: unknown): void {
361 this.attributes.set(key, value);
362 this.delegate.attribute(key, value);
363 }
364​
365 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
366 const nextAttributes = attributes ?? {};
367 this.events.push([name, startTime, nextAttributes]);
368 this.delegate.event(name, startTime, nextAttributes);
369 }
370​
371 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
372 this.links.push(...links);
373 this.delegate.addLinks(links);
374 }
376​
377export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
378 options: LocalFileTracerOptions,
379) {
380 const sink =
381 options.sink ??
382 (yield* makeTraceSink({
383 filePath: options.filePath,
384 maxBytes: options.maxBytes,
385 maxFiles: options.maxFiles,
386 batchWindowMs: options.batchWindowMs,
387 }));
388​
389 const delegate =
390 options.delegate ??
391 Tracer.make({
392 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
393 });
394​
395 return Tracer.make({
396 span(spanOptions) {
397 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
398 },
399 ...(delegate.context ? { context: delegate.context } : {}),
400 });
401});
402​
403const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
404 1: "internal",
405 2: "server",
406 3: "client",
407 4: "producer",
408 5: "consumer",
409};
410​
411export function decodeOtlpTraceRecords(
412 payload: OtlpTracer.TraceData,
413): ReadonlyArray<OtlpTraceRecord> {
414 const records: Array<OtlpTraceRecord> = [];
415​
416 for (const resourceSpan of payload.resourceSpans) {
417 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
418​
419 for (const scopeSpan of resourceSpan.scopeSpans) {
420 for (const span of scopeSpan.spans) {
421 records.push(
422 otlpSpanToTraceRecord({
423 resourceAttributes,
424 scopeAttributes: decodeAttributes(
425 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
426 ? scopeSpan.scope.attributes
427 : [],
428 ),
429 scopeName: scopeSpan.scope.name,
430 scopeVersion:
431 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
432 ? scopeSpan.scope.version
433 : undefined,
434 span,
435 }),
436 );
437 }
438 }
439 }
440​
441 return records;
443​
444function otlpSpanToTraceRecord(input: {
445 readonly resourceAttributes: Readonly<Record<string, unknown>>;
446 readonly scopeAttributes: Readonly<Record<string, unknown>>;
447 readonly scopeName: string | undefined;
448 readonly scopeVersion: string | undefined;
449 readonly span: OtlpSpan;
450}): OtlpTraceRecord {
451 return {
452 type: "otlp-span",
453 name: input.span.name,
454 traceId: input.span.traceId,
455 spanId: input.span.spanId,
456 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
457 sampled: true,
458 kind: normalizeSpanKind(input.span.kind),
459 startTimeUnixNano: input.span.startTimeUnixNano,
460 endTimeUnixNano: input.span.endTimeUnixNano,
461 durationMs:
462 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
463 1_000_000,
464 attributes: decodeAttributes(input.span.attributes),
465 resourceAttributes: input.resourceAttributes,
466 scope: {
467 ...(input.scopeName ? { name: input.scopeName } : {}),
468 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
469 attributes: input.scopeAttributes,
470 },
471 events: decodeEvents(input.span.events),
472 links: decodeLinks(input.span.links),
473 status: decodeStatus(input.span.status),
474 };
476​
477function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
478 const code = String(input.code);
479 const message = input.message;
480​
481 return {
482 code,
483 ...(message ? { message } : {}),
484 };
486​
487function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
488 return input.map((current) => ({
489 name: current.name,
490 timeUnixNano: current.timeUnixNano,
491 attributes: decodeAttributes(current.attributes),
492 }));
494​
495function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
496 return input.flatMap((current) => {
497 const traceId = current.traceId;
498 const spanId = current.spanId;
499 return {
500 traceId,
501 spanId,
502 attributes: decodeAttributes(current.attributes),
503 };
504 });
506​
507function decodeAttributes(
508 input: ReadonlyArray<OtlpResource.KeyValue>,
509): Readonly<Record<string, unknown>> {
510 const entries: Record<string, unknown> = {};
511​
512 for (const attribute of input) {
513 entries[attribute.key] = decodeValue(attribute.value);
514 }
515​
516 return compactTraceAttributes(entries);
518​
519function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
520 if (input == null) {
521 return null;
522 }
523 if ("stringValue" in input) {
524 return input.stringValue;
525 }
526 if ("boolValue" in input) {
527 return input.boolValue;
528 }
529 if ("intValue" in input) {
530 return input.intValue;
531 }
532 if ("doubleValue" in input) {
533 return input.doubleValue;
534 }
535 if ("bytesValue" in input) {
536 return input.bytesValue;
537 }
538 if (input.arrayValue) {
539 return input.arrayValue.values.map((entry) => decodeValue(entry));
540 }
541 if (input.kvlistValue) {
542 return decodeAttributes(input.kvlistValue.values);
543 }
544 return null;
546​
547function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
548 return SPAN_KIND_MAP[input] || "internal";
550​
551function parseBigInt(input: string): bigint {
552 try {
553 return BigInt(input);
554 } catch {
555 return 0n;
556 }