PageRenderTime 44ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/http-cache-semantics/README.md

https://gitlab.com/AVA_Sri/agovbe
Markdown | 203 lines | 142 code | 61 blank | 0 comment | 0 complexity | 1f87ccc62dcfc72f3cf890151740b395 MD5 | raw file
  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. `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.
  3. It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`.
  4. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses.
  5. ## Usage
  6. Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy.
  7. ```js
  8. const policy = new CachePolicy(request, response, options);
  9. if (!policy.storable()) {
  10. // throw the response away, it's not usable at all
  11. return;
  12. }
  13. // Cache the data AND the policy object in your cache
  14. // (this is pseudocode, roll your own cache (lru-cache package works))
  15. letsPretendThisIsSomeCache.set(
  16. request.url,
  17. { policy, response },
  18. policy.timeToLive()
  19. );
  20. ```
  21. ```js
  22. // And later, when you receive a new request:
  23. const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url);
  24. // It's not enough that it exists in the cache, it has to match the new request, too:
  25. if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
  26. // OK, the previous response can be used to respond to the `newRequest`.
  27. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
  28. response.headers = policy.responseHeaders();
  29. return response;
  30. }
  31. ```
  32. It 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.
  33. The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met.
  34. ### Constructor options
  35. Request 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).
  36. ```js
  37. const request = {
  38. url: '/',
  39. method: 'GET',
  40. headers: {
  41. accept: '*/*',
  42. },
  43. };
  44. const response = {
  45. status: 200,
  46. headers: {
  47. 'cache-control': 'public, max-age=7234',
  48. },
  49. };
  50. const options = {
  51. shared: true,
  52. cacheHeuristic: 0.1,
  53. immutableMinTimeToLive: 24 * 3600 * 1000, // 24h
  54. ignoreCargoCult: false,
  55. };
  56. ```
  57. If `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.
  58. `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.
  59. `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.
  60. If `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.
  61. ### `storable()`
  62. Returns `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.
  63. ### `satisfiesWithoutRevalidation(newRequest)`
  64. This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request.
  65. If 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()`.
  66. If 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()`).
  67. ### `responseHeaders()`
  68. Returns 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.
  69. ```js
  70. cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse);
  71. ```
  72. ### `timeToLive()`
  73. Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh).
  74. After 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()`.
  75. `stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale.
  76. ### `toObject()`/`fromObject(json)`
  77. Chances 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.
  78. ### Refreshing stale cache (revalidation)
  79. When 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.
  80. The following methods help perform the update efficiently and correctly.
  81. #### `revalidationHeaders(newRequest)`
  82. Returns 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.
  83. Use this method when updating cache from the origin server.
  84. ```js
  85. updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest);
  86. ```
  87. #### `revalidatedPolicy(revalidationRequest, revalidationResponse)`
  88. Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys:
  89. - `policy` A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one.
  90. - `modified` Boolean indicating whether the response body has changed.
  91. - 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`.
  92. - 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.
  93. ```js
  94. // When serving requests from cache:
  95. const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get(
  96. newRequest.url
  97. );
  98. if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) {
  99. // Change the request to ask the origin server if the cached response can be used
  100. newRequest.headers = oldPolicy.revalidationHeaders(newRequest);
  101. // Send request to the origin server. The server may respond with status 304
  102. const newResponse = await makeRequest(newRequest);
  103. // Create updated policy and combined response from the old and new data
  104. const { policy, modified } = oldPolicy.revalidatedPolicy(
  105. newRequest,
  106. newResponse
  107. );
  108. const response = modified ? newResponse : oldResponse;
  109. // Update the cache with the newer/fresher response
  110. letsPretendThisIsSomeCache.set(
  111. newRequest.url,
  112. { policy, response },
  113. policy.timeToLive()
  114. );
  115. // And proceed returning cached response as usual
  116. response.headers = policy.responseHeaders();
  117. return response;
  118. }
  119. ```
  120. # Yo, FRESH
  121. ![satisfiesWithoutRevalidation](fresh.jpg)
  122. ## Used by
  123. - [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)
  124. ## Implemented
  125. - `Cache-Control` response header with all the quirks.
  126. - `Expires` with check for bad clocks.
  127. - `Pragma` response header.
  128. - `Age` response header.
  129. - `Vary` response header.
  130. - Default cacheability of statuses and methods.
  131. - Requests for stale data.
  132. - Filtering of hop-by-hop headers.
  133. - Basic revalidation request
  134. - `stale-if-error`
  135. ## Unimplemented
  136. - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable)
  137. - Revalidation of multiple representations
  138. ### Trusting server `Date`
  139. Per 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:
  140. * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong).
  141. * 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).
  142. Previous 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).