Skip to content

Commit 4c6e295

Browse files
committed
feat(node): Extract Sentry-specific node-fetch instrumentation
To allow users to opt-out of using the otel instrumentation.
1 parent d76db31 commit 4c6e295

File tree

7 files changed

+463
-114
lines changed

7 files changed

+463
-114
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { loggingTransport } from '@sentry-internal/node-integration-tests';
2+
import * as Sentry from '@sentry/node';
3+
4+
Sentry.init({
5+
dsn: 'https://[email protected]/1337',
6+
release: '1.0',
7+
tracePropagationTargets: [/\/v0/, 'v1'],
8+
integrations: [Sentry.nativeNodeFetchIntegration({ spans: false })],
9+
transport: loggingTransport,
10+
});
11+
12+
async function run(): Promise<void> {
13+
// Since fetch is lazy loaded, we need to wait a bit until it's fully instrumented
14+
await new Promise(resolve => setTimeout(resolve, 100));
15+
await fetch(`${process.env.SERVER_URL}/api/v0`).then(res => res.text());
16+
await fetch(`${process.env.SERVER_URL}/api/v1`).then(res => res.text());
17+
await fetch(`${process.env.SERVER_URL}/api/v2`).then(res => res.text());
18+
await fetch(`${process.env.SERVER_URL}/api/v3`).then(res => res.text());
19+
20+
Sentry.captureException(new Error('foo'));
21+
}
22+
23+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
24+
run();
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { createRunner } from '../../../../utils/runner';
2+
import { createTestServer } from '../../../../utils/server';
3+
4+
describe('outgoing fetch', () => {
5+
test('outgoing fetch requests are correctly instrumented with tracing & spans are disabled', done => {
6+
expect.assertions(11);
7+
8+
createTestServer(done)
9+
.get('/api/v0', headers => {
10+
expect(headers['sentry-trace']).toEqual(expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})$/));
11+
expect(headers['sentry-trace']).not.toEqual('00000000000000000000000000000000-0000000000000000');
12+
expect(headers['baggage']).toEqual(expect.any(String));
13+
})
14+
.get('/api/v1', headers => {
15+
expect(headers['sentry-trace']).toEqual(expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})$/));
16+
expect(headers['sentry-trace']).not.toEqual('00000000000000000000000000000000-0000000000000000');
17+
expect(headers['baggage']).toEqual(expect.any(String));
18+
})
19+
.get('/api/v2', headers => {
20+
expect(headers['baggage']).toBeUndefined();
21+
expect(headers['sentry-trace']).toBeUndefined();
22+
})
23+
.get('/api/v3', headers => {
24+
expect(headers['baggage']).toBeUndefined();
25+
expect(headers['sentry-trace']).toBeUndefined();
26+
})
27+
.start()
28+
.then(([SERVER_URL, closeTestServer]) => {
29+
createRunner(__dirname, 'scenario.ts')
30+
.withEnv({ SERVER_URL })
31+
.ensureNoErrorOutput()
32+
.expect({
33+
event: {
34+
exception: {
35+
values: [
36+
{
37+
type: 'Error',
38+
value: 'foo',
39+
},
40+
],
41+
},
42+
},
43+
})
44+
.start(closeTestServer);
45+
});
46+
});
47+
});
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
import { VERSION } from '@opentelemetry/core';
2+
import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
3+
import { InstrumentationBase } from '@opentelemetry/instrumentation';
4+
import type { SanitizedRequestData } from '@sentry/core';
5+
import { LRUMap, getClient, getTraceData } from '@sentry/core';
6+
import { addBreadcrumb, getBreadcrumbLogLevelFromHttpStatusCode, getSanitizedUrlString, parseUrl } from '@sentry/core';
7+
import { shouldPropagateTraceForUrl } from '@sentry/opentelemetry';
8+
import * as diagch from 'diagnostics_channel';
9+
import { NODE_MAJOR, NODE_MINOR } from '../../nodeVersion';
10+
import type { UndiciRequest, UndiciResponse } from './types';
11+
12+
export type SentryNodeFetchInstrumentationOptions = InstrumentationConfig & {
13+
/**
14+
* Whether breadcrumbs should be recorded for requests.
15+
*
16+
* @default `true`
17+
*/
18+
breadcrumbs?: boolean;
19+
20+
/**
21+
* Do not capture breadcrumbs for outgoing fetch requests to URLs where the given callback returns `true`.
22+
* For the scope of this instrumentation, this callback only controls breadcrumb creation.
23+
* The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and
24+
* span creation.
25+
*
26+
* @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.
27+
*/
28+
ignoreOutgoingRequests?: (url: string) => boolean;
29+
};
30+
31+
interface ListenerRecord {
32+
name: string;
33+
unsubscribe: () => void;
34+
}
35+
36+
/**
37+
* This custom node-fetch instrumentation is used to instrument outgoing fetch requests.
38+
* It does not emit any spans.
39+
*
40+
* The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,
41+
* which would lead to Sentry not working as expected.
42+
*
43+
* This is heavily inspired & adapted from:
44+
* https://github.com/open-telemetry/opentelemetry-js-contrib/blob/28e209a9da36bc4e1f8c2b0db7360170ed46cb80/plugins/node/instrumentation-undici/src/undici.ts
45+
*/
46+
export class SentryNodeFetchInstrumentation extends InstrumentationBase<SentryNodeFetchInstrumentationOptions> {
47+
// Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug and for
48+
// unsubscribing.
49+
private _channelSubs: Array<ListenerRecord>;
50+
private _propagationDecisionMap: LRUMap<string, boolean>;
51+
52+
public constructor(config: SentryNodeFetchInstrumentationOptions = {}) {
53+
super('@sentry/instrumentation-node-fetch', VERSION, config);
54+
this._channelSubs = [];
55+
this._propagationDecisionMap = new LRUMap<string, boolean>(100);
56+
}
57+
58+
/** No need to instrument files/modules. */
59+
public init(): void {
60+
return undefined;
61+
}
62+
63+
/** Disable the instrumentation. */
64+
public disable(): void {
65+
super.disable();
66+
this._channelSubs.forEach(sub => sub.unsubscribe());
67+
this._channelSubs = [];
68+
}
69+
70+
/** Enable the instrumentation. */
71+
public enable(): void {
72+
// "enabled" handling is currently a bit messy with InstrumentationBase.
73+
// If constructed with `{enabled: false}`, this `.enable()` is still called,
74+
// and `this.getConfig().enabled !== this.isEnabled()`, creating confusion.
75+
//
76+
// For now, this class will setup for instrumenting if `.enable()` is
77+
// called, but use `this.getConfig().enabled` to determine if
78+
// instrumentation should be generated. This covers the more likely common
79+
// case of config being given a construction time, rather than later via
80+
// `instance.enable()`, `.disable()`, or `.setConfig()` calls.
81+
super.enable();
82+
83+
// This method is called by the super-class constructor before ours is
84+
// called. So we need to ensure the property is initalized.
85+
this._channelSubs = this._channelSubs || [];
86+
87+
// Avoid to duplicate subscriptions
88+
if (this._channelSubs.length > 0) {
89+
return;
90+
}
91+
92+
this._subscribeToChannel('undici:request:create', this._onRequestCreated.bind(this));
93+
this._subscribeToChannel('undici:request:headers', this._onResponseHeaders.bind(this));
94+
}
95+
96+
/**
97+
* This method is called when a request is created.
98+
* You can still mutate the request here before it is sent.
99+
*/
100+
private _onRequestCreated({ request }: { request: UndiciRequest }): void {
101+
const config = this.getConfig();
102+
const enabled = config.enabled !== false;
103+
104+
if (!enabled) {
105+
return;
106+
}
107+
108+
// Add trace propagation headers
109+
const url = getAbsoluteUrl(request.origin, request.path);
110+
const _ignoreOutgoingRequests = config.ignoreOutgoingRequests;
111+
const shouldIgnore = _ignoreOutgoingRequests && url && _ignoreOutgoingRequests(url);
112+
113+
if (shouldIgnore) {
114+
return;
115+
}
116+
117+
// Manually add the trace headers, if it applies
118+
// Note: We do not use `propagation.inject()` here, because our propagator relies on an active span
119+
// Which we do not have in this case
120+
// The propagator _may_ overwrite this, but this should be fine as it is the same data
121+
const tracePropagationTargets = getClient()?.getOptions().tracePropagationTargets;
122+
const addedHeaders = shouldPropagateTraceForUrl(url, tracePropagationTargets, this._propagationDecisionMap)
123+
? getTraceData()
124+
: {};
125+
126+
// We do not want to overwrite existing headers here
127+
// If the core UndiciInstrumentation is registered, it will already have set the headers
128+
// We do not want to add any then
129+
if (Array.isArray(request.headers)) {
130+
const requestHeaders = request.headers;
131+
Object.entries(addedHeaders)
132+
.filter(([k]) => {
133+
// If the header already exists, we do not want to set it again
134+
return !requestHeaders.includes(`${k}:`);
135+
})
136+
.forEach(headers => requestHeaders.push(...headers));
137+
} else {
138+
const requestHeaders = request.headers;
139+
request.headers += Object.entries(addedHeaders)
140+
.filter(([k]) => {
141+
// If the header already exists, we do not want to set it again
142+
return !requestHeaders.includes(`${k}:`);
143+
})
144+
.map(([k, v]) => `${k}: ${v}\r\n`)
145+
.join('');
146+
}
147+
}
148+
149+
/**
150+
* This method is called when a response is received.
151+
*/
152+
private _onResponseHeaders({ request, response }: { request: UndiciRequest; response: UndiciResponse }): void {
153+
const config = this.getConfig();
154+
const enabled = config.enabled !== false;
155+
156+
if (!enabled) {
157+
return;
158+
}
159+
160+
const _breadcrumbs = config.breadcrumbs;
161+
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
162+
163+
const _ignoreOutgoingRequests = config.ignoreOutgoingRequests;
164+
const shouldCreateBreadcrumb =
165+
typeof _ignoreOutgoingRequests === 'function'
166+
? !_ignoreOutgoingRequests(getAbsoluteUrl(request.origin, request.path))
167+
: true;
168+
169+
if (breadCrumbsEnabled && shouldCreateBreadcrumb) {
170+
addRequestBreadcrumb(request, response);
171+
}
172+
}
173+
174+
/** Subscribe to a diagnostics channel. */
175+
private _subscribeToChannel(
176+
diagnosticChannel: string,
177+
onMessage: (message: unknown, name: string | symbol) => void,
178+
): void {
179+
// `diagnostics_channel` had a ref counting bug until v18.19.0.
180+
// https://github.com/nodejs/node/pull/47520
181+
const useNewSubscribe = NODE_MAJOR > 18 || (NODE_MAJOR === 18 && NODE_MINOR >= 19);
182+
183+
let unsubscribe: () => void;
184+
if (useNewSubscribe) {
185+
diagch.subscribe?.(diagnosticChannel, onMessage);
186+
unsubscribe = () => diagch.unsubscribe?.(diagnosticChannel, onMessage);
187+
} else {
188+
const channel = diagch.channel(diagnosticChannel);
189+
channel.subscribe(onMessage);
190+
unsubscribe = () => channel.unsubscribe(onMessage);
191+
}
192+
193+
this._channelSubs.push({
194+
name: diagnosticChannel,
195+
unsubscribe,
196+
});
197+
}
198+
}
199+
200+
/** Add a breadcrumb for outgoing requests. */
201+
function addRequestBreadcrumb(request: UndiciRequest, response: UndiciResponse): void {
202+
const data = getBreadcrumbData(request);
203+
204+
const statusCode = response.statusCode;
205+
const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);
206+
207+
addBreadcrumb(
208+
{
209+
category: 'http',
210+
data: {
211+
status_code: statusCode,
212+
...data,
213+
},
214+
type: 'http',
215+
level,
216+
},
217+
{
218+
event: 'response',
219+
request,
220+
response,
221+
},
222+
);
223+
}
224+
225+
function getBreadcrumbData(request: UndiciRequest): Partial<SanitizedRequestData> {
226+
try {
227+
const url = getAbsoluteUrl(request.origin, request.path);
228+
const parsedUrl = parseUrl(url);
229+
230+
const data: Partial<SanitizedRequestData> = {
231+
url: getSanitizedUrlString(parsedUrl),
232+
'http.method': request.method || 'GET',
233+
};
234+
235+
if (parsedUrl.search) {
236+
data['http.query'] = parsedUrl.search;
237+
}
238+
if (parsedUrl.hash) {
239+
data['http.fragment'] = parsedUrl.hash;
240+
}
241+
242+
return data;
243+
} catch {
244+
return {};
245+
}
246+
}
247+
248+
function getAbsoluteUrl(origin: string, path: string = '/'): string {
249+
try {
250+
const url = new URL(path, origin);
251+
return url.toString();
252+
} catch {
253+
// fallback: Construct it on our own
254+
const url = `${origin}`;
255+
256+
if (url.endsWith('/') && path.startsWith('/')) {
257+
return `${url}${path.slice(1)}`;
258+
}
259+
260+
if (!url.endsWith('/') && !path.startsWith('/')) {
261+
return `${url}/${path.slice(1)}`;
262+
}
263+
264+
return `${url}${path}`;
265+
}
266+
}

0 commit comments

Comments
 (0)