Repository navigation
refactor(cache): make Origin trait stream-shaped (#271 PR1/4) - #513
Conversation
Convert OriginFetch::Found(Bytes) to a streaming variant carrying a boxed Stream<io::Result<Bytes>> + size_hint so the engine can pipe origin bytes straight into iroh-blobs' add_stream in a follow-up. PR 1 is behavior- preserving: every adapter still buffers the full payload and wraps it via OriginFetch::found_one_shot, and the engine drains via collect_to_bytes before re-entering the existing size-cap → BLAKE3 → add_bytes flow. The new shape's bound (Send + Sync + 'static) is the one Blobs::add_stream demands, so PR 2 (FilesystemOrigin streaming) can hand the stream straight through without an adapter shim. PRs 2-4 cut each backend over to true chunked streaming and replace the engine's collect step with a tee'd add_stream + temp_tag-then-promote pattern. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Refactors the decdn-cache origin fetch interface to be stream-shaped (in preparation for true streaming pull-through in follow-up PRs addressing #271), while keeping current backends behaviorally equivalent by wrapping existing buffered Bytes payloads into a single-chunk stream.
Changes:
- Redefines
OriginFetch::Foundto carry{ stream, size_hint }and introducesOriginByteStream, plus helpersfound_one_shotandcollect_to_bytes. - Updates cache engine + all origin backends and test mocks to use the new stream-shaped
OriginFetch(viafound_one_shot) and adapts tests to drain streams withcollect_to_bytes. - Adds workspace dependencies
futures-utilandtokio-utilto support streaming primitives and upcomingAsyncRead↔Stream<Bytes>bridges.
Reviewed changes
Copilot reviewed 11 out of 12 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/metrics.rs | Updates origin test mock to return the new stream-shaped OriginFetch via found_one_shot. |
| crates/node/src/admin.rs | Updates admin test mocks to return stream-shaped OriginFetch via found_one_shot. |
| crates/cache/tests/s3_origin.rs | Adapts S3 origin tests to consume OriginFetch via collect_to_bytes. |
| crates/cache/tests/pull_through.rs | Updates pull-through test origins to return stream-shaped OriginFetch via found_one_shot. |
| crates/cache/src/origin/s3.rs | Wraps buffered S3 payload in found_one_shot (PR-1 shim). |
| crates/cache/src/origin/mod.rs | Introduces OriginByteStream, stream-shaped OriginFetch, and helper APIs (found_one_shot, collect_to_bytes). |
| crates/cache/src/origin/http.rs | Wraps buffered HTTP payload in found_one_shot (PR-1 shim). |
| crates/cache/src/origin/fs.rs | Wraps buffered filesystem payload in found_one_shot and updates tests to drain streams. |
| crates/cache/src/engine.rs | Switches pull-through to drain OriginFetch via collect_to_bytes (transitional buffered path). |
| crates/cache/Cargo.toml | Adds futures-util and tokio-util dependencies for streaming-related utilities. |
| Cargo.toml | Adds workspace dependency entries for futures-util and tokio-util. |
| Cargo.lock | Records dependency graph updates for the new crates. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| pub async fn collect_to_bytes(self) -> Result<Option<Bytes>, std::io::Error> { | ||
| use bytes::BytesMut; | ||
| use futures_util::StreamExt; | ||
| match self { | ||
| Self::NotFound => Ok(None), | ||
| Self::Found { | ||
| mut stream, | ||
| size_hint, | ||
| } => { | ||
| let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0); | ||
| let mut buf = BytesMut::with_capacity(cap); | ||
| while let Some(chunk) = stream.next().await { | ||
| buf.extend_from_slice(&chunk?); | ||
| } | ||
| Ok(Some(buf.freeze())) |
| /// Best-effort upfront size estimate from the adapter. Used by | ||
| /// the engine for short-circuit cap checks before reading the | ||
| /// first byte; the engine still re-checks the running total as | ||
| /// chunks arrive. |
| /// Errors flow as `io::Error` so the engine can collapse mid-stream | ||
| /// failures into [`OriginPullError::Permanent`] without re-classifying | ||
| /// every adapter's native error type. Headers-phase classification stays | ||
| /// in each adapter (transient vs permanent) and is emitted before the | ||
| /// stream is constructed. |
There was a problem hiding this comment.
Code Review
This pull request introduces streaming primitives for origin pull-through by transitioning the OriginFetch result from a fully buffered Bytes payload to a chunked OriginByteStream. It adds futures-util and tokio-util dependencies and implements transitional shims across the filesystem, HTTP, and S3 origin backends to maintain compatibility while the engine is updated. Feedback includes a recommendation to cap initial buffer allocations to prevent memory exhaustion from large size hints and corrections for direct indexing violations that conflict with the project's anti-panic policies.
| let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0); | ||
| let mut buf = BytesMut::with_capacity(cap); |
There was a problem hiding this comment.
The size_hint is used directly for the initial allocation of BytesMut. If an origin provides an excessive hint (e.g., via a large Content-Length header), this could lead to memory exhaustion or a panic during allocation. It is safer to cap the initial capacity and let the buffer grow as needed, similar to the implementation in HttpOrigin.
| let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0); | |
| let mut buf = BytesMut::with_capacity(cap); | |
| let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0); | |
| let mut buf = BytesMut::with_capacity(cap.min(1024 * 1024)); |
References
- When implementing origin fetch logic, prefer streaming the response body with a running size cap instead of buffering the entire payload into memory to prevent Out-Of-Memory (OOM) conditions, especially for chunked responses that may omit a
Content-Lengthheader. - When reading files with a maximum size limit, bound the read operation at the I/O layer using
file.take(max_bytes.saturating_add(1))to prevent Time-of-Check to Time-of-Use (TOCTOU) vulnerabilities if the file grows mid-read. Additionally, cap the initialVec::with_capacityallocation hint to a reasonable constant (e.g., 1 MiB) to avoid large up-front memory commitments for potentially very large files, while still allowing the buffer to grow as needed. - Avoid panics when converting file sizes (u64) to
usizeforVec::with_capacity. Useusize::try_fromto handle potential overflows gracefully as a typed error, especially on systems with smaller address spaces or whenmax_bytesis very large.
| .collect_to_bytes() | ||
| .await? | ||
| .ok_or_else(|| anyhow::anyhow!("expected Found, got NotFound"))?; | ||
| anyhow::ensure!(&bytes[..] == payload, "got: {bytes:?}"); |
There was a problem hiding this comment.
Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.
| anyhow::ensure!(&bytes[..] == payload, "got: {bytes:?}"); | |
| anyhow::ensure!(bytes == payload, "got: {bytes:?}"); |
References
- To comply with the anti-panic policy which denies
clippy::indexing_slicing, use.get()withunwrap_oror other safe methods for slicing instead of direct indexing ([]).
| .collect_to_bytes() | ||
| .await? | ||
| .ok_or_else(|| anyhow::anyhow!("expected Found"))?; | ||
| anyhow::ensure!(&bytes[..] == payload); |
There was a problem hiding this comment.
Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.
| anyhow::ensure!(&bytes[..] == payload); | |
| anyhow::ensure!(bytes == payload); |
References
- To comply with the anti-panic policy which denies
clippy::indexing_slicing, use.get()withunwrap_oror other safe methods for slicing instead of direct indexing ([]).
| .collect_to_bytes() | ||
| .await? | ||
| .ok_or_else(|| anyhow::anyhow!("expected Found"))?; | ||
| anyhow::ensure!(&bytes[..] == payload); |
There was a problem hiding this comment.
Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.
| anyhow::ensure!(&bytes[..] == payload); | |
| anyhow::ensure!(bytes == payload); |
References
- To comply with the anti-panic policy which denies
clippy::indexing_slicing, use.get()withunwrap_oror other safe methods for slicing instead of direct indexing ([]).
Coverage reportTotal: 87.83% (was 87.90%, ▼ 0.07%) — 11963/13621 lines
History
|
Addressing review feedback on #513: - `OriginFetch::collect_to_bytes`: cap the upfront `BytesMut::with_capacity` hint at 1 MiB regardless of `size_hint`. A hostile origin advertising `Content-Length: 10 TiB` would otherwise trigger a huge alloc before any byte of the body arrives. The buffer still grows incrementally past the cap; engine's running cap on streamed bytes catches the actual overrun. Mirrors the pre-existing `INITIAL_READ_CAP_HINT` from `FilesystemOrigin`. - `OriginByteStream` doc: clarify that `io::Error` stream items do NOT feed `retry_fetch`'s transient/permanent classification — retry runs around `fetch`, so post-fetch stream errors surface via `CacheError::OriginError` without retry. (Copilot caught a stale description that suggested otherwise.) - `OriginFetch::Found` doc: spell out that PR 1 still drains the stream via `collect_to_bytes` before re-entering the buffered `add_bytes` path; memory savings only land in PR 2 onward. The `size_hint` short-circuit is also a PR 2 feature. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Triaged review feedback. Pushed Implemented:
Pushed back on:
Did not change:
|
Summary
PR 1 of 4 for issue #271 (cache: FilesystemOrigin.fetch reads the entire blob into memory before returning Bytes). Behavior-preserving trait shape change so PRs 2-4 can cut each backend over to true streaming without re-rolling the trait once per backend.
OriginFetch::Found(Bytes)→OriginFetch::Found { stream: OriginByteStream, size_hint: Option<u64> }whereOriginByteStream = Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send + Sync + 'static>>— exactly the boundiroh_blobs::api::blobs::Blobs::add_streamrequires.Bytespayload via the newOriginFetch::found_one_shot(bytes)constructor (single-chunkstream::once).pull_throughdrains the stream viaOriginFetch::collect_to_bytesbefore re-entering the existing size-cap → BLAKE3 →add_bytespath. PR 2 replaces that collect step with a tee'dadd_streamand drops the explicit BLAKE3 verification.futures-util(already transitive via reqwest) andtokio-util(PR 2'sReaderStreamsource). Both MIT/Apache;cargo denyclean.What this PR does NOT do
engine.get(hash) -> Bytes. Stream-shapedget()is in scope for Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317 (cdn/client/v1 paid delivery).Test plan
cargo build— workspace builds cleancargo clippy --workspace --all-targets— no new warningscargo nextest run -p decdn-cache— 139/139 passcargo nextest run— 678/678 passcargo fmt -- --check— cleancargo deny check— advisories / bans / licenses / sources all OKpre-commit run --all-files— all hooks passCloses part of #271. Follow-ups: PR 2 (FilesystemOrigin), PR 3 (HttpOrigin + async-compression), PR 4 (S3Origin).
🤖 Generated with Claude Code