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

Why does the Hapi plugin implementation use enterWith() instead of run()? #58

Closed ao10 closed 2 years ago

ao10 commented 2 years ago

Hi, I had a question on the implementation for the Hapi plugin. I noticed that for the rest of the other framework middleware/plugins you use AsyncLocalStorage.run() but for the Hapi plugin enterWith() is used instead? Why is that and what is it about Hapi specifically that it had to be done this way?

From the Node docs

run() should be preferred over enterWith() unless there are strong reasons to use the latter method.

https://nodejs.org/api/async_context.html#asynclocalstorageenterwithstore

Thank you

puzpuzpuz commented 2 years ago

Hello,

That's because of the plugin API provided by Hapi in the form of multiple hooks. There is simply no single place where you could run ALS.run() (or, at least, that's how it used to be at the time when I was writing that code), so that's why cls-rtracer uses a low-level, less safe ALS API.

BTW Koa v1 middleware also uses ALS.enterWith(): https://github.com/puzpuzpuz/cls-rtracer/blob/2745858bc2728d6c54cd05afd36d4be3c357a8f6/src/rtracer.js#L166-L191

The reason for Koa v1 is different - it uses generators.

puzpuzpuz commented 2 years ago

Hopefully the above reply answers your question. Closing this one for now.

ao10 commented 2 years ago

Thank you!