forked from getsentry/sentry-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscope.ts
583 lines (513 loc) · 14.8 KB
/
scope.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
/* eslint-disable max-lines */
import {
Attachment,
Breadcrumb,
CaptureContext,
Context,
Contexts,
Event,
EventHint,
EventProcessor,
Extra,
Extras,
Primitive,
RequestSession,
Scope as ScopeInterface,
ScopeContext,
Session,
Severity,
SeverityLevel,
Span,
Transaction,
User,
} from '@sentry/types';
import {
arrayify,
dateTimestampInSeconds,
getGlobalSingleton,
isPlainObject,
isThenable,
logger,
SyncPromise,
} from '@sentry/utils';
import { updateSession } from './session';
/**
* Default value for maximum number of breadcrumbs added to an event.
*/
const DEFAULT_MAX_BREADCRUMBS = 100;
/**
* Holds additional event information. {@link Scope.applyToEvent} will be
* called by the client before an event will be sent.
*/
export class Scope implements ScopeInterface {
/** Flag if notifying is happening. */
protected _notifyingListeners: boolean;
/** Callback for client to receive scope changes. */
protected _scopeListeners: Array<(scope: Scope) => void>;
/** Callback list that will be called after {@link applyToEvent}. */
protected _eventProcessors: EventProcessor[];
/** Array of breadcrumbs. */
protected _breadcrumbs: Breadcrumb[];
/** User */
protected _user: User;
/** Tags */
protected _tags: { [key: string]: Primitive };
/** Extra */
protected _extra: Extras;
/** Contexts */
protected _contexts: Contexts;
/** Attachments */
protected _attachments: Attachment[];
/**
* A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
* sent to Sentry
*/
protected _sdkProcessingMetadata: { [key: string]: unknown };
/** Fingerprint */
protected _fingerprint?: string[];
/** Severity */
// eslint-disable-next-line deprecation/deprecation
protected _level?: Severity | SeverityLevel;
/** Transaction Name */
protected _transactionName?: string;
/** Span */
protected _span?: Span;
/** Session */
protected _session?: Session;
/** Request Mode Session Status */
protected _requestSession?: RequestSession;
public constructor() {
this._notifyingListeners = false;
this._scopeListeners = [];
this._eventProcessors = [];
this._breadcrumbs = [];
this._attachments = [];
this._user = {};
this._tags = {};
this._extra = {};
this._contexts = {};
this._sdkProcessingMetadata = {};
}
/**
* Inherit values from the parent scope.
* @param scope to clone.
*/
public static clone(scope?: Scope): Scope {
const newScope = new Scope();
if (scope) {
newScope._breadcrumbs = [...scope._breadcrumbs];
newScope._tags = { ...scope._tags };
newScope._extra = { ...scope._extra };
newScope._contexts = { ...scope._contexts };
newScope._user = scope._user;
newScope._level = scope._level;
newScope._span = scope._span;
newScope._session = scope._session;
newScope._transactionName = scope._transactionName;
newScope._fingerprint = scope._fingerprint;
newScope._eventProcessors = [...scope._eventProcessors];
newScope._requestSession = scope._requestSession;
newScope._attachments = [...scope._attachments];
}
return newScope;
}
/**
* Add internal on change listener. Used for sub SDKs that need to store the scope.
* @hidden
*/
public addScopeListener(callback: (scope: Scope) => void): void {
this._scopeListeners.push(callback);
}
/**
* @inheritDoc
*/
public addEventProcessor(callback: EventProcessor): this {
this._eventProcessors.push(callback);
return this;
}
/**
* @inheritDoc
*/
public setUser(user: User | null): this {
this._user = user || {};
if (this._session) {
updateSession(this._session, { user });
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public getUser(): User | undefined {
return this._user;
}
/**
* @inheritDoc
*/
public getRequestSession(): RequestSession | undefined {
return this._requestSession;
}
/**
* @inheritDoc
*/
public setRequestSession(requestSession?: RequestSession): this {
this._requestSession = requestSession;
return this;
}
/**
* @inheritDoc
*/
public setTags(tags: { [key: string]: Primitive }): this {
this._tags = {
...this._tags,
...tags,
};
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setTag(key: string, value: Primitive): this {
this._tags = { ...this._tags, [key]: value };
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setExtras(extras: Extras): this {
this._extra = {
...this._extra,
...extras,
};
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setExtra(key: string, extra: Extra): this {
this._extra = { ...this._extra, [key]: extra };
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setFingerprint(fingerprint: string[]): this {
this._fingerprint = fingerprint;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setLevel(
// eslint-disable-next-line deprecation/deprecation
level: Severity | SeverityLevel,
): this {
this._level = level;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setTransactionName(name?: string): this {
this._transactionName = name;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setContext(key: string, context: Context | null): this {
if (context === null) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._contexts[key];
} else {
this._contexts = { ...this._contexts, [key]: context };
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public setSpan(span?: Span): this {
this._span = span;
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public getSpan(): Span | undefined {
return this._span;
}
/**
* @inheritDoc
*/
public getTransaction(): Transaction | undefined {
// Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will
// have a pointer to the currently-active transaction.
const span = this.getSpan();
return span && span.transaction;
}
/**
* @inheritDoc
*/
public setSession(session?: Session): this {
if (!session) {
delete this._session;
} else {
this._session = session;
}
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public getSession(): Session | undefined {
return this._session;
}
/**
* @inheritDoc
*/
public update(captureContext?: CaptureContext): this {
if (!captureContext) {
return this;
}
if (typeof captureContext === 'function') {
const updatedScope = (captureContext as <T>(scope: T) => T)(this);
return updatedScope instanceof Scope ? updatedScope : this;
}
if (captureContext instanceof Scope) {
this._tags = { ...this._tags, ...captureContext._tags };
this._extra = { ...this._extra, ...captureContext._extra };
this._contexts = { ...this._contexts, ...captureContext._contexts };
if (captureContext._user && Object.keys(captureContext._user).length) {
this._user = captureContext._user;
}
if (captureContext._level) {
this._level = captureContext._level;
}
if (captureContext._fingerprint) {
this._fingerprint = captureContext._fingerprint;
}
if (captureContext._requestSession) {
this._requestSession = captureContext._requestSession;
}
} else if (isPlainObject(captureContext)) {
// eslint-disable-next-line no-param-reassign
captureContext = captureContext as ScopeContext;
this._tags = { ...this._tags, ...captureContext.tags };
this._extra = { ...this._extra, ...captureContext.extra };
this._contexts = { ...this._contexts, ...captureContext.contexts };
if (captureContext.user) {
this._user = captureContext.user;
}
if (captureContext.level) {
this._level = captureContext.level;
}
if (captureContext.fingerprint) {
this._fingerprint = captureContext.fingerprint;
}
if (captureContext.requestSession) {
this._requestSession = captureContext.requestSession;
}
}
return this;
}
/**
* @inheritDoc
*/
public clear(): this {
this._breadcrumbs = [];
this._tags = {};
this._extra = {};
this._user = {};
this._contexts = {};
this._level = undefined;
this._transactionName = undefined;
this._fingerprint = undefined;
this._requestSession = undefined;
this._span = undefined;
this._session = undefined;
this._notifyScopeListeners();
this._attachments = [];
return this;
}
/**
* @inheritDoc
*/
public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {
const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
// No data has been changed, so don't notify scope listeners
if (maxCrumbs <= 0) {
return this;
}
const mergedBreadcrumb = {
timestamp: dateTimestampInSeconds(),
...breadcrumb,
};
this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public clearBreadcrumbs(): this {
this._breadcrumbs = [];
this._notifyScopeListeners();
return this;
}
/**
* @inheritDoc
*/
public addAttachment(attachment: Attachment): this {
this._attachments.push(attachment);
return this;
}
/**
* @inheritDoc
*/
public getAttachments(): Attachment[] {
return this._attachments;
}
/**
* @inheritDoc
*/
public clearAttachments(): this {
this._attachments = [];
return this;
}
/**
* Applies data from the scope to the event and runs all event processors on it.
*
* @param event Event
* @param hint Object containing additional information about the original exception, for use by the event processors.
* @hidden
*/
public applyToEvent(event: Event, hint: EventHint = {}): PromiseLike<Event | null> {
if (this._extra && Object.keys(this._extra).length) {
event.extra = { ...this._extra, ...event.extra };
}
if (this._tags && Object.keys(this._tags).length) {
event.tags = { ...this._tags, ...event.tags };
}
if (this._user && Object.keys(this._user).length) {
event.user = { ...this._user, ...event.user };
}
if (this._contexts && Object.keys(this._contexts).length) {
event.contexts = { ...this._contexts, ...event.contexts };
}
if (this._level) {
event.level = this._level;
}
if (this._transactionName) {
event.transaction = this._transactionName;
}
// We want to set the trace context for normal events only if there isn't already
// a trace context on the event. There is a product feature in place where we link
// errors with transaction and it relies on that.
if (this._span) {
event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };
const transactionName = this._span.transaction && this._span.transaction.name;
if (transactionName) {
event.tags = { transaction: transactionName, ...event.tags };
}
}
this._applyFingerprint(event);
event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];
event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;
event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };
return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);
}
/**
* Add data which will be accessible during event processing but won't get sent to Sentry
*/
public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {
this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };
return this;
}
/**
* This will be called after {@link applyToEvent} is finished.
*/
protected _notifyEventProcessors(
processors: EventProcessor[],
event: Event | null,
hint: EventHint,
index: number = 0,
): PromiseLike<Event | null> {
return new SyncPromise<Event | null>((resolve, reject) => {
const processor = processors[index];
if (event === null || typeof processor !== 'function') {
resolve(event);
} else {
const result = processor({ ...event }, hint) as Event | null;
__DEBUG_BUILD__ &&
processor.id &&
result === null &&
logger.log(`Event processor "${processor.id}" dropped event`);
if (isThenable(result)) {
void result
.then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
.then(null, reject);
} else {
void this._notifyEventProcessors(processors, result, hint, index + 1)
.then(resolve)
.then(null, reject);
}
}
});
}
/**
* This will be called on every set call.
*/
protected _notifyScopeListeners(): void {
// We need this check for this._notifyingListeners to be able to work on scope during updates
// If this check is not here we'll produce endless recursion when something is done with the scope
// during the callback.
if (!this._notifyingListeners) {
this._notifyingListeners = true;
this._scopeListeners.forEach(callback => {
callback(this);
});
this._notifyingListeners = false;
}
}
/**
* Applies fingerprint from the scope to the event if there's one,
* uses message if there's one instead or get rid of empty fingerprint
*/
private _applyFingerprint(event: Event): void {
// Make sure it's an array first and we actually have something in place
event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
// If we have something on the scope, then merge it with event
if (this._fingerprint) {
event.fingerprint = event.fingerprint.concat(this._fingerprint);
}
// If we have no data at all, remove empty array default
if (event.fingerprint && !event.fingerprint.length) {
delete event.fingerprint;
}
}
}
/**
* Returns the global event processors.
*/
function getGlobalEventProcessors(): EventProcessor[] {
return getGlobalSingleton<EventProcessor[]>('globalEventProcessors', () => []);
}
/**
* Add a EventProcessor to be kept globally.
* @param callback EventProcessor to add
*/
export function addGlobalEventProcessor(callback: EventProcessor): void {
getGlobalEventProcessors().push(callback);
}