Skip to content

Commit b6a0a04

Browse files
committed
fix: Defensive calling 📞
1 parent b46300a commit b6a0a04

1 file changed

Lines changed: 27 additions & 20 deletions

File tree

  • packages/core/src/tracing/workers-ai

‎packages/core/src/tracing/workers-ai/index.ts‎

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -49,32 +49,39 @@ function instrumentRun(
4949

5050
if (isStreamRequested && !returnsRawResponse) {
5151
return startSpanManual(spanConfig, (span: Span) => {
52-
const originalResult = originalRun.apply(context, args) as Promise<unknown>;
52+
// `startSpanManual` does not auto-end the span, so we must end it on every exit path,
53+
// including a synchronous throw from `run`.
54+
const handleError = (error: unknown): never => {
55+
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
56+
captureException(error, {
57+
mechanism: { handled: false, type: `${WORKERS_AI_ORIGIN}.stream`, data: { function: 'run' } },
58+
});
59+
span.end();
60+
throw error;
61+
};
62+
63+
let originalResult: Promise<unknown>;
64+
65+
try {
66+
originalResult = originalRun.apply(context, args) as Promise<unknown>;
67+
} catch (error) {
68+
return handleError(error);
69+
}
5370

5471
if (options.recordInputs) {
5572
addRequestAttributes(span, inputs, operationName, shouldEnableTruncation(options.enableTruncation));
5673
}
5774

58-
return originalResult.then(
59-
result => {
60-
if (isReadableStream(result)) {
61-
return instrumentWorkersAiStream(result, span, options.recordOutputs);
62-
}
75+
return originalResult.then(result => {
76+
if (isReadableStream(result)) {
77+
return instrumentWorkersAiStream(result, span, options.recordOutputs);
78+
}
6379

64-
// The model did not actually return a stream — finalize the span eagerly.
65-
addResponseAttributes(span, result, options.recordOutputs);
66-
span.end();
67-
return result;
68-
},
69-
error => {
70-
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
71-
captureException(error, {
72-
mechanism: { handled: false, type: `${WORKERS_AI_ORIGIN}.stream`, data: { function: 'run' } },
73-
});
74-
span.end();
75-
throw error;
76-
},
77-
);
80+
// The model did not actually return a stream — finalize the span eagerly.
81+
addResponseAttributes(span, result, options.recordOutputs);
82+
span.end();
83+
return result;
84+
}, handleError);
7885
});
7986
}
8087

0 commit comments

Comments
 (0)