-
-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix context loss when async storage is instantiated early in the request lifecycle #12
Conversation
@Eomm Does the light-my-request go through the whole usual HTTP request flow with http body parser et all? I wonder if behaviour is different from what was reported in fastify/help#236 due to missing some of the steps that happen in real usage scenarios. |
lib/requestContextPlugin.js
Outdated
@@ -10,7 +10,7 @@ function plugin(fastify, opts, next) { | |||
fastify.decorate('requestContext', requestContext) | |||
fastify.decorateRequest('requestContext', requestContext) | |||
|
|||
fastify.addHook('onRequest', (req, res, done) => { | |||
fastify.addHook(opts.hook || 'onRequest', (req, res, done) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we might want to run this on multiple hooks as well, maybe it should be an array?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added, but what is the use-case for that? Why would you want to reinitialize storage on multiple steps, if just the earliest one should suffice? Also I'm thinking of switching default to preValidation
, as it seems to be logical to init it as early as possible. Thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
onRequest
happens before preValidation
.
I don't think it should be reinitialized, but probably something must be done to retain the context.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I digged deeper, and yes, we are definitely losing the context after payload parsing is triggered (as in we retain storage betwen onRequest
and preParsing
, but lose between preParsing
and preValidation
), which actually seems to be a problem that was around a while and was breaking CLS in the past as well. Still investigating what the options are.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks like a variation of nodejs/node#34401
What are we using for body parsing in fastify? some kind of custom in-house solution? is there some sort of pooling involved there?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this can be done by manually doing something inside the
'preValidation'
hook.
@puzpuzpuz do you think it would be possible to create a custom AsyncResource there and restore it in that way?
If the request object is available in all hooks, then yes, it should be possible to initialize an AsyncResource
early enough, store it in req
and then restore it where necessary and, may be, wrap next calls with asyncResource.runInAsyncScope
. This approach also requires proper integration between ALS and the AsyncResource
, but that part is trivial.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's possible, the core request is available.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@puzpuzpuz @mcollina What am I doing wrong?
function plugin(fastify, opts, next) {
fastify.decorate('requestContext', requestContext)
fastify.decorateRequest('requestContext', requestContext)
const hook = opts.hook || 'onRequest'
if (hook === 'onRequest' || hook === 'preParsing') {
fastify.addHook('preValidation', (req, res, done) => {
const asyncResource = req.asyncResource
asyncResource.runInAsyncScope(done, req)
})
}
fastify.addHook(hook, (req, res, done) => {
const asyncResource = new AsyncResource('fastify-request-context')
als.runWith(() => {
req.asyncResource = asyncResource
asyncResource.runInAsyncScope(done, req)
}, opts.defaultStoreValues)
})
next()
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kibertoad you should move AsyncResource
ctor call inside of the als.runWith
call. This way it'll be associated with the same store object (I mean the Map
object created by the als
wrapper library).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@puzpuzpuz Thanks!
@mcollina I believe PR is ready for the final rereview.
handler: endpoint, | ||
}) | ||
|
||
app.listen(8085, '0.0.0.0', (err, address) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please set 0 as the port and use app.server.address()
to get the actual port.
There is no need to use 0.0.0.0
either.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.
const { TestService } = require('./internal/testService') | ||
|
||
function initAppPostWithPrevalidation(endpoint) { | ||
return new Promise((resolve) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not wrap with a promise, use an async function. .listen()
returns a promise if a callback is not passed in.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done
let responseCounter = 0 | ||
return new Promise((resolveResponsePromise) => { | ||
const promiseRequest2 = new Promise((resolveRequest2Promise) => { | ||
const promiseRequest1 = new Promise((resolveRequest1Promise) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please use async functions instead.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are you sure that would work as expected? In this case we want to able to have flexibility to control when each promise resolves specifically, and I don't think that is possible with async functions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh ok.
…test that covers multi-phase asyncstorage usage
const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin') | ||
const { TestService } = require('./internal/testService') | ||
|
||
async function initAppPostWithPrevalidation(endpoint) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this function is duplicated in test/requestContextPlugin.spec.js
(except ready vs listen)
Could you use once?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, need to do a couple of deduplication passes. Will do.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Eomm Extracted this part, probably can extract some more.
lib/requestContextPlugin.js
Outdated
@@ -10,7 +10,7 @@ function plugin(fastify, opts, next) { | |||
fastify.decorate('requestContext', requestContext) | |||
fastify.decorateRequest('requestContext', requestContext) | |||
|
|||
fastify.addHook('onRequest', (req, res, done) => { | |||
fastify.addHook(opts.hook || 'preValidation', (req, res, done) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be a semver major this change?
***continue
if the opts.hook is an array, it won't works, so we need to iterate over the array.
Why we should add the same hook on multiple lifecycle events?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, will have to do major version bump.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hopefully there is a way to fix losing context from onRequest stage, though, but worst case scenario, initting ASL only on preValidation upwards can be made canonic.
index.d.ts
Outdated
export type RequestContextOptions = { | ||
defaultStoreValues?: Record<string, any> | ||
hook?: Hook | Hook[] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it is wrong since this doesn't work:
fastify.addHook(['onResponse', 'preHandler'], ()=>{}) // throw new FST_ERR_HOOK_INVALID_TYPE()
***continue
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't see much point in having multiple hooks, so kept just one.
lib/requestContextPlugin.js
Outdated
als.runWith(() => { | ||
wrapHttpEmitters(req.raw, res.raw) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@puzpuzpuz In your example I see that you are using reply.res
instead of res.raw
. Any reason for that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIRC that property is not available in Fastify v2.x which my plugin requires.
lib/requestContextPlugin.js
Outdated
als.runWith(() => { | ||
done() | ||
const asyncResource = new AsyncResource('fastify-request-context') | ||
req.asyncResource = asyncResource |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would probably store this in a symbol instead
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
(test will fail as there is a botched find-my-way release out, don-'t worry about them as it will be fixed in a few minutes)
@mcollina Jobs still fail for me when I rerun them, even though they pass locally with fully rebuilt package-lock.json. |
No, you should be able to re-run the pipeline going in the details of the run in order to let the badge in README green again |
fixes fastify/help#236