Unverified Commit db23b5ff authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Share local span recording across tooling and request insights

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 7693c1b1
......@@ -16,6 +16,7 @@ import {
type LocalSpanParent,
} from './span-store'
import { getOrCreateGlobalAsyncLocalStorage } from '../../app-render/async-local-storage'
import { LocalSpan } from '../../../shared/lib/local-span'
import type {
RequestInsightKind,
RequestInsightProxyStatus,
......@@ -280,10 +281,17 @@ type RequestIdentity = {
url?: string
}
class LocalRecordingSpan implements Span {
public name: string
class LocalRecordingSpan
extends LocalSpan<
SpanStoreAttributes,
number,
Parameters<Span['end']>[0],
SpanStoreRecord
>
implements Span
{
declare public name: string
private attributes: SpanStoreAttributes
private events: SpanStoreEvent[]
private readonly spanContextValue: ReturnType<Span['spanContext']>
private readonly openTelemetryIsolated: boolean
......@@ -293,8 +301,6 @@ class LocalRecordingSpan implements Span {
private links?: SpanStoreLink[]
private readonly parentSpanId?: string
private requestIdentity: RequestIdentity
private recordSpans: ReturnType<typeof captureLocalSpanRecorder> | undefined
private readonly startTime: number
private statusCode: number | undefined
private statusMessage: string | undefined
private exception:
......@@ -303,7 +309,6 @@ class LocalRecordingSpan implements Span {
message?: string
}
| undefined
private ended: boolean
constructor({
name,
......@@ -330,8 +335,12 @@ class LocalRecordingSpan implements Span {
requestIdentity: RequestIdentity
isolateOpenTelemetry: boolean
}) {
this.name = name
this.attributes = cleanSpanStoreAttributes(attributes)
super(
name,
cleanSpanStoreAttributes(attributes),
getTimestamp(startTime),
captureLocalSpanRecorder()
)
this.events = []
this.delegateSpan = delegateSpan
this.openTelemetrySpan = delegateSpan ?? publicParentSpan
......@@ -345,12 +354,9 @@ class LocalRecordingSpan implements Span {
this.links = getSpanStoreLinks(links)
this.parentSpanId = parentSpanId
this.requestIdentity = requestIdentity
this.recordSpans = captureLocalSpanRecorder()
this.startTime = getTimestamp(startTime)
this.statusCode = undefined
this.statusMessage = undefined
this.exception = undefined
this.ended = false
}
spanContext(): ReturnType<Span['spanContext']> {
......@@ -375,7 +381,7 @@ class LocalRecordingSpan implements Span {
return this
}
this.attributes[key] = value
this.setLocalAttribute(key, value)
this.delegateSpan?.setAttribute(key, value)
return this
}
......@@ -390,7 +396,7 @@ class LocalRecordingSpan implements Span {
for (const key of Object.keys(attributes)) {
const value = attributes[key]
if (value !== undefined) {
this.attributes[key] = value
this.setLocalAttribute(key, value)
}
}
this.delegateSpan?.setAttributes(attributes)
......@@ -443,19 +449,14 @@ class LocalRecordingSpan implements Span {
}
end(endTime?: Parameters<Span['end']>[0]): void {
if (this.ended) {
return
}
this.finish(endTime)
}
this.ended = true
protected onEnd(endTime: Parameters<Span['end']>[0]): void {
try {
this.delegateSpan?.end(endTime)
} finally {
try {
this.record(endTime)
} finally {
this.releaseReferences()
}
this.record(endTime)
}
}
......@@ -484,38 +485,35 @@ class LocalRecordingSpan implements Span {
const recordAttributes =
Object.keys(this.attributes).length > 0 ? this.attributes : undefined
this.recordSpans?.([
{
timestamp: getTimestamp(),
name: this.name,
startTime: this.startTime,
durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),
status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',
traceId: this.spanContextValue.traceId,
spanId: this.spanContextValue.spanId,
parentSpanId: this.parentSpanId,
requestId: this.requestIdentity.requestId,
requestInsightKind: this.requestIdentity.requestInsightKind,
requestInsightSource: this.requestIdentity.requestInsightSource,
requestInsightProxyStatus:
this.requestIdentity.requestInsightProxyStatus,
htmlRequestId: this.requestIdentity.htmlRequestId,
route:
getStringAttribute(recordAttributes, 'next.route') ??
getStringAttribute(recordAttributes, 'http.route') ??
this.requestIdentity.route,
url:
getStringAttribute(recordAttributes, 'http.url') ??
this.requestIdentity.url,
attributes: recordAttributes,
links: this.links,
events: this.events.length > 0 ? this.events : undefined,
error: this.getRecordError(),
},
])
this.emit({
timestamp: getTimestamp(),
name: this.name,
startTime: this.startTime,
durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),
status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',
traceId: this.spanContextValue.traceId,
spanId: this.spanContextValue.spanId,
parentSpanId: this.parentSpanId,
requestId: this.requestIdentity.requestId,
requestInsightKind: this.requestIdentity.requestInsightKind,
requestInsightSource: this.requestIdentity.requestInsightSource,
requestInsightProxyStatus: this.requestIdentity.requestInsightProxyStatus,
htmlRequestId: this.requestIdentity.htmlRequestId,
route:
getStringAttribute(recordAttributes, 'next.route') ??
getStringAttribute(recordAttributes, 'http.route') ??
this.requestIdentity.route,
url:
getStringAttribute(recordAttributes, 'http.url') ??
this.requestIdentity.url,
attributes: recordAttributes,
links: this.links,
events: this.events.length > 0 ? this.events : undefined,
error: this.getRecordError(),
})
}
private releaseReferences(): void {
protected releaseReferences(): void {
// AsyncLocalStorage can keep an ended span reachable when work spawned
// inside the span outlives it. Keep only the immutable span context and
// primitive timing/identity fields needed by the Span API after end.
......@@ -526,7 +524,7 @@ class LocalRecordingSpan implements Span {
this.openTelemetrySpan = undefined
this.links = undefined
this.requestIdentity = {}
this.recordSpans = undefined
this.subscriber = undefined
this.statusMessage = undefined
this.exception = undefined
}
......
import { getOrCreateGlobalAsyncLocalStorage } from '../../app-render/async-local-storage'
import { emitLocalSpans } from '../../../shared/lib/local-span'
import type {
RequestInsightKind,
RequestInsightProxyStatus,
......@@ -103,7 +104,9 @@ export function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {
}
export function recordSpans(spans: readonly SpanStoreRecord[]): void {
exportSpans(spans, getLocalSpanSinkStorage().getStore())
// Completed observations share delivery with live local spans, but retain
// request-only enablement and scoped sink ownership at this boundary.
emitLocalSpans(spans, captureLocalSpanRecorder())
}
export function captureLocalSpanRecorder(): (
......
/** @jest-environment node */
import { mkdtemp, rm } from 'fs/promises'
import { readFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { LocalSpan, emitLocalSpans } from './local-span'
import {
Span,
clearTraceEvents,
closeAllTraces,
flushAllTraces,
getTraceEvents,
initializeTraceState,
recordTraceEvents,
} from '../../trace/trace'
import { setGlobal } from '../../trace/shared'
import { PHASE_PRODUCTION_BUILD } from './constants'
import { createLocalSpan } from '../../server/lib/trace/local-span-recorder'
import {
recordSpans,
runWithLocalSpanSink,
setLocalSpanExporter,
setSpanRecorderForTest,
type SpanStoreRecord,
} from '../../server/lib/trace/span-store'
type Completion = { name: string; start: bigint; end: bigint; tags: Tags }
type Tags = Record<string, unknown>
class TestSpan extends LocalSpan<Tags, bigint, bigint, Completion> {
constructor(subscriber: (records: readonly Completion[]) => void) {
super('test', { raw: [null, { nested: true }] }, 1000n, subscriber)
}
setAttribute(key: string, value: unknown) {
this.setLocalAttribute(key, value)
}
end(time: bigint) {
this.finish(time)
}
protected onEnd(end: bigint) {
this.emit({
name: this.name,
start: this.startTime,
end,
tags: this.attributes,
})
}
}
const originalDevServer = process.env.__NEXT_DEV_SERVER
describe('shared local span recording', () => {
beforeEach(() => {
process.env.__NEXT_DEV_SERVER = '1'
initializeTraceState({ lastId: 0, shouldSaveTraceEvents: true })
clearTraceEvents()
setGlobal('distDir', undefined)
setGlobal('phase', undefined)
})
afterEach(() => {
jest.restoreAllMocks()
closeAllTraces()
setGlobal('distDir', undefined)
setGlobal('phase', undefined)
setSpanRecorderForTest(undefined)
setLocalSpanExporter(undefined)
if (originalDevServer === undefined) delete process.env.__NEXT_DEV_SERVER
else process.env.__NEXT_DEV_SERVER = originalDevServer
})
it('shares capture, attribute mutation, end-once and completion emission across both facades', () => {
const finish = jest.spyOn(LocalSpan.prototype as any, 'finish')
const mutate = jest.spyOn(LocalSpan.prototype as any, 'setLocalAttribute')
const emit = jest.spyOn(LocalSpan.prototype as any, 'emit')
const records: SpanStoreRecord[] = []
setSpanRecorderForTest((record) => records.push(record))
const tooling = new Span({ name: 'tooling', startTime: 1000n })
const request = createLocalSpan({
name: 'request',
startTime: 1700000000000,
})
expect(tooling).toBeInstanceOf(LocalSpan)
expect(request).toBeInstanceOf(LocalSpan)
tooling.setAttribute('value', { nested: [false, null] })
request.setAttribute('value', 'request-value')
tooling.stop(5000n)
request.end(1700000000010)
tooling.stop(9000n)
request.end(1700000000020)
expect(finish).toHaveBeenCalledTimes(4)
expect(mutate).toHaveBeenCalledTimes(2)
expect(emit).toHaveBeenCalledTimes(2)
expect(getTraceEvents()).toEqual([
expect.objectContaining({
name: 'tooling',
timestamp: 1,
duration: 4,
tags: { value: { nested: [false, null] } },
}),
])
expect(records).toEqual([
expect.objectContaining({
name: 'request',
startTime: 1700000000000,
durationMs: 10,
attributes: { value: 'request-value' },
}),
])
})
it('captures raw tags and clocks without OTel normalization', () => {
const records: Completion[] = []
const span = new TestSpan((batch) => records.push(...batch))
span.setAttribute('raw', {
array: [null, false, 3, 'four'],
unset: undefined,
})
span.end(9007199254740993123n)
span.end(9007199254740993999n)
expect(records).toEqual([
{
name: 'test',
start: 1000n,
end: 9007199254740993123n,
tags: { raw: { array: [null, false, 3, 'four'], unset: undefined } },
},
])
})
it('marks completion before notifying a reentrant or throwing subscriber', () => {
const error = new Error('subscriber failed')
const subscriber = jest.fn(() => {
span.end(3000n)
throw error
})
const span = new TestSpan(subscriber)
expect(() => span.end(2000n)).toThrow(error)
span.end(4000n)
expect(subscriber).toHaveBeenCalledTimes(1)
})
it('accepts completed batches without constructing live spans', () => {
const subscriber = jest.fn()
const records = [{ name: 'observed', originalTimestamp: 42 }]
emitLocalSpans(records, subscriber)
expect(subscriber).toHaveBeenCalledWith(records)
expect(subscriber.mock.calls[0][0]).toBe(records)
expect(() => emitLocalSpans(records, undefined)).not.toThrow()
})
it('writes legacy files directly without request recording or an application provider', async () => {
delete process.env.__NEXT_DEV_SERVER
const requestExporter = jest.fn()
setLocalSpanExporter({ isEnabled: () => true, export: requestExporter })
const dir = await mkdtemp(join(tmpdir(), 'shared-local-span-'))
try {
setGlobal('distDir', dir)
setGlobal('phase', PHASE_PRODUCTION_BUILD)
const span = new Span({
name: 'next-build',
startTime: 1234567890123456789n,
wallStartTimeMs: 1700000000000,
attrs: { object: { nested: [false, null, 3] }, unset: undefined },
})
span.setAttribute('null', null)
span.stop(1234567890123466789n)
flushAllTraces()
const expected = {
name: 'next-build',
id: 1,
timestamp: 1234567890123456,
duration: 10,
startTime: 1700000000000,
tags: { object: { nested: [false, null, 3] }, null: null },
}
for (const file of ['trace', 'trace-build']) {
const lines = readFileSync(join(dir, file), 'utf8').trim().split('\n')
const records = lines.flatMap((line) => JSON.parse(line))
expect(records).toEqual([expect.objectContaining(expected)])
}
expect(requestExporter).not.toHaveBeenCalled()
} finally {
closeAllTraces()
await rm(dir, { recursive: true, force: true })
}
})
it('does not broadcast tooling records into a scoped request sink', () => {
const sink = jest.fn()
const exporter = jest.fn()
setLocalSpanExporter({ isEnabled: () => true, export: exporter })
let request: ReturnType<typeof createLocalSpan>
runWithLocalSpanSink(sink, () => {
request = createLocalSpan({ name: 'scoped request' })
new Span({ name: 'tooling' }).stop()
})
request!.end()
expect(sink).toHaveBeenCalledTimes(1)
expect(sink).toHaveBeenCalledWith(
expect.objectContaining({ name: 'scoped request' })
)
expect(exporter).not.toHaveBeenCalled()
expect(getTraceEvents().map((record) => record.name)).toEqual(['tooling'])
})
it('keeps emitted request data after releasing the live span and ignoring late mutations', () => {
const records: SpanStoreRecord[] = []
setSpanRecorderForTest((record) => records.push(record))
const span = createLocalSpan({
name: 'request',
attributes: { initial: true },
})
span.addEvent('event', { value: 'captured' })
span.end()
span.updateName('late name').setAttribute('late', true)
expect(records[0]).toMatchObject({
name: 'request',
attributes: { initial: true },
events: [{ name: 'event', attributes: { value: 'captured' } }],
})
expect((span as any).name).toBe('')
expect((span as any).subscriber).toBeUndefined()
})
it('preserves the distinct post-end mutation policies of the facades', () => {
const records: SpanStoreRecord[] = []
setSpanRecorderForTest((record) => records.push(record))
const tooling = new Span({ name: 'tooling' })
const request = createLocalSpan({ name: 'request' })
tooling.stop()
request.end()
tooling.setAttribute('late', { raw: true })
request.setAttribute('late', true)
// Legacy saved tooling events retain the mutable tag object. Request
// completions survive reference release and reject subsequent API writes.
expect(getTraceEvents()[0].tags).toEqual({ late: { raw: true } })
expect(records[0].attributes).toBeUndefined()
})
it('emits locally and releases references even when a request delegate throws', () => {
const records: SpanStoreRecord[] = []
setSpanRecorderForTest((record) => records.push(record))
const error = new Error('delegate end failed')
const delegate = {
spanContext: () => ({ traceId: 'trace', spanId: 'span', traceFlags: 0 }),
end: jest.fn(() => {
throw error
}),
}
const request = createLocalSpan({
name: 'request',
delegateSpan: delegate as any,
})
const endTime: [number, number] = [1700000000, 123456789]
expect(() => request.end(endTime)).toThrow(error)
request.end()
expect(delegate.end).toHaveBeenCalledTimes(1)
expect(delegate.end).toHaveBeenCalledWith(endTime)
expect(records).toEqual([expect.objectContaining({ name: 'request' })])
expect((request as any).subscriber).toBeUndefined()
expect((request as any).delegateSpan).toBeUndefined()
})
it('retains scoped sink errors while releasing the ended request payload', () => {
const error = new Error('scoped sink failed')
let request: ReturnType<typeof createLocalSpan>
runWithLocalSpanSink(
() => {
throw error
},
() => {
request = createLocalSpan({
name: 'request',
attributes: { payload: 'released' },
})
}
)
expect(() => request!.end()).toThrow(error)
expect(request!.isRecording()).toBe(false)
expect((request! as any).attributes).toEqual({})
expect((request! as any).subscriber).toBeUndefined()
expect(() => request!.end()).not.toThrow()
})
it('preserves batch identity and ordering for imported request observations', () => {
const exporter = jest.fn()
setLocalSpanExporter({ isEnabled: () => true, export: exporter })
const records = [
{ name: 'browser first', timestamp: 1 },
{ name: 'browser second', timestamp: 2 },
]
recordSpans(records)
expect(exporter).toHaveBeenCalledTimes(1)
expect(exporter.mock.calls[0][0]).toBe(records)
})
it('imports completed tooling records with original timing and numeric parentage', () => {
const records = [
{
name: 'worker',
id: 20,
parentId: 2,
timestamp: 123,
duration: 4,
tags: { raw: [null, true] },
},
]
recordTraceEvents(records)
expect(getTraceEvents()).toEqual(records)
expect(new Span({ name: 'after import' }).getId()).toBe(22)
})
})
// Internal, synchronous local recording. No SDK, request context, feature gate,
// clock conversion or destination error policy belongs in this module.
export type LocalSpanSubscriber<Record> = (records: readonly Record[]) => void
// Observations received already completed (e.g. worker/browser batches) use the
// same delivery path without allocating artificial live spans or changing order.
export function emitLocalSpans<Record>(
records: readonly Record[],
subscriber: LocalSpanSubscriber<Record> | undefined
): void {
subscriber?.(records)
}
// Facades retain their native clocks and completion schemas: converting tooling
// bigint nanoseconds/raw tags to request milliseconds/API attributes is lossy.
export abstract class LocalSpan<
Attributes extends Record<string, unknown>,
StartTime,
EndTime,
Completion,
> {
protected ended = false
constructor(
protected name: string,
protected attributes: Attributes,
protected readonly startTime: StartTime,
protected subscriber: LocalSpanSubscriber<Completion> | undefined
) {}
protected setLocalAttribute(key: string, value: Attributes[string]): void {
this.attributes[key as keyof Attributes] = value
}
protected finish(endTime: EndTime): void {
if (this.ended) return
// Set before any destination/delegate call: reentrancy and throwing
// subscribers must not report a second completion.
this.ended = true
try {
this.onEnd(endTime)
} finally {
this.releaseReferences()
}
}
protected emit(record: Completion): void {
emitLocalSpans([record], this.subscriber)
}
// The facade defines timing/schema conversion and delegate ordering, not the
// shared recorder. In particular, request delegates end before local emission;
// tooling's deferred terminal metadata must survive a throwing local writer.
protected abstract onEnd(endTime: EndTime): void
protected releaseReferences(): void {}
}
......@@ -38,9 +38,12 @@ These are cooperative deadlines checked between SDK operations: a synchronous ap
**Dev shutdown:** the CLI normally gives its child only 100ms before SIGKILL. Set `NEXT_EXIT_TIMEOUT_MS` high enough for server cleanup, the deferred drain and the cooperative hook (the command above allows 11 seconds). SIGKILL, crashes and forced restarts cannot guarantee remote completion. Production server shutdown/request tracing is unchanged by this prototype.
## Two independent lanes
## Local recording and independent destinations
- **Local:** the tooling Span records directly through the existing JSON reporters, independently of any application delegate. Like Request Insights' local recorder, it does not need a private provider. Legacy safe numeric IDs, monotonic microseconds, epoch-millisecond wall start and arbitrary raw tags remain independent of SDK attribute limits. This spike leaves Request Insights' request-specific recorder/context handling unchanged.
`shared/lib/local-span.ts` is the shared, SDK-independent recording core for the tooling `Span` and Request Insights' API-compatible `LocalRecordingSpan`. It owns captured name/attributes/start time, attribute mutation, the end-once guard and synchronous completion delivery. The facades retain their native clocks, record schemas and destination/delegate ordering. Completed worker/browser observations enter the same delivery path without reconstructing live spans. This is internal plumbing, not an application subscription API.
- **Local files:** a simple local subscriber passes tooling completions directly to the existing JSON/build/telemetry reporters. It does not consume SDK spans, perform OTel normalization or depend on Request Insights, application registration or sampling. Legacy safe numeric IDs, monotonic microseconds, epoch-millisecond wall start and arbitrary raw tags remain independent of SDK attribute limits. Existing buffered file I/O is synchronous, not a promise of non-blocking recording.
- **Request Insights:** the request facade keeps request identity, API-compatible attributes/events/links, local context, SDK delegation and reference release outside the shared core. Its dev-only gate and creation-time scoped sink ownership remain request destination policy; tooling works independently during both dev and build. Sharing the core does not broadcast tooling records into request sinks/history or export local-only request observations to the application.
- **Application reporting:** the producer captures lightweight start metadata and one immutable JSON snapshot at completion, without calling the OTel API/SDK or mirroring attribute mutations. A single deferred consumer lazy-loads the API and uses the application's global tracer (`next.js.tooling`) with explicit ROOT-based parent contexts. It processes up to 64 records or 4 ms per turn, then yields; this is not guaranteed CPU-idle execution. No active application context, provider, sampler, context manager or propagator is replaced. Application sampling and attribute limits apply to this lane only. Structured/array legacy tags are represented as JSON-valued strings for OTel; null/undefined tags are omitted there, not from local data.
`.next/dev/trace`, `.next/trace` and filtered `.next/trace-build` retain their existing newline-delimited array format, session ID, numeric IDs/parents, event names/tags, integer-microsecond durations and buffering/rotation semantics. Custom output directories are supported. The writer uses append mode in dev, but **ordinary dev startup cleanup still removes the prior session's trace**, as before. The legacy upload flag and custom upload wire format remain unchanged; they are not OTLP.
......@@ -65,8 +68,8 @@ Failures before successful compilation/registration still flush local traces onc
## Verification
The development suites `hmr-trace-timing`, `enabled-features-trace` and `rage-restart-trace` establish the legacy file contract first; the same assertions run with the gate enabled on Webpack and Turbopack. `test/e2e/app-dir/otel-tooling` exercises a custom HTTP exporter, custom dist directory, original timing/parentage, compiler-worker export, provider identity, AlwaysOff independence, registration count and flush ordering. Parentage checks require either a completed export or matching live-span identity observed by the application's public processor; missing completed parents still fail. Focused replay tests prove zero inline SDK work, deferred sampler inputs, immutable payloads and metadata-only completion after payload loss, reserved-root storage bounds, direct late parents, worker ordering/redelivery/suppression, deep iterative traversal, one yielding consumer, session generations and separate final-drain/hook budgets. The existing writer/parser tests remain responsible for low-level buffered I/O and rotation edges.
The development suites `hmr-trace-timing`, `enabled-features-trace` and `rage-restart-trace` establish the legacy file contract first; the same assertions run with the gate enabled on Webpack and Turbopack. `test/e2e/app-dir/otel-tooling` exercises a custom HTTP exporter, custom dist directory, original timing/parentage, compiler-worker export, provider identity, AlwaysOff independence, registration count and flush ordering. Parentage checks require either a completed export or matching live-span identity observed by the application's public processor; missing completed parents still fail. The shared-core unit tests exercise both facades' common capture/end-once/delivery path, raw tags and native timing, direct file writing without request recording, completed imports, reentrant/throwing destinations, request sink isolation and payload lifetime. Focused replay tests prove zero inline SDK work, deferred sampler inputs, immutable payloads and metadata-only completion after payload loss, reserved-root storage bounds, direct late parents, worker ordering/redelivery/suppression, deep iterative traversal, one yielding consumer, session generations and separate final-drain/hook budgets. The existing writer/parser tests remain responsible for low-level buffered I/O and rotation edges.
This flag is for dev/build tooling, not an additional `next start` reporting mode. Production request tracing continues to use the existing instrumentation lifecycle; do not carry the prototype flag into a production deployment. Generalizing Request Insights and tooling recorders is separate work.
This flag is for dev/build tooling, not an additional `next start` reporting mode. Production request tracing continues to use the existing instrumentation lifecycle; do not carry the prototype flag into a production deployment. The shared local core changes neither production request SDK delegation nor the optional tooling adapter's external hierarchy.
The framework adds no SDK provider or SDK dependency; it uses the OTel API only in the deferred consumer, without requiring a particular application SDK version. Start/attribute producer paths avoid SDK/normalization work, but the extra JSON snapshot at completion is real producer cost. Deferred SDK work, allocation and export costs still exist, particularly for per-module profiling. Full-scale performance review is required before considering a default rollout.
import { reporter } from './report'
import { LocalSpan, emitLocalSpans } from '../shared/lib/local-span'
import type { SpanId, TraceEvent, TraceState } from './types'
import type { ReportingRecord } from './otel-reporting'
......@@ -38,18 +39,23 @@ interface Attributes {
[key: string]: unknown
}
export class Span {
private name: string
// Direct local subscriber: the reporters consume the original tooling schema,
// independently of request diagnostics and the optional deferred SDK adapter.
function reportToolingSpans(events: readonly TraceEvent[]): void {
for (const event of events) reporter.report(event)
}
export class Span extends LocalSpan<
Attributes,
bigint,
bigint | undefined,
TraceEvent
> {
private reporting?: ReportingRecord
private id: SpanId
private parentId?: SpanId
private attrs: { [key: string]: unknown }
private status: SpanStatus
private now: number
// Monotonic nanoseconds from process.hrtime.bigint().
private _start: bigint
constructor({
name,
parentId,
......@@ -70,13 +76,14 @@ export class Span {
// Internal entry-point marker: reserves the coordinator root descriptor.
reportingRoot?: boolean
}) {
super(
name,
attrs ? { ...attrs } : {},
startTime || process.hrtime.bigint(),
reportToolingSpans
)
this.id = getId()
this.parentId = parentId ?? defaultParentSpanId
this.name = name
this.attrs = attrs ? { ...attrs } : {}
this.status = SpanStatus.Started
this._start = startTime || process.hrtime.bigint()
// hrtime cannot be used to reconstruct tracing span's actual start time
// since it does not have relation to clock time:
// `These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift`
......@@ -87,7 +94,7 @@ export class Span {
name,
id: this.id,
parentId: this.parentId,
startTime: this._start,
startTime: this.startTime,
reportingParent,
reportingRoot,
})
......@@ -98,36 +105,34 @@ export class Span {
// Additionally, ~285 years can be safely represented as microseconds as
// a float64 in both JSON and JavaScript.
stop(stopTime?: bigint) {
if (this.status === SpanStatus.Stopped) {
// Don't report the same span twice.
// TODO: In the future this should throw as `.stop()` shouldn't be called multiple times.
return
}
this.finish(stopTime)
}
protected onEnd(stopTime: bigint | undefined): void {
const end: bigint = stopTime || process.hrtime.bigint()
const duration = (end - this._start) / NUM_OF_MICROSEC_IN_NANOSEC
this.status = SpanStatus.Stopped
const duration = (end - this.startTime) / NUM_OF_MICROSEC_IN_NANOSEC
if (duration > Number.MAX_SAFE_INTEGER) {
throw new Error(`Duration is too long to express as float64: ${duration}`)
}
const timestamp = this._start / NUM_OF_MICROSEC_IN_NANOSEC
const timestamp = this.startTime / NUM_OF_MICROSEC_IN_NANOSEC
const traceEvent: TraceEvent = {
name: this.name,
duration: Number(duration),
timestamp: Number(timestamp),
id: this.id,
parentId: this.parentId,
tags: this.attrs,
tags: this.attributes,
startTime: this.now,
}
try {
if (duration > RECORD_SPAN_THRESHOLD_MS * 1000) {
reporter.report(traceEvent)
this.emit(traceEvent)
if (shouldSaveTraceEvents) {
savedTraceEvents.push(traceEvent)
}
}
} finally {
otel?.stopSpan(this.reporting, end, this.attrs)
otel?.stopSpan(this.reporting, end, this.attributes)
}
}
......@@ -172,7 +177,7 @@ export class Span {
}
setAttribute(key: string, value: unknown) {
this.attrs[key] = value
this.setLocalAttribute(key, value)
}
traceFn<T>(fn: (span: Span) => T): T {
......@@ -248,7 +253,7 @@ export function getTraceEvents(): TraceEvent[] {
export function recordTraceEvents(events: TraceEvent[]) {
if (otel) events = otel.freshWorkerEvents(events)
for (const traceEvent of events) {
reporter.report(traceEvent)
emitLocalSpans([traceEvent], reportToolingSpans)
if (traceEvent.id > count) {
count = traceEvent.id + 1
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment