Skip to content

Commit 11bca7d

Browse files
committed
Instrument HTTP request end-to-end
This commit extends the current span to include the transfer of the HTTP response body rather than ending it when the headers complete. This provides a fuller, more accurate picture of the HTTP request. This is implemented using a `TransformStream` on the HTTP response body that acts as a pass-through and only calling `span.end()` once the stream has completed.
1 parent effeb54 commit 11bca7d

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/instrumentation/fetch.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,13 +196,26 @@ export function instrumentClientFetch(
196196
if (request.cf) span.setAttributes(gatherOutgoingCfAttributes(request.cf))
197197
const response = await Reflect.apply(target, thisArg, [request])
198198
span.setAttributes(gatherResponseAttributes(response))
199-
return response
199+
200+
if (!response.body) {
201+
span.end()
202+
return response
203+
}
204+
205+
const transformer = new TransformStream({
206+
transform(chunk, controller) {
207+
controller.enqueue(chunk)
208+
},
209+
flush() {
210+
span.end()
211+
},
212+
})
213+
return new Response(response.body.pipeThrough(transformer), response)
200214
} catch (error: unknown) {
201215
span.recordException(error as Exception)
202216
span.setStatus({ code: SpanStatusCode.ERROR })
203-
throw error
204-
} finally {
205217
span.end()
218+
throw error
206219
}
207220
})
208221
return promise

0 commit comments

Comments
 (0)