@sentry/node 9.15.0 → 9.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/integrations/anr/index.js +1 -1
- package/build/cjs/integrations/context.js +1 -0
- package/build/cjs/integrations/context.js.map +1 -1
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js +130 -126
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/cjs/integrations/http/SentryHttpInstrumentationBeforeOtel.js +50 -44
- package/build/cjs/integrations/http/SentryHttpInstrumentationBeforeOtel.js.map +1 -1
- package/build/cjs/integrations/http/index.js +31 -7
- package/build/cjs/integrations/http/index.js.map +1 -1
- package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/build/cjs/integrations/tracing/express-v5/instrumentation.js +4 -2
- package/build/cjs/integrations/tracing/express-v5/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/index.js +2 -4
- package/build/cjs/integrations/tracing/index.js.map +1 -1
- package/build/cjs/integrations/tracing/prisma.js +2 -7
- package/build/cjs/integrations/tracing/prisma.js.map +1 -1
- package/build/cjs/integrations/winston.js +2 -2
- package/build/cjs/integrations/winston.js.map +1 -1
- package/build/esm/integrations/anr/index.js +1 -1
- package/build/esm/integrations/anr/worker-script.js +2 -2
- package/build/esm/integrations/context.js +1 -0
- package/build/esm/integrations/context.js.map +1 -1
- package/build/esm/integrations/http/SentryHttpInstrumentation.js +131 -127
- package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/esm/integrations/http/SentryHttpInstrumentationBeforeOtel.js +51 -45
- package/build/esm/integrations/http/SentryHttpInstrumentationBeforeOtel.js.map +1 -1
- package/build/esm/integrations/http/index.js +31 -7
- package/build/esm/integrations/http/index.js.map +1 -1
- package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/build/esm/integrations/local-variables/worker-script.js +2 -2
- package/build/esm/integrations/tracing/express-v5/instrumentation.js +4 -2
- package/build/esm/integrations/tracing/express-v5/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/index.js +2 -4
- package/build/esm/integrations/tracing/index.js.map +1 -1
- package/build/esm/integrations/tracing/prisma.js +2 -7
- package/build/esm/integrations/tracing/prisma.js.map +1 -1
- package/build/esm/integrations/winston.js +2 -2
- package/build/esm/integrations/winston.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/integrations/context.d.ts.map +1 -1
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +9 -13
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
- package/build/types/integrations/http/SentryHttpInstrumentationBeforeOtel.d.ts.map +1 -1
- package/build/types/integrations/http/index.d.ts +8 -0
- package/build/types/integrations/http/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/express-v5/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/prisma.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +3 -3
- package/build/types-ts3.8/integrations/http/SentryHttpInstrumentation.d.ts +9 -13
- package/build/types-ts3.8/integrations/http/index.d.ts +11 -0
- package/build/types-ts3.8/integrations/winston.d.ts +3 -3
- package/package.json +4 -4
- package/build/cjs/integrations/http/vendor/getRequestInfo.js +0 -130
- package/build/cjs/integrations/http/vendor/getRequestInfo.js.map +0 -1
- package/build/esm/integrations/http/vendor/getRequestInfo.js +0 -128
- package/build/esm/integrations/http/vendor/getRequestInfo.js.map +0 -1
- package/build/types/integrations/http/vendor/getRequestInfo.d.ts +0 -21
- package/build/types/integrations/http/vendor/getRequestInfo.d.ts.map +0 -1
- package/build/types-ts3.8/integrations/http/vendor/getRequestInfo.d.ts +0 -21
|
@@ -1,11 +1,10 @@
|
|
|
1
|
+
import { subscribe, unsubscribe } from 'node:diagnostics_channel';
|
|
1
2
|
import { propagation, context } from '@opentelemetry/api';
|
|
2
3
|
import { VERSION } from '@opentelemetry/core';
|
|
3
4
|
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
|
|
4
|
-
import { getIsolationScope, httpRequestToRequestData, stripUrlQueryAndFragment, withIsolationScope, generateSpanId, getCurrentScope,
|
|
5
|
+
import { logger, getIsolationScope, httpRequestToRequestData, stripUrlQueryAndFragment, withIsolationScope, generateSpanId, getCurrentScope, addNonEnumerableProperty, getBreadcrumbLogLevelFromHttpStatusCode, addBreadcrumb, getClient, parseUrl, getSanitizedUrlString } from '@sentry/core';
|
|
5
6
|
import { DEBUG_BUILD } from '../../debug-build.js';
|
|
6
7
|
import { getRequestUrl } from '../../utils/getRequestUrl.js';
|
|
7
|
-
import { stealthWrap } from './utils.js';
|
|
8
|
-
import { getRequestInfo } from './vendor/getRequestInfo.js';
|
|
9
8
|
|
|
10
9
|
const INSTRUMENTATION_NAME = '@sentry/instrumentation-http';
|
|
11
10
|
|
|
@@ -32,71 +31,134 @@ class SentryHttpInstrumentation extends InstrumentationBase {
|
|
|
32
31
|
|
|
33
32
|
/** @inheritdoc */
|
|
34
33
|
init() {
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
// We register handlers when either http or https is instrumented
|
|
35
|
+
// but we only want to register them once, whichever is loaded first
|
|
36
|
+
let hasRegisteredHandlers = false;
|
|
37
|
+
|
|
38
|
+
const onHttpServerRequestStart = ((_data) => {
|
|
39
|
+
const data = _data ;
|
|
40
|
+
this._patchServerEmitOnce(data.server);
|
|
41
|
+
}) ;
|
|
42
|
+
|
|
43
|
+
const onHttpClientResponseFinish = ((_data) => {
|
|
44
|
+
const data = _data ;
|
|
45
|
+
this._onOutgoingRequestFinish(data.request, data.response);
|
|
46
|
+
}) ;
|
|
47
|
+
|
|
48
|
+
const onHttpClientRequestError = ((_data) => {
|
|
49
|
+
const data = _data ;
|
|
50
|
+
this._onOutgoingRequestFinish(data.request, undefined);
|
|
51
|
+
}) ;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* You may be wondering why we register these diagnostics-channel listeners
|
|
55
|
+
* in such a convoluted way (as InstrumentationNodeModuleDefinition...)˝,
|
|
56
|
+
* instead of simply subscribing to the events once in here.
|
|
57
|
+
* The reason for this is timing semantics: These functions are called once the http or https module is loaded.
|
|
58
|
+
* If we'd subscribe before that, there seem to be conflicts with the OTEL native instrumentation in some scenarios,
|
|
59
|
+
* especially the "import-on-top" pattern of setting up ESM applications.
|
|
60
|
+
*/
|
|
61
|
+
return [
|
|
62
|
+
new InstrumentationNodeModuleDefinition(
|
|
63
|
+
'http',
|
|
64
|
+
['*'],
|
|
65
|
+
(moduleExports) => {
|
|
66
|
+
if (hasRegisteredHandlers) {
|
|
67
|
+
return moduleExports;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
hasRegisteredHandlers = true;
|
|
71
|
+
|
|
72
|
+
subscribe('http.server.request.start', onHttpServerRequestStart);
|
|
73
|
+
subscribe('http.client.response.finish', onHttpClientResponseFinish);
|
|
74
|
+
|
|
75
|
+
// When an error happens, we still want to have a breadcrumb
|
|
76
|
+
// In this case, `http.client.response.finish` is not triggered
|
|
77
|
+
subscribe('http.client.request.error', onHttpClientRequestError);
|
|
78
|
+
|
|
79
|
+
return moduleExports;
|
|
80
|
+
},
|
|
81
|
+
() => {
|
|
82
|
+
unsubscribe('http.server.request.start', onHttpServerRequestStart);
|
|
83
|
+
unsubscribe('http.client.response.finish', onHttpClientResponseFinish);
|
|
84
|
+
unsubscribe('http.client.request.error', onHttpClientRequestError);
|
|
85
|
+
},
|
|
86
|
+
),
|
|
87
|
+
new InstrumentationNodeModuleDefinition(
|
|
88
|
+
'https',
|
|
89
|
+
['*'],
|
|
90
|
+
(moduleExports) => {
|
|
91
|
+
if (hasRegisteredHandlers) {
|
|
92
|
+
return moduleExports;
|
|
93
|
+
}
|
|
37
94
|
|
|
38
|
-
|
|
39
|
-
_getHttpInstrumentation() {
|
|
40
|
-
return new InstrumentationNodeModuleDefinition(
|
|
41
|
-
'http',
|
|
42
|
-
['*'],
|
|
43
|
-
(moduleExports) => {
|
|
44
|
-
// Patch incoming requests for request isolation
|
|
45
|
-
stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());
|
|
95
|
+
hasRegisteredHandlers = true;
|
|
46
96
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
|
|
97
|
+
subscribe('http.server.request.start', onHttpServerRequestStart);
|
|
98
|
+
subscribe('http.client.response.finish', onHttpClientResponseFinish);
|
|
50
99
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
100
|
+
// When an error happens, we still want to have a breadcrumb
|
|
101
|
+
// In this case, `http.client.response.finish` is not triggered
|
|
102
|
+
subscribe('http.client.request.error', onHttpClientRequestError);
|
|
103
|
+
|
|
104
|
+
return moduleExports;
|
|
105
|
+
},
|
|
106
|
+
() => {
|
|
107
|
+
unsubscribe('http.server.request.start', onHttpServerRequestStart);
|
|
108
|
+
unsubscribe('http.client.response.finish', onHttpClientResponseFinish);
|
|
109
|
+
unsubscribe('http.client.request.error', onHttpClientRequestError);
|
|
110
|
+
},
|
|
111
|
+
),
|
|
112
|
+
];
|
|
57
113
|
}
|
|
58
114
|
|
|
59
|
-
/**
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
115
|
+
/**
|
|
116
|
+
* This is triggered when an outgoing request finishes.
|
|
117
|
+
* It has access to the final request and response objects.
|
|
118
|
+
*/
|
|
119
|
+
_onOutgoingRequestFinish(request, response) {
|
|
120
|
+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');
|
|
121
|
+
|
|
122
|
+
const _breadcrumbs = this.getConfig().breadcrumbs;
|
|
123
|
+
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
|
|
124
|
+
const options = getRequestOptions(request);
|
|
67
125
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
126
|
+
const _ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests;
|
|
127
|
+
const shouldCreateBreadcrumb =
|
|
128
|
+
typeof _ignoreOutgoingRequests === 'function' ? !_ignoreOutgoingRequests(getRequestUrl(request), options) : true;
|
|
71
129
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
// no unwrap here
|
|
76
|
-
},
|
|
77
|
-
);
|
|
130
|
+
if (breadCrumbsEnabled && shouldCreateBreadcrumb) {
|
|
131
|
+
addRequestBreadcrumb(request, response);
|
|
132
|
+
}
|
|
78
133
|
}
|
|
79
134
|
|
|
80
135
|
/**
|
|
81
|
-
* Patch
|
|
136
|
+
* Patch a server.emit function to handle process isolation for incoming requests.
|
|
137
|
+
* This will only patch the emit function if it was not already patched.
|
|
82
138
|
*/
|
|
83
|
-
|
|
139
|
+
_patchServerEmitOnce(server) {
|
|
140
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
141
|
+
const originalEmit = server.emit;
|
|
142
|
+
|
|
143
|
+
// This means it was already patched, do nothing
|
|
144
|
+
if ((originalEmit ).__sentry_patched__) {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching server.emit');
|
|
84
149
|
|
|
85
|
-
{
|
|
86
150
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
87
151
|
const instrumentation = this;
|
|
88
152
|
const { ignoreIncomingRequestBody } = instrumentation.getConfig();
|
|
89
153
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
) => {
|
|
93
|
-
return function incomingRequest( ...args) {
|
|
154
|
+
const newEmit = new Proxy(originalEmit, {
|
|
155
|
+
apply(target, thisArg, args) {
|
|
94
156
|
// Only traces request events
|
|
95
157
|
if (args[0] !== 'request') {
|
|
96
|
-
return
|
|
158
|
+
return target.apply(thisArg, args);
|
|
97
159
|
}
|
|
98
160
|
|
|
99
|
-
|
|
161
|
+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling incoming request');
|
|
100
162
|
|
|
101
163
|
const isolationScope = getIsolationScope().clone();
|
|
102
164
|
const request = args[1] ;
|
|
@@ -141,88 +203,20 @@ class SentryHttpInstrumentation extends InstrumentationBase {
|
|
|
141
203
|
|
|
142
204
|
// If we don't want to extract the trace from the header, we can skip this
|
|
143
205
|
if (!instrumentation.getConfig().extractIncomingTraceFromHeader) {
|
|
144
|
-
return
|
|
206
|
+
return target.apply(thisArg, args);
|
|
145
207
|
}
|
|
146
208
|
|
|
147
209
|
const ctx = propagation.extract(context.active(), normalizedRequest.headers);
|
|
148
210
|
return context.with(ctx, () => {
|
|
149
|
-
return
|
|
211
|
+
return target.apply(thisArg, args);
|
|
150
212
|
});
|
|
151
213
|
});
|
|
152
|
-
}
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Patch the outgoing request function for breadcrumbs.
|
|
158
|
-
*/
|
|
159
|
-
_getPatchOutgoingRequestFunction()
|
|
160
|
-
|
|
161
|
-
{
|
|
162
|
-
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
163
|
-
const instrumentation = this;
|
|
164
|
-
|
|
165
|
-
return (original) => {
|
|
166
|
-
return function outgoingRequest( ...args) {
|
|
167
|
-
instrumentation._diag.debug('http instrumentation for outgoing requests');
|
|
168
|
-
|
|
169
|
-
// Making a copy to avoid mutating the original args array
|
|
170
|
-
// We need to access and reconstruct the request options object passed to `ignoreOutgoingRequests`
|
|
171
|
-
// so that it matches what Otel instrumentation passes to `ignoreOutgoingRequestHook`.
|
|
172
|
-
// @see https://github.com/open-telemetry/opentelemetry-js/blob/7293e69c1e55ca62e15d0724d22605e61bd58952/experimental/packages/opentelemetry-instrumentation-http/src/http.ts#L756-L789
|
|
173
|
-
const argsCopy = [...args];
|
|
174
|
-
|
|
175
|
-
const options = argsCopy.shift() ;
|
|
176
|
-
|
|
177
|
-
const extraOptions =
|
|
178
|
-
typeof argsCopy[0] === 'object' && (typeof options === 'string' || options instanceof URL)
|
|
179
|
-
? (argsCopy.shift() )
|
|
180
|
-
: undefined;
|
|
181
|
-
|
|
182
|
-
const { optionsParsed } = getRequestInfo(instrumentation._diag, options, extraOptions);
|
|
183
|
-
|
|
184
|
-
const request = original.apply(this, args) ;
|
|
185
|
-
|
|
186
|
-
request.prependListener('response', (response) => {
|
|
187
|
-
const _breadcrumbs = instrumentation.getConfig().breadcrumbs;
|
|
188
|
-
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
|
|
189
|
-
|
|
190
|
-
const _ignoreOutgoingRequests = instrumentation.getConfig().ignoreOutgoingRequests;
|
|
191
|
-
const shouldCreateBreadcrumb =
|
|
192
|
-
typeof _ignoreOutgoingRequests === 'function'
|
|
193
|
-
? !_ignoreOutgoingRequests(getRequestUrl(request), optionsParsed)
|
|
194
|
-
: true;
|
|
195
|
-
|
|
196
|
-
if (breadCrumbsEnabled && shouldCreateBreadcrumb) {
|
|
197
|
-
addRequestBreadcrumb(request, response);
|
|
198
|
-
}
|
|
199
|
-
});
|
|
214
|
+
},
|
|
215
|
+
});
|
|
200
216
|
|
|
201
|
-
|
|
202
|
-
};
|
|
203
|
-
};
|
|
204
|
-
}
|
|
217
|
+
addNonEnumerableProperty(newEmit, '__sentry_patched__', true);
|
|
205
218
|
|
|
206
|
-
|
|
207
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
208
|
-
_getPatchOutgoingGetFunction(clientRequest) {
|
|
209
|
-
return (_original) => {
|
|
210
|
-
// Re-implement http.get. This needs to be done (instead of using
|
|
211
|
-
// getPatchOutgoingRequestFunction to patch it) because we need to
|
|
212
|
-
// set the trace context header before the returned http.ClientRequest is
|
|
213
|
-
// ended. The Node.js docs state that the only differences between
|
|
214
|
-
// request and get are that (1) get defaults to the HTTP GET method and
|
|
215
|
-
// (2) the returned request object is ended immediately. The former is
|
|
216
|
-
// already true (at least in supported Node versions up to v10), so we
|
|
217
|
-
// simply follow the latter. Ref:
|
|
218
|
-
// https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
|
|
219
|
-
// https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198
|
|
220
|
-
return function outgoingGetRequest(...args) {
|
|
221
|
-
const req = clientRequest(...args);
|
|
222
|
-
req.end();
|
|
223
|
-
return req;
|
|
224
|
-
};
|
|
225
|
-
};
|
|
219
|
+
server.emit = newEmit;
|
|
226
220
|
}
|
|
227
221
|
}
|
|
228
222
|
|
|
@@ -230,7 +224,7 @@ class SentryHttpInstrumentation extends InstrumentationBase {
|
|
|
230
224
|
function addRequestBreadcrumb(request, response) {
|
|
231
225
|
const data = getBreadcrumbData(request);
|
|
232
226
|
|
|
233
|
-
const statusCode = response
|
|
227
|
+
const statusCode = response?.statusCode;
|
|
234
228
|
const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);
|
|
235
229
|
|
|
236
230
|
addBreadcrumb(
|
|
@@ -286,6 +280,8 @@ function patchRequestToCaptureBody(req, isolationScope) {
|
|
|
286
280
|
let bodyByteLength = 0;
|
|
287
281
|
const chunks = [];
|
|
288
282
|
|
|
283
|
+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching request.on');
|
|
284
|
+
|
|
289
285
|
/**
|
|
290
286
|
* We need to keep track of the original callbacks, in order to be able to remove listeners again.
|
|
291
287
|
* Since `off` depends on having the exact same function reference passed in, we need to be able to map
|
|
@@ -299,11 +295,8 @@ function patchRequestToCaptureBody(req, isolationScope) {
|
|
|
299
295
|
apply: (target, thisArg, args) => {
|
|
300
296
|
const [event, listener, ...restArgs] = args;
|
|
301
297
|
|
|
302
|
-
if (DEBUG_BUILD) {
|
|
303
|
-
logger.log(INSTRUMENTATION_NAME, 'Patching request.on', event);
|
|
304
|
-
}
|
|
305
|
-
|
|
306
298
|
if (event === 'data') {
|
|
299
|
+
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling request.on("data")');
|
|
307
300
|
const callback = new Proxy(listener, {
|
|
308
301
|
apply: (target, thisArg, args) => {
|
|
309
302
|
try {
|
|
@@ -374,6 +367,17 @@ function patchRequestToCaptureBody(req, isolationScope) {
|
|
|
374
367
|
}
|
|
375
368
|
}
|
|
376
369
|
|
|
370
|
+
function getRequestOptions(request) {
|
|
371
|
+
return {
|
|
372
|
+
method: request.method,
|
|
373
|
+
protocol: request.protocol,
|
|
374
|
+
host: request.host,
|
|
375
|
+
hostname: request.host,
|
|
376
|
+
path: request.path,
|
|
377
|
+
headers: request.getHeaders(),
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
377
381
|
/**
|
|
378
382
|
* Starts a session and tracks it in the context of a given isolation scope.
|
|
379
383
|
* When the passed response is finished, the session is put into a task and is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type * as http from 'node:http';\nimport type { IncomingMessage, RequestOptions } from 'node:http';\nimport type * as https from 'node:https';\nimport type { EventEmitter } from 'node:stream';\nimport { context, propagation } from '@opentelemetry/api';\nimport { VERSION } from '@opentelemetry/core';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';\nimport type { AggregationCounts, Client, SanitizedRequestData, Scope } from '@sentry/core';\nimport {\n addBreadcrumb,\n generateSpanId,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getCurrentScope,\n getIsolationScope,\n getSanitizedUrlString,\n httpRequestToRequestData,\n logger,\n parseUrl,\n stripUrlQueryAndFragment,\n withIsolationScope,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getRequestUrl } from '../../utils/getRequestUrl';\nimport { stealthWrap } from './utils';\nimport { getRequestInfo } from './vendor/getRequestInfo';\n\ntype Http = typeof http;\ntype Https = typeof https;\n\nconst INSTRUMENTATION_NAME = '@sentry/instrumentation-http';\n\nexport type SentryHttpInstrumentationOptions = InstrumentationConfig & {\n /**\n * Whether breadcrumbs should be recorded for requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to extract the trace ID from the `sentry-trace` header for incoming requests.\n * By default this is done by the HttpInstrumentation, but if that is not added (e.g. because tracing is disabled, ...)\n * then this instrumentation can take over.\n *\n * @default `false`\n */\n extractIncomingTraceFromHeader?: boolean;\n\n /**\n * Do not capture breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * For the scope of this instrumentation, this callback only controls breadcrumb creation.\n * The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and\n * span creation.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed and we want to avoid capturing it.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreIncomingRequestBody?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n trackIncomingRequestsAsSessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `trackIncomingRequestsAsSessions` will be flushed as a session aggregate.\n *\n * Defaults to `60000` (60s).\n */\n sessionFlushingDelayMS?: number;\n};\n\n// We only want to capture request bodies up to 1mb.\nconst MAX_BODY_BYTE_LENGTH = 1024 * 1024;\n\n/**\n * This custom HTTP instrumentation is used to isolate incoming requests and annotate them with additional information.\n * It does not emit any spans.\n *\n * The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,\n * which would lead to Sentry not working as expected.\n *\n * Important note: Contrary to other OTEL instrumentation, this one cannot be unwrapped.\n * It only does minimal things though and does not emit any spans.\n *\n * This is heavily inspired & adapted from:\n * https://github.com/open-telemetry/opentelemetry-js/blob/f8ab5592ddea5cba0a3b33bf8d74f27872c0367f/experimental/packages/opentelemetry-instrumentation-http/src/http.ts\n */\nexport class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpInstrumentationOptions> {\n public constructor(config: SentryHttpInstrumentationOptions = {}) {\n super(INSTRUMENTATION_NAME, VERSION, config);\n }\n\n /** @inheritdoc */\n public init(): [InstrumentationNodeModuleDefinition, InstrumentationNodeModuleDefinition] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n /** Get the instrumentation for the http module. */\n private _getHttpInstrumentation(): InstrumentationNodeModuleDefinition {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n // Patch incoming requests for request isolation\n stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());\n\n // Patch outgoing requests for breadcrumbs\n const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());\n stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));\n\n return moduleExports;\n },\n () => {\n // no unwrap here\n },\n );\n }\n\n /** Get the instrumentation for the https module. */\n private _getHttpsInstrumentation(): InstrumentationNodeModuleDefinition {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n // Patch incoming requests for request isolation\n stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());\n\n // Patch outgoing requests for breadcrumbs\n const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());\n stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));\n\n return moduleExports;\n },\n () => {\n // no unwrap here\n },\n );\n }\n\n /**\n * Patch the incoming request function for request isolation.\n */\n private _getPatchIncomingRequestFunction(): (\n original: (event: string, ...args: unknown[]) => boolean,\n ) => (this: unknown, event: string, ...args: unknown[]) => boolean {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const instrumentation = this;\n const { ignoreIncomingRequestBody } = instrumentation.getConfig();\n\n return (\n original: (event: string, ...args: unknown[]) => boolean,\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return function incomingRequest(this: unknown, ...args: [event: string, ...args: unknown[]]): boolean {\n // Only traces request events\n if (args[0] !== 'request') {\n return original.apply(this, args);\n }\n\n instrumentation._diag.debug('http instrumentation for incoming request');\n\n const isolationScope = getIsolationScope().clone();\n const request = args[1] as http.IncomingMessage;\n const response = args[2] as http.OutgoingMessage;\n\n const normalizedRequest = httpRequestToRequestData(request);\n\n // request.ip is non-standard but some frameworks set this\n const ipAddress = (request as { ip?: string }).ip || request.socket?.remoteAddress;\n\n const url = request.url || '/';\n if (!ignoreIncomingRequestBody?.(url, request)) {\n patchRequestToCaptureBody(request, isolationScope);\n }\n\n // Update the isolation scope, isolate this request\n isolationScope.setSDKProcessingMetadata({ normalizedRequest, ipAddress });\n\n // attempt to update the scope's `transactionName` based on the request URL\n // Ideally, framework instrumentations coming after the HttpInstrumentation\n // update the transactionName once we get a parameterized route.\n const httpMethod = (request.method || 'GET').toUpperCase();\n const httpTarget = stripUrlQueryAndFragment(url);\n\n const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;\n\n isolationScope.setTransactionName(bestEffortTransactionName);\n\n if (instrumentation.getConfig().trackIncomingRequestsAsSessions !== false) {\n recordRequestSession({\n requestIsolationScope: isolationScope,\n response,\n sessionFlushingDelayMS: instrumentation.getConfig().sessionFlushingDelayMS ?? 60_000,\n });\n }\n\n return withIsolationScope(isolationScope, () => {\n // Set a new propagationSpanId for this request\n // We rely on the fact that `withIsolationScope()` will implicitly also fork the current scope\n // This way we can save an \"unnecessary\" `withScope()` invocation\n getCurrentScope().getPropagationContext().propagationSpanId = generateSpanId();\n\n // If we don't want to extract the trace from the header, we can skip this\n if (!instrumentation.getConfig().extractIncomingTraceFromHeader) {\n return original.apply(this, args);\n }\n\n const ctx = propagation.extract(context.active(), normalizedRequest.headers);\n return context.with(ctx, () => {\n return original.apply(this, args);\n });\n });\n };\n };\n }\n\n /**\n * Patch the outgoing request function for breadcrumbs.\n */\n private _getPatchOutgoingRequestFunction(): (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n original: (...args: any[]) => http.ClientRequest,\n ) => (options: URL | http.RequestOptions | string, ...args: unknown[]) => http.ClientRequest {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const instrumentation = this;\n\n return (original: (...args: unknown[]) => http.ClientRequest): ((...args: unknown[]) => http.ClientRequest) => {\n return function outgoingRequest(this: unknown, ...args: unknown[]): http.ClientRequest {\n instrumentation._diag.debug('http instrumentation for outgoing requests');\n\n // Making a copy to avoid mutating the original args array\n // We need to access and reconstruct the request options object passed to `ignoreOutgoingRequests`\n // so that it matches what Otel instrumentation passes to `ignoreOutgoingRequestHook`.\n // @see https://github.com/open-telemetry/opentelemetry-js/blob/7293e69c1e55ca62e15d0724d22605e61bd58952/experimental/packages/opentelemetry-instrumentation-http/src/http.ts#L756-L789\n const argsCopy = [...args];\n\n const options = argsCopy.shift() as URL | http.RequestOptions | string;\n\n const extraOptions =\n typeof argsCopy[0] === 'object' && (typeof options === 'string' || options instanceof URL)\n ? (argsCopy.shift() as http.RequestOptions)\n : undefined;\n\n const { optionsParsed } = getRequestInfo(instrumentation._diag, options, extraOptions);\n\n const request = original.apply(this, args) as ReturnType<typeof http.request>;\n\n request.prependListener('response', (response: http.IncomingMessage) => {\n const _breadcrumbs = instrumentation.getConfig().breadcrumbs;\n const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;\n\n const _ignoreOutgoingRequests = instrumentation.getConfig().ignoreOutgoingRequests;\n const shouldCreateBreadcrumb =\n typeof _ignoreOutgoingRequests === 'function'\n ? !_ignoreOutgoingRequests(getRequestUrl(request), optionsParsed)\n : true;\n\n if (breadCrumbsEnabled && shouldCreateBreadcrumb) {\n addRequestBreadcrumb(request, response);\n }\n });\n\n return request;\n };\n };\n }\n\n /** Path the outgoing get function for breadcrumbs. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _getPatchOutgoingGetFunction(clientRequest: (...args: any[]) => http.ClientRequest) {\n return (_original: unknown): ((...args: unknown[]) => http.ClientRequest) => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest(...args: unknown[]): http.ClientRequest {\n const req = clientRequest(...args);\n req.end();\n return req;\n };\n };\n }\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction addRequestBreadcrumb(request: http.ClientRequest, response: http.IncomingMessage): void {\n const data = getBreadcrumbData(request);\n\n const statusCode = response.statusCode;\n const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: statusCode,\n ...data,\n },\n type: 'http',\n level,\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: http.ClientRequest): Partial<SanitizedRequestData> {\n try {\n // `request.host` does not contain the port, but the host header does\n const host = request.getHeader('host') || request.host;\n const url = new URL(request.path, `${request.protocol}//${host}`);\n const parsedUrl = parseUrl(url.toString());\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\n/**\n * This method patches the request object to capture the body.\n * Instead of actually consuming the streamed body ourselves, which has potential side effects,\n * we monkey patch `req.on('data')` to intercept the body chunks.\n * This way, we only read the body if the user also consumes the body, ensuring we do not change any behavior in unexpected ways.\n */\nfunction patchRequestToCaptureBody(req: IncomingMessage, isolationScope: Scope): void {\n let bodyByteLength = 0;\n const chunks: Buffer[] = [];\n\n /**\n * We need to keep track of the original callbacks, in order to be able to remove listeners again.\n * Since `off` depends on having the exact same function reference passed in, we need to be able to map\n * original listeners to our wrapped ones.\n */\n const callbackMap = new WeakMap();\n\n try {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n req.on = new Proxy(req.on, {\n apply: (target, thisArg, args: Parameters<typeof req.on>) => {\n const [event, listener, ...restArgs] = args;\n\n if (DEBUG_BUILD) {\n logger.log(INSTRUMENTATION_NAME, 'Patching request.on', event);\n }\n\n if (event === 'data') {\n const callback = new Proxy(listener, {\n apply: (target, thisArg, args: Parameters<typeof listener>) => {\n try {\n const chunk = args[0] as Buffer | string;\n const bufferifiedChunk = Buffer.from(chunk);\n\n if (bodyByteLength < MAX_BODY_BYTE_LENGTH) {\n chunks.push(bufferifiedChunk);\n bodyByteLength += bufferifiedChunk.byteLength;\n } else if (DEBUG_BUILD) {\n logger.log(\n INSTRUMENTATION_NAME,\n `Dropping request body chunk because maximum body length of ${MAX_BODY_BYTE_LENGTH}b is exceeded.`,\n );\n }\n } catch (err) {\n DEBUG_BUILD && logger.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n callbackMap.set(listener, callback);\n\n return Reflect.apply(target, thisArg, [event, callback, ...restArgs]);\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n // Ensure we also remove callbacks correctly\n // eslint-disable-next-line @typescript-eslint/unbound-method\n req.off = new Proxy(req.off, {\n apply: (target, thisArg, args: Parameters<typeof req.off>) => {\n const [, listener] = args;\n\n const callback = callbackMap.get(listener);\n if (callback) {\n callbackMap.delete(listener);\n\n const modifiedArgs = args.slice();\n modifiedArgs[1] = callback;\n return Reflect.apply(target, thisArg, modifiedArgs);\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n req.on('end', () => {\n try {\n const body = Buffer.concat(chunks).toString('utf-8');\n if (body) {\n isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: body } });\n }\n } catch (error) {\n if (DEBUG_BUILD) {\n logger.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);\n }\n }\n });\n } catch (error) {\n if (DEBUG_BUILD) {\n logger.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);\n }\n }\n}\n\n/**\n * Starts a session and tracks it in the context of a given isolation scope.\n * When the passed response is finished, the session is put into a task and is\n * aggregated with other sessions that may happen in a certain time window\n * (sessionFlushingDelayMs).\n *\n * The sessions are always aggregated by the client that is on the current scope\n * at the time of ending the response (if there is one).\n */\n// Exported for unit tests\nexport function recordRequestSession({\n requestIsolationScope,\n response,\n sessionFlushingDelayMS,\n}: {\n requestIsolationScope: Scope;\n response: EventEmitter;\n sessionFlushingDelayMS?: number;\n}): void {\n requestIsolationScope.setSDKProcessingMetadata({\n requestSession: { status: 'ok' },\n });\n response.once('close', () => {\n // We need to grab the client off the current scope instead of the isolation scope because the isolation scope doesn't hold any client out of the box.\n const client = getClient();\n const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;\n\n if (client && requestSession) {\n DEBUG_BUILD && logger.debug(`Recorded request session with status: ${requestSession.status}`);\n\n const roundedDate = new Date();\n roundedDate.setSeconds(0, 0);\n const dateBucketKey = roundedDate.toISOString();\n\n const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client);\n const bucket = existingClientAggregate?.[dateBucketKey] || { exited: 0, crashed: 0, errored: 0 };\n bucket[({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status]]++;\n\n if (existingClientAggregate) {\n existingClientAggregate[dateBucketKey] = bucket;\n } else {\n DEBUG_BUILD && logger.debug('Opened new request session aggregate.');\n const newClientAggregate = { [dateBucketKey]: bucket };\n clientToRequestSessionAggregatesMap.set(client, newClientAggregate);\n\n const flushPendingClientAggregates = (): void => {\n clearTimeout(timeout);\n unregisterClientFlushHook();\n clientToRequestSessionAggregatesMap.delete(client);\n\n const aggregatePayload: AggregationCounts[] = Object.entries(newClientAggregate).map(\n ([timestamp, value]) => ({\n started: timestamp,\n exited: value.exited,\n errored: value.errored,\n crashed: value.crashed,\n }),\n );\n client.sendSession({ aggregates: aggregatePayload });\n };\n\n const unregisterClientFlushHook = client.on('flush', () => {\n DEBUG_BUILD && logger.debug('Sending request session aggregate due to client flush');\n flushPendingClientAggregates();\n });\n const timeout = setTimeout(() => {\n DEBUG_BUILD && logger.debug('Sending request session aggregate due to flushing schedule');\n flushPendingClientAggregates();\n }, sessionFlushingDelayMS).unref();\n }\n }\n });\n}\n\nconst clientToRequestSessionAggregatesMap = new Map<\n Client,\n { [timestampRoundedToSeconds: string]: { exited: number; crashed: number; errored: number } }\n>();\n"],"names":[],"mappings":";;;;;;;;;AAgCA,MAAM,oBAAA,GAAuB,8BAA8B;;AAuD3D;AACA,MAAM,oBAAqB,GAAE,IAAK,GAAE,IAAI;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,yBAAA,SAAkC,mBAAmB,CAAmC;AACrG,GAAS,WAAW,CAAC,MAAM,GAAqC,EAAE,EAAE;AACpE,IAAI,KAAK,CAAC,oBAAoB,EAAE,OAAO,EAAE,MAAM,CAAC;AAChD;;AAEA;AACA,GA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,CAAA,OAAA;AACA,cAAA,OAAA,EAAA,KAAA,CAAA,OAAA;AACA,aAAA,CAAA;AACA,WAAA;AACA,UAAA,MAAA,CAAA,WAAA,CAAA,EAAA,UAAA,EAAA,gBAAA,EAAA,CAAA;AACA,SAAA;;AAEA,QAAA,MAAA,yBAAA,GAAA,MAAA,CAAA,EAAA,CAAA,OAAA,EAAA,MAAA;AACA,UAAA,WAAA,IAAA,MAAA,CAAA,KAAA,CAAA,uDAAA,CAAA;AACA,UAAA,4BAAA,EAAA;AACA,SAAA,CAAA;AACA,QAAA,MAAA,OAAA,GAAA,UAAA,CAAA,MAAA;AACA,UAAA,WAAA,IAAA,MAAA,CAAA,KAAA,CAAA,4DAAA,CAAA;AACA,UAAA,4BAAA,EAAA;AACA,SAAA,EAAA,sBAAA,CAAA,CAAA,KAAA,EAAA;AACA;AACA;AACA,GAAA,CAAA;AACA;;AAEA,MAAA,mCAAA,GAAA,IAAA;;AAGA,EAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { ChannelListener } from 'node:diagnostics_channel';\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport type * as http from 'node:http';\nimport type * as https from 'node:https';\nimport type { EventEmitter } from 'node:stream';\nimport { context, propagation } from '@opentelemetry/api';\nimport { VERSION } from '@opentelemetry/core';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';\nimport type { AggregationCounts, Client, SanitizedRequestData, Scope } from '@sentry/core';\nimport {\n addBreadcrumb,\n addNonEnumerableProperty,\n generateSpanId,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getCurrentScope,\n getIsolationScope,\n getSanitizedUrlString,\n httpRequestToRequestData,\n logger,\n parseUrl,\n stripUrlQueryAndFragment,\n withIsolationScope,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getRequestUrl } from '../../utils/getRequestUrl';\n\nconst INSTRUMENTATION_NAME = '@sentry/instrumentation-http';\n\ntype Http = typeof http;\ntype Https = typeof https;\n\nexport type SentryHttpInstrumentationOptions = InstrumentationConfig & {\n /**\n * Whether breadcrumbs should be recorded for requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to extract the trace ID from the `sentry-trace` header for incoming requests.\n * By default this is done by the HttpInstrumentation, but if that is not added (e.g. because tracing is disabled, ...)\n * then this instrumentation can take over.\n *\n * @default `false`\n */\n extractIncomingTraceFromHeader?: boolean;\n\n /**\n * Do not capture breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * For the scope of this instrumentation, this callback only controls breadcrumb creation.\n * The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and\n * span creation.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed and we want to avoid capturing it.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreIncomingRequestBody?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n trackIncomingRequestsAsSessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `trackIncomingRequestsAsSessions` will be flushed as a session aggregate.\n *\n * Defaults to `60000` (60s).\n */\n sessionFlushingDelayMS?: number;\n};\n\n// We only want to capture request bodies up to 1mb.\nconst MAX_BODY_BYTE_LENGTH = 1024 * 1024;\n\n/**\n * This custom HTTP instrumentation is used to isolate incoming requests and annotate them with additional information.\n * It does not emit any spans.\n *\n * The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,\n * which would lead to Sentry not working as expected.\n *\n * Important note: Contrary to other OTEL instrumentation, this one cannot be unwrapped.\n * It only does minimal things though and does not emit any spans.\n *\n * This is heavily inspired & adapted from:\n * https://github.com/open-telemetry/opentelemetry-js/blob/f8ab5592ddea5cba0a3b33bf8d74f27872c0367f/experimental/packages/opentelemetry-instrumentation-http/src/http.ts\n */\nexport class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpInstrumentationOptions> {\n public constructor(config: SentryHttpInstrumentationOptions = {}) {\n super(INSTRUMENTATION_NAME, VERSION, config);\n }\n\n /** @inheritdoc */\n public init(): [InstrumentationNodeModuleDefinition, InstrumentationNodeModuleDefinition] {\n // We register handlers when either http or https is instrumented\n // but we only want to register them once, whichever is loaded first\n let hasRegisteredHandlers = false;\n\n const onHttpServerRequestStart = ((_data: unknown) => {\n const data = _data as { server: http.Server };\n this._patchServerEmitOnce(data.server);\n }) satisfies ChannelListener;\n\n const onHttpClientResponseFinish = ((_data: unknown) => {\n const data = _data as { request: http.ClientRequest; response: http.IncomingMessage };\n this._onOutgoingRequestFinish(data.request, data.response);\n }) satisfies ChannelListener;\n\n const onHttpClientRequestError = ((_data: unknown) => {\n const data = _data as { request: http.ClientRequest };\n this._onOutgoingRequestFinish(data.request, undefined);\n }) satisfies ChannelListener;\n\n /**\n * You may be wondering why we register these diagnostics-channel listeners\n * in such a convoluted way (as InstrumentationNodeModuleDefinition...)˝,\n * instead of simply subscribing to the events once in here.\n * The reason for this is timing semantics: These functions are called once the http or https module is loaded.\n * If we'd subscribe before that, there seem to be conflicts with the OTEL native instrumentation in some scenarios,\n * especially the \"import-on-top\" pattern of setting up ESM applications.\n */\n return [\n new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n if (hasRegisteredHandlers) {\n return moduleExports;\n }\n\n hasRegisteredHandlers = true;\n\n subscribe('http.server.request.start', onHttpServerRequestStart);\n subscribe('http.client.response.finish', onHttpClientResponseFinish);\n\n // When an error happens, we still want to have a breadcrumb\n // In this case, `http.client.response.finish` is not triggered\n subscribe('http.client.request.error', onHttpClientRequestError);\n\n return moduleExports;\n },\n () => {\n unsubscribe('http.server.request.start', onHttpServerRequestStart);\n unsubscribe('http.client.response.finish', onHttpClientResponseFinish);\n unsubscribe('http.client.request.error', onHttpClientRequestError);\n },\n ),\n new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n if (hasRegisteredHandlers) {\n return moduleExports;\n }\n\n hasRegisteredHandlers = true;\n\n subscribe('http.server.request.start', onHttpServerRequestStart);\n subscribe('http.client.response.finish', onHttpClientResponseFinish);\n\n // When an error happens, we still want to have a breadcrumb\n // In this case, `http.client.response.finish` is not triggered\n subscribe('http.client.request.error', onHttpClientRequestError);\n\n return moduleExports;\n },\n () => {\n unsubscribe('http.server.request.start', onHttpServerRequestStart);\n unsubscribe('http.client.response.finish', onHttpClientResponseFinish);\n unsubscribe('http.client.request.error', onHttpClientRequestError);\n },\n ),\n ];\n }\n\n /**\n * This is triggered when an outgoing request finishes.\n * It has access to the final request and response objects.\n */\n private _onOutgoingRequestFinish(request: http.ClientRequest, response?: http.IncomingMessage): void {\n DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');\n\n const _breadcrumbs = this.getConfig().breadcrumbs;\n const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;\n const options = getRequestOptions(request);\n\n const _ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests;\n const shouldCreateBreadcrumb =\n typeof _ignoreOutgoingRequests === 'function' ? !_ignoreOutgoingRequests(getRequestUrl(request), options) : true;\n\n if (breadCrumbsEnabled && shouldCreateBreadcrumb) {\n addRequestBreadcrumb(request, response);\n }\n }\n\n /**\n * Patch a server.emit function to handle process isolation for incoming requests.\n * This will only patch the emit function if it was not already patched.\n */\n private _patchServerEmitOnce(server: http.Server): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEmit = server.emit;\n\n // This means it was already patched, do nothing\n if ((originalEmit as { __sentry_patched__?: boolean }).__sentry_patched__) {\n return;\n }\n\n DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching server.emit');\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const instrumentation = this;\n const { ignoreIncomingRequestBody } = instrumentation.getConfig();\n\n const newEmit = new Proxy(originalEmit, {\n apply(target, thisArg, args: [event: string, ...args: unknown[]]) {\n // Only traces request events\n if (args[0] !== 'request') {\n return target.apply(thisArg, args);\n }\n\n DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling incoming request');\n\n const isolationScope = getIsolationScope().clone();\n const request = args[1] as http.IncomingMessage;\n const response = args[2] as http.OutgoingMessage;\n\n const normalizedRequest = httpRequestToRequestData(request);\n\n // request.ip is non-standard but some frameworks set this\n const ipAddress = (request as { ip?: string }).ip || request.socket?.remoteAddress;\n\n const url = request.url || '/';\n if (!ignoreIncomingRequestBody?.(url, request)) {\n patchRequestToCaptureBody(request, isolationScope);\n }\n\n // Update the isolation scope, isolate this request\n isolationScope.setSDKProcessingMetadata({ normalizedRequest, ipAddress });\n\n // attempt to update the scope's `transactionName` based on the request URL\n // Ideally, framework instrumentations coming after the HttpInstrumentation\n // update the transactionName once we get a parameterized route.\n const httpMethod = (request.method || 'GET').toUpperCase();\n const httpTarget = stripUrlQueryAndFragment(url);\n\n const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;\n\n isolationScope.setTransactionName(bestEffortTransactionName);\n\n if (instrumentation.getConfig().trackIncomingRequestsAsSessions !== false) {\n recordRequestSession({\n requestIsolationScope: isolationScope,\n response,\n sessionFlushingDelayMS: instrumentation.getConfig().sessionFlushingDelayMS ?? 60_000,\n });\n }\n\n return withIsolationScope(isolationScope, () => {\n // Set a new propagationSpanId for this request\n // We rely on the fact that `withIsolationScope()` will implicitly also fork the current scope\n // This way we can save an \"unnecessary\" `withScope()` invocation\n getCurrentScope().getPropagationContext().propagationSpanId = generateSpanId();\n\n // If we don't want to extract the trace from the header, we can skip this\n if (!instrumentation.getConfig().extractIncomingTraceFromHeader) {\n return target.apply(thisArg, args);\n }\n\n const ctx = propagation.extract(context.active(), normalizedRequest.headers);\n return context.with(ctx, () => {\n return target.apply(thisArg, args);\n });\n });\n },\n });\n\n addNonEnumerableProperty(newEmit, '__sentry_patched__', true);\n\n server.emit = newEmit;\n }\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction addRequestBreadcrumb(request: http.ClientRequest, response: http.IncomingMessage | undefined): void {\n const data = getBreadcrumbData(request);\n\n const statusCode = response?.statusCode;\n const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: statusCode,\n ...data,\n },\n type: 'http',\n level,\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: http.ClientRequest): Partial<SanitizedRequestData> {\n try {\n // `request.host` does not contain the port, but the host header does\n const host = request.getHeader('host') || request.host;\n const url = new URL(request.path, `${request.protocol}//${host}`);\n const parsedUrl = parseUrl(url.toString());\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\n/**\n * This method patches the request object to capture the body.\n * Instead of actually consuming the streamed body ourselves, which has potential side effects,\n * we monkey patch `req.on('data')` to intercept the body chunks.\n * This way, we only read the body if the user also consumes the body, ensuring we do not change any behavior in unexpected ways.\n */\nfunction patchRequestToCaptureBody(req: http.IncomingMessage, isolationScope: Scope): void {\n let bodyByteLength = 0;\n const chunks: Buffer[] = [];\n\n DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching request.on');\n\n /**\n * We need to keep track of the original callbacks, in order to be able to remove listeners again.\n * Since `off` depends on having the exact same function reference passed in, we need to be able to map\n * original listeners to our wrapped ones.\n */\n const callbackMap = new WeakMap();\n\n try {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n req.on = new Proxy(req.on, {\n apply: (target, thisArg, args: Parameters<typeof req.on>) => {\n const [event, listener, ...restArgs] = args;\n\n if (event === 'data') {\n DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling request.on(\"data\")');\n const callback = new Proxy(listener, {\n apply: (target, thisArg, args: Parameters<typeof listener>) => {\n try {\n const chunk = args[0] as Buffer | string;\n const bufferifiedChunk = Buffer.from(chunk);\n\n if (bodyByteLength < MAX_BODY_BYTE_LENGTH) {\n chunks.push(bufferifiedChunk);\n bodyByteLength += bufferifiedChunk.byteLength;\n } else if (DEBUG_BUILD) {\n logger.log(\n INSTRUMENTATION_NAME,\n `Dropping request body chunk because maximum body length of ${MAX_BODY_BYTE_LENGTH}b is exceeded.`,\n );\n }\n } catch (err) {\n DEBUG_BUILD && logger.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n callbackMap.set(listener, callback);\n\n return Reflect.apply(target, thisArg, [event, callback, ...restArgs]);\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n // Ensure we also remove callbacks correctly\n // eslint-disable-next-line @typescript-eslint/unbound-method\n req.off = new Proxy(req.off, {\n apply: (target, thisArg, args: Parameters<typeof req.off>) => {\n const [, listener] = args;\n\n const callback = callbackMap.get(listener);\n if (callback) {\n callbackMap.delete(listener);\n\n const modifiedArgs = args.slice();\n modifiedArgs[1] = callback;\n return Reflect.apply(target, thisArg, modifiedArgs);\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n\n req.on('end', () => {\n try {\n const body = Buffer.concat(chunks).toString('utf-8');\n if (body) {\n isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: body } });\n }\n } catch (error) {\n if (DEBUG_BUILD) {\n logger.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);\n }\n }\n });\n } catch (error) {\n if (DEBUG_BUILD) {\n logger.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);\n }\n }\n}\n\nfunction getRequestOptions(request: http.ClientRequest): http.RequestOptions {\n return {\n method: request.method,\n protocol: request.protocol,\n host: request.host,\n hostname: request.host,\n path: request.path,\n headers: request.getHeaders(),\n };\n}\n\n/**\n * Starts a session and tracks it in the context of a given isolation scope.\n * When the passed response is finished, the session is put into a task and is\n * aggregated with other sessions that may happen in a certain time window\n * (sessionFlushingDelayMs).\n *\n * The sessions are always aggregated by the client that is on the current scope\n * at the time of ending the response (if there is one).\n */\n// Exported for unit tests\nexport function recordRequestSession({\n requestIsolationScope,\n response,\n sessionFlushingDelayMS,\n}: {\n requestIsolationScope: Scope;\n response: EventEmitter;\n sessionFlushingDelayMS?: number;\n}): void {\n requestIsolationScope.setSDKProcessingMetadata({\n requestSession: { status: 'ok' },\n });\n response.once('close', () => {\n // We need to grab the client off the current scope instead of the isolation scope because the isolation scope doesn't hold any client out of the box.\n const client = getClient();\n const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;\n\n if (client && requestSession) {\n DEBUG_BUILD && logger.debug(`Recorded request session with status: ${requestSession.status}`);\n\n const roundedDate = new Date();\n roundedDate.setSeconds(0, 0);\n const dateBucketKey = roundedDate.toISOString();\n\n const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client);\n const bucket = existingClientAggregate?.[dateBucketKey] || { exited: 0, crashed: 0, errored: 0 };\n bucket[({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status]]++;\n\n if (existingClientAggregate) {\n existingClientAggregate[dateBucketKey] = bucket;\n } else {\n DEBUG_BUILD && logger.debug('Opened new request session aggregate.');\n const newClientAggregate = { [dateBucketKey]: bucket };\n clientToRequestSessionAggregatesMap.set(client, newClientAggregate);\n\n const flushPendingClientAggregates = (): void => {\n clearTimeout(timeout);\n unregisterClientFlushHook();\n clientToRequestSessionAggregatesMap.delete(client);\n\n const aggregatePayload: AggregationCounts[] = Object.entries(newClientAggregate).map(\n ([timestamp, value]) => ({\n started: timestamp,\n exited: value.exited,\n errored: value.errored,\n crashed: value.crashed,\n }),\n );\n client.sendSession({ aggregates: aggregatePayload });\n };\n\n const unregisterClientFlushHook = client.on('flush', () => {\n DEBUG_BUILD && logger.debug('Sending request session aggregate due to client flush');\n flushPendingClientAggregates();\n });\n const timeout = setTimeout(() => {\n DEBUG_BUILD && logger.debug('Sending request session aggregate due to flushing schedule');\n flushPendingClientAggregates();\n }, sessionFlushingDelayMS).unref();\n }\n }\n });\n}\n\nconst clientToRequestSessionAggregatesMap = new Map<\n Client,\n { [timestampRoundedToSeconds: string]: { exited: number; crashed: number; errored: number } }\n>();\n"],"names":[],"mappings":";;;;;;;;AA6BA,MAAM,oBAAA,GAAuB,8BAA8B;;AA0D3D;AACA,MAAM,oBAAqB,GAAE,IAAK,GAAE,IAAI;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,yBAAA,SAAkC,mBAAmB,CAAmC;AACrG,GAAS,WAAW,CAAC,MAAM,GAAqC,EAAE,EAAE;AACpE,IAAI,KAAK,CAAC,oBAAoB,EAAE,OAAO,EAAE,MAAM,CAAC;AAChD;;AAEA;AACA,GAAS,IAAI,GAA+E;AAC5F;AACA;AACA,IAAI,IAAI,qBAAsB,GAAE,KAAK;;AAErC,IAAI,MAAM,wBAAyB,IAAG,CAAC,KAAK,KAAc;AAC1D,MAAM,MAAM,IAAK,GAAE,KAAM;AACzB,MAAM,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC;AAC5C,KAAK,CAAE;;AAEP,IAAI,MAAM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AA,GAAA,MAAA,CAAA,OAAA,CAAA,kBAAA,CAAA,CAAA,GAAA;AACA,YAAA,CAAA,CAAA,SAAA,EAAA,KAAA,CAAA,MAAA;AACA,cAAA,OAAA,EAAA,SAAA;AACA,cAAA,MAAA,EAAA,KAAA,CAAA,MAAA;AACA,cAAA,OAAA,EAAA,KAAA,CAAA,OAAA;AACA,cAAA,OAAA,EAAA,KAAA,CAAA,OAAA;AACA,aAAA,CAAA;AACA,WAAA;AACA,UAAA,MAAA,CAAA,WAAA,CAAA,EAAA,UAAA,EAAA,gBAAA,EAAA,CAAA;AACA,SAAA;;AAEA,QAAA,MAAA,yBAAA,GAAA,MAAA,CAAA,EAAA,CAAA,OAAA,EAAA,MAAA;AACA,UAAA,WAAA,IAAA,MAAA,CAAA,KAAA,CAAA,uDAAA,CAAA;AACA,UAAA,4BAAA,EAAA;AACA,SAAA,CAAA;AACA,QAAA,MAAA,OAAA,GAAA,UAAA,CAAA,MAAA;AACA,UAAA,WAAA,IAAA,MAAA,CAAA,KAAA,CAAA,4DAAA,CAAA;AACA,UAAA,4BAAA,EAAA;AACA,SAAA,EAAA,sBAAA,CAAA,CAAA,KAAA,EAAA;AACA;AACA;AACA,GAAA,CAAA;AACA;;AAEA,MAAA,mCAAA,GAAA,IAAA;;AAGA,EAAA;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { VERSION } from '@opentelemetry/core';
|
|
2
2
|
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
|
|
3
|
-
import {
|
|
3
|
+
import { logger, vercelWaitUntil, flush } from '@sentry/core';
|
|
4
4
|
import { DEBUG_BUILD } from '../../debug-build.js';
|
|
5
5
|
import { stealthWrap } from './utils.js';
|
|
6
6
|
|
|
@@ -63,8 +63,7 @@ class SentryHttpInstrumentationBeforeOtel extends InstrumentationBase {
|
|
|
63
63
|
return original.apply(this, args);
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
const response = args[
|
|
67
|
-
|
|
66
|
+
const response = args[2] ;
|
|
68
67
|
patchResponseToFlushOnServerlessPlatforms(response);
|
|
69
68
|
|
|
70
69
|
return original.apply(this, args);
|
|
@@ -76,51 +75,58 @@ class SentryHttpInstrumentationBeforeOtel extends InstrumentationBase {
|
|
|
76
75
|
function patchResponseToFlushOnServerlessPlatforms(res) {
|
|
77
76
|
// Freely extend this function with other platforms if necessary
|
|
78
77
|
if (process.env.VERCEL) {
|
|
78
|
+
DEBUG_BUILD && logger.log('Patching response to flush on Vercel');
|
|
79
|
+
|
|
79
80
|
// In some cases res.end does not seem to be defined leading to errors if passed to Proxy
|
|
80
81
|
// https://github.com/getsentry/sentry-javascript/issues/15759
|
|
81
|
-
if (typeof res.end
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
markOnEndDone = res;
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
res.on('close', () => {
|
|
88
|
-
markOnEndDone();
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
92
|
-
res.end = new Proxy(res.end, {
|
|
93
|
-
apply(target, thisArg, argArray) {
|
|
94
|
-
vercelWaitUntil(
|
|
95
|
-
new Promise(finishWaitUntil => {
|
|
96
|
-
// Define a timeout that unblocks the lambda just to be safe so we're not indefinitely keeping it alive, exploding server bills
|
|
97
|
-
const timeout = setTimeout(() => {
|
|
98
|
-
finishWaitUntil();
|
|
99
|
-
}, 2000);
|
|
100
|
-
|
|
101
|
-
onEndDonePromise
|
|
102
|
-
.then(() => {
|
|
103
|
-
DEBUG_BUILD && logger.log('Flushing events before Vercel Lambda freeze');
|
|
104
|
-
return flush(2000);
|
|
105
|
-
})
|
|
106
|
-
.then(
|
|
107
|
-
() => {
|
|
108
|
-
clearTimeout(timeout);
|
|
109
|
-
finishWaitUntil();
|
|
110
|
-
},
|
|
111
|
-
e => {
|
|
112
|
-
clearTimeout(timeout);
|
|
113
|
-
DEBUG_BUILD && logger.log('Error while flushing events for Vercel:\n', e);
|
|
114
|
-
finishWaitUntil();
|
|
115
|
-
},
|
|
116
|
-
);
|
|
117
|
-
}),
|
|
118
|
-
);
|
|
119
|
-
|
|
120
|
-
return target.apply(thisArg, argArray);
|
|
121
|
-
},
|
|
122
|
-
});
|
|
82
|
+
if (typeof res.end !== 'function') {
|
|
83
|
+
DEBUG_BUILD && logger.warn('res.end is not a function, skipping patch...');
|
|
84
|
+
return;
|
|
123
85
|
}
|
|
86
|
+
|
|
87
|
+
let markOnEndDone = () => undefined;
|
|
88
|
+
const onEndDonePromise = new Promise(res => {
|
|
89
|
+
markOnEndDone = res;
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
res.on('close', () => {
|
|
93
|
+
markOnEndDone();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
logger.log('Patching res.end()');
|
|
97
|
+
|
|
98
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
99
|
+
res.end = new Proxy(res.end, {
|
|
100
|
+
apply(target, thisArg, argArray) {
|
|
101
|
+
vercelWaitUntil(
|
|
102
|
+
new Promise(finishWaitUntil => {
|
|
103
|
+
// Define a timeout that unblocks the lambda just to be safe so we're not indefinitely keeping it alive, exploding server bills
|
|
104
|
+
const timeout = setTimeout(() => {
|
|
105
|
+
finishWaitUntil();
|
|
106
|
+
}, 2000);
|
|
107
|
+
|
|
108
|
+
onEndDonePromise
|
|
109
|
+
.then(() => {
|
|
110
|
+
DEBUG_BUILD && logger.log('Flushing events before Vercel Lambda freeze');
|
|
111
|
+
return flush(2000);
|
|
112
|
+
})
|
|
113
|
+
.then(
|
|
114
|
+
() => {
|
|
115
|
+
clearTimeout(timeout);
|
|
116
|
+
finishWaitUntil();
|
|
117
|
+
},
|
|
118
|
+
e => {
|
|
119
|
+
clearTimeout(timeout);
|
|
120
|
+
DEBUG_BUILD && logger.log('Error while flushing events for Vercel:\n', e);
|
|
121
|
+
finishWaitUntil();
|
|
122
|
+
},
|
|
123
|
+
);
|
|
124
|
+
}),
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
return target.apply(thisArg, argArray);
|
|
128
|
+
},
|
|
129
|
+
});
|
|
124
130
|
}
|
|
125
131
|
}
|
|
126
132
|
|