Open sleroq opened 1 year ago
This was supposed to be a bug, marked as support by mistake.
@nargonath
Sorry for mentioning directly, I believe this issue is being neglected because of the wrong label.
This is pretty tricky— if the request is aborted, then onPostResponse
happens at that moment since that is when the request has settled. There are equally use-cases where you want the "finalize response" steps (quoting the docs) to occur immediately. The docs even take a moment to note that you may want your onPostResponse
handlers to defer asynchronous work so that they can all be called immediately when the request settles.
So that's the tension: on one hand, the finalize response steps and onPostResponse
should occur as soon as the request settles; on the other hand, if there's a lifecycle method that is still running at that moment (which is likely) then of course there's no reliable way to cause it to terminate immediately. The onRequest
extension should still begin before onPostResponse
, which might be the most we can really guarantee for the case of an aborted request.
At the same time, I totally see how this poses an issue for you. My recommendation would be to handle this case by checking if the request is active after you setup the database connection, and if it isn't then you can tear it down immediately:
server.ext('onRequest', async (req, h) => {
req.app.db = await setupDbConnection();
if (!req.active()) {
await req.app.db.close();
}
return h.continue;
});
Thank you for the explanation.
I agree that both variants are acceptable. However, it seems odd to me to make this change in the patch version.
If this change was intentional, then I believe the issue is resolved.
Support plan
Context
What I am trying to achieve
I'm using
onRequest
andonPostResponse
events to open and close connections with database. ExpectingonPostResponse
to always trigger afteronRequest
. But in #4295 this behavior changes, andonPostResonse
is able to fire beforeonRequest
(if request is aborted).This behavior does not match with request lifecycle documentation.
Steps to reproduce:
const server = Hapi.server({port: 1234});
(async () => { server.ext('onRequest', async (req, h) => { await setTimeout(1000); console.log(
open: ${req.info.id}:${req.path}
); return h.continue; });})();
What was the result you got?
What result did you expect?