2016-11-28 13:06:05 +01:00
|
|
|
# Async Hooks
|
|
|
|
|
2017-11-04 09:08:46 +01:00
|
|
|
<!--introduced_in=v8.1.0-->
|
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
> Stability: 1 - Experimental
|
|
|
|
|
2020-02-06 15:24:45 +01:00
|
|
|
The `async_hooks` module provides an API to track asynchronous resources. It
|
|
|
|
can be accessed using:
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
const async_hooks = require('async_hooks');
|
|
|
|
```
|
|
|
|
|
|
|
|
## Terminology
|
|
|
|
|
|
|
|
An asynchronous resource represents an object with an associated callback.
|
2018-04-09 18:30:22 +02:00
|
|
|
This callback may be called multiple times, for example, the `'connection'`
|
|
|
|
event in `net.createServer()`, or just a single time like in `fs.open()`.
|
2018-04-29 19:46:41 +02:00
|
|
|
A resource can also be closed before the callback is called. `AsyncHook` does
|
|
|
|
not explicitly distinguish between these different cases but will represent them
|
2016-11-28 13:06:05 +01:00
|
|
|
as the abstract concept that is a resource.
|
|
|
|
|
2018-05-22 21:47:06 +02:00
|
|
|
If [`Worker`][]s are used, each thread has an independent `async_hooks`
|
|
|
|
interface, and each thread will use a new set of async IDs.
|
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
## Public API
|
|
|
|
|
|
|
|
### Overview
|
|
|
|
|
|
|
|
Following is a simple overview of the public API.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const async_hooks = require('async_hooks');
|
|
|
|
|
|
|
|
// Return the ID of the current execution context.
|
2017-06-14 12:39:53 +02:00
|
|
|
const eid = async_hooks.executionAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
// Return the ID of the handle responsible for triggering the callback of the
|
|
|
|
// current execution scope to call.
|
2017-06-14 12:39:53 +02:00
|
|
|
const tid = async_hooks.triggerAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
// Create a new AsyncHook instance. All of these callbacks are optional.
|
2017-09-09 17:50:42 +02:00
|
|
|
const asyncHook =
|
|
|
|
async_hooks.createHook({ init, before, after, destroy, promiseResolve });
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
// Allow callbacks of this AsyncHook instance to call. This is not an implicit
|
|
|
|
// action after running the constructor, and must be explicitly run to begin
|
|
|
|
// executing callbacks.
|
|
|
|
asyncHook.enable();
|
|
|
|
|
|
|
|
// Disable listening for new asynchronous events.
|
|
|
|
asyncHook.disable();
|
|
|
|
|
|
|
|
//
|
|
|
|
// The following are the callbacks that can be passed to createHook().
|
|
|
|
//
|
|
|
|
|
|
|
|
// init is called during object construction. The resource may not have
|
|
|
|
// completed construction when this callback runs, therefore all fields of the
|
|
|
|
// resource referenced by "asyncId" may not have been populated.
|
2017-06-14 12:39:53 +02:00
|
|
|
function init(asyncId, type, triggerAsyncId, resource) { }
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-12-03 17:15:45 +01:00
|
|
|
// Before is called just before the resource's callback is called. It can be
|
2016-11-28 13:06:05 +01:00
|
|
|
// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
|
2018-10-31 15:45:07 +01:00
|
|
|
// time for requests (e.g. FSReqCallback).
|
2016-11-28 13:06:05 +01:00
|
|
|
function before(asyncId) { }
|
|
|
|
|
2018-12-03 17:15:45 +01:00
|
|
|
// After is called just after the resource's callback has finished.
|
2016-11-28 13:06:05 +01:00
|
|
|
function after(asyncId) { }
|
|
|
|
|
2018-12-10 13:27:32 +01:00
|
|
|
// Destroy is called when an AsyncWrap instance is destroyed.
|
2016-11-28 13:06:05 +01:00
|
|
|
function destroy(asyncId) { }
|
2017-09-09 17:50:42 +02:00
|
|
|
|
|
|
|
// promiseResolve is called only for promise resources, when the
|
|
|
|
// `resolve` function passed to the `Promise` constructor is invoked
|
|
|
|
// (either directly or through other means of resolving a promise).
|
|
|
|
function promiseResolve(asyncId) { }
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `async_hooks.createHook(callbacks)`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
<!-- YAML
|
2017-11-16 15:32:56 +01:00
|
|
|
added: v8.1.0
|
2016-11-28 13:06:05 +01:00
|
|
|
-->
|
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* `callbacks` {Object} The [Hook Callbacks][] to register
|
2017-08-30 23:45:21 +02:00
|
|
|
* `init` {Function} The [`init` callback][].
|
|
|
|
* `before` {Function} The [`before` callback][].
|
|
|
|
* `after` {Function} The [`after` callback][].
|
|
|
|
* `destroy` {Function} The [`destroy` callback][].
|
2019-09-02 10:31:27 +02:00
|
|
|
* `promiseResolve` {Function} The [`promiseResolve` callback][].
|
2018-01-29 23:15:53 +01:00
|
|
|
* Returns: {AsyncHook} Instance used for disabling and enabling hooks
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
Registers functions to be called for different lifetime events of each async
|
|
|
|
operation.
|
|
|
|
|
|
|
|
The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
|
|
|
|
respective asynchronous event during a resource's lifetime.
|
|
|
|
|
2017-10-21 15:29:49 +02:00
|
|
|
All callbacks are optional. For example, if only resource cleanup needs to
|
|
|
|
be tracked, then only the `destroy` callback needs to be passed. The
|
|
|
|
specifics of all functions that can be passed to `callbacks` is in the
|
|
|
|
[Hook Callbacks][] section.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
```js
|
|
|
|
const async_hooks = require('async_hooks');
|
|
|
|
|
|
|
|
const asyncHook = async_hooks.createHook({
|
|
|
|
init(asyncId, type, triggerAsyncId, resource) { },
|
|
|
|
destroy(asyncId) { }
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2019-06-20 22:09:34 +02:00
|
|
|
The callbacks will be inherited via the prototype chain:
|
2017-08-30 23:45:21 +02:00
|
|
|
|
|
|
|
```js
|
|
|
|
class MyAsyncCallbacks {
|
|
|
|
init(asyncId, type, triggerAsyncId, resource) { }
|
|
|
|
destroy(asyncId) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
class MyAddedCallbacks extends MyAsyncCallbacks {
|
|
|
|
before(asyncId) { }
|
|
|
|
after(asyncId) { }
|
|
|
|
}
|
|
|
|
|
|
|
|
const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
|
|
|
|
```
|
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
##### Error Handling
|
|
|
|
|
|
|
|
If any `AsyncHook` callbacks throw, the application will print the stack trace
|
2017-10-21 15:29:49 +02:00
|
|
|
and exit. The exit path does follow that of an uncaught exception, but
|
2018-04-09 18:30:22 +02:00
|
|
|
all `'uncaughtException'` listeners are removed, thus forcing the process to
|
2016-11-28 13:06:05 +01:00
|
|
|
exit. The `'exit'` callbacks will still be called unless the application is run
|
|
|
|
with `--abort-on-uncaught-exception`, in which case a stack trace will be
|
|
|
|
printed and the application exits, leaving a core file.
|
|
|
|
|
|
|
|
The reason for this error handling behavior is that these callbacks are running
|
|
|
|
at potentially volatile points in an object's lifetime, for example during
|
|
|
|
class construction and destruction. Because of this, it is deemed necessary to
|
|
|
|
bring down the process quickly in order to prevent an unintentional abort in the
|
|
|
|
future. This is subject to change in the future if a comprehensive analysis is
|
|
|
|
performed to ensure an exception can follow the normal control flow without
|
|
|
|
unintentional side effects.
|
|
|
|
|
|
|
|
##### Printing in AsyncHooks callbacks
|
|
|
|
|
|
|
|
Because printing to the console is an asynchronous operation, `console.log()`
|
|
|
|
will cause the AsyncHooks callbacks to be called. Using `console.log()` or
|
|
|
|
similar asynchronous operations inside an AsyncHooks callback function will thus
|
2018-03-13 05:04:55 +01:00
|
|
|
cause an infinite recursion. An easy solution to this when debugging is to use a
|
2018-11-30 10:06:14 +01:00
|
|
|
synchronous logging operation such as `fs.writeFileSync(file, msg, flag)`.
|
|
|
|
This will print to the file and will not invoke AsyncHooks recursively because
|
|
|
|
it is synchronous.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
const fs = require('fs');
|
|
|
|
const util = require('util');
|
|
|
|
|
2017-06-02 11:20:47 +02:00
|
|
|
function debug(...args) {
|
2018-12-03 17:15:45 +01:00
|
|
|
// Use a function like this one when debugging inside an AsyncHooks callback
|
2018-11-30 10:06:14 +01:00
|
|
|
fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
|
2016-11-28 13:06:05 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
If an asynchronous operation is needed for logging, it is possible to keep
|
|
|
|
track of what caused the asynchronous operation using the information
|
|
|
|
provided by AsyncHooks itself. The logging should then be skipped when
|
|
|
|
it was the logging itself that caused AsyncHooks callback to call. By
|
|
|
|
doing this the otherwise infinite recursion is broken.
|
|
|
|
|
2020-02-19 11:27:52 +01:00
|
|
|
### Class: `AsyncHook`
|
|
|
|
|
|
|
|
The class `AsyncHook` exposes an interface for tracking lifetime events
|
|
|
|
of asynchronous operations.
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncHook.enable()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* Returns: {AsyncHook} A reference to `asyncHook`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
Enable the callbacks for a given `AsyncHook` instance. If no callbacks are
|
|
|
|
provided enabling is a noop.
|
|
|
|
|
2017-10-21 15:29:49 +02:00
|
|
|
The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance
|
2016-11-28 13:06:05 +01:00
|
|
|
should be enabled immediately after creation, the following pattern can be used.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const async_hooks = require('async_hooks');
|
|
|
|
|
|
|
|
const hook = async_hooks.createHook(callbacks).enable();
|
|
|
|
```
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncHook.disable()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* Returns: {AsyncHook} A reference to `asyncHook`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
Disable the callbacks for a given `AsyncHook` instance from the global pool of
|
2018-04-29 19:46:41 +02:00
|
|
|
`AsyncHook` callbacks to be executed. Once a hook has been disabled it will not
|
2016-11-28 13:06:05 +01:00
|
|
|
be called again until enabled.
|
|
|
|
|
|
|
|
For API consistency `disable()` also returns the `AsyncHook` instance.
|
|
|
|
|
|
|
|
#### Hook Callbacks
|
|
|
|
|
|
|
|
Key events in the lifetime of asynchronous events have been categorized into
|
|
|
|
four areas: instantiation, before/after the callback is called, and when the
|
2017-10-21 15:29:49 +02:00
|
|
|
instance is destroyed.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
##### `init(asyncId, type, triggerAsyncId, resource)`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* `asyncId` {number} A unique ID for the async resource.
|
|
|
|
* `type` {string} The type of the async resource.
|
|
|
|
* `triggerAsyncId` {number} The unique ID of the async resource in whose
|
|
|
|
execution context this async resource was created.
|
2018-02-12 08:31:55 +01:00
|
|
|
* `resource` {Object} Reference to the resource representing the async
|
|
|
|
operation, needs to be released during _destroy_.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
Called when a class is constructed that has the _possibility_ to emit an
|
|
|
|
asynchronous event. This _does not_ mean the instance must call
|
|
|
|
`before`/`after` before `destroy` is called, only that the possibility
|
|
|
|
exists.
|
|
|
|
|
|
|
|
This behavior can be observed by doing something like opening a resource then
|
|
|
|
closing it before the resource can be used. The following snippet demonstrates
|
|
|
|
this.
|
|
|
|
|
|
|
|
```js
|
|
|
|
require('net').createServer().listen(function() { this.close(); });
|
|
|
|
// OR
|
|
|
|
clearTimeout(setTimeout(() => {}, 10));
|
|
|
|
```
|
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
Every new resource is assigned an ID that is unique within the scope of the
|
2018-05-22 21:47:06 +02:00
|
|
|
current Node.js instance.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
###### `type`
|
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
The `type` is a string identifying the type of resource that caused
|
2017-06-14 00:54:41 +02:00
|
|
|
`init` to be called. Generally, it will correspond to the name of the
|
|
|
|
resource's constructor.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-15 15:57:00 +02:00
|
|
|
```text
|
2018-12-13 18:35:48 +01:00
|
|
|
FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
|
|
|
|
HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
|
|
|
|
SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
|
|
|
|
TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
|
2018-09-19 17:33:52 +02:00
|
|
|
RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2017-06-04 13:35:56 +02:00
|
|
|
There is also the `PROMISE` resource type, which is used to track `Promise`
|
|
|
|
instances and asynchronous work scheduled by them.
|
|
|
|
|
2018-01-23 11:08:20 +01:00
|
|
|
Users are able to define their own `type` when using the public embedder API.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-03-13 04:35:14 +01:00
|
|
|
It is possible to have type name collisions. Embedders are encouraged to use
|
|
|
|
unique prefixes, such as the npm package name, to prevent collisions when
|
|
|
|
listening to the hooks.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-04-15 15:05:55 +02:00
|
|
|
###### `triggerAsyncId`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
`triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered")
|
|
|
|
the new resource to initialize and that caused `init` to call. This is different
|
2017-06-14 12:39:53 +02:00
|
|
|
from `async_hooks.executionAsyncId()` that only shows *when* a resource was
|
|
|
|
created, while `triggerAsyncId` shows *why* a resource was created.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-14 12:39:53 +02:00
|
|
|
The following is a simple demonstration of `triggerAsyncId`:
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
async_hooks.createHook({
|
2017-06-14 12:39:53 +02:00
|
|
|
init(asyncId, type, triggerAsyncId) {
|
|
|
|
const eid = async_hooks.executionAsyncId();
|
2017-06-02 15:17:58 +02:00
|
|
|
fs.writeSync(
|
2017-06-14 12:39:53 +02:00
|
|
|
1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
|
2016-11-28 13:06:05 +01:00
|
|
|
}
|
|
|
|
}).enable();
|
|
|
|
|
|
|
|
require('net').createServer((conn) => {}).listen(8080);
|
|
|
|
```
|
|
|
|
|
|
|
|
Output when hitting the server with `nc localhost 8080`:
|
|
|
|
|
2017-06-15 15:57:00 +02:00
|
|
|
```console
|
2018-11-02 23:58:37 +01:00
|
|
|
TCPSERVERWRAP(5): trigger: 1 execution: 1
|
|
|
|
TCPWRAP(7): trigger: 5 execution: 0
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2017-11-20 17:18:40 +01:00
|
|
|
The `TCPSERVERWRAP` is the server which receives the connections.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-11-20 17:18:40 +01:00
|
|
|
The `TCPWRAP` is the new connection from the client. When a new
|
2018-03-13 04:35:14 +01:00
|
|
|
connection is made, the `TCPWrap` instance is immediately constructed. This
|
|
|
|
happens outside of any JavaScript stack. (An `executionAsyncId()` of `0` means
|
2018-03-15 06:32:42 +01:00
|
|
|
that it is being executed from C++ with no JavaScript stack above it.) With only
|
2018-03-13 04:35:14 +01:00
|
|
|
that information, it would be impossible to link resources together in
|
2018-02-12 08:31:55 +01:00
|
|
|
terms of what caused them to be created, so `triggerAsyncId` is given the task
|
|
|
|
of propagating what resource is responsible for the new resource's existence.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
###### `resource`
|
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
`resource` is an object that represents the actual async resource that has
|
|
|
|
been initialized. This can contain useful information that can vary based on
|
|
|
|
the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type,
|
2020-01-12 16:17:57 +01:00
|
|
|
`resource` provides the host name used when looking up the IP address for the
|
2018-11-06 18:58:42 +01:00
|
|
|
host in `net.Server.listen()`. The API for accessing this information is
|
2017-08-30 23:45:21 +02:00
|
|
|
currently not considered public, but using the Embedder API, users can provide
|
2017-10-21 15:29:49 +02:00
|
|
|
and document their own resource objects. For example, such a resource object
|
|
|
|
could contain the SQL query being executed.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-10-12 08:56:26 +02:00
|
|
|
In the case of Promises, the `resource` object will have an
|
2018-04-29 19:46:41 +02:00
|
|
|
`isChainedPromise` property, set to `true` if the promise has a parent promise,
|
|
|
|
and `false` otherwise. For example, in the case of `b = a.then(handler)`, `a` is
|
|
|
|
considered a parent `Promise` of `b`. Here, `b` is considered a chained promise.
|
2017-06-04 13:35:56 +02:00
|
|
|
|
2018-02-06 06:55:16 +01:00
|
|
|
In some cases the resource object is reused for performance reasons, it is
|
|
|
|
thus not safe to use it as a key in a `WeakMap` or add properties to it.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
###### Asynchronous context example
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
The following is an example with additional information about the calls to
|
2016-11-28 13:06:05 +01:00
|
|
|
`init` between the `before` and `after` calls, specifically what the
|
|
|
|
callback to `listen()` will look like. The output formatting is slightly more
|
|
|
|
elaborate to make calling context easier to see.
|
|
|
|
|
|
|
|
```js
|
|
|
|
let indent = 0;
|
|
|
|
async_hooks.createHook({
|
2017-06-14 12:39:53 +02:00
|
|
|
init(asyncId, type, triggerAsyncId) {
|
|
|
|
const eid = async_hooks.executionAsyncId();
|
2017-06-02 15:17:58 +02:00
|
|
|
const indentStr = ' '.repeat(indent);
|
|
|
|
fs.writeSync(
|
|
|
|
1,
|
2017-06-14 12:39:53 +02:00
|
|
|
`${indentStr}${type}(${asyncId}):` +
|
|
|
|
` trigger: ${triggerAsyncId} execution: ${eid}\n`);
|
2016-11-28 13:06:05 +01:00
|
|
|
},
|
|
|
|
before(asyncId) {
|
2017-06-02 15:17:58 +02:00
|
|
|
const indentStr = ' '.repeat(indent);
|
2018-11-30 10:06:14 +01:00
|
|
|
fs.writeFileSync('log.out',
|
|
|
|
`${indentStr}before: ${asyncId}\n`, { flag: 'a' });
|
2016-11-28 13:06:05 +01:00
|
|
|
indent += 2;
|
|
|
|
},
|
|
|
|
after(asyncId) {
|
|
|
|
indent -= 2;
|
2017-06-02 15:17:58 +02:00
|
|
|
const indentStr = ' '.repeat(indent);
|
2018-11-30 10:06:14 +01:00
|
|
|
fs.writeFileSync('log.out',
|
|
|
|
`${indentStr}after: ${asyncId}\n`, { flag: 'a' });
|
2016-11-28 13:06:05 +01:00
|
|
|
},
|
|
|
|
destroy(asyncId) {
|
2017-06-02 15:17:58 +02:00
|
|
|
const indentStr = ' '.repeat(indent);
|
2018-11-30 10:06:14 +01:00
|
|
|
fs.writeFileSync('log.out',
|
|
|
|
`${indentStr}destroy: ${asyncId}\n`, { flag: 'a' });
|
2016-11-28 13:06:05 +01:00
|
|
|
},
|
|
|
|
}).enable();
|
|
|
|
|
|
|
|
require('net').createServer(() => {}).listen(8080, () => {
|
|
|
|
// Let's wait 10ms before logging the server started.
|
|
|
|
setTimeout(() => {
|
2017-06-14 12:39:53 +02:00
|
|
|
console.log('>>>', async_hooks.executionAsyncId());
|
2016-11-28 13:06:05 +01:00
|
|
|
}, 10);
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
Output from only starting the server:
|
|
|
|
|
2017-06-15 15:57:00 +02:00
|
|
|
```console
|
2018-11-02 23:58:37 +01:00
|
|
|
TCPSERVERWRAP(5): trigger: 1 execution: 1
|
|
|
|
TickObject(6): trigger: 5 execution: 1
|
|
|
|
before: 6
|
|
|
|
Timeout(7): trigger: 6 execution: 6
|
|
|
|
after: 6
|
|
|
|
destroy: 6
|
|
|
|
before: 7
|
|
|
|
>>> 7
|
|
|
|
TickObject(8): trigger: 7 execution: 7
|
|
|
|
after: 7
|
|
|
|
before: 8
|
|
|
|
after: 8
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2018-02-06 06:55:16 +01:00
|
|
|
As illustrated in the example, `executionAsyncId()` and `execution` each specify
|
|
|
|
the value of the current execution context; which is delineated by calls to
|
|
|
|
`before` and `after`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-14 12:39:53 +02:00
|
|
|
Only using `execution` to graph resource allocation results in the following:
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-15 15:57:00 +02:00
|
|
|
```console
|
2018-11-02 23:58:37 +01:00
|
|
|
Timeout(7) -> TickObject(6) -> root(1)
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2017-11-20 17:18:40 +01:00
|
|
|
The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for
|
2020-01-12 16:17:57 +01:00
|
|
|
`console.log()` being called. This is because binding to a port without a host
|
|
|
|
name is a *synchronous* operation, but to maintain a completely asynchronous
|
2017-08-30 23:45:21 +02:00
|
|
|
API the user's callback is placed in a `process.nextTick()`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
The graph only shows *when* a resource was created, not *why*, so to track
|
2017-06-14 12:39:53 +02:00
|
|
|
the *why* use `triggerAsyncId`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
##### `before(asyncId)`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
* `asyncId` {number}
|
|
|
|
|
|
|
|
When an asynchronous operation is initiated (such as a TCP server receiving a
|
|
|
|
new connection) or completes (such as writing data to disk) a callback is
|
|
|
|
called to notify the user. The `before` callback is called just before said
|
|
|
|
callback is executed. `asyncId` is the unique identifier assigned to the
|
|
|
|
resource about to execute the callback.
|
|
|
|
|
|
|
|
The `before` callback will be called 0 to N times. The `before` callback
|
|
|
|
will typically be called 0 times if the asynchronous operation was cancelled
|
2017-08-30 23:45:21 +02:00
|
|
|
or, for example, if no connections are received by a TCP server. Persistent
|
|
|
|
asynchronous resources like a TCP server will typically call the `before`
|
2017-10-21 15:29:49 +02:00
|
|
|
callback multiple times, while other operations like `fs.open()` will call
|
2017-08-30 23:45:21 +02:00
|
|
|
it only once.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
##### `after(asyncId)`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
* `asyncId` {number}
|
|
|
|
|
|
|
|
Called immediately after the callback specified in `before` is completed.
|
|
|
|
|
2018-03-13 04:35:14 +01:00
|
|
|
If an uncaught exception occurs during execution of the callback, then `after`
|
|
|
|
will run *after* the `'uncaughtException'` event is emitted or a `domain`'s
|
|
|
|
handler runs.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
##### `destroy(asyncId)`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
* `asyncId` {number}
|
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
Called after the resource corresponding to `asyncId` is destroyed. It is also
|
|
|
|
called asynchronously from the embedder API `emitDestroy()`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-03-13 04:35:14 +01:00
|
|
|
Some resources depend on garbage collection for cleanup, so if a reference is
|
|
|
|
made to the `resource` object passed to `init` it is possible that `destroy`
|
|
|
|
will never be called, causing a memory leak in the application. If the resource
|
|
|
|
does not depend on garbage collection, then this will not be an issue.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
##### `promiseResolve(asyncId)`
|
2017-09-09 17:50:42 +02:00
|
|
|
|
2019-03-29 11:23:08 +01:00
|
|
|
<!-- YAML
|
|
|
|
added: v8.6.0
|
|
|
|
-->
|
|
|
|
|
2017-09-09 17:50:42 +02:00
|
|
|
* `asyncId` {number}
|
|
|
|
|
|
|
|
Called when the `resolve` function passed to the `Promise` constructor is
|
|
|
|
invoked (either directly or through other means of resolving a promise).
|
|
|
|
|
2019-06-20 22:09:34 +02:00
|
|
|
`resolve()` does not do any observable synchronous work.
|
2017-09-09 17:50:42 +02:00
|
|
|
|
2018-03-13 04:35:14 +01:00
|
|
|
The `Promise` is not necessarily fulfilled or rejected at this point if the
|
|
|
|
`Promise` was resolved by assuming the state of another `Promise`.
|
2017-09-09 17:50:42 +02:00
|
|
|
|
|
|
|
```js
|
|
|
|
new Promise((resolve) => resolve(true)).then((a) => {});
|
|
|
|
```
|
|
|
|
|
|
|
|
calls the following callbacks:
|
|
|
|
|
2017-10-22 17:51:14 +02:00
|
|
|
```text
|
2017-09-09 17:50:42 +02:00
|
|
|
init for PROMISE with id 5, trigger id: 1
|
|
|
|
promise resolve 5 # corresponds to resolve(true)
|
|
|
|
init for PROMISE with id 6, trigger id: 5 # the Promise returned by then()
|
|
|
|
before 6 # the then() callback is entered
|
|
|
|
promise resolve 6 # the then() callback resolves the promise by returning
|
|
|
|
after 6
|
|
|
|
```
|
|
|
|
|
2018-05-04 08:00:07 +02:00
|
|
|
#### `async_hooks.executionAsyncResource()`
|
|
|
|
|
|
|
|
<!-- YAML
|
2020-02-17 22:02:21 +01:00
|
|
|
added: v13.9.0
|
2018-05-04 08:00:07 +02:00
|
|
|
-->
|
|
|
|
|
|
|
|
* Returns: {Object} The resource representing the current execution.
|
|
|
|
Useful to store data within the resource.
|
|
|
|
|
|
|
|
Resource objects returned by `executionAsyncResource()` are most often internal
|
|
|
|
Node.js handle objects with undocumented APIs. Using any functions or properties
|
|
|
|
on the object is likely to crash your application and should be avoided.
|
|
|
|
|
|
|
|
Using `executionAsyncResource()` in the top-level execution context will
|
|
|
|
return an empty object as there is no handle or request object to use,
|
|
|
|
but having an object representing the top-level can be helpful.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const { open } = require('fs');
|
|
|
|
const { executionAsyncId, executionAsyncResource } = require('async_hooks');
|
|
|
|
|
|
|
|
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
|
|
|
|
open(__filename, 'r', (err, fd) => {
|
|
|
|
console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
This can be used to implement continuation local storage without the
|
|
|
|
use of a tracking `Map` to store the metadata:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const { createServer } = require('http');
|
|
|
|
const {
|
|
|
|
executionAsyncId,
|
|
|
|
executionAsyncResource,
|
|
|
|
createHook
|
|
|
|
} = require('async_hooks');
|
|
|
|
const sym = Symbol('state'); // Private symbol to avoid pollution
|
|
|
|
|
|
|
|
createHook({
|
|
|
|
init(asyncId, type, triggerAsyncId, resource) {
|
|
|
|
const cr = executionAsyncResource();
|
|
|
|
if (cr) {
|
|
|
|
resource[sym] = cr[sym];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}).enable();
|
|
|
|
|
|
|
|
const server = createServer(function(req, res) {
|
|
|
|
executionAsyncResource()[sym] = { state: req.url };
|
|
|
|
setTimeout(function() {
|
|
|
|
res.end(JSON.stringify(executionAsyncResource()[sym]));
|
|
|
|
}, 100);
|
|
|
|
}).listen(3000);
|
|
|
|
```
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `async_hooks.executionAsyncId()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-12-22 00:10:24 +01:00
|
|
|
<!-- YAML
|
|
|
|
added: v8.1.0
|
|
|
|
changes:
|
|
|
|
- version: v8.2.0
|
|
|
|
pr-url: https://github.com/nodejs/node/pull/13490
|
2018-04-29 19:46:41 +02:00
|
|
|
description: Renamed from `currentId`
|
2017-12-22 00:10:24 +01:00
|
|
|
-->
|
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* Returns: {number} The `asyncId` of the current execution context. Useful to
|
2017-08-30 23:45:21 +02:00
|
|
|
track when something calls.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
```js
|
2017-08-30 23:45:21 +02:00
|
|
|
const async_hooks = require('async_hooks');
|
|
|
|
|
2017-06-14 12:39:53 +02:00
|
|
|
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
|
2017-06-02 15:17:58 +02:00
|
|
|
fs.open(path, 'r', (err, fd) => {
|
2017-06-14 12:39:53 +02:00
|
|
|
console.log(async_hooks.executionAsyncId()); // 6 - open()
|
2016-11-28 13:06:05 +01:00
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2018-01-22 04:29:18 +01:00
|
|
|
The ID returned from `executionAsyncId()` is related to execution timing, not
|
2018-02-21 00:10:10 +01:00
|
|
|
causality (which is covered by `triggerAsyncId()`):
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
```js
|
2018-11-24 08:35:20 +01:00
|
|
|
const server = net.createServer((conn) => {
|
2016-11-28 13:06:05 +01:00
|
|
|
// Returns the ID of the server, not of the new connection, because the
|
2018-11-24 08:35:20 +01:00
|
|
|
// callback runs in the execution scope of the server's MakeCallback().
|
2017-06-14 12:39:53 +02:00
|
|
|
async_hooks.executionAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-11-24 08:35:20 +01:00
|
|
|
}).listen(port, () => {
|
2016-11-28 13:06:05 +01:00
|
|
|
// Returns the ID of a TickObject (i.e. process.nextTick()) because all
|
|
|
|
// callbacks passed to .listen() are wrapped in a nextTick().
|
2017-06-14 12:39:53 +02:00
|
|
|
async_hooks.executionAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2019-06-20 22:09:34 +02:00
|
|
|
Promise contexts may not get precise `executionAsyncIds` by default.
|
2018-02-03 00:48:09 +01:00
|
|
|
See the section on [promise execution tracking][].
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `async_hooks.triggerAsyncId()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* Returns: {number} The ID of the resource responsible for calling the callback
|
2016-11-28 13:06:05 +01:00
|
|
|
that is currently being executed.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const server = net.createServer((conn) => {
|
2017-06-02 15:17:58 +02:00
|
|
|
// The resource that caused (or triggered) this callback to be called
|
2017-06-14 12:39:53 +02:00
|
|
|
// was that of the new connection. Thus the return value of triggerAsyncId()
|
2017-06-02 15:17:58 +02:00
|
|
|
// is the asyncId of "conn".
|
2017-06-14 12:39:53 +02:00
|
|
|
async_hooks.triggerAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
}).listen(port, () => {
|
|
|
|
// Even though all callbacks passed to .listen() are wrapped in a nextTick()
|
|
|
|
// the callback itself exists because the call to the server's .listen()
|
|
|
|
// was made. So the return value would be the ID of the server.
|
2017-06-14 12:39:53 +02:00
|
|
|
async_hooks.triggerAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2019-06-20 22:09:34 +02:00
|
|
|
Promise contexts may not get valid `triggerAsyncId`s by default. See
|
2018-02-03 00:48:09 +01:00
|
|
|
the section on [promise execution tracking][].
|
|
|
|
|
|
|
|
## Promise execution tracking
|
|
|
|
|
2018-04-29 19:46:41 +02:00
|
|
|
By default, promise executions are not assigned `asyncId`s due to the relatively
|
2018-02-03 00:48:09 +01:00
|
|
|
expensive nature of the [promise introspection API][PromiseHooks] provided by
|
|
|
|
V8. This means that programs using promises or `async`/`await` will not get
|
|
|
|
correct execution and trigger ids for promise callback contexts by default.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const ah = require('async_hooks');
|
|
|
|
Promise.resolve(1729).then(() => {
|
|
|
|
console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
|
|
|
|
});
|
|
|
|
// produces:
|
|
|
|
// eid 1 tid 0
|
|
|
|
```
|
|
|
|
|
2018-04-29 19:46:41 +02:00
|
|
|
Observe that the `then()` callback claims to have executed in the context of the
|
2019-06-20 22:09:34 +02:00
|
|
|
outer scope even though there was an asynchronous hop involved. Also,
|
2018-04-29 19:46:41 +02:00
|
|
|
the `triggerAsyncId` value is `0`, which means that we are missing context about
|
|
|
|
the resource that caused (triggered) the `then()` callback to be executed.
|
2018-02-03 00:48:09 +01:00
|
|
|
|
|
|
|
Installing async hooks via `async_hooks.createHook` enables promise execution
|
2018-08-26 18:02:27 +02:00
|
|
|
tracking:
|
2018-02-03 00:48:09 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
const ah = require('async_hooks');
|
|
|
|
ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
|
|
|
|
Promise.resolve(1729).then(() => {
|
|
|
|
console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
|
|
|
|
});
|
|
|
|
// produces:
|
|
|
|
// eid 7 tid 6
|
|
|
|
```
|
|
|
|
|
|
|
|
In this example, adding any actual hook function enabled the tracking of
|
|
|
|
promises. There are two promises in the example above; the promise created by
|
2018-04-29 19:46:41 +02:00
|
|
|
`Promise.resolve()` and the promise returned by the call to `then()`. In the
|
|
|
|
example above, the first promise got the `asyncId` `6` and the latter got
|
|
|
|
`asyncId` `7`. During the execution of the `then()` callback, we are executing
|
|
|
|
in the context of promise with `asyncId` `7`. This promise was triggered by
|
|
|
|
async resource `6`.
|
2018-02-03 00:48:09 +01:00
|
|
|
|
|
|
|
Another subtlety with promises is that `before` and `after` callbacks are run
|
2018-04-29 19:46:41 +02:00
|
|
|
only on chained promises. That means promises not created by `then()`/`catch()`
|
|
|
|
will not have the `before` and `after` callbacks fired on them. For more details
|
|
|
|
see the details of the V8 [PromiseHooks][] API.
|
2018-02-03 00:48:09 +01:00
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
## JavaScript Embedder API
|
|
|
|
|
2017-12-31 10:45:43 +01:00
|
|
|
Library developers that handle their own asynchronous resources performing tasks
|
2018-02-12 08:31:55 +01:00
|
|
|
like I/O, connection pooling, or managing callback queues may use the
|
|
|
|
`AsyncWrap` JavaScript API so that all the appropriate callbacks are called.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
### Class: `AsyncResource`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-03-13 05:04:55 +01:00
|
|
|
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
|
2016-11-28 13:06:05 +01:00
|
|
|
own resources.
|
|
|
|
|
|
|
|
The `init` hook will trigger when an `AsyncResource` is instantiated.
|
|
|
|
|
|
|
|
The following is an overview of the `AsyncResource` API.
|
|
|
|
|
|
|
|
```js
|
2017-11-09 22:57:04 +01:00
|
|
|
const { AsyncResource, executionAsyncId } = require('async_hooks');
|
2017-06-02 15:17:58 +02:00
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
// AsyncResource() is meant to be extended. Instantiating a
|
2017-06-14 12:39:53 +02:00
|
|
|
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
|
|
|
// async_hook.executionAsyncId() is used.
|
2017-11-09 22:57:04 +01:00
|
|
|
const asyncResource = new AsyncResource(
|
|
|
|
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
|
|
|
|
);
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-02-02 00:25:41 +01:00
|
|
|
// Run a function in the execution context of the resource. This will
|
|
|
|
// * establish the context of the resource
|
|
|
|
// * trigger the AsyncHooks before callbacks
|
|
|
|
// * call the provided function `fn` with the supplied arguments
|
|
|
|
// * trigger the AsyncHooks after callbacks
|
|
|
|
// * restore the original execution context
|
|
|
|
asyncResource.runInAsyncScope(fn, thisArg, ...args);
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
// Call AsyncHooks destroy callbacks.
|
|
|
|
asyncResource.emitDestroy();
|
|
|
|
|
|
|
|
// Return the unique ID assigned to the AsyncResource instance.
|
|
|
|
asyncResource.asyncId();
|
|
|
|
|
|
|
|
// Return the trigger ID for the AsyncResource instance.
|
2017-06-14 12:39:53 +02:00
|
|
|
asyncResource.triggerAsyncId();
|
2016-11-28 13:06:05 +01:00
|
|
|
```
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `new AsyncResource(type[, options])`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-10-21 15:29:49 +02:00
|
|
|
* `type` {string} The type of async event.
|
2017-11-09 22:57:04 +01:00
|
|
|
* `options` {Object}
|
|
|
|
* `triggerAsyncId` {number} The ID of the execution context that created this
|
2018-04-02 07:38:48 +02:00
|
|
|
async event. **Default:** `executionAsyncId()`.
|
2020-03-27 07:22:45 +01:00
|
|
|
* `requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy`
|
|
|
|
when the object is garbage collected. This usually does not need to be set
|
|
|
|
(even if `emitDestroy` is called manually), unless the resource's `asyncId`
|
|
|
|
is retrieved and the sensitive API's `emitDestroy` is called with it.
|
2020-03-22 19:53:52 +01:00
|
|
|
When set to `false`, the `emitDestroy` call on garbage collection
|
|
|
|
will only take place if there is at least one active `destroy` hook.
|
2018-04-29 19:46:41 +02:00
|
|
|
**Default:** `false`.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
```js
|
|
|
|
class DBQuery extends AsyncResource {
|
|
|
|
constructor(db) {
|
|
|
|
super('DBQuery');
|
|
|
|
this.db = db;
|
|
|
|
}
|
|
|
|
|
|
|
|
getInfo(query, callback) {
|
|
|
|
this.db.get(query, (err, data) => {
|
2018-02-02 00:25:41 +01:00
|
|
|
this.runInAsyncScope(callback, null, err, data);
|
2016-11-28 13:06:05 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
|
|
|
this.db = null;
|
|
|
|
this.emitDestroy();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
|
2018-02-02 00:25:41 +01:00
|
|
|
<!-- YAML
|
2018-02-21 17:28:13 +01:00
|
|
|
added: v9.6.0
|
2018-02-02 00:25:41 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
* `fn` {Function} The function to call in the execution context of this async
|
|
|
|
resource.
|
|
|
|
* `thisArg` {any} The receiver to be used for the function call.
|
|
|
|
* `...args` {any} Optional 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.
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncResource.emitDestroy()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-10-31 09:53:38 +01:00
|
|
|
* Returns: {AsyncResource} A reference to `asyncResource`.
|
|
|
|
|
2016-11-28 13:06:05 +01:00
|
|
|
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.
|
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncResource.asyncId()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2017-06-18 21:53:54 +02:00
|
|
|
* Returns: {number} The unique `asyncId` assigned to the resource.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2019-12-23 21:38:38 +01:00
|
|
|
#### `asyncResource.triggerAsyncId()`
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2018-02-12 08:31:55 +01:00
|
|
|
* Returns: {number} The same `triggerAsyncId` that is passed to the
|
|
|
|
`AsyncResource` constructor.
|
2016-11-28 13:06:05 +01:00
|
|
|
|
2020-02-01 13:48:16 +01:00
|
|
|
<a id="async-resource-worker-pool"></a>
|
|
|
|
### 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:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const { parentPort } = require('worker_threads');
|
|
|
|
parentPort.on('message', (task) => {
|
|
|
|
parentPort.postMessage(task.a + task.b);
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
a Worker pool around it could use the following structure:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const { AsyncResource } = require('async_hooks');
|
|
|
|
const { EventEmitter } = require('events');
|
|
|
|
const path = require('path');
|
|
|
|
const { Worker } = require('worker_threads');
|
|
|
|
|
|
|
|
const kTaskInfo = Symbol('kTaskInfo');
|
|
|
|
const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
|
|
|
|
|
|
|
|
class WorkerPoolTaskInfo extends AsyncResource {
|
|
|
|
constructor(callback) {
|
|
|
|
super('WorkerPoolTaskInfo');
|
|
|
|
this.callback = callback;
|
|
|
|
}
|
|
|
|
|
|
|
|
done(err, result) {
|
|
|
|
this.runInAsyncScope(this.callback, null, err, result);
|
|
|
|
this.emitDestroy(); // `TaskInfo`s are used only once.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class WorkerPool extends EventEmitter {
|
|
|
|
constructor(numThreads) {
|
|
|
|
super();
|
|
|
|
this.numThreads = numThreads;
|
|
|
|
this.workers = [];
|
|
|
|
this.freeWorkers = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < numThreads; i++)
|
|
|
|
this.addNewWorker();
|
|
|
|
}
|
|
|
|
|
|
|
|
addNewWorker() {
|
|
|
|
const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
|
|
|
|
worker.on('message', (result) => {
|
|
|
|
// In case of success: Call the callback that was passed to `runTask`,
|
|
|
|
// remove the `TaskInfo` associated with the Worker, and mark it as free
|
|
|
|
// again.
|
|
|
|
worker[kTaskInfo].done(null, result);
|
|
|
|
worker[kTaskInfo] = null;
|
|
|
|
this.freeWorkers.push(worker);
|
|
|
|
this.emit(kWorkerFreedEvent);
|
|
|
|
});
|
|
|
|
worker.on('error', (err) => {
|
|
|
|
// In case of an uncaught exception: Call the callback that was passed to
|
|
|
|
// `runTask` with the error.
|
|
|
|
if (worker[kTaskInfo])
|
|
|
|
worker[kTaskInfo].done(err, null);
|
|
|
|
else
|
|
|
|
this.emit('error', err);
|
|
|
|
// Remove the worker from the list and start a new Worker to replace the
|
|
|
|
// current one.
|
|
|
|
this.workers.splice(this.workers.indexOf(worker), 1);
|
|
|
|
this.addNewWorker();
|
|
|
|
});
|
|
|
|
this.workers.push(worker);
|
|
|
|
this.freeWorkers.push(worker);
|
|
|
|
}
|
|
|
|
|
|
|
|
runTask(task, callback) {
|
|
|
|
if (this.freeWorkers.length === 0) {
|
|
|
|
// No free threads, wait until a worker thread becomes free.
|
|
|
|
this.once(kWorkerFreedEvent, () => this.runTask(task, callback));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const worker = this.freeWorkers.pop();
|
|
|
|
worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
|
|
|
|
worker.postMessage(task);
|
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
|
|
|
for (const worker of this.workers) worker.terminate();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = WorkerPool;
|
|
|
|
```
|
|
|
|
|
|
|
|
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 `Worker`s 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:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const WorkerPool = require('./worker_pool.js');
|
|
|
|
const os = require('os');
|
|
|
|
|
|
|
|
const pool = new WorkerPool(os.cpus().length);
|
|
|
|
|
|
|
|
let finished = 0;
|
|
|
|
for (let i = 0; i < 10; i++) {
|
|
|
|
pool.runTask({ a: 42, b: 100 }, (err, result) => {
|
|
|
|
console.log(i, err, result);
|
|
|
|
if (++finished === 10)
|
|
|
|
pool.close();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2019-03-01 21:31:36 +01:00
|
|
|
## Class: `AsyncLocalStorage`
|
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
This class is used to create asynchronous state within callbacks and promise
|
|
|
|
chains. It allows 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 following example builds a logger that will always know the current HTTP
|
|
|
|
request and uses it to display enhanced logs without needing to explicitly
|
|
|
|
provide the current HTTP request to it.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const { AsyncLocalStorage } = require('async_hooks');
|
|
|
|
const http = require('http');
|
|
|
|
|
|
|
|
const kReq = 'CURRENT_REQUEST';
|
|
|
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
|
|
|
|
|
|
function log(...args) {
|
|
|
|
const store = asyncLocalStorage.getStore();
|
|
|
|
// Make sure the store exists and it contains a request.
|
|
|
|
if (store && store.has(kReq)) {
|
|
|
|
const req = store.get(kReq);
|
|
|
|
// Prints `GET /items ERR could not do something
|
|
|
|
console.log(req.method, req.url, ...args);
|
|
|
|
} else {
|
|
|
|
console.log(...args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
http.createServer((request, response) => {
|
2020-02-24 11:00:59 +01:00
|
|
|
asyncLocalStorage.run(new Map(), () => {
|
2019-03-01 21:31:36 +01:00
|
|
|
const store = asyncLocalStorage.getStore();
|
|
|
|
store.set(kReq, request);
|
|
|
|
someAsyncOperation((err, result) => {
|
|
|
|
if (err) {
|
|
|
|
log('ERR', err.message);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.listen(8080);
|
|
|
|
```
|
|
|
|
|
|
|
|
When having multiple instances of `AsyncLocalStorage`, they are independent
|
|
|
|
from each other. It is safe to instantiate this class multiple times.
|
|
|
|
|
|
|
|
### `new AsyncLocalStorage()`
|
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
|
2020-03-14 07:06:06 +01:00
|
|
|
`run` method call.
|
2019-03-01 21:31:36 +01:00
|
|
|
|
|
|
|
### `asyncLocalStorage.disable()`
|
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
This method disables the instance of `AsyncLocalStorage`. All subsequent calls
|
|
|
|
to `asyncLocalStorage.getStore()` will return `undefined` until
|
2020-03-14 07:06:06 +01:00
|
|
|
`asyncLocalStorage.run()` is called again.
|
2019-03-01 21:31:36 +01:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
This method is to be used when the `asyncLocalStorage` is not in use anymore
|
|
|
|
in the current process.
|
|
|
|
|
|
|
|
### `asyncLocalStorage.getStore()`
|
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
2020-02-24 11:00:59 +01:00
|
|
|
* Returns: {any}
|
2019-03-01 21:31:36 +01:00
|
|
|
|
|
|
|
This method returns the current store.
|
|
|
|
If this method is called outside of an asynchronous context initialized by
|
2020-03-14 07:06:06 +01:00
|
|
|
calling `asyncLocalStorage.run`, it will return `undefined`.
|
2019-03-01 21:31:36 +01:00
|
|
|
|
2020-02-25 06:46:46 +01:00
|
|
|
### `asyncLocalStorage.enterWith(store)`
|
|
|
|
<!-- YAML
|
2020-03-10 23:56:51 +01:00
|
|
|
added: v13.11.0
|
2020-02-25 06:46:46 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
* `store` {any}
|
|
|
|
|
|
|
|
Calling `asyncLocalStorage.enterWith(store)` will transition into the context
|
|
|
|
for the remainder of the current synchronous execution and will persist
|
|
|
|
through any following asynchronous calls.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const store = { id: 1 };
|
|
|
|
asyncLocalStorage.enterWith(store);
|
|
|
|
asyncLocalStorage.getStore(); // Returns the store object
|
|
|
|
someAsyncOperation(() => {
|
|
|
|
asyncLocalStorage.getStore(); // Returns the same object
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
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`.
|
|
|
|
|
|
|
|
```js
|
|
|
|
const store = { id: 1 };
|
|
|
|
|
|
|
|
emitter.on('my-event', () => {
|
|
|
|
asyncLocalStorage.enterWith(store);
|
|
|
|
});
|
|
|
|
emitter.on('my-event', () => {
|
|
|
|
asyncLocalStorage.getStore(); // Returns the same object
|
|
|
|
});
|
|
|
|
|
|
|
|
asyncLocalStorage.getStore(); // Returns undefined
|
|
|
|
emitter.emit('my-event');
|
|
|
|
asyncLocalStorage.getStore(); // Returns the same object
|
|
|
|
```
|
|
|
|
|
2020-02-24 11:00:59 +01:00
|
|
|
### `asyncLocalStorage.run(store, callback[, ...args])`
|
2019-03-01 21:31:36 +01:00
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
2020-02-24 11:00:59 +01:00
|
|
|
* `store` {any}
|
2019-03-01 21:31:36 +01:00
|
|
|
* `callback` {Function}
|
|
|
|
* `...args` {any}
|
|
|
|
|
|
|
|
This methods runs a function synchronously within a context and return its
|
|
|
|
return value. The store is not accessible outside of the callback function or
|
|
|
|
the asynchronous operations created within the callback.
|
|
|
|
|
|
|
|
Optionally, arguments can be passed to the function. They will be passed to
|
|
|
|
the callback function.
|
|
|
|
|
2020-03-14 07:06:06 +01:00
|
|
|
If the callback function throws an error, it will be thrown by `run` too.
|
|
|
|
The stacktrace will not be impacted by this call and the context will
|
|
|
|
be exited.
|
2019-03-01 21:31:36 +01:00
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
```js
|
2020-02-24 11:00:59 +01:00
|
|
|
const store = { id: 2 };
|
2019-03-01 21:31:36 +01:00
|
|
|
try {
|
2020-03-14 07:06:06 +01:00
|
|
|
asyncLocalStorage.run(store, () => {
|
2020-02-24 11:00:59 +01:00
|
|
|
asyncLocalStorage.getStore(); // Returns the store object
|
2019-03-01 21:31:36 +01:00
|
|
|
throw new Error();
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
asyncLocalStorage.getStore(); // Returns undefined
|
|
|
|
// The error will be caught here
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-03-14 07:06:06 +01:00
|
|
|
### `asyncLocalStorage.exit(callback[, ...args])`
|
2019-03-01 21:31:36 +01:00
|
|
|
<!-- YAML
|
2020-03-01 00:28:30 +01:00
|
|
|
added: v13.10.0
|
2019-03-01 21:31:36 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
* `callback` {Function}
|
|
|
|
* `...args` {any}
|
|
|
|
|
|
|
|
This methods runs a function synchronously outside of a context and return its
|
|
|
|
return value. The store is not accessible within the callback function or
|
|
|
|
the asynchronous operations created within the callback.
|
|
|
|
|
|
|
|
Optionally, arguments can be passed to the function. They will be passed to
|
|
|
|
the callback function.
|
|
|
|
|
2020-03-14 07:06:06 +01:00
|
|
|
If the callback function throws an error, it will be thrown by `exit` too.
|
|
|
|
The stacktrace will not be impacted by this call and
|
2019-03-01 21:31:36 +01:00
|
|
|
the context will be re-entered.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
```js
|
2020-03-14 07:06:06 +01:00
|
|
|
// Within a call to run
|
2019-03-01 21:31:36 +01:00
|
|
|
try {
|
2020-02-24 11:00:59 +01:00
|
|
|
asyncLocalStorage.getStore(); // Returns the store object or value
|
2020-03-14 07:06:06 +01:00
|
|
|
asyncLocalStorage.exit(() => {
|
2019-03-01 21:31:36 +01:00
|
|
|
asyncLocalStorage.getStore(); // Returns undefined
|
|
|
|
throw new Error();
|
|
|
|
});
|
|
|
|
} catch (e) {
|
2020-02-24 11:00:59 +01:00
|
|
|
asyncLocalStorage.getStore(); // Returns the same object or value
|
2019-03-01 21:31:36 +01:00
|
|
|
// The error will be caught here
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-03-14 07:06:06 +01:00
|
|
|
### Usage with `async/await`
|
2019-03-01 21:31:36 +01:00
|
|
|
|
|
|
|
If, within an async function, only one `await` call is to run within a context,
|
|
|
|
the following pattern should be used:
|
|
|
|
|
|
|
|
```js
|
|
|
|
async function fn() {
|
2020-03-14 07:06:06 +01:00
|
|
|
await asyncLocalStorage.run(new Map(), () => {
|
2019-03-01 21:31:36 +01:00
|
|
|
asyncLocalStorage.getStore().set('key', value);
|
|
|
|
return foo(); // The return value of foo will be awaited
|
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
In this example, the store is only available in the callback function and the
|
2020-03-14 07:06:06 +01:00
|
|
|
functions called by `foo`. Outside of `run`, calling `getStore` will return
|
|
|
|
`undefined`.
|
2019-03-01 21:31:36 +01:00
|
|
|
|
2017-08-30 23:45:21 +02:00
|
|
|
[`after` callback]: #async_hooks_after_asyncid
|
|
|
|
[`before` callback]: #async_hooks_before_asyncid
|
2017-10-21 04:16:23 +02:00
|
|
|
[`destroy` callback]: #async_hooks_destroy_asyncid
|
2017-08-30 23:45:21 +02:00
|
|
|
[`init` callback]: #async_hooks_init_asyncid_type_triggerasyncid_resource
|
2019-09-02 10:31:27 +02:00
|
|
|
[`promiseResolve` callback]: #async_hooks_promiseresolve_asyncid
|
2017-10-14 16:08:22 +02:00
|
|
|
[Hook Callbacks]: #async_hooks_hook_callbacks
|
2018-07-14 14:10:10 +02:00
|
|
|
[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
|
2018-06-01 15:13:43 +02:00
|
|
|
[`Worker`]: worker_threads.html#worker_threads_class_worker
|
2018-11-27 20:49:21 +01:00
|
|
|
[promise execution tracking]: #async_hooks_promise_execution_tracking
|