-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathindex.ts
342 lines (292 loc) · 10.8 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import {
endSession,
functionToStringIntegration,
getClient,
getCurrentScope,
getIntegrationsToSetup,
getIsolationScope,
hasTracingEnabled,
inboundFiltersIntegration,
linkedErrorsIntegration,
requestDataIntegration,
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
} from '@sentry/opentelemetry';
import type { Client, Integration, Options } from '@sentry/types';
import {
consoleSandbox,
dropUndefinedKeys,
logger,
propagationContextFromHeaders,
stackParserFromStackParserOptions,
} from '@sentry/utils';
import { DEBUG_BUILD } from '../debug-build';
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 { 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 { defaultStackParser, getSentryRelease } from './api';
import { NodeClient } from './client';
import { initOpenTelemetry, maybeInitializeEsmLoader } from './initOtel';
function getCjsOnlyIntegrations(): Integration[] {
return isCjs() ? [modulesIntegration()] : [];
}
/**
* Get default integrations, excluding performance.
*/
export function getDefaultIntegrationsWithoutPerformance(): Integration[] {
return [
// Common
inboundFiltersIntegration(),
functionToStringIntegration(),
linkedErrorsIntegration(),
requestDataIntegration(),
// Native Wrappers
consoleIntegration(),
httpIntegration(),
nativeNodeFetchIntegration(),
// Global Handlers
onUncaughtExceptionIntegration(),
onUnhandledRejectionIntegration(),
// Event Info
contextLinesIntegration(),
localVariablesIntegration(),
nodeContextIntegration(),
...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
...(shouldAddPerformanceIntegrations(options) ? getAutoPerformanceIntegrations() : []),
];
}
function shouldAddPerformanceIntegrations(options: Options): boolean {
if (!hasTracingEnabled(options)) {
return false;
}
// We want to ensure `tracesSampleRate` is not just undefined/null here
// eslint-disable-next-line deprecation/deprecation
return options.enableTracing || options.tracesSampleRate != null || 'tracesSampler' in options;
}
/**
* 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(options.registerEsmLoaderHooks === true ? undefined : options.registerEsmLoaderHooks);
}
setOpenTelemetryContextAsyncContextStrategy();
const scope = getCurrentScope();
scope.update(options.initialScope);
const client = new NodeClient(options);
// The client is on the current scope, from where it generally is inherited
getCurrentScope().setClient(client);
if (isEnabled(client)) {
client.init();
}
logger.log(`Running in ${isCjs() ? 'CommonJS' : 'ESM'} mode.`);
if (options.autoSessionTracking) {
startSessionTracking();
}
client.startClientReportTracking();
updateScopeFromEnvVariables();
if (options.spotlight) {
// force integrations to be setup even if no DSN was set
// If they have already been added before, they will be ignored anyhow
const integrations = client.getOptions().integrations;
for (const integration of integrations) {
client.addIntegration(integration);
}
client.addIntegration(
spotlightIntegration({
sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,
}),
);
}
// 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);
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);
const autoSessionTracking =
typeof release !== 'string'
? false
: options.autoSessionTracking === undefined
? true
: options.autoSessionTracking;
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,
autoSessionTracking,
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 {
const sentryUseEnvironment = (process.env.SENTRY_USE_ENVIRONMENT || '').toLowerCase();
if (!['false', 'n', 'no', 'off', '0'].includes(sentryUseEnvironment)) {
const sentryTraceEnv = process.env.SENTRY_TRACE;
const baggageEnv = process.env.SENTRY_BAGGAGE;
const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv);
getCurrentScope().setPropagationContext(propagationContext);
}
}
/**
* Enable automatic Session Tracking for the node process.
*/
function startSessionTracking(): void {
const client = getClient<NodeClient>();
if (client && client.getOptions().autoSessionTracking) {
client.initSessionFlusher();
}
startSession();
// Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because
// The 'beforeExit' event is not emitted for conditions causing explicit termination,
// such as calling process.exit() or uncaught exceptions.
// Ref: https://nodejs.org/api/process.html#process_event_beforeexit
process.on('beforeExit', () => {
const session = getIsolationScope().getSession();
// Only call endSession, if the Session exists on Scope and SessionStatus is not a
// Terminal Status i.e. Exited or Crashed because
// "When a session is moved away from ok it must not be updated anymore."
// Ref: https://develop.sentry.dev/sdk/sessions/
if (session && session.status !== 'ok') {
endSession();
}
});
}
function isEnabled(client: Client): boolean {
return client.getOptions().enabled !== false && client.getTransport() !== undefined;
}