NestJS中文文档
实战配方 / 异步本地存储
已译 191/191

异步本地存储

AsyncLocalStorage 是一个 Node.js API(基于 async_hooks API),它提供了一种替代方式,无需把本地状态作为函数参数显式传递,就能在应用中传播它。它类似于其他语言中的线程本地存储。

异步本地存储的核心思想是:你可以用 AsyncLocalStorage#run 调用把一次函数调用 包裹 起来。被包裹的调用内部所执行的全部代码都能访问同一个 store,而该 store 对每条调用链都是唯一的。

在 NestJS 的语境下,这意味着如果你能在请求生命周期的某个位置把请求剩余的代码包裹起来,就可以访问并修改只对该请求可见的状态。这可以作为请求作用域提供者的替代方案,避开它们的一些限制。

另一种做法是,你可以只用 ALS 为系统的一部分(例如 事务 对象)传播上下文,而不必在各服务间显式地传来传去,这能提升隔离性与封装性。

如果你的应用已经用 NestJS Observe 做了仪器化,你就已经拥有请求作用域的 store,无需自行构建。请参见下面的 NestJS Observe 一节。

自定义实现

NestJS 核心框架没有为 AsyncLocalStorage 提供内置抽象,因此我们以最简单的 HTTP 场景为例,走一遍自己实现它的过程,以便更好地理解整个概念:

提示

现成的方案请参见下面的 @nestjs/observe 与 nestjs-cls 两节。

  1. 首先,在一个共享的源文件中创建 AsyncLocalStorage 的新实例。既然我们用 NestJS,也顺便把它做成一个带自定义提供者的模块。
als.module.ts
@Module({
  providers: [
    {
      provide: AsyncLocalStorage,
      useValue: new AsyncLocalStorage(),
    },
  ],
  exports: [AsyncLocalStorage],
})
export class AlsModule {}
提示

AsyncLocalStorage 从 node:async_hooks 导入。

  1. 我们只关心 HTTP,所以用一个中间件,把 next 函数用 AsyncLocalStorage#run 包裹起来。由于中间件是请求最先到达的地方,这样做能让 store 在所有增强器以及系统的其余部分中可用。
app.module.ts
@Module({
  imports: [AlsModule],
  providers: [CatsService],
  controllers: [CatsController],
})
export class AppModule implements NestModule {
  constructor(
    // 在模块构造函数中注入 AsyncLocalStorage,
    private readonly als: AsyncLocalStorage
  ) {}

  configure(consumer: MiddlewareConsumer) {
    // 绑定中间件,
    consumer
      .apply((req, res, next) => {
        // 根据请求填充一些 store 的默认值,
        const store = {
          userId: req.headers['x-user-id'],
        };
        // 并把 "next" 函数作为回调,
        // 连同 store 一起传给 "als.run" 方法。
        this.als.run(store, () => next());
      })
      .forRoutes('*path');
  }
}
@Module({
  imports: [AlsModule],
  providers: [CatsService],
  controllers: [CatsController],
})
@Dependencies(AsyncLocalStorage)
export class AppModule {
  constructor(als) {
    // inject the AsyncLocalStorage in the module constructor,
    this.als = als;
  }

  configure(consumer) {
    // bind the middleware,
    consumer
      .apply((req, res, next) => {
        // populate the store with some default values
        // based on the request,
        const store = {
          userId: req.headers['x-user-id'],
        };
        // and pass the "next" function as callback
        // to the "als.run" method together with the store.
        this.als.run(store, () => next());
      })
      .forRoutes('*path');
  }
}
  1. 现在你可以在请求生命周期内的任何位置访问这个本地 store 实例。
cats.service.ts
@Injectable()
export class CatsService {
  constructor(
    // 我们可以注入所提供的 ALS 实例。
    private readonly als: AsyncLocalStorage,
    private readonly catsRepository: CatsRepository,
  ) {}

  getCatForUser() {
    // "getStore" 方法始终会返回
    // 与给定请求关联的 store 实例。
    const userId = this.als.getStore()["userId"] as number;
    return this.catsRepository.getForUser(userId);
  }
}
@Injectable()
@Dependencies(AsyncLocalStorage, CatsRepository)
export class CatsService {
  constructor(als, catsRepository) {
    // We can inject the provided ALS instance.
    this.als = als;
    this.catsRepository = catsRepository;
  }

  getCatForUser() {
    // The "getStore" method will always return the
    // store instance associated with the given request.
    const userId = this.als.getStore()["userId"];
    return this.catsRepository.getForUser(userId);
  }
}
  1. 现在你有了一种共享请求相关状态的方式,无需注入整个 REQUEST 对象。
警告

尽管这一技巧在许多场景下都很有用,但它天然会模糊代码流程(因为创建了隐式上下文),所以请负责任地使用,尤其要避免创建上下文式的「上帝对象」。

NestJS Observe

如果你运行 NestJS Observe,@nestjs/observe SDK 已经为其仪器化的每个请求、任务和消息维护了一个 AsyncLocalStorage store。这个 store 会把追踪上下文贯穿你的调用栈。TracerService 将它暴露出来,因此请求作用域的状态变成了你读写的东西,而不是你需要搭起来的东西:不用写模块、不用挂载中间件,也不必为每种传输重新接线。

提示

这就是手动仪器化中所记录的那个 TracerService。本节只讲它在异步本地存储这一面的能力;span、已处理的错误与自定义指标在那里描述。

设置

除可观测性 → SDK中描述的标准 SDK 集成之外,无需任何额外设置:安装该包,导入 ObserveModule.forRoot(),并把 ObserveInstrument 传给 NestFactory.create()。

$ npm i @nestjs/observe

ObserveModule 会导出 TracerService,因此你可以在应用中的任何位置注入它:

cats.service.ts
import { Injectable } from '@nestjs/common';
import { TracerService } from '@nestjs/observe';

@Injectable()
export class CatsService {
  constructor(private readonly tracerService: TracerService) {}
}

读写 store

setAttribute(key, value) 写入当前上下文的 store,而 getAttribute(key) 可以从同一请求下游的任何位置(另一个服务、守卫或拦截器)读回该值,无需把它贯穿每个函数签名:

cats.controller.ts
@Get()
findAll(@Req() req: Request) {
  this.tracerService.setAttribute('userId', req.headers['x-user-id']);
  return this.catsService.getCatForUser();
}
cats.service.ts
@Injectable()
export class CatsService {
  constructor(
    private readonly tracerService: TracerService,
    private readonly catsRepository: CatsRepository,
  ) {}

  getCatForUser() {
    const userId = this.tracerService.getAttribute('userId');
    return this.catsRepository.getForUser(userId);
  }
}

getAttribute() 对从未设置过的键返回 undefined。在追踪上下文之外调用这两个方法都会抛错,因为没有 store 可供读取或写入。如果某个值可能在任何请求出现之前就被合法读取,请对该调用做相应的守卫。

为 store 指定类型

把 store 的形状作为 TracerService 的第一个类型参数传入,就能对键和值做类型检查,嵌套路径也包括在内:

interface RequestStore {
  userId: number;
  flags: { betaCheckout: boolean };
}

@Injectable()
export class CatsService {
  constructor(private readonly tracerService: TracerService<RequestStore>) {}

  enableBeta() {
    this.tracerService.setAttribute('flags.betaCheckout', true);
  }
}

超越 HTTP

因为 store 是由仪器化而非中间件创建的,所以只要 SDK 追踪某个操作,store 就存在:HTTP 与 GraphQL 请求,gRPC 与 @nestjs/microservices 消息,以及 BullMQ 消费者、cron 运行之类的后台工作。上面的模式在所有这些场景中完全一致。这正是它与手写的、基于中间件的实现之间的实际差别——后者只覆盖 HTTP。

该 store 还保存着当前的 trace ID,因此它同时充当日志与下游服务的关联键。currentTraceId() 会返回它。与 getAttribute() 不同,在追踪上下文之外它返回 null,而不是抛错:

const traceId = this.tracerService.currentTraceId();
提示

ObserveModule 还会导出底层的 AsyncLocalStorage 实例。setAttribute() 与 getAttribute() 是访问 store 的受支持方式;只有当你需要它们没有暴露的能力时,才直接注入该实例。

NestJS CLS

nestjs-cls 包在纯 AsyncLocalStorage 之上提供了若干开发者体验上的改进(CLS 是 continuation-local storage 的缩写)。它把实现抽象成 ClsModule,提供多种为不同传输(不止 HTTP)初始化 store 的方式,并带来强类型支持。

随后你可以用可注入的 ClsService 访问 store,或者通过代理提供者把它完全从业务逻辑中抽象出去。

注意

nestjs-cls 是第三方包,不由 NestJS 核心团队维护。该库的任何问题请到 nestjs-cls 仓库反馈。

安装

除了对 @nestjs 系列包的同级依赖之外,它只使用 Node.js 的内置 API。像安装其他任何包一样安装它:

$ npm i nestjs-cls

用法

你可以用 nestjs-cls 实现与上面自定义实现类似的功能,如下所示:

  1. 在根模块中导入 ClsModule。
app.module.ts
@Module({
  imports: [
    // 注册 ClsModule,
    ClsModule.forRoot({
      middleware: {
        // 自动为所有路由挂载
        // ClsMiddleware
        mount: true,
        // 并用 setup 方法
        // 提供默认的 store 值。
        setup: (cls, req) => {
          cls.set('userId', req.headers['x-user-id']);
        },
      },
    }),
  ],
  providers: [CatsService],
  controllers: [CatsController],
})
export class AppModule {}
  1. 然后用 ClsService 访问 store 中的值。
cats.service.ts
@Injectable()
export class CatsService {
  constructor(
    // 我们可以注入所提供的 ClsService 实例,
    private readonly cls: ClsService,
    private readonly catsRepository: CatsRepository,
  ) {}

  getCatForUser() {
    // 并用 "get" 方法取出任何已存储的值。
    const userId = this.cls.get('userId');
    return this.catsRepository.getForUser(userId);
  }
}
@Injectable()
@Dependencies(ClsService, CatsRepository)
export class CatsService {
  constructor(cls, catsRepository) {
    // We can inject the provided ClsService instance,
    this.cls = cls;
    this.catsRepository = catsRepository;
  }

  getCatForUser() {
    // and use the "get" method to retrieve any stored value.
    const userId = this.cls.get('userId');
    return this.catsRepository.getForUser(userId);
  }
}
  1. 要对 ClsService 所管理的 store 值获得强类型(以及字符串键的自动提示),请在注入时使用可选的类型参数 ClsService<MyClsStore>。
export interface MyClsStore extends ClsStore {
  userId: number;
}
提示

你也可以让该包自动生成请求 ID,之后用 cls.getId() 访问它,或者用 cls.get(CLS_REQ) 取得整个请求对象。

测试

由于 ClsService 只是另一个可注入的提供者,你完全可以在单元测试中把它 mock 掉。

不过,在某些集成测试中,你可能仍想使用真实的 ClsService 实现。这种情况下,请用 ClsService#run 或 ClsService#runWith 把依赖上下文的代码包裹起来:

describe('CatsService', () => {
  let service: CatsService
  let cls: ClsService
  const mockCatsRepository = createMock<CatsRepository>()

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      // 像平常一样配置测试模块的大部分内容。
      providers: [
        CatsService,
        {
          provide: CatsRepository,
          useValue: mockCatsRepository,
        }
      ],
      imports: [
        // 导入 ClsModule 的静态版本,它只提供
        // ClsService,但不会以任何方式设置 store。
        ClsModule
      ],
    }).compile()

    service = module.get(CatsService)

    // 同时取出 ClsService 以便后续使用。
    cls = module.get(ClsService)
  })

  describe('getCatForUser', () => {
    it('retrieves cat based on user id', async () => {
      const expectedUserId = 42
      mockCatsRepository.getForUser.mockImplementationOnce(
        (id) => ({ userId: id })
      )

      // 把测试调用包在 `runWith` 方法中,
      // 这样我们就可以传入手工构造的 store 值。
      const cat = await cls.runWith(
        { userId: expectedUserId },
        () => service.getCatForUser()
      )

      expect(cat.userId).toEqual(expectedUserId)
    })
  })
})

更多信息

访问 nestjs-cls GitHub 页面,获取完整的 API 文档与更多代码示例。