Repository navigation
feat(cache): add cache engine with HTTP + filesystem origin adapters - #232
Conversation
Implements the cache engine scaffolding so `cdn/client/v1` and gossip `popular_hashes`/`LoadHint` have a substrate to build on. - `CacheEngine` wraps `iroh_blobs::store::fs::FsStore`; `get` serves local hits and otherwise pulls via a configured `Origin`, BLAKE3-verifies the bytes, and inserts them before returning. - `Origin` trait + `HttpOrigin` (reqwest, 30s timeout, content-length pre-check). S3/R2/B2 backends are a follow-up. - Typed `CacheError` (NotFound, HashMismatch, BlobTooLarge, NoOrigin, OriginError, Store) — mismatched bytes never reach the store. - Config surface: `[cache] origin_url`, `--origin-url`, `DECDN_ORIGIN_URL`. Node runtime builds and holds the engine so the next PR's handler can consume it. Leaf crate per ADR 023: no mode branching here. Eviction, streaming reads, and node-to-node pull-through via `cdn/client/v1` are deferred. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a cache engine for the deCDN project, utilizing iroh-blobs for local storage and providing an HTTP origin backend for pull-through on cache misses. It includes the core engine logic, error handling, configuration updates to support an origin URL, and integration into the node runtime. Feedback focuses on potential memory issues with large blobs, the thundering herd problem during concurrent fetches, and the adequacy of default request timeouts for large transfers.
There was a problem hiding this comment.
Pull request overview
This PR turns crates/cache into a working MVP cache engine built on iroh_blobs::store::fs::FsStore, adds an Origin abstraction with an HTTP pull-through backend, and wires cache initialization + origin_url configuration into the node runtime.
Changes:
- Implement
decdn_cache::CacheEnginewith pull-through on miss, BLAKE3 verification, and structuredCacheErrors. - Add
Origintrait plusHttpOrigin(reqwest + rustls, timeout, Content-Length pre-check) and integration tests using wiremock. - Extend node config/CLI with
[cache] origin_url/--origin-url/DECDN_ORIGIN_URL, and initialize the cache engine during runtime startup.
Reviewed changes
Copilot reviewed 15 out of 16 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/cache/src/engine.rs | Adds CacheEngine (FsStore + optional origin) with pull-through, size checks, and hash verification. |
| crates/cache/src/origin/mod.rs | Introduces Origin trait and OriginFetch result type. |
| crates/cache/src/origin/http.rs | Implements HTTP origin fetch logic (URL join, timeout, status handling, Content-Length check). |
| crates/cache/src/error.rs | Defines CacheError variants used by the engine/origin wiring. |
| crates/cache/src/lib.rs | Updates crate docs and re-exports the new public API surface. |
| crates/cache/tests/pull_through.rs | Adds end-to-end integration tests for miss→pull→cache hit, hash mismatch, 404, oversize, and no-origin. |
| crates/cache/Cargo.toml | Adds reqwest + test dependencies for the cache crate. |
| crates/node/src/runtime/mod.rs | Builds and logs cache engine at runtime startup (kept alive for upcoming handler work). |
| crates/node/src/config/types.rs | Adds cache.origin_url to TOML config types. |
| crates/node/src/config/resolved.rs | Adds resolved origin_url field to cache config. |
| crates/node/src/config/mod.rs | Resolves origin_url from CLI/file config and updates config tests. |
| crates/node/src/cli/run.rs | Adds --origin-url / DECDN_ORIGIN_URL CLI/env support. |
| crates/node/tests/config_validate.rs | Updates sample resolved config to include origin_url: None. |
| crates/node/Cargo.toml | Switches tempfile dev-dep to workspace-managed version. |
| Cargo.toml | Adds workspace deps for reqwest, tempfile, wiremock. |
| Cargo.lock | Updates lockfile for newly introduced dependencies. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- http origin: stream body chunk-by-chunk with running size cap so an
untrusted origin can't force allocation beyond max_blob_size_mb when
Content-Length is omitted or misreports; two-layer defense (pre-check
+ streaming).
- http origin: validate URL scheme is http/https (reject file://, etc).
- http origin: drop total request timeout (cannot be sized for both
small blobs and 10 GB); rely on connect_timeout plus streaming cap.
- runtime: keep cache engine named and call `shutdown()` on graceful
drain so in-flight store writes reach disk before exit.
- engine: shutdown() doc comment now matches the impl (debug log +
explicit FsStore::shutdown for crash-safety).
- config: `${VAR}` expansion now applies to `cache.origin_url`, matching
the other URL fields (rpc_url, relay_url, otlp_endpoint).
- tests: drop `Box::leak` in blob_too_large_is_rejected — hash can be
computed from an owned Vec before it moves into `set_body_bytes`.
Deferred (YAGNI): request coalescing / thundering-herd mitigation —
`CacheEngine::get` has no callers yet; add when the handler shape
reveals an actual need.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`cargo doc -D warnings` rejects `[`FsStore::shutdown`]` because FsStore is a re-export that rustdoc can't resolve from this crate. Use a fully qualified `iroh_blobs::store::fs::FsStore` reference plus prose instead of a method link. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Critical:
- runtime: `cache.shutdown()` failure now logs at `error!` and bubbles
out of `run()` — supervisors get a non-zero exit when the store may
be inconsistent, while the task drain still completes cleanly.
- engine docs: `open()` now accurately mentions both OriginError and
BlobTooLarge as possible oversize surfaces; `get()` lists NotFound,
HashMismatch, BlobTooLarge, OriginError, and Store variants.
Type refinement — single origin-URL parser:
- cache: new `parse_origin_url(&str) -> reqwest::Url` encapsulates
scheme check + trailing-slash normalization; `HttpOrigin::new` now
takes a parsed Url, `HttpOrigin::parse` wraps for test ergonomics.
- cache: re-export `reqwest::Url` as `OriginUrl` so node doesn't pull
in reqwest.
- node: `ResolvedCache.origin_url` is now `Option<OriginUrl>`, parsed
in `resolve_cache` — invalid URLs fail config loading, not engine
wiring. Eliminates "parses here, rejected there" drift flagged by
the type analyzer.
Test coverage:
- `HttpOrigin::parse_origin_url`: 5 unit tests (trailing slash append
/preserve, http/https accept, file/ftp/ws reject, unparseable input).
- engine: integration test using a custom oversized Origin impl to
prove the engine-level size post-check is load-bearing defense in
depth, independent of the HTTP origin's streaming cap.
- engine: shutdown round-trip — open, pull, shutdown, drop origin,
reopen, read back without origin; locks the flush contract.
- config: `${VAR}` expansion on `cache.origin_url`, scheme rejection
at resolve time, CLI > TOML precedence; `cache.origin_url` added
to the `expand_env_per_field_error_context` sweep.
Observability:
- engine: `pull_through` emits `error!` with hash + byte length when
verified bytes fail to land in the store — distinct failure mode
from a generic store error (caller just paid origin egress).
Polish:
- http.rs: `BytesMut::with_capacity` hint is capped at 1 MiB so a
legitimate 10 GB blob grows incrementally instead of pre-allocating
up front.
- http.rs: CONNECT_TIMEOUT comment rewritten to explicitly call out
that a stalled mid-stream origin is not time-bounded in MVP.
- engine.rs: TODO noting iroh-blobs verified-insert API would drop
the double BLAKE3 hash on the happy path.
- engine.rs: dropped `#[allow(clippy::unused_self)]` from `stats()`;
the method keeps `&self` so no signature churn when accounting
lands.
All 57 tests pass (was 47; +10 new). Clippy, fmt, and `cargo doc
-D warnings` all clean.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Bug fix:
- parse_origin_url: pre-fix impl did `format!("{raw}/")` on the whole
input, so `http://host?q` became `http://host?q/` (trailing slash
smuggled into the query) and `.join(&hex)` silently dropped the
query. Now parse first, reject bases with query or fragment (both
get silently discarded by `Url::join`), and normalize the trailing
slash via `url.set_path()` on the parsed object. Two new unit tests
cover query and fragment rejection; the path-append test extended
to check `/v1` segment preservation through `join`.
Type refinement:
- OriginUrl is now a newtype (`pub struct OriginUrl(reqwest::Url)`),
not a transparent alias. `parse_origin_url` is the only public
constructor, so the invariants it enforces (http/https scheme,
trailing-slash path, no query/fragment) are carried *by the type*
and cannot be bypassed by a caller that parses directly. Exposed
via `as_url()` / `into_url()` / `Display`. `HttpOrigin::new` takes
`OriginUrl` — trust contract is type-enforced instead of prose.
Test depth:
- shutdown_flushes_without_drop: now calls `std::mem::forget(engine)`
after `shutdown()` so `FsStore::Drop` cannot also flush. This pins
the contract that `shutdown()` — not `Drop` — is what makes writes
durable; the prior test would have passed with a no-op shutdown.
- mid_stream_overrun_is_rejected_by_http_origin: new test that binds
an ephemeral TcpListener and serves a 2 MiB chunked body with no
`Content-Length`, so the HTTP origin's fast-path can't trip. The
streaming `while resp.chunk()` running-total cap is the only thing
that can catch this — a regression removing or misflipping that
check is now caught by CI.
- open_on_file_path_yields_store_error: new negative test exercising
the `CacheError::Store` variant (previously unreached).
Polish:
- engine.rs stats(): restored `#[allow(clippy::unused_self)]` with a
one-line comment explaining the signature choice, in place of the
opaque `let _ = self;` idiom.
- tests: fixed "would caught" → "would be caught".
61 tests pass (was 57; +4). clippy -D warnings clean; cargo fmt
clean; `cargo doc -D warnings` clean.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Second `Origin` implementation alongside `HttpOrigin`, so operators can
point a node at a pre-seeded directory without standing up an HTTP
server. Exercises the `Origin` trait as a genuine seam rather than a
pattern waiting for a second impl.
Layout & config:
- Blobs live at `{base}/{hex[0..2]}/{hex}` (sharded, git-objects style)
so a content set with millions of entries doesn't land in a single
flat directory.
- New `cache.origin_path` / `--origin-path` / `DECDN_ORIGIN_PATH` —
mutually exclusive with `origin_url` (resolve_cache errors if both
are set). `file://` URLs still rejected by `parse_origin_url`; no
behavioral reversal.
- Runtime `build_cache` dispatches on a `(origin_url, origin_path)`
match — the resolved-time mutex means the unreachable arm is
handled with `anyhow::bail!` instead of an `unwrap()` / `unreachable!`.
Behavior:
- `FilesystemOrigin::new` fails fast on a missing path or a path that
isn't a directory — config-time feedback, not per-request misses.
- `fetch` stats first so an oversize file is rejected without ever
being read into memory (mirrors the HTTP origin's Content-Length
fast-path).
- NotFound (ENOENT) surfaces as `OriginFetch::NotFound`; other I/O
errors carry contextual paths.
Tests (+8):
- Unit: `FilesystemOrigin::new` rejects missing path, rejects
non-directory; `path_for` uses the two-char shard.
- Integration: fs_origin_pulls_and_caches (full round-trip with local
serve after origin drop), fs_origin_reports_not_found,
fs_origin_rejects_oversize.
- Config: resolve_cache_rejects_both_origin_url_and_path,
resolve_cache_origin_path_only. `cache.origin_path` added to the
per-field error-context sweep (catches "added a field, forgot to
wire expansion" regressions).
69 tests pass (was 61). clippy -D warnings, fmt, cargo-doc clean.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements a cache engine for deCDN, integrating iroh-blobs with pull-through logic from HTTP and filesystem origins. The system features sharded storage, URL normalization, and streaming size enforcement. Review feedback focuses on critical performance and reliability enhancements, including offloading heavy hashing operations to blocking threads, implementing timeouts for network requests to prevent resource exhaustion, and replacing unstable Rust syntax to ensure compatibility with stable toolchains.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 17 changed files in this pull request and generated 3 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…blocking Round 3 review findings (gemini + Copilot on bb6f190): - HTTP origin: add phase-level timeouts now that the total-request timeout is deliberately absent. RESPONSE_HEADERS_TIMEOUT (30s) wraps the `.send()` future to catch slow-header origins; CHUNK_IDLE_TIMEOUT (30s) wraps each `resp.chunk()` to catch slow-trickle origins that stay within max_bytes but take forever. Previously these were called out as known MVP limitations; now they're real guards. - HTTP origin: redact userinfo (user:pass@) from error messages in `parse_origin_url` and `HttpOrigin::fetch`. Operators may legitimately put credentials in `base_url` for internal origins; leaking them into error logs is a real concern. New `redact_for_log` / `redact_raw_for_log` helpers; unparseable URLs surface as "<unparseable URL>" rather than echoing raw input. - engine: BLAKE3 of a 10 GB blob is seconds of 100% CPU — would block one tokio worker and starve other tasks. `pull_through` now uses `spawn_blocking` above a 1 MiB threshold (below that, the inline path is cheaper than the round-trip). Panic from the blocking task surfaces as `CacheError::Store`. - runtime: `cache.shutdown()` error context was "cache shutdown failed during drain", but shutdown runs *before* the task drain. Reworded to "cache shutdown failed" to match reality. Not changed: - Thundering herd (gemini, medium): YAGNI — `CacheEngine::get` has no callers yet, prior reply on thread. - "let_chains is unstable" (gemini, medium): factually wrong — CI MSRV check on rustc 1.85.0 passes this exact code on every commit. Reply on thread. - OOM via streaming all the way through (gemini, high): MVP returns `Bytes`; the concrete OOM concern is bounded by `max_bytes` via three defense layers. Prior reply on thread still applies. 69 tests pass (unchanged count — new behavior is exercised by existing tests). clippy -D warnings, fmt, cargo-doc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… JoinError
Correctness:
- `CacheEngine::pull_through` spawn_blocking JoinError: stop
unconditionally labeling as "hash task panicked". Branch on
`is_panic()` / `is_cancelled()` so error context matches reality
(cancellation fires on runtime shutdown, not a panic).
- `redact_for_log`: fail closed. If `set_username("")` + `set_password(None)`
leave anything behind (URL-parsing misattributed credentials into
host/path, or cannot-be-a-base URL), emit `<redacted URL>` instead
of echoing the residue. Prevents a class of URL-parsing-ambiguity
leaks the round-3 fix didn't cover.
Test coverage:
- `response_headers_timeout_fires_on_silent_server`: raw `TcpListener`
that accepts and holds the socket open without writing. Exercises
the `.send()` timeout wrapper added in the round-3 commit. Uses
`HttpOrigin::with_timeouts(200ms, ..)` so the test runs sub-second.
- `chunk_idle_timeout_fires_when_origin_stalls_mid_body`: raw
`TcpListener` that serves headers + 4 body bytes, then hangs.
Exercises the per-chunk idle timeout wrapper. Also asserts the new
progress-info suffix (`4 bytes buffered`) so regressions in the
error context catch-all are detected.
- `pull_through_succeeds_above_blocking_hash_threshold`: 2 MiB
payload via FilesystemOrigin crosses `BLOCKING_HASH_THRESHOLD` and
exercises the `spawn_blocking` branch. Prior above-threshold tests
all aborted before hash verification.
- Inline unit tests for `redact_for_log` (user:pass, user only),
`redact_raw_for_log` placeholder, and an end-to-end
`parse_origin_url` error-message-doesn't-leak-credentials assertion.
API:
- `HttpOrigin::with_timeouts(headers, idle)` — override the phase
timeouts. Primary use is tests (as above); operator policy could
plausibly want it too, so the setter is `pub` rather than
`#[cfg(test)]`.
Polish:
- Idle-timeout error context now includes `buf.len() bytes buffered`
so operators can distinguish "stalled at handshake" from
"stalled after 9 GiB".
- `redact_for_log` doc notes the scheme-preservation contract from
`Url::join`, not just `parse_origin_url`.
- `RESPONSE_HEADERS_TIMEOUT` wrapper comment clarifies `.send()`
semantics (covers request-write through header-read, plus any
pool-miss connect).
- `BLOCKING_HASH_THRESHOLD = 1 << 20; // 1 MiB` trailing unit
comment matches the style used for `INITIAL_CAPACITY_HINT_CAP`.
76 tests pass (was 69; +7). clippy -D warnings, fmt,
`cargo doc -D warnings` all clean.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Requested minor changes, LGTM
Fixes RUSTSEC-2026-0098 — URI name constraints were incorrectly accepted. Not reachable via any API we use (rustls-webpki has no public URI-name assertion API), but the advisory blocks `cargo deny check` in CI. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses Alper's review comment on #232: the fetch path already uses tokio::fs::metadata, so the sync std::fs::metadata in the constructor was inconsistent. Flip new() to async and update all 8 call sites. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts: # crates/node/src/config/mod.rs # crates/node/src/runtime/mod.rs
Summary
Stands up
crates/cache(previously a 5-line docstring stub) with:CacheEnginearoundiroh_blobs::store::fs::FsStorewith origin pull-through on miss. BLAKE3 verification gates every insert — hash-mismatched bytes are rejected before reaching the store (CacheError::HashMismatch). Above a 1 MiB threshold the hash runs ontokio::task::spawn_blockingso a 10 GB blob doesn't monopolize an async worker. Three layers of size-cap defense (Content-Length pre-check, mid-stream running total, engine post-check) bound the memory an untrusted origin can force us to allocate.Origintrait as a genuine seam, with two concrete backends:HttpOrigin— reqwest + rustls, phase-level timeouts:CONNECT_TIMEOUT(10s) for handshake,RESPONSE_HEADERS_TIMEOUT(30s) wrapping.send(),CHUNK_IDLE_TIMEOUT(30s) wrapping eachresp.chunk(). No total-request timeout (cannot be sized for both small blobs and 10 GB max). Scheme validation (http/httpsonly,file://rejected), trailing-slash normalization, query/fragment rejection, all centralized inparse_origin_url. URL-userinfo redacted from all error messages via a fail-closed helper souser:pass@never reaches logs.FilesystemOrigin— sharded{base}/{hex[0..2]}/{hex}layout (git-objects style). Useful for local dev, pre-seeded caches, and operators who prefer to curate the origin surface offline. Fails fast on missing path / non-directory; metadata-first oversize rejection.OriginUrlnewtype — invariants (http/https scheme, trailing-slash path, no query/fragment) are type-enforced rather than documented.parse_origin_urlis the only public constructor, so "parses here, rejected there" drift is impossible.CacheEngine::shutdown()outsideSHUTDOWN_DEADLINEso a slow flush is preferable to a lost write; on failure the error propagates out ofrun()for a non-zero exit.[cache] origin_url/origin_path/ sizes / etc., with CLI flags (--origin-url,--origin-path) and env vars (DECDN_ORIGIN_URL,DECDN_ORIGIN_PATH).origin_urlandorigin_pathare mutually exclusive at resolve time;${VAR}and~expansion apply to both URL and path fields.Unblocks the next two milestones called out in the cache docstring and gossip stubs:
cdn/client/v1paid-delivery handler (needs something to serve) and gossippopular_hashes/LoadHint(needs real cache stats). ADR 023 leaf-crate rule respected — no#[cfg(feature = "poc")]incrates/cache.Explicitly deferred (with tracking notes in code where relevant):
cache_size_mbis read but not enforced yet).getstill returnsBytes).cdn/client/v1(that handler doesn't exist yet).Origintrait is ready.CacheEngine::stats()returns zeros; interface is stable).Test plan
cargo build -p decdn-cache -p decdn-nodecargo clippy -p decdn-cache -p decdn-node --all-targets -- -D warnings(anti-panic lints green: nounwrap/expect/panic/indexing_slicing)cargo fmt -- --checkRUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-itemscargo nextest run— 76 tests passTest coverage highlights (crates/cache)
HttpOrigin:
CacheError::NotFoundCacheError::OriginErrorCacheError::OriginError— rawTcpListenerfixture exercises the streaming cap that wiremock can't reachTcpListeneraccepts and holds the socket open without writing;.send()wrapper catches itTcpListenerserves headers + partial body then hangs; idle-timeout wrapper aborts withN bytes bufferedprogress infoHttpOrigin::with_timeouts(headers, idle)builder makes both timeout tests sub-secondparse_origin_urlunit tests: scheme accept/reject (http, https, file, ftp, ws), trailing-slash append/preserve, query rejection, fragment rejection, unparseable inputredact_for_log,redact_raw_for_log) unit-tested; integration assertion confirmsparse_origin_urlerrors on a URL with credentials do not leak themFilesystemOrigin:
CacheError::NotFoundnewrejects missing path and non-directorypath_foruses the two-char shard correctlyEngine / runtime:
pull_through_succeeds_above_blocking_hash_threshold— 2 MiB payload exercises thespawn_blockingbranch of BLAKE3 verificationOversizedOriginstand-in proves the engine-levelBlobTooLargepost-check catches a misbehavingOriginimpl (defense in depth)shutdown_flushes_without_drop— usesstd::mem::forgetto skipDrop, pinning the flush-on-shutdown contractopen_on_file_path_yields_store_errorcovers theCacheError::StorevariantCacheError::NoOriginConfig:
${VAR}expansion oncache.origin_urlparse_origin_urlscheme rejection at resolve timeorigin_urlorigin_url+origin_pathmutual-exclusion rejectionorigin_path-only resolutioncache.origin_urlandcache.origin_pathadded to theexpand_env_per_field_error_contextsweep (regression guard for future fields)Manual smoke
decdn run --origin-url https://origin.example/ ...against a real HTTP origin — owner to verify before mergedecdn run --origin-path /var/cache/decdn/origin ...with a pre-seeded sharded directory — owner to verify before merge🤖 Generated with Claude Code