Repository navigation
fix(fastify): settle async lifecycle hooks once - #17997
Conversation
kamilmysliwiec
left a comment
There was a problem hiding this comment.
Thanks! Returning the hook's promise fixes promise-only hooks, but it breaks the documented style (setOnRequestHook says to call done()): for an async (req, reply, done) => { await x; done(); } hook, fastify's hook runner now continues twice, once from done and once when the promise resolves, so the route handler runs twice (a POST would create its record twice). The same pattern makes the final onResponse callback run twice.
Instead of returning the result, please guard done so it can only fire once and continue on whichever comes first, done being called or the returned promise settling (rejection → done(err)), and add a test with an async hook that also calls done(), asserting the handler runs once.
PR Checklist
PR Type
What is the current behavior?
The Fastify wrappers discard the results of
setOnRequestHookandsetOnResponseHook, although both accept Promise-returning hooks. A promise-only request hook leaves the request pending, and an async response hook does not advance the response lifecycle.Simply returning the promise introduces another failure: an async hook that also calls
done()advances Fastify twice. A POST handler awaiting asynchronous work can execute twice, and the final response callback can run twice.Issue Number: N/A
What is the new behavior?
Both wrappers complete through a shared, once-only callback. Whichever happens first —
done(), promise fulfillment, or failure — settles the hook. Promise rejection and synchronous throws reach Fastify through the guarded callback; later completion signals are ignored. The wrappers consume the promise rather than returning it to Fastify.The implementation preserves callback hooks and their adapter receiver, and retains Fastify's error for a promise rejected without a reason. Real injected requests verify promise-only hooks, error handling, async hooks that also call
done(), repeated/late callbacks, late rejection, and exactly one response completion.Does this PR introduce a breaking change?
Other information
Validation on the existing PR branch:
shutdown process should not be interrupted by another handlerandshould defer shutdown until all init hooks are resolved.npm run build,npm run lint:ci, andgit diff --checkpassed. Lint retains one existing warning inpackages/websockets/socket-module.ts.Unit command: