Skip to content

Commit b1d3a59

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 450435b commit b1d3a59

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/instrumentation/fetch.ts

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,16 +159,29 @@ export function executeFetchHandler(fetchFn: FetchHandler, [request, env, ctx]:
159159
const response = await fetchFn(request, env, ctx)
160160
span.setAttributes(gatherResponseAttributes(response))
161161

162-
return response
162+
if (!response.body) {
163+
span.end()
164+
return response
165+
}
166+
167+
const transformer = new TransformStream({
168+
transform(chunk, controller) {
169+
controller.enqueue(chunk)
170+
},
171+
flush() {
172+
span.end()
173+
},
174+
})
175+
return new Response(response.body.pipeThrough(transformer), response)
163176
} catch (error) {
164177
span.recordException(error as Exception)
165178
span.setStatus({ code: SpanStatusCode.ERROR })
179+
span.end()
166180
throw error
167181
} finally {
168182
if (readable.attributes['http.route']) {
169183
span.updateName(`fetchHandler ${method} ${readable.attributes['http.route']}`)
170184
}
171-
span.end()
172185
}
173186
})
174187
return promise
@@ -233,10 +246,24 @@ export function instrumentClientFetch(
233246
}
234247
span.setAttributes(gatherRequestAttributes(request))
235248
if (request.cf) span.setAttributes(gatherOutgoingCfAttributes(request.cf))
249+
236250
const response = await Reflect.apply(target, thisArg, [request])
237251
span.setAttributes(gatherResponseAttributes(response))
238-
span.end()
239-
return response
252+
253+
if (!response.body) {
254+
span.end()
255+
return response
256+
}
257+
258+
const transformer = new TransformStream({
259+
transform(chunk, controller) {
260+
controller.enqueue(chunk)
261+
},
262+
flush() {
263+
span.end()
264+
},
265+
})
266+
return new Response(response.body.pipeThrough(transformer), response)
240267
})
241268
return promise
242269
},

0 commit comments

Comments
 (0)