diff --git a/src/fetch.ts b/src/fetch.ts index 9df86555..0165453f 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -218,6 +218,8 @@ export class FetchFactory { res = await UndiciFetch(input, init); }); } catch (e: any) { + updateSocketInfo(socketInfo, internalOpaque /* , rawError */); + urllibResponse.rt = performanceTime(requestStartTime); channels.fetchResponse.publish({ fetch: fetchMeta, error: e, diff --git a/src/utils.ts b/src/utils.ts index 04f7a688..aa39f0c2 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -159,6 +159,7 @@ export function isReadable(stream: any) { export function updateSocketInfo(socketInfo: SocketInfo, internalOpaque: any, err?: any) { const socket = internalOpaque[symbols.kRequestSocket] ?? err?.[symbols.kErrorSocket]; + if (socket) { socketInfo.id = socket[symbols.kSocketId]; socketInfo.handledRequests = socket[symbols.kHandledRequests]; diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 9429d95c..6171e220 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -57,4 +57,44 @@ describe('fetch.test.ts', () => { assert(stats); assert(Object.keys(stats).length > 0); }); + + it('fetch error should has socket info', async () => { + let requestDiagnosticsMessage: RequestDiagnosticsMessage; + let responseDiagnosticsMessage: ResponseDiagnosticsMessage; + let fetchDiagnosticsMessage: FetchDiagnosticsMessage; + let fetchResponseDiagnosticsMessage: FetchResponseDiagnosticsMessage; + diagnosticsChannel.subscribe('urllib:request', msg => { + requestDiagnosticsMessage = msg as RequestDiagnosticsMessage; + }); + diagnosticsChannel.subscribe('urllib:response', msg => { + responseDiagnosticsMessage = msg as ResponseDiagnosticsMessage; + }); + diagnosticsChannel.subscribe('urllib:fetch:request', msg => { + fetchDiagnosticsMessage = msg as FetchDiagnosticsMessage; + }); + diagnosticsChannel.subscribe('urllib:fetch:response', msg => { + fetchResponseDiagnosticsMessage = msg as FetchResponseDiagnosticsMessage; + }); + FetchFactory.setClientOptions({}); + + try { + await fetch(`${_url}html?timeout=9999`, { + signal: AbortSignal.timeout(100), + }); + } catch (error) { + console.log(error); + } + + assert(requestDiagnosticsMessage!.request); + assert(responseDiagnosticsMessage!.request); + assert(responseDiagnosticsMessage!.response); + assert([ '127.0.0.1', '::1' ].includes(responseDiagnosticsMessage!.response.socket.localAddress)); + + assert(fetchDiagnosticsMessage!.fetch); + assert(fetchResponseDiagnosticsMessage!.fetch); + + const stats = FetchFactory.getDispatcherPoolStats(); + assert(stats); + assert(Object.keys(stats).length > 0); + }); });