-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathindex.ts
290 lines (249 loc) · 9.15 KB
/
index.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import type { Integration, Options } from '@sentry/core';
import {
consoleSandbox,
dropUndefinedKeys,
functionToStringIntegration,
getCurrentScope,
getIntegrationsToSetup,
hasTracingEnabled,
inboundFiltersIntegration,
linkedErrorsIntegration,
logger,
propagationContextFromHeaders,
requestDataIntegration,
stackParserFromStackParserOptions,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
} from '@sentry/opentelemetry';
import { DEBUG_BUILD } from '../debug-build';
import { childProcessIntegration } from '../integrations/childProcess';
import { consoleIntegration } from '../integrations/console';
import { nodeContextIntegration } from '../integrations/context';
import { contextLinesIntegration } from '../integrations/contextlines';
import { httpIntegration } from '../integrations/http';
import { localVariablesIntegration } from '../integrations/local-variables';
import { modulesIntegration } from '../integrations/modules';
import { nativeNodeFetchIntegration } from '../integrations/node-fetch';
import { onUncaughtExceptionIntegration } from '../integrations/onuncaughtexception';
import { onUnhandledRejectionIntegration } from '../integrations/onunhandledrejection';
import { processSessionIntegration } from '../integrations/processSession';
import { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from '../integrations/spotlight';
import { getAutoPerformanceIntegrations } from '../integrations/tracing';
import { makeNodeTransport } from '../transports';
import type { NodeClientOptions, NodeOptions } from '../types';
import { isCjs } from '../utils/commonjs';
import { envToBool } from '../utils/envToBool';
import { defaultStackParser, getSentryRelease } from './api';
import { NodeClient } from './client';
import { initOpenTelemetry, maybeInitializeEsmLoader } from './initOtel';
function getCjsOnlyIntegrations(): Integration[] {
return isCjs() ? [modulesIntegration()] : [];
}
/**
* Get default integrations, excluding performance.
*
* Ensure to keep this in sync with `NodeOptions`!
*/
export function getDefaultIntegrationsWithoutPerformance(): Integration[] {
return [
// Common
inboundFiltersIntegration(),
functionToStringIntegration(),
linkedErrorsIntegration(),
requestDataIntegration(),
// Native Wrappers
consoleIntegration(),
httpIntegration(),
nativeNodeFetchIntegration(),
// Global Handlers
onUncaughtExceptionIntegration(),
onUnhandledRejectionIntegration(),
// Event Info
contextLinesIntegration(),
localVariablesIntegration(),
nodeContextIntegration(),
childProcessIntegration(),
processSessionIntegration(),
...getCjsOnlyIntegrations(),
];
}
/** Get the default integrations for the Node SDK. */
export function getDefaultIntegrations(options: Options): Integration[] {
return [
...getDefaultIntegrationsWithoutPerformance(),
// We only add performance integrations if tracing is enabled
// Note that this means that without tracing enabled, e.g. `expressIntegration()` will not be added
// This means that generally request isolation will work (because that is done by httpIntegration)
// But `transactionName` will not be set automatically
...(hasTracingEnabled(options) ? getAutoPerformanceIntegrations() : []),
];
}
/**
* Initialize Sentry for Node.
*/
export function init(options: NodeOptions | undefined = {}): NodeClient | undefined {
return _init(options, getDefaultIntegrations);
}
/**
* Initialize Sentry for Node, without any integrations added by default.
*/
export function initWithoutDefaultIntegrations(options: NodeOptions | undefined = {}): NodeClient {
return _init(options, () => []);
}
/**
* Initialize Sentry for Node, without performance instrumentation.
*/
function _init(
_options: NodeOptions | undefined = {},
getDefaultIntegrationsImpl: (options: Options) => Integration[],
): NodeClient {
const options = getClientOptions(_options, getDefaultIntegrationsImpl);
if (options.debug === true) {
if (DEBUG_BUILD) {
logger.enable();
} else {
// use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');
});
}
}
if (!isCjs() && options.registerEsmLoaderHooks !== false) {
maybeInitializeEsmLoader();
}
setOpenTelemetryContextAsyncContextStrategy();
const scope = getCurrentScope();
scope.update(options.initialScope);
if (options.spotlight && !options.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {
options.integrations.push(
spotlightIntegration({
sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,
}),
);
}
const client = new NodeClient(options);
// The client is on the current scope, from where it generally is inherited
getCurrentScope().setClient(client);
client.init();
logger.log(`Running in ${isCjs() ? 'CommonJS' : 'ESM'} mode.`);
client.startClientReportTracking();
updateScopeFromEnvVariables();
// If users opt-out of this, they _have_ to set up OpenTelemetry themselves
// There is no way to use this SDK without OpenTelemetry!
if (!options.skipOpenTelemetrySetup) {
initOpenTelemetry(client, {
spanProcessors: options.openTelemetrySpanProcessors,
});
validateOpenTelemetrySetup();
}
enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
return client;
}
/**
* Validate that your OpenTelemetry setup is correct.
*/
export function validateOpenTelemetrySetup(): void {
if (!DEBUG_BUILD) {
return;
}
const setup = openTelemetrySetupCheck();
const required: ReturnType<typeof openTelemetrySetupCheck> = ['SentryContextManager', 'SentryPropagator'];
if (hasTracingEnabled()) {
required.push('SentrySpanProcessor');
}
for (const k of required) {
if (!setup.includes(k)) {
logger.error(
`You have to set up the ${k}. Without this, the OpenTelemetry & Sentry integration will not work properly.`,
);
}
}
if (!setup.includes('SentrySampler')) {
logger.warn(
'You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.',
);
}
}
function getClientOptions(
options: NodeOptions,
getDefaultIntegrationsImpl: (options: Options) => Integration[],
): NodeClientOptions {
const release = getRelease(options.release);
if (options.spotlight == null) {
const spotlightEnv = envToBool(process.env.SENTRY_SPOTLIGHT, { strict: true });
if (spotlightEnv == null) {
options.spotlight = process.env.SENTRY_SPOTLIGHT;
} else {
options.spotlight = spotlightEnv;
}
}
const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);
const baseOptions = dropUndefinedKeys({
transport: makeNodeTransport,
dsn: process.env.SENTRY_DSN,
environment: process.env.SENTRY_ENVIRONMENT,
sendClientReports: true,
});
const overwriteOptions = dropUndefinedKeys({
release,
tracesSampleRate,
});
const mergedOptions = {
...baseOptions,
...options,
...overwriteOptions,
};
if (options.defaultIntegrations === undefined) {
options.defaultIntegrations = getDefaultIntegrationsImpl(mergedOptions);
}
const clientOptions: NodeClientOptions = {
...mergedOptions,
stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
integrations: getIntegrationsToSetup({
defaultIntegrations: options.defaultIntegrations,
integrations: options.integrations,
}),
};
return clientOptions;
}
function getRelease(release: NodeOptions['release']): string | undefined {
if (release !== undefined) {
return release;
}
const detectedRelease = getSentryRelease();
if (detectedRelease !== undefined) {
return detectedRelease;
}
return undefined;
}
function getTracesSampleRate(tracesSampleRate: NodeOptions['tracesSampleRate']): number | undefined {
if (tracesSampleRate !== undefined) {
return tracesSampleRate;
}
const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;
if (!sampleRateFromEnv) {
return undefined;
}
const parsed = parseFloat(sampleRateFromEnv);
return isFinite(parsed) ? parsed : undefined;
}
/**
* Update scope and propagation context based on environmental variables.
*
* See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md
* for more details.
*/
function updateScopeFromEnvVariables(): void {
if (envToBool(process.env.SENTRY_USE_ENVIRONMENT) !== false) {
const sentryTraceEnv = process.env.SENTRY_TRACE;
const baggageEnv = process.env.SENTRY_BAGGAGE;
const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv);
getCurrentScope().setPropagationContext(propagationContext);
}
}