-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
hub.ts
631 lines (556 loc) · 16.8 KB
/
hub.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/* eslint-disable max-lines */
import {
Breadcrumb,
BreadcrumbHint,
Client,
CustomSamplingContext,
Event,
EventHint,
Extra,
Extras,
Hub as HubInterface,
Integration,
IntegrationClass,
Primitive,
SessionContext,
SessionStatus,
Severity,
Span,
SpanContext,
Transaction,
TransactionContext,
User,
} from '@sentry/types';
import { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils';
import { Scope } from './scope';
import { Session } from './session';
/**
* API compatibility version of this hub.
*
* WARNING: This number should only be increased when the global interface
* changes and new methods are introduced.
*
* @hidden
*/
export const API_VERSION = 4;
/**
* Default maximum number of breadcrumbs added to an event. Can be overwritten
* with {@link Options.maxBreadcrumbs}.
*/
const DEFAULT_BREADCRUMBS = 100;
/**
* A layer in the process stack.
* @hidden
*/
export interface Layer {
client?: Client;
scope?: Scope;
}
/**
* An object that contains a hub and maintains a scope stack.
* @hidden
*/
export interface Carrier {
__SENTRY__?: {
hub?: Hub;
/**
* Extra Hub properties injected by various SDKs
*/
integrations?: Integration[];
extensions?: {
/** Hack to prevent bundlers from breaking our usage of the domain package in the cross-platform Hub package */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
domain?: { [key: string]: any };
} & {
/** Extension methods for the hub, which are bound to the current Hub instance */
// eslint-disable-next-line @typescript-eslint/ban-types
[key: string]: Function;
};
};
}
/**
* @hidden
* @deprecated Can be removed once `Hub.getActiveDomain` is removed.
*/
export interface DomainAsCarrier extends Carrier {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
members: { [key: string]: any }[];
}
/**
* @inheritDoc
*/
export class Hub implements HubInterface {
/** Is a {@link Layer}[] containing the client and scope */
private readonly _stack: Layer[] = [{}];
/** Contains the last event id of a captured event. */
private _lastEventId?: string;
/**
* Creates a new instance of the hub, will push one {@link Layer} into the
* internal stack on creation.
*
* @param client bound to the hub.
* @param scope bound to the hub.
* @param version number, higher number means higher priority.
*/
public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {
this.getStackTop().scope = scope;
if (client) {
this.bindClient(client);
}
}
/**
* @inheritDoc
*/
public isOlderThan(version: number): boolean {
return this._version < version;
}
/**
* @inheritDoc
*/
public bindClient(client?: Client): void {
const top = this.getStackTop();
top.client = client;
if (client && client.setupIntegrations) {
client.setupIntegrations();
}
}
/**
* @inheritDoc
*/
public pushScope(): Scope {
// We want to clone the content of prev scope
const scope = Scope.clone(this.getScope());
this.getStack().push({
client: this.getClient(),
scope,
});
return scope;
}
/**
* @inheritDoc
*/
public popScope(): boolean {
if (this.getStack().length <= 1) return false;
return !!this.getStack().pop();
}
/**
* @inheritDoc
*/
public withScope(callback: (scope: Scope) => void): void {
const scope = this.pushScope();
try {
callback(scope);
} finally {
this.popScope();
}
}
/**
* @inheritDoc
*/
public getClient<C extends Client>(): C | undefined {
return this.getStackTop().client as C;
}
/** Returns the scope of the top stack. */
public getScope(): Scope | undefined {
return this.getStackTop().scope;
}
/** Returns the scope stack for domains or the process. */
public getStack(): Layer[] {
return this._stack;
}
/** Returns the topmost scope layer in the order domain > local > process. */
public getStackTop(): Layer {
return this._stack[this._stack.length - 1];
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
public captureException(exception: any, hint?: EventHint): string {
const eventId = (this._lastEventId = uuid4());
let finalHint = hint;
// If there's no explicit hint provided, mimic the same thing that would happen
// in the minimal itself to create a consistent behavior.
// We don't do this in the client, as it's the lowest level API, and doing this,
// would prevent user from having full control over direct calls.
if (!hint) {
let syntheticException: Error;
try {
throw new Error('Sentry syntheticException');
} catch (exception) {
syntheticException = exception as Error;
}
finalHint = {
originalException: exception,
syntheticException,
};
}
this._invokeClient('captureException', exception, {
...finalHint,
event_id: eventId,
});
return eventId;
}
/**
* @inheritDoc
*/
public captureMessage(message: string, level?: Severity, hint?: EventHint): string {
const eventId = (this._lastEventId = uuid4());
let finalHint = hint;
// If there's no explicit hint provided, mimic the same thing that would happen
// in the minimal itself to create a consistent behavior.
// We don't do this in the client, as it's the lowest level API, and doing this,
// would prevent user from having full control over direct calls.
if (!hint) {
let syntheticException: Error;
try {
throw new Error(message);
} catch (exception) {
syntheticException = exception as Error;
}
finalHint = {
originalException: message,
syntheticException,
};
}
this._invokeClient('captureMessage', message, level, {
...finalHint,
event_id: eventId,
});
return eventId;
}
/**
* @inheritDoc
*/
public captureEvent(event: Event, hint?: EventHint): string {
const eventId = uuid4();
if (event.type !== 'transaction') {
this._lastEventId = eventId;
}
this._invokeClient('captureEvent', event, {
...hint,
event_id: eventId,
});
return eventId;
}
/**
* @inheritDoc
*/
public lastEventId(): string | undefined {
return this._lastEventId;
}
/**
* @inheritDoc
*/
public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {
const { scope, client } = this.getStackTop();
if (!scope || !client) return;
// eslint-disable-next-line @typescript-eslint/unbound-method
const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =
(client.getOptions && client.getOptions()) || {};
if (maxBreadcrumbs <= 0) return;
const timestamp = dateTimestampInSeconds();
const mergedBreadcrumb = { timestamp, ...breadcrumb };
const finalBreadcrumb = beforeBreadcrumb
? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)
: mergedBreadcrumb;
if (finalBreadcrumb === null) return;
scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
}
/**
* @inheritDoc
*/
public setUser(user: User | null): void {
const scope = this.getScope();
if (scope) scope.setUser(user);
}
/**
* @inheritDoc
*/
public setTags(tags: { [key: string]: Primitive }): void {
const scope = this.getScope();
if (scope) scope.setTags(tags);
}
/**
* @inheritDoc
*/
public setExtras(extras: Extras): void {
const scope = this.getScope();
if (scope) scope.setExtras(extras);
}
/**
* @inheritDoc
*/
public setTag(key: string, value: Primitive): void {
const scope = this.getScope();
if (scope) scope.setTag(key, value);
}
/**
* @inheritDoc
*/
public setExtra(key: string, extra: Extra): void {
const scope = this.getScope();
if (scope) scope.setExtra(key, extra);
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public setContext(name: string, context: { [key: string]: any } | null): void {
const scope = this.getScope();
if (scope) scope.setContext(name, context);
}
/**
* @inheritDoc
*/
public configureScope(callback: (scope: Scope) => void): void {
const { scope, client } = this.getStackTop();
if (scope && client) {
callback(scope);
}
}
/**
* @inheritDoc
*/
public run(callback: (hub: Hub) => void): void {
const oldHub = makeMain(this);
try {
callback(this);
} finally {
makeMain(oldHub);
}
}
/**
* @inheritDoc
*/
public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {
const client = this.getClient();
if (!client) return null;
try {
return client.getIntegration(integration);
} catch (_oO) {
logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);
return null;
}
}
/**
* @inheritDoc
*/
public startSpan(context: SpanContext): Span {
return this._callExtensionMethod('startSpan', context);
}
/**
* @inheritDoc
*/
public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {
return this._callExtensionMethod('startTransaction', context, customSamplingContext);
}
/**
* @inheritDoc
*/
public traceHeaders(): { [key: string]: string } {
return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');
}
/**
* @inheritDoc
*/
public captureSession(endSession: boolean = false): void {
// both send the update and pull the session from the scope
if (endSession) {
return this.endSession();
}
// only send the update
this._sendSessionUpdate();
}
/**
* @inheritDoc
*/
public endSession(): void {
this.getStackTop()
?.scope?.getSession()
?.close();
this._sendSessionUpdate();
// the session is over; take it off of the scope
this.getStackTop()?.scope?.setSession();
}
/**
* @inheritDoc
*/
public startSession(context?: SessionContext): Session {
const { scope, client } = this.getStackTop();
const { release, environment } = (client && client.getOptions()) || {};
// Will fetch userAgent if called from browser sdk
const global = getGlobalObject<{ navigator?: { userAgent?: string } }>();
const { userAgent } = global.navigator || {};
const session = new Session({
release,
environment,
...(scope && { user: scope.getUser() }),
...(userAgent && { userAgent }),
...context,
});
if (scope) {
// End existing session if there's one
const currentSession = scope.getSession && scope.getSession();
if (currentSession && currentSession.status === SessionStatus.Ok) {
currentSession.update({ status: SessionStatus.Exited });
}
this.endSession();
// Afterwards we set the new session on the scope
scope.setSession(session);
}
return session;
}
/**
* Sends the current Session on the scope
*/
private _sendSessionUpdate(): void {
const { scope, client } = this.getStackTop();
if (!scope) return;
const session = scope.getSession && scope.getSession();
if (session) {
if (client && client.captureSession) {
client.captureSession(session);
}
}
}
/**
* Internal helper function to call a method on the top client if it exists.
*
* @param method The method to call on the client.
* @param args Arguments to pass to the client function.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _invokeClient<M extends keyof Client>(method: M, ...args: any[]): void {
const { scope, client } = this.getStackTop();
if (client && client[method]) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(client as any)[method](...args, scope);
}
}
/**
* Calls global extension method and binding current instance to the function call
*/
// @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _callExtensionMethod<T>(method: string, ...args: any[]): T {
const carrier = getMainCarrier();
const sentry = carrier.__SENTRY__;
if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {
return sentry.extensions[method].apply(this, args);
}
logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);
}
}
/**
* Returns the global shim registry.
*
* FIXME: This function is problematic, because despite always returning a valid Carrier,
* it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check
* at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.
**/
export function getMainCarrier(): Carrier {
const carrier = getGlobalObject();
carrier.__SENTRY__ = carrier.__SENTRY__ || {
extensions: {},
hub: undefined,
};
return carrier;
}
/**
* Replaces the current main hub with the passed one on the global object
*
* @returns The old replaced hub
*/
export function makeMain(hub: Hub): Hub {
const registry = getMainCarrier();
const oldHub = getHubFromCarrier(registry);
setHubOnCarrier(registry, hub);
return oldHub;
}
/**
* Returns the default hub instance.
*
* If a hub is already registered in the global carrier but this module
* contains a more recent version, it replaces the registered version.
* Otherwise, the currently registered hub will be returned.
*/
export function getCurrentHub(): Hub {
// Get main carrier (global for every environment)
const registry = getMainCarrier();
// If there's no hub, or its an old API, assign a new one
if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
setHubOnCarrier(registry, new Hub());
}
// Prefer domains over global if they are there (applicable only to Node environment)
if (isNodeEnv()) {
return getHubFromActiveDomain(registry);
}
// Return hub that lives on a global object
return getHubFromCarrier(registry);
}
/**
* Returns the active domain, if one exists
* @deprecated No longer used; remove in v7
* @returns The domain, or undefined if there is no active domain
*/
// eslint-disable-next-line deprecation/deprecation
export function getActiveDomain(): DomainAsCarrier | undefined {
logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');
const sentry = getMainCarrier().__SENTRY__;
return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
}
/**
* Try to read the hub from an active domain, and fallback to the registry if one doesn't exist
* @returns discovered hub
*/
function getHubFromActiveDomain(registry: Carrier): Hub {
try {
const activeDomain = getMainCarrier().__SENTRY__?.extensions?.domain?.active;
// If there's no active domain, just return global hub
if (!activeDomain) {
return getHubFromCarrier(registry);
}
// If there's no hub on current domain, or it's an old API, assign a new one
if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {
const registryHubTopStack = getHubFromCarrier(registry).getStackTop();
setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));
}
// Return hub that lives on a domain
return getHubFromCarrier(activeDomain);
} catch (_Oo) {
// Return hub that lives on a global object
return getHubFromCarrier(registry);
}
}
/**
* This will tell whether a carrier has a hub on it or not
* @param carrier object
*/
function hasHubOnCarrier(carrier: Carrier): boolean {
return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
}
/**
* This will create a new {@link Hub} and add to the passed object on
* __SENTRY__.hub.
* @param carrier object
* @hidden
*/
export function getHubFromCarrier(carrier: Carrier): Hub {
if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) return carrier.__SENTRY__.hub;
carrier.__SENTRY__ = carrier.__SENTRY__ || {};
carrier.__SENTRY__.hub = new Hub();
return carrier.__SENTRY__.hub;
}
/**
* This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute
* @param carrier object
* @param hub Hub
* @returns A boolean indicating success or failure
*/
export function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {
if (!carrier) return false;
carrier.__SENTRY__ = carrier.__SENTRY__ || {};
carrier.__SENTRY__.hub = hub;
return true;
}