Asynchronous context tracking
Table des matières
- Introduction
- Class: AsyncLocalStorage
- Class: AsyncResource
- new AsyncResource(type[, options])
- Static method: AsyncResource.bind(fn[, type[, thisArg]])
- asyncResource.bind(fn[, thisArg])
- asyncResource.runInAsyncScope(fn[, thisArg, ...args])
- asyncResource.emitDestroy()
- asyncResource.asyncId()
- asyncResource.triggerAsyncId()
- Using AsyncResource for a Worker thread pool
- Integrating AsyncResource with EventEmitter
Ajouté en: v16.4.0
Code source: lib/async_hooks.js
Introduction
These classes are used to associate state and propagate it throughout callbacks and promise chains. They allow storing data throughout the lifetime of a web request or any other asynchronous duration. It is similar to thread-local storage in other languages.
The AsyncLocalStorage and AsyncResource classes are part of the
node:async_hooks module:
MJS
CJS
C AsyncLocalStorage
Historique
| Version | Changements |
|---|---|
| v16.4.0 | AsyncLocalStorage is now Stable. Previously, it had been Experimental. |
| v13.10.0, v12.17.0 | Ajouté en: v13.10.0, v12.17.0 |
This class creates stores that stay coherent through asynchronous operations.
While you can create your own implementation on top of the node:async_hooks
module, AsyncLocalStorage should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.
The following example uses AsyncLocalStorage to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.
MJS
CJS
Each instance of AsyncLocalStorage maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
M new AsyncLocalStorage()
Ajouté en: v13.10.0, v12.17.0
Creates a new instance of AsyncLocalStorage. Store is only provided within a
run() call or after an enterWith() call.
M asyncLocalStorage.disable()
Ajouté en: v13.10.0, v12.17.0
Disables the instance of AsyncLocalStorage. All subsequent calls
to asyncLocalStorage.getStore() will return undefined until
asyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.
When calling asyncLocalStorage.disable(), all current contexts linked to the
instance will be exited.
Calling asyncLocalStorage.disable() is required before the
asyncLocalStorage can be garbage collected. This does not apply to stores
provided by the asyncLocalStorage, as those objects are garbage collected
along with the corresponding async resources.
Use this method when the asyncLocalStorage is not in use anymore
in the current process.
M asyncLocalStorage.getStore()
Ajouté en: v13.10.0, v12.17.0
- Returns:
any
Returns the current store.
If called outside of an asynchronous context initialized by
calling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it
returns undefined.
M asyncLocalStorage.enterWith(store)
Ajouté en: v13.11.0, v12.17.0
storeany
Transitions into the context for the remainder of the current synchronous execution and then persists the store through any following asynchronous calls.
Example:
JS
This transition will continue for the entire synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an AsyncResource. That is why
run() should be preferred over enterWith() unless there are strong reasons
to use the latter method.
JS
M asyncLocalStorage.run(store, callback[, ...args])
Ajouté en: v13.10.0, v12.17.0
Runs a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by run() too.
The stacktrace is not impacted by this call and the context is exited.
Example:
JS
M asyncLocalStorage.exit(callback[, ...args])
Ajouté en: v13.10.0, v12.17.0
Runs a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any getStore()
call done within the callback function will always return undefined.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by exit() too.
The stacktrace is not impacted by this call and the context is re-entered.
Example:
JS
Usage with async/await
If, within an async function, only one await call is to run within a context,
the following pattern should be used:
JS
In this example, the store is only available in the callback function and the
functions called by foo. Outside of run, calling getStore will return
undefined.
Troubleshooting: Context loss
In most cases, AsyncLocalStorage works without issues. In rare situations, the
current store is lost in one of the asynchronous operations.
If your code is callback-based, it is enough to promisify it with
util.promisify() so it starts working with native promises.
If you need to use a callback-based API or your code assumes
a custom thenable implementation, use the AsyncResource class
to associate the asynchronous operation with the correct execution context.
Find the function call responsible for the context loss by logging the content
of asyncLocalStorage.getStore() after the calls you suspect are responsible
for the loss. When the code logs undefined, the last callback called is
probably responsible for the context loss.
C AsyncResource
The class AsyncResource is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.
The init hook will trigger when an AsyncResource is instantiated.
The following is an overview of the AsyncResource API.
MJS
CJS
M new AsyncResource(type[, options])
typestringThe type of async event.optionsObjecttriggerAsyncIdnumberThe ID of the execution context that created this async event. Default:executionAsyncId().requireManualDestroybooleanIf set totrue, disablesemitDestroywhen the object is garbage collected. This usually does not need to be set (even ifemitDestroyis called manually), unless the resource'sasyncIdis retrieved and the sensitive API'semitDestroyis called with it. When set tofalse, theemitDestroycall on garbage collection will only take place if there is at least one activedestroyhook. Default:false.
Example usage:
JS
Static method: AsyncResource.bind(fn[, type[, thisArg]])
Historique
| Version | Changements |
|---|---|
| v17.8.0, v16.15.0 | Changed the default when `thisArg` is undefined to use `this` from the caller. |
| v16.0.0 | Added optional thisArg. |
| v14.8.0, v12.19.0 | Ajouté en: v14.8.0, v12.19.0 |
fnFunctionThe function to bind to the current execution context.typestringAn optional name to associate with the underlyingAsyncResource.thisArgany
Binds the given function to the current execution context.
The returned function will have an asyncResource property referencing
the AsyncResource to which the function is bound.
M asyncResource.bind(fn[, thisArg])
Historique
| Version | Changements |
|---|---|
| v17.8.0, v16.15.0 | Changed the default when `thisArg` is undefined to use `this` from the caller. |
| v16.0.0 | Added optional thisArg. |
| v14.8.0, v12.19.0 | Ajouté en: v14.8.0, v12.19.0 |
Binds the given function to execute to this AsyncResource's scope.
The returned function will have an asyncResource property referencing
the AsyncResource to which the function is bound.
M asyncResource.runInAsyncScope(fn[, thisArg, ...args])
Ajouté en: v9.6.0
fnFunctionThe function to call in the execution context of this async resource.thisArganyThe receiver to be used for the function call....argsanyOptional arguments to pass to the function.
Call the provided function with the provided arguments in the execution context of the async resource. This will establish the context, trigger the AsyncHooks before callbacks, call the function, trigger the AsyncHooks after callbacks, and then restore the original execution context.
M asyncResource.emitDestroy()
- Returns:
AsyncResourceA reference toasyncResource.
Call all destroy hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This must be manually called. If
the resource is left to be collected by the GC then the destroy hooks will
never be called.
M asyncResource.asyncId()
- Returns:
numberThe uniqueasyncIdassigned to the resource.
M asyncResource.triggerAsyncId()
- Returns:
numberThe sametriggerAsyncIdthat is passed to theAsyncResourceconstructor.
Using AsyncResource for a Worker thread pool
The following example shows how to use the AsyncResource class to properly
provide async tracking for a Worker pool. Other resource pools, such as
database connection pools, can follow a similar model.
Assuming that the task is adding two numbers, using a file named
task_processor.js with the following content:
MJS
CJS
a Worker pool around it could use the following structure:
MJS
CJS
Without the explicit tracking added by the WorkerPoolTaskInfo objects,
it would appear that the callbacks are associated with the individual Worker
objects. However, the creation of the Workers is not associated with the
creation of the tasks and does not provide information about when tasks
were scheduled.
This pool could be used as follows:
MJS
CJS
Integrating AsyncResource with EventEmitter
Event listeners triggered by an EventEmitter may be run in a different
execution context than the one that was active when eventEmitter.on() was
called.
The following example shows how to use the AsyncResource class to properly
associate an event listener with the correct execution context. The same
approach can be applied to a Stream or a similar event-driven class.
MJS
CJS