forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork_undici.js
More file actions
246 lines (222 loc) · 7.59 KB
/
Copy pathnetwork_undici.js
File metadata and controls
246 lines (222 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
'use strict';
const {
DateNow,
StringPrototypeToLowerCase,
} = primordials;
const {
kInspectorRequestId,
kResourceType,
getMonotonicTime,
getNextRequestId,
registerDiagnosticChannels,
sniffMimeType,
} = require('internal/inspector/network');
const { Network } = require('inspector');
const { Buffer } = require('buffer');
// Convert an undici request headers array to a plain object (Map<string, string>)
function requestHeadersArrayToDictionary(headers) {
const dict = {};
let charset;
let mimeType;
for (let idx = 0; idx < headers.length; idx += 2) {
const key = `${headers[idx]}`;
const value = `${headers[idx + 1]}`;
dict[key] = value;
if (StringPrototypeToLowerCase(key) === 'content-type') {
const result = sniffMimeType(value);
charset = result.charset;
mimeType = result.mimeType;
}
}
return [dict, charset, mimeType];
};
// Convert an undici response headers array to a plain object (Map<string, string>)
function responseHeadersArrayToDictionary(headers) {
const dict = {};
let charset;
let mimeType;
for (let idx = 0; idx < headers.length; idx += 2) {
const key = `${headers[idx]}`;
const lowerCasedKey = StringPrototypeToLowerCase(key);
const value = `${headers[idx + 1]}`;
const prevValue = dict[key];
if (lowerCasedKey === 'content-type') {
const result = sniffMimeType(value);
charset = result.charset;
mimeType = result.mimeType;
}
if (typeof prevValue === 'string') {
// ChromeDevTools frontend treats 'set-cookie' as a special case
// https://github.com/ChromeDevTools/devtools-frontend/blob/4275917f84266ef40613db3c1784a25f902ea74e/front_end/core/sdk/NetworkRequest.ts#L1368
if (lowerCasedKey === 'set-cookie') dict[key] = `${prevValue}\n${value}`;
else dict[key] = `${prevValue}, ${value}`;
} else {
dict[key] = value;
}
}
return [dict, charset, mimeType];
};
/**
* When a client request starts, emit Network.requestWillBeSent event.
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#event-requestWillBeSent
* @param {{ request: undici.Request }} event
*/
function onClientRequestStart({ request }) {
const url = `${request.origin}${request.path}`;
request[kInspectorRequestId] = getNextRequestId();
const { 0: headers, 1: charset } = requestHeadersArrayToDictionary(request.headers);
Network.requestWillBeSent({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
wallTime: DateNow(),
charset,
request: {
url,
method: request.method,
headers: headers,
hasPostData: request.body != null,
},
});
}
/**
* When a client request errors, emit Network.loadingFailed event.
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#event-loadingFailed
* @param {{ request: undici.Request, error: any }} event
*/
function onClientRequestError({ request, error }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
Network.loadingFailed({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
// TODO(legendecas): distinguish between `undici.request` and `undici.fetch`.
type: kResourceType.Fetch,
errorText: error.message,
});
}
/**
* When a chunk of the request body is being sent, cache it until `getRequestPostData` request.
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-getRequestPostData
* @param {{ request: undici.Request, chunk: Uint8Array | string }} event
*/
function onClientRequestBodyChunkSent({ request, chunk }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
const buffer = Buffer.from(chunk);
Network.dataSent({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
dataLength: buffer.byteLength,
data: buffer,
});
}
/**
* Mark a request body as fully sent.
* @param {{request: undici.Request}} event
*/
function onClientRequestBodySent({ request }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
Network.dataSent({
requestId: request[kInspectorRequestId],
finished: true,
});
}
/**
* When response headers are received, emit Network.responseReceived event.
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#event-responseReceived
* @param {{ request: undici.Request, response: undici.Response }} event
*/
function onClientResponseHeaders({ request, response }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
const { 0: headers, 1: charset, 2: mimeType } = responseHeadersArrayToDictionary(response.headers);
const url = `${request.origin}${request.path}`;
Network.responseReceived({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
// TODO(legendecas): distinguish between `undici.request` and `undici.fetch`.
type: kResourceType.Fetch,
response: {
url,
status: response.statusCode,
statusText: response.statusText,
headers,
mimeType,
charset,
},
});
}
/**
* When a chunk of the response body has been received, cache it until `getResponseBody` request
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-getResponseBody or
* stream it with `streamResourceContent` request.
* https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-streamResourceContent
* @param {{ request: undici.Request, chunk: Uint8Array | string }} event
*/
function onClientRequestBodyChunkReceived({ request, chunk }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
Network.dataReceived({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
dataLength: chunk.byteLength,
encodedDataLength: chunk.byteLength,
data: chunk,
});
}
/**
* When a response is completed, emit Network.loadingFinished event.
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#event-loadingFinished
* @param {{ request: undici.Request, response: undici.Response }} event
*/
function onClientResponseFinish({ request }) {
if (typeof request[kInspectorRequestId] !== 'string') {
return;
}
Network.loadingFinished({
requestId: request[kInspectorRequestId],
timestamp: getMonotonicTime(),
});
}
// TODO: Move Network.webSocketCreated to the actual creation time of the WebSocket.
// undici:websocket:open fires when the connection is established, but this results
// in an inaccurate stack trace.
function onWebSocketOpen({ websocket, handshakeResponse }) {
websocket[kInspectorRequestId] = getNextRequestId();
const url = websocket.url.toString();
Network.webSocketCreated({
requestId: websocket[kInspectorRequestId],
url,
});
Network.webSocketHandshakeResponseReceived({
requestId: websocket[kInspectorRequestId],
timestamp: getMonotonicTime(),
response: handshakeResponse,
});
}
function onWebSocketClose({ websocket }) {
if (typeof websocket[kInspectorRequestId] !== 'string') {
return;
}
Network.webSocketClosed({
requestId: websocket[kInspectorRequestId],
timestamp: getMonotonicTime(),
});
}
module.exports = registerDiagnosticChannels([
['undici:request:create', onClientRequestStart],
['undici:request:error', onClientRequestError],
['undici:request:headers', onClientResponseHeaders],
['undici:request:trailers', onClientResponseFinish],
['undici:request:bodyChunkSent', onClientRequestBodyChunkSent],
['undici:request:bodySent', onClientRequestBodySent],
['undici:request:bodyChunkReceived', onClientRequestBodyChunkReceived],
['undici:websocket:open', onWebSocketOpen],
['undici:websocket:close', onWebSocketClose],
]);