Timeout for Sandboxed processors
A pattern for applying time-to-live to sandboxed processors.
// This processor will timeout in 30 seconds.
const MAX_TTL = 30_000;
// The processor will have a cleanup timeout of 5 seconds.
const CLEANUP_TTL = 5_000;
// We use a custom exit code to mark the TTL, but any would do in practice
// as long as it is < 256 (Due to Unix limitation to 8 bits per exit code)
const TTL_EXIT_CODE = 10;
module.exports = async function (job) {
let hasCompleted = false;
const harKillTimeout = setTimeout(() => {
if (!hasCompleted) {
process.exit(TTL_EXIT_CODE);
}
}, MAX_TTL);
const softKillTimeout = setTimeout(async () => {
if (!hasCompleted) {
await doCleanup(job);
}
}, CLEANUP_TTL);
try {
// If doAsyncWork is CPU intensive and blocks NodeJS loop forever,
// the timeout will never be triggered either.
await doAsyncWork(job);
hasCompleted = true;
} finally {
// Important to clear the timeouts before returning as this process will be reused.
clearTimeout(harKillTimeout);
clearTimeout(softKillTimeout);
}
};
const doAsyncWork = async job => {
// Simulate a long running operation.
await new Promise(resolve => setTimeout(resolve, 10000));
};
const doCleanup = async job => {
// Simulate a cleanup operation.
await job.updateProgress(50);
};
Last updated
Was this helpful?