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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fibery/correlation-id

v5.0.1

Published

Correlation id helper based on async local storage

Downloads

1,105

Readme

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