source: node_modules/http-cache-semantics/README.md@ 62b2964

finki-main main
Last change on this file since 62b2964 was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 12.4 KB
Line 
1# Can I cache this?
2
3This library tells when responses can be reused from a cache, taking into account [HTTP RFC 7234/9111](http://httpwg.org/specs/rfc9111.html) rules for user agents and shared caches.
4It also implements `stale-if-error` and `stale-while-revalidate` from [RFC 5861](https://tools.ietf.org/html/rfc5861).
5It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses.
6
7## Basic Usage
8
9`CachePolicy` is a metadata object that is meant to be stored in the cache, and it will keep track of cacheability of the response.
10
11Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy.
12
13```js
14const policy = new CachePolicy(request, response, options);
15
16if (!policy.storable()) {
17 // throw the response away, it's not usable at all
18 return;
19}
20
21// Cache the data AND the policy object in your cache
22// (this is pseudocode, roll your own cache (lru-cache package works))
23letsPretendThisIsSomeCache.set(
24 request.url,
25 { policy, body: response.body }, // you only need to store the response body. CachePolicy holds the headers.
26 policy.timeToLive()
27);
28```
29
30```js
31// And later, when you receive a new request:
32const { policy, body } = letsPretendThisIsSomeCache.get(newRequest.url);
33
34// It's not enough that it exists in the cache, it has to match the new request, too:
35if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
36 // OK, the previous response can be used to respond to the `newRequest`.
37 // Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
38 return {
39 headers: policy.responseHeaders(),
40 body,
41 }
42}
43
44// Cache miss. See revalidationHeaders() and revalidatedPolicy() for advanced usage.
45```
46
47It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc.
48
49The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met.
50
51### Constructor options
52
53Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method).
54
55```js
56const request = {
57 url: '/',
58 method: 'GET',
59 headers: {
60 accept: '*/*',
61 },
62};
63
64const response = {
65 status: 200,
66 headers: {
67 'cache-control': 'public, max-age=7234',
68 },
69};
70
71const options = {
72 shared: true,
73 cacheHeuristic: 0.1,
74 immutableMinTimeToLive: 24 * 3600 * 1000, // 24h
75 ignoreCargoCult: false,
76};
77```
78
79If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). `shared: true` is recommended for HTTP clients.
80
81`options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100\*0.1 = 10 days.
82
83`options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default.
84
85If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults.
86
87### `storable()`
88
89Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response.
90
91### `satisfiesWithoutRevalidation(newRequest)`
92
93Use this method to check whether the cached response is still fresh in the context of the new request.
94
95If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`.
96
97If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`).
98
99### `responseHeaders()`
100
101Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time.
102
103```js
104cachedResponse.headers = cachePolicy.responseHeaders();
105```
106
107### `timeToLive()`
108
109Suggests a time in _milliseconds_ for how long this cache entry may be useful. This is not freshness, so always check with `satisfiesWithoutRevalidation()`. This time may be longer than response's `max-age` to allow for `stale-if-error` and `stale-while-revalidate`.
110
111After that time (when `timeToLive() <= 0`) the response may still be usable in certain cases, e.g. if client can explicitly allows stale responses.
112
113### `toObject()`/`fromObject(json)`
114
115You'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it.
116
117## Complete Usage
118
119### `evaluateRequest(newRequest)`
120
121Returns an object telling what to do next — optional `revalidation`, and optional `response` from cache. Either one of these properties will be present. Both may be present at the same time.
122
123```js
124{
125 // If defined, you must send a request to the server.
126 revalidation: {
127 headers: {}, // HTTP headers to use when sending the revalidation response
128 // If true, you MUST wait for a response from the server before using the cache
129 // If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously.
130 synchronous: bool,
131 },
132 // If defined, you can use this cached response.
133 response: {
134 headers: {}, // Updated cached HTTP headers you must use when responding to the client
135 },
136}
137```
138
139### Example
140
141```js
142let cached = cacheStorage.get(incomingRequest.url);
143
144// Cache miss - make a request to the origin and cache it
145if (!cached) {
146 const newResponse = await makeRequest(incomingRequest);
147 const policy = new CachePolicy(incomingRequest, newResponse);
148
149 cacheStorage.set(
150 incomingRequest.url,
151 { policy, body: newResponse.body },
152 policy.timeToLive()
153 );
154
155 return {
156 // use responseHeaders() to remove hop-by-hop headers that should not be passed through proxies
157 headers: policy.responseHeaders(),
158 body: newResponse.body,
159 }
160}
161
162// There's something cached, see if it's a hit
163let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest);
164
165// Revalidation always goes first
166if (revalidation) {
167 // It's very important to update the request headers to make a correct revalidation request
168 incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders()
169
170 // The cache may be updated immediately or in the background,
171 // so use a Promise to optionally defer the update
172 const updatedResponsePromise = makeRequest(incomingRequest).then(() => {
173 // Refresh the old response with the new information, if applicable
174 const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse);
175
176 const body = modified ? newResponse.body : cached.body;
177
178 // Update the cache with the newer response
179 if (policy.storable()) {
180 cacheStorage.set(
181 incomingRequest.url,
182 { policy, body },
183 policy.timeToLive()
184 );
185 }
186
187 return {
188 headers: policy.responseHeaders(), // these are from the new revalidated policy
189 body,
190 }
191 });
192
193 if (revalidation.synchronous) {
194 // If synchronous, then you MUST get a reply from the server first
195 return await updatedResponsePromise;
196 }
197
198 // If not synchronous, it can fall thru to returning the cached response,
199 // while the request to the server is happening in the background.
200}
201
202return {
203 headers: response.headers, // Same as cached.policy.responseHeaders()
204 body: cached.body,
205}
206```
207
208### Refreshing stale cache (revalidation)
209
210When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth.
211
212The following methods help perform the update efficiently and correctly.
213
214#### `revalidationHeaders(newRequest)`
215
216Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is.
217
218Use this method when updating cache from the origin server. Also available in `evaluateRequest(newRequest).revalidation.headers`.
219
220```js
221updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest);
222```
223
224#### `revalidatedPolicy(revalidationRequest, revalidationResponse)`
225
226Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys:
227
228- `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one.
229- `modified` — Boolean indicating whether the response body has changed, and you should use the new response body sent by the server.
230 - If `true`, you should use the new response body, and you can replace the old cached response with the updated one.
231 - If `false`, then you should reuse the old cached response body. Either a valid 304 Not Modified response has been received, or an error happened and `stale-if-error` allows falling back to the cache.
232
233# Yo, FRESH
234
235![satisfiesWithoutRevalidation](fresh.jpg)
236
237## Used by
238
239- [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request) ([got](https://www.npmjs.com/package/got)), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/kornelski/http-cache-semantics/network/dependents)
240- [Rust version of this library](https://lib.rs/crates/http-cache-semantics).
241
242## Implemented
243
244- `Cache-Control` response header with all the quirks.
245- `Expires` with check for bad clocks.
246- `Pragma` response header.
247- `Age` response header.
248- `Vary` response header.
249- Default cacheability of statuses and methods.
250- Requests for stale data.
251- Filtering of hop-by-hop headers.
252- Basic revalidation request
253- `stale-if-error`
254- `stale-while-revalidate`
255
256## Unimplemented
257
258- Merging of range requests, `If-Range` (but correctly supports them as non-cacheable)
259- Revalidation of multiple representations
260
261### Trusting server `Date`
262
263Per the RFC, the cache should take into account the time between server-supplied `Date` and the time it received the response. The RFC-mandated behavior creates two problems:
264
265 * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong).
266 * Even reasonably correct clocks may be off by a couple of seconds, breaking `max-age=1` trick (which is useful for reverse proxies on high-traffic servers).
267
268Previous versions of this library had an option to ignore the server date if it was "too inaccurate". To support the `max-age=1` trick the library also has to ignore dates that pretty accurate. There's no point of having an option to trust dates that are only a bit inaccurate, so this library won't trust any server dates. `max-age` will be interpreted from the time the response has been received, not from when it has been sent. This will affect only [RFC 1149 networks](https://tools.ietf.org/html/rfc1149).
Note: See TracBrowser for help on using the repository browser.