kornelski / http-cache-semantics

RFC 7234 in JavaScript. Parses HTTP headers to correctly compute cacheability of responses, even in complex cases
http://httpwg.org/specs/rfc7234.html
BSD 2-Clause "Simplified" License
244 stars 27 forks source link

Support stale-while-revalidate and stale-if-error #27

Open adamstep opened 4 years ago

adamstep commented 4 years ago

Hi @kornelski, thanks for your work on this library, it looks fantastic.

For my use case, I would need the library to support these two Cache-Control directives. From MDN:

I think it could be implemented in the following way:

If you're open to these enhancements, I'd be happy to work on them.

kornelski commented 4 years ago

It would be great to support these features. stale-if-error seems like a straighforward improvement of the current implementation.

stale-while-revalidate is the more interesting feature, but it doesn't fit the existing API. satisfiesWithRevalidation is not a good solution, since a cache would have to run both functions, so it's adding whole another evaluation just for taking one option into account.

Perhaps there could be a new method like whatDoIDoWithThis (needs a better name) that returns one of "use it", "use it, but revalidate", "don't use it, go to server", etc. (needs better names).

adamstep commented 4 years ago

I'll work on stale-if-error first since it doesn't require a change to the API.

Maybe the new method could look like this: const { use, revalidate } = policy.check(newRequest)

kornelski commented 4 years ago

Yeah, that looks good.

adamstep commented 4 years ago

I started implementing this and realized that my proposal for stale-if-error doesn't work. satisfiesWithoutRevalidation looks at the new request before revalidation, whereas stale-if-error only applies if a validation attempt fails due to an error.

So I think this has to be done with a new method satisfiesIfError(newRequest), which would need to be called if satisfiedWithoutRevalidation(newRequest) returns false and the revalidation responses is a 50X.

kornelski commented 4 years ago

Ah, right. So together with stale-while-revalidate this requires rethinking how this interacts with caches.

sithmel commented 4 years ago

I think stale-if-error should:

What do you think? I am happy to help with the implementation

kornelski commented 4 years ago

If you're implementing it in parallel with an actual HTTP client I'm confident it'll make sense.

sithmel commented 4 years ago

The implementation is ready here: https://github.com/kornelski/http-cache-semantics/pull/30