Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(node): Undici integration #7582

Merged
merged 11 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/node/src/integrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { ContextLines } from './contextlines';
export { Context } from './context';
export { RequestData } from './requestdata';
export { LocalVariables } from './localvariables';
export { Undici } from './undici';
220 changes: 220 additions & 0 deletions packages/node/src/integrations/undici/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import type { Hub } from '@sentry/core';
import type { EventProcessor, Integration } from '@sentry/types';
import {
dynamicRequire,
dynamicSamplingContextToSentryBaggageHeader,
parseSemver,
stringMatchesSomePattern,
stripUrlQueryAndFragment,
} from '@sentry/utils';

import type { NodeClient } from '../../client';
import { isSentryRequest } from '../utils/http';
import type { DiagnosticsChannel, RequestCreateMessage, RequestEndMessage, RequestErrorMessage } from './types';

const NODE_VERSION = parseSemver(process.versions.node);

export enum ChannelName {
// https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md#undicirequestcreate
RequestCreate = 'undici:request:create',
RequestEnd = 'undici:request:headers',
RequestError = 'undici:request:error',
}

export interface UndiciOptions {
/**
* Whether breadcrumbs should be recorded for requests
* Defaults to true
*/
breadcrumbs: boolean;
}

const DEFAULT_UNDICI_OPTIONS: UndiciOptions = {
breadcrumbs: true,
};

/**
* Instruments outgoing HTTP requests made with the `undici` package via
* Node's `diagnostics_channel` API.
*
* Supports Undici 4.7.0 or higher.
*
* Requires Node 16.17.0 or higher.
*/
export class Undici implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'Undici';

/**
* @inheritDoc
*/
public name: string = Undici.id;

private readonly _options: UndiciOptions;

public constructor(_options: Partial<UndiciOptions> = {}) {
this._options = {
...DEFAULT_UNDICI_OPTIONS,
..._options,
};
}

/**
* @inheritDoc
*/
public setupOnce(_addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
// Requires Node 16+ to use the diagnostics_channel API.
if (NODE_VERSION.major && NODE_VERSION.major < 16) {
return;
}

let ds: DiagnosticsChannel | undefined;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
ds = dynamicRequire(module, 'diagnostics_channel') as DiagnosticsChannel;
} catch (e) {
// no-op
}

if (!ds || !ds.subscribe) {
return;
}

// https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md
ds.subscribe(ChannelName.RequestCreate, message => {
const { request } = message as RequestCreateMessage;

const url = new URL(request.path, request.origin);
const stringUrl = url.toString();

if (isSentryRequest(stringUrl)) {
return;
}

const hub = getCurrentHub();
const client = hub.getClient<NodeClient>();
const scope = hub.getScope();

const activeSpan = scope.getSpan();

if (activeSpan && client) {
const clientOptions = client.getOptions();

// eslint-disable-next-line deprecation/deprecation
const shouldCreateSpan = clientOptions.shouldCreateSpanForRequest
? // eslint-disable-next-line deprecation/deprecation
clientOptions.shouldCreateSpanForRequest(stringUrl)
: true;

if (shouldCreateSpan) {
const data: Record<string, unknown> = {};
const params = url.searchParams.toString();
if (params) {
data['http.query'] = `?${params}`;
}
if (url.hash) {
data['http.fragment'] = url.hash;
}

const span = activeSpan.startChild({
op: 'http.client',
description: `${request.method || 'GET'} ${stripUrlQueryAndFragment(stringUrl)}`,
data,
});
request.__sentry__ = span;

// eslint-disable-next-line deprecation/deprecation
const shouldPropagate = clientOptions.tracePropagationTargets
? // eslint-disable-next-line deprecation/deprecation
stringMatchesSomePattern(stringUrl, clientOptions.tracePropagationTargets)
: true;

if (shouldPropagate) {
// TODO: Only do this based on tracePropagationTargets
request.addHeader('sentry-trace', span.toTraceparent());
if (span.transaction) {
const dynamicSamplingContext = span.transaction.getDynamicSamplingContext();
const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);
if (sentryBaggageHeader) {
request.addHeader('baggage', sentryBaggageHeader);
}
}
}
}
}
});

ds.subscribe(ChannelName.RequestEnd, message => {
const { request, response } = message as RequestEndMessage;

const url = new URL(request.path, request.origin);
const stringUrl = url.toString();

if (isSentryRequest(stringUrl)) {
return;
}

const span = request.__sentry__;
if (span) {
span.setHttpStatus(response.statusCode);
span.finish();
}

if (this._options.breadcrumbs) {
getCurrentHub().addBreadcrumb(
{
category: 'http',
data: {
method: request.method,
status_code: response.statusCode,
url: stringUrl,
},
type: 'http',
},
{
event: 'response',
request,
response,
},
);
}
});

ds.subscribe(ChannelName.RequestError, message => {
const { request } = message as RequestErrorMessage;

const url = new URL(request.path, request.origin);
const stringUrl = url.toString();

if (isSentryRequest(stringUrl)) {
return;
}

const span = request.__sentry__;
if (span) {
span.setStatus('internal_error');
span.finish();
}

if (this._options.breadcrumbs) {
getCurrentHub().addBreadcrumb(
{
category: 'http',
data: {
method: request.method,
url: stringUrl,
},
level: 'error',
type: 'http',
},
{
event: 'error',
request,
},
);
}
});
}
}
Loading