Repository navigation
feat(cache): stream HttpOrigin + async-compression decode (#271 PR3/4) - #515
Conversation
There was a problem hiding this comment.
Pull request overview
This PR (stack 3/4 for #271) completes the HTTP leg of cache pull-through streaming by turning HttpOrigin::fetch into a chunked stream and switching gzip/zstd decoding from sync Read-based decompression to an async-compression streaming pipeline, so large origin responses no longer require buffering the full encoded/decoded body in memory.
Changes:
- Stream
HttpOrigin::fetchend-to-end (reqwest chunk loop → stream adapter → optional async gzip/zstd decode → engineadd_stream). - Add an engine-side error “side-channel” to preserve mid-stream
io::Errorcauses thatiroh-blobsotherwise swallows. - Update tests and workspace deps to reflect the new streaming/decompression behavior (
async-compressionruntime;flate2/zstdkept for test fixtures only).
Reviewed changes
Copilot reviewed 6 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/cache/src/origin/http.rs | Reworks HTTP fetch to stream chunks and optionally decode gzip/zstd via async-compression without buffering whole bodies. |
| crates/cache/src/engine.rs | Captures mid-stream errors via side-channel, improves surfacing of upstream failures, and adjusts stream-capping adapter behavior. |
| crates/cache/src/origin/fs.rs | Makes stream wrappers terminate deterministically after an error to avoid re-poll/hang edge cases. |
| crates/cache/tests/pull_through.rs | Updates the decompression-bomb assertion to match the new “decoded bytes cap in engine” behavior/message. |
| crates/cache/Cargo.toml | Moves flate2/zstd to dev-deps and adds async-compression for runtime streaming decode. |
| Cargo.toml | Adds workspace dependency for async-compression. |
| Cargo.lock | Locks new transitive deps for async-compression and related updates. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // `anyhow::Error::msg(chain_msg)` keeps the Display | ||
| // honest; we couldn't preserve typed downcast for an | ||
| // inner we can't name. | ||
| let _ = other_box; | ||
| return anyhow::Error::msg(chain_msg); |
| /// Adapter that bumps the `pull_through_bytes` metric per chunk, | ||
| /// aborts mid-stream if cumulative bytes exceed `max_bytes`, and | ||
| /// captures any `io::Error` it observes into `captured_err` before | ||
| /// passing it along. |
| // `Option` so polling stops once we yield an `Err`. Polling a | ||
| // stream after a terminal error is undefined; without the | ||
| // sentinel, iroh-blobs' `add_stream` can hang because its | ||
| // internal `data.next().await` re-enters our adapter, which | ||
| // re-polls the already-errored upstream. |
| .and_then(|l| usize::try_from(l).ok()) | ||
| .map_or(0, |l| min(l, INITIAL_CAPACITY_HINT_CAP)); | ||
| // Build the body stream: | ||
| // 1. reqwest::Response::bytes_stream() yields encoded chunks |
There was a problem hiding this comment.
Code Review
This pull request refactors the HTTP origin to use streaming decompression via the async-compression crate, replacing the previous buffered synchronous approach. It introduces a side-channel mechanism in the cache engine to capture and propagate typed errors from the stream that were previously swallowed. Feedback focused on optimizing error handling by deferring string allocations and avoiding redundant error messages, as well as ensuring that metrics accurately reflect resource usage by counting bytes even when a size limit is breached.
| fn flatten_error_chain(err: &(dyn std::error::Error + 'static)) -> String { | ||
| let mut messages: Vec<String> = Vec::new(); | ||
| let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err); | ||
| while let Some(e) = current { | ||
| messages.push(e.to_string()); | ||
| current = e.source(); | ||
| } | ||
| messages.join(": ") | ||
| } |
There was a problem hiding this comment.
The flatten_error_chain function produces redundant messages when used with error types (like those from thiserror) that already include their source in their Display implementation. For example, OriginError::DecompressionFailed includes its source, so flattening will repeat the source message. Consider relying on the canonical Display implementation to ensure consistency and avoid redundancy.
References
- Prefer using canonical representations, such as an existing Display implementation, to ensure consistency and avoid redundant error messaging.
| fn build_origin_anyhow_from_io(upstream: std::io::Error) -> anyhow::Error { | ||
| // Extract the message NOW because `into_inner()` consumes the | ||
| // io::Error and the message lives on the wrapped error's | ||
| // Display, which we'll lose access to once we drill into the | ||
| // typed inner. | ||
| let chain_msg = flatten_error_chain(&upstream); | ||
|
|
||
| // Try to peel off the typed inner. `io::Error::into_inner()` | ||
| // returns `Option<Box<dyn Error + Send + Sync>>`; the `Box::downcast` | ||
| // on the trait object recovers the concrete `OriginError` if | ||
| // the adapter packed one in via `typed_decoder_error`. | ||
| let inner_opt = upstream.into_inner(); | ||
| if let Some(boxed) = inner_opt { | ||
| match boxed.downcast::<OriginError>() { | ||
| Ok(typed) => return anyhow::Error::from(*typed), | ||
| Err(other_box) => { | ||
| // Inner wasn't a typed `OriginError` — but it's still | ||
| // some other error worth keeping in the chain. | ||
| // `anyhow::Error::msg(chain_msg)` keeps the Display | ||
| // honest; we couldn't preserve typed downcast for an | ||
| // inner we can't name. | ||
| let _ = other_box; | ||
| return anyhow::Error::msg(chain_msg); | ||
| } | ||
| } | ||
| } | ||
| // No inner at all (io::Error from a raw kind, no wrapped | ||
| // payload). The flattened message is all we have. | ||
| anyhow::Error::msg(chain_msg) | ||
| } |
There was a problem hiding this comment.
The flatten_error_chain call is performed before checking if the error can be downcast to OriginError. Since flatten_error_chain involves string allocations and joining, it should be deferred until it's actually needed in the fallback paths. This avoids unnecessary work when a typed OriginError is successfully recovered.
fn build_origin_anyhow_from_io(upstream: std::io::Error) -> anyhow::Error {
let inner_opt = upstream.into_inner();
if let Some(boxed) = inner_opt {
match boxed.downcast::<OriginError>() {
Ok(typed) => return anyhow::Error::from(*typed),
Err(other_box) => {
let chain_msg = flatten_error_chain(&*other_box);
return anyhow::Error::msg(chain_msg);
}
}
}
anyhow::Error::msg(upstream.to_string())
}| let new_total = total.saturating_add(chunk.len() as u64); | ||
| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "origin stream exceeded max_blob_bytes={max_bytes} mid-flight" | ||
| )); | ||
| return Some((Err(err), (s, total, metrics))); | ||
| *captured.lock().unwrap_or_else(PoisonError::into_inner) = Some(err); | ||
| return None; | ||
| } | ||
| if let Some(m) = metrics.as_ref() { | ||
| m.pull_through_bytes | ||
| .inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | ||
| } |
There was a problem hiding this comment.
The pull_through_bytes metric is incremented only after the max_bytes check. If a chunk causes the total to exceed the limit, it is rejected and not counted. To accurately reflect origin resource usage and avoid inaccurate statistics, the metric should be incremented for all bytes received once the retrieval has started, even if the operation eventually fails due to size limits.
Ok(chunk) => {
let chunk_len = u64::try_from(chunk.len()).unwrap_or(u64::MAX);
if let Some(m) = metrics.as_ref() {
m.pull_through_bytes.inc_by(chunk_len);
}
let new_total = total.saturating_add(chunk_len);
if new_total > max_bytes {
let err = std::io::Error::other(format!(
"origin stream exceeded max_blob_bytes={max_bytes} mid-flight"
));
*captured.lock().unwrap_or_else(PoisonError::into_inner) = Some(err);
return None;
}References
- Once retrieval has started, errors should not roll back counters to accurately reflect origin resource usage and avoid inaccurate statistics.
- Prefer streaming the response body with a running size cap to prevent Out-Of-Memory (OOM) conditions.
9c7a057 to
2464211
Compare
f5b1524 to
e286838
Compare
|
Force-pushed Implemented:
Did not change:
|
2464211 to
ed4d321
Compare
PR 3 of 4 for issue #271. Cuts HttpOrigin to true streaming end-to-end: the chunk-collecting `BytesMut` loop is replaced with `stream::unfold` over `resp.chunk()`, and gzip / zstd decoding moves from synchronous `flate2` / `zstd` over `Read` to `async-compression`'s `bufread` decoders layered through `tokio_util::io::{StreamReader, ReaderStream}`. What this PR achieves end-to-end (HttpOrigin → engine → store): - Per-fetch heap drops to chunk-size for both identity and compressed bodies. A 10 GB gzipped origin no longer pins 10 GB of process RSS through a `decompress_body` round-trip; decoded bytes flow straight into iroh-blobs' `add_stream`. - The `DECOMPRESS_BLOCKING_THRESHOLD` `spawn_blocking` shim and the `read_capped` synchronous decode loop are removed. async-compression decodes in poll-driven async chunks, no executor pin. - Decompression bombs are now caught by the engine's running cap on decoded bytes (`count_and_cap_stream`), not by a per-decoder cap (the `read_capped` mid-stream check). Same security posture, single cap layer. - Mid-stream stream errors (cap breach, idle timeout, decoder failure) flow through a side-channel (`Arc<Mutex<Option<io::Error>>>`) so the engine surfaces the actionable upstream message via `build_origin_anyhow_from_io`. Typed `OriginError::DecompressionFailed` is preserved on the chain via `io::Error::into_inner` + `Box::downcast`, so `origin_error_kind()` still recovers it for truncated / empty gzip bodies. Stream-after-error termination: `count_and_cap_stream` and `response_chunk_stream` both use the `Option<S>`-state-then-`None`- yield pattern so iroh-blobs' `add_stream` doesn't hang waiting for `Done` after a sender-drop. On upstream error we **yield None** (clean stream end) rather than `Err`; the engine reads from the side channel to surface the real failure instead of the partial-import's `HashMismatch`. The partial blob lands in the store as an unprotected `TempTag` and is reclaimed by iroh-blobs' GC. Workspace deps: - Add `async-compression` (gzip + zstd, tokio I/O bindings). - `flate2` and `zstd` move from `[dependencies]` to `[dev-dependencies]` on the cache crate (test fixtures still construct gzipped/zstd bodies; the runtime no longer touches them). Tests: - 141/141 cache unit + integration tests pass; 680/680 workspace tests pass. - `http_origin_rejects_decompression_bomb` updated: bomb is now rejected by the engine's `count_and_cap_stream` (single cap layer) rather than by the per-decoder `read_capped` cap. Same security guarantee, message check switched from "mid-stream" to "max_blob_bytes / mid-flight". Typed-downcast assertion removed because the cap fires at the engine layer. - `http_origin_truncated_gzip_surfaces_decompression_failed` and `http_origin_empty_gzip_body_surfaces_decompression_failed` keep their typed `DecompressionFailed` assertion — the engine's `build_origin_anyhow_from_io` peels the typed inner out so the chain walk still finds it. - All headers-phase typed-error tests (`UnsupportedEncoding`, multi-encoding rejection, malformed encoding) pass unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
e286838 to
ab1fa06
Compare
Coverage reportTotal: 88.19% (was 87.90%, ▲ +0.29%) — 12115/13737 lines
History
|
Summary
PR 3 of 4 for issue #271. Stacked on #514 (PR 2).
HttpOrigin::fetchnow streams viastream::unfoldoverresp.chunk()with the per-chunk idle timeout and per-chunk encoded-size cap preserved as adapter logic. Decompression replaces the synchronousflate2/zstdReadround-trip withasync-compression'stokio::bufread::{GzipDecoder, ZstdDecoder}layered throughtokio_util::io::{StreamReader, ReaderStream}. Thedecompress_body,read_capped, andDECOMPRESS_BLOCKING_THRESHOLDpaths are gone.add_streamwith per-fetch heap bounded by the decoder's working set.Key new mechanics
Side-channel for typed errors. iroh-blobs'
add_streamswallows the upstreamio::Error(the inner async block uses?and the outertokio::join!discards the failure) and can also hang waiting forDoneafter a sender-drop. The fix:count_and_cap_streamwrites the upstreamio::Errorto anArc<Mutex<Option<io::Error>>>side channel, then yieldsNone(clean stream end) soadd_streamsendsDonecleanly; the import commits a partial blob with the wrong hash. The engine consults the side channel before checking iroh-blobs' result and surfaces the real failure (build_origin_anyhow_from_io). The partial blob is left as an unprotectedTempTagand reclaimed by iroh-blobs' GC.Typed-error preservation.
io::Error::source()returnsinner.source(), notSome(&inner)— so a typedOriginError::DecompressionFailedpacked insideio::Error::new(kind, typed)is invisible to achain().downcast_ref::<OriginError>()walk. The fix inbuild_origin_anyhow_from_io: pull the typed inner out viainto_inner()+Box::downcast::<OriginError>()before constructing the anyhow chain. When successful, the typed variant becomes the deepest error and is recoverable byCacheError::origin_error_kind. Truncated and empty gzip body tests still see typedDecompressionFailed.Behavioural changes worth flagging
count_and_cap_stream) rather than by a per-decoder cap (the oldread_capped). Same security guarantee, single cap layer. The corresponding test was updated to assert on the new error message ("max_blob_bytes / mid-flight") and no longer requires a typedDecompressionFaileddowncast (the cap fires at the engine layer, before the decoder fails).reqwesterrors are no longer retried. Pre-cache: FilesystemOrigin.fetch reads the entire blob into memory before returning Bytes, preventing streaming delivery to the client for large blobs #271 the full body was collected insidefetch, so retry saw mid-body errors. After this PR they surface to the engine afterretry_fetchhas already returnedOk. A separate request triggers a fresh retry budget. Acceptable for memory savings; mid-stream retry would need engine-level abort-and-restart logic on the partially-imported tag and is out of scope.Workspace deps
async-compression = { version = "0.4", features = ["tokio", "gzip", "zstd"] }(workspace).flate2,zstdfrom[dependencies]to[dev-dependencies]on the cache crate. Test fixtures still construct gzipped / zstd bodies; the runtime no longer touches them.Test plan
cargo build --workspace— cleancargo clippy --workspace --all-targets— no warningscargo nextest run -p decdn-cache— 141/141 passcargo nextest run— 680/680 passcargo fmt -- --check— cleancargo deny check— advisories / bans / licenses / sources OKpre-commit run --all-files— all hooks passDecompressionFailedassertion still holds for truncated and empty gzip body testsUnsupportedEncoding, multi-encoding rejection, malformed encoding) unchanged🤖 Generated with Claude Code