npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lark-apaas/nestjs-observable

v0.0.5

Published

NestJS integration for Observable SDK

Readme

@lark-apaas/nestjs-observable

面向 NestJS 的 Observable SDK 集成,提供可注入的 Observable 服务、自动链路追踪拦截器,以及请求级 Root Span 中间件,便于在应用内统一记录日志与链路数据并自动透传请求上下文。

1. Project Context (项目背景与定位)

Architectural Role: Core (核心底层)

NestJS Observable 是一个核心底层库,为整个 Lark Apaas 服务端生态提供统一的可观测性能力,包括日志记录和链路追踪。

Key Consumers (谁在用我)

  • 📱 @lark-apaas/fullstack-nestjs-core:平台核心模块,集成了该库作为底层可观测性基础
  • 📝 @lark-apaas/nestjs-logger:日志模块,基于该库实现可观测性日志功能

Core Dependencies (我依赖谁)

  • 🔧 @lark-apaas/nestjs-common:提供请求上下文服务和基础接口定义
  • 📊 @lark-apaas/observable:底层可观测性 SDK,提供实际的日志和链路功能

2. Real-world Scenarios (基于真实挖掘)

Scenario A: The Standard Usage

说明: 在应用中集成和使用 Observable 服务的标准方式(参考自 @lark-apaas/nestjs-logger

import { Module } from '@nestjs/common';
import { NestjsObservableModule, Observable } from '@lark-apaas/nestjs-observable';
import { RequestContextService, OBSERVABLE_SERVICE, CommonModule, ObservableService } from '@lark-apaas/nestjs-common';

@Module({
  imports: [CommonModule, NestjsObservableModule],
  providers: [
    {
      provide: OBSERVABLE_SERVICE,
      useFactory: (observable: ObservableService | null, rtx: RequestContextService) => {
        return observable ?? new Observable(rtx);
      },
      inject: [{
        token: OBSERVABLE_SERVICE,
        optional: true,
      }, RequestContextService],
    },
  ],
})
export class AppModule {}

Scenario B: Integration Example

说明: 在完整的 NestJS 应用中集成所有可观测性功能(参考自 @lark-apaas/fullstack-nestjs-core

import { DynamicModule, Global, Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { CommonModule, OBSERVABLE_SERVICE } from '@lark-apaas/nestjs-common';
import { NestjsObservableModule, Observable, ObservableTraceMiddleware, TraceInterceptor } from '@lark-apaas/nestjs-observable';

@Global()
@Module({})
export class PlatformModule implements NestModule {
  static forRoot(options = {}): DynamicModule {
    return {
      module: PlatformModule,
      imports: [
        CommonModule,
        ObservableModule, // 引入 Observable 模块
      ],
      providers: [
        {
          provide: OBSERVABLE_SERVICE,
          useClass: Observable, // 提供可注入的 Observable 服务
        },
        {
          provide: APP_INTERCEPTOR,
          useClass: TraceInterceptor, // 全局应用自动链路追踪拦截器
        }
      ],
      exports: [OBSERVABLE_SERVICE]
    };
  }

  // 配置中间件
  configure(consumer: MiddlewareConsumer) {
    // 应用请求级 Root Span 中间件
    consumer
      .apply(
        ObservableTraceMiddleware // 应用 Observable 跟踪中间件
      )
      .forRoutes('/*');
  }
}

业务服务中使用示例:

import { Injectable } from '@nestjs/common';
import { Observable } from '@lark-apaas/nestjs-observable';

@Injectable()
export class DemoService {
  constructor(private readonly observable: Observable) {}

  async doWork(): Promise<boolean> {
    // 记录日志,自动包含上下文信息
    this.observable.log('info', '任务开始', { module: 'demo' });
    
    // 在链路中执行业务逻辑
    return this.observable.trace('doWork', async (span) => {
      // 业务逻辑
      this.observable.log('info', '任务进行中', { step: 'processing' });
      
      // 记录链路属性
      span.setAttributes({ processing_step: 'completed' });
      
      return true;
    });
  }
}

3. API Reference

Core Exports

| 导出项 | 类型 | 说明 | |--------|------|------| | NestjsObservableModule | NestJS Module | 全局模块,自动启动底层 SDK | | Observable | Injectable Class | 可注入的 Observable 服务,提供日志和链路功能 | | ObservableTraceMiddleware | NestJS Middleware | 请求级 Root Span 中间件,自动创建和管理链路上下文 | | TraceInterceptor | NestJS Interceptor | 自动链路追踪拦截器,基于元数据自动为方法创建子链路 |

Observable Service API

log(level: string, message: string, attributes?: Record<string, unknown>): void

  • 记录日志,自动合并平台默认属性和请求上下文属性(user_id, tenant_id, app_id)
  • 参数:
    • level: 日志级别(如 'info', 'error')
    • message: 日志消息内容
    • attributes: 自定义属性(可选)

trace<T>(name: string, fn: (span: Span) => T | Promise<T> | Observable<T>): T | Promise<T> | Observable<T>

  • 在指定名称的链路中执行函数,自动设置默认和上下文属性
  • 参数:
    • name: 链路名称
    • fn: 要执行的函数,接收 span 对象作为参数
  • 返回值:函数执行结果,支持同步、Promise 和 RxJS Observable

flush(): Promise<void>

  • 主动刷新缓冲,在 FaaS 或短生命周期场景下使用更安全

Configuration

该库无需额外配置,会自动使用底层 @lark-apaas/observable SDK 的配置。主要依赖请求上下文服务 RequestContextService 来获取用户、租户和应用信息。

4. Middleware & Interceptor Behavior

ObservableTraceMiddleware

  • 根据请求 methodpath 自动命名 Root Span
  • 从请求上下文获取用户信息并添加到链路属性
  • 响应完成时自动设置 HTTP 状态码和 Span 状态(5xx 为 ERROR,4xx 为 UNSET,其他为 OK)
  • 自动结束 Span 并刷新缓冲

TraceInterceptor

  • 读取处理器元数据键 AUTO_TRACE(来自 @lark-apaas/nestjs-common
  • 存在时使用其值作为追踪名,否则采用处理器方法名
  • 通过 Observable.trace() 包裹后续执行,实现自动链路追踪

5. Installation

npm install @lark-apaas/nestjs-observable

需要 @nestjs/common@nestjs/core 作为 peer 依赖。

License

MIT