unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.81k stars 489 forks source link

staleMaxAge is not respected when swr is enabled #2164

Open cjpearson opened 6 months ago

cjpearson commented 6 months ago

Environment

node v20.11.1, Nuxt 3.10.2, Nitro 2.8.1

Reproduction

Configure routeRules to enable swr and set a stale max age.

e.g.

{
  swr: true,
  staleMaxAge: 10*60 // 10 minutes
}

Describe the bug

Nitro does not consider staleMaxAge and validate the age of a cached value when swr is enabled. It will always return a stale value if one is present, even if it is older than than the configured stale period.

Additional context

It looks like here only the swr flag is checked and the age of the entry and staleMaxAge is not considered. https://github.com/unjs/nitro/blob/e9975ac36914f582d7c7b724945e0abdd398291a/src/runtime/cache.ts#L141

Logs

No response

cjpearson commented 1 month ago

I've created a basic reproduction here.

It has a single route with a max age of 10 seconds and stale max age of 30 seconds.

On the initial request, the handler should be executed and the result returned. This works.

If refreshing within 10 seconds, the handler should not be executed and instead the previous result returned. This also works.

If refreshing 10 seconds after the initial request, but before 30 seconds, the cached result should still be used, but the handler should be executed in the background. This works too.

If refreshing more than 30 seconds after the initial request (or last update), the stale period has expired and the cached result should not be used. This is where the bug occurs.

ronenteva commented 2 days ago

Sorry to bump, but I think this is a major issue that deserves more attention. Seems like it's already solved, just wasn't merged for some reason.