nitrojs / nitro

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

I'm using the caching system of nitro, which use the redis driver. If my redis connection fails, is there a way to make defineCachedEventHandler not report an error and not use the cache? #2609

Closed robertyclin closed 1 week ago

robertyclin commented 4 months ago

Describe the feature

defineCachedEventHandler works normally

Additional information

HPieters commented 3 months ago

I was looking into this myself and was wondering if there is a way to skip cache if the driver gives an error. If valuable I can make a reproduction, but it's quit simple just run nitro or nuxt and a redis instance and kill your redis instance after which defineCachedEventHandler will return an error.

Happy to help implementing this if somebody would point me in the right direction. Possible solution to add this manually is to use shouldBypassCache but then I am unsure how I could check if redis (or any cache driver) is available at the time.

So something like this seems to work but feels like a workaround.

shouldBypassCache: async (event: H3Event) => {
    try {
      const cacheStorage = useStorage('cache:nitro');
      await cacheStorage.getKeys();
      return false;
    } catch () {
      return true;
    }
}
bitbytebit1 commented 1 month ago

This seems like quite an important issue, I'm surprised it hasn't got any love! I would also expect that should the caching mechanism fail it should fall back to calling the function and logging the error

cjpearson commented 2 weeks ago

For a reproduction you can use the starter app and adjust the config:

// https://nitro.unjs.io/config
export default defineNitroConfig({
  srcDir: "server",
  storage: {
    redis: {
      driver: "redis",
      url: "redis://localhost:6379",
      maxRetriesPerRequest: 3, // give up sooner and return an error
    },
  },
  routeRules: {
    "/**": { cache: { maxAge: 60 * 60, base: "redis" } },
  },
});
cjpearson commented 1 week ago

@pi0 I think this can be marked as fixed