source: trip-planner-front/node_modules/http-cache-semantics/README.md@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 10.1 KB
Line 
1# Can I cache this? [![Build Status](https://travis-ci.org/kornelski/http-cache-semantics.svg?branch=master)](https://travis-ci.org/kornelski/http-cache-semantics)
2
3`CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches.
4It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`.
5It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses.
6
7## Usage
8
9Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy.
10
11```js
12const policy = new CachePolicy(request, response, options);
13
14if (!policy.storable()) {
15 // throw the response away, it's not usable at all
16 return;
17}
18
19// Cache the data AND the policy object in your cache
20// (this is pseudocode, roll your own cache (lru-cache package works))
21letsPretendThisIsSomeCache.set(
22 request.url,
23 { policy, response },
24 policy.timeToLive()
25);
26```
27
28```js
29// And later, when you receive a new request:
30const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url);
31
32// It's not enough that it exists in the cache, it has to match the new request, too:
33if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
34 // OK, the previous response can be used to respond to the `newRequest`.
35 // Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
36 response.headers = policy.responseHeaders();
37 return response;
38}
39```
40
41It 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.
42
43The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met.
44
45### Constructor options
46
47Request 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).
48
49```js
50const request = {
51 url: '/',
52 method: 'GET',
53 headers: {
54 accept: '*/*',
55 },
56};
57
58const response = {
59 status: 200,
60 headers: {
61 'cache-control': 'public, max-age=7234',
62 },
63};
64
65const options = {
66 shared: true,
67 cacheHeuristic: 0.1,
68 immutableMinTimeToLive: 24 * 3600 * 1000, // 24h
69 ignoreCargoCult: false,
70};
71```
72
73If `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.
74
75`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.
76
77`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.
78
79If `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.
80
81### `storable()`
82
83Returns `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.
84
85### `satisfiesWithoutRevalidation(newRequest)`
86
87This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request.
88
89If 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()`.
90
91If 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()`).
92
93### `responseHeaders()`
94
95Returns 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.
96
97```js
98cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse);
99```
100
101### `timeToLive()`
102
103Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh).
104
105After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`.
106`stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale.
107
108### `toObject()`/`fromObject(json)`
109
110Chances are you'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.
111
112### Refreshing stale cache (revalidation)
113
114When 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.
115
116The following methods help perform the update efficiently and correctly.
117
118#### `revalidationHeaders(newRequest)`
119
120Returns 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.
121
122Use this method when updating cache from the origin server.
123
124```js
125updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest);
126```
127
128#### `revalidatedPolicy(revalidationRequest, revalidationResponse)`
129
130Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys:
131
132- `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one.
133- `modified` — Boolean indicating whether the response body has changed.
134 - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. This is also affected by `stale-if-error`.
135 - If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource.
136
137```js
138// When serving requests from cache:
139const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get(
140 newRequest.url
141);
142
143if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) {
144 // Change the request to ask the origin server if the cached response can be used
145 newRequest.headers = oldPolicy.revalidationHeaders(newRequest);
146
147 // Send request to the origin server. The server may respond with status 304
148 const newResponse = await makeRequest(newRequest);
149
150 // Create updated policy and combined response from the old and new data
151 const { policy, modified } = oldPolicy.revalidatedPolicy(
152 newRequest,
153 newResponse
154 );
155 const response = modified ? newResponse : oldResponse;
156
157 // Update the cache with the newer/fresher response
158 letsPretendThisIsSomeCache.set(
159 newRequest.url,
160 { policy, response },
161 policy.timeToLive()
162 );
163
164 // And proceed returning cached response as usual
165 response.headers = policy.responseHeaders();
166 return response;
167}
168```
169
170# Yo, FRESH
171
172![satisfiesWithoutRevalidation](fresh.jpg)
173
174## Used by
175
176- [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)
177
178## Implemented
179
180- `Cache-Control` response header with all the quirks.
181- `Expires` with check for bad clocks.
182- `Pragma` response header.
183- `Age` response header.
184- `Vary` response header.
185- Default cacheability of statuses and methods.
186- Requests for stale data.
187- Filtering of hop-by-hop headers.
188- Basic revalidation request
189- `stale-if-error`
190
191## Unimplemented
192
193- Merging of range requests, `If-Range` (but correctly supports them as non-cacheable)
194- Revalidation of multiple representations
195
196### Trusting server `Date`
197
198Per 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:
199
200 * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong).
201 * 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).
202
203Previous 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.