On this page

async_context 异步上下文跟踪

History
Source Code: lib/async_hooks.js

稳定性:2 - 稳定

这些类用于关联状态,并在 回调和 promise 链中传播该状态。 它们允许在 Web 请求的整个生命周期中 或任何其他异步期间存储数据。这类似于其他语言中的 线程局部存储。

AsyncLocalStorage 和 AsyncResource 类是 node:async_hooks 模块的一部分:

此类创建的存储在异步操作期间保持一致。

虽然可以在 node:async_hooks 模块之上自行实现,但应优先使用 AsyncLocalStorage,因为它是性能和内存安全的实现, 其中包含大量不易 自行实现的优化。

下面的示例使用 AsyncLocalStorage 构建一个简单的日志记录器, 它为传入的 HTTP 请求分配 ID,并将其包含在 该请求内记录的日志消息中。

import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // 在此想象任意的异步操作链
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// 打印:
//   0: start
//   0: finish
//   1: start
//   1: finish

每个 AsyncLocalStorage 实例都维护独立的存储上下文。 多个实例可以安全地同时存在,不会干扰 彼此的数据。

new AsyncLocalStorage(options?): void
Attributes
options:<Object>
defaultValue:<any>
未提供存储时使用的值。
AsyncLocalStorage 值的名称。

创建一个新的 AsyncLocalStorage 实例。只有在 run() 调用中或 调用 enterWith() 之后才会提供存储。

Attributes
要绑定到当前执行上下文的函数。

将给定函数绑定到当前执行上下文。

  • 返回:<Function> 一个签名为 (fn: (...args) : R, ...args) : R 的新函数。

捕获当前执行上下文并返回一个接受函数作为参数的函数。 每当调用返回的函数时,它都会在捕获的上下文中 调用传给它的函数。

const asyncLocalStorage = new AsyncLocalStorage();
const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
console.log(result);  // returns 123

对于简单的异步上下文跟踪用途,AsyncLocalStorage.snapshot() 可以替代 AsyncResource 的使用,例如:

class Foo {
  #runInAsyncScope = AsyncLocalStorage.snapshot();

  get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
}

const foo = asyncLocalStorage.run(123, () => new Foo());
console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
M

asyncLocalStorage.disable

History
asyncLocalStorage.disable(): void

稳定性:1 - 实验性

禁用 AsyncLocalStorage 实例。此后所有对 asyncLocalStorage.getStore() 的调用都将返回 undefined,直到 再次调用 asyncLocalStorage.run() 或 asyncLocalStorage.enterWith()。

调用 asyncLocalStorage.disable() 时,将退出与该实例关联的所有 当前上下文。

在 asyncLocalStorage 可被垃圾回收之前,必须调用 asyncLocalStorage.disable()。这不适用于由 asyncLocalStorage 提供的存储, 因为这些对象会与相应的异步资源一起被 垃圾回收。

当当前进程中不再使用 asyncLocalStorage 时, 请使用此方法。

M

asyncLocalStorage.getStore

History
asyncLocalStorage.getStore(): void

返回当前存储。 如果在未通过调用 asyncLocalStorage.run() 或 asyncLocalStorage.enterWith() 初始化的异步上下文之外调用,则 返回 undefined。

M

asyncLocalStorage.enterWith

History
asyncLocalStorage.enterWith(store): void

稳定性:1 - 实验性

Attributes
store:<any>

在当前同步执行的剩余部分切换到该上下文,然后在随后的 任何异步调用中保持该 存储。

示例:

const store = { id: 1 };
// 用给定的 store 对象替换之前的存储
asyncLocalStorage.enterWith(store);
asyncLocalStorage.getStore(); // Returns the store object
someAsyncOperation(() => {
  asyncLocalStorage.getStore(); // Returns the same object
});

此切换会在_整个_同步执行期间持续。 这意味着,例如,如果在事件处理程序中进入该上下文, 后续事件处理程序也将在该上下文中运行,除非 使用 AsyncResource 明确绑定到另一个上下文。因此,除非有充分理由 使用后一种方法,否则应优先使用 run() 而不是 enterWith()。

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
P

asyncLocalStorage.name

History

如果提供了名称,则为 AsyncLocalStorage 实例的名称。

M

asyncLocalStorage.run

History
asyncLocalStorage.run(store, callback, ...args?): void
Attributes
store:<any>
callback:<Function>
...args:<any>

在上下文中同步运行一个函数并返回其 返回值。在回调函数之外无法访问该存储。 在回调中创建的任何异步操作都可以访问 该存储。

可选的 args 会传递给回调函数。

如果回调函数抛出错误,则该错误也会由 run() 抛出。 堆栈跟踪不受此调用影响,并且上下文会退出。

示例:

const store = { id: 2 };
try {
  asyncLocalStorage.run(store, () => {
    asyncLocalStorage.getStore(); // Returns the store object
    setTimeout(() => {
      asyncLocalStorage.getStore(); // Returns the store object
    }, 200);
    throw new Error();
  });
} catch (e) {
  asyncLocalStorage.getStore(); // Returns undefined
  // 将在此捕获错误
}
M

asyncLocalStorage.exit

History
asyncLocalStorage.exit(callback, ...args?): void

稳定性:1 - 实验性

Attributes
callback:<Function>
...args:<any>

在上下文之外同步运行一个函数并返回其 返回值。回调函数中或回调中创建的异步操作内 都无法访问该存储。在回调函数中调用任何 getStore() 都将始终返回 undefined。

可选的 args 会传递给回调函数。

如果回调函数抛出错误,则该错误也会由 exit() 抛出。 堆栈跟踪不受此调用影响,并且会重新进入上下文。

示例:

// 在 `run` 调用中
try {
  asyncLocalStorage.getStore(); // Returns the store object or value
  asyncLocalStorage.exit(() => {
    asyncLocalStorage.getStore(); // Returns undefined
    throw new Error();
  });
} catch (e) {
  asyncLocalStorage.getStore(); // Returns the same object or value
  // 将在此捕获错误
}
M

asyncLocalStorage.withScope

History
asyncLocalStorage.withScope(store): void

稳定性:1 - 实验性

Attributes
store:<any>

创建一个一次性作用域,它会进入给定的存储,并在该作用域释放时 自动恢复之前的存储值。此方法旨在使用 JavaScript 的显式资源管理 (using 语法)。

示例:

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

{
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
}

console.log(asyncLocalStorage.getStore()); // Prints: undefined

withScope() 方法特别适用于管理同步代码中的上下文, 在这种代码中,你希望退出代码块时恢复之前的存储值, 即使抛出了错误也是如此。

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

try {
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
  throw new Error('test');
} catch (e) {
  // 即使在出错后也会自动恢复存储
  console.log(asyncLocalStorage.getStore()); // Prints: undefined
}

重要:在异步函数中第一次 await 之前使用 withScope() 时, 请注意作用域的更改会影响调用者的上下文。异步函数的同步部分 (第一次 await 之前)在调用时立即执行,当到达第一次 await 时, 它会将 promise 返回给调用者。此时,作用域更改会在 调用者的上下文中可见,并会在后续的同步代码中持续存在,直到 其他内容更改了作用域值。对于异步操作,建议改用 run(), 它能在异步边界之间 正确隔离上下文。

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

async function example() {
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
  await someAsyncOperation(); // Function pauses here and returns promise
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
}

// 不等待 await 直接调用
example(); // Synchronous portion runs, then pauses at first await
// 在 promise 返回后,作用域 'my-store' 现在已在调用者中激活!
console.log(asyncLocalStorage.getStore()); // Prints: my-store (unexpected!)

如果在异步函数中只有一个 await 调用需要在上下文中运行, 则应使用以下模式:

async function fn() {
  await asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set('key', value);
    return foo(); // The return value of foo will be awaited
  });
}

在此示例中,存储仅在回调函数和 foo 调用的函数中可用。在 run 之外,调用 getStore 将返回 undefined。

在大多数情况下,AsyncLocalStorage 可以正常工作。在极少数情况下, 当前存储会在某个异步操作中丢失。

如果代码基于回调,只需使用 util.promisify() 将其 Promise 化, 即可使其与原生 promise 一起工作。

如果需要使用基于回调的 API,或代码假定 自定义 thenable 实现,请使用 AsyncResource 类 将异步操作与正确的执行上下文关联起来。 通过在怀疑导致丢失的调用之后记录 asyncLocalStorage.getStore() 的内容,找出导致上下文丢失的函数调用。 当代码记录 undefined 时,最后调用的回调 很可能就是导致上下文丢失的原因。

类:RunScope

History

稳定性:1 - 实验性

由 asyncLocalStorage.withScope() 返回的一次性作用域,在释放时 会自动恢复之前的存储值。此类实现 Explicit Resource Management 协议, 旨在与 JavaScript 的 using 语法一起使用。

当 using 块退出时,无论是正常完成还是抛出错误, 作用域都会自动恢复之前的存储值。

M

scope.dispose

History
scope.dispose(): void

显式结束作用域并恢复之前的存储值。此方法是 幂等的:多次调用与调用一次效果相同。

[Symbol.dispose]() 方法会转交给 dispose()。

如果调用 withScope() 时没有使用 using 关键字,则必须手动 调用 dispose() 以恢复之前的存储值。忘记调用 dispose() 将导致存储值在 当前执行上下文的剩余部分中持续存在:

import { AsyncLocalStorage } from 'node:async_hooks';

const storage = new AsyncLocalStorage();

// 不使用 using 时,必须手动释放作用域
const scope = storage.withScope('my-store');
// 此处 storage.getStore() === 'my-store'

scope.dispose(); // Restore previous value
// 此处 storage.getStore() === undefined

AsyncResource 类设计用于由嵌入方的异步 资源继承。使用它,用户可以轻松触发自己资源的 生命周期事件。

当 AsyncResource 被实例化时,将触发 init 钩子。

下面是 AsyncResource API 的概览。

import { AsyncResource, executionAsyncId } from 'node:async_hooks';

// AsyncResource() 用于被继承。实例化一个
// 新的 AsyncResource() 也会触发 init。如果省略 triggerAsyncId,则
// 使用 async_hook.executionAsyncId()。
const asyncResource = new AsyncResource(
  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
);

// 在该资源的执行上下文中运行一个函数。这将
// * 建立该资源的上下文
// * 在回调之前触发 AsyncHooks
// * 使用提供的参数调用提供的函数 `fn`
// * 在回调之后触发 AsyncHooks
// * 恢复原始执行上下文
asyncResource.runInAsyncScope(fn, thisArg, ...args);

// 调用 AsyncHooks 的 destroy 回调。
asyncResource.emitDestroy();

// 返回分配给 AsyncResource 实例的唯一 ID。
asyncResource.asyncId();

// 返回 AsyncResource 实例的触发 ID。
asyncResource.triggerAsyncId();
new AsyncResource(type, options?): void
Attributes
异步事件的类型。
options:<Object>
triggerAsyncId:<number>
创建此异步事件的执行上下文的 ID。  默认值: executionAsyncId() 。
requireManualDestroy:<boolean>
若设置为  true ,则在对象被垃圾回收时禁用 emitDestroy 。 通常无需设置此项(即使手动调用了 emitDestroy ),除非 获取了资源的 asyncId 并使用它调用了敏感 API 的 emitDestroy 。 当设置为 false 时,垃圾回收时的 emitDestroy 调用 只有在至少有一个活动的 destroy 钩子时 才会发生。 默认值: false 。

示例用法:

class DBQuery extends AsyncResource {
  constructor(db) {
    super('DBQuery');
    this.db = db;
  }

  getInfo(query, callback) {
    this.db.get(query, (err, data) => {
      this.runInAsyncScope(callback, null, err, data);
    });
  }

  close() {
    this.db = null;
    this.emitDestroy();
  }
}
Attributes
要绑定到当前执行上下文的函数。
与底层  AsyncResource 关联的 可选名称。
thisArg:<any>

将给定函数绑定到当前执行上下文。

asyncResource.bind(fn, thisArg?): void
Attributes
要绑定到当前  AsyncResource 的函数。
thisArg:<any>

将给定函数绑定为在此 AsyncResource 的作用域中执行。

M

asyncResource.runInAsyncScope

History
asyncResource.runInAsyncScope(fn, thisArg?, ...args?): void
Attributes
要在此异步资源的执行上下文中 调用的函数。
thisArg:<any>
用于函数调用的接收者。
...args:<any>
要传给函数的可选参数。

在异步资源的执行上下文中使用提供的参数调用提供的函数。 这将建立上下文,在回调之前触发 AsyncHooks, 调用函数,在回调之后触发 AsyncHooks,然后 恢复原始执行上下文。

asyncResource.emitDestroy(): void

调用所有 destroy 钩子。此方法只应调用一次。如果调用多次,将 抛出错误。此方法必须手动调用。如果 资源交由 GC 回收,则 destroy 钩子将 永远不会被调用。

asyncResource.asyncId(): void
  • 返回:<number> 分配给该资源的唯一 asyncId。
asyncResource.triggerAsyncId(): void
  • 返回:<number> 传给 AsyncResource 构造函数的同一个 triggerAsyncId。

下面的示例展示如何使用 AsyncResource 类为 Worker 池 正确提供异步跟踪。其他资源池(例如 数据库连接池)可以遵循类似的模式。

假设任务是将两个数字相加,使用一个名为 task_processor.js 的文件,其内容如下:

import { parentPort } from 'node:worker_threads';
parentPort.on('message', (task) => {
  parentPort.postMessage(task.a + task.b);
});

围绕它构建的 Worker 池可以使用以下结构:

import { AsyncResource } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import { Worker } from 'node: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.
  }
}

export default class WorkerPool extends EventEmitter {
  constructor(numThreads) {
    super();
    this.numThreads = numThreads;
    this.workers = [];
    this.freeWorkers = [];
    this.tasks = [];

    for (let i = 0; i < numThreads; i++)
      this.addNewWorker();

    // 每当 kWorkerFreedEvent 触发时,分发队列中
    // 下一个待处理任务(如果有)。
    this.on(kWorkerFreedEvent, () => {
      if (this.tasks.length > 0) {
        const { task, callback } = this.tasks.shift();
        this.runTask(task, callback);
      }
    });
  }

  addNewWorker() {
    const worker = new Worker(new URL('task_processor.js', import.meta.url));
    worker.on('message', (result) => {
      // 成功时:调用传给 `runTask` 的回调,
      // 移除与该 Worker 关联的 `TaskInfo`,并再次
      // 将其标记为空闲。
      worker[kTaskInfo].done(null, result);
      worker[kTaskInfo] = null;
      this.freeWorkers.push(worker);
      this.emit(kWorkerFreedEvent);
    });
    worker.on('error', (err) => {
      // 发生未捕获异常时:调用传给 `runTask` 的回调,
      // 并将错误传给该回调。
      if (worker[kTaskInfo])
        worker[kTaskInfo].done(err, null);
      else
        this.emit('error', err);
      // 从列表中移除该 worker 并启动一个新的 Worker 来替换
      // 当前的 Worker。
      this.workers.splice(this.workers.indexOf(worker), 1);
      this.addNewWorker();
    });
    this.workers.push(worker);
    this.freeWorkers.push(worker);
    this.emit(kWorkerFreedEvent);
  }

  runTask(task, callback) {
    if (this.freeWorkers.length === 0) {
      // 没有空闲线程,等待某个 worker 线程变为空闲。
      this.tasks.push({ 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();
  }
}

如果没有 WorkerPoolTaskInfo 对象添加的显式跟踪, 看起来这些回调是与各个 Worker 对象关联的。然而, 然而,Worker 的创建与任务的创建并无关联, 也不提供有关任务 何时被调度的信息。

该池可以按如下方式使用:

import WorkerPool from './worker_pool.js';
import os from 'node:os';

const pool = new WorkerPool(os.availableParallelism());

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();
  });
}

由 EventEmitter 触发的事件监听器可能在不同于 调用 eventEmitter.on() 时处于活动状态的执行上下文中 运行。

下面的示例展示如何使用 AsyncResource 类将事件监听器 正确地关联到相应的执行上下文。同样的 方法也适用于 Stream 或类似的事件驱动类。

import { createServer } from 'node:http';
import { AsyncResource, executionAsyncId } from 'node:async_hooks';

const server = createServer((req, res) => {
  req.on('close', AsyncResource.bind(() => {
    // 执行上下文绑定到当前外部作用域。
  }));
  req.on('close', () => {
    // 执行上下文绑定到导致 'close' 触发的作用域。
  });
  res.end();
}).listen(3000);