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

observability.ts

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