Skip to content

Commit

Permalink
fix(cache): Cache panics with error handling #365 (#366)
Browse files Browse the repository at this point in the history
* fix(cache): Cache panics with error handling #365

* fix cahce panic
  • Loading branch information
chrislearn authored Aug 13, 2023
1 parent e8d1a53 commit 994646e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
16 changes: 11 additions & 5 deletions crates/cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ pub trait CacheStore: Send + Sync + 'static {
/// [`ResBody`] has Stream type, which is not `Send + Sync`, so we need to convert it to `CachedBody`.
/// If response's body is ['ResBody::Stream`], it will not be cached.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CachedBody {
/// None body.
None,
Expand Down Expand Up @@ -283,12 +284,17 @@ where
Some(cache) => cache,
None => {
ctrl.call_next(req, depot, res).await;
if !res.body.is_stream() {
if !res.body.is_stream() && !res.body.is_error() {
let headers = res.headers().clone();
let body: CachedBody = (&res.body).try_into().unwrap();
let cached_data = CachedEntry::new(res.status_code, headers, body);
if let Err(e) = self.store.save_entry(key, cached_data).await {
tracing::error!(error = ?e, "cache failed");
let body = TryInto::<CachedBody>::try_into(&res.body);
match body {
Ok(body) => {
let cached_data = CachedEntry::new(res.status_code, headers, body);
if let Err(e) = self.store.save_entry(key, cached_data).await {
tracing::error!(error = ?e, "cache failed");
}
}
Err(e) => tracing::error!(error = ?e, "cache failed"),
}
}
return;
Expand Down
6 changes: 6 additions & 0 deletions crates/core/src/http/body/res.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ impl ResBody {
ResBody::Error(_) => None,
}
}

/// Set body to none and returns current body.
#[inline]
pub fn take(&mut self) -> ResBody {
std::mem::replace(self, ResBody::None)
}
}

impl Stream for ResBody {
Expand Down

0 comments on commit 994646e

Please sign in to comment.