http-cache-stream 0.4.0

A HTTP cache implementation for streaming bodies.
Documentation
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Implementation of the HTTP cache.

use std::fmt;
use std::time::SystemTime;

use anyhow::Result;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use http::Response;
use http::StatusCode;
use http::Uri;
use http::Version;
use http::header;
use http::header::CACHE_CONTROL;
use http::uri::Authority;
use http_body::Body;
use http_cache_semantics::AfterResponse;
use http_cache_semantics::BeforeRequest;
use http_cache_semantics::CacheOptions;
use http_cache_semantics::CachePolicy;
use sha2::Digest;
use sha2::Sha256;
use tracing::debug;

use crate::body::CacheBody;
use crate::storage::CacheStorage;
use crate::storage::StoredResponse;

/// The name of the `x-cache-lookup` custom header.
///
/// Value will be `HIT` if a response existed in cache, `MISS` if not.
pub const X_CACHE_LOOKUP: &str = "x-cache-lookup";

/// The name of the `x-cache` custom header.
///
/// Value will be `HIT` if a response was served from the cache, `MISS` if not.
pub const X_CACHE: &str = "x-cache";

/// The name of the `x-cache-digest` custom header.
///
/// This header is only present in the response when returning a body from the
/// cache.
///
/// This can be used to read a body directly from cache storage rather than
/// reading the body through the response.
///
/// This header is only present when a cached response body is being served from
/// the cache.
pub const X_CACHE_DIGEST: &str = "x-cache-digest";

/// Gets the storage key for a request.
fn storage_key(method: &Method, uri: &Uri, headers: &HeaderMap) -> String {
    let mut hasher = Sha256::new();
    hasher.update(method.as_str());
    hasher.update(":");

    if let Some(scheme) = uri.scheme_str() {
        hasher.update(scheme);
    }

    hasher.update("://");
    if let Some(authority) = uri.authority() {
        hasher.update(authority.as_str());
    }

    hasher.update(uri.path());

    if let Some(query) = uri.query() {
        hasher.update(query);
    }

    if let Some(value) = headers.get(header::RANGE) {
        hasher.update(value.as_bytes());
    }

    let bytes = hasher.finalize();
    hex::encode(bytes)
}

/// Represents a basic cache lookup status.
///
/// Used in the custom header `x-cache-lookup`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum CacheLookupStatus {
    /// A response exists in the cache.
    Hit,
    /// A response does not exist in the cache.
    Miss,
}

impl fmt::Display for CacheLookupStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hit => write!(f, "HIT"),
            Self::Miss => write!(f, "MISS"),
        }
    }
}

/// Represents a cache status.
///
/// Used in the custom header `x-cache`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum CacheStatus {
    /// The response was served from the cache.
    Hit,
    /// The response was not served from the cache.
    Miss,
}

impl fmt::Display for CacheStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hit => write!(f, "HIT"),
            Self::Miss => write!(f, "MISS"),
        }
    }
}

/// An extension trait for [`Response`].
trait ResponseExt {
    /// Adds a warning header to the response.
    fn add_warning(&mut self, uri: &Uri, code: usize, message: &str);

    /// Checks if the Cache-Control header contains the must-revalidate
    /// directive.
    fn must_revalidate(&self) -> bool;

    /// Extends the request's headers with those from the given header map.
    ///
    /// Existing matching headers will be replaced.
    fn extend_headers(&mut self, headers: HeaderMap);

    /// Sets the cache status headers of the response.
    fn set_cache_status(
        &mut self,
        lookup: CacheLookupStatus,
        status: CacheStatus,
        digest: Option<&str>,
    );
}

impl<B> ResponseExt for Response<B> {
    fn add_warning(&mut self, url: &Uri, code: usize, message: &str) {
        // warning    = "warning" ":" 1#warning-value
        // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
        // warn-code  = 3DIGIT
        // warn-agent = ( host [ ":" port ] ) | pseudonym
        //                 ; the name or pseudonym of the server adding
        //                 ; the warning header, for use in debugging
        // warn-text  = quoted-string
        // warn-date  = <"> HTTP-date <">
        // (https://tools.ietf.org/html/rfc2616#section-14.46)
        self.headers_mut().insert(
            "warning",
            HeaderValue::from_str(&format!(
                "{} {} {:?} \"{}\"",
                code,
                url.host().expect("URL should be valid"),
                message,
                httpdate::fmt_http_date(SystemTime::now())
            ))
            .expect("value should be valid"),
        );
    }

    fn must_revalidate(&self) -> bool {
        self.headers()
            .get(CACHE_CONTROL.as_str())
            .is_some_and(|val| {
                val.to_str()
                    .unwrap_or("")
                    .to_lowercase()
                    .contains("must-revalidate")
            })
    }

    fn extend_headers(&mut self, headers: HeaderMap) {
        self.headers_mut().extend(headers);
    }

    fn set_cache_status(
        &mut self,
        lookup: CacheLookupStatus,
        status: CacheStatus,
        digest: Option<&str>,
    ) {
        let headers = self.headers_mut();
        headers.insert(
            X_CACHE_LOOKUP,
            lookup.to_string().parse().expect("value should parse"),
        );
        headers.insert(
            X_CACHE,
            status.to_string().parse().expect("value should parse"),
        );
        if let Some(digest) = digest {
            headers.insert(X_CACHE_DIGEST, digest.parse().expect("value should parse"));
        }
    }
}

/// An abstraction of an HTTP request.
///
/// This trait is used in HTTP middleware integrations to abstract the request
/// type and sending the request upstream.
pub trait Request<B: Body>: Send {
    /// Gets the request's version.
    fn version(&self) -> Version;

    /// Gets the request's method.
    fn method(&self) -> &Method;

    /// Gets the request's URI.
    fn uri(&self) -> &Uri;

    /// Gets the request's headers.
    fn headers(&self) -> &HeaderMap;

    /// Sends the request to upstream and gets the response.
    ///
    /// If `headers` is `Some`, the supplied headers should override any
    /// matching headers in the original request.
    fn send(self, headers: Option<HeaderMap>) -> impl Future<Output = Result<Response<B>>> + Send;
}

/// Provides an implementation of `RequestLike` for `http-cache-semantics`.
struct RequestLike {
    /// The request method.
    method: Method,
    /// The request URI.
    uri: Uri,
    /// The request headers.
    headers: HeaderMap,
}

impl RequestLike {
    /// Constructs a new `RequestLike` for the given request.
    fn new<R: Request<B>, B: Body>(request: &R) -> Self {
        // Unfortunate we have to clone the header map here
        Self {
            method: request.method().clone(),
            uri: request.uri().clone(),
            headers: request.headers().clone(),
        }
    }
}

impl http_cache_semantics::RequestLike for RequestLike {
    fn uri(&self) -> Uri {
        // Note: URI is cheaply cloned
        self.uri.clone()
    }

    fn is_same_uri(&self, other: &Uri) -> bool {
        self.uri.eq(other)
    }

    fn method(&self) -> &Method {
        &self.method
    }

    fn headers(&self) -> &HeaderMap {
        &self.headers
    }
}

/// Represents a revalidation hook.
///
/// The hook is provided the original request and a mutable header map
/// containing headers explicitly set for the revalidation request.
///
/// For example, a hook may alter the revalidation headers to update an
/// `Authorization` header based on the headers used for revalidation.
///
/// If the hook returns an error, the error is propagated out as the result of
/// the original request.
type RevalidationHook = dyn Fn(&dyn http_cache_semantics::RequestLike, &mut HeaderMap) -> Result<()>
    + Send
    + Sync
    + 'static;

/// Implement a HTTP cache.
pub struct Cache<S> {
    /// The cache storage.
    storage: S,
    /// The cache options to use.
    options: CacheOptions,
    /// Stores the revalidation hook.
    ///
    /// This is `None` if no revalidation hook is used.
    hook: Option<Box<RevalidationHook>>,
}

impl<S> Cache<S>
where
    S: CacheStorage,
{
    /// Construct a new cache with the given storage.
    ///
    /// Defaults to a private cache.
    pub fn new(storage: S) -> Self {
        Self {
            storage,
            // Default to a private cache
            options: CacheOptions {
                shared: false,
                ..Default::default()
            },
            hook: None,
        }
    }

    /// Construct a new cache with the given storage and options.
    pub fn new_with_options(storage: S, options: CacheOptions) -> Self {
        Self {
            storage,
            options,
            hook: None,
        }
    }

    /// Sets the revalidation hook to use.
    ///
    /// The hook is provided the original request and a mutable header map
    /// containing headers explicitly set for the revalidation request.
    ///
    /// For example, a hook may alter the revalidation headers to update an
    /// `Authorization` header based on the headers used for revalidation.
    ///
    /// If the hook returns an error, the error is propagated out as the result
    /// of the original request.
    pub fn with_revalidation_hook(
        mut self,
        hook: impl Fn(&dyn http_cache_semantics::RequestLike, &mut HeaderMap) -> Result<()>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.hook = Some(Box::new(hook));
        self
    }

    /// Gets the storage used by the cache.
    pub fn storage(&self) -> &S {
        &self.storage
    }

    /// Sends a HTTP request through the cache.
    ///
    /// If a previous response is cached and not stale, the request is not sent
    /// upstream and the cached response is returned.
    ///
    /// If a previous response is cached and is stale, the response is
    /// revalidated, the cache is updated, and the cached response returned.
    ///
    /// If a previous response is not in the cache, the request is sent upstream
    /// and the response is cached, if it is cacheable.
    pub async fn send<B: Body + Send>(
        &self,
        request: impl Request<B>,
    ) -> Result<Response<CacheBody<B>>> {
        let method = request.method();
        let uri = request.uri();

        let key = storage_key(method, uri, request.headers());
        if matches!(*method, Method::GET | Method::HEAD) {
            match self.storage.get(&key).await {
                Ok(Some(stored)) => {
                    debug!(
                        method = method.as_str(),
                        scheme = uri.scheme_str(),
                        authority = uri.authority().map(Authority::as_str),
                        path = uri.path(),
                        key,
                        "cache hit"
                    );
                    return self.conditional_send_upstream(key, request, stored).await;
                }
                Ok(None) => {
                    debug!(
                        method = method.as_str(),
                        scheme = uri.scheme_str(),
                        authority = uri.authority().map(Authority::as_str),
                        path = uri.path(),
                        key,
                        "cache miss"
                    );
                }
                Err(e) => {
                    debug!(
                        method = method.as_str(),
                        scheme = uri.scheme_str(),
                        authority = uri.authority().map(Authority::as_str),
                        path = uri.path(),
                        key,
                        error = format!("{e:?}"),
                        "failed to get response from storage; treating as not cached"
                    );

                    // Treat as a miss
                }
            }
        }

        self.send_upstream(key, request, CacheLookupStatus::Miss)
            .await
    }

    /// Sends the original request upstream.
    ///
    /// Caches the response if the response is cacheable.
    async fn send_upstream<B: Body + Send>(
        &self,
        key: String,
        request: impl Request<B>,
        lookup_status: CacheLookupStatus,
    ) -> Result<Response<CacheBody<B>>> {
        let request_like: RequestLike = RequestLike::new(&request);

        let mut response = request.send(None).await?;
        let policy =
            CachePolicy::new_options(&request_like, &response, SystemTime::now(), self.options);

        response.set_cache_status(lookup_status, CacheStatus::Miss, None);

        if matches!(request_like.method, Method::GET | Method::HEAD)
            && response.status().is_success()
            && policy.is_storable()
        {
            let (parts, body) = response.into_parts();
            return match self.storage.store(key.clone(), parts, body, policy).await {
                Ok(response) => Ok(response),
                Err(e) => {
                    debug!(
                        method = request_like.method.as_str(),
                        scheme = request_like.uri.scheme_str(),
                        authority = request_like.uri.authority().map(Authority::as_str),
                        path = request_like.uri.path(),
                        key,
                        error = format!("{e:?}"),
                        "failed to store response"
                    );
                    Err(e)
                }
            };
        }

        debug!(
            method = request_like.method.as_str(),
            scheme = request_like.uri.scheme_str(),
            authority = request_like.uri.authority().map(Authority::as_str),
            path = request_like.uri.path(),
            key,
            status = response.status().as_u16(),
            "response is not cacheable"
        );

        if !request_like.method.is_safe() {
            // If the request is not safe, assume the resource has been modified and delete
            // any cached responses we may have for HEAD/GET
            for method in [Method::HEAD, Method::GET] {
                let key = storage_key(&method, &request_like.uri, &request_like.headers);
                if let Err(e) = self.storage.delete(&key).await {
                    debug!(
                        method = method.as_str(),
                        scheme = request_like.uri.scheme_str(),
                        authority = request_like.uri.authority().map(Authority::as_str),
                        path = request_like.uri.path(),
                        key,
                        error = format!("{e:?}"),
                        "failed to put response into storage"
                    );
                }
            }
        }

        Ok(response.map(CacheBody::from_upstream))
    }

    /// Performs a conditional send to upstream.
    ///
    /// If a cached request is still fresh, it is returned.
    ///
    /// If a cached request is stale, an attempt is made to revalidate it.
    async fn conditional_send_upstream<B: Body + Send>(
        &self,
        key: String,
        request: impl Request<B>,
        mut stored: StoredResponse<B>,
    ) -> Result<Response<CacheBody<B>>> {
        let request_like = RequestLike::new(&request);

        let mut headers = match stored
            .policy
            .before_request(&request_like, SystemTime::now())
        {
            BeforeRequest::Fresh(parts) => {
                // The cached response is still fresh, return it
                debug!(
                    method = request_like.method.as_str(),
                    scheme = request_like.uri.scheme_str(),
                    authority = request_like.uri.authority().map(Authority::as_str),
                    path = request_like.uri.path(),
                    key,
                    digest = stored.digest,
                    "response is still fresh: responding with body from storage"
                );

                stored.response.extend_headers(parts.headers);
                stored.response.set_cache_status(
                    CacheLookupStatus::Hit,
                    CacheStatus::Hit,
                    Some(&stored.digest),
                );
                return Ok(stored.response);
            }
            BeforeRequest::Stale {
                request: http::request::Parts { headers, .. },
                matches,
            } => {
                // Cached response is stale and needs to be revalidated
                if matches { Some(headers) } else { None }
            }
        };

        debug!(
            method = request_like.method.as_str(),
            scheme = request_like.uri.scheme_str(),
            authority = request_like.uri.authority().map(Authority::as_str),
            path = request_like.uri.path(),
            key,
            "response is stale: sending request upstream for revalidation"
        );

        // Invoke the revalidation hook if the request will use different headers
        if let Some(headers) = &mut headers
            && let Some(hook) = &self.hook
        {
            hook(&request_like, headers)?;
        }

        // Revalidate the request
        match request.send(headers).await {
            Ok(response) if response.status().is_success() => {
                debug!(
                    method = request_like.method.as_str(),
                    scheme = request_like.uri.scheme_str(),
                    authority = request_like.uri.authority().map(Authority::as_str),
                    path = request_like.uri.path(),
                    key,
                    "server responded with a new response"
                );

                // The server responded with the body, the cached body is no longer valid
                let policy = CachePolicy::new_options(
                    &request_like,
                    &response,
                    SystemTime::now(),
                    self.options,
                );

                let (parts, body) = response.into_parts();
                match self.storage.store(key.clone(), parts, body, policy).await {
                    Ok(mut response) => {
                        response.set_cache_status(CacheLookupStatus::Hit, CacheStatus::Miss, None);
                        Ok(response)
                    }
                    Err(e) => {
                        debug!(
                            method = request_like.method.as_str(),
                            scheme = request_like.uri.scheme_str(),
                            authority = request_like.uri.authority().map(Authority::as_str),
                            path = request_like.uri.path(),
                            key,
                            error = format!("{e:?}"),
                            "failed to put response into cache storage"
                        );
                        Err(e)
                    }
                }
            }
            Ok(response) if response.status() == StatusCode::NOT_MODIFIED => {
                debug!(
                    method = request_like.method.as_str(),
                    scheme = request_like.uri.scheme_str(),
                    authority = request_like.uri.authority().map(Authority::as_str),
                    path = request_like.uri.path(),
                    key,
                    "server responded with a not modified status"
                );

                // The server informed us that our response hasn't been modified
                // Note that the response body for this code is always empty
                match stored
                    .policy
                    .after_response(&request_like, &response, SystemTime::now())
                {
                    AfterResponse::Modified(..) => {
                        // Certain cloud providers (e.g. Azure Blob Storage) do not correctly
                        // implement 304 responses. Specifically, they aren't returning the same
                        // headers that a 2XX response would have. This causes the HTTP cache
                        // implementation to effectively say the body needs updating when it does
                        // not. Instead, we'll return a stale response with a warning; this will
                        // cause unnecessary revalidation requests in the future, however, because
                        // we are not storing an updated cache policy object.

                        debug!(
                            method = request_like.method.as_str(),
                            scheme = request_like.uri.scheme_str(),
                            authority = request_like.uri.authority().map(Authority::as_str),
                            path = request_like.uri.path(),
                            key,
                            "cached response was considered modified despite revalidation \
                             replying with not modified"
                        );

                        Self::prepare_stale_response(
                            &request_like.uri,
                            &mut stored.response,
                            &stored.digest,
                        );
                        Ok(stored.response)
                    }
                    AfterResponse::NotModified(policy, parts) => {
                        stored.response.extend_headers(parts.headers);

                        let (parts, body) = stored.response.into_parts();
                        match self
                            .storage
                            .put(&key, &parts, &policy, &stored.digest)
                            .await
                        {
                            Ok(_) => {
                                debug!(
                                    method = request_like.method.as_str(),
                                    scheme = request_like.uri.scheme_str(),
                                    authority = request_like.uri.authority().map(Authority::as_str),
                                    path = request_like.uri.path(),
                                    key,
                                    digest = stored.digest,
                                    "response updated in cache successfully"
                                );

                                // Response was updated and the body comes from storage
                                let mut cached_response = Response::from_parts(parts, body);
                                cached_response.set_cache_status(
                                    CacheLookupStatus::Hit,
                                    CacheStatus::Hit,
                                    Some(&stored.digest),
                                );
                                Ok(cached_response)
                            }
                            Err(e) => {
                                debug!(
                                    method = request_like.method.as_str(),
                                    scheme = request_like.uri.scheme_str(),
                                    authority = request_like.uri.authority().map(Authority::as_str),
                                    path = request_like.uri.path(),
                                    key,
                                    error = format!("{e:?}"),
                                    "failed to put response into cache storage"
                                );
                                Err(e)
                            }
                        }
                    }
                }
            }
            Ok(response)
                if response.status().is_server_error() && !stored.response.must_revalidate() =>
            {
                debug!(
                    method = request_like.method.as_str(),
                    scheme = request_like.uri.scheme_str(),
                    authority = request_like.uri.authority().map(Authority::as_str),
                    path = request_like.uri.path(),
                    key,
                    stored.digest,
                    "failed to revalidate response: serving potentially stale body from storage \
                     with a warning"
                );

                Self::prepare_stale_response(
                    &request_like.uri,
                    &mut stored.response,
                    &stored.digest,
                );
                Ok(stored.response)
            }
            Ok(mut response) => {
                debug!(
                    method = request_like.method.as_str(),
                    scheme = request_like.uri.scheme_str(),
                    authority = request_like.uri.authority().map(Authority::as_str),
                    path = request_like.uri.path(),
                    key,
                    "failed to revalidate response: returning response from server uncached"
                );

                // Otherwise, don't serve the cached response at all
                response.set_cache_status(CacheLookupStatus::Hit, CacheStatus::Miss, None);
                Ok(response.map(CacheBody::from_upstream))
            }
            Err(e) => {
                if stored.response.must_revalidate() {
                    Err(e)
                } else {
                    debug!(
                        method = request_like.method.as_str(),
                        scheme = request_like.uri.scheme_str(),
                        authority = request_like.uri.authority().map(Authority::as_str),
                        path = request_like.uri.path(),
                        key,
                        stored.digest,
                        "failed to revalidate response: serving potentially stale body from \
                         storage with a warning"
                    );

                    Self::prepare_stale_response(
                        &request_like.uri,
                        &mut stored.response,
                        &stored.digest,
                    );
                    Ok(stored.response)
                }
            }
        }
    }

    /// Prepares a stale response for sending back to the client.
    fn prepare_stale_response<B>(uri: &Uri, response: &mut Response<CacheBody<B>>, digest: &str) {
        // If the server failed to give us a response, add the required warning to the
        // cached response:
        //   111 Revalidation failed
        //   MUST be included if a cache returns a stale response
        //   because an attempt to revalidate the response failed,
        //   due to an inability to reach the server.
        // (https://tools.ietf.org/html/rfc2616#section-14.46)
        response.add_warning(uri, 111, "Revalidation failed");
        response.set_cache_status(CacheLookupStatus::Hit, CacheStatus::Hit, Some(digest));
    }
}