forked from 06chaynes/http-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
327 lines (314 loc) · 10.5 KB
/
lib.rs
File metadata and controls
327 lines (314 loc) · 10.5 KB
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
#![forbid(unsafe_code, future_incompatible)]
#![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
nonstandard_style,
unused_qualifications,
unused_import_braces,
unused_extern_crates,
trivial_casts,
trivial_numeric_casts
)]
#![allow(clippy::doc_lazy_continuation)]
#![cfg_attr(docsrs, feature(doc_cfg))]
//! HTTP caching middleware for the surf HTTP client.
//!
//! This crate provides middleware for the surf HTTP client that implements HTTP caching
//! according to RFC 7234. It supports various cache modes and storage backends.
//!
//! ## Basic Usage
//!
//! Add HTTP caching to your surf client:
//!
//! ```no_run
//! use surf::Client;
//! use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
//! use macro_rules_attribute::apply;
//! use smol_macros::main;
//!
//! #[apply(main!)]
//! async fn main() -> surf::Result<()> {
//! let client = surf::Client::new()
//! .with(Cache(HttpCache {
//! mode: CacheMode::Default,
//! manager: CACacheManager::new("./cache".into(), true),
//! options: Default::default(),
//! }));
//!
//! // This request will be cached according to response headers
//! let mut res = client.get("https://httpbin.org/cache/60").await?;
//! println!("Response: {}", res.body_string().await?);
//!
//! // Subsequent identical requests may be served from cache
//! let mut cached_res = client.get("https://httpbin.org/cache/60").await?;
//! println!("Cached response: {}", cached_res.body_string().await?);
//!
//! Ok(())
//! }
//! ```
//!
//! ## Cache Modes
//!
//! Control caching behavior with different modes:
//!
//! ```no_run
//! use surf::Client;
//! use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
//! use macro_rules_attribute::apply;
//! use smol_macros::main;
//!
//! #[apply(main!)]
//! async fn main() -> surf::Result<()> {
//! let client = surf::Client::new()
//! .with(Cache(HttpCache {
//! mode: CacheMode::ForceCache, // Cache everything, ignore headers
//! manager: CACacheManager::new("./cache".into(), true),
//! options: Default::default(),
//! }));
//!
//! // This will be cached even if headers say not to cache
//! let mut res = client.get("https://httpbin.org/uuid").await?;
//! println!("{}", res.body_string().await?);
//! Ok(())
//! }
//! ```
//!
//! ## In-Memory Caching
//!
//! Use the Moka in-memory cache:
//!
//! ```no_run
//! # #[cfg(feature = "manager-moka")]
//! use surf::Client;
//! # #[cfg(feature = "manager-moka")]
//! use http_cache_surf::{Cache, MokaManager, HttpCache, CacheMode};
//! # #[cfg(feature = "manager-moka")]
//! use http_cache_surf::MokaCache;
//! # #[cfg(feature = "manager-moka")]
//! use macro_rules_attribute::apply;
//! # #[cfg(feature = "manager-moka")]
//! use smol_macros::main;
//!
//! # #[cfg(feature = "manager-moka")]
//! #[apply(main!)]
//! async fn main() -> surf::Result<()> {
//! let client = surf::Client::new()
//! .with(Cache(HttpCache {
//! mode: CacheMode::Default,
//! manager: MokaManager::new(MokaCache::new(1000)), // Max 1000 entries
//! options: Default::default(),
//! }));
//!
//! let mut res = client.get("https://httpbin.org/cache/60").await?;
//! println!("{}", res.body_string().await?);
//! Ok(())
//! }
//! # #[cfg(not(feature = "manager-moka"))]
//! # fn main() {}
//! ```
//!
//! ## Custom Cache Keys
//!
//! Customize how cache keys are generated:
//!
//! ```no_run
//! use surf::Client;
//! use http_cache_surf::{Cache, CACacheManager, HttpCache, CacheMode};
//! use http_cache::HttpCacheOptions;
//! use std::sync::Arc;
//! use macro_rules_attribute::apply;
//! use smol_macros::main;
//!
//! #[apply(main!)]
//! async fn main() -> surf::Result<()> {
//! let options = HttpCacheOptions {
//! cache_key: Some(Arc::new(|parts: &http::request::Parts| {
//! // Include query parameters in cache key
//! format!("{}:{}", parts.method, parts.uri)
//! })),
//! ..Default::default()
//! };
//!
//! let client = surf::Client::new()
//! .with(Cache(HttpCache {
//! mode: CacheMode::Default,
//! manager: CACacheManager::new("./cache".into(), true),
//! options,
//! }));
//!
//! let mut res = client.get("https://httpbin.org/cache/60?param=value").await?;
//! println!("{}", res.body_string().await?);
//! Ok(())
//! }
//! ```
use std::convert::TryInto;
use std::str::FromStr;
use std::time::SystemTime;
use http::{
header::CACHE_CONTROL,
request::{self, Parts},
};
use http_cache::{
BadHeader, BoxError, CacheManager, CacheOptions, HitOrMiss, HttpResponse,
Middleware, Result, XCACHE, XCACHELOOKUP,
};
pub use http_cache::{CacheMode, HttpCache, HttpHeaders};
use http_cache_semantics::CachePolicy;
use http_types::{
headers::HeaderValue as HttpTypesHeaderValue,
Response as HttpTypesResponse, StatusCode as HttpTypesStatusCode,
Version as HttpTypesVersion,
};
use http_types::{Method as HttpTypesMethod, Request, Url};
use surf::{middleware::Next, Client};
// Re-export managers and cache types
#[cfg(feature = "manager-cacache")]
pub use http_cache::CACacheManager;
pub use http_cache::HttpCacheOptions;
pub use http_cache::ResponseCacheModeFn;
#[cfg(feature = "manager-moka")]
#[cfg_attr(docsrs, doc(cfg(feature = "manager-moka")))]
pub use http_cache::{MokaCache, MokaCacheBuilder, MokaManager};
#[cfg(feature = "rate-limiting")]
#[cfg_attr(docsrs, doc(cfg(feature = "rate-limiting")))]
pub use http_cache::rate_limiting::{
CacheAwareRateLimiter, DirectRateLimiter, DomainRateLimiter, Quota,
};
/// A wrapper around [`HttpCache`] that implements [`surf::middleware::Middleware`]
#[derive(Debug, Clone)]
pub struct Cache<T: CacheManager>(pub HttpCache<T>);
// Re-export unified error types from http-cache core
pub use http_cache::{BadRequest, HttpCacheError};
/// Implements ['Middleware'] for surf
pub(crate) struct SurfMiddleware<'a> {
pub req: Request,
pub client: Client,
pub next: Next<'a>,
}
#[async_trait::async_trait]
impl Middleware for SurfMiddleware<'_> {
fn is_method_get_head(&self) -> bool {
self.req.method() == HttpTypesMethod::Get
|| self.req.method() == HttpTypesMethod::Head
}
fn policy(&self, response: &HttpResponse) -> Result<CachePolicy> {
Ok(CachePolicy::new(&self.parts()?, &response.parts()?))
}
fn policy_with_options(
&self,
response: &HttpResponse,
options: CacheOptions,
) -> Result<CachePolicy> {
Ok(CachePolicy::new_options(
&self.parts()?,
&response.parts()?,
SystemTime::now(),
options,
))
}
fn update_headers(&mut self, parts: &Parts) -> Result<()> {
for header in parts.headers.iter() {
let value = match HttpTypesHeaderValue::from_str(header.1.to_str()?)
{
Ok(v) => v,
Err(_e) => return Err(Box::new(BadHeader)),
};
self.req.insert_header(header.0.as_str(), value);
}
Ok(())
}
fn force_no_cache(&mut self) -> Result<()> {
self.req.insert_header(CACHE_CONTROL.as_str(), "no-cache");
Ok(())
}
fn parts(&self) -> Result<Parts> {
let mut converted = request::Builder::new()
.method(self.req.method().as_ref())
.uri(self.req.url().as_str())
.body(())?;
{
let headers = converted.headers_mut();
for header in self.req.iter() {
headers.insert(
http::header::HeaderName::from_str(header.0.as_str())?,
http::HeaderValue::from_str(header.1.as_str())?,
);
}
}
Ok(converted.into_parts().0)
}
fn url(&self) -> Result<Url> {
Ok(self.req.url().clone())
}
fn method(&self) -> Result<String> {
Ok(self.req.method().as_ref().to_string())
}
async fn remote_fetch(&mut self) -> Result<HttpResponse> {
let url = self.req.url().clone();
let mut res =
self.next.run(self.req.clone().into(), self.client.clone()).await?;
let mut headers = HttpHeaders::new();
for header in res.iter() {
headers.insert(
header.0.as_str().to_owned(),
header.1.as_str().to_owned(),
);
}
let status = res.status().into();
let version = res.version().unwrap_or(HttpTypesVersion::Http1_1);
let body: Vec<u8> = res.body_bytes().await?;
Ok(HttpResponse {
body,
headers,
status,
url,
version: version.try_into()?,
})
}
}
fn to_http_types_error(e: BoxError) -> http_types::Error {
http_types::Error::from_str(500, format!("HTTP cache error: {e}"))
}
#[surf::utils::async_trait]
impl<T: CacheManager> surf::middleware::Middleware for Cache<T> {
async fn handle(
&self,
req: surf::Request,
client: Client,
next: Next<'_>,
) -> std::result::Result<surf::Response, http_types::Error> {
let req: Request = req.into();
let mut middleware = SurfMiddleware { req, client, next };
if self.0.can_cache_request(&middleware).map_err(to_http_types_error)? {
let res =
self.0.run(middleware).await.map_err(to_http_types_error)?;
let mut converted = HttpTypesResponse::new(HttpTypesStatusCode::Ok);
for header in &res.headers {
let val = HttpTypesHeaderValue::from_bytes(
header.1.as_bytes().to_vec(),
)?;
converted.insert_header(header.0.as_str(), val);
}
converted.set_status(res.status.try_into()?);
converted.set_version(Some(res.version.into()));
converted.set_body(res.body);
Ok(surf::Response::from(converted))
} else {
self.0
.run_no_cache(&mut middleware)
.await
.map_err(to_http_types_error)?;
let mut res = middleware
.next
.run(middleware.req.into(), middleware.client)
.await?;
let miss = HitOrMiss::MISS.to_string();
res.append_header(XCACHE, miss.clone());
res.append_header(XCACHELOOKUP, miss);
Ok(res)
}
}
}
#[cfg(test)]
mod test;