-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathprepareEvent.ts
343 lines (299 loc) · 11.1 KB
/
prepareEvent.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
import type { Client } from '../client';
import { DEFAULT_ENVIRONMENT } from '../constants';
import { getGlobalScope } from '../currentScopes';
import { notifyEventProcessors } from '../eventProcessors';
import type { CaptureContext, ScopeContext } from '../scope';
import { Scope } from '../scope';
import type { ClientOptions, Event, EventHint, StackParser } from '../types-hoist';
import { getFilenameToDebugIdMap } from '../utils-hoist/debug-ids';
import { addExceptionMechanism, uuid4 } from '../utils-hoist/misc';
import { normalize } from '../utils-hoist/normalize';
import { truncate } from '../utils-hoist/string';
import { dateTimestampInSeconds } from '../utils-hoist/time';
import { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';
/**
* This type makes sure that we get either a CaptureContext, OR an EventHint.
* It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:
* { user: { id: '123' }, mechanism: { handled: false } }
*/
export type ExclusiveEventHintOrCaptureContext =
| (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)
| (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);
/**
* Adds common information to events.
*
* The information includes release and environment from `options`,
* breadcrumbs and context (extra, tags and user) from the scope.
*
* Information that is already present in the event is never overwritten. For
* nested objects, such as the context, keys are merged.
*
* @param event The original event.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A new event with more information.
* @hidden
*/
export function prepareEvent(
options: ClientOptions,
event: Event,
hint: EventHint,
scope?: Scope,
client?: Client,
isolationScope?: Scope,
): PromiseLike<Event | null> {
const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;
const prepared: Event = {
...event,
event_id: event.event_id || hint.event_id || uuid4(),
timestamp: event.timestamp || dateTimestampInSeconds(),
};
const integrations = hint.integrations || options.integrations.map(i => i.name);
applyClientOptions(prepared, options);
applyIntegrationsMetadata(prepared, integrations);
if (client) {
client.emit('applyFrameMetadata', event);
}
// Only put debug IDs onto frames for error events.
if (event.type === undefined) {
applyDebugIds(prepared, options.stackParser);
}
// If we have scope given to us, use it as the base for further modifications.
// This allows us to prevent unnecessary copying of data if `captureContext` is not provided.
const finalScope = getFinalScope(scope, hint.captureContext);
if (hint.mechanism) {
addExceptionMechanism(prepared, hint.mechanism);
}
const clientEventProcessors = client ? client.getEventProcessors() : [];
// This should be the last thing called, since we want that
// {@link Scope.addEventProcessor} gets the finished prepared event.
// Merge scope data together
const data = getGlobalScope().getScopeData();
if (isolationScope) {
const isolationData = isolationScope.getScopeData();
mergeScopeData(data, isolationData);
}
if (finalScope) {
const finalScopeData = finalScope.getScopeData();
mergeScopeData(data, finalScopeData);
}
const attachments = [...(hint.attachments || []), ...data.attachments];
if (attachments.length) {
hint.attachments = attachments;
}
applyScopeDataToEvent(prepared, data);
const eventProcessors = [
...clientEventProcessors,
// Run scope event processors _after_ all other processors
...data.eventProcessors,
];
const result = notifyEventProcessors(eventProcessors, prepared, hint);
return result.then(evt => {
if (evt) {
// We apply the debug_meta field only after all event processors have ran, so that if any event processors modified
// file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.
// This should not cause any PII issues, since we're only moving data that is already on the event and not adding
// any new data
applyDebugMeta(evt);
}
if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
}
return evt;
});
}
/**
* Enhances event using the client configuration.
* It takes care of all "static" values like environment, release and `dist`,
* as well as truncating overly long values.
*
* Only exported for tests.
*
* @param event event instance to be enhanced
*/
export function applyClientOptions(event: Event, options: ClientOptions): void {
const { environment, release, dist, maxValueLength = 250 } = options;
// empty strings do not make sense for environment, release, and dist
// so we handle them the same as if they were not provided
event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;
if (!event.release && release) {
event.release = release;
}
if (!event.dist && dist) {
event.dist = dist;
}
const request = event.request;
if (request?.url) {
request.url = truncate(request.url, maxValueLength);
}
}
/**
* Puts debug IDs into the stack frames of an error event.
*/
export function applyDebugIds(event: Event, stackParser: StackParser): void {
// Build a map of filename -> debug_id
const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
event.exception?.values?.forEach(exception => {
exception.stacktrace?.frames?.forEach(frame => {
if (frame.filename) {
frame.debug_id = filenameDebugIdMap[frame.filename];
}
});
});
}
/**
* Moves debug IDs from the stack frames of an error event into the debug_meta field.
*/
export function applyDebugMeta(event: Event): void {
// Extract debug IDs and filenames from the stack frames on the event.
const filenameDebugIdMap: Record<string, string> = {};
event.exception?.values?.forEach(exception => {
exception.stacktrace?.frames?.forEach(frame => {
if (frame.debug_id) {
if (frame.abs_path) {
filenameDebugIdMap[frame.abs_path] = frame.debug_id;
} else if (frame.filename) {
filenameDebugIdMap[frame.filename] = frame.debug_id;
}
delete frame.debug_id;
}
});
});
if (Object.keys(filenameDebugIdMap).length === 0) {
return;
}
// Fill debug_meta information
event.debug_meta = event.debug_meta || {};
event.debug_meta.images = event.debug_meta.images || [];
const images = event.debug_meta.images;
Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
images.push({
type: 'sourcemap',
code_file: filename,
debug_id,
});
});
}
/**
* This function adds all used integrations to the SDK info in the event.
* @param event The event that will be filled with all integrations.
*/
function applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {
if (integrationNames.length > 0) {
event.sdk = event.sdk || {};
event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];
}
}
/**
* Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
* Normalized keys:
* - `breadcrumbs.data`
* - `user`
* - `contexts`
* - `extra`
* @param event Event
* @returns Normalized event
*/
function normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {
if (!event) {
return null;
}
const normalized: Event = {
...event,
...(event.breadcrumbs && {
breadcrumbs: event.breadcrumbs.map(b => ({
...b,
...(b.data && {
data: normalize(b.data, depth, maxBreadth),
}),
})),
}),
...(event.user && {
user: normalize(event.user, depth, maxBreadth),
}),
...(event.contexts && {
contexts: normalize(event.contexts, depth, maxBreadth),
}),
...(event.extra && {
extra: normalize(event.extra, depth, maxBreadth),
}),
};
// event.contexts.trace stores information about a Transaction. Similarly,
// event.spans[] stores information about child Spans. Given that a
// Transaction is conceptually a Span, normalization should apply to both
// Transactions and Spans consistently.
// For now the decision is to skip normalization of Transactions and Spans,
// so this block overwrites the normalized event to add back the original
// Transaction information prior to normalization.
if (event.contexts?.trace && normalized.contexts) {
normalized.contexts.trace = event.contexts.trace;
// event.contexts.trace.data may contain circular/dangerous data so we need to normalize it
if (event.contexts.trace.data) {
normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);
}
}
// event.spans[].data may contain circular/dangerous data so we need to normalize it
if (event.spans) {
normalized.spans = event.spans.map(span => {
return {
...span,
...(span.data && {
data: normalize(span.data, depth, maxBreadth),
}),
};
});
}
// event.contexts.flags (FeatureFlagContext) stores context for our feature
// flag integrations. It has a greater nesting depth than our other typed
// Contexts, so we re-normalize with a fixed depth of 3 here. We do not want
// to skip this in case of conflicting, user-provided context.
if (event.contexts?.flags && normalized.contexts) {
normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);
}
return normalized;
}
function getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {
if (!captureContext) {
return scope;
}
const finalScope = scope ? scope.clone() : new Scope();
finalScope.update(captureContext);
return finalScope;
}
/**
* Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.
* This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.
*/
export function parseEventHintOrCaptureContext(
hint: ExclusiveEventHintOrCaptureContext | undefined,
): EventHint | undefined {
if (!hint) {
return undefined;
}
// If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext
if (hintIsScopeOrFunction(hint)) {
return { captureContext: hint };
}
if (hintIsScopeContext(hint)) {
return {
captureContext: hint,
};
}
return hint;
}
function hintIsScopeOrFunction(hint: CaptureContext | EventHint): hint is Scope | ((scope: Scope) => Scope) {
return hint instanceof Scope || typeof hint === 'function';
}
type ScopeContextProperty = keyof ScopeContext;
const captureContextKeys: readonly ScopeContextProperty[] = [
'user',
'level',
'extra',
'contexts',
'tags',
'fingerprint',
'propagationContext',
] as const;
function hintIsScopeContext(hint: Partial<ScopeContext> | EventHint): hint is Partial<ScopeContext> {
return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));
}