Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(loader): manually deregister listeners setup by loader to prevent memory leaks #167 #168

Merged
merged 1 commit into from
Nov 16, 2023
Merged
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
32 changes: 32 additions & 0 deletions loader/src/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,50 @@ var Module = (() => {
* @returns {HandleResponse}
*/

/**
* See this issue with emscripten https://github.com/emscripten-core/emscripten/issues/12740
*
* We need to manually cleanup any listeners that are setup as part of the WASM module,
* so that they can be deregistered later and the associated WASM memory can be garbage collected
*/
function trackListeners (name) {
const start = process.listeners(name)
/**
* tally any new listeners that did not exist before the WASM was bootstrapped
*
* TODO: could this capture listeners created by other modules?
* For now, this gets us what we need
*/
return () => {
const diff = process.listeners(name).filter(l => start.indexOf(l) === -1)
/**
* Deregister any listeners that did not exist before this
* WASM module was bootstrapped
*/
return () => {
diff.forEach(l => process.removeListener(name, l))
}
}
}

/**
* @param {ArrayBuffer} binary
* @returns {Promise<handleFunction>}
*/
module.exports = async function (binary) {
const listenerDiffs = [trackListeners('unhandledRejection'), trackListeners('uncaughtException')]
const instance = await Module(binary)
const cleanupListeners = listenerDiffs.map(diff => diff())
const doHandle = instance.cwrap('handle', 'string', ['string', 'string'])

return (buffer, msg, env) => {
if (buffer) instance.HEAPU8.set(buffer)

const { ok, response } = JSON.parse(doHandle(JSON.stringify(msg), JSON.stringify(env)))
/**
* Cleanup any listeners to prevent memory leaks
*/
cleanupListeners.forEach(c => c())

if (!ok) throw response

Expand Down