#How to propagate nestjs-cls (CLS) context to RMQ microservice in the same app?

6 messages · Page 1 of 1 (latest)

signal garnet
#

I recently added nestjs-cls to add more info to the logs, but ideally the RMQ microservices we have would keep the CLS from where it was originally triggered through ClientProxy emit.

For reference:

`
// microservice connection setup
app.connectMicroservice({
transport: Transport.RMQ,
options: {
urls: [rabbitMqUrl],
queue: queue.name,
noAck: false,
queueOptions: {
durable: true,
prefetchCount: queue.prefetchCount,
},
},
});

// some service called through a http request
this.log('log from service. this log will show some CLS values');
this._someRmqQueue.emit(
'some-message-pattern',
{
foo: foo,
bar: bar,
},
);

// microservice controller
@MessagePattern('some-message-pattern')
async startArtworkProcessingHandler(
@Payload() payload,
@Ctx() ctx: RmqContext,
) {
// ideally this log here would still be able to access the original CLS from above
this.log('log from microservice. ideally the CLS values would be the same as in the service above.');`

I know it would be possible to just pass what I need through the payload, but ideally there would be some solution that doesn't require that manual work each time we publish a message to the queue.

Any ideas? I don't think something like nestjs-cls/transactional is needed. If somehow we can just intercept the emission, we could dynamically add it to the payload (or as a header option using RmqRecordBuilder), even.

plush surge
#

On the receiving side (message pattern), you can use an interceptor that will populate the context from the payload, but you still have to include the cls values in the payload, since the flow goes out of process.

#

So, on the emitting side, you can wrap the client proxy in a custom service which extracts the cls store and attaches them to the payload (or to the headers) of the message.

#

Keep in mind that you can only transfer cls values that are serializable this way

#

In conclusion - there is no built in solution for propagating the cls context through out-of-process calls, so you need to instrument them yourself.

signal garnet
#

yeah that's still better than doing it all the time