Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion packages/node/src/anr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,20 @@ function startChildProcess(options: Options): void {
}
}

function createHrTimer(): { getTimeMs: () => number; reset: () => void } {
let lastPoll = process.hrtime();

return {
getTimeMs: (): number => {
const [seconds, nanoSeconds] = process.hrtime(lastPoll);
return Math.floor(seconds * 1e3 + nanoSeconds / 1e6);
},
reset: (): void => {
lastPoll = process.hrtime();
},
};
}

function handleChildProcess(options: Options): void {
function log(message: string): void {
logger.log(`[ANR child process] ${message}`);
Expand Down Expand Up @@ -182,7 +196,7 @@ function handleChildProcess(options: Options): void {
}
}

const { poll } = watchdogTimer(options.pollInterval, options.anrThreshold, watchdogTimeout);
const { poll } = watchdogTimer(createHrTimer, options.pollInterval, options.anrThreshold, watchdogTimeout);

process.on('message', () => {
poll();
Expand Down
16 changes: 11 additions & 5 deletions packages/utils/src/anr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,27 @@ type WatchdogReturn = {
enabled: (state: boolean) => void;
};

type CreateTimerImpl = () => { getTimeMs: () => number; reset: () => void };

/**
* A node.js watchdog timer
* @param pollInterval The interval that we expect to get polled at
* @param anrThreshold The threshold for when we consider ANR
* @param callback The callback to call for ANR
* @returns An object with `poll` and `enabled` functions {@link WatchdogReturn}
*/
export function watchdogTimer(pollInterval: number, anrThreshold: number, callback: () => void): WatchdogReturn {
let lastPoll = process.hrtime();
export function watchdogTimer(
createTimer: CreateTimerImpl,
pollInterval: number,
anrThreshold: number,
callback: () => void,
): WatchdogReturn {
const timer = createTimer();
let triggered = false;
let enabled = true;

setInterval(() => {
const [seconds, nanoSeconds] = process.hrtime(lastPoll);
const diffMs = Math.floor(seconds * 1e3 + nanoSeconds / 1e6);
const diffMs = timer.getTimeMs();

if (triggered === false && diffMs > pollInterval + anrThreshold) {
triggered = true;
Expand All @@ -40,7 +46,7 @@ export function watchdogTimer(pollInterval: number, anrThreshold: number, callba

return {
poll: () => {
lastPoll = process.hrtime();
timer.reset();
},
enabled: (state: boolean) => {
enabled = state;
Expand Down