fastify / fastify-request-context

Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)
MIT License
153 stars 13 forks source link

Expose API for direct access to the context #13

Closed puzpuzpuz closed 4 years ago

puzpuzpuz commented 4 years ago

🚀 Feature Proposal

Expose request context (at least the CLS part of it) as a global object instead of (or as an alternative to) asking users to access it through req/app.

Motivation

The whole purpose of any CLS is to avoid having to pass a context object through application modules. Exposing request context through the req object kinda kills the whole idea. Having it available on app makes things a bit better as it could provide isolation guarantees for multiple Fastify instances running in a single node process, but it looks like the underlying asynchronous-local-storage library has a single global AsyncLocalStorage instance, which means no isolation as such.

Example

const { ctx } = require('fastify-request-context')

// Later in route handler
const foo = ctx.get('bar')
kibertoad commented 4 years ago

Great idea! I'll add this later today.

kibertoad commented 4 years ago

@puzpuzpuz Do you think that isolation across multiple fastify instances is an important feature and access to context should be key-based, or just one instance is enough?

puzpuzpuz commented 4 years ago

In my opinion, majority of users are using a single Fastify instance per app, so a global request context should be fine for them. There might be cases when the app runs multiple Fastify instances (and thus listens on multiple ports), but those are quite rare. And even in that case each HTTP request will be associated with a different async context anyway, so things will be isolated even with the global request context approach.

kibertoad commented 4 years ago

Thanks, that makes sense!

kibertoad commented 4 years ago

Released in 2.1.0