Skip to content
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

Merged
merged 17 commits into from
Aug 14, 2020

Conversation

kibertoad
Copy link
Member

@kibertoad kibertoad commented Aug 13, 2020

@kibertoad kibertoad requested a review from Eomm August 13, 2020 13:52
@kibertoad
Copy link
Member Author

kibertoad commented Aug 13, 2020

@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.

@kibertoad kibertoad changed the title Add test for POST request with body, using async storage in prevalida… Support specifying alternate hook for the plugin Aug 13, 2020
@kibertoad kibertoad requested a review from mcollina August 13, 2020 14:56
@@ -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) => {
Copy link
Member

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?

Copy link
Member Author

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?

Copy link
Member

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.

Copy link
Member Author

@kibertoad kibertoad Aug 13, 2020

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.

Copy link
Member Author

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?

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.

Copy link
Member

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.

Copy link
Member Author

@kibertoad kibertoad Aug 14, 2020

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()
}

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).

Copy link
Member Author

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) => {
Copy link
Member

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.

Copy link
Member Author

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) => {
Copy link
Member

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.

Copy link
Member Author

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) => {
Copy link
Member

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.

Copy link
Member Author

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.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh ok.

const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin')
const { TestService } = require('./internal/testService')

async function initAppPostWithPrevalidation(endpoint) {
Copy link
Member

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?

Copy link
Member Author

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.

Copy link
Member Author

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.

@@ -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) => {
Copy link
Member

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?

Copy link
Member Author

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.

Copy link
Member Author

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[]
Copy link
Member

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

Copy link
Member Author

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.

als.runWith(() => {
wrapHttpEmitters(req.raw, res.raw)
Copy link
Member Author

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?

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.

@kibertoad kibertoad requested review from Eomm and mcollina August 14, 2020 10:24
@kibertoad kibertoad changed the title Support specifying alternate hook for the plugin Fix context loss when async storage is instantiated early in the request lifecycle Aug 14, 2020
lib/requestContextPlugin.js Show resolved Hide resolved
als.runWith(() => {
done()
const asyncResource = new AsyncResource('fastify-request-context')
req.asyncResource = asyncResource
Copy link
Member

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

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Member

@mcollina mcollina left a 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)

@kibertoad kibertoad merged commit a5cbaf2 into master Aug 14, 2020
@kibertoad kibertoad deleted the test/prevalidation branch August 14, 2020 15:34
@kibertoad
Copy link
Member Author

@mcollina Jobs still fail for me when I rerun them, even though they pass locally with fully rebuilt package-lock.json.
Are GitHub actions caching dependencies by default?

@Eomm
Copy link
Member

Eomm commented Aug 15, 2020

Are GitHub actions caching dependencies by default?

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

fastify-request-context is not working for POST API calls
6 participants