-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathevent-loop-block-integration.ts
More file actions
300 lines (260 loc) · 8.53 KB
/
event-loop-block-integration.ts
File metadata and controls
300 lines (260 loc) · 8.53 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
import { isPromise } from 'node:util/types';
import { isMainThread, Worker } from 'node:worker_threads';
import type {
ClientOptions,
Contexts,
DsnComponents,
Event,
EventHint,
Integration,
IntegrationFn,
ScopeData,
} from '@sentry/core';
import {
debug,
defineIntegration,
getClient,
getCurrentScope,
getFilenameToDebugIdMap,
getGlobalScope,
getIsolationScope,
mergeScopeData,
} from '@sentry/core';
import type { NodeClient } from '@sentry/node';
import { registerThread, threadPoll } from '@sentry-internal/node-native-stacktrace';
import type { ThreadBlockedIntegrationOptions, WorkerStartData } from './common';
import { POLL_RATIO } from './common';
const INTEGRATION_NAME = 'ThreadBlocked';
const DEFAULT_THRESHOLD_MS = 1_000;
function log(message: string, ...args: unknown[]): void {
debug.log(`[Sentry Event Loop Blocked] ${message}`, ...args);
}
/**
* Gets contexts by calling all event processors. This shouldn't be called until all integrations are setup
*/
async function getContexts(client: NodeClient): Promise<Contexts> {
let event: Event | null = { message: INTEGRATION_NAME };
const eventHint: EventHint = {};
for (const processor of client.getEventProcessors()) {
if (event === null) break;
event = await processor(event, eventHint);
}
return event?.contexts || {};
}
function getLocalScopeData(): ScopeData {
const globalScope = getGlobalScope().getScopeData();
const currentScope = getCurrentScope().getScopeData();
mergeScopeData(globalScope, currentScope);
return globalScope;
}
type IntegrationInternal = { start: () => void; stop: () => void };
function poll(enabled: boolean, clientOptions: ClientOptions): void {
try {
const currentSession = getIsolationScope().getSession();
// We need to copy the session object and remove the toJSON method so it can be sent to the worker
// serialized without making it a SerializedSession
const session = currentSession ? { ...currentSession, toJSON: undefined } : undefined;
const scope = getLocalScopeData();
// message the worker to tell it the main event loop is still running
threadPoll(enabled, { session, scope, debugImages: getFilenameToDebugIdMap(clientOptions.stackParser) });
} catch {
// we ignore all errors
}
}
/**
* Starts polling
*/
function startPolling(
client: NodeClient,
integrationOptions: Partial<ThreadBlockedIntegrationOptions>,
): IntegrationInternal | undefined {
if (client.asyncLocalStorageLookup) {
const { asyncLocalStorage, contextSymbol } = client.asyncLocalStorageLookup;
registerThread({ asyncLocalStorage, stateLookup: ['_currentContext', contextSymbol] });
} else {
registerThread();
}
let enabled = true;
const initOptions = client.getOptions();
const pollInterval = (integrationOptions.threshold || DEFAULT_THRESHOLD_MS) / POLL_RATIO;
// unref so timer does not block exit
setInterval(() => poll(enabled, initOptions), pollInterval).unref();
return {
start: () => {
enabled = true;
},
stop: () => {
enabled = false;
// poll immediately because the timer above might not get a chance to run
// before the event loop gets blocked
poll(enabled, initOptions);
},
};
}
/**
* Starts the worker thread that will monitor the other threads.
*
* This function is only called in the main thread.
*/
async function startWorker(
dsn: DsnComponents,
client: NodeClient,
integrationOptions: Partial<ThreadBlockedIntegrationOptions>,
): Promise<void> {
const contexts = await getContexts(client);
// These will not be accurate if sent later from the worker thread
delete contexts.app?.app_memory;
delete contexts.device?.free_memory;
const initOptions = client.getOptions();
const sdkMetadata = client.getSdkMetadata() || {};
if (sdkMetadata.sdk) {
sdkMetadata.sdk.integrations = initOptions.integrations.map(i => i.name);
}
const options: WorkerStartData = {
debug: debug.isEnabled(),
dsn,
tunnel: initOptions.tunnel,
environment: initOptions.environment || 'production',
release: initOptions.release,
dist: initOptions.dist,
sdkMetadata,
appRootPath: integrationOptions.appRootPath,
threshold: integrationOptions.threshold || DEFAULT_THRESHOLD_MS,
maxEventsPerHour: integrationOptions.maxEventsPerHour || 1,
staticTags: integrationOptions.staticTags || {},
contexts,
};
const worker = new Worker(new URL('./event-loop-block-watchdog.js', import.meta.url), {
workerData: options,
// We don't want any Node args like --import to be passed to the worker
execArgv: [],
env: { ...process.env, NODE_OPTIONS: undefined },
});
process.on('exit', () => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
worker.terminate();
});
worker.once('error', (err: Error) => {
log('watchdog worker error', err);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
worker.terminate();
});
worker.once('exit', (code: number) => {
log('watchdog worker exit', code);
});
// Ensure this thread can't block app exit
worker.unref();
}
const _eventLoopBlockIntegration = ((options: Partial<ThreadBlockedIntegrationOptions> = {}) => {
let polling: IntegrationInternal | undefined;
return {
name: INTEGRATION_NAME,
async afterAllSetup(client: NodeClient): Promise<void> {
const dsn = client.getDsn();
if (!dsn) {
log('No DSN configured, skipping starting integration');
return;
}
// Otel is not setup until after afterAllSetup returns.
setImmediate(async () => {
try {
polling = startPolling(client, options);
if (isMainThread) {
await startWorker(dsn, client, options);
}
} catch (err) {
log('Failed to start integration', err);
return;
}
});
},
start() {
polling?.start();
},
stop() {
polling?.stop();
},
} as Integration & IntegrationInternal;
}) satisfies IntegrationFn;
/**
* Monitors the Node.js event loop for blocking behavior and reports blocked events to Sentry.
*
* Uses a background worker thread to detect when the main thread is blocked for longer than
* the configured threshold (default: 1 second).
*
* When instrumenting via the `--import` flag, this integration will
* automatically monitor all worker threads as well.
*
* ```js
* // instrument.mjs
* import * as Sentry from '@sentry/node';
* import { eventLoopBlockIntegration } from '@sentry/node-native';
*
* Sentry.init({
* dsn: '__YOUR_DSN__',
* integrations: [
* eventLoopBlockIntegration({
* threshold: 500, // Report blocks longer than 500ms
* }),
* ],
* });
* ```
*
* Start your application with:
* ```bash
* node --import instrument.mjs app.mjs
* ```
*/
export const eventLoopBlockIntegration = defineIntegration(_eventLoopBlockIntegration);
export function disableBlockDetectionForCallback<T>(callback: () => T): T;
export function disableBlockDetectionForCallback<T>(callback: () => Promise<T>): Promise<T>;
/**
* Disables Event Loop Block detection for the current thread for the duration
* of the callback.
*
* This utility function allows you to disable block detection during operations that
* are expected to block the event loop, such as intensive computational tasks or
* synchronous I/O operations.
*/
export function disableBlockDetectionForCallback<T>(callback: () => T | Promise<T>): T | Promise<T> {
const integration = getClient()?.getIntegrationByName(INTEGRATION_NAME) as IntegrationInternal | undefined;
if (!integration) {
return callback();
}
integration.stop();
try {
const result = callback();
if (isPromise(result)) {
return result.finally(() => integration.start());
}
integration.start();
return result;
} catch (error) {
integration.start();
throw error;
}
}
/**
* Pauses the block detection integration.
*
* This function pauses event loop block detection for the current thread.
*/
export function pauseEventLoopBlockDetection(): void {
const integration = getClient()?.getIntegrationByName(INTEGRATION_NAME) as IntegrationInternal | undefined;
if (!integration) {
return;
}
integration.stop();
}
/**
* Restarts the block detection integration.
*
* This function restarts event loop block detection for the current thread.
*/
export function restartEventLoopBlockDetection(): void {
const integration = getClient()?.getIntegrationByName(INTEGRATION_NAME) as IntegrationInternal | undefined;
if (!integration) {
return;
}
integration.start();
}