watchdog-timer

Detects and notifies when program does not check-in within a timeout.
Motivation
API
import {
createWatchdogTimer,
} from 'watchdog-timer';
type WatchdogTimerType = {|
+destroy: () => void,
+reset: () => void,
|};
type TimeoutEventType = {|
+consequentTimeouts: number,
|};
type WatchdogTimerConfigurationInputType = {|
+onTimeout: (event: TimeoutEventType) => void,
+timeout: number,
|};
createWatchdogTimer(configuration: WatchdogTimerConfigurationInputType) => WatchdogTimerType;
Example usage
Using watchdog-timer with process.exit
A watchdog timeout is one of the rare, valid use cases for forced process termination, i.e. using process.exit().
import {
createWatchdogTimer,
} from 'watchdog-timer';
const main = async () => {
const watchdogTimer = createWatchdogTimer({
onTimeout: () => {
console.error('watchdog timer timeout; forcing program termination');
process.nextTick(() => {
process.exit(1);
});
},
timeout: 1000,
});
while (true) {
watchdogTimer.reset();
await foo();
}
};
main();
Using watchdog-timer with Lightship
lightship is an NPM module for signaling Kubernetes about the health of a Node.js application. In case of watchdog-timer, Lightship can be used to initiate a controlled termination of the Node.js process.
import {
createWatchdogTimer,
} from 'watchdog-timer';
import {
createLightship,
} from 'lightship';
const main = async () => {
const lightship = createLightship({
timeout: 5 * 1000,
});
lightship.signalReady();
lightship.registerShutdownHandler(async () => {
console.log('shutting down');
});
const watchdogTimer = createWatchdogTimer({
onTimeout: () => {
watchdogTimer.destroy();
lightship.shutdown();
},
timeout: 1000,
});
while (true) {
if (lightship.isServerShuttingDown()) {
console.log('detected that the service is shutting down; terminating the event loop');
break;
}
watchdogTimer.reset();
await foo();
}
watchdogTimer.destroy();
};
main();