-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathevent-loop-block-watchdog.ts
More file actions
321 lines (270 loc) · 8.46 KB
/
event-loop-block-watchdog.ts
File metadata and controls
321 lines (270 loc) · 8.46 KB
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
import { workerData } from 'node:worker_threads';
import type { DebugImage, Event, ScopeData, Session, StackFrame, Thread } from '@sentry/core';
import {
applyScopeDataToEvent,
createEventEnvelope,
createSessionEnvelope,
filenameIsInApp,
generateSpanId,
getEnvelopeEndpointWithUrlEncodedAuth,
makeSession,
mergeScopeData,
normalizeUrlToBase,
Scope,
stripSentryFramesAndReverse,
updateSession,
uuid4,
} from '@sentry/core';
import { makeNodeTransport } from '@sentry/node';
import { captureStackTrace, getThreadsLastSeen } from '@sentry-internal/node-native-stacktrace';
import type { ThreadState, WorkerStartData } from './common';
import { POLL_RATIO } from './common';
type CurrentScopes = {
isolationScope: Scope;
};
const {
threshold,
appRootPath,
contexts,
debug,
dist,
dsn,
environment,
maxEventsPerHour,
release,
sdkMetadata,
staticTags: tags,
tunnel,
} = workerData as WorkerStartData;
const pollInterval = threshold / POLL_RATIO;
const triggeredThreads = new Set<string>();
function log(...msg: unknown[]): void {
if (debug) {
// eslint-disable-next-line no-console
console.log('[Sentry Event Loop Blocked Watchdog]', ...msg);
}
}
function createRateLimiter(maxEventsPerHour: number): () => boolean {
let currentHour = 0;
let currentCount = 0;
return function isRateLimited(): boolean {
const hour = new Date().getHours();
if (hour !== currentHour) {
currentHour = hour;
currentCount = 0;
}
if (currentCount >= maxEventsPerHour) {
if (currentCount === maxEventsPerHour) {
currentCount += 1;
log(`Rate limit reached: ${currentCount} events in this hour`);
}
return true;
}
currentCount += 1;
return false;
};
}
const url = getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkMetadata.sdk);
const transport = makeNodeTransport({
url,
recordDroppedEvent: () => {
//
},
});
const isRateLimited = createRateLimiter(maxEventsPerHour);
async function sendAbnormalSession(serializedSession: Session | undefined): Promise<void> {
if (!serializedSession) {
return;
}
log('Sending abnormal session');
const session = makeSession(serializedSession);
updateSession(session, {
status: 'abnormal',
abnormal_mechanism: 'anr_foreground',
release,
environment,
});
const envelope = createSessionEnvelope(session, dsn, sdkMetadata, tunnel);
// Log the envelope so to aid in testing
log(JSON.stringify(envelope));
await transport.send(envelope);
}
log('Started');
function prepareStackFrames(stackFrames: StackFrame[] | undefined): StackFrame[] | undefined {
if (!stackFrames) {
return undefined;
}
// Strip Sentry frames and reverse the stack frames so they are in the correct order
const strippedFrames = stripSentryFramesAndReverse(stackFrames);
for (const frame of strippedFrames) {
if (!frame.filename) {
continue;
}
frame.in_app = filenameIsInApp(frame.filename);
// If we have an app root path, rewrite the filenames to be relative to the app root
if (appRootPath) {
frame.filename = normalizeUrlToBase(frame.filename, appRootPath);
}
}
return strippedFrames;
}
function stripFileProtocol(filename: string | undefined): string | undefined {
if (!filename) {
return undefined;
}
return filename.replace(/^file:\/\//, '');
}
// eslint-disable-next-line complexity
function applyDebugMeta(event: Event, debugImages: Record<string, string>): void {
if (Object.keys(debugImages).length === 0) {
return;
}
const normalisedDebugImages = appRootPath ? {} : debugImages;
if (appRootPath) {
for (const [path, debugId] of Object.entries(debugImages)) {
normalisedDebugImages[normalizeUrlToBase(path, appRootPath)] = debugId;
}
}
const filenameToDebugId = new Map<string, string>();
for (const exception of event.exception?.values || []) {
for (const frame of exception.stacktrace?.frames || []) {
const filename = stripFileProtocol(frame.abs_path || frame.filename);
if (filename && normalisedDebugImages[filename]) {
filenameToDebugId.set(filename, normalisedDebugImages[filename]);
}
}
}
for (const thread of event.threads?.values || []) {
for (const frame of thread.stacktrace?.frames || []) {
const filename = stripFileProtocol(frame.abs_path || frame.filename);
if (filename && normalisedDebugImages[filename]) {
filenameToDebugId.set(filename, normalisedDebugImages[filename]);
}
}
}
if (filenameToDebugId.size > 0) {
const images: DebugImage[] = [];
for (const [code_file, debug_id] of filenameToDebugId.entries()) {
images.push({
type: 'sourcemap',
code_file,
debug_id,
});
}
event.debug_meta = { images };
}
}
function getExceptionAndThreads(
crashedThreadId: string,
threads: ReturnType<typeof captureStackTrace<CurrentScopes, ThreadState>>,
): Event {
const crashedThread = threads[crashedThreadId];
return {
exception: {
values: [
{
type: 'EventLoopBlocked',
value: `Event Loop Blocked for at least ${threshold} ms`,
stacktrace: { frames: prepareStackFrames(crashedThread?.frames) },
// This ensures the UI doesn't say 'Crashed in' for the stack trace
mechanism: { type: 'ANR' },
thread_id: crashedThreadId,
},
],
},
threads: {
values: Object.entries(threads).map(([threadId, threadState]) => {
const crashed = threadId === crashedThreadId;
const thread: Thread = {
id: threadId,
name: threadId === '0' ? 'main' : `worker-${threadId}`,
crashed,
current: true,
main: threadId === '0',
};
if (!crashed) {
thread.stacktrace = { frames: prepareStackFrames(threadState.frames) };
}
return thread;
}),
},
};
}
function applyScopeToEvent(event: Event, scope: ScopeData): void {
applyScopeDataToEvent(event, scope);
if (!event.contexts?.trace) {
const { traceId, parentSpanId, propagationSpanId } = scope.propagationContext;
event.contexts = {
trace: {
trace_id: traceId,
span_id: propagationSpanId || generateSpanId(),
parent_span_id: parentSpanId,
},
...event.contexts,
};
}
}
async function sendBlockEvent(crashedThreadId: string): Promise<void> {
if (isRateLimited()) {
return;
}
const threads = captureStackTrace<CurrentScopes, ThreadState>();
const crashedThread = threads[crashedThreadId];
if (!crashedThread) {
log(`No thread found with ID '${crashedThreadId}'`);
return;
}
try {
await sendAbnormalSession(crashedThread.pollState?.session);
} catch (error) {
log(`Failed to send abnormal session for thread '${crashedThreadId}':`, error);
}
log('Sending event');
const event: Event = {
event_id: uuid4(),
contexts,
release,
environment,
dist,
platform: 'node',
level: 'error',
tags,
...getExceptionAndThreads(crashedThreadId, threads),
};
const scope = crashedThread.pollState?.scope
? new Scope().update(crashedThread.pollState.scope).getScopeData()
: new Scope().getScopeData();
if (crashedThread?.asyncState?.isolationScope) {
// We need to rehydrate the scope from the serialized object with properties beginning with _user, etc
const isolationScope = Object.assign(new Scope(), crashedThread.asyncState.isolationScope).getScopeData();
mergeScopeData(scope, isolationScope);
}
applyScopeToEvent(event, scope);
const allDebugImages: Record<string, string> = Object.values(threads).reduce((acc, threadState) => {
return { ...acc, ...threadState.pollState?.debugImages };
}, {});
applyDebugMeta(event, allDebugImages);
const envelope = createEventEnvelope(event, dsn, sdkMetadata, tunnel);
// Log the envelope to aid in testing
log(JSON.stringify(envelope));
await transport.send(envelope);
await transport.flush(2000);
}
setInterval(async () => {
for (const [threadId, time] of Object.entries(getThreadsLastSeen())) {
if (time > threshold) {
if (triggeredThreads.has(threadId)) {
continue;
}
log(`Blocked thread detected '${threadId}' last polled ${time} ms ago.`);
triggeredThreads.add(threadId);
try {
await sendBlockEvent(threadId);
} catch (error) {
log(`Failed to send event for thread '${threadId}':`, error);
}
} else {
triggeredThreads.delete(threadId);
}
}
}, pollInterval);