diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 9cc54bb1..bf69d934 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -124,6 +124,15 @@ jobs:
- name: Verify the packaged Rust crate with every feature
working-directory: rust
run: cargo package --locked --all-features
+ - name: Check the isolated production-feature Rust consumer
+ working-directory: rust/tests/production_consumer
+ env:
+ CARGO_TARGET_DIR: ${{ github.workspace }}/rust/target/production-consumer
+ run: |
+ cargo tree --locked --edges features --invert dialcache
+ cargo fmt --check
+ cargo clippy --locked --all-targets -- -D warnings
+ cargo run --locked
- name: Install LLVM coverage tools for the pinned Rust toolchain
working-directory: rust
run: rustup component add llvm-tools-preview
diff --git a/docs/getting-started.md b/docs/getting-started.md
index bc8c9b80..dbb9d804 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -48,8 +48,9 @@ dialcache = { path = "../DialCache/rust" }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
```
-Adjust the path to your checkout. The core crate requires Rust 1.85; the `redis`
-feature currently requires Rust 1.88. See the [Rust guide](languages/rust.md) for
+Adjust the path to your checkout. The core crate requires Rust 1.85 or later;
+building the `redis` feature with this repository's lockfile requires Rust 1.88.
+See the [Rust guide](languages/rust.md) for
runtime, feature and value-ownership details.
diff --git a/docs/languages/rust.md b/docs/languages/rust.md
index 0c2d099f..c4a4abf6 100644
--- a/docs/languages/rust.md
+++ b/docs/languages/rust.md
@@ -19,7 +19,8 @@ serde = { version = "1", features = ["derive"] }
```
Adjust the path to your checkout. The core crate requires Rust 1.85 or later;
-the current `redis` dependency requires 1.88. The crate has no Node.js runtime
+building the `redis` feature with this repository's lockfile requires Rust 1.88.
+The crate has no Node.js runtime
dependency. Available registry versions are listed on
[crates.io](https://crates.io/crates/dialcache); docs.rs builds their API references.
@@ -113,3 +114,120 @@ replaces it, and is the only source of differences for an operation whose
Application codecs control their own scheduling. See
[compression](../redis.md#compression) for thresholds and fail-open behavior
when compression or decompression capacity is exhausted.
+
+## Application-owned limits
+
+
+
+These four recipes use existing APIs. They add no library defaults and protect
+an application only after it adopts them. Choose limits for your workload.
+The complete [executable examples](https://github.com/lan17/DialCache/blob/main/rust/tests/docs_examples.rs)
+include imports, test dependencies and assertions.
+
+### Source and policy work
+
+Acquire source capacity inside the registered source, not around `get`.
+The permit then remains held when a caller stops waiting or the cache source
+deadline expires. The same source guard applies to uncached and shadow calls.
+Use non-waiting admission to avoid an unbounded queue of waiting callers.
+
+This example uses a semaphore as a test dependency. Replace that wait with
+source I/O that has its own finite budget:
+
+<<< @/../rust/tests/docs_examples.rs#rust-source-budget{rust}
+
+The application's one-second timeout drops this dependency future and releases
+its permit. It does not prove cancellation of work in a client-owned task or at
+the server. If your client starts separate tasks, keep the permit with the task
+that owns the resource until it finishes, and bound its native queue and I/O.
+Acquire the permit before scheduling that task, not after it starts.
+A caller timeout only ends that caller's wait. None of these timers can preempt
+blocking synchronous code.
+
+Admission and dependency timeout errors are `Error::Source`, not
+`Error::FallbackTimeout`. If stale recovery should accept one of these errors,
+classify that specific error with `should_recover`; do not accept every source
+failure.
+
+Prefer a cheap local configuration snapshot. When a provider must await I/O,
+bound that work separately: policy resolves before source sharing and before
+the source timer starts.
+
+<<< @/../rust/tests/docs_examples.rs#rust-provider-budget{rust}
+
+A provider error runs the source uncached; it does not enable baseline caching.
+Keep the source guard active on that path. `Ok(None)` means inherit, not
+configuration failure.
+
+### Complete mutation calls
+
+Wrap the remote adapter before passing it to the cache builder. This example
+forwards the original read request and cancellation context, and gives each
+write or invalidation one 200 ms wait budget:
+
+<<< @/../rust/tests/docs_examples.rs#rust-mutation-budget{rust}
+
+For `RedisAdapter`, the invalidation budget covers both `EVALSHA` and its `EVAL`
+retry. Keep the client's own finite connection, command and queue limits as
+well. No breaker bypasses invalidation. A timed-out write preserves the source
+result; a timed-out invalidation returns an error to its caller.
+
+Timeout drops the adapter future, not an already accepted server command. A
+mutation can still happen after the error, so its outcome is unknown until
+verified. This budget excludes earlier serialization and compression; give an
+asynchronous custom codec its own settlement bound. It is not a total-call
+deadline.
+
+### Values and request scopes
+
+Use a value domain with a known bound on retained data, and validate remote
+decodes as well as source results. This example stores only a 32-byte digest.
+The codec checks the JSON payload length and the exact decoded array length:
+
+<<< @/../rust/tests/docs_examples.rs#rust-bounded-values{rust}
+
+The payload check runs **after** the engine's decompression. It does not prevent
+decompression allocations, nor does a serialized-byte limit measure heap size.
+The fixed array bounds this value type, not process memory or all temporary
+allocations.
+
+Set process-local capacity explicitly. Here `remote` is the test snapshot
+adapter and `clock` is its fixed test clock; use your adapter and normal clock
+in the application:
+
+<<< @/../rust/tests/docs_examples.rs#rust-bounded-scopes{rust}
+
+Capacity counts entries, not bytes. Request memoization has no capacity limit.
+Bound simultaneous requests and keys per request, use bounded key types, and
+close scopes promptly:
+
+<<< @/../rust/tests/docs_examples.rs#rust-bounded-request{rust}
+
+Use `request_local(false)` when request memoization is not needed. Closing a
+scope releases its memo, but does not cancel source work or release `Arc`s held
+by callers. Keep the request permit until the caller also releases retained
+results. Apply the source controls above as well.
+
+### Nonblocking metric transport
+
+`DatadogObserver` maps names, tags and units, then calls `DogStatsdClient`
+synchronously. A slow client delays cache calls. This client queues packets
+with `try_send`; a full or closed queue drops the packet rather than waiting:
+
+<<< @/../rust/tests/docs_examples.rs#rust-metric-queue{rust}
+
+Create it with `sync_channel` and a fixed capacity, then pass it to
+`DatadogObserver::new`. The example also caps each packet at 512 bytes and drops
+unsafe wire separators. Keep application labels stable and bounded.
+
+A separate sender must consume the queue with finite I/O budgets. The tests use
+only a loopback UDP socket with a write timeout, preserve the exporter's metric
+mapping, and count send errors separately. Monitor drop and send-error counters
+outside this exporter to avoid recursive reporting. Stop producers and drop
+their sender handles before joining the sender at shutdown.
+
+Queue acceptance and a successful UDP send do not prove delivery to Datadog.
+This example changes neither the metric schema nor the selected histogram or
+distribution mode.
+
+
diff --git a/docs/redis.md b/docs/redis.md
index 59300e61..ab946a69 100644
--- a/docs/redis.md
+++ b/docs/redis.md
@@ -474,7 +474,10 @@ bounded for large values.
Compression of payloads of at least 64 KiB (or at levels 10–22 once the
threshold is met) and every decompression run on a bounded CPU queue shared by
-all instances: two workers and two queued jobs by default. When that queue is
+all instances: two workers and two queued jobs by default. Tokio worker-thread
+and blocking-thread limits do not change this pool. Use a custom
+`Runtime::spawn_blocking` implementation for a different bounded CPU executor.
+When that queue is
full, the work is rejected and DialCache fails open: a read of a compressed
value falls through to the source, and the write is skipped. Custom codecs
manage their own CPU work.
diff --git a/formal/catalogs/go-parity.json b/formal/catalogs/go-parity.json
index 4e876fa2..65e6df9e 100644
--- a/formal/catalogs/go-parity.json
+++ b/formal/catalogs/go-parity.json
@@ -10,7 +10,7 @@
"inputs": {
"semanticCasesSha256": "380273598e1d956a3f9fce270cc84424b342e456139b279bd56576bd3b837f65",
"executionSha256": "eaf117c3e8630013cc8df0524f84af440c470f42e8711ab4dd07b931161c784f",
- "sourceAuditDispositionsSha256": "942eab018ae0d8fa189ff16c322f6d9b3301aadc7c46d00b311018728c62f34e",
+ "sourceAuditDispositionsSha256": "b31ef053e3ee5a2e05fcd22d940b4dd64d0a98218012ab3052ef40d36e14e27b",
"featureCoverageSha256": "a49438a0fab8997518956565f391486a569aab304f2057a667d28c5d41bde834",
"coverageWitnessesSha256": "745cebececddbfa97912621ada94072d648e8e60e8b3eb013b91eefd16f352a1",
"profilesSha256": "888a522f8ad97862ebcb0b5fe363ec7bec60367fa42c60e1623141814b1991b3"
diff --git a/formal/catalogs/source-audit.json b/formal/catalogs/source-audit.json
index 6daa5093..9db032c3 100644
--- a/formal/catalogs/source-audit.json
+++ b/formal/catalogs/source-audit.json
@@ -125,7 +125,7 @@
},
{
"path": "docs/getting-started.md",
- "sha256": "409c3e6dd51f72d8df6e746fbcf1ee5a619cdc2f0f97beaf37a5b20c9c99c3c1",
+ "sha256": "d9591172e2680824531564768959573dc577b7603728c0d5a58d557ccaaa47a2",
"entries": [
{"title":"Getting started","contracts":["B01"]},
{"title":"Install","contracts":["B01"]},
@@ -211,14 +211,19 @@
},
{
"path": "docs/languages/rust.md",
- "sha256": "ae1e0dcb12f62dc827c075c0e8f3c92ac298a6758e59d6d65205180b3dee9c4c",
+ "sha256": "d298b5d3223a66f17342f0c645030e131526803c70f47d1dc98a1ce16b5785f4",
"entries": [
{"title":"Rust integration","contracts":["B01"]},
{"title":"Installation and runtime","contracts":["B01","B02"]},
{"title":"Request scope and operations","contracts":["C01","C02","C03","B01","B02"]},
{"title":"Policy and errors","contracts":["C16","C17","C18","C20","C21","C23","C25","C27","C29","B01","B02"]},
{"title":"Identity and values","contracts":["W01","W02","E04","B03"]},
- {"title":"Integrations","contracts":["E01","B01","B03","X01","C46","C47","C60"]}
+ {"title":"Integrations","contracts":["E01","B01","B03","X01","C46","C47","C60"]},
+ {"title":"Application-owned limits","contracts":["B01","E03","X02"]},
+ {"title":"Source and policy work","contracts":["C01","C11","C20","C23","C25","C27","B01","B02","E03","X02"]},
+ {"title":"Complete mutation calls","contracts":["C27","C29","C56","B01","E01","E03","X02"]},
+ {"title":"Values and request scopes","contracts":["C03","C07","C08","B03","E04","X02"]},
+ {"title":"Nonblocking metric transport","contracts":["C30","X01","X02"]}
]
},
{
@@ -259,7 +264,7 @@
},
{
"path": "docs/redis.md",
- "sha256": "fce0b00a5ce212e1267aa3eda28f4e9334209d87730fb0ea0fe5f543b741888b",
+ "sha256": "37cd276f3bbc4e60f01c3a1b2447f57e63652a75661861b49ae63743145b4af6",
"entries": [
{"title":"Redis and Valkey","contracts":["E01"]},
{"title":"Install a client","contracts":["B01","E01"]},
@@ -1767,7 +1772,7 @@
},
{
"path": "formal/guides/VALIDATION.md",
- "sha256": "8f0a8bbd03f71d630f337a83c9c01f1e737bd7c634e7e7ac9d9a4b988fb511ea",
+ "sha256": "c2baf298efdc5723f991acd3e3d200c1b0aa97bcfd113a4fa683cd35b6a01715",
"entries": [
{"title":"Validation and evidence"},
{"title":"Prerequisites"},
@@ -1776,7 +1781,8 @@
{"title":"Reproducing one history"},
{"title":"Mutation evidence"},
{"title":"Exploratory runs"},
- {"title":"A retained sampling regression"}
+ {"title":"A retained sampling regression"},
+ {"title":"Rust consumer and resource checks"}
],
"review": {
"kind": "tooling-guide",
diff --git a/formal/guides/VALIDATION.md b/formal/guides/VALIDATION.md
index a56adf98..a9c33aaa 100644
--- a/formal/guides/VALIDATION.md
+++ b/formal/guides/VALIDATION.md
@@ -419,3 +419,54 @@ public-action regressions now anchor all of them:
| policy / `remote-value:7`, `remote-value:8`, `remote-value:9` | [falsyRemoteValuesAreServedFromRemoteTest](../models/dialcache-policy-conformance.qnt) |
| layers / `source-publication-probed-in-all-three-layers` | [untrackedSourcePublicationIsProbedInAllThreeLayersTest](../models/dialcache-layers-conformance.qnt) |
| independent / `distinct-retained-recovery-values` | [independentRecoveriesServeDistinctAcquiredSnapshotsTest](../models/dialcache-independent-conformance.qnt) |
+
+## Rust consumer and resource checks
+
+The Rust CI job separately builds `rust/tests/production_consumer`, whose own
+workspace and lockfile keep the root crate's `test-util` development dependency
+out of the consumer graph. It checks the production shadow-log rendering path
+and panic isolation, not the deterministic replay runtime:
+
+```sh
+cargo tree --locked --manifest-path rust/tests/production_consumer/Cargo.toml --edges features --invert dialcache
+cargo fmt --manifest-path rust/tests/production_consumer/Cargo.toml --check
+cargo clippy --locked --manifest-path rust/tests/production_consumer/Cargo.toml --target-dir rust/target/production-consumer --all-targets -- -D warnings
+cargo run --locked --manifest-path rust/tests/production_consumer/Cargo.toml --target-dir rust/target/production-consumer
+```
+
+The consumer's first assertion distinguishes the production renderer from the
+test renderer. As a negative control, adding `--features dialcache/test-util`
+to the last command must fail that assertion. Do not count that expected failure
+as a production validation result.
+
+The default native suite also checks application-owned permits across actual
+socket work, caller abandonment and native I/O expiry; retained result values
+and post-decompression codec limits; and bounded metric queue, sender error and
+shutdown behavior. These tests do not turn the recipes into library defaults.
+
+Longer load tests and the local transport fixture are opt-in. The load runner
+requires GNU `timeout`, Python 3, a clean committed checkout and a new output
+directory for each run:
+
+```sh
+DIALCACHE_SOAK_CASES='hot-hit cancellation' \
+DIALCACHE_SOAK_WORKER_COUNTS=1 DIALCACHE_SOAK_RATES=1000 DIALCACHE_SOAK_SECONDS=10 \
+bash scripts/rust-scale-soak.sh /tmp/dialcache-scale-evidence
+
+cargo test --locked --manifest-path rust/tests/redis_transport_recovery/Cargo.toml \
+ --test transport -- --test-threads=1
+```
+
+The load runner records its source and harness fingerprints, offered arrivals,
+admission decisions, caller outcomes, bounded latency histograms and actual work
+drain. Fixed-window completions and eventual cohort success are different
+measurements. Synthetic remote results are not Redis capacity measurements, and
+RSS observations do not prove a memory ceiling.
+
+The transport fixture needs TLS-capable `redis-server` and OpenSSL and fails
+when prerequisites are missing. Its separate downstream manifest selects Redis
+TLS/Sentinel features and a rustls crypto provider without changing the library
+defaults. It tests explicit primary rediscovery, not automatic application
+failover. See its [scope and commands](../../rust/tests/redis_transport_recovery/README.md)
+before running it. Neither opt-in suite replaces portable replay, required
+hosted validation, or the Docker-backed interoperability matrix.
diff --git a/formal/guides/course/13-catalogs-and-ledgers.md b/formal/guides/course/13-catalogs-and-ledgers.md
index 2c2f8800..42ca0ec2 100644
--- a/formal/guides/course/13-catalogs-and-ledgers.md
+++ b/formal/guides/course/13-catalogs-and-ledgers.md
@@ -99,9 +99,9 @@ You will edit a tracked guide and undo it at the end.
{
sources: 50,
tests: 633,
- sections: 216,
+ sections: 221,
reviewedGuides: 19,
- guideSections: 195
+ guideSections: 196
}
```
diff --git a/formal/guides/course/README.md b/formal/guides/course/README.md
index e619e8b6..41a3c6b5 100644
--- a/formal/guides/course/README.md
+++ b/formal/guides/course/README.md
@@ -148,7 +148,7 @@ so the drift is caught by the check, not by a learner:
the code may have moved for a reason the lesson should mention.
- **A quoted count comes from a check.** Quote a number only as `node
formal/tools/execution.mjs` prints it (`"regressions": 489`) or as `node
- formal/tools/check-source-audit.mjs` prints it (`guideSections: 195`); the
+ formal/tools/check-source-audit.mjs` prints it (`guideSections: 196`); the
check compares both with today's output. When an exercise changes a count, say
so in words rather than quoting the new number.
- **The course is outside the review ledger on purpose.** The lessons are
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index dd0e0335..ab32e296 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -164,7 +164,7 @@ dependencies = [
"thiserror 2.0.20",
"tokio",
"zstd",
- "zstd-safe 7.3.0",
+ "zstd-safe 7.4.0",
]
[[package]]
@@ -993,9 +993,9 @@ dependencies = [
[[package]]
name = "tokio"
-version = "1.53.1"
+version = "1.53.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
dependencies = [
"bytes",
"libc",
@@ -1181,36 +1181,36 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zstd"
-version = "0.14.0"
+version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e"
+checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
dependencies = [
- "zstd-safe 8.0.0",
+ "zstd-safe 8.2.0",
]
[[package]]
name = "zstd-safe"
-version = "7.3.0"
+version = "7.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"
+checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-safe"
-version = "8.0.0"
+version = "8.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab"
+checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
-version = "2.1.0+zstd.1.5.7"
+version = "2.1.2+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
+checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
dependencies = [
"cc",
"pkg-config",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index b51d68b0..15875d27 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -29,11 +29,11 @@ lru = "0.18"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
ryu-js = "1"
-zstd = "0.14"
-zstd-safe = "7"
+zstd = "0.14.3"
+zstd-safe = "7.4.0"
thiserror = "2"
log = "0.4"
-tokio = { version = "1", features = ["rt", "time"], optional = true }
+tokio = { version = "1.53.3", features = ["rt", "time"], optional = true }
redis = { version = "1", features = ["tokio-comp", "cluster-async", "connection-manager", "script"], optional = true }
sha1 = { version = "0.11", optional = true }
hex = { version = "0.4", optional = true }
@@ -42,7 +42,7 @@ prometheus = { version = "0.14", optional = true }
[dev-dependencies]
sha2 = "0.11"
dialcache = { path = ".", features = ["test-util"] }
-tokio = { version = "1", features = ["full"] }
+tokio = { version = "1.53.3", features = ["full"] }
hex = "0.4"
serde_json = "1"
diff --git a/rust/tests/docs_examples.rs b/rust/tests/docs_examples.rs
index 23925fe7..f5712040 100644
--- a/rust/tests/docs_examples.rs
+++ b/rust/tests/docs_examples.rs
@@ -1,4 +1,5 @@
//! Executable source of the shared guides' code regions.
+//! Rust-only application recipes also feed the native integration guide.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
@@ -156,3 +157,1031 @@ async fn tracked_invalidation() -> Result<(), BoxError> {
.await?;
Ok(())
}
+
+struct SnapshotRemote(dialcache::Payload);
+
+impl dialcache::Remote for SnapshotRemote {
+ fn read(
+ &self,
+ _: dialcache::ReadRequest,
+ _: dialcache::ReadContext,
+ ) -> futures::future::BoxFuture<'_, Result> {
+ Box::pin(async {
+ Ok(dialcache::ReadResult::Hit(dialcache::Frame {
+ created_at_ms: 1_000,
+ payload: self.0.clone(),
+ }))
+ })
+ }
+
+ fn write(
+ &self,
+ _: dialcache::WriteRequest,
+ ) -> futures::future::BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(async { Ok(()) })
+ }
+
+ fn invalidate(
+ &self,
+ _: dialcache::InvalidateRequest,
+ ) -> futures::future::BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(async { Ok(()) })
+ }
+}
+
+mod application_budgets {
+ use super::*;
+ use std::time::Duration;
+
+ use dialcache::{Error, SourceBudget};
+ use tokio::sync::{Semaphore, TryAcquireError};
+ use tokio::time::{error::Elapsed, timeout};
+
+ #[tokio::test]
+ async fn source_permit_outlives_the_cache_wait() -> Result<(), BoxError> {
+ let dependency = Arc::new(Semaphore::new(0));
+ let started = Arc::new(Semaphore::new(0));
+ // #region rust-source-budget
+ let source_slots = Arc::new(Semaphore::new(1));
+ let cache = DialCache::builder().build()?;
+ let reader = cache
+ .use_case::("item", "boundedSource")
+ .policy(Policy::default().local_ttl_sec(60))
+ .budget(SourceBudget::Millis(20))
+ .key(|id: &u64| KeySpec::new(id))
+ .source({
+ let slots = source_slots.clone();
+ let dependency = dependency.clone();
+ let started = started.clone();
+ move |_scope, id| {
+ let (slots, dependency, started) =
+ (slots.clone(), dependency.clone(), started.clone());
+ async move {
+ // This permit belongs to the raw source, not its caller's wait.
+ let _permit = slots.try_acquire_owned()?;
+ timeout(Duration::from_secs(1), async {
+ started.add_permits(1);
+ // A test dependency; replace with bounded native source I/O.
+ dependency.acquire().await?.forget();
+ Ok::<_, BoxError>(id)
+ })
+ .await?
+ }
+ }
+ })
+ .register()?;
+ // #endregion rust-source-budget
+
+ let request = cache.enable_guard();
+ let (first, follower) = tokio::join!(
+ reader.get(request.scope(), 1),
+ reader.get(request.scope(), 1)
+ );
+ assert!(matches!(first, Err(Error::FallbackTimeout(_))));
+ assert!(matches!(follower, Err(Error::FallbackTimeout(_))));
+ assert_eq!(started.available_permits(), 1);
+ assert_eq!(source_slots.available_permits(), 0);
+ for id in [1, 2] {
+ let error = reader.get_uncached(id).await.unwrap_err();
+ assert!(error.source_error().unwrap().is::());
+ }
+ dependency.add_permits(1);
+ drop(timeout(Duration::from_secs(2), source_slots.acquire()).await??);
+ assert_eq!(source_slots.available_permits(), 1);
+
+ // A caller drop also leaves the source permit attached to the raw work.
+ started.acquire().await?.forget();
+ let caller = tokio::spawn({
+ let reader = reader.clone();
+ async move { reader.get_uncached(3).await }
+ });
+ timeout(Duration::from_secs(2), started.acquire())
+ .await??
+ .forget();
+ caller.abort();
+ assert!(caller.await.unwrap_err().is_cancelled());
+ assert_eq!(source_slots.available_permits(), 0);
+ dependency.add_permits(1);
+ drop(timeout(Duration::from_secs(2), source_slots.acquire()).await??);
+
+ // Outside a cache scope, the application's own timeout still applies.
+ let error = timeout(Duration::from_secs(2), reader.get_uncached(4))
+ .await?
+ .unwrap_err();
+ assert!(error.source_error().unwrap().is::());
+ assert_eq!(source_slots.available_permits(), 1);
+ dependency.add_permits(1);
+ assert_eq!(*reader.get_uncached(5).await?, 5);
+ Ok(())
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn native_work_keeps_its_permit_after_the_wait_ends() -> Result<(), BoxError> {
+ use std::io::{ErrorKind, Read};
+ use std::net::TcpStream;
+ use tokio::io::AsyncWriteExt;
+ use tokio::net::TcpListener;
+
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let address = listener.local_addr()?;
+ let slots = Arc::new(Semaphore::new(1));
+ let started = Arc::new(Semaphore::new(0));
+ let finished = Arc::new(Semaphore::new(0));
+ let active = Arc::new(AtomicUsize::new(0));
+ let peak = Arc::new(AtomicUsize::new(0));
+ let native_timeouts = Arc::new(AtomicUsize::new(0));
+ let cache = DialCache::builder().build()?;
+ let reader = cache
+ .use_case::("item", "nativeSource")
+ .key(|id: &u64| KeySpec::new(id))
+ .source({
+ let (slots, started, finished) = (slots.clone(), started.clone(), finished.clone());
+ let (active, peak, native_timeouts) =
+ (active.clone(), peak.clone(), native_timeouts.clone());
+ move |_, _| {
+ let (slots, started, finished) =
+ (slots.clone(), started.clone(), finished.clone());
+ let (active, peak, native_timeouts) =
+ (active.clone(), peak.clone(), native_timeouts.clone());
+ async move {
+ let permit = slots.try_acquire_owned()?;
+ // Dropping the join handle cannot stop blocking I/O.
+ let work = tokio::task::spawn_blocking(move || {
+ let mut stream =
+ TcpStream::connect_timeout(&address, Duration::from_secs(1))?;
+ stream.set_read_timeout(Some(Duration::from_secs(2)))?;
+ let running = active.fetch_add(1, Ordering::SeqCst) + 1;
+ peak.fetch_max(running, Ordering::SeqCst);
+ started.add_permits(1);
+ let mut reply = [0];
+ let result = stream.read_exact(&mut reply);
+ if result.as_ref().is_err_and(|error| {
+ matches!(error.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock)
+ }) {
+ native_timeouts.fetch_add(1, Ordering::SeqCst);
+ }
+ drop(stream);
+ active.fetch_sub(1, Ordering::SeqCst);
+ drop(permit);
+ finished.add_permits(1);
+ result?;
+ Ok::<_, BoxError>(u64::from(reply[0]))
+ });
+ timeout(Duration::from_millis(200), work).await??
+ }
+ }
+ })
+ .register()?;
+
+ let caller = tokio::spawn({
+ let reader = reader.clone();
+ async move { reader.get_uncached(1).await }
+ });
+ let (mut server, _) = timeout(Duration::from_secs(3), listener.accept()).await??;
+ timeout(Duration::from_secs(3), started.acquire())
+ .await??
+ .forget();
+ let error = timeout(Duration::from_secs(3), caller).await??.unwrap_err();
+ assert!(error.source_error().unwrap().is::());
+ assert_eq!(active.load(Ordering::SeqCst), 1);
+ let rejected = reader.get_uncached(2).await.unwrap_err();
+ assert_eq!(peak.load(Ordering::SeqCst), 1);
+ assert_eq!(active.load(Ordering::SeqCst), 1);
+ assert_eq!(slots.available_permits(), 0);
+ assert!(rejected.source_error().unwrap().is::());
+ assert_eq!(native_timeouts.load(Ordering::SeqCst), 0);
+ server.write_all(&[1]).await?;
+ timeout(Duration::from_secs(3), finished.acquire())
+ .await??
+ .forget();
+ drop(server);
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ assert_eq!(slots.available_permits(), 1);
+
+ let caller = tokio::spawn({
+ let reader = reader.clone();
+ async move { reader.get_uncached(2).await }
+ });
+ let (stalled_server, _) = timeout(Duration::from_secs(3), listener.accept()).await??;
+ timeout(Duration::from_secs(3), started.acquire())
+ .await??
+ .forget();
+ caller.abort();
+ assert!(caller.await.unwrap_err().is_cancelled());
+ assert_eq!(active.load(Ordering::SeqCst), 1);
+ assert_eq!(slots.available_permits(), 0);
+ timeout(Duration::from_secs(4), finished.acquire())
+ .await??
+ .forget();
+ drop(stalled_server);
+ assert_eq!(native_timeouts.load(Ordering::SeqCst), 1);
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ assert_eq!(slots.available_permits(), 1);
+
+ let caller = tokio::spawn({
+ let reader = reader.clone();
+ async move { reader.get_uncached(3).await }
+ });
+ let (mut server, _) = timeout(Duration::from_secs(3), listener.accept()).await??;
+ server.write_all(&[3]).await?;
+ assert_eq!(*timeout(Duration::from_secs(3), caller).await???, 3);
+ timeout(Duration::from_secs(3), finished.acquire())
+ .await??
+ .forget();
+ drop(server);
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ assert_eq!(peak.load(Ordering::SeqCst), 1);
+ assert_eq!(slots.available_permits(), 1);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn provider_failure_never_activates_baseline_caching() -> Result<(), BoxError> {
+ let configuration = Arc::new(Semaphore::new(0));
+ let provider_started = Arc::new(Semaphore::new(0));
+ let source_calls = Arc::new(AtomicUsize::new(0));
+ let source_slots = Arc::new(Semaphore::new(1));
+ // #region rust-provider-budget
+ let provider_slots = Arc::new(Semaphore::new(1));
+ let cache = DialCache::builder()
+ .policy_provider({
+ let slots = provider_slots.clone();
+ let configuration = configuration.clone();
+ let started = provider_started.clone();
+ move |_identity| {
+ let (slots, configuration, started) =
+ (slots.clone(), configuration.clone(), started.clone());
+ async move {
+ let _permit = slots.try_acquire_owned()?;
+ timeout(Duration::from_millis(200), async {
+ started.add_permits(1);
+ // Replace with a bounded config read, or use a local snapshot.
+ configuration.acquire().await?.forget();
+ Ok::<_, BoxError>(None::)
+ })
+ .await?
+ }
+ }
+ })
+ .build()?;
+ // An error stays an error: Ok(None) would activate the baseline policy.
+ // #endregion rust-provider-budget
+ let reader = cache
+ .use_case::("item", "boundedPolicy")
+ .policy(Policy::default().request_local(true).local_ttl_sec(60))
+ .key(|id: &u64| KeySpec::new(id))
+ .source({
+ let slots = source_slots.clone();
+ let calls = source_calls.clone();
+ move |_, _| {
+ let (slots, calls) = (slots.clone(), calls.clone());
+ async move {
+ let _permit = slots.try_acquire_owned()?;
+ Ok(calls.fetch_add(1, Ordering::SeqCst) + 1)
+ }
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ let first = tokio::spawn({
+ let (reader, scope) = (reader.clone(), request.scope().clone());
+ async move { reader.get(&scope, 1).await }
+ });
+ timeout(Duration::from_secs(2), provider_started.acquire())
+ .await??
+ .forget();
+ assert_eq!(provider_slots.available_permits(), 0);
+ // Both same-key and distinct-key invocations resolve policy before sharing.
+ for id in [1, 2, 1] {
+ reader.get(request.scope(), id).await?;
+ }
+ assert_eq!(source_calls.load(Ordering::SeqCst), 3);
+ assert_eq!(provider_started.available_permits(), 0);
+ let occupied = source_slots.acquire().await?;
+ let error = reader.get(request.scope(), 1).await.unwrap_err();
+ assert!(error.source_error().unwrap().is::());
+ drop(occupied);
+ assert_eq!(*timeout(Duration::from_secs(2), first).await???, 4);
+ assert_eq!(provider_slots.available_permits(), 1);
+ // No result from the failed provider entered the request or local cache.
+ assert_eq!(*reader.get(request.scope(), 1).await?, 5);
+ assert_eq!(*reader.get_uncached(1).await?, 6);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn source_guard_also_applies_to_disabled_shadow_calls() -> Result<(), BoxError> {
+ use dialcache::observe::ShadowOutcome;
+ use dialcache::{Event, Observer, Payload, ShadowPolicy, SystemClock};
+
+ struct Shadows(Arc);
+ impl Observer for Shadows {
+ fn observe(&self, event: &Event) {
+ if let Event::ShadowValidation { outcome, .. } = event {
+ assert_eq!(*outcome, ShadowOutcome::SourceError);
+ self.0.add_permits(1);
+ }
+ }
+ fn observes_shadow_outcomes(&self) -> bool {
+ true
+ }
+ }
+ let outcomes = Arc::new(Semaphore::new(0));
+ let slots = Arc::new(Semaphore::new(1));
+ let occupied = slots.acquire().await?;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let enabled_calls = Arc::new(AtomicUsize::new(0));
+ let cache = DialCache::builder()
+ .remote(SnapshotRemote(Payload::text("7")))
+ .clock(SystemClock::with_sources(|| Duration::ZERO, || 1_000))
+ .observer(Shadows(outcomes.clone()))
+ .build()?;
+ let reader = cache
+ .use_case::("item", "shadowAdmission")
+ .policy(Policy::default().remote_ttl_sec(60).shadow(ShadowPolicy {
+ ramp: Some(100.0),
+ ..Default::default()
+ }))
+ .key(|id: &u64| KeySpec::new(id))
+ .source({
+ let (slots, calls) = (slots.clone(), calls.clone());
+ let enabled_calls = enabled_calls.clone();
+ move |scope, _| {
+ if scope.is_enabled() {
+ enabled_calls.fetch_add(1, Ordering::SeqCst);
+ }
+ let (slots, calls) = (slots.clone(), calls.clone());
+ async move {
+ let _permit = slots.try_acquire_owned()?;
+ calls.fetch_add(1, Ordering::SeqCst);
+ Ok(7)
+ }
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ assert_eq!(*reader.get(request.scope(), 1).await?, 7);
+ timeout(Duration::from_secs(2), outcomes.acquire())
+ .await??
+ .forget();
+ assert!(reader
+ .get_uncached(1)
+ .await
+ .unwrap_err()
+ .source_error()
+ .unwrap()
+ .is::());
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ drop(occupied);
+ assert_eq!(*reader.get_uncached(1).await?, 7);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert_eq!(enabled_calls.load(Ordering::SeqCst), 0);
+ Ok(())
+ }
+}
+
+mod mutation_budgets {
+ use super::*;
+ use std::sync::Mutex;
+ use std::time::Duration;
+
+ use dialcache::{
+ CancelToken, InvalidateRequest, MissReason, ReadContext, ReadRequest, ReadResult, Remote,
+ SourceBudget, WriteRequest,
+ };
+ use futures::future::BoxFuture;
+ use tokio::sync::{oneshot, Semaphore};
+ use tokio::time::timeout;
+
+ // #region rust-mutation-budget
+ struct MutationBudget {
+ remote: Arc,
+ }
+
+ impl Remote for MutationBudget {
+ fn read(
+ &self,
+ request: ReadRequest,
+ context: ReadContext,
+ ) -> BoxFuture<'_, Result> {
+ self.remote.read(request, context)
+ }
+
+ fn write(&self, request: WriteRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(async move {
+ timeout(Duration::from_millis(200), async {
+ self.remote.write(request).await
+ })
+ .await?
+ })
+ }
+
+ fn invalidate(&self, request: InvalidateRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(async move {
+ // One timer covers the complete adapter call, including its retry.
+ timeout(Duration::from_millis(200), async {
+ self.remote.invalidate(request).await
+ })
+ .await?
+ })
+ }
+ }
+ // #endregion rust-mutation-budget
+
+ struct AcceptedCommands {
+ reads: Mutex>,
+ started: Semaphore,
+ release: Arc,
+ finished: Arc,
+ }
+
+ impl AcceptedCommands {
+ async fn dispatch(&self) -> Result<(), BoxError> {
+ let (reply, response) = oneshot::channel();
+ let (release, finished) = (self.release.clone(), self.finished.clone());
+ // A fake server keeps an accepted command even if its response is dropped.
+ tokio::spawn(async move {
+ release.acquire().await.unwrap().forget();
+ finished.add_permits(1);
+ let _ = reply.send(());
+ });
+ self.started.add_permits(1);
+ response.await?;
+ Ok(())
+ }
+ }
+
+ impl Remote for AcceptedCommands {
+ fn read(
+ &self,
+ request: ReadRequest,
+ context: ReadContext,
+ ) -> BoxFuture<'_, Result> {
+ self.reads.lock().unwrap().push((request, context));
+ Box::pin(async { Ok(ReadResult::miss(MissReason::ValueAbsent)) })
+ }
+
+ fn write(&self, _: WriteRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(self.dispatch())
+ }
+
+ fn invalidate(&self, _: InvalidateRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(self.dispatch())
+ }
+ }
+
+ #[tokio::test]
+ async fn mutation_timeout_ends_the_wait_not_the_accepted_command() -> Result<(), BoxError> {
+ let remote = Arc::new(AcceptedCommands {
+ reads: Mutex::new(Vec::new()),
+ started: Semaphore::new(0),
+ release: Arc::new(Semaphore::new(0)),
+ finished: Arc::new(Semaphore::new(0)),
+ });
+ let bounded = MutationBudget {
+ remote: remote.clone(),
+ };
+ let cancel = CancelToken::new();
+ let read = ReadRequest {
+ value_key: "value".into(),
+ watermark_key: Some("mark".into()),
+ };
+ bounded
+ .read(
+ read.clone(),
+ ReadContext {
+ timeout_ms: 17,
+ cancel: cancel.clone(),
+ },
+ )
+ .await?;
+ cancel.cancel();
+ {
+ let reads = remote.reads.lock().unwrap();
+ assert_eq!(reads[0].0, read);
+ assert_eq!(reads[0].1.timeout_ms, 17);
+ assert!(reads[0].1.cancel.is_cancelled());
+ }
+ let cache = DialCache::builder().remote(bounded).build()?;
+ let reader = cache
+ .use_case::("item", "boundedMutation")
+ .policy(Policy::default().remote_ttl_sec(60))
+ .budget(SourceBudget::Millis(5))
+ .key(|id: &u64| KeySpec::new(id))
+ .source(|_, id| async move { Ok(id) })
+ .register()?;
+ let request = cache.enable_guard();
+ let (first, follower) = timeout(Duration::from_secs(2), async {
+ tokio::join!(
+ reader.get(request.scope(), 1),
+ reader.get(request.scope(), 1)
+ )
+ })
+ .await?;
+ assert_eq!(*first?, 1);
+ assert_eq!(*follower?, 1);
+ assert_eq!(remote.started.available_permits(), 1);
+ assert_eq!(cache.coalescing_state().process.active_leaders, 0);
+ assert!(cache.invalidate("item", 1_u64, 0).await.is_err());
+ assert_eq!(remote.started.available_permits(), 2);
+ assert_eq!(remote.finished.available_permits(), 0);
+ remote.release.add_permits(2);
+ timeout(Duration::from_secs(2), remote.finished.acquire_many(2))
+ .await??
+ .forget();
+ Ok(())
+ }
+
+ #[cfg(feature = "redis")]
+ #[tokio::test]
+ async fn invalidation_retry_shares_one_mutation_deadline() -> Result<(), BoxError> {
+ use dialcache::{RedisAdapter, RedisConnection};
+
+ #[derive(Clone, Default)]
+ struct Scripts(Arc>>>);
+
+ impl RedisConnection for Scripts {
+ fn run(&self, command: redis::Cmd) -> BoxFuture<'_, redis::RedisResult> {
+ Box::pin(async move {
+ self.0.lock().unwrap().push(command.get_packed_command());
+ tokio::time::sleep(Duration::from_millis(125)).await;
+ if self.0.lock().unwrap().len() == 1 {
+ Err(std::io::Error::other("first script response failed").into())
+ } else {
+ Ok(redis::Value::Int(1))
+ }
+ })
+ }
+
+ fn run_on_primary(
+ &self,
+ _: &str,
+ command: redis::Cmd,
+ ) -> BoxFuture<'_, redis::RedisResult> {
+ self.run(command)
+ }
+ }
+ let connection = Scripts::default();
+ let bounded = MutationBudget {
+ remote: Arc::new(RedisAdapter::new(connection.clone())),
+ };
+ let error = bounded
+ .invalidate(InvalidateRequest {
+ watermark_key: "{example:item:1}#watermark".into(),
+ invalidated_at_ms: 1_000,
+ future_buffer_ms: 25,
+ })
+ .await
+ .unwrap_err();
+ assert!(error.is::());
+ let commands = connection.0.lock().unwrap();
+ assert_eq!(commands.len(), 2);
+ assert!(commands[0].windows(7).any(|s| s == b"EVALSHA"));
+ assert!(commands[1].windows(4).any(|s| s == b"EVAL"));
+ let arguments =
+ b"$1\r\n1\r\n$26\r\n{example:item:1}#watermark\r\n$2\r\n25\r\n$4\r\n1000\r\n";
+ assert!(commands.iter().all(|command| command.ends_with(arguments)));
+ Ok(())
+ }
+}
+
+mod bounded_values {
+ use super::*;
+ use dialcache::{Codec, JsonCodec, Payload};
+ use futures::future::BoxFuture;
+ use std::time::Duration;
+ use tokio::sync::Semaphore;
+
+ // #region rust-bounded-values
+ #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+ struct Digest([u8; 32]);
+
+ struct DigestCodec;
+
+ impl Codec for DigestCodec {
+ fn encode<'a>(&'a self, value: &'a Digest) -> BoxFuture<'a, Result> {
+ Box::pin(async move { JsonCodec::encode_value(value) })
+ }
+
+ fn decode(&self, payload: Payload) -> BoxFuture<'_, Result> {
+ Box::pin(async move {
+ if payload.len() > 129 {
+ return Err("digest JSON is too large".into());
+ }
+ JsonCodec::decode_value(&payload)
+ })
+ }
+ }
+ // #endregion rust-bounded-values
+
+ #[tokio::test]
+ async fn fixed_values_and_short_scopes_bound_retained_entries() -> Result<(), BoxError> {
+ use dialcache::SystemClock;
+ let payload = JsonCodec::encode_value(&Digest([255; 32]))?;
+ assert_eq!(payload.len(), 129);
+ let remote = SnapshotRemote(payload);
+ let clock = SystemClock::with_sources(|| Duration::ZERO, || 1_000);
+ // #region rust-bounded-scopes
+ let cache = DialCache::builder()
+ .local_capacity(1)
+ .remote(remote)
+ .clock(clock)
+ .build()?;
+ // #endregion rust-bounded-scopes
+ let source_calls = Arc::new(AtomicUsize::new(0));
+ let reader = cache
+ .use_case::("digest", "byId")
+ .policy(
+ Policy::default()
+ .request_local(true)
+ .local_ttl_sec(60)
+ .remote_ttl_sec(60),
+ )
+ .key(|id: &u8| KeySpec::new(*id as u64))
+ .codec(Arc::new(DigestCodec))
+ .source({
+ let calls = source_calls.clone();
+ move |_, id| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async move { Ok(Digest([id; 32])) }
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ let first = reader.get(request.scope(), 1).await?;
+ let first_weak = Arc::downgrade(&first);
+ drop(first);
+ let second = reader.get(request.scope(), 2).await?;
+ let second_weak = Arc::downgrade(&second);
+ drop(second);
+ assert_eq!(source_calls.load(Ordering::SeqCst), 0);
+ assert!(first_weak.upgrade().is_some());
+ drop(request);
+ assert!(first_weak.upgrade().is_none());
+ assert!(second_weak.upgrade().is_some());
+ let next = cache.enable_guard();
+ reader.get(next.scope(), 3).await?;
+ assert!(second_weak.upgrade().is_none());
+ drop(next);
+ // #region rust-bounded-request
+ // Keep this semaphore with the application's request handler.
+ let requests = Semaphore::new(1);
+ let _request_permit = requests.try_acquire()?;
+ let request = cache.enable_guard();
+ // This handler accepts at most two fixed-size IDs per request.
+ for id in [1_u8, 2] {
+ let digest = reader.get(request.scope(), id).await?;
+ assert_eq!(digest.0, [255; 32]);
+ }
+ drop(request);
+ // #endregion rust-bounded-request
+ assert!(requests.try_acquire().is_err());
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn invalid_remote_values_use_the_bounded_source_type() -> Result<(), BoxError> {
+ use dialcache::SystemClock;
+ for payload in [Payload::text("[0]"), Payload::text(" ".repeat(130))] {
+ let cache = DialCache::builder()
+ .remote(SnapshotRemote(payload))
+ .clock(SystemClock::with_sources(|| Duration::ZERO, || 1_000))
+ .build()?;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let reader = cache
+ .use_case::("digest", "fallback")
+ .policy(Policy::default().remote_ttl_sec(60))
+ .key(|id: &u8| KeySpec::new(*id as u64))
+ .codec(Arc::new(DigestCodec))
+ .source({
+ let calls = calls.clone();
+ move |_, id| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async move { Ok(Digest([id; 32])) }
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ assert_eq!(reader.get(request.scope(), 3).await?.0, [3; 32]);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn request_permit_covers_caller_retained_values() -> Result<(), BoxError> {
+ use dialcache::{Identity, Operation};
+
+ let requests = Semaphore::new(1);
+ let permit = requests.try_acquire()?;
+ let cache = DialCache::builder().local_capacity(0).build()?;
+ let request = cache.enable_guard();
+ let operation = Operation::::new(Identity::new("digest", 1_u64, "retained"))
+ .policy(Policy::default().request_local(true));
+ let value = cache
+ .get_or_load(request.scope(), operation, |_| async {
+ Ok(Digest([1; 32]))
+ })
+ .await?;
+ let weak = Arc::downgrade(&value);
+ drop(request);
+ assert!(weak.upgrade().is_some());
+ assert!(requests.try_acquire().is_err());
+ drop(value);
+ assert!(weak.upgrade().is_none());
+ drop(permit);
+ assert_eq!(requests.available_permits(), 1);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn digest_limit_runs_after_remote_decompression() -> Result<(), BoxError> {
+ use dialcache::limits::MAX_DECOMPRESSED_BYTES;
+ use dialcache::observe::CompressionOutcome;
+ use dialcache::protocol::{compress_payload, CompressionConfig};
+ use dialcache::SystemClock;
+
+ struct MeasuredCodec(Arc);
+
+ impl Codec for MeasuredCodec {
+ fn encode<'a>(&'a self, value: &'a Digest) -> BoxFuture<'a, Result> {
+ DigestCodec.encode(value)
+ }
+
+ fn decode(&self, payload: Payload) -> BoxFuture<'_, Result> {
+ self.0.store(payload.len(), Ordering::SeqCst);
+ DigestCodec.decode(payload)
+ }
+ }
+
+ let valid = JsonCodec::encode_value(&Digest([255; 32]))?;
+ let mut oversized = valid.clone();
+ oversized.bytes.resize(1 << 20, b' ');
+ for (payload, expected, source_calls) in [
+ (valid, 255, 0),
+ (oversized, 3, 1),
+ (JsonCodec::encode_value(&vec![0_u8; 33])?, 3, 1),
+ ] {
+ let size = payload.len();
+ let compressed = compress_payload(
+ payload,
+ &CompressionConfig {
+ threshold_bytes: 1,
+ ..CompressionConfig::default()
+ },
+ MAX_DECOMPRESSED_BYTES,
+ )?;
+ assert_eq!(compressed.outcome, CompressionOutcome::Compressed);
+ assert!(compressed.payload.len() < 129);
+ let cache = DialCache::builder()
+ .local_capacity(0)
+ .disable_compression()
+ .remote(SnapshotRemote(compressed.payload))
+ .clock(SystemClock::with_sources(|| Duration::ZERO, || 1_000))
+ .build()?;
+ let decoded_bytes = Arc::new(AtomicUsize::new(0));
+ let calls = Arc::new(AtomicUsize::new(0));
+ let reader = cache
+ .use_case::("digest", "compressed")
+ .policy(Policy::default().remote_ttl_sec(60))
+ .key(|id: &u8| KeySpec::new(*id as u64))
+ .codec(Arc::new(MeasuredCodec(decoded_bytes.clone())))
+ .source({
+ let calls = calls.clone();
+ move |_, id| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async move { Ok(Digest([id; 32])) }
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ let value = reader.get(request.scope(), 3).await?;
+ assert_eq!(decoded_bytes.load(Ordering::SeqCst), size);
+ assert_eq!(value.0, [expected; 32]);
+ assert_eq!(calls.load(Ordering::SeqCst), source_calls);
+ }
+ Ok(())
+ }
+}
+
+mod metric_transport {
+ use super::*;
+ use std::sync::mpsc::{sync_channel, SyncSender};
+
+ use dialcache::{DatadogObserver, DatadogOptions, DogStatsdClient, ObservationMetricType};
+
+ // #region rust-metric-queue
+ struct QueuedMetrics {
+ packets: SyncSender,
+ dropped: Arc,
+ }
+
+ impl QueuedMetrics {
+ fn send(&self, name: &str, value: f64, kind: &str, tags: &[(String, String)]) {
+ let value = value.to_string();
+ let size = name.len()
+ + value.len()
+ + kind.len()
+ + 4
+ + tags
+ .iter()
+ .map(|(key, value)| key.len() + value.len() + 1)
+ .sum::()
+ + tags.len().saturating_sub(1);
+ let unsafe_tag = tags.iter().any(|(key, value)| {
+ key.contains([':', '|', ',', '\n', '\r']) || value.contains(['|', ',', '\n', '\r'])
+ });
+ if size > 512 || name.contains([':', '|', ',', '\n', '\r']) || unsafe_tag {
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ return;
+ }
+ let tags = tags
+ .iter()
+ .map(|(key, value)| format!("{key}:{value}"))
+ .collect::>()
+ .join(",");
+ let packet = format!("{name}:{value}|{kind}|#{tags}");
+ if self.packets.try_send(packet).is_err() {
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+
+ impl DogStatsdClient for QueuedMetrics {
+ fn increment(&self, name: &str, value: f64, tags: &[(String, String)]) {
+ self.send(name, value, "c", tags);
+ }
+ fn histogram(&self, name: &str, value: f64, tags: &[(String, String)]) {
+ self.send(name, value, "h", tags);
+ }
+ fn distribution(&self, name: &str, value: f64, tags: &[(String, String)]) {
+ self.send(name, value, "d", tags);
+ }
+ }
+ // #endregion rust-metric-queue
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn full_or_closed_metric_queue_does_not_wait() -> Result<(), BoxError> {
+ let (packets, receiver) = sync_channel(1);
+ let (finished, completion) = sync_channel(1);
+ let watchdog = std::thread::spawn(move || {
+ let completed = completion
+ .recv_timeout(std::time::Duration::from_secs(2))
+ .is_ok();
+ let retained = receiver.try_recv();
+ drop(receiver);
+ (completed, retained)
+ });
+ let dropped = Arc::new(AtomicUsize::new(0));
+ let client = QueuedMetrics {
+ packets,
+ dropped: dropped.clone(),
+ };
+ client.increment("test", 1.0, &[]);
+ client.histogram("test", 0.25, &[]);
+ client.distribution("test", 0.5, &[]);
+ assert_eq!(dropped.load(Ordering::Relaxed), 2);
+ let observer = DatadogObserver::new(
+ client,
+ DatadogOptions::new(ObservationMetricType::Distribution),
+ )?;
+ let cache = DialCache::builder().observer(observer).build()?;
+ let reader = cache
+ .use_case::("item", "metricsQueue")
+ .policy(Policy::default().local_ttl_sec(60))
+ .key(|id: &u64| KeySpec::new(id))
+ .source(|_, id| async move {
+ if id == 0 {
+ Err("source failed".into())
+ } else {
+ Ok(id)
+ }
+ })
+ .register()?;
+ let request = cache.enable_guard();
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ reader.get(request.scope(), 1),
+ )
+ .await;
+ let _ = finished.send(());
+ let (completed, retained) = watchdog.join().unwrap();
+ assert!(completed, "metric export waited for its sink");
+ assert_eq!(retained?, "test:1|c|#");
+ assert_eq!(*result??, 1);
+ assert!(dropped.load(Ordering::Relaxed) > 2);
+ let before = dropped.load(Ordering::Relaxed);
+ assert_eq!(*reader.get(request.scope(), 1).await?, 1);
+ assert_eq!(dropped.load(Ordering::Relaxed), before + 2);
+ let error = reader.get(request.scope(), 0).await.unwrap_err();
+ assert_eq!(error.source_error().unwrap().to_string(), "source failed");
+ Ok(())
+ }
+
+ #[test]
+ fn bounded_packets_reach_only_the_local_test_socket() -> Result<(), BoxError> {
+ use dialcache::observe::Layer;
+ use dialcache::{Event, Labels, Observer};
+ use std::net::UdpSocket;
+ use std::time::Duration;
+
+ for (mode, kind) in [
+ (ObservationMetricType::Distribution, "d"),
+ (ObservationMetricType::Histogram, "h"),
+ ] {
+ let receiver = UdpSocket::bind("127.0.0.1:0")?;
+ receiver.set_read_timeout(Some(Duration::from_secs(2)))?;
+ let socket = UdpSocket::bind("127.0.0.1:0")?;
+ socket.connect(receiver.local_addr()?)?;
+ socket.set_write_timeout(Some(Duration::from_millis(50)))?;
+ let (packets, queue) = sync_channel::(4);
+ let (stopped, completion) = sync_channel(1);
+ let errors = Arc::new(AtomicUsize::new(0));
+ let send_errors = errors.clone();
+ let sender = std::thread::spawn(move || {
+ for packet in queue {
+ if socket.send(packet.as_bytes()).is_err() {
+ send_errors.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ stopped.send(()).unwrap();
+ });
+ let dropped = Arc::new(AtomicUsize::new(0));
+ let client = QueuedMetrics {
+ packets,
+ dropped: dropped.clone(),
+ };
+ client.increment("test", 1.0, &[("bad".into(), "newline\n".into())]);
+ client.increment("test", 1.0, &[("large".into(), "x".repeat(513))]);
+ assert_eq!(dropped.load(Ordering::Relaxed), 2);
+ let observer = DatadogObserver::new(client, DatadogOptions::new(mode))?;
+ let labels = Labels {
+ namespace: "example".into(),
+ use_case: "item:byId".into(),
+ key_type: "item".into(),
+ layer: Layer::Local,
+ };
+ observer.observe(&Event::Request {
+ labels: labels.clone(),
+ });
+ observer.observe(&Event::Get {
+ labels,
+ seconds: 0.25,
+ });
+ drop(observer);
+ completion.recv_timeout(Duration::from_secs(2))?;
+ sender.join().unwrap();
+ assert_eq!(errors.load(Ordering::Relaxed), 0);
+ assert_eq!(dropped.load(Ordering::Relaxed), 2);
+ let mut buffer = [0; 512];
+ let count = receiver.recv(&mut buffer)?;
+ assert_eq!(std::str::from_utf8(&buffer[..count])?, "dialcache.request.count:1|c|#cache_namespace:example,use_case:item:byId,key_type:item,layer:local");
+ let count = receiver.recv(&mut buffer)?;
+ assert_eq!(std::str::from_utf8(&buffer[..count])?, format!("dialcache.get.duration:0.25|{kind}|#cache_namespace:example,use_case:item:byId,key_type:item,layer:local"));
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn sender_counts_failed_sends_and_stops_after_all_producers() -> Result<(), BoxError> {
+ use std::net::UdpSocket;
+ use std::sync::mpsc::TryRecvError;
+ use std::time::Duration;
+
+ // An unconnected socket makes send fail without relying on remote ICMP.
+ let socket = UdpSocket::bind("127.0.0.1:0")?;
+ socket.set_write_timeout(Some(Duration::from_millis(50)))?;
+ let (packets, queue) = sync_channel::(4);
+ let (stopped, completion) = sync_channel(1);
+ let errors = Arc::new(AtomicUsize::new(0));
+ let send_errors = errors.clone();
+ let sender = std::thread::spawn(move || {
+ for packet in queue {
+ if socket.send(packet.as_bytes()).is_err() {
+ send_errors.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ stopped.send(()).unwrap();
+ });
+ let dropped = Arc::new(AtomicUsize::new(0));
+ let last_producer = QueuedMetrics {
+ packets: packets.clone(),
+ dropped: dropped.clone(),
+ };
+ let client = QueuedMetrics {
+ packets,
+ dropped: dropped.clone(),
+ };
+ client.increment("test", 1.0, &[]);
+ client.histogram("test", 0.25, &[]);
+ drop(client);
+ assert!(matches!(completion.try_recv(), Err(TryRecvError::Empty)));
+ last_producer.distribution("test", 0.5, &[]);
+ drop(last_producer);
+ completion.recv_timeout(Duration::from_secs(2))?;
+ sender.join().unwrap();
+ assert_eq!(errors.load(Ordering::Relaxed), 3);
+ assert_eq!(dropped.load(Ordering::Relaxed), 0);
+ Ok(())
+ }
+}
diff --git a/rust/tests/production_consumer/Cargo.lock b/rust/tests/production_consumer/Cargo.lock
new file mode 100644
index 00000000..5eaa26c3
--- /dev/null
+++ b/rust/tests/production_consumer/Cargo.lock
@@ -0,0 +1,490 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "cc"
+version = "1.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "dialcache"
+version = "0.27.0"
+dependencies = [
+ "futures",
+ "log",
+ "lru",
+ "parking_lot",
+ "ryu-js",
+ "serde",
+ "serde_json",
+ "slab",
+ "thiserror",
+ "tokio",
+ "zstd",
+ "zstd-safe 7.4.0",
+]
+
+[[package]]
+name = "dialcache-production-consumer"
+version = "0.0.0"
+dependencies = [
+ "dialcache",
+ "futures",
+ "serde",
+ "serde_json",
+ "tokio",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "futures"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom",
+ "libc",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lru"
+version = "0.18.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25"
+dependencies = [
+ "hashbrown",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "ryu-js"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio"
+version = "1.53.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
+dependencies = [
+ "pin-project-lite",
+ "tokio-macros",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zstd"
+version = "0.14.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
+dependencies = [
+ "zstd-safe 8.2.0",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "7.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "8.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.1.2+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
diff --git a/rust/tests/production_consumer/Cargo.toml b/rust/tests/production_consumer/Cargo.toml
new file mode 100644
index 00000000..96881f2f
--- /dev/null
+++ b/rust/tests/production_consumer/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "dialcache-production-consumer"
+version = "0.0.0"
+edition = "2021"
+publish = false
+
+[workspace]
+
+[dependencies]
+dialcache = { path = "../.." }
+futures = "0.3"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
diff --git a/rust/tests/production_consumer/src/main.rs b/rust/tests/production_consumer/src/main.rs
new file mode 100644
index 00000000..b78120ff
--- /dev/null
+++ b/rust/tests/production_consumer/src/main.rs
@@ -0,0 +1,341 @@
+#[cfg(not(panic = "unwind"))]
+compile_error!("The panic-containment check requires unwinding");
+
+use std::fmt::Debug;
+use std::future::ready;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use dialcache::observe::{ShadowMismatchLoggingOutcome, ShadowOutcome};
+use dialcache::preview::{
+ SHADOW_LOG_DIFF_MAX_BYTES, SHADOW_LOG_TRUNCATION_MARKER, SHADOW_LOG_VALUE_MAX_BYTES,
+ SHADOW_MISMATCH_MAX_ENTRIES,
+};
+use dialcache::{
+ BoxError, Clock, DialCache, Event, Frame, Identity, InvalidateRequest, LogEvent, Logger,
+ MismatchDiff, MismatchLogging, Observer, Operation, Payload, Policy, ReadContext, ReadRequest,
+ ReadResult, Remote, ShadowMismatchDetails, ShadowPolicy, SourceBudget, SystemClock,
+ WriteRequest,
+};
+use futures::future::BoxFuture;
+use serde::de::DeserializeOwned;
+use serde::ser::{Error, SerializeSeq};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use serde_json::{json, Value};
+use tokio::sync::oneshot;
+
+struct Snapshot(Frame);
+
+impl Remote for Snapshot {
+ fn read(&self, _: ReadRequest, _: ReadContext) -> BoxFuture<'_, Result> {
+ Box::pin(ready(Ok(ReadResult::Hit(self.0.clone()))))
+ }
+
+ fn write(&self, _: WriteRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(ready(Ok(())))
+ }
+
+ fn invalidate(&self, _: InvalidateRequest) -> BoxFuture<'_, Result<(), BoxError>> {
+ Box::pin(ready(Ok(())))
+ }
+}
+
+struct Recorder {
+ warning: Mutex