main
1// Minimal OTLP/JSON tracer. One ExportTraceServiceRequest per span per line (JSONL),
2// so `grep '"key":"git.pack.objects"' trace.jsonl` works and the same lines can be
3// POSTed to any OTLP/HTTP collector unchanged.
5/* oxlint-disable max-classes-per-file -- Tracer and Span are one API: a Tracer starts Spans, a Span exports through its Tracer */
6import { scrubError } from './errors.js';
7import { thrownCode, thrownMessage, thrownName, thrownStack } from './boundary.js';
8import { errorKind, getOrElse, none } from './result.js';
9import type { Input } from './absent.js';
10import { atOr, field, fromNullable, fromNullish, isMissing, withDefaults } from './absent.js';
12// OTLP AnyValue: exactly one of these fields. `in` on the field name discriminates.
13export type AnyValue =
14 | { readonly stringValue: string }
15 | { readonly boolValue: boolean }
16 | { readonly intValue: string }
17 | { readonly doubleValue: number }
18 | { readonly bytesValue: string }
19 | { readonly arrayValue: { readonly values: readonly AnyValue[] } };
20export type KeyValue = { readonly key: string; readonly value: AnyValue };
21// Span attributes as the caller writes them: scalars, bytes or arrays of them. A key holding the platform missing value
22// is not exported (a caller's `{ x: maybe }` sets nothing); null is exported as the empty string.
23export type Attrs = Readonly<Record<string, unknown>>;
24export type Scrub = (s: string) => string;
25// OTLP StatusCode: 0 unset, 1 ok, 2 error. Only an error carries a message.
26export type Status = { readonly code: 0 } | { readonly code: 1 } | { readonly code: 2; readonly message: string };
27export type SpanEvent = { readonly name: string; readonly timeUnixNano: string; readonly attributes: readonly KeyValue[] };
28export type SpanLink = { readonly traceId: string; readonly spanId: string; readonly attributes: readonly KeyValue[] };
29// A root span has no parentSpanId key at all (OTLP omits it); a child names its parent.
30export type OtlpRootSpan = {
31 readonly traceId: string;
32 readonly spanId: string;
33 readonly name: string;
34 readonly kind: number;
35 readonly startTimeUnixNano: string;
36 readonly endTimeUnixNano: string;
37 readonly attributes: readonly KeyValue[];
38 readonly events: readonly SpanEvent[];
39 readonly links: readonly SpanLink[];
40 readonly status: Status;
41 readonly droppedAttributesCount: number;
42 readonly droppedEventsCount: number;
43 readonly droppedLinksCount: number;
44};
45export type OtlpChildSpan = OtlpRootSpan & { readonly parentSpanId: string };
46export type OtlpSpan = OtlpRootSpan | OtlpChildSpan;
47export type Scope = { readonly name: string; readonly version: string };
48export type ScopeSpans = { readonly scope: Scope; readonly spans: readonly OtlpSpan[] };
49export type ResourceSpans = { readonly resource: { readonly attributes: readonly KeyValue[] }; readonly scopeSpans: readonly ScopeSpans[] };
50export type ExportLine = { readonly resourceSpans: readonly ResourceSpans[] };
51// Returns nothing ply reads. An async exporter's promise is watched: its rejection goes to onTelemetryError.
52export type Exporter = (line: ExportLine) => unknown;
53// A span as it ended, as plain values: exactly what `flattenLine` reads back from the OTLP line `end()` would export for
54// it (attributes and event attributes scrubbed, an int as a number, bytes as base64, null as ''), plus its start and end
55// times. `otlp()` builds that OTLP span on first call and returns the same object after. For an exporter that lives in
56// the same process (a list kept for the request, a span mirrored onto a platform tracer): no OTLP is built for it.
57export type EndedSpan = FlatSpan & {
58 readonly startTimeUnixNano: string;
59 readonly endTimeUnixNano: string;
60 readonly otlp: () => OtlpSpan;
61};
62export type SpanSink = (span: EndedSpan) => unknown;
64// Platform clocks are probed, not type-checked: newer Workers compatibility dates define a `process` global whose
65// `hrtime`/`cpuUsage` exist but throw "not implemented" (found under workerd 2026-10-18, compat date 2026-10-18).
66const probe = <F extends () => unknown>(make: () => F, fallback: F): F => { try { const f = make(); f(); return f; } catch { return fallback; } };
67const nowNs = probe((): (() => bigint) => { const base = BigInt(Date.now()) * 1_000_000n - process.hrtime.bigint(); return () => base + process.hrtime.bigint(); }, () => BigInt(Date.now()) * 1_000_000n);
68const now = (): string => nowNs().toString();
70// CPU clock: real on node (process.cpuUsage), null on Workers where no clock advances during synchronous work. Spans
71// record cpu_ms only where it is measured; the edge carries calibrated estimates instead (see edit.js CPU_RATE).
72export const cpuNow: () => number | null = probe((): (() => number | null) => () => { const u = process.cpuUsage(); return (u.user + u.system) / 1000; }, () => null);
73// t0 is non-null only where the clock is real, so cpuNow() is a number there.
74// oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- see above (and no `!`: docs/STACK.md)
75export const cpuSince = (t0: number | null): number | null => (t0 === null ? null : (cpuNow() as number) - t0);
77// Isolate-lifetime invocation counter: module scope survives across requests inside one isolate (workerd, node), so the
78// first root span of an isolate is the one that paid connection setup, JIT warmup and cache misses.
79let invocations = 0;
81// Span and trace ids: `words` random 32-bit words as lowercase hex, 8 digits each. The words come from a pool filled 256
82// at a time (one getRandomValues call per 42 spans, not one per id), each word used once. Filled on first use, never at
83// module load: Workers refuse getRandomValues in the global scope.
84const POOL_WORDS = 256;
85const pool = new Uint32Array(POOL_WORDS);
86let pooled = POOL_WORDS;
87const rand = (words: number): string => {
88 let hex = '';
89 for (let i = 0; i < words; i++) {
90 // Stryker disable next-line ConditionalExpression: refilling for every word gives ids of the same form (the pool is the fast path)
91 if (pooled === POOL_WORDS) { crypto.getRandomValues(pool); pooled = 0; }
92 hex += atOr(pool, pooled++, 0).toString(16).padStart(8, '0');
93 }
94 return hex;
95};
97// OTLP AnyValue encoding (pure)
98export function anyValue(v: unknown): AnyValue {
99 if (fromNullish(v).tag === 'none') return { stringValue: '' };
100 if (typeof v === 'string') return { stringValue: v };
101 if (typeof v === 'boolean') return { boolValue: v };
102 if (typeof v === 'bigint') return { intValue: v.toString() };
103 if (typeof v === 'number') return Number.isInteger(v) ? { intValue: String(v) } : { doubleValue: v };
104 // bytes are code units 0-255, where fromCharCode and fromCodePoint agree
105 // oxlint-disable-next-line unicorn/prefer-code-point -- see above
106 if (v instanceof Uint8Array) return { bytesValue: btoa(String.fromCharCode(...v.subarray(0, 4096))) };
107 // oxlint-disable-next-line unicorn/no-array-callback-reference -- bundle budget: anyValue takes one argument, so map's index and array are ignored
108 if (Array.isArray(v)) return { arrayValue: { values: v.map(anyValue) } };
109 // objects are stringified: attribute values are scalars or arrays of scalars
110 // oxlint-disable-next-line typescript/no-base-to-string -- a caller's object renders as String() renders it, as before
111 return { stringValue: String(v) };
112}
113export const kvs = (obj: Attrs): KeyValue[] => Object.entries(obj).filter(([, v]) => fromNullable(v).tag === 'some').map(([key, value]) => ({ key, value: anyValue(value) }));
114const scrubAny = (v: AnyValue, scrub: Scrub): AnyValue => {
115 if ('stringValue' in v) return { stringValue: scrub(v.stringValue) };
116 return 'arrayValue' in v ? { arrayValue: { values: v.arrayValue.values.map(x => scrubAny(x, scrub)) } } : v;
117};
118const scrubKvs = (list: readonly KeyValue[], scrub: Scrub): KeyValue[] => list.map(({ key, value }) => ({ key, value: scrubAny(value, scrub) }));
120// One attribute value as the reading side sees it: fromAny(scrubAny(anyValue(v))) without building the AnyValue, so an
121// in-process consumer pays neither encoding. Each branch is anyValue's, in its order; test/otel-ended.test.js holds the
122// two equal over every kind of value.
123const text = (s: string, scrub: Scrub | null): string => (scrub === null ? s : scrub(s));
124function flatValue(v: unknown, scrub: Scrub | null): FlatValue {
125 if (v === null || isMissing(v)) return text('', scrub);
126 // Stryker disable next-line ConditionalExpression,StringLiteral: a string skipped here reaches the String(v) branch below, which returns the same text
127 if (typeof v === 'string') return text(v, scrub);
128 if (typeof v === 'boolean') return v;
129 if (typeof v === 'bigint') return Number(v.toString());
130 // an integer goes out as intValue String(v) and comes back through Number(): only -0 changes (to 0)
131 if (typeof v === 'number') return v === 0 ? 0 : v;
132 // bytes are not scrubbed: they leave as base64, which no credential pattern matches
133 // oxlint-disable-next-line unicorn/prefer-code-point -- code units 0-255, as anyValue
134 if (v instanceof Uint8Array) return btoa(String.fromCharCode(...v.subarray(0, 4096)));
135 if (Array.isArray(v)) return v.map(x => flatValue(x, scrub));
136 // oxlint-disable-next-line typescript/no-base-to-string -- a caller's object renders as String() renders it, as anyValue
137 return text(String(v), scrub);
138}
139// A plain record, keyed as Object.fromEntries keys it: an own `__proto__` key is a property, not the prototype.
140function flatAttrs(attrs: Attrs, scrub: Scrub | null): FlatAttrs {
141 const out: FlatAttrs = {};
142 for (const key of Object.keys(attrs)) {
143 const v = attrs[key];
144 if (isMissing(v)) continue;
145 // Stryker disable next-line ConditionalExpression: defining every key as a property gives the same record (the assignment is the fast path)
146 if (key === '__proto__') Object.defineProperty(out, key, { value: flatValue(v, scrub), enumerable: true, writable: true, configurable: true });
147 else out[key] = flatValue(v, scrub);
148 }
149 return out;
150}
152// The default exporter: spans are dropped. end() checks for it, so a tracer without an exporter builds no OTLP.
153const dropSpans: Exporter = () => { /* spans are dropped */ };
155export const KIND: Readonly<{ INTERNAL: 1; SERVER: 2; CLIENT: 3; PRODUCER: 4; CONSUMER: 5 }> = Object.freeze({ INTERNAL: 1, SERVER: 2, CLIENT: 3, PRODUCER: 4, CONSUMER: 5 });
157// `onEnd`: called with each span as it ends (an EndedSpan), before the exporter. `exporter`: the OTLP/JSON line per span.
158// A tracer with only `onEnd` builds no OTLP unless a consumer calls `otlp()`; one with neither builds nothing.
159// `onTelemetryError`: telemetry never changes an operation's outcome. A throw or a rejected promise from `onEnd`, from
160// `exporter` (or an overridden `export`) or from an operation's `onFinish` is caught where ply calls it, counted in
161// `tracer.telemetryErrors` and handed to this hook (null: only counted). What the hook itself throws is dropped.
162// The hook 'internal' is ply's own failure, never the caller's: building the span (its OTLP encoding, its EndedSpan) threw.
163export type TelemetryHook = 'onEnd' | 'exporter' | 'onFinish' | 'internal';
164export type TelemetryErrorSink = (error: unknown, at: { readonly hook: TelemetryHook; readonly span: string }) => unknown;
165// The tracer's settings, total (what the constructor holds after defaults).
166type TracerSettings = { readonly exporter: Exporter; readonly onEnd: SpanSink | null; readonly onTelemetryError: TelemetryErrorSink | null; readonly resource: Attrs; readonly scope: Scope; readonly maxEvents: number };
167// The exported config: `onTelemetryError` may be left out (a consumer that builds a whole TracerConfig written before
168// the hook existed still type-checks); every other key is required here and optional in TracerOptions.
169export type TracerConfig = Omit<TracerSettings, 'onTelemetryError'> & Input<Pick<TracerSettings, 'onTelemetryError'>>;
170export type TracerOptions = Input<TracerConfig>;
171// How a span starts: under `parent`, or following `follows` (never both), with the credential scrubber it inherits.
172export type StartConfig = { readonly parent: Span | null; readonly follows: Span | null; readonly kind: number; readonly attrs: Attrs; readonly scrub: Scrub | null };
173export type StartOptions = Input<StartConfig>;
174type SpanInit = StartConfig & { readonly name: string };
175// A span's scrubber: its own, else its parent's, else the span it follows.
176const inheritedScrub = ({ scrub, parent, follows }: StartConfig): Scrub | null => {
177 if (scrub !== null) return scrub;
178 if (parent !== null) return parent.scrub;
179 return follows === null ? null : follows.scrub;
180};
181// A thrown field rendered the way String() renders it (a stack, a message). A string is itself.
182const asText = (v: unknown): string => (typeof v === 'string' ? v : String(v));
184// ---- reading a value back (shared by the reading side below and EndedSpan) ----
185export function fromAny(v: AnyValue): FlatValue {
186 if ('stringValue' in v) return v.stringValue;
187 if ('intValue' in v) return Number(v.intValue);
188 if ('doubleValue' in v) return v.doubleValue;
189 if ('boolValue' in v) return v.boolValue;
190 if ('arrayValue' in v) return v.arrayValue.values.map(fromAny);
191 return v.bytesValue;
192}
193export const flattenKvs = (list: readonly KeyValue[]): FlatAttrs => Object.fromEntries(list.map(({ key, value }) => [key, fromAny(value)]));
195// an error's message (even empty) is a string the scrubber must see; ok and unset carry none
196const scrubbedStatus = (status: Status, s: Scrub | null): Status => (s !== null && status.code === 2 ? { code: 2, message: s(status.message) } : status);
198// What the OTLP span is built from: a live span, or an ended span's fields as they were when it ended.
199type SpanFields = Pick<Span, 'traceId' | 'spanId' | 'parentSpanId' | 'name' | 'kind' | 'start' | 'attrs' | 'events' | 'links' | 'status' | 'droppedEvents' | 'droppedLinks' | 'scrub'>;
201// The OTLP span end() exports.
202function otlpSpan(span: SpanFields, endTimeUnixNano: string): OtlpSpan {
203 const s = span.scrub;
204 return {
205 ...(span.parentSpanId === null ? {} : { parentSpanId: span.parentSpanId }),
206 traceId: span.traceId, spanId: span.spanId, name: span.name, kind: span.kind,
207 startTimeUnixNano: span.start, endTimeUnixNano,
208 attributes: s ? scrubKvs(kvs(span.attrs), s) : kvs(span.attrs),
209 events: s ? span.events.map(ev => ({ ...ev, attributes: scrubKvs(ev.attributes, s) })) : span.events,
210 links: span.links, status: scrubbedStatus(span.status, s),
211 droppedAttributesCount: 0, droppedEventsCount: span.droppedEvents, droppedLinksCount: span.droppedLinks,
212 };
213}
215const flatEvent = (ev: SpanEvent, s: Scrub | null): FlatSpan['events'][number] => ({ name: ev.name, attrs: flattenKvs(s ? scrubKvs(ev.attributes, s) : ev.attributes) });
216const flatLink = (l: SpanLink): FlatSpan['links'][number] => ({ traceId: l.traceId, spanId: l.spanId, attrs: flattenKvs(l.attributes) });
217// A list as it stands, for a span that may still be written to after it ended. Most spans have no events or links.
218// Stryker disable next-line ConditionalExpression: slicing an empty list is a fresh empty list too (the test is the fast path)
219const copied = <T>(list: T[]): T[] => (list.length === 0 ? [] : list.slice());
221// The EndedSpan of a span that just ended. Its OTLP form is built on first call from the span's fields as they were at
222// end: the attributes record (set() after end writes a copy), and copies of the event and link lists.
223function endedSpan(span: Span, end: bigint): EndedSpan {
224 const s = span.scrub;
225 const endTimeUnixNano = end.toString();
226 const fields: SpanFields = {
227 traceId: span.traceId, spanId: span.spanId, parentSpanId: span.parentSpanId, name: span.name, kind: span.kind, start: span.start,
228 attrs: span.attrs, events: copied(span.events), links: copied(span.links), status: span.status,
229 droppedEvents: span.droppedEvents, droppedLinks: span.droppedLinks, scrub: s,
230 };
231 let built: OtlpSpan | null = null;
232 const otlp = (): OtlpSpan => {
233 if (built === null) built = otlpSpan(fields, endTimeUnixNano);
234 return built;
235 };
236 return {
237 traceId: span.traceId, spanId: span.spanId, parentSpanId: span.parentSpanId, name: span.name, kind: span.kind,
238 durationMs: Number(end - BigInt(span.start)) / 1e6,
239 status: scrubbedStatus(span.status, s), attrs: flatAttrs(span.attrs, s), droppedEvents: span.droppedEvents,
240 events: fields.events.map(ev => flatEvent(ev, s)), links: fields.links.map(flatLink),
241 startTimeUnixNano: span.start, endTimeUnixNano, otlp,
242 };
243}
245// The boundary around the caller's telemetry code, as functions of this module and not methods of the tracer: ply calls
246// no method on a caller's tracer that operation()'s entry check does not guarantee (a wrapper with only start/span, a
247// Tracer built by another copy of ply). A failure is counted on `telemetryErrors` where the object has that counter and
248// handed to its `onTelemetryError` where that is a function; both are read, neither is required.
249function telemetryFailed(tracer: object, thrown: unknown, hook: TelemetryHook, span: string): void {
250 const counted = getOrElse(field(tracer, 'telemetryErrors'), null);
251 if (typeof counted === 'number') Reflect.set(tracer, 'telemetryErrors', counted + 1);
252 const report = getOrElse(field(tracer, 'onTelemetryError'), null);
253 if (typeof report !== 'function') return;
254 try {
255 const returned: unknown = Reflect.apply(report, tracer, [thrown, { hook, span }]);
256 if (typeof returned === 'object' && returned !== null) Promise.resolve(returned).catch(() => { /* the reporter is telemetry too */ });
257 } catch { /* the reporter is telemetry too: what it throws is dropped */ }
258}
259// Run `call`; a throw, or a rejection of the promise it returns (an async exporter), is counted and reported, and never
260// reaches the operation that ended the span.
261export function guardTelemetry(tracer: object, hook: TelemetryHook, span: string, call: () => unknown): void {
262 try {
263 const returned = call();
264 // an async exporter returns a promise (any thenable is an object): its rejection is this hook's failure too
265 if (typeof returned === 'object' && returned !== null) Promise.resolve(returned).catch((e: unknown) => { telemetryFailed(tracer, e, hook, span); });
266 } catch (e) { telemetryFailed(tracer, e, hook, span); }
267}
268// ply's own span-building step: null when it threw (reported as 'internal'; the span is counted, not exported).
269function buildSpan<T>(tracer: { count: number }, span: string, make: () => T): T | null {
270 try { return make(); } catch (e) { tracer.count++; telemetryFailed(tracer, e, 'internal', span); return null; }
271}
273// `declare` fields: assigned in the constructor, so they emit nothing (the JS is the constructor body as before).
274// A span under an authenticated transport carries the transport's `scrub` (http.js), and every child inherits it. At
275// export every string (attributes, event attributes, status) passes through it, and `error(e)` scrubs the error object
276// itself in place, so neither the trace nor the error the caller catches holds a credential a server echoed back.
277export class Span {
278 public declare tracer: Tracer;
279 public declare traceId: string;
280 public declare spanId: string;
281 public declare parentSpanId: string | null;
282 public declare name: string;
283 public declare kind: number;
284 public declare start: string;
285 public declare attrs: Record<string, unknown>;
286 public declare events: SpanEvent[];
287 public declare links: SpanLink[];
288 public declare droppedEvents: number;
289 public declare droppedLinks: number;
290 public declare status: Status;
291 public declare ended: boolean;
292 public declare scrub: Scrub | null;
293 public constructor(tracer: Tracer, init: SpanInit) {
294 const { name, kind, attrs, parent, follows } = init;
295 if (parent && follows) throw new TypeError('a span has a parent or follows one, not both');
296 this.tracer = tracer;
297 this.traceId = parent ? parent.traceId : rand(4);
298 this.spanId = rand(2);
299 this.parentSpanId = parent ? parent.spanId : null;
300 this.name = name;
301 this.kind = kind;
302 this.start = now();
303 this.attrs = { ...attrs };
304 if (!parent && !follows) { invocations++; this.attrs['ply.isolate.invocation'] = invocations; this.attrs['ply.isolate.cold'] = invocations === 1; }
305 this.events = [];
306 this.links = [];
307 this.droppedEvents = 0;
308 this.droppedLinks = 0;
309 this.status = { code: 0 };
310 this.ended = false;
311 this.scrub = inheritedScrub(init);
312 if (follows) { this.link(follows, { 'ply.link': 'follows_from' }); if (!follows.ended) follows.link(this, { 'ply.link': 'followed_by' }); }
313 }
314 // After end() the record an EndedSpan's otlp() reads is left as it ended: a late set() writes to a copy.
315 public set(attrs: Attrs): this { if (this.ended) this.attrs = { ...this.attrs }; Object.assign(this.attrs, attrs); return this; }
316 // Bounded: a pack with 10k objects must not produce a 10k-event span. The count of dropped events is exported.
317 public event(name: string, attrs: Attrs = {}): this {
318 if (this.events.length >= this.tracer.maxEvents) { this.droppedEvents++; return this; }
319 this.events.push({ name, timeUnixNano: now(), attributes: kvs(attrs) }); return this;
320 }
321 // OTLP span link: a causal relation to a span that is not the parent (e.g. the attempt this one retries). Bounded like
322 // events: a checkout that streams 10k blobs must not produce a 10k-link span.
323 public link(span: Span, attrs: Attrs = {}): this {
324 if (this.links.length >= this.tracer.maxEvents) { this.droppedLinks++; return this; }
325 this.links.push({ traceId: span.traceId, spanId: span.spanId, attributes: kvs(attrs) }); return this;
326 }
327 // `type`: the error.type to record (a caller's code); without one, or with null, the thrown value's code or name.
328 public error(e: unknown, ...type: [] | [unknown]): this {
329 scrubError(e, this.scrub);
330 // a thrown value of any type: a primitive or null has none of these fields
331 const message = asText(getOrElse(thrownMessage(e), e));
332 const name = getOrElse<unknown>(thrownName(e), 'Error');
333 const given = type.length === 0 ? none : fromNullish(type[0]);
334 this.status = { code: 2, message };
335 // error.type stays the taxonomy code (or the type the caller passed). error.kind is the closed discriminant
336 // callers switch on: miss.kind, then kind, then reason, then code (#157).
337 this.set({ 'error.type': getOrElse(given, getOrElse(thrownCode(e), name)), 'error.kind': errorKind(e) });
338 this.event('exception', { 'exception.type': name, 'exception.message': message, 'exception.stacktrace': asText(getOrElse<unknown>(thrownStack(e), '')) });
339 return this;
340 }
341 public ok(): this { if (this.status.code === 0) this.status = { code: 1 }; return this; }
342 // Ends the span once. The tracer's onEnd gets the EndedSpan; its exporter (or an override of export) gets the OTLP
343 // span. With neither, nothing is built: the span is only counted.
344 public end(): this {
345 if (this.ended) return this;
346 this.ended = true;
347 this.ok();
348 const end = nowNs();
349 const tracer = this.tracer;
350 const sink = tracer.onEnd;
351 // a subclass that overrides export (a tracer that mirrors spans elsewhere) still gets every span
352 // oxlint-disable-next-line no-use-before-define -- Span and Tracer are one API (see the top of this file); this runs after both exist
353 const exports = tracer.exporter !== dropSpans || tracer.export !== Tracer.prototype.export;
354 // Every call below into the caller's code (onEnd, the exporter, an overridden export) is guarded: end() never throws.
355 // Building the span is ply's code: what it throws is reported as 'internal', not as the caller's exporter.
356 const name = this.name;
357 if (sink === null) {
358 if (!exports) { tracer.count++; return this; }
359 const span = buildSpan(tracer, name, () => otlpSpan(this, end.toString()));
360 // oxlint-disable-next-line typescript/no-confusing-void-expression -- an override of export may be async: the guard watches what it returns
361 if (span !== null) guardTelemetry(tracer, 'exporter', name, (): unknown => tracer.export(span));
362 return this;
363 }
364 const ended = buildSpan(tracer, name, () => endedSpan(this, end));
365 if (ended === null) return this;
366 guardTelemetry(tracer, 'onEnd', name, (): unknown => sink(ended));
367 if (!exports) { tracer.count++; return this; }
368 const span = buildSpan(tracer, name, () => ended.otlp());
369 // oxlint-disable-next-line typescript/no-confusing-void-expression -- as above
370 if (span !== null) guardTelemetry(tracer, 'exporter', name, (): unknown => tracer.export(span));
371 return this;
372 }
373}
375// fn(span) under a span that is ended for it, as a function of start() alone: how ply runs a body on a caller's
376// tracer. opts.tracer is duck-typed and operation()'s entry check guarantees start() and nothing else, so ply never
377// calls a caller's span(). The body's value passes through; what it throws is recorded, the span ended, and rethrown.
378// Not every caller comes through that check: push(t), lsRefs(t), discover(t) and the other step functions take a
379// Transport whose `tracer` nothing has checked (a caller's transport record, a test double with only span()). A tracer
380// with no start() function there is the documented default, a tracer with no exporter (README: without one spans are
381// dropped; http.ts gives a transport made without one the same): the body runs on a dropped span, never a TypeError.
382// The refusal for a non-tracer stays where the README puts it, at operation()'s entry (bad_request, what: 'tracer').
383export async function spanOn<T>(tracer: { readonly start: (name: string, options: StartOptions) => Span }, name: string, opts: StartOptions, fn: (s: Span) => T | PromiseLike<T>): Promise<T> {
384 const start = getOrElse(field(tracer, 'start'), null);
385 // oxlint-disable-next-line typescript/no-unsafe-type-assertion, no-use-before-define -- a start() is the caller's Span factory (the duck-typed contract above); Tracer is defined below and exists when this runs
386 const s = (typeof start === 'function' ? Reflect.apply(start, tracer, [name, opts]) : new Tracer().start(name, opts)) as Span;
387 try { const r = await fn(s); s.end(); return r; }
388 catch (e) { s.error(e); s.end(); throw e; }
389}
391export class Tracer {
392 public declare exporter: Exporter;
393 public declare onEnd: SpanSink | null;
394 public declare onTelemetryError: TelemetryErrorSink | null;
395 // how many calls into the caller's telemetry code (onEnd, exporter, onFinish) threw or rejected
396 public declare telemetryErrors: number;
397 public declare maxEvents: number;
398 public declare resource: { attributes: KeyValue[] };
399 public declare scope: Scope;
400 public declare count: number;
401 public constructor(options: TracerOptions = {}) {
402 const { exporter, onEnd, onTelemetryError, resource, scope, maxEvents } = withDefaults<TracerSettings>(options, { exporter: dropSpans, onEnd: null, onTelemetryError: null, resource: {}, scope: { name: 'ply', version: '0.2.0' }, maxEvents: 256 });
403 this.exporter = exporter;
404 this.onEnd = onEnd;
405 this.onTelemetryError = onTelemetryError;
406 this.telemetryErrors = 0;
407 this.maxEvents = maxEvents;
408 this.resource = { attributes: kvs({ 'service.name': 'ply', 'telemetry.sdk.name': 'ply-otel', 'telemetry.sdk.language': 'javascript', ...resource }) };
409 this.scope = scope;
410 this.count = 0;
411 }
412 // `follows`: start a span that measures work the caller drives after `follows` returns (a stream it reads, an iterator
413 // it drains). It is the root of a trace of its own with a 'follows_from' link to `follows` (and, while `follows` is
414 // still open, a 'followed_by' link back), so no child outlives its parent: README "Span lifetimes".
415 public start(name: string, options: StartOptions = {}): Span {
416 return new Span(this, { name, ...withDefaults<StartConfig>(options, { parent: null, follows: null, kind: KIND.INTERNAL, attrs: {}, scrub: null }) });
417 }
418 // Run fn(span) with automatic end/status.
419 // oxlint-disable-next-line typescript/promise-function-async -- spanOn's promise, returned as is
420 public span<T>(name: string, opts: StartOptions, fn: (s: Span) => T | PromiseLike<T>): Promise<T> { return spanOn(this, name, opts, fn); }
421 public export(span: OtlpSpan): void {
422 this.count++;
423 const line: ExportLine = { resourceSpans: [{ resource: this.resource, scopeSpans: [{ scope: this.scope, spans: [span] }] }] };
424 // guarded here as well as in Span.end(): an async exporter's rejection is caught where its promise is returned
425 guardTelemetry(this, 'exporter', span.name, (): unknown => this.exporter(line));
426 }
427 // The telemetry boundary as a method (guardTelemetry above): ply itself never calls it on a caller's tracer.
428 public guard(hook: TelemetryHook, span: string, call: () => unknown): void { guardTelemetry(this, hook, span, call); }
429}
431// ---- exporters ----
432export type ArrayExporter = Exporter & { readonly lines: ExportLine[] };
433export const arrayExporter = (arr: ExportLine[] = []): ArrayExporter => Object.assign((line: ExportLine) => { arr.push(line); }, { lines: arr });
434// the console exporter's default sink is the console; bundle budget: the JS's arrow, byte for byte
435// oxlint-disable-next-line no-console, typescript/no-confusing-void-expression -- see above
436export const consoleExporter = (log: (s: string) => void = console.log): Exporter => request => log(JSON.stringify(request));
437// ---- reading side (pure): flatten a JSONL line back to {name, attrs, events, ...} ----
438export type FlatValue = string | number | boolean | readonly FlatValue[];
439export type FlatAttrs = Record<string, FlatValue>;
440export type FlatSpan = {
441 readonly traceId: string;
442 readonly spanId: string;
443 readonly parentSpanId: string | null;
444 readonly name: string;
445 readonly kind: number;
446 readonly durationMs: number;
447 readonly status: Status;
448 readonly attrs: FlatAttrs;
449 readonly droppedEvents: number;
450 readonly events: ReadonlyArray<{ readonly name: string; readonly attrs: FlatAttrs }>;
451 readonly links: ReadonlyArray<{ readonly traceId: string; readonly spanId: string; readonly attrs: FlatAttrs }>;
452};
453// The reading side takes lines from any producer: parentSpanId, links and the dropped counts may be missing there.
454const foreignString = (s: OtlpSpan, key: string): string | null => { const v = field(s, key); return v.tag === 'some' && typeof v.value === 'string' ? v.value : null; };
455const foreignCount = (s: OtlpSpan, key: string): number => { const v = field(s, key); return v.tag === 'some' && typeof v.value === 'number' ? v.value : 0; };
456// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a foreign line's links, when it has a list there, are OTLP links
457const foreignLinks = (s: OtlpSpan): readonly SpanLink[] => { const v = field(s, 'links'); return v.tag === 'some' && Array.isArray(v.value) ? v.value as SpanLink[] : []; };
458export function flattenLine(line: ExportLine): FlatSpan[] {
459 return line.resourceSpans.flatMap(rs => rs.scopeSpans.flatMap(ss => ss.spans.map(s => ({
460 traceId: s.traceId, spanId: s.spanId, parentSpanId: foreignString(s, 'parentSpanId'), name: s.name, kind: s.kind,
461 durationMs: Number(BigInt(s.endTimeUnixNano) - BigInt(s.startTimeUnixNano)) / 1e6,
462 status: s.status, attrs: flattenKvs(s.attributes), droppedEvents: foreignCount(s, 'droppedEventsCount'),
463 events: s.events.map(e => ({ name: e.name, attrs: flattenKvs(e.attributes) })),
464 links: foreignLinks(s).map(l => ({ traceId: l.traceId, spanId: l.spanId, attrs: flattenKvs(l.attributes) })),
465 }))));
466}
Diagnostics4 git calls · 417 ms
CallStatusSizeTime0417 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=38434 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=38434 git.pkt.payload.max=38339 git.sideband.band1.bytes=38338 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=63 git.pack.bytes=38338 git.pack.ofs_delta=0 git.pack.ref_delta=8 git.pack.chain.max=8 git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77 git.pack.full=55Open pack map
fetch2009.9 KiB411 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=411 git.response.bytes=10139 git.response.cache=MISS git.response.duration_ms=411 git.fetch.wants=91811e3cb1148581810180c7f84f315910ad6539 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=10139 git.pkt.payload.max=10118 git.sideband.band1.bytes=10117 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e2f4a81f117089
- Request
- 4c36c2e1…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format