witchcraft_server/service/
no_caching.rs

1// Copyright 2022 Palantir Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use crate::service::{Layer, Service};
15use http::header::{Entry, CACHE_CONTROL};
16use http::{HeaderValue, Method, Request, Response};
17
18#[allow(clippy::declare_interior_mutable_const)]
19const DO_NOT_CACHE: HeaderValue = HeaderValue::from_static("no-cache, no-store, must-revalidate");
20
21/// A layer which disables caching of responses to GET requests that do not already contain a `Cache-Control` header.
22pub struct NoCachingLayer;
23
24impl<S> Layer<S> for NoCachingLayer {
25    type Service = NoCachingService<S>;
26
27    fn layer(self, inner: S) -> Self::Service {
28        NoCachingService { inner }
29    }
30}
31
32pub struct NoCachingService<S> {
33    inner: S,
34}
35
36impl<S, B1, B2> Service<Request<B1>> for NoCachingService<S>
37where
38    S: Service<Request<B1>, Response = Response<B2>> + Sync,
39    B1: Send,
40{
41    type Response = S::Response;
42
43    async fn call(&self, req: Request<B1>) -> Self::Response {
44        let is_get = req.method() == Method::GET;
45
46        let mut response = self.inner.call(req).await;
47        if is_get {
48            if let Entry::Vacant(e) = response.headers_mut().entry(CACHE_CONTROL) {
49                e.insert(DO_NOT_CACHE);
50            }
51        }
52
53        response
54    }
55}