-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathnode-fetch.ts
204 lines (171 loc) · 6.61 KB
/
node-fetch.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
import type { Span } from '@opentelemetry/api';
import { trace } from '@opentelemetry/api';
import { context, propagation } from '@opentelemetry/api';
import { addBreadcrumb, defineIntegration, getCurrentScope, hasTracingEnabled } from '@sentry/core';
import {
addOpenTelemetryInstrumentation,
generateSpanContextForPropagationContext,
getPropagationContextFromSpan,
} from '@sentry/opentelemetry';
import type { IntegrationFn, SanitizedRequestData } from '@sentry/types';
import { getSanitizedUrlString, logger, parseUrl } from '@sentry/utils';
import { DEBUG_BUILD } from '../debug-build';
import { NODE_MAJOR } from '../nodeVersion';
import type { FetchInstrumentation } from 'opentelemetry-instrumentation-fetch-node';
import { addOriginToSpan } from '../utils/addOriginToSpan';
interface FetchRequest {
method: string;
origin: string;
path: string;
headers: string | string[];
}
interface FetchResponse {
headers: Buffer[];
statusCode: number;
}
interface NodeFetchOptions {
/**
* Whether breadcrumbs should be recorded for requests.
* Defaults to true
*/
breadcrumbs?: boolean;
/**
* Do not capture spans or breadcrumbs for outgoing fetch 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;
}
const _nativeNodeFetchIntegration = ((options: NodeFetchOptions = {}) => {
const _breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;
const _ignoreOutgoingRequests = options.ignoreOutgoingRequests;
async function getInstrumentation(): Promise<FetchInstrumentation | void> {
// Only add NodeFetch if Node >= 18, as previous versions do not support it
if (NODE_MAJOR < 18) {
DEBUG_BUILD && logger.log('NodeFetch is not supported on Node < 18, skipping instrumentation...');
return;
}
try {
const pkg = await import('opentelemetry-instrumentation-fetch-node');
const { FetchInstrumentation } = pkg;
class SentryNodeFetchInstrumentation extends FetchInstrumentation {
// We extend this method so we have access to request _and_ response for the breadcrumb
public onHeaders({ request, response }: { request: FetchRequest; response: FetchResponse }): void {
if (_breadcrumbs) {
_addRequestBreadcrumb(request, response);
}
return super.onHeaders({ request, response });
}
}
return new SentryNodeFetchInstrumentation({
ignoreRequestHook: (request: FetchRequest) => {
const url = getAbsoluteUrl(request.origin, request.path);
const tracingDisabled = !hasTracingEnabled();
const shouldIgnore = _ignoreOutgoingRequests && url && _ignoreOutgoingRequests(url);
if (shouldIgnore) {
return true;
}
// If tracing is disabled, we still want to propagate traces
// So we do that manually here, matching what the instrumentation does otherwise
if (tracingDisabled) {
const ctx = context.active();
const addedHeaders: Record<string, string> = {};
// We generate a virtual span context from the active one,
// Where we attach the URL to the trace state, so the propagator can pick it up
const activeSpan = trace.getSpan(ctx);
const propagationContext = activeSpan
? getPropagationContextFromSpan(activeSpan)
: getCurrentScope().getPropagationContext();
const spanContext = generateSpanContextForPropagationContext(propagationContext);
// We know that in practice we'll _always_ haven a traceState here
spanContext.traceState = spanContext.traceState?.set('sentry.url', url);
const ctxWithUrlTraceState = trace.setSpanContext(ctx, spanContext);
propagation.inject(ctxWithUrlTraceState, addedHeaders);
const requestHeaders = request.headers;
if (Array.isArray(requestHeaders)) {
Object.entries(addedHeaders).forEach(headers => requestHeaders.push(...headers));
} else {
request.headers += Object.entries(addedHeaders)
.map(([k, v]) => `${k}: ${v}\r\n`)
.join('');
}
// Prevent starting a span for this request
return true;
}
return false;
},
onRequest: ({ span }: { span: Span }) => {
_updateSpan(span);
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
} catch (error) {
// Could not load instrumentation
DEBUG_BUILD && logger.log('Error while loading NodeFetch instrumentation: \n', error);
}
}
return {
name: 'NodeFetch',
setupOnce() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
getInstrumentation().then(instrumentation => {
if (instrumentation) {
addOpenTelemetryInstrumentation(instrumentation);
}
});
},
};
}) satisfies IntegrationFn;
export const nativeNodeFetchIntegration = defineIntegration(_nativeNodeFetchIntegration);
/** Update the span with data we need. */
function _updateSpan(span: Span): void {
addOriginToSpan(span, 'auto.http.otel.node_fetch');
}
/** Add a breadcrumb for outgoing requests. */
function _addRequestBreadcrumb(request: FetchRequest, response: FetchResponse): void {
const data = getBreadcrumbData(request);
addBreadcrumb(
{
category: 'http',
data: {
status_code: response.statusCode,
...data,
},
type: 'http',
},
{
event: 'response',
request,
response,
},
);
}
function getBreadcrumbData(request: FetchRequest): Partial<SanitizedRequestData> {
try {
const url = new URL(request.path, request.origin);
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 {};
}
}
// Matching the behavior of the base instrumentation
function getAbsoluteUrl(origin: string, path: string = '/'): string {
const url = `${origin}`;
if (url.endsWith('/') && path.startsWith('/')) {
return `${url}${path.slice(1)}`;
}
if (!url.endsWith('/') && !path.startsWith('/')) {
return `${url}/${path.slice(1)}`;
}
return `${url}${path}`;
}