-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhttp.ts
218 lines (185 loc) · 7.45 KB
/
http.ts
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
import type { ClientRequest, ServerResponse } from 'node:http';
import type { Span } from '@opentelemetry/api';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { addOpenTelemetryInstrumentation } from '@sentry/opentelemetry';
import {
addBreadcrumb,
defineIntegration,
getCapturedScopesOnSpan,
getCurrentScope,
getIsolationScope,
isSentryRequestUrl,
setCapturedScopesOnSpan,
} from '@sentry/core';
import { getClient } from '@sentry/opentelemetry';
import type { IntegrationFn, SanitizedRequestData } from '@sentry/types';
import { getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment } from '@sentry/utils';
import type { NodeClient } from '../sdk/client';
import { setIsolationScope } from '../sdk/scope';
import type { HTTPModuleRequestIncomingMessage } from '../transports/http-module';
import { addOriginToSpan } from '../utils/addOriginToSpan';
import { getRequestUrl } from '../utils/getRequestUrl';
interface HttpOptions {
/**
* Whether breadcrumbs should be recorded for requests.
* Defaults to true
*/
breadcrumbs?: boolean;
/**
* Do not capture spans or breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.
* This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.
*/
ignoreOutgoingRequests?: (url: string) => boolean;
/**
* Do not capture spans or breadcrumbs for incoming HTTP requests to URLs where the given callback returns `true`.
* This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.
*/
ignoreIncomingRequests?: (url: string) => boolean;
/** Allows to pass a custom version of HttpInstrumentation. We use this for Next.js. */
_instrumentation?: typeof HttpInstrumentation;
}
const _httpIntegration = ((options: HttpOptions = {}) => {
const _breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;
const _ignoreOutgoingRequests = options.ignoreOutgoingRequests;
const _ignoreIncomingRequests = options.ignoreIncomingRequests;
const _InstrumentationClass = options._instrumentation || HttpInstrumentation;
return {
name: 'Http',
setupOnce() {
addOpenTelemetryInstrumentation(
new _InstrumentationClass({
ignoreOutgoingRequestHook: request => {
const url = getRequestUrl(request);
if (!url) {
return false;
}
if (isSentryRequestUrl(url, getClient())) {
return true;
}
if (_ignoreOutgoingRequests && _ignoreOutgoingRequests(url)) {
return true;
}
return false;
},
ignoreIncomingRequestHook: request => {
const url = getRequestUrl(request);
const method = request.method?.toUpperCase();
// We do not capture OPTIONS/HEAD requests as transactions
if (method === 'OPTIONS' || method === 'HEAD') {
return true;
}
if (_ignoreIncomingRequests && _ignoreIncomingRequests(url)) {
return true;
}
return false;
},
requireParentforOutgoingSpans: false,
requireParentforIncomingSpans: false,
requestHook: (span, req) => {
addOriginToSpan(span, 'auto.http.otel.http');
// both, incoming requests and "client" requests made within the app trigger the requestHook
// we only want to isolate and further annotate incoming requests (IncomingMessage)
if (_isClientRequest(req)) {
return;
}
const scopes = getCapturedScopesOnSpan(span);
const isolationScope = (scopes.isolationScope || getIsolationScope()).clone();
const scope = scopes.scope || getCurrentScope();
// Update the isolation scope, isolate this request
isolationScope.setSDKProcessingMetadata({ request: req });
const client = getClient<NodeClient>();
if (client && client.getOptions().autoSessionTracking) {
isolationScope.setRequestSession({ status: 'ok' });
}
setIsolationScope(isolationScope);
setCapturedScopesOnSpan(span, scope, isolationScope);
// attempt to update the scope's `transactionName` based on the request URL
// Ideally, framework instrumentations coming after the HttpInstrumentation
// update the transactionName once we get a parameterized route.
const httpMethod = (req.method || 'GET').toUpperCase();
const httpTarget = stripUrlQueryAndFragment(req.url || '/');
const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;
isolationScope.setTransactionName(bestEffortTransactionName);
},
responseHook: () => {
const client = getClient<NodeClient>();
if (client && client.getOptions().autoSessionTracking) {
setImmediate(() => {
client['_captureRequestSession']();
});
}
},
applyCustomAttributesOnSpan: (
_span: Span,
request: ClientRequest | HTTPModuleRequestIncomingMessage,
response: HTTPModuleRequestIncomingMessage | ServerResponse,
) => {
if (_breadcrumbs) {
_addRequestBreadcrumb(request, response);
}
},
}),
);
},
};
}) satisfies IntegrationFn;
/**
* The http integration instruments Node's internal http and https modules.
* It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.
*/
export const httpIntegration = defineIntegration(_httpIntegration);
/** Add a breadcrumb for outgoing requests. */
function _addRequestBreadcrumb(
request: ClientRequest | HTTPModuleRequestIncomingMessage,
response: HTTPModuleRequestIncomingMessage | ServerResponse,
): void {
// Only generate breadcrumbs for outgoing requests
if (!_isClientRequest(request)) {
return;
}
const data = getBreadcrumbData(request);
addBreadcrumb(
{
category: 'http',
data: {
status_code: response.statusCode,
...data,
},
type: 'http',
},
{
event: 'response',
request,
response,
},
);
}
function getBreadcrumbData(request: ClientRequest): Partial<SanitizedRequestData> {
try {
// `request.host` does not contain the port, but the host header does
const host = request.getHeader('host') || request.host;
const url = new URL(request.path, `${request.protocol}//${host}`);
const parsedUrl = parseUrl(url.toString());
const data: Partial<SanitizedRequestData> = {
url: getSanitizedUrlString(parsedUrl),
'http.method': request.method || 'GET',
};
if (parsedUrl.search) {
data['http.query'] = parsedUrl.search;
}
if (parsedUrl.hash) {
data['http.fragment'] = parsedUrl.hash;
}
return data;
} catch {
return {};
}
}
/**
* Determines if @param req is a ClientRequest, meaning the request was created within the express app
* and it's an outgoing request.
* Checking for properties instead of using `instanceOf` to avoid importing the request classes.
*/
function _isClientRequest(req: ClientRequest | HTTPModuleRequestIncomingMessage): req is ClientRequest {
return 'outputData' in req && 'outputSize' in req && !('client' in req) && !('statusCode' in req);
}