1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use ;
use ;
//
// CachingLayer
//
/// HTTP response caching layer with integrated compression.
///
/// This layer configures and installs a [CachingService].
///
/// The cache and cache key implementations are provided as generic type parameters. The
/// [CommonCacheKey] implementation should suffice for common use cases.
///
/// For more information and usage examples see the
/// [home page](https://github.com/tliron/tower-http-response-cache).
//
/// Requirements
/// ============
///
/// The response body type *and* its data type must both implement
/// [From]\<[ImmutableBytes](kutil::std::immutable::ImmutableBytes)\>. (This is the case with
/// [axum](https://github.com/tokio-rs/axum).)
///
/// Usage notes
/// ===========
///
/// 1. By default this layer is "opt-out" for caching and encoding. You can "punch through" this
/// behavior via custom response headers (which will be removed before sending the response
/// downstream):
///
/// * Set `XX-Cache` to "false" to skip caching.
/// * Set `XX-Encode` to "false" to skip encoding.
///
/// However, you can also configure for "opt-in", *requiring* these headers to be set to "true"
/// in order to enable the features. See [cacheable_by_default](Self::cacheable_by_default) and
/// [encodable_by_default](Self::encodable_by_default).
///
/// 2. Alternatively, you can provide [cacheable_by_request](Self::cacheable_by_request),
/// [cacheable_by_response](Self::cacheable_by_response),
/// [encodable_by_request](Self::encodable_by_request),
/// and/or [encodable_by_response](Self::encodable_by_response) hooks to control these features.
/// (If not provided they are assumed to return true.) The response hooks can be workarounds for
/// when you can't add custom headers upstream.
///
/// 3. You can explicitly set the cache duration for a response via a `XX-Cache-Duration` header.
/// Its string value is parsed using [duration-str](https://github.com/baoyachi/duration-str).
/// You can also provide a [cache_duration](Self::cache_duration) hook (the
/// `XX-Cache-Duration` header will override it). The actual effect of the duration depends on
/// the cache implementation.
///
/// ([Here](https://docs.rs/moka/latest/moka/policy/trait.Expiry.html#method.expire_after_create)
/// is the logic used for the Moka implementation.)
///
/// 4. Though this layer transparently handles HTTP content negotiation for `Accept-Encoding`, for
/// which the underlying content is the same, it cannot do so for `Accept` and
/// `Accept-Language`, for which content can differ. We do, however, provide a solution for
/// situations in which negotiation can be handled *without* the upstream response: the
/// [cache_key](Self::cache_key) hook. Here you can handle negotiation yourself and update the
/// cache key accordingly, so that different content will be cached separately. [CommonCacheKey]
/// reserves fields for media type and languages, just for this purpose.
///
/// If this impossible or too cumbersome, the alternative to content negotiation is to make
/// content selection the client's responsibility by including the content type in the URL, in
/// the path itself or as a query parameter. Web browsers often rely on JavaScript to automate
/// this for users by switching to the appropriate URL, for example adding "/en" to the path to
/// select English.
///
/// General advice
/// ==============
///
/// 1. Compressing already-compressed content is almost always a waste of compute for both the
/// server and the client. For this reason it's a good idea to explicitly skip the encoding of
/// [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types)
/// that are known to be already-compressed, such as those for audio, video, and images. You can
/// do this via the [encodable_by_response](Self::encodable_by_response) hook mentioned above.
/// (See the example.)
///
/// 2. We advise setting the `Content-Length` header on your responses whenever possible as it
/// allows this layer to check for cacheability without having to read the body, and it's
/// generally a good practice that helps many HTTP components to run optimally. That said, this
/// layer will optimize as much as it can even when `Content-Length` is not available, reading
/// only as many bytes as necessary to determine if the response is cacheable and then "pushing
/// back" those bytes (zero-copy) if it decides to skip the cache and send the response
/// downstream.
///
/// 3. Make use of client-side caching by setting the `Last-Modified` and/or `ETag` headers on your
/// responses. They are of course important without server-side caching, but this layer will
/// respect them even for cached entries by returning 304 (Not Modified) when appropriate.
///
/// If you don't set the `Last-Modified` header yourself then this layer will default to using
/// the instant in which the *cache entry* was created, which would be less optimal then the
/// timestamp of the actual data on which it is based.
///
/// 4. This caching layer does *not* own the cache, meaning that you can can insert or invalidate
/// cache entries according to application events other than user requests. Example scenarios:
///
/// 1. Inserting cache entries manually can be critical for avoiding "cold cache" performance
/// degradation (as well as outright failure) for busy, resource-heavy servers. You might
/// want to initialize your cache with popular entries before opening your server to
/// requests. If your cache is distributed it might also mean syncing the cache first.
///
/// 2. Invalidating cache entries manually can be critical for ensuring that clients don't
/// see out-of-date data, especially when your cache durations are long. For example, when
/// certain data is deleted from your database you can make sure to invalidate all cache
/// entries that depend on that data. To simplify this, you can the data IDs to your cache
/// keys. When invalidating, you can then enumerate all existing keys that contain the
/// relevant ID. [CommonCacheKey] reserves an `extensions` fields just for this purpose.
///
/// Request handling
/// ================
///
/// Here we'll go over the complete processing flow in detail:
///
/// 1. A request arrives. Check if it is cacheable (for now). Reasons it won't be cacheable:
///
/// * Caching is disabled for this layer
/// * The request is non-idempotent (e.g. POST)
/// * If we pass the checks above then we give the
/// [cacheable_by_request](Self::cacheable_by_request) hook a chance to skip caching.
/// If it returns false then we are non-cacheable.
///
/// If the response is non-cacheable then go to "Non-cached request handling" below.
///
/// 2. Check if we have a cached response.
///
/// 3. If we do, then:
///
/// 1. Select the best encoding according to our configured preferences and the priorities
/// specified in the request's `Accept-Encoding`. If the cached response has `XX-Encode`
/// header as "false" then use Identity encoding.
///
/// 2. If we have that encoding in the cache then:
///
/// 1. If the client sent `If-Modified-Since` then compare with our cached `Last-Modified`,
/// and if not modified then send a 304 (Not Modified) status (conditional HTTP). END.
///
/// 2. Otherwise create a response from the cache entry and send it. Note that we know its
/// size so we set `Content-Length` accordingly. END.
///
/// 3. Otherwise, if we don't have the encoding in the cache then check to see if the cache
/// entry has `XX-Encode` entry as "false". If so, we will choose Identity encoding and go up
/// to step 3.2.2.
///
/// 4. Find the best starting point from the encodings we already have. We select them in order
/// from cheapest to decode (Identity) to the most expensive.
///
/// 5. If the starting point encoding is *not* Identity then we must first decode it. If
/// `keep_identity_encoding` is true then we will store the decoded data in the cache so that
/// we can skip this step in the future (the trade-off is taking up more room in the cache).
///
/// 6. Encode the body and store it in the cache.
///
/// 7. Go up to step 3.2.2.
///
/// 4. If we don't have a cached response:
///
/// 1. Get the upstream response and check if it is cacheable. Reasons it won't be cacheable:
///
/// * Its status code is not "success" (200 to 299)
/// * Its `XX-Cache` header is "false"
/// * It has a `Content-Range` header (we don't cache partial responses)
/// * It has a `Content-Length` header that is lower than our configured minimum or higher
/// than our configured maximum
/// * If we pass all the checks above then we give the
/// [cacheable_by_response](Self::cacheable_by_response) hook one last chance to skip
/// caching. If it returns false then we are non-cacheable.
///
/// If the upstream response is non-cacheable then go to "Non-cached request handling" below.
///
/// 2. Otherwise select the best encoding according to our configured preferences and the
/// priorities specified in the request's `Accept-Encoding`. If the upstream response has
/// `XX-Encode` header as "false" or has `Content-Length` smaller than our configured
/// minimum, then use Identity encoding.
///
/// 3. If the selected encoding is not Identity then we give the
/// [encodable_by_response](Self::encodable_by_response) hook one last chance to skip
/// encoding. If it returns false we set the encoding to Identity and add the `XX-Encode`
/// header as "true" for use by step 3.1 above.
///
/// 4. Read the upstream response body into a buffer. If there is no `Content-Length` header
/// then make sure to read no more than our configured maximum size.
///
/// 5. If there's still more data left or the data that was read is less than our configured
/// minimum size then it means the upstream response is non-cacheable, so:
///
/// 1. Push the data that we read back into the front of the upstream response body.
///
/// 2. Go to "Non-cached request handling" step 4 below.
///
/// 6. Otherwise store the read bytes in the cache, encoding them if necessary. We know the
/// size, so we can check if it's smaller than the configured minimum for encoding, in
/// which case we use Identity encoding. We also make sure to set the cached `Last-Modified`
/// header to the current time if the header wasn't already set. Go up to step 3.2.
///
/// Note that upstream response trailers are discarded and *not* stored in the cache. (We
/// make the assumption that trailers are only relevant to "real" responses.)
///
/// ### Non-cached request handling
///
/// 1. If the upstream response has `XX-Encode` header as "false" or has `Content-Length` smaller
/// than our configured minimum, then pass it through as is. THE END.
///
/// Note that without `Content-Length` there is no way for us to check against the minimum and
/// so we must continue.
///
/// 2. Select the best encoding according to our configured preferences and the priorities
/// specified in the request's `Accept-Encoding`.
///
/// 3. If the selected encoding is not Identity then we give the
/// [encodable_by_request](Self::encodable_by_request) and
/// [encodable_by_response](Self::encodable_by_response) hooks one last chance to skip encoding.
/// If either returns false we set the encoding to Identity.
///
/// 4. If the upstream response is already in the selected encoding then pass it through. END.
///
/// 5. Otherwise, if the upstream response is Identity, then wrap it in an encoder and send it
/// downstream. Note that we do not know the encoded size in advance so we make sure there is no
/// `Content-Length` header. END.
///
/// 6. However, if the upstream response is *not* Identity, then just pass it through as is. END.
///
/// Note that this is technically wrong and in fact there is no guarantee here that the client
/// would support the upstream response's encoding. However, we implement it this way because:
///
/// 1) This is likely a rare case. If you are using this middleware then you probably don't have
/// already-encoded data coming from previous layers.
///
/// 2) If you do have already-encoded data, it is reasonable to expect that the encoding was
/// selected according to the request's `Accept-Encoding`.
///
/// 3) It's quite a waste of compute to decode and then reencode, which goes against the goals
/// of this middleware. (We do emit a warning in the logs.)