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

Bound browser React timing collection per request

Co-authored-by: 's avatarDavid Ilie <david@davidilie.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent a4ca892f
...@@ -1043,7 +1043,7 @@ function ReactRenderPass({ ...@@ -1043,7 +1043,7 @@ function ReactRenderPass({
const incompleteMessage = group.incompleteReason const incompleteMessage = group.incompleteReason
? group.incompleteReason === 'budget' ? group.incompleteReason === 'budget'
? 'Recording limit reached. Some React intervals are missing.' ? 'Recording limit reached. Some React intervals are missing.'
: 'Some React intervals could not be decoded.' : 'Some React intervals were dropped during recording or transport.'
: undefined : undefined
return ( return (
......
...@@ -3,12 +3,12 @@ import { ...@@ -3,12 +3,12 @@ import {
decoderConsole, decoderConsole,
decoderPerformance, decoderPerformance,
decoderSetTimeout, decoderSetTimeout,
} from '../../../../packages/next/src/client/dev/react-decoder-host' } from '../../../client/dev/react-decoder-host'
import { import {
createBrowserReactTiming, createBrowserReactTiming,
setReactTimingSender, setReactTimingSender,
} from '../../../../packages/next/src/client/dev/react-render-timing' } from '../../../client/dev/react-render-timing'
import { createBrowserReactTimingReceiver } from '../../../../packages/next/src/server/lib/trace/browser-react-timings' import { createBrowserReactTimingReceiver } from './browser-react-timings'
import { import {
clearRequestInsightsForTest, clearRequestInsightsForTest,
completeRequestInsight, completeRequestInsight,
...@@ -16,15 +16,15 @@ import { ...@@ -16,15 +16,15 @@ import {
registerRequestInsightsExporter, registerRequestInsightsExporter,
setRequestInsightRootParent, setRequestInsightRootParent,
startRequestInsight, startRequestInsight,
} from '../../../../packages/next/src/server/lib/trace/request-insights' } from './request-insights'
import { import {
recordSpan, recordSpan,
setSpanRecorderForTest, setSpanRecorderForTest,
type SpanStoreRecord, type SpanStoreRecord,
} from '../../../../packages/next/src/server/lib/trace/span-store' } from './span-store'
import { NEXT_REQUEST_ID_HEADER } from '../../../../packages/next/src/client/components/app-router-headers' import { NEXT_REQUEST_ID_HEADER } from '../../../client/components/app-router-headers'
import { HMR_MESSAGE_SENT_TO_SERVER } from '../../../../packages/next/src/server/dev/hot-reloader-types' import { HMR_MESSAGE_SENT_TO_SERVER } from '../../dev/hot-reloader-types'
import { MAX_LIVE_COMPLETED_REQUEST_INSIGHTS } from '../../../../packages/next/src/shared/lib/request-insights' import { MAX_LIVE_COMPLETED_REQUEST_INSIGHTS } from '../../../shared/lib/request-insights'
const originalDevServer = process.env.__NEXT_DEV_SERVER const originalDevServer = process.env.__NEXT_DEV_SERVER
const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS const originalRequestInsights = process.env.__NEXT_REQUEST_INSIGHTS
...@@ -147,6 +147,90 @@ describe('browser React timing transport', () => { ...@@ -147,6 +147,90 @@ describe('browser React timing transport', () => {
]) ])
}) })
it('does not replay records after reconnecting', () => {
start()
setRequestInsightRootParent(
{ requestId: 'server-owned' },
{ traceId: 'server-trace', spanId: 'server-parent' }
)
const first = receiver()
first.receive(message(), 1000)
completeRequestInsight({ requestId: 'server-owned' })
first.dispose()
receiver().receive(message(), 1000)
expect(spans).toHaveLength(1)
receiver().receive(message({ id: 'decoded:1' }), 1000)
expect(spans).toHaveLength(2)
})
it('limits browser records for the whole request, across reconnects and time windows', () => {
jest.useFakeTimers({ doNotFake: ['performance'] })
start()
finish()
spans.length = 0
const first = receiver()
for (let batch = 0; batch < 257; batch++) {
const records = Array.from(
{ length: 32 },
(_, i) => message({ id: `decoded:${batch * 32 + i}` }).records[0]
)
first.receive({ ...message(), records }, 32_000)
}
expect(
spans.filter((span) => span.name === 'ReactServerComponents.component')
).toHaveLength(8192)
expect(
spans.filter((span) => span.name === 'ReactServerComponents.incomplete')
).toHaveLength(1)
first.dispose()
jest.advanceTimersByTime(60_001)
const second = receiver()
const count = spans.length
second.receive({ ...message(), decoderId: '1' }, 1000)
second.receive(message({ id: 'decoded:9000' }), 1000)
expect(spans).toHaveLength(count)
})
it('bounds retained UTF-8 bytes as well as the number of records', () => {
start()
finish()
spans.length = 0
const ingest = receiver()
for (let i = 0; i < 1000; i++) {
ingest.receive(
message({
id: `decoded:${i}`,
name: '界'.repeat(256),
componentPath: '界'.repeat(2048),
source: {
file: '界'.repeat(2048),
line: 1,
column: 1,
methodName: 'Page',
},
}),
32_000
)
}
const timings = spans.filter(
(span) => span.name === 'ReactServerComponents.component'
)
expect(timings.length).toBeGreaterThan(0)
expect(timings.length).toBeLessThan(1000)
expect(
timings.reduce(
(bytes, span) => bytes + Buffer.byteLength(JSON.stringify(span)),
0
)
).toBeLessThanOrEqual(8 * 1024 * 1024)
expect(
spans.filter((span) => span.name === 'ReactServerComponents.incomplete')
).toHaveLength(1)
const count = spans.length
receiver().receive({ ...message(), decoderId: '1' }, 1000)
expect(spans).toHaveLength(count)
})
it('accepts initial HTML timings only from that document connection', () => { it('accepts initial HTML timings only from that document connection', () => {
startRequestInsight({ startRequestInsight({
requestId: 'html-owned', requestId: 'html-owned',
...@@ -214,7 +298,7 @@ describe('browser React timing transport', () => { ...@@ -214,7 +298,7 @@ describe('browser React timing transport', () => {
}) })
}) })
it('continues accepting decoders beyond the recent decoder window', () => { it('bounds decoder state without evicting replay protection', () => {
start() start()
finish() finish()
spans.length = 0 spans.length = 0
...@@ -222,7 +306,14 @@ describe('browser React timing transport', () => { ...@@ -222,7 +306,14 @@ describe('browser React timing transport', () => {
for (let i = 0; i < 130; i++) { for (let i = 0; i < 130; i++) {
ingest.receive({ ...message(), decoderId: String(i) }, 1000) ingest.receive({ ...message(), decoderId: String(i) }, 1000)
} }
expect(spans).toHaveLength(130) expect(
spans.filter((span) => span.name === 'ReactServerComponents.component')
).toHaveLength(128)
expect(
spans.filter((span) => span.name === 'ReactServerComponents.incomplete')
).toHaveLength(1)
receiver().receive(message(), 1000)
expect(spans).toHaveLength(129)
}) })
it('marks bounded client transport loss as partial observation', () => { it('marks bounded client transport loss as partial observation', () => {
...@@ -253,7 +344,10 @@ describe('browser React timing transport', () => { ...@@ -253,7 +344,10 @@ describe('browser React timing transport', () => {
spans.find((span) => span.name === 'ReactServerComponents.incomplete') spans.find((span) => span.name === 'ReactServerComponents.incomplete')
).toMatchObject({ ).toMatchObject({
parentSpanId: 'server-parent', parentSpanId: 'server-parent',
attributes: { 'next.rsc.observation_partial': true }, attributes: {
'next.rsc.observation_partial': true,
'next.rsc.incomplete_reason': 'transport',
},
}) })
}) })
...@@ -270,27 +364,20 @@ describe('browser React timing transport', () => { ...@@ -270,27 +364,20 @@ describe('browser React timing transport', () => {
expect(spans).toEqual([]) expect(spans).toEqual([])
}) })
it('bounds empty partial messages after the transport rate limit', () => { it('reports transport loss only once per request, including across reconnects', () => {
start() start()
finish() finish()
spans.length = 0 spans.length = 0
const ingest = receiver() const ingest = receiver()
const payload = message() const payload = message()
for (let i = 0; i < 256; i++) { ingest.receive(payload, 1000)
ingest.receive(
{ ...payload, records: Array(32).fill(payload.records[0]) },
10_000
)
}
ingest.receive( ingest.receive(
{ ...payload, decoderId: '1', partial: true, records: [] }, { ...payload, decoderId: '1', partial: true, records: [] },
1000 1000
) )
expect(spans).toHaveLength(1)
ingest.receive(payload, 1000)
expect(spans).toHaveLength(2) expect(spans).toHaveLength(2)
expect(spans[1].name).toBe('ReactServerComponents.incomplete') expect(spans[1].name).toBe('ReactServerComponents.incomplete')
ingest.receive( receiver().receive(
{ ...payload, decoderId: '2', partial: true, records: [] }, { ...payload, decoderId: '2', partial: true, records: [] },
1000 1000
) )
...@@ -434,8 +521,8 @@ describe('browser React timing transport', () => { ...@@ -434,8 +521,8 @@ describe('browser React timing transport', () => {
await Promise.all([a, b]) await Promise.all([a, b])
await new Promise<void>((resolve) => setTimeout(resolve, 0)) await new Promise<void>((resolve) => setTimeout(resolve, 0))
expect( expect(
send.mock.calls.map(([message]) => { send.mock.calls.map(([payload]) => {
const parsed = JSON.parse(message) const parsed = JSON.parse(payload)
return [parsed.requestId, parsed.records[0].name] return [parsed.requestId, parsed.records[0].name]
}) })
).toEqual([ ).toEqual([
...@@ -499,12 +586,12 @@ describe('browser React timing transport', () => { ...@@ -499,12 +586,12 @@ describe('browser React timing transport', () => {
) )
}) })
jest.runAllTimers() jest.runAllTimers()
const message = send.mock.calls[0][0] const payload = send.mock.calls[0][0]
expect( expect(
JSON.parse(message).records.map((record: { name: string }) => record.name) JSON.parse(payload).records.map((record: { name: string }) => record.name)
).toEqual(['Component', 'async work']) ).toEqual(['Component', 'async work'])
expect(message).not.toContain('secret') expect(payload).not.toContain('secret')
expect(message).not.toContain('password') expect(payload).not.toContain('password')
console.timeStamp = timeStamp console.timeStamp = timeStamp
}) })
......
...@@ -17,11 +17,22 @@ import { ...@@ -17,11 +17,22 @@ import {
} from './request-insights' } from './request-insights'
import { createReactTimingSpanRecords } from './react-render-timing' import { createReactTimingSpanRecords } from './react-render-timing'
import { createLocalSpanId } from './local-span-recorder' import { createLocalSpanId } from './local-span-recorder'
import { recordSpans } from './span-store' import { recordSpans, type SpanStoreRecord } from './span-store'
const MAX_REQUEST_RECORDS = 8192
const MAX_REQUEST_BYTES = 8 * 1024 * 1024
const MAX_REQUEST_DECODERS = 128
type Decoder = { type Decoder = {
renderId: string renderId: string
highestRecordId: number highestRecordId: number
}
export type BrowserReactTimingState = {
decoders: Map<string, Decoder>
recordCount: number
byteLength: number
exhausted: boolean
partialReported: boolean partialReported: boolean
} }
...@@ -30,13 +41,12 @@ export function createBrowserReactTimingReceiver( ...@@ -30,13 +41,12 @@ export function createBrowserReactTimingReceiver(
enabled: boolean enabled: boolean
) { ) {
const documentId = getValidatedDevHtmlRequestId(htmlRequestId ?? undefined) const documentId = getValidatedDevHtmlRequestId(htmlRequestId ?? undefined)
const decoders = new Map<string, Decoder>() let disposed = false
let received = 0
let windowStart = Date.now()
return { return {
receive(value: unknown, messageLength: number) { receive(value: unknown, messageLength: number) {
if ( if (
disposed ||
!enabled || !enabled ||
!documentId || !documentId ||
!isRequestInsightsEnabled() || !isRequestInsightsEnabled() ||
...@@ -69,37 +79,29 @@ export function createBrowserReactTimingReceiver( ...@@ -69,37 +79,29 @@ export function createBrowserReactTimingReceiver(
documentId documentId
) )
if (!target?.parent) return if (!target?.parent) return
const { identity, insight, parent } = target const { identity, insight, parent, browserTimings: state } = target
if (state.exhausted) return
const now = Date.now() let decoder = state.decoders.get(message.decoderId)
if (now - windowStart >= 60_000) {
windowStart = now
received = 0
}
received += Math.max(1, message.records.length)
const key = `${identity.requestId}:${message.decoderId}`
let decoder = decoders.get(key)
const rateLimited = received > 8192
if (rateLimited && !decoder) return
if (!decoder) { if (!decoder) {
if (decoders.size >= 128) { if (state.decoders.size >= MAX_REQUEST_DECODERS) {
decoders.delete(decoders.keys().next().value!) state.exhausted = true
} } else {
decoder = { decoder = {
renderId: createLocalSpanId(), renderId: createLocalSpanId(),
highestRecordId: -1, highestRecordId: -1,
partialReported: false, }
state.decoders.set(message.decoderId, decoder)
} }
} else {
decoders.delete(key)
} }
decoders.set(key, decoder)
const records: ReactTimingRecord[] = [] const records: ReactTimingRecord[] = []
if (!rateLimited) { if (decoder) {
for (const record of message.records) { for (const record of message.records) {
const id = Number(record.id.slice(8)) const id = Number(record.id.slice(8))
if (id <= decoder.highestRecordId) continue if (id <= decoder.highestRecordId) continue
if (state.recordCount + records.length >= MAX_REQUEST_RECORDS) {
state.exhausted = true
break
}
decoder.highestRecordId = id decoder.highestRecordId = id
records.push(copyBrowserReactTimingRecord(record)) records.push(copyBrowserReactTimingRecord(record))
} }
...@@ -115,13 +117,25 @@ export function createBrowserReactTimingReceiver( ...@@ -115,13 +117,25 @@ export function createBrowserReactTimingReceiver(
traceId: parent.traceId, traceId: parent.traceId,
parentSpanId: parent.spanId, parentSpanId: parent.spanId,
} }
const spans = createReactTimingSpanRecords( const spans: SpanStoreRecord[] = []
records, if (decoder) {
context, for (const span of createReactTimingSpanRecords(
decoder.renderId records,
) context,
if ((message.partial || rateLimited) && !decoder.partialReported) { decoder.renderId
decoder.partialReported = true )) {
const bytes = Buffer.byteLength(JSON.stringify(span), 'utf8')
if (state.byteLength + bytes > MAX_REQUEST_BYTES) {
state.exhausted = true
break
}
state.byteLength += bytes
state.recordCount++
spans.push(span)
}
}
if ((message.partial || state.exhausted) && !state.partialReported) {
state.partialReported = true
spans.push({ spans.push({
...context, ...context,
name: 'ReactServerComponents.incomplete', name: 'ReactServerComponents.incomplete',
...@@ -131,16 +145,19 @@ export function createBrowserReactTimingReceiver( ...@@ -131,16 +145,19 @@ export function createBrowserReactTimingReceiver(
'next.span_type': 'ReactServerComponents.incomplete', 'next.span_type': 'ReactServerComponents.incomplete',
'next.span_name': 'Some decoded React observations were dropped', 'next.span_name': 'Some decoded React observations were dropped',
'next.span_category': 'application', 'next.span_category': 'application',
'next.rsc.render_id': decoder.renderId, 'next.rsc.render_id': decoder?.renderId ?? createLocalSpanId(),
'next.rsc.observation': 'decoded', 'next.rsc.observation': 'decoded',
'next.rsc.observation_partial': true, 'next.rsc.observation_partial': true,
'next.rsc.incomplete_reason': state.exhausted
? 'budget'
: 'transport',
}, },
}) })
} }
if (spans.length > 0) recordSpans(spans) if (spans.length > 0) recordSpans(spans)
}, },
dispose() { dispose() {
decoders.clear() disposed = true
}, },
} }
} }
...@@ -26,14 +26,10 @@ import { ...@@ -26,14 +26,10 @@ import {
resetRequestInsightsJournalForTest, resetRequestInsightsJournalForTest,
StaleRequestInsightsHistoryCursorError, StaleRequestInsightsHistoryCursorError,
} from './request-insights-journal' } from './request-insights-journal'
import { recordSpan, recordSpans } from './span-store' import { recordSpan } from './span-store'
import { createReactTimingSpanRecords } from './react-render-timing'
import { createBrowserReactTimingReceiver } from './browser-react-timings' import { createBrowserReactTimingReceiver } from './browser-react-timings'
import { HMR_MESSAGE_SENT_TO_SERVER } from '../../dev/hot-reloader-types' import { HMR_MESSAGE_SENT_TO_SERVER } from '../../dev/hot-reloader-types'
import { import { registerLocalSpanRecorder } from './local-span-recorder'
captureLocalSpanContext,
registerLocalSpanRecorder,
} from './local-span-recorder'
import { AppRenderSpan } from './constants' import { AppRenderSpan } from './constants'
import { getTracer } from './tracer' import { getTracer } from './tracer'
import { import {
...@@ -930,12 +926,10 @@ describe('request insights', () => { ...@@ -930,12 +926,10 @@ describe('request insights', () => {
await initializeRequestInsightsJournal(distDir) await initializeRequestInsightsJournal(distDir)
configureJournalProvider(distDir) configureJournalProvider(distDir)
startRequestInsight(identity) startRequestInsight(identity)
let context!: ReturnType<typeof captureLocalSpanContext>
let parentSpanId!: string let parentSpanId!: string
runWithRequestInsightsIdentity(identity, () => runWithRequestInsightsIdentity(identity, () =>
getTracer().trace(AppRenderSpan.renderToReadableStream, (span) => { getTracer().trace(AppRenderSpan.renderToReadableStream, (span) => {
parentSpanId = span!.spanContext().spanId parentSpanId = span!.spanContext().spanId
context = captureLocalSpanContext(span!.spanContext())
setRequestInsightRootParent(identity, span!.spanContext()) setRequestInsightRootParent(identity, span!.spanContext())
}) })
) )
...@@ -961,7 +955,23 @@ describe('request insights', () => { ...@@ -961,7 +955,23 @@ describe('request insights', () => {
startTime: 2, startTime: 2,
durationMs: 3, durationMs: 3,
} }
recordSpans(createReactTimingSpanRecords([component], context, 'render')) const firstReceiver = createBrowserReactTimingReceiver(
'react-stream',
true
)
const firstMessage = {
event: HMR_MESSAGE_SENT_TO_SERVER.REACT_DEBUG_TIMINGS,
requestId: 'react-stream',
decoderId: '0',
records: [component],
}
firstReceiver.receive(firstMessage, JSON.stringify(firstMessage).length)
firstReceiver.dispose()
const budget = getRequestInsightForDebugRequest(
'react-stream',
'react-stream'
)!.browserTimings
expect(budget.recordCount).toBe(1)
expect(getRequestInsightsSnapshot().requests[0]).toMatchObject({ expect(getRequestInsightsSnapshot().requests[0]).toMatchObject({
...responseTiming, ...responseTiming,
spans: expect.arrayContaining([ spans: expect.arrayContaining([
...@@ -978,11 +988,20 @@ describe('request insights', () => { ...@@ -978,11 +988,20 @@ describe('request insights', () => {
expect( expect(
getRequestInsightForDebugRequest('react-stream', 'react-stream') getRequestInsightForDebugRequest('react-stream', 'react-stream')
).toMatchObject({ parent: { spanId: parentSpanId } }) ).toMatchObject({ parent: { spanId: parentSpanId } })
expect(
getRequestInsightForDebugRequest('react-stream', 'react-stream')!
.browserTimings
).toBe(budget)
await readRequestInsightsJournal(distDir, identity) await readRequestInsightsJournal(distDir, identity)
expect( expect(
getRequestInsightForDebugRequest('react-stream', 'react-stream') getRequestInsightForDebugRequest('react-stream', 'react-stream')
).toMatchObject({ parent: { spanId: parentSpanId } }) ).toMatchObject({ parent: { spanId: parentSpanId } })
const receiver = createBrowserReactTimingReceiver('react-stream', true) const receiver = createBrowserReactTimingReceiver('react-stream', true)
expect(
getRequestInsightForDebugRequest('react-stream', 'react-stream')!
.browserTimings
).toBe(budget)
receiver.receive(firstMessage, JSON.stringify(firstMessage).length)
const message = { const message = {
event: HMR_MESSAGE_SENT_TO_SERVER.REACT_DEBUG_TIMINGS, event: HMR_MESSAGE_SENT_TO_SERVER.REACT_DEBUG_TIMINGS,
requestId: 'react-stream', requestId: 'react-stream',
...@@ -991,6 +1010,7 @@ describe('request insights', () => { ...@@ -991,6 +1010,7 @@ describe('request insights', () => {
} }
receiver.receive(message, JSON.stringify(message).length) receiver.receive(message, JSON.stringify(message).length)
receiver.dispose() receiver.dispose()
expect(budget.recordCount).toBe(2)
const [stored] = await readRequestInsightsJournal(distDir, identity) const [stored] = await readRequestInsightsJournal(distDir, identity)
expect(stored).toMatchObject(responseTiming) expect(stored).toMatchObject(responseTiming)
......
...@@ -30,6 +30,7 @@ import type { ...@@ -30,6 +30,7 @@ import type {
import type { RequestInsightsIdentity } from './request-insights-identity' import type { RequestInsightsIdentity } from './request-insights-identity'
import { reparentLocalSpans } from './local-span-recorder' import { reparentLocalSpans } from './local-span-recorder'
import { AppRenderSpan } from './constants' import { AppRenderSpan } from './constants'
import type { BrowserReactTimingState } from './browser-react-timings'
export { isRequestInsightsEnabled } export { isRequestInsightsEnabled }
const MAX_REQUEST_INSIGHT_URL_LENGTH = 2048 const MAX_REQUEST_INSIGHT_URL_LENGTH = 2048
...@@ -50,6 +51,7 @@ export type RequestInsightDebugContext = { ...@@ -50,6 +51,7 @@ export type RequestInsightDebugContext = {
debugRequestId: string debugRequestId: string
identity: DebugRequestIdentity & { requestId: string } identity: DebugRequestIdentity & { requestId: string }
parent: LocalSpanParent | undefined parent: LocalSpanParent | undefined
browserTimings: BrowserReactTimingState
} }
type RequestInsightsListener = (insight: RequestInsight) => void type RequestInsightsListener = (insight: RequestInsight) => void
...@@ -147,10 +149,9 @@ class InMemoryRequestInsightsStore { ...@@ -147,10 +149,9 @@ class InMemoryRequestInsightsStore {
private readonly completedRequestOrder: string[] = [] private readonly completedRequestOrder: string[] = []
private readonly listeners = new Set<RequestInsightsListener>() private readonly listeners = new Set<RequestInsightsListener>()
private readonly debugRequestKeys = new Map<string, string>() private readonly debugRequestKeys = new Map<string, string>()
private readonly debugRequestParents = new Map<string, LocalSpanParent>()
private readonly debugRequests = new Map< private readonly debugRequests = new Map<
string, string,
{ requests: Map<string, DebugRequestIdentity>; ambiguous: boolean } { requests: Map<string, RequestInsightDebugContext>; ambiguous: boolean }
>() >()
startRequest(identity: DebugRequestIdentity): void { startRequest(identity: DebugRequestIdentity): void {
...@@ -180,7 +181,23 @@ class InMemoryRequestInsightsStore { ...@@ -180,7 +181,23 @@ class InMemoryRequestInsightsStore {
if (entry.requests.size > 0 && !entry.requests.has(insightKey)) { if (entry.requests.size > 0 && !entry.requests.has(insightKey)) {
entry.ambiguous = true entry.ambiguous = true
} }
entry.requests.set(insightKey, identity) const context = entry.requests.get(insightKey)
if (context) {
context.identity = { ...identity, requestId: identity.requestId }
} else {
entry.requests.set(insightKey, {
debugRequestId,
identity: { ...identity, requestId: identity.requestId },
parent: undefined,
browserTimings: {
decoders: new Map(),
recordCount: 0,
byteLength: 0,
exhausted: false,
partialReported: false,
},
})
}
this.debugRequestKeys.set(insightKey, debugKey) this.debugRequestKeys.set(insightKey, debugKey)
} }
if (this.requests.get(insightKey)?.completedAt === undefined) { if (this.requests.get(insightKey)?.completedAt === undefined) {
...@@ -380,14 +397,13 @@ class InMemoryRequestInsightsStore { ...@@ -380,14 +397,13 @@ class InMemoryRequestInsightsStore {
if (archived === null) return undefined if (archived === null) return undefined
if (!entry) return archived && { ...archived, insight: undefined } if (!entry) return archived && { ...archived, insight: undefined }
if (entry.requests.size !== 1) return undefined if (entry.requests.size !== 1) return undefined
const [insightKey, identity] = entry.requests.entries().next().value! const [insightKey, context] = entry.requests.entries().next().value!
if (archived && getRequestInsightKey(archived.identity) !== insightKey) { if (archived && getRequestInsightKey(archived.identity) !== insightKey) {
return undefined return undefined
} }
return { return {
identity, ...context,
insight: this.requests.get(insightKey), insight: this.requests.get(insightKey),
parent: this.debugRequestParents.get(insightKey),
} }
} }
...@@ -406,11 +422,14 @@ class InMemoryRequestInsightsStore { ...@@ -406,11 +422,14 @@ class InMemoryRequestInsightsStore {
requestId: identity.requestId, requestId: identity.requestId,
kind: identity.kind, kind: identity.kind,
}) })
if (this.debugRequestKeys.has(key) && !this.debugRequestParents.has(key)) { const debugKey = this.debugRequestKeys.get(key)
this.debugRequestParents.set(key, { const context =
debugKey && this.debugRequests.get(debugKey)?.requests.get(key)
if (context && !context.parent) {
context.parent = {
traceId: parent.traceId, traceId: parent.traceId,
spanId: parent.spanId, spanId: parent.spanId,
}) }
} }
} }
...@@ -428,7 +447,6 @@ class InMemoryRequestInsightsStore { ...@@ -428,7 +447,6 @@ class InMemoryRequestInsightsStore {
this.requestOrder.length = 0 this.requestOrder.length = 0
this.completedRequestOrder.length = 0 this.completedRequestOrder.length = 0
this.debugRequestKeys.clear() this.debugRequestKeys.clear()
this.debugRequestParents.clear()
this.debugRequests.clear() this.debugRequests.clear()
} }
...@@ -559,24 +577,17 @@ class InMemoryRequestInsightsStore { ...@@ -559,24 +577,17 @@ class InMemoryRequestInsightsStore {
insight.completedAt = completedAt insight.completedAt = completedAt
this.completedRequestOrder.push(insightKey) this.completedRequestOrder.push(insightKey)
const completedDebugKey = this.debugRequestKeys.get(insightKey) const completedDebugKey = this.debugRequestKeys.get(insightKey)
const identity = const debugContext =
completedDebugKey && completedDebugKey &&
this.debugRequests.get(completedDebugKey)?.requests.get(insightKey) this.debugRequests.get(completedDebugKey)?.requests.get(insightKey)
appendCompletedRequestInsight( if (debugContext) {
insight, debugContext.identity = {
identity ...debugContext.identity,
? { route: insight.route,
debugRequestId: identity.debugRequestId ?? identity.requestId!, url: insight.url,
identity: { }
...identity, }
requestId: insight.requestId, appendCompletedRequestInsight(insight, debugContext || undefined)
route: insight.route,
url: insight.url,
},
parent: this.debugRequestParents.get(insightKey),
}
: undefined
)
const requestIndex = this.requestOrder.indexOf(insightKey) const requestIndex = this.requestOrder.indexOf(insightKey)
if (requestIndex !== -1) { if (requestIndex !== -1) {
...@@ -595,7 +606,6 @@ class InMemoryRequestInsightsStore { ...@@ -595,7 +606,6 @@ class InMemoryRequestInsightsStore {
entry?.requests.delete(completedInsightKey) entry?.requests.delete(completedInsightKey)
if (entry?.requests.size === 0) this.debugRequests.delete(debugKey) if (entry?.requests.size === 0) this.debugRequests.delete(debugKey)
this.debugRequestKeys.delete(completedInsightKey) this.debugRequestKeys.delete(completedInsightKey)
this.debugRequestParents.delete(completedInsightKey)
} }
this.requests.delete(completedInsightKey) this.requests.delete(completedInsightKey)
this.requestTimings.delete(completedInsightKey) this.requestTimings.delete(completedInsightKey)
......
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