Skip to content

Instantly share code, notes, and snippets.

@puzpuzpuz
Last active December 23, 2019 17:04
Show Gist options
  • Save puzpuzpuz/f0b23458a821d7edab3738550e58f0e2 to your computer and use it in GitHub Desktop.
Save puzpuzpuz/f0b23458a821d7edab3738550e58f0e2 to your computer and use it in GitHub Desktop.
A fragment of async-resource-vs-destroy.js (see https://github.com/nodejs/node/pull/31016)
/* AsyncContext (implementation based on WeakMap) */
const kStore = 'store';
function buildAsyncContext(getServe) {
const asyncContext = new AsyncContext();
const server = createServer((req, res) => {
asyncContext.run(() => {
getServe(getCLS, setCLS)(req, res);
});
});
return {
server,
close
};
function getCLS() {
const store = asyncContext.getStore();
return store.get(kStore);
}
function setCLS(state) {
const store = asyncContext.getStore();
store.set(kStore, state);
}
function close() {
server.close();
}
}
/* cls-hooked 4.2.2 */
const cls = require('cls-hooked');
function buildClsHooked(getServe) {
const ns = cls.createNamespace('cls-hooked-benchmark');
const server = createServer((req, res) => {
ns.bindEmitter(req);
ns.bindEmitter(res);
ns.run(() => {
getServe(getCLS, setCLS)(req, res);
});
});
return {
server,
close
};
function getCLS() {
return ns.get(kStore);
}
function setCLS(state) {
ns.set(kStore, state);
}
function close() {
server.close();
cls.destroyNamespace('cls-hooked-benchmark');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment