@@ -260,6 +260,11 @@ function addHTTPTimings(span: Span, client: Client): void {
260260 return ;
261261 }
262262
263+ // Clean up the performance observer and other resources
264+ // We have to wait here because otherwise this cleans itself up before it is fully done.
265+ // Default (non-streaming): just deregister the observer.
266+ let onEntryFound = ( ) : void => void setTimeout ( cleanup ) ;
267+
263268 // For streamed spans, we have to artificially delay the ending of the span until we
264269 // either receive the timing data, or HTTP_TIMING_WAIT_MS elapses.
265270 if ( hasSpanStreamingEnabled ( client ) ) {
@@ -276,36 +281,24 @@ function addHTTPTimings(span: Span, client: Client): void {
276281 return ;
277282 }
278283 isEnded = true ;
279- // In the next tick, clean up the performance observer
280- // We have to wait here because otherwise we clean it up before it is fully done
281284 setTimeout ( cleanup ) ;
282285 originalEnd ( capturedEndTimestamp ) ;
283286 clearTimeout ( fallbackTimeout ) ;
284287 } ;
285288
286- const cleanup = addPerformanceInstrumentationHandler ( 'resource' , ( { entries } ) => {
287- entries . forEach ( entry => {
288- if ( isPerformanceResourceTiming ( entry ) && entry . name . endsWith ( url ) ) {
289- span . setAttributes ( resourceTimingToSpanAttributes ( entry ) ) ;
290- endSpanAndCleanup ( ) ;
291- }
292- } ) ;
293- } ) ;
289+ onEntryFound = endSpanAndCleanup ;
294290
295291 // Fallback: always end the span after HTTP_TIMING_WAIT_MS even if no
296292 // PerformanceResourceTiming entry arrives (e.g. cross-origin without
297293 // Timing-Allow-Origin, or the browser didn't fire the observer in time).
298294 const fallbackTimeout = setTimeout ( endSpanAndCleanup , HTTP_TIMING_WAIT_MS ) ;
299- return ;
300295 }
301296
302297 const cleanup = addPerformanceInstrumentationHandler ( 'resource' , ( { entries } ) => {
303298 entries . forEach ( entry => {
304299 if ( isPerformanceResourceTiming ( entry ) && entry . name . endsWith ( url ) ) {
305300 span . setAttributes ( resourceTimingToSpanAttributes ( entry ) ) ;
306- // In the next tick, clean this handler up
307- // We have to wait here because otherwise this cleans itself up before it is fully done
308- setTimeout ( cleanup ) ;
301+ onEntryFound ( ) ;
309302 }
310303 } ) ;
311304 } ) ;
0 commit comments