-
-
Save Swizec/30df527907e3488a546075b3ec691dd9 to your computer and use it in GitHub Desktop.
An attempt to detect long running promises in JavaScript code on the server. Unfortunately it can't get a reference to execution context, which diminishes its usefulness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ah = require('async_hooks') | |
const promiseTimes = {} | |
// if a promise runs for more than 10s, something's wrong | |
const MAX_TIME = 10 * 1000 | |
ah.createHook({ | |
// save meta data when async instantiates | |
init(asyncId, type) { | |
promiseTimes[asyncId] = { | |
type | |
} | |
}, | |
// save timestamp when promise begins | |
before(asyncId) { | |
if (!promiseTimes[asyncId]) { | |
promiseTimes[asyncId] = {} | |
} | |
promiseTimes[asyncId].time = new Date() | |
// warn if a promise doesn't resolve in time | |
promiseTimes[asyncId].timer = setTimeout(() => { | |
if (promiseTimes[asyncId]) { | |
Logger.warn(`Promise not resolved within ${MAX_TIME}ms`, { | |
type: promiseTimes[asyncId].type | |
}) | |
} | |
}, MAX_TIME) | |
}, | |
// check duration and cleanup when promise ends | |
after(asyncId) { | |
if (promiseTimes[asyncId]) { | |
const delta = new Date() - promiseTimes[asyncId].time | |
if (delta > MAX_TIME) { | |
Logger.warn(`Promise ran longer than ${MAX_TIME}ms`, { | |
delta, | |
type: promiseTimes[asyncId].type | |
}) | |
} | |
} | |
}, | |
// cleanup | |
destroy(asyncId) { | |
if (promiseTimes[asyncId]) { | |
clearTimeout(promiseTimes[asyncId].timer) | |
delete promiseTimes[asyncId] | |
} | |
} | |
}).enable() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment