puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Can't make it work with HAPI #55

Closed QuentinFarizon closed 2 years ago

QuentinFarizon commented 3 years ago

Hello, I can't make it work with HAPI (version 20).

I'm following the documentation :

const server: Server = hapiServer({
    host,
    (...)
})

await server.register({
  plugin: rTracer.hapiPlugin
})    

 (other plugins, routes, ...)

And in a route :

handler: (request: Request, h: ResponseToolkit) => {
  const requestId = rTracer.id()
  console.log(`requestId: ${requestId}`)

rTracer.id() always returns undefined

By debugging in rtracer.js, I can see that I enter als.enterWith with a generated id, but when the route handler is called als.getStore() alwasy returns undefined

What am I missing ?

puzpuzpuz commented 3 years ago

The following minimal snippet seems to work fine for me with Hapi 20.2.0 and Node.js v14.17.6:

'use strict';

const Hapi = require('@hapi/hapi');
const rTracer = require('cls-rtracer');

const init = async () => {
    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });
    await server.register({
        plugin: rTracer.hapiPlugin
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            const id = rTracer.id()
            return { id };
        }
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

Could you try it yourself?

QuentinFarizon commented 3 years ago

Thanks for your quick reply !

Your sample works, so I will have to disable other plugins and routes to find what's the issue

puzpuzpuz commented 3 years ago

Yes, other plugins may lead to context loss. It makes sense to enable them one by one until you find the problematic one.

QuentinFarizon commented 3 years ago

Turns out it was https://www.npmjs.com/package/hapi-require-https

puzpuzpuz commented 3 years ago

If you were registering that plugin after cls-rtracer, moving it up may fix the issue. If it's already registered before cls-rtracer, I'm afraid that the only way would be to debug it (or replace it with another similar plugin, if any exist).

puzpuzpuz commented 2 years ago

Closing this one as the reason was found.