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

onReady might be executed twice #5049

Closed
mcollina opened this issue Sep 19, 2023 · 3 comments · Fixed by #5051
Closed

onReady might be executed twice #5049

mcollina opened this issue Sep 19, 2023 · 3 comments · Fixed by #5051
Labels
bug Confirmed bug

Comments

@mcollina
Copy link
Member

If we call ready() in parallel, the onReady hooks are triggered twice

import fastify from './fastify.js'

const app = fastify()

app.addHook('onReady', async function () {
  console.log('onReady')
})


await Promise.race([app.ready(), app.ready()])

await app.ready()

Note that this is also a problem when using inject()

@saikiran76
Copy link

saikiran76 commented Oct 29, 2023

You are correct that calling ready() in parallel can cause the onReady hooks to be triggered twice. This is because onReady hooks are triggered once for each call to be ready().

To avoid this issue, you can use a boolean flag to ensure that the onReady hooks are only triggered once. Here's an example:

import fastify from './fastify.js'

const app = fastify()

let isReady = false

app.addHook('onReady', async function () {
if (!isReady) {
console.log('onReady')
isReady = true
}
})

await Promise.race([app.ready(), app.ready()])

await app.ready()

@saikiran76
Copy link

If the above seems it can work, may be I will be able to work on this. @mcollina

@mcollina
Copy link
Member Author

Yes... but it's likely going to be more tricky than that example.

Uzlopak added a commit that referenced this issue Dec 13, 2023

Partially verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
We cannot verify signatures from co-authors, and some of the co-authors attributed to this commit require their commits to be signed.
* fix: call onready once

* fix: ensure on-ready promises are triggered in the right order

* refactor: Apply suggestions from code review

Co-authored-by: Manuel Spigolon <behemoth89@gmail.com>

* refactor: use promise as flow management

---------

Co-authored-by: Manuel Spigolon <behemoth89@gmail.com>
Co-authored-by: Aras Abbasi <aras.abbasi@googlemail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Confirmed bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants