Correlation id helper based on async local storage
Create correlation id instance
``javascript`
import {createCorrelationId} from '@vizydrop/correlation-id';
const correlationId = createCorrelationId();
Integrate with @fibery/vizydrop-logger
`javascript@fibery/vizydrop-logger
const {createLogger} = require();
const logger = createLogger({
correlationId: {
enabled: true,
getCorrelationId: () => correlationId.correlator.getId(),
emptyValue: nocorrelation,`
},
});
Register middleware. Support koa and express
`javascript`
// koa
app.use(correlationId.koaMiddleware);
// express
app.use(correlationId.expressMiddleware);
Enhance request so each request will contain correlation id http header.
`javascriptrequest
const request = require();http://anotherservice:10020/data
const correlatedRequest = correlationId.enhanceRequest(request);
correlatedRequest.get();`
Enhance http proxy so each proxied request will contain correlation id http header.
`javascripthttp-proxy
const httpProxy = require();http://anotherservice:10020/
const proxy = httpProxy.createProxyServer({
target: ,`
});
correlationId.enhanceHttpProxy(proxy);
Run jobs. Jobs usually do not go through express/koa middleware so correlation id should be generated manually.
`javascript
function jobTask() {}
function runJob() {
correlationId.correlator.withId(correlator.generateDefaultId(), () => {
jobTask();
});
}
`
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.
- expressMiddleware - express middleware that runs next middlewares in scope of correlation id async hookkoaMiddleware
- - koa middleware that runs next middlewares in scope of correlation id async hookenhanceHttpRequest
- - takes request and return new request instance that adds correlation id header by defaultenhanceHttpProxy
- - register additional listener that adds correlation id header by defaultcorrelator.getId()
- - returns current correlation idcorrelator.withId(id, fn)
- - run function and all subsequent function with specified correlation idcorrelator.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-eventemittercorrelator.generateId()
- - generates new correlation id
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.correlator.bind
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 (see https://nodejs.org/api/async_context.html#integrating-asyncresource-with-eventemitter). Following example shows how to workaround this for dead koa-morgan package:
`:method :status :url (:res[content-length] bytes) :response-time ms
app.use(morgan(
,
{
stream: {
write: (text) => logger.info(text.trim()), // no correlation id here, context is lost
},
immediate: false,
},
));
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);
});
- does not work well with bluebird.promisifyAll. Alternative solution is to explicitly promisify using native promise
`javascriptredis
const redis = require();util
const util = require();
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.
`javascriptmongooose
const mongoose = require();
mongoose.Promise = global.Promise;
EntityModel.find({name: name}).then((value) => {``
// do something
});