( scope: CopilotOtelScope, fn: (otelContext: Context) => Promise<T> )
| 543 | } |
| 544 | |
| 545 | export async function withCopilotOtelContext<T>( |
| 546 | scope: CopilotOtelScope, |
| 547 | fn: (otelContext: Context) => Promise<T> |
| 548 | ): Promise<T> { |
| 549 | const parentContext = context.active() |
| 550 | // Same trace-id-derives-requestId dance as startCopilotOtelRoot — see |
| 551 | // that function for the rationale. Stamp a placeholder, read the real |
| 552 | // trace ID off the span, then overwrite. |
| 553 | const span = getTracer().startSpan( |
| 554 | TraceSpan.GenAiAgentExecute, |
| 555 | { attributes: buildAgentSpanAttributes({ ...scope, requestId: scope.requestId ?? '' }) }, |
| 556 | parentContext |
| 557 | ) |
| 558 | const carrierSpan = isValidSpanContext(span.spanContext()) |
| 559 | ? span |
| 560 | : trace.wrapSpanContext(createFallbackSpanContext()) |
| 561 | const spanContext = carrierSpan.spanContext() |
| 562 | const resolvedRequestId = |
| 563 | scope.requestId ?? |
| 564 | (spanContext.traceId && spanContext.traceId.length === 32 ? spanContext.traceId : '') |
| 565 | if (resolvedRequestId) { |
| 566 | span.setAttribute(TraceAttr.RequestId, resolvedRequestId) |
| 567 | span.setAttribute(TraceAttr.SimRequestId, resolvedRequestId) |
| 568 | } |
| 569 | const otelContext = trace.setSpan(parentContext, carrierSpan) |
| 570 | let terminalStatusSet = false |
| 571 | |
| 572 | try { |
| 573 | const result = await context.with(otelContext, () => fn(otelContext)) |
| 574 | span.setStatus({ code: SpanStatusCode.OK }) |
| 575 | terminalStatusSet = true |
| 576 | return result |
| 577 | } catch (error) { |
| 578 | markSpanForError(span, error) |
| 579 | terminalStatusSet = true |
| 580 | throw error |
| 581 | } finally { |
| 582 | if (!terminalStatusSet) { |
| 583 | // Extremely defensive: should be unreachable, but avoids leaking |
| 584 | // an unset span status if some future refactor breaks both arms. |
| 585 | span.setStatus({ code: SpanStatusCode.OK }) |
| 586 | } |
| 587 | span.end() |
| 588 | } |
| 589 | } |
no test coverage detected