-
Notifications
You must be signed in to change notification settings - Fork 29.7k
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
async_hooks: add currentResource #21313
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
'use strict'; | ||
|
||
const { promisify } = require('util'); | ||
const { readFile } = require('fs'); | ||
const sleep = promisify(setTimeout); | ||
const read = promisify(readFile); | ||
const common = require('../common.js'); | ||
const { | ||
createHook, | ||
currentResource, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this be named |
||
executionAsyncId | ||
} = require('async_hooks'); | ||
const { createServer } = require('http'); | ||
|
||
// configuration for the http server | ||
// there is no need for parameters in this test | ||
const connections = 500; | ||
const path = '/'; | ||
|
||
const bench = common.createBenchmark(main, { | ||
type: ['current-resource', 'destroy'], | ||
method: ['callbacks', 'async'], | ||
n: [1e6] | ||
}); | ||
|
||
function buildCurrentResource(getServe) { | ||
const server = createServer(getServe(getCLS, setCLS)); | ||
const hook = createHook({ init }); | ||
const cls = Symbol('cls'); | ||
let closed = false; | ||
hook.enable(); | ||
|
||
return { | ||
server, | ||
close | ||
}; | ||
|
||
function getCLS() { | ||
// we need to protect this, as once the hook is | ||
// disabled currentResource will return null | ||
if (closed) { | ||
return; | ||
} | ||
|
||
const resource = currentResource(); | ||
if (!resource[cls]) { | ||
return null; | ||
} | ||
return resource[cls].state; | ||
} | ||
|
||
function setCLS(state) { | ||
// we need to protect this, as once the hook is | ||
// disabled currentResource will return null | ||
if (closed) { | ||
return; | ||
} | ||
const resource = currentResource(); | ||
if (!resource[cls]) { | ||
resource[cls] = { state }; | ||
} else { | ||
resource[cls].state = state; | ||
} | ||
} | ||
|
||
function init(asyncId, type, triggerAsyncId, resource) { | ||
if (type === 'TIMERWRAP') return; | ||
|
||
var cr = currentResource(); | ||
if (cr) { | ||
resource[cls] = cr[cls]; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think this necessarily pertinent to the intent of the benchmark here, but I'll call it out nonetheless: If I'm reading correctly, this results in every resource sharing the same object instance for There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Per conversation, here's an example of where values would be over-written: function f0() {
setCLS("a");
setTimeout(function f1() {
setCLS("b");
setTimeout(function f2() {
getCLS(); // expect "b", will get "c"
}, 100);
}, 10);
setTimeout(function f3() => {
getCLS(); // expect "a", will get "b"
setCLS("c");
setTimeout(function f4() {
getCLS(); // get "c"
}, 25);
}, 25);
};
f(); Order of execution is But There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think branch containment really matters for this test. We just need to verify that an object can be passed through the tree via attachment to the current resource in some form. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Agreed, but it came up on the diag call & I offered to post example code. :) |
||
} | ||
} | ||
|
||
function close() { | ||
closed = true; | ||
hook.disable(); | ||
server.close(); | ||
} | ||
} | ||
|
||
function buildDestroy(getServe) { | ||
const transactions = new Map(); | ||
const server = createServer(getServe(getCLS, setCLS)); | ||
const hook = createHook({ init, destroy }); | ||
hook.enable(); | ||
|
||
return { | ||
server, | ||
close | ||
}; | ||
|
||
function getCLS() { | ||
const asyncId = executionAsyncId(); | ||
return transactions.has(asyncId) ? transactions.get(asyncId) : null; | ||
} | ||
|
||
function setCLS(value) { | ||
const asyncId = executionAsyncId(); | ||
transactions.set(asyncId, value); | ||
} | ||
|
||
function init(asyncId, type, triggerAsyncId, resource) { | ||
if (type === 'TIMERWRAP') return; | ||
|
||
transactions.set(asyncId, getCLS()); | ||
} | ||
|
||
function destroy(asyncId) { | ||
transactions.delete(asyncId); | ||
} | ||
|
||
function close() { | ||
hook.disable(); | ||
server.close(); | ||
} | ||
} | ||
|
||
function getServeAwait(getCLS, setCLS) { | ||
return async function serve(req, res) { | ||
setCLS(Math.random()); | ||
await sleep(10); | ||
await read(__filename); | ||
res.setHeader('content-type', 'application/json'); | ||
res.end(JSON.stringify({ cls: getCLS() })); | ||
}; | ||
} | ||
|
||
function getServeCallbacks(getCLS, setCLS) { | ||
return function serve(req, res) { | ||
setCLS(Math.random()); | ||
setTimeout(function() { | ||
readFile(__filename, function() { | ||
res.setHeader('content-type', 'application/json'); | ||
res.end(JSON.stringify({ cls: getCLS() })); | ||
}); | ||
}, 10); | ||
}; | ||
} | ||
|
||
const types = { | ||
'current-resource': buildCurrentResource, | ||
'destroy': buildDestroy | ||
}; | ||
|
||
const asyncMethod = { | ||
'callbacks': getServeCallbacks, | ||
'async': getServeAwait | ||
}; | ||
|
||
function main({ type, method }) { | ||
const { server, close } = types[type](asyncMethod[method]); | ||
|
||
server | ||
.listen(common.PORT) | ||
.on('listening', function() { | ||
|
||
bench.http({ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think I would prefer a benchmark that doesn't use |
||
path, | ||
connections | ||
}, function() { | ||
close(); | ||
}); | ||
}); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -462,6 +462,57 @@ init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() | |
after 6 | ||
``` | ||
|
||
#### async_hooks.currentResource() | ||
|
||
<!-- YAML | ||
added: REPLACEME | ||
--> | ||
|
||
* Returns: {Object} The resource that triggered the current | ||
execution context. | ||
Useful to store data within the resource. | ||
|
||
```js | ||
const { open } = require('fs'); | ||
const { executionAsyncId, currentResource } = require('async_hooks'); | ||
|
||
console.log(executionAsyncId(), currentResource()); // 1 null | ||
open(__filename, 'r', (err, fd) => { | ||
console.log(executionAsyncId(), currentResource()); // 7 FSReqWrap | ||
}); | ||
``` | ||
|
||
This can be used to implement continuation local storage without the | ||
using of a tracking `Map` to store the metadata: | ||
|
||
```js | ||
const { createServer } = require('http'); | ||
const { | ||
executionAsyncId, | ||
currentResource, | ||
createHook | ||
} = require('async_hooks'); | ||
const sym = Symbol('state'); // private symbol to avoid pollution | ||
|
||
createHook({ | ||
init(asyncId, type, triggerAsyncId, resource) { | ||
const cr = currentResource(); | ||
if (cr) { | ||
resource[sym] = cr[sym]; | ||
} | ||
} | ||
}).enable(); | ||
|
||
const server = createServer(function(req, res) { | ||
currentResource()[sym] = { state: req.url }; | ||
setTimeout(function() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
res.end(JSON.stringify(currentResource()[sym])); | ||
}, 100); | ||
}).listen(3000); | ||
``` | ||
|
||
`currentResource()` will return `null` during application bootstrap. | ||
|
||
#### async_hooks.executionAsyncId() | ||
|
||
<!-- YAML | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,6 +25,7 @@ const { | |
emitBefore, | ||
emitAfter, | ||
emitDestroy, | ||
currentResource | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As mentioned above, how about using |
||
} = internal_async_hooks; | ||
|
||
// Get symbols | ||
|
@@ -216,6 +217,7 @@ module.exports = { | |
createHook, | ||
executionAsyncId, | ||
triggerAsyncId, | ||
currentResource, | ||
// Embedder API | ||
AsyncResource, | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -67,6 +67,8 @@ const active_hooks = { | |
|
||
const { registerDestroyHook } = async_wrap; | ||
|
||
const { currentResource, setCurrentResource } = async_wrap; | ||
|
||
// Each constant tracks how many callbacks there are for any given step of | ||
// async execution. These are tracked so if the user didn't include callbacks | ||
// for a given step, that step can bail out early. | ||
|
@@ -337,13 +339,14 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) { | |
} | ||
|
||
|
||
function emitBeforeScript(asyncId, triggerAsyncId) { | ||
function emitBeforeScript(asyncId, triggerAsyncId, resource) { | ||
// Validate the ids. An id of -1 means it was never set and is visible on the | ||
// call graph. An id < -1 should never happen in any circumstance. Throw | ||
// on user calls because async state should still be recoverable. | ||
validateAsyncId(asyncId, 'asyncId'); | ||
validateAsyncId(triggerAsyncId, 'triggerAsyncId'); | ||
|
||
setCurrentResource(resource); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. assert here is that |
||
pushAsyncIds(asyncId, triggerAsyncId); | ||
|
||
if (async_hook_fields[kBefore] > 0) | ||
|
@@ -357,6 +360,8 @@ function emitAfterScript(asyncId) { | |
if (async_hook_fields[kAfter] > 0) | ||
emitAfterNative(asyncId); | ||
|
||
setCurrentResource(null); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If we have nested There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yeah, shouldn't There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I thought the same. However I struggled to execute user code after There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this should work:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this only happening with runInAsyncScope? That would be easy to fix without adding a full stack where we push/pop. Adding a full stack is also a serious refactoring of the async_hooks machinery, something that this PR currently avoids. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @mcollina We do have a full stack in place currently, though?
It can happen with all mechanisms that trigger async hooks. |
||
|
||
popAsyncIds(asyncId); | ||
} | ||
|
||
|
@@ -444,6 +449,7 @@ module.exports = { | |
clearDefaultTriggerAsyncId, | ||
clearAsyncIdStack, | ||
hasAsyncIdStack, | ||
currentResource, | ||
// Internal Embedder API | ||
newAsyncId, | ||
getOrSetAsyncId, | ||
|
@@ -457,4 +463,5 @@ module.exports = { | |
emitAfter: emitAfterScript, | ||
emitDestroy: emitDestroyScript, | ||
registerDestroyHook, | ||
setCurrentResource | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMO some comments explaining what this benchmark is testing will help readers going forward.