@fibery/correlation-id

中文文档
5.0.1发布于 2024/01/15MITTypeScriptESM + CJS零依赖近 30 天下载 2782

Correlation id helper based on async local storage

原始使用文档
文档目录5 节
  1. How to use
  2. Settings
  3. Correlation ID API
  4. Known issues after 5.0.0
  5. Known issues 4.3.0.

Correlation Id

How to use

Create correlation id instance

import {createCorrelationId} from '@vizydrop/correlation-id';
const correlationId = createCorrelationId();

Integrate with @fibery/vizydrop-logger

const {createLogger} = require(`@fibery/vizydrop-logger`);

const logger = createLogger({
    correlationId: {
        enabled: true,
        getCorrelationId: () => correlationId.correlator.getId(),
        emptyValue: `nocorrelation`,
    },
});

Register middleware. Support koa and express

// koa
app.use(correlationId.koaMiddleware);
// express
app.use(correlationId.expressMiddleware);

Enhance request so each request will contain correlation id http header.

const request = require(`request`);
const correlatedRequest = correlationId.enhanceRequest(request);
correlatedRequest.get(`http://anotherservice:10020/data`);

Enhance http proxy so each proxied request will contain correlation id http header.

const httpProxy = require(`http-proxy`);
const proxy = httpProxy.createProxyServer({
    target: `http://anotherservice:10020/`,
});
correlationId.enhanceHttpProxy(proxy);

Run jobs. Jobs usually do not go through express/koa middleware so correlation id should be generated manually.

function jobTask() {}

function runJob() {
    correlationId.correlator.withId(correlator.generateDefaultId(), () => {
        jobTask();
    });
}

Settings

Custom settings can be passed as an object to createCorrelationId function.

  • generateDefaultId - function that should return new correlation id. By default crypto.randomUUID is used.

Correlation ID API

  • expressMiddleware - express middleware that runs next middlewares in scope of correlation id async hook
  • koaMiddleware - koa middleware that runs next middlewares in scope of correlation id async hook
  • enhanceHttpRequest - takes request and return new request instance that adds correlation id header by default
  • enhanceHttpProxy - register additional listener that adds correlation id header by default
  • correlator.getId() - returns current correlation id
  • correlator.withId(id, fn) - run function and all subsequent function with specified correlation id
  • correlator.bind() - binds provided function to current execution context. Actually now it's a simple alias to AsyncResource.bind https://nodejs.org/api/async_context.html#integrating-asyncresource-with-eventemitter
  • correlator.generateId() - generates new correlation id

Known issues after 5.0.0

Since bindEmitter method was removed and we don't bind req in express and koa middlewares there might be some edge cases where correlation-id gets lost. According to the https://github.com/nodejs/node/issues/33723 it's not recommended to bind whole emitter as execution in different context might be intentional so packages should maintain correct async context on their side. And it was actually fixed in many packages like express.js, body-parser, on-finished, fastify and etc. In most cases where it's still a problem this can be worked around with correlator.bind (see https://nodejs.org/api/async_context.html#integrating-asyncresource-with-eventemitter). Following example shows how to workaround this for dead koa-morgan package:

<!-- WAS -->
app.use(morgan(
    `:method :status :url (:res[content-length] bytes) :response-time ms`,
    {
        stream: {
            write: (text) => logger.info(text.trim()), // no correlation id here, context is lost
        },
        immediate: false,
    },
));

<!-- Should become -->
app.use(async (ctx, next) => {
    await morgan(
        `:method :status :url (:res[content-length] bytes) :response-time ms`,
        {
            stream: {
                write: correlator.bind((text) => logger.info(text.trim())), // correlation-id is here as we bound the callback to current async context
            },
            immediate: false,
        },
    )(ctx, next);
});

Known issues 4.3.0.

  • does not work well with bluebird.promisifyAll. Alternative solution is to explicitly promisify using native promise
const redis = require(`redis`);
const util = require(`util`);

const client = redis.createClient();

client.setAsync = util.promisify(client.set).bind(client);
client.getAsync = util.promisify(client.get).bind(client);
  • does not work well with mongoose callbacks. Alternative solution is to use promisified functions.
const mongoose = require(`mongooose`);
mongoose.Promise = global.Promise;

EntityModel.find({name: `name`}).then((value) => {
    // do something
});

版本与发布记录

@fibery/correlation-id 共发布 13 个版本,首次发布于 2020/12/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
5.0.1latest2024/01/152 年前
5.0.02024/01/152 年前
4.3.02023/09/043 年前
4.2.42023/09/043 年前
4.2.32023/09/043 年前
4.2.22023/07/043 年前

关于 @fibery/correlation-id 的常见问题

@fibery/correlation-id 是什么?

Correlation id helper based on async local storage

如何安装 @fibery/correlation-id?

在项目目录运行 npm install @fibery/correlation-id,或使用 pnpm add / yarn add / bun add。

@fibery/correlation-id 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fibery/correlation-id 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@fibery/correlation-id 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.4。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@fibery/correlation-id 可以商用吗?

@fibery/correlation-id 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fibery/correlation-id 的下载量有多少?

根据 npm 官方下载统计,@fibery/correlation-id 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,782 次,日均约 93 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fibery/correlation-id 还在维护吗?

最新版本 5.0.1 发布于 2024/01/15(2 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/12/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。