* Lazily start a background interval that evicts orphaned spans from activeSpans. * * Normal teardown calls endInteractionSpan / endToolSpan, which delete spans * immediately. This interval is a safety net for spans that were never ended * (e.g. aborted streams, uncaught exceptions mid-query) —
()
| 98 | * work is done. |
| 99 | */ |
| 100 | function ensureCleanupInterval(): void { |
| 101 | if (_cleanupIntervalStarted) return |
| 102 | _cleanupIntervalStarted = true |
| 103 | const interval = setInterval(() => { |
| 104 | const cutoff = Date.now() - SPAN_TTL_MS |
| 105 | for (const [spanId, weakRef] of activeSpans) { |
| 106 | const ctx = weakRef.deref() |
| 107 | if (ctx === undefined) { |
| 108 | activeSpans.delete(spanId) |
| 109 | strongSpans.delete(spanId) |
| 110 | } else if (ctx.startTime < cutoff) { |
| 111 | if (!ctx.ended) ctx.span.end() // flush any recorded attributes to the exporter |
| 112 | activeSpans.delete(spanId) |
| 113 | strongSpans.delete(spanId) |
| 114 | } |
| 115 | } |
| 116 | }, 60_000) |
| 117 | if (typeof interval.unref === 'function') { |
| 118 | interval.unref() // Node.js / Bun: don't block process exit |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Check if enhanced telemetry is enabled. |
no test coverage detected