From 0bdf4ceed28ea7e803afc04e0d2daf5702cef22b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Fri, 4 Dec 2026 08:20:28 +0300 Subject: [PATCH 1/4] feat(core): envelope codec with make/decode/encode, strict data serializer and codec benchmark --- Cargo.lock | 280 +++++++- crates/babelqueue/Cargo.toml | 7 + crates/babelqueue/benches/README.md | 66 ++ crates/babelqueue/benches/codec.rs | 162 +++++ crates/babelqueue/src/codec.rs | 6 + crates/babelqueue/src/codec/decode.rs | 921 +++++++++++++++++++++++++ crates/babelqueue/src/codec/encode.rs | 564 +++++++++++++++ crates/babelqueue/src/codec/strict.rs | 519 ++++++++++++++ crates/babelqueue/src/envelope.rs | 300 ++++++++ crates/babelqueue/src/error.rs | 154 +++++ crates/babelqueue/src/lib.rs | 63 +- crates/babelqueue/src/uuid.rs | 60 ++ crates/babelqueue/tests/conformance.rs | 760 ++++++++++++++++++++ 13 files changed, 3827 insertions(+), 35 deletions(-) create mode 100644 crates/babelqueue/benches/README.md create mode 100644 crates/babelqueue/benches/codec.rs create mode 100644 crates/babelqueue/src/codec.rs create mode 100644 crates/babelqueue/src/codec/decode.rs create mode 100644 crates/babelqueue/src/codec/encode.rs create mode 100644 crates/babelqueue/src/codec/strict.rs create mode 100644 crates/babelqueue/src/envelope.rs create mode 100644 crates/babelqueue/src/error.rs create mode 100644 crates/babelqueue/src/uuid.rs create mode 100644 crates/babelqueue/tests/conformance.rs diff --git a/Cargo.lock b/Cargo.lock index 91e6d12..e7cc5f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,10 +2,38 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "babelqueue" version = "0.1.0" dependencies = [ + "criterion", "getrandom", "serde", "serde_json", @@ -18,12 +46,113 @@ dependencies = [ "babelqueue", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "criterion" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools", + "num-traits", + "oorandom", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "getrandom" version = "0.3.4" @@ -36,6 +165,26 @@ dependencies = [ "wasip2", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" @@ -54,6 +203,21 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -78,6 +242,44 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "serde" version = "1.0.229" @@ -85,6 +287,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -104,7 +307,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -120,6 +323,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -131,12 +345,32 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasip2" version = "1.0.1+wasi-0.2.4" @@ -146,12 +380,56 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "wit-bindgen" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/babelqueue/Cargo.toml b/crates/babelqueue/Cargo.toml index 69607f5..f23ce6d 100644 --- a/crates/babelqueue/Cargo.toml +++ b/crates/babelqueue/Cargo.toml @@ -19,3 +19,10 @@ getrandom.workspace = true [lints] workspace = true + +[dev-dependencies] +criterion = { version = "0.7.0", default-features = false, features = ["cargo_bench_support"] } + +[[bench]] +name = "codec" +harness = false diff --git a/crates/babelqueue/benches/README.md b/crates/babelqueue/benches/README.md new file mode 100644 index 0000000..276d67b --- /dev/null +++ b/crates/babelqueue/benches/README.md @@ -0,0 +1,66 @@ +# Codec benchmarks + +`benches/codec.rs` guards GR-8: the envelope encode/decode path may add at most 2% latency over a raw +broker publish/consume. It is pure CPU, no broker. The payload and the bare-JSON baseline mirror the +Go SDK's `bench_test.go` (`BenchmarkEnvelopeRoundTrip`, `BenchmarkBarePayloadJSON`), so the numbers +are comparable across SDKs. + +```sh +cargo bench -p babelqueue --bench codec # full run, ~2 minutes +cargo bench -p babelqueue --bench codec -- --quick # smoke run, ~15 seconds +``` + +`criterion` is a dev-dependency only (no `plotters`, no HTML reports); it is not part of +`cargo tree -p babelqueue -e normal`. + +## What is measured + +| Benchmark | Path | +| :- | :- | +| `make_encode` | `make` (UUIDs, strict serializer proxy, `RawValue` capture) + `Envelope::encode` | +| `decode` | `decode` (one scan, member walk, `data` number-validation pass) | +| `decode_and_read_data` | `decode` + `Envelope::data::()` (the lazy parse a handler pays) | +| `re_emit` | `decode` + `increment_attempts` + `encode` (what retry, DLQ, redrive and relay do) | +| `round_trip` | `make` + `encode` + `decode`, the Go benchmark's `envelopeRoundTrip` | +| `bare_json` | the baseline every publisher pays anyway: payload to bytes and back to a `serde_json::Value` | +| `top_level_keys/decode_N_extra` | `decode` of a body with N extra unknown top-level keys: the duplicate-key lookup (linear scan below `INDEX_THRESHOLD` = 32 members, hash index above) | + +`small` is the Go benchmark's payload (4 fields, 67 bytes of `data`). `medium_2kib` is 40 string +fields plus a list of 20 objects (about 2 KiB of `data`). + +## Baseline + +Taken on 2026-12-04, `cargo bench` (release profile, `criterion` 0.7, full run), rustc 1.100.1, +Apple Silicon (arm64) macOS laptop, otherwise idle. Time per operation, the middle value of +criterion's interval. + +| Benchmark | `small` | `medium_2kib` | +| :- | -: | -: | +| `make_encode` | 2.01 us | 5.05 us | +| `decode` | 851 ns | 4.05 us | +| `decode_and_read_data` | 1.12 us | - | +| `re_emit` | 995 ns | - | +| `round_trip` | 2.97 us | 9.25 us | +| `bare_json` | 299 ns | 7.60 us | + +Extra unknown top-level keys (`top_level_keys`, `decode`, threshold 32): 8 keys 1.14 us, 16 keys 1.77 us, 40 keys 4.58 us, 200 keys 17.4 us (about 85 ns per key; a scan-only lookup would take 46.9 us at 200 keys). The threshold was chosen from this: with the index at 16 keys, a 16-key body cost 2.15 us instead of 1.78 us. +## GR-8 reading + +GR-8 budgets the codec at 2% of a conservative 750 us broker round-trip (Go's +`referenceBrokerRoundTrip`), that is **15 us** of added time per message. + +- `small`: the full codec path costs 2.97 us, of which 0.30 us is what a publisher pays anyway. The + marginal cost is **2.67 us = 0.36%** of 750 us. +- `medium_2kib`: the full path costs 9.25 us and the bare baseline 7.60 us. The marginal cost is + **1.65 us = 0.22%** of 750 us. + +Go's gate additionally scales the 750 us reference by how fast the runner runs its bare-JSON baseline +(`marginal <= 2% * 750us * bare / 1.4us`). Rust's `serde_json` baseline is about 5x faster than the +Go calibration machine's, so that scaling shrinks the Rust budget to about 3.2 us for `small`; the +measured 2.67 us (1.7% on that scale) still fits, but the scaled form is not a meaningful gate for +this SDK and is not used here. A regression is a change that moves the absolute numbers above +noticeably; criterion reports it against the previous local run. + +The decode path scans `data` twice: once to capture it as raw text and once to validate its numbers +(`1e400` is poison). If a later change makes decode too slow, the planned replacement is a single +`DeserializeSeed` pass that validates and captures at once, with no API change (design D3). diff --git a/crates/babelqueue/benches/codec.rs b/crates/babelqueue/benches/codec.rs new file mode 100644 index 0000000..0e20034 --- /dev/null +++ b/crates/babelqueue/benches/codec.rs @@ -0,0 +1,162 @@ +//! Codec benchmarks guarding GR-8 (the envelope path may add at most 2% over a raw broker +//! round-trip). The payload and the bare-JSON baseline mirror the Go SDK's `bench_test.go`, so the +//! numbers are comparable. See `benches/README.md` for the baseline and how to read it. + +#![allow(missing_docs)] // `criterion_group!` generates an undocumented public function + +use std::collections::BTreeMap; +use std::hint::black_box; + +use babelqueue::{MakeOptions, decode, make}; +use criterion::{Criterion, criterion_group, criterion_main}; +use serde::Serialize; +use serde_json::Value; + +const URN: &str = "urn:babel:orders:created"; + +/// The Go benchmark's payload. +#[derive(Serialize)] +struct Order { + order_id: u32, + amount: f64, + currency: &'static str, + note: &'static str, +} + +const ORDER: Order = Order { + order_id: 1042, + amount: 99.9, + currency: "USD", + note: "café ☕", +}; + +/// A payload of roughly 2 KiB: 40 string fields plus a nested list. +fn medium_payload() -> BTreeMap { + let mut data: BTreeMap = (0..40) + .map(|i| { + ( + format!("field_{i:02}"), + Value::from(format!("value number {i} with some text")), + ) + }) + .collect(); + data.insert( + "items".to_owned(), + Value::from( + (0..20) + .map(|i| serde_json::json!({"sku": i, "qty": 2})) + .collect::>(), + ), + ); + data +} + +fn encoded(data: &T) -> Vec { + make(URN, data, MakeOptions::new().queue("orders")) + .expect("make") + .encode() + .expect("encode") +} + +fn bench_codec(c: &mut Criterion) { + let small = encoded(&ORDER); + let medium_data = medium_payload(); + let medium = encoded(&medium_data); + + let mut group = c.benchmark_group("small"); + group.bench_function("make_encode", |b| { + b.iter(|| { + let env = + make(URN, black_box(&ORDER), MakeOptions::new().queue("orders")).expect("make"); + black_box(env.encode().expect("encode")) + }); + }); + group.bench_function("decode", |b| { + b.iter(|| black_box(decode(black_box(&small)).expect("decode"))) + }); + group.bench_function("decode_and_read_data", |b| { + b.iter(|| { + let decoded = decode(black_box(&small)).expect("decode"); + black_box(decoded.envelope().data::().expect("data")) + }); + }); + group.bench_function("re_emit", |b| { + b.iter(|| { + let mut env = decode(black_box(&small)).expect("decode").into_envelope(); + env.increment_attempts(); + black_box(env.encode().expect("encode")) + }); + }); + // The full codec path of the Go benchmark: build, encode, decode. + group.bench_function("round_trip", |b| { + b.iter(|| { + let env = + make(URN, black_box(&ORDER), MakeOptions::new().queue("orders")).expect("make"); + let body = env.encode().expect("encode"); + black_box(decode(&body).expect("decode")) + }); + }); + // The baseline every publisher pays anyway: the bare payload, serialized and parsed. + group.bench_function("bare_json", |b| { + b.iter(|| { + let body = serde_json::to_vec(black_box(&ORDER)).expect("serialize"); + black_box(serde_json::from_slice::(&body).expect("parse")) + }); + }); + group.finish(); + + let mut group = c.benchmark_group("medium_2kib"); + group.bench_function("make_encode", |b| { + b.iter(|| { + let env = make( + URN, + black_box(&medium_data), + MakeOptions::new().queue("orders"), + ) + .expect("make"); + black_box(env.encode().expect("encode")) + }); + }); + group.bench_function("decode", |b| { + b.iter(|| black_box(decode(black_box(&medium)).expect("decode"))) + }); + group.bench_function("round_trip", |b| { + b.iter(|| { + let env = make( + URN, + black_box(&medium_data), + MakeOptions::new().queue("orders"), + ) + .expect("make"); + let body = env.encode().expect("encode"); + black_box(decode(&body).expect("decode")) + }); + }); + group.bench_function("bare_json", |b| { + b.iter(|| { + let body = serde_json::to_vec(black_box(&medium_data)).expect("serialize"); + black_box(serde_json::from_slice::(&body).expect("parse")) + }); + }); + group.finish(); + + // Many unknown top-level keys: exercises the duplicate-key lookup (a linear scan below + // `INDEX_THRESHOLD` members in `decode.rs`, a hash index above it). + let mut group = c.benchmark_group("top_level_keys"); + for extra in [8usize, 16, 40, 200] { + let mut body = String::from( + r#"{"job":"urn:a","trace_id":"t","data":{},"meta":{"id":"i","queue":"q","lang":"rust","schema_version":1,"created_at":1},"attempts":0"#, + ); + for i in 0..extra { + body.push_str(&format!(r#","x_{i:03}":{i}"#)); + } + body.push('}'); + group.bench_function(format!("decode_{extra}_extra"), |b| { + b.iter(|| black_box(decode(black_box(body.as_bytes())).expect("decode"))); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_codec); +criterion_main!(benches); diff --git a/crates/babelqueue/src/codec.rs b/crates/babelqueue/src/codec.rs new file mode 100644 index 0000000..330ded0 --- /dev/null +++ b/crates/babelqueue/src/codec.rs @@ -0,0 +1,6 @@ +//! The wire codec: [`decode`] for the consumer side, [`make`] and [`Envelope::encode`](crate::Envelope::encode) +//! for the producer side, and the strict serializer proxy both build on. + +pub(crate) mod decode; +pub(crate) mod encode; +pub(crate) mod strict; diff --git a/crates/babelqueue/src/codec/decode.rs b/crates/babelqueue/src/codec/decode.rs new file mode 100644 index 0000000..d08bd52 --- /dev/null +++ b/crates/babelqueue/src/codec/decode.rs @@ -0,0 +1,921 @@ +//! The consumer side: [`decode`] (ADR-0041 D2, design D3). +//! +//! The body is scanned once with `serde_json`: the top-level object (and, later, `meta` and +//! `dead_letter`) is walked member by member as `(String, &RawValue)` pairs, so `data` and every +//! unknown key are captured as raw text and written back verbatim on re-emit. A key that occurs more +//! than once resolves to its last occurrence (the value is replaced, never merged). Known members +//! are typed from their raw text; the numbers inside `data` get one validation pass so an +//! out-of-range number (`1e400`) makes the body poison. + +use std::collections::HashMap; +use std::fmt; + +use serde::de::{self, DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor}; +use serde_json::value::RawValue; + +use super::encode::FORBIDDEN_META_KEYS; +use crate::envelope::{DeadLetter, Envelope, Meta, RawMember, is_blank_ascii}; +use crate::error::DecodeError; + +/// A decoded envelope together with the non-fatal findings of the decode. +#[derive(Debug, Clone)] +pub struct Decoded { + envelope: Envelope, + warnings: Vec, +} + +impl Decoded { + /// The envelope. + #[must_use] + pub fn envelope(&self) -> &Envelope { + &self.envelope + } + + /// Consumes the result and returns the envelope, dropping the warnings. + #[must_use] + pub fn into_envelope(self) -> Envelope { + self.envelope + } + + /// The non-fatal problems the decode found: a dropped forbidden key + /// (message-envelope.md section 10), a dropped `urn` alias next to a non-blank `job`, or a + /// non-string `job` that was ignored (ADR-0032 section 6). Each names the key as an RFC 6901 + /// pointer, for example `/meta/max_retries`. Empty for a clean envelope. + #[must_use] + pub fn warnings(&self) -> &[String] { + &self.warnings + } + + /// Splits the result into the envelope and its warnings. + #[must_use] + pub fn into_parts(self) -> (Envelope, Vec) { + (self.envelope, self.warnings) + } +} + +/// Decodes a raw message body. +/// +/// `urn` is accepted as an inbound alias for `job` when `job` is missing, empty, only ASCII +/// whitespace or not a string; the decoded envelope carries the URN as `job` and never keeps `urn`. +/// When a non-blank `job` and a `urn` are both present, `job` wins and `urn` is dropped with a +/// warning. Unknown top-level and `meta` keys are kept, in order, for re-emit; forbidden keys +/// (`timestamp`, `meta.max_retries`, `meta.attempts`, `meta.source`, `meta.ts`) are dropped with a +/// warning. Envelope keys match byte for byte and case-sensitively: `JOB` is an unknown key. A +/// member that occurs more than once resolves to its last occurrence. +/// +/// The body is *poison* when decoding fails: it is not one valid JSON document (empty, truncated, a +/// byte order mark, trailing data, `NaN`, a leading-zero number, invalid UTF-8), its top-level value +/// is not an object, a known member has the wrong type (an integer member must be written as +/// `0|[1-9][0-9]*` within the signed 64-bit range), `data` is not an object, `data` holds an +/// out-of-range number, or there is no valid identity (ADR-0032 section 6, ADR-0036 decision 4). A +/// JSON `null` document has no identity either. +/// +/// # Errors +/// +/// A [`DecodeError`]; [`DecodeError::NoIdentity`] carries the envelope decoded so far. +/// +/// ``` +/// let body = br#"{"job":"urn:babel:orders:created","trace_id":"t","data":{"order_id":1042},"meta":{"id":"i","queue":"orders","lang":"go","schema_version":1,"created_at":1749132727000},"attempts":0}"#; +/// let decoded = babelqueue::decode(body)?; +/// assert_eq!(decoded.envelope().job(), "urn:babel:orders:created"); +/// assert!(decoded.envelope().accepts()); +/// assert!(decoded.warnings().is_empty()); +/// # Ok::<(), babelqueue::DecodeError>(()) +/// ``` +pub fn decode(raw: &[u8]) -> Result { + let mut de = serde_json::Deserializer::from_slice(raw); + let top = (&mut de) + .deserialize_any(MembersVisitor { allow_null: true }) + .map_err(DecodeError::Json)?; + de.end().map_err(DecodeError::Json)?; + match top { + Some(members) => build(members), + // A JSON `null` document names no handler: it has no identity. + None => Err(DecodeError::NoIdentity(Box::new(Decoded { + envelope: Envelope::empty(), + warnings: Vec::new(), + }))), + } +} + +// --------------------------------------------------------------------------------------------- +// Member scanning +// --------------------------------------------------------------------------------------------- + +/// Below this many members the duplicate lookup is a linear scan; from here on a hash index takes +/// over, so a body with very many keys cannot make decode quadratic. +/// +/// Measured with the `top_level_keys` benchmark (extra unknown top-level keys, release build): a +/// scan-only lookup costs 1.78 us at 16 extra keys, 4.40 us at 40 and 46.9 us at 200 (quadratic); an +/// index built at 16 costs 2.15 us, 4.19 us and 17.1 us. Building the index only pays off above +/// about 30 keys, so the switch is at 32, well past a normal envelope (about 10 members). +const INDEX_THRESHOLD: usize = 32; + +/// The members of one JSON object in first-seen order; a repeated key replaces the earlier value in +/// place (last wins). +struct Members<'de> { + items: Vec<(String, &'de RawValue)>, + index: Option>, +} + +impl<'de> Members<'de> { + fn new() -> Self { + Self { + items: Vec::new(), + index: None, + } + } + + fn insert(&mut self, key: String, value: &'de RawValue) { + if let Some(index) = &mut self.index { + if let Some(&slot) = index.get(&key) { + self.items[slot].1 = value; + } else { + index.insert(key.clone(), self.items.len()); + self.items.push((key, value)); + } + return; + } + if let Some(slot) = self.items.iter_mut().find(|(k, _)| *k == key) { + slot.1 = value; + return; + } + self.items.push((key, value)); + if self.items.len() >= INDEX_THRESHOLD { + self.index = Some( + self.items + .iter() + .enumerate() + .map(|(i, (k, _))| (k.clone(), i)) + .collect(), + ); + } + } +} + +/// Walks one JSON object into [`Members`]; with `allow_null` a JSON `null` yields `None`. +struct MembersVisitor { + allow_null: bool, +} + +impl<'de> Visitor<'de> for MembersVisitor { + type Value = Option>; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(if self.allow_null { + "a JSON object (the envelope) or null" + } else { + "a JSON object" + }) + } + + fn visit_unit(self) -> Result { + if self.allow_null { + Ok(None) + } else { + Err(E::invalid_type(de::Unexpected::Unit, &self)) + } + } + + fn visit_map>(self, mut map: A) -> Result { + let mut members = Members::new(); + while let Some(key) = map.next_key::()? { + let value: &'de RawValue = map.next_value()?; + members.insert(key, value); + } + Ok(Some(members)) + } +} + +fn members_of<'de>(text: &'de str, pointer: &str) -> Result, DecodeError> { + let mut de = serde_json::Deserializer::from_str(text); + match (&mut de).deserialize_any(MembersVisitor { allow_null: false }) { + Ok(Some(members)) => Ok(members), + Ok(None) => Err(invalid(pointer, "an object")), + Err(_) => Err(invalid(pointer, "a well-formed JSON object")), + } +} + +// --------------------------------------------------------------------------------------------- +// `data` validation +// --------------------------------------------------------------------------------------------- + +/// Parses every value of a JSON document the way a consumer would read it, and throws it away: a +/// number that does not fit an `f64` (`1e400`) and an invalid string escape make it fail. The raw +/// text is never altered. +struct Validate; + +impl<'de> Visitor<'de> for Validate { + type Value = (); + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("any JSON value") + } + + fn visit_bool(self, _: bool) -> Result<(), E> { + Ok(()) + } + + fn visit_i64(self, _: i64) -> Result<(), E> { + Ok(()) + } + + fn visit_u64(self, _: u64) -> Result<(), E> { + Ok(()) + } + + fn visit_f64(self, _: f64) -> Result<(), E> { + Ok(()) + } + + fn visit_str(self, _: &str) -> Result<(), E> { + Ok(()) + } + + fn visit_unit(self) -> Result<(), E> { + Ok(()) + } + + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while seq.next_element_seed(ValidateSeed)?.is_some() {} + Ok(()) + } + + fn visit_map>(self, mut map: A) -> Result<(), A::Error> { + while map.next_key::()?.is_some() { + map.next_value_seed(ValidateSeed)?; + } + Ok(()) + } +} + +struct ValidateSeed; + +impl<'de> DeserializeSeed<'de> for ValidateSeed { + type Value = (); + + fn deserialize>(self, deserializer: D) -> Result<(), D::Error> { + deserializer.deserialize_any(Validate) + } +} + +fn validate_data(text: &str) -> Result<(), DecodeError> { + let mut de = serde_json::Deserializer::from_str(text); + (&mut de).deserialize_any(Validate).map_err(|_| { + invalid( + "/data", + "made of well-formed values (a number outside the f64 range or a bad string escape is rejected)", + ) + }) +} + +// --------------------------------------------------------------------------------------------- +// Typing the known members +// --------------------------------------------------------------------------------------------- + +enum Kind { + Null, + String, + Object, + Other, +} + +fn kind(raw: &RawValue) -> Kind { + match raw.get().as_bytes().first() { + Some(b'n') => Kind::Null, + Some(b'"') => Kind::String, + Some(b'{') => Kind::Object, + _ => Kind::Other, + } +} + +fn invalid(pointer: &str, expected: &'static str) -> DecodeError { + DecodeError::InvalidField { + pointer: pointer.to_owned(), + expected, + } +} + +/// Reads a JSON string value. A failure (a lone surrogate escape) is reported against the member, not +/// as a `serde_json` error: its line and column would count inside the member text, not the body. +fn json_string(raw: &RawValue, pointer: &str) -> Result { + serde_json::from_str(raw.get()).map_err(|_| invalid(pointer, "a well-formed JSON string")) +} + +/// A string member; `null` reads as absent. +fn string_or_null(raw: &RawValue, pointer: &str) -> Result, DecodeError> { + match kind(raw) { + Kind::Null => Ok(None), + Kind::String => json_string(raw, pointer).map(Some), + _ => Err(invalid(pointer, "a string or null")), + } +} + +/// An integer member; `null` reads as absent. The text must be `0|[1-9][0-9]*` and fit `i64`, so a +/// fractional, exponent-form, negative (including `-0`) or overflowing number is rejected. +fn uint_or_null(raw: &RawValue, pointer: &str) -> Result, DecodeError> { + const EXPECTED: &str = "a non-negative integer within the signed 64-bit range, or null"; + let text = raw.get(); + if text == "null" { + return Ok(None); + } + let lexical = match text.as_bytes() { + [b'0'] => true, + [b'1'..=b'9', rest @ ..] => rest.iter().all(u8::is_ascii_digit), + _ => false, + }; + if !lexical { + return Err(invalid(pointer, EXPECTED)); + } + text.parse::() + .map(Some) + .map_err(|_| invalid(pointer, EXPECTED)) +} + +fn owned(raw: &RawValue) -> Box { + raw.to_owned() +} + +fn forbidden_warning(pointer: &str) -> String { + format!( + "babelqueue: dropped forbidden non-canonical envelope key {pointer} (message-envelope.md section 10)" + ) +} + +fn meta_from(raw: &RawValue) -> Result<(Meta, Vec, Vec), DecodeError> { + let mut meta = Meta::empty(); + let mut extras = Vec::new(); + let mut forbidden = Vec::new(); + if matches!(kind(raw), Kind::Null) { + return Ok((meta, extras, forbidden)); + } + if !matches!(kind(raw), Kind::Object) { + return Err(invalid("/meta", "an object or null")); + } + for (name, value) in members_of(raw.get(), "/meta")?.items { + match name.as_str() { + "id" => meta.id = string_or_null(value, "/meta/id")?.unwrap_or_default(), + "queue" => meta.queue = string_or_null(value, "/meta/queue")?.unwrap_or_default(), + "lang" => meta.lang = string_or_null(value, "/meta/lang")?.unwrap_or_default(), + "schema_version" => { + meta.schema_version = uint_or_null(value, "/meta/schema_version")?.unwrap_or(0); + } + "created_at" => { + meta.created_at = uint_or_null(value, "/meta/created_at")?.unwrap_or(0); + } + other if FORBIDDEN_META_KEYS.contains(&other) => forbidden.push(name), + _ => extras.push((name, owned(value))), + } + } + forbidden.sort_unstable(); + Ok((meta, extras, forbidden)) +} + +fn dead_letter_from(raw: &RawValue) -> Result, DecodeError> { + if matches!(kind(raw), Kind::Null) { + return Ok(None); + } + if !matches!(kind(raw), Kind::Object) { + return Err(invalid("/dead_letter", "an object or null")); + } + let mut dl = DeadLetter::empty(); + for (name, value) in members_of(raw.get(), "/dead_letter")?.items { + match name.as_str() { + "reason" => { + dl.reason = string_or_null(value, "/dead_letter/reason")?.unwrap_or_default() + } + "error" => dl.error = string_or_null(value, "/dead_letter/error")?, + "exception" => dl.exception = string_or_null(value, "/dead_letter/exception")?, + "failed_at" => { + dl.failed_at = uint_or_null(value, "/dead_letter/failed_at")?.unwrap_or(0); + } + "original_queue" => { + dl.original_queue = + string_or_null(value, "/dead_letter/original_queue")?.unwrap_or_default(); + } + "attempts" => { + dl.attempts = + uint_or_null(value, "/dead_letter/attempts")?.map_or(0, i64::unsigned_abs); + } + "lang" => dl.lang = string_or_null(value, "/dead_letter/lang")?.unwrap_or_default(), + _ => {} // unknown dead_letter members are not carried + } + } + Ok(Some(dl)) +} + +fn build(members: Members<'_>) -> Result { + let mut env = Envelope::empty(); + let mut warnings = Vec::new(); + + let mut job_ignored = false; + let mut alias: Option = None; // the `urn` alias, when it is a string + let mut urn_seen = false; + let mut forbidden_top: Vec<&str> = Vec::new(); + let mut meta_forbidden: Vec = Vec::new(); + + for (name, value) in members.items { + match name.as_str() { + "job" => match kind(value) { + // ADR-0032 section 6: a `job` that is not a string (`null` included) is ignored. + Kind::String => { + env.job = json_string(value, "/job")?; + } + _ => job_ignored = true, + }, + "urn" => { + urn_seen = true; + if matches!(kind(value), Kind::String) { + alias = Some(json_string(value, "/urn")?); + } + } + "trace_id" => { + env.trace_id = string_or_null(value, "/trace_id")?.unwrap_or_default(); + } + "data" => match kind(value) { + Kind::Null => {} + Kind::Object => { + validate_data(value.get())?; + env.data = Some(owned(value)); + } + _ => return Err(invalid("/data", "an object or null")), + }, + "meta" => (env.meta, env.meta_extras, meta_forbidden) = meta_from(value)?, + "attempts" => { + env.attempts = uint_or_null(value, "/attempts")?.map_or(0, i64::unsigned_abs); + } + "dead_letter" => env.dead_letter = dead_letter_from(value)?, + "timestamp" => forbidden_top.push("timestamp"), + _ => env.extras.push((name, owned(value))), + } + } + + // The `urn` key itself is never kept. It is silent only when it is the identity (a blank `job` + // and a string alias); otherwise it is dropped with a warning: next to a non-blank `job`, `job` + // wins, and a non-string alias is no alias at all. + let alias_takes_over = alias.is_some() && is_blank_ascii(&env.job); + if urn_seen && !alias_takes_over { + forbidden_top.push("urn"); + } + if let (true, Some(alias)) = (alias_takes_over, alias) { + env.job = alias; // copied verbatim; a padded alias stays padded and is judged by the consumer + } + + if job_ignored { + warnings.push( + "babelqueue: ignored non-string envelope key /job (ADR-0032 section 6)".to_owned(), + ); + } + forbidden_top.sort_unstable(); + warnings.extend( + forbidden_top + .iter() + .map(|k| forbidden_warning(&format!("/{k}"))), + ); + warnings.extend( + meta_forbidden + .iter() + .map(|k| forbidden_warning(&format!("/meta/{k}"))), + ); + + let blank = is_blank_ascii(&env.job); + let decoded = Decoded { + envelope: env, + warnings, + }; + if blank { + return Err(DecodeError::NoIdentity(Box::new(decoded))); + } + Ok(decoded) +} + +#[cfg(test)] +mod tests { + use serde::Deserialize; + + use super::*; + + const GOOD_META: &str = r#""meta":{"id":"i","queue":"q","lang":"php","schema_version":1,"created_at":1700000000000}"#; + + fn body(job: &str, extra: &str) -> String { + format!( + r#"{{"job":{job},"trace_id":"t","data":{{"a":1}},{GOOD_META},"attempts":0{extra}}}"# + ) + } + + fn ok(text: &str) -> Decoded { + decode(text.as_bytes()).unwrap_or_else(|e| panic!("{text}: {e}")) + } + + fn poison(text: &str) -> DecodeError { + decode(text.as_bytes()).expect_err(text) + } + + #[test] + fn decodes_a_canonical_envelope() { + let decoded = ok(&body(r#""urn:babel:orders:created""#, "")); + let env = decoded.envelope(); + assert_eq!(env.job(), "urn:babel:orders:created"); + assert_eq!(env.trace_id(), "t"); + assert_eq!(env.data_json(), Some(r#"{"a":1}"#)); + assert_eq!(env.meta().id(), "i"); + assert_eq!(env.meta().queue(), "q"); + assert_eq!(env.meta().lang(), "php"); + assert_eq!(env.meta().schema_version(), 1); + assert_eq!(env.meta().created_at(), 1_700_000_000_000); + assert_eq!(env.attempts(), 0); + assert!(env.accepts()); + assert!(decoded.warnings().is_empty()); + } + + #[test] + fn data_is_read_lazily_into_a_caller_type() { + #[derive(Deserialize)] + struct Order { + a: u8, + } + let env = ok(&body(r#""urn:a""#, "")).into_envelope(); + assert_eq!(env.data::().expect("order").a, 1); + assert!(matches!(env.data::>(), Err(DecodeError::Data(_)))); + let no_data = ok(r#"{"job":"urn:a"}"#).into_envelope(); + assert!(matches!(no_data.data::(), Err(DecodeError::Data(_)))); + } + + #[test] + fn syntax_problems_are_poison() { + for bad in [ + "", + " ", + "not-json", + r#"{"job":"urn:a""#, + "[]", + "123", + "\"s\"", + "true", + "\u{feff}{\"job\":\"urn:a\"}", + r#"{"job":"urn:a"} trailing"#, + r#"{"job":"urn:a"}{"job":"urn:b"}"#, + r#"{"job":"urn:a","attempts":01}"#, + r#"{"job":"urn:a","attempts":NaN}"#, + "{'job':'urn:a'}", + ] { + assert!(matches!(poison(bad), DecodeError::Json(_)), "{bad:?}"); + } + assert!( + matches!(decode(b"{\"job\":\"\xff\"}"), Err(DecodeError::Json(_))), + "invalid UTF-8" + ); + } + + #[test] + fn a_null_document_and_an_empty_object_have_no_identity() { + for text in ["null", "{}", r#"{"x":1}"#] { + assert!(poison(text).is_no_identity(), "{text}"); + } + } + + #[test] + fn known_members_of_the_wrong_type_are_poison() { + for bad in [ + r#"{"job":"urn:a","trace_id":7}"#, + r#"{"job":"urn:a","data":[]}"#, + r#"{"job":"urn:a","data":"x"}"#, + r#"{"job":"urn:a","meta":"x"}"#, + r#"{"job":"urn:a","meta":[]}"#, + r#"{"job":"urn:a","meta":{"id":5}}"#, + r#"{"job":"urn:a","meta":{"lang":true}}"#, + r#"{"job":"urn:a","meta":{"created_at":"2026"}}"#, + r#"{"job":"urn:a","meta":{"schema_version":1.0}}"#, + r#"{"job":"urn:a","attempts":"3"}"#, + r#"{"job":"urn:a","dead_letter":"x"}"#, + r#"{"job":"urn:a","dead_letter":{"reason":5}}"#, + r#"{"job":"urn:a","dead_letter":{"attempts":"3"}}"#, + ] { + assert!( + matches!(poison(bad), DecodeError::InvalidField { .. }), + "{bad}" + ); + } + } + + #[test] + fn integer_members_must_be_plain_non_negative_i64_literals() { + for good in ["0", "1", "2", "9223372036854775807"] { + let text = format!(r#"{{"job":"urn:a","attempts":{good}}}"#); + assert_eq!( + ok(&text).envelope().attempts(), + good.parse::().expect("u64") + ); + } + for bad in [ + "1.5", + "1.0", + "1e0", + "1E2", + "-0", + "-1", + "9223372036854775808", + "1e400", + "00", + ] { + let text = format!(r#"{{"job":"urn:a","attempts":{bad}}}"#); + assert!(decode(text.as_bytes()).is_err(), "attempts {bad}"); + } + for bad in ["1.5", "1e3", "1.0", "-0", "9223372036854775808"] { + let text = format!(r#"{{"job":"urn:a","meta":{{"created_at":{bad}}}}}"#); + assert!(decode(text.as_bytes()).is_err(), "created_at {bad}"); + } + } + + #[test] + fn null_known_members_read_as_their_zero_value() { + let env = ok( + r#"{"job":"urn:a","trace_id":null,"data":null,"meta":null,"attempts":null,"dead_letter":null}"#, + ) + .into_envelope(); + assert_eq!(env.trace_id(), ""); + assert!(env.data_json().is_none()); + assert_eq!(env.meta(), &Meta::empty()); + assert_eq!(env.attempts(), 0); + assert!(env.dead_letter().is_none()); + assert!(!env.accepts()); + let env = ok(r#"{"job":"urn:a","meta":{"schema_version":null,"id":null}}"#).into_envelope(); + assert_eq!(env.meta().schema_version(), 0); + } + + #[test] + fn duplicate_keys_resolve_to_the_last_occurrence() { + assert_eq!(ok(r#"{"job":5,"job":"urn:x"}"#).envelope().job(), "urn:x"); + assert!(poison(r#"{"job":"urn:x","job":5}"#).is_no_identity()); + // Objects are replaced, never merged. + let env = ok( + r#"{"job":"urn:a","data":{"a":1},"data":{"b":2},"meta":{"id":"i","x":1},"meta":{"queue":"q"}}"#, + ) + .into_envelope(); + assert_eq!(env.data_json(), Some(r#"{"b":2}"#)); + assert_eq!(env.meta().id(), ""); + assert_eq!(env.meta().queue(), "q"); + assert_eq!(env.meta_extras().count(), 0); + // A repeated unknown key keeps its first position and takes the last value. + let env = ok(r#"{"job":"urn:a","x":1,"y":2,"x":3}"#).into_envelope(); + assert_eq!( + env.extras().collect::>(), + vec![("x", "3"), ("y", "2")] + ); + } + + #[test] + fn many_keys_decode_without_a_quadratic_blowup_and_still_deduplicate() { + let mut text = String::from(r#"{"job":"urn:a""#); + for i in 0..5_000 { + text.push_str(&format!(r#","k{i}":{i}"#)); + } + text.push_str(r#","k0":"last","k4999":"last"}"#); + let env = ok(&text).into_envelope(); + assert_eq!(env.extras().count(), 5_000); + let extras: HashMap<_, _> = env.extras().collect(); + assert_eq!(extras["k0"], r#""last""#); + assert_eq!(extras["k4999"], r#""last""#); + assert_eq!(extras["k17"], "17"); + } + + #[test] + fn keys_are_case_sensitive() { + let text = r#"{"job":"urn:a","JOB":"urn:shadow","Data":{"x":1},"data":{"a":1},"META":5,"meta":{"Queue":"shadow","queue":"q"},"Attempts":9}"#; + let decoded = ok(text); + let env = decoded.envelope(); + assert_eq!(env.job(), "urn:a"); + assert_eq!(env.meta().queue(), "q"); + assert_eq!(env.attempts(), 0); + let extras: Vec<_> = env.extras().collect(); + assert_eq!( + extras, + vec![ + ("JOB", r#""urn:shadow""#), + ("Data", r#"{"x":1}"#), + ("META", "5"), + ("Attempts", "9") + ] + ); + assert_eq!( + env.meta_extras().collect::>(), + vec![("Queue", r#""shadow""#)] + ); + assert!(decoded.warnings().is_empty()); + assert!(poison(r#"{"JOB":"urn:x"}"#).is_no_identity()); + } + + #[test] + fn urn_alias_and_job_type_rules() { + // job missing / empty / ASCII-blank: the alias is the identity, silently, and verbatim. + for job in [ + "", + r#""job":"","#, + r#""job":" \t\r\n","#, + r#""job":"\u000b\u000c ","#, + ] { + let text = format!(r#"{{{job}"urn":" urn:b ","data":{{}}}}"#); + let decoded = ok(&text); + assert_eq!(decoded.envelope().job(), " urn:b ", "{text}"); + assert!(decoded.warnings().is_empty(), "{text}"); + assert_eq!(decoded.envelope().extras().count(), 0, "urn is never kept"); + } + // job not a string: ignored with a warning, alias takes over. + for job in ["null", "5", "true", "{}", "[]"] { + let text = format!(r#"{{"job":{job},"urn":"urn:b"}}"#); + let decoded = ok(&text); + assert_eq!(decoded.envelope().job(), "urn:b", "{text}"); + assert_eq!(decoded.warnings().len(), 1, "{text}"); + assert!(decoded.warnings()[0].contains("/job")); + } + // job and urn both usable: job wins, urn is dropped with a warning naming /urn. + let decoded = ok(r#"{"job":"urn:a","urn":"urn:b"}"#); + assert_eq!(decoded.envelope().job(), "urn:a"); + assert!(decoded.warnings().iter().any(|w| w.contains("/urn"))); + // a non-string urn next to a good job is dropped with a warning too. + assert!( + ok(r#"{"job":"urn:a","urn":5}"#) + .warnings() + .iter() + .any(|w| w.contains("/urn")) + ); + // a Unicode space is not blank: it does not fall back to the alias. + let decoded = ok("{\"job\":\"\u{2003}\",\"urn\":\"urn:b\"}"); + assert_eq!(decoded.envelope().job(), "\u{2003}"); + assert!(decoded.warnings().iter().any(|w| w.contains("/urn"))); + // no valid identity at all. + for text in [ + r#"{"job":null}"#, + r#"{"job":" "}"#, + r#"{"job":"","urn":""}"#, + r#"{"job":[],"urn":[]}"#, + r#"{"urn":5}"#, + r#"{"job":5,"urn":" \t"}"#, + ] { + assert!(poison(text).is_no_identity(), "{text}"); + } + } + + #[test] + fn no_identity_hands_back_the_envelope_decoded_so_far() { + let err = poison(r#"{"job":5,"attempts":4,"timestamp":1}"#); + let partial = err.partial().expect("partial"); + assert_eq!(partial.envelope().attempts(), 4); + assert_eq!(partial.warnings().len(), 2, "{:?}", partial.warnings()); + assert!(poison("[]").partial().is_none()); + } + + #[test] + fn forbidden_keys_are_dropped_with_a_warning_and_never_re_emitted() { + let decoded = ok(&body( + r#""urn:a""#, + r#","timestamp":5,"extra":1"#, + ).replace(r#""created_at":1700000000000"#, r#""created_at":1700000000000,"max_retries":3,"attempts":1,"source":"s","ts":2,"keep":true"#)); + let env = decoded.envelope(); + assert_eq!(decoded.warnings().len(), 5, "{:?}", decoded.warnings()); + for pointer in [ + "/timestamp", + "/meta/attempts", + "/meta/max_retries", + "/meta/source", + "/meta/ts", + ] { + assert!( + decoded.warnings().iter().any(|w| w.contains(pointer)), + "{pointer}" + ); + } + assert_eq!(env.extras().collect::>(), vec![("extra", "1")]); + assert_eq!( + env.meta_extras().collect::>(), + vec![("keep", "true")] + ); + let out = + String::from_utf8(env.encode().expect("a decoded envelope re-encodes")).expect("utf-8"); + for gone in ["timestamp", "max_retries", "source", "\"ts\""] { + assert!(!out.contains(gone), "{gone} in {out}"); + } + // forbidden keys of odd types are still just dropped. + assert!( + ok(r#"{"job":"urn:a","timestamp":"x","meta":{"max_retries":"x","ts":{}}}"#) + .warnings() + .len() + == 3 + ); + } + + #[test] + fn unknown_keys_keep_their_raw_text_and_order() { + let text = r#"{"job":"urn:a","z":{"b":1.0,"a":[1E2]},"y":null,"data":{},"meta":{"vendor":{"k":1},"ext":{"acme":{"tier":"gold"}}},"x-foo":-0.0}"#; + let env = ok(text).into_envelope(); + assert_eq!( + env.extras().collect::>(), + vec![ + ("z", r#"{"b":1.0,"a":[1E2]}"#), + ("y", "null"), + ("x-foo", "-0.0") + ] + ); + assert_eq!( + env.meta_extras().collect::>(), + vec![ + ("vendor", r#"{"k":1}"#), + ("ext", r#"{"acme":{"tier":"gold"}}"#) + ] + ); + } + + #[test] + fn data_numbers_are_validated_but_re_emitted_verbatim() { + let env = ok(r#"{"job":"urn:a","data":{"n":1.0e2,"big":18446744073709551616,"neg":-0.0}}"#) + .into_envelope(); + assert_eq!( + env.data_json(), + Some(r#"{"n":1.0e2,"big":18446744073709551616,"neg":-0.0}"#) + ); + for bad in [r#"{"n":1e400}"#, r#"{"a":[{"n":-1e999}]}"#] { + let text = format!(r#"{{"job":"urn:a","data":{bad}}}"#); + assert!( + matches!(poison(&text), DecodeError::InvalidField { ref pointer, .. } if pointer == "/data"), + "{bad}" + ); + } + } + + #[test] + fn member_level_failures_name_the_member_not_a_sub_document_position() { + // `serde_json` would report line 1 column 35 here, counted inside the data text. + let text = r#"{"job":"u","trace_id":"t","data":{"n":18446744073709551616,"f":1e400}}"#; + let message = poison(text).to_string(); + assert!(message.contains("/data"), "{message}"); + assert!(!message.contains("column"), "{message}"); + let message = poison(r#"{"job":"urn:a","trace_id":"\ud800"}"#).to_string(); + assert!(message.contains("/trace_id"), "{message}"); + } + + #[test] + fn a_lone_surrogate_in_data_is_poison() { + // Documented spec gap (design D3): there is no conformance case for it. The validation pass + // reads strings the way a consumer would, and a lone surrogate cannot be read as a string. + assert!(decode(br#"{"job":"urn:a","data":{"s":"\ud800"}}"#).is_err()); + assert!(decode(r#"{"job":"urn:a","data":{"s":"😀"}}"#.as_bytes()).is_ok()); + } + + #[test] + fn deeply_nested_data_is_bounded() { + let deep = format!("{}{}", "[".repeat(10_000), "]".repeat(10_000)); + let text = format!(r#"{{"job":"urn:a","data":{{"d":{deep}}}}}"#); + assert!( + decode(text.as_bytes()).is_err(), + "serde_json's recursion limit applies" + ); + } + + #[test] + fn dead_letter_block_is_typed_and_unknown_members_are_dropped() { + let env = ok( + r#"{"job":"urn:a","dead_letter":{"reason":"failed","error":null,"exception":"E","failed_at":5,"original_queue":"orders","attempts":3,"lang":"cobol","unknown":1}}"#, + ) + .into_envelope(); + let dl = env.dead_letter().expect("dead_letter"); + assert_eq!(dl.reason, "failed"); + assert_eq!(dl.error, None); + assert_eq!(dl.exception.as_deref(), Some("E")); + assert_eq!((dl.failed_at, dl.attempts), (5, 3)); + assert_eq!(dl.original_queue, "orders"); + assert_eq!(dl.lang, "cobol"); + } + + #[test] + fn accepts_follows_the_consumer_rules() { + assert!(ok(&body(r#""urn:a""#, "")).envelope().accepts()); + let blank_trace = + ok(&body(r#""urn:a""#, "").replace(r#""trace_id":"t""#, r#""trace_id":" \t\n""#)); + assert!(!blank_trace.envelope().accepts(), "blank trace_id"); + let v2 = + ok(&body(r#""urn:a""#, "").replace(r#""schema_version":1"#, r#""schema_version":2"#)); + assert!(!v2.envelope().accepts(), "unknown schema_version"); + assert!( + !ok(&body(r#""urn:a""#, "").replace(r#""trace_id":"t","#, "")) + .envelope() + .accepts() + ); + } + + #[test] + fn re_emit_never_trims_and_keeps_an_unusual_lang() { + let text = format!( + r#"{{"job":" urn:a\t","trace_id":"{ideographic}t ","data":{{}},"meta":{{"id":"i","queue":"q","lang":"Rust 1","schema_version":1,"created_at":1}},"attempts":0}}"#, + ideographic = '\u{3000}' + ); + let env = ok(&text).into_envelope(); + assert_eq!(env.job(), " urn:a\t"); + assert_eq!(env.trace_id(), "\u{3000}t "); + assert_eq!(env.meta().lang(), "Rust 1"); + let out = env.encode().expect("encode"); + let back = decode(&out).expect("decode").into_envelope(); + assert_eq!(back.job(), env.job()); + assert_eq!(back.trace_id(), env.trace_id()); + assert_eq!(back.meta(), env.meta()); + } +} diff --git a/crates/babelqueue/src/codec/encode.rs b/crates/babelqueue/src/codec/encode.rs new file mode 100644 index 0000000..39b62a4 --- /dev/null +++ b/crates/babelqueue/src/codec/encode.rs @@ -0,0 +1,564 @@ +//! The producer side: [`make`], the `meta` write API and [`Envelope::encode`]. + +use std::io::Write as _; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::Serialize; +use serde_json::value::RawValue; + +use super::strict::serialize_strict; +use crate::envelope::{DeadLetter, Envelope, Meta, RawMember, trim_ascii}; +use crate::error::EncodeError; +use crate::uuid::uuid_v4; +use crate::{SCHEMA_VERSION, SOURCE_LANG}; + +/// Core `meta` keys; an extension entry may not reuse them (ADR-0031 (b)). +pub(crate) const CORE_META_KEYS: [&str; 5] = + ["id", "queue", "lang", "schema_version", "created_at"]; +/// Top-level keys the frame writes itself. +const CORE_TOP_KEYS: [&str; 6] = ["job", "trace_id", "data", "meta", "attempts", "dead_letter"]; +/// Forbidden top-level keys (message-envelope.md section 10). `urn` is forbidden as a producer +/// field and is handled with them. +pub(crate) const FORBIDDEN_TOP_KEYS: [&str; 2] = ["timestamp", "urn"]; +/// Forbidden `meta` keys (message-envelope.md section 10). +pub(crate) const FORBIDDEN_META_KEYS: [&str; 4] = ["max_retries", "attempts", "source", "ts"]; + +/// Options of [`make`]: the queue name, a trace to continue and the `meta` extension entries. +/// +/// ``` +/// use babelqueue::MakeOptions; +/// +/// let opts = MakeOptions::new() +/// .queue("orders") +/// .trace_id("7b3f9c2a-e41d-4f88-9b2a-1c0d5e6f7a8b") +/// .meta("vendor_flag", &true); +/// # let _ = opts; +/// ``` +#[derive(Debug)] +pub struct MakeOptions { + queue: String, + trace_id: Option, + meta: Vec, + /// The first rejected `meta` entry; surfaced by [`make`], like Go's `WithMeta`. + meta_error: Option, +} + +impl Default for MakeOptions { + fn default() -> Self { + Self { + queue: "default".to_owned(), + trace_id: None, + meta: Vec::new(), + meta_error: None, + } + } +} + +impl MakeOptions { + /// Default options: queue `default`, a fresh trace id, no `meta` extensions. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Sets the logical queue name recorded in `meta.queue` (default `default`). + #[must_use] + pub fn queue(mut self, queue: impl Into) -> Self { + self.queue = queue.into(); + self + } + + /// Continues an existing trace: the id is trimmed with the ASCII set and reused unchanged, even + /// when it is not a UUID. A blank value is ignored and a fresh id is minted. + #[must_use] + pub fn trace_id(mut self, trace_id: impl Into) -> Self { + self.trace_id = Some(trace_id.into()); + self + } + + /// Adds one extension entry to `meta`, next to the core keys (ADR-0031 (b)). A vendor block is + /// supplied as the whole value of `ext` (`meta.ext.` is the recommended shape). + /// + /// The entry is rejected, and [`make`] returns the error, when the key is empty, collides with a + /// core `meta` key, is a forbidden key (message-envelope.md section 10), was already supplied, + /// or its value cannot be encoded as JSON. Matching is exact and case-sensitive. The first + /// rejection wins. + #[must_use] + pub fn meta(mut self, key: &str, value: &T) -> Self { + if self.meta_error.is_some() { + return self; + } + let pointer = || format!("/meta/{key}"); + let rejected = if key.is_empty() { + Some(EncodeError::EmptyKey) + } else if CORE_META_KEYS.contains(&key) { + Some(EncodeError::ReservedKey { pointer: pointer() }) + } else if FORBIDDEN_META_KEYS.contains(&key) { + Some(EncodeError::ForbiddenKey { pointer: pointer() }) + } else if self.meta.iter().any(|(k, _)| k == key) { + Some(EncodeError::DuplicateKey { pointer: pointer() }) + } else { + None + }; + if let Some(err) = rejected { + self.meta_error = Some(err); + return self; + } + match to_raw(value) { + Ok(raw) => self.meta.push((key.to_owned(), raw)), + Err(err) => self.meta_error = Some(err), + } + self + } +} + +/// Builds the canonical envelope for a `(urn, data)` pair. +/// +/// The URN and an explicit trace id are trimmed with the ASCII set (ADR-0032 section 5); a fresh v4 +/// UUID is minted for `trace_id` unless one is continued and always for `meta.id`. `attempts` +/// starts at 0, `meta.lang` is `rust`, `meta.schema_version` is 1 and `meta.created_at` is the +/// current Unix time in milliseconds. `data` is written straight from the caller's `Serialize` +/// implementation in its field order, through a strict proxy that rejects `NaN`/infinite floats. +/// +/// # Errors +/// +/// [`EncodeError::EmptyUrn`] when the URN is blank, [`EncodeError::DataNotObject`] when `data` does +/// not serialize to a JSON object (an empty map is `{}`), [`EncodeError::NonFiniteFloat`], the +/// first rejected [`MakeOptions::meta`] entry, or [`EncodeError::Serialize`]. +/// +/// ``` +/// use std::collections::BTreeMap; +/// +/// let mut data = BTreeMap::new(); +/// data.insert("order_id", 1042); +/// let env = babelqueue::make("urn:babel:orders:created", &data, babelqueue::MakeOptions::new().queue("orders"))?; +/// assert_eq!(env.job(), "urn:babel:orders:created"); +/// assert_eq!(env.data_json(), Some(r#"{"order_id":1042}"#)); +/// # Ok::<(), babelqueue::EncodeError>(()) +/// ``` +pub fn make( + urn: &str, + data: &T, + opts: MakeOptions, +) -> Result { + let urn = trim_ascii(urn); + if urn.is_empty() { + return Err(EncodeError::EmptyUrn); + } + if let Some(err) = opts.meta_error { + return Err(err); + } + let trace_id = match opts.trace_id.as_deref().map(trim_ascii) { + Some(t) if !t.is_empty() => t.to_owned(), + _ => uuid_v4()?, + }; + let data = to_raw(data)?; + if !data.get().starts_with('{') { + return Err(EncodeError::DataNotObject); + } + let created_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|d| i64::try_from(d.as_millis()).ok()) + .unwrap_or_default(); + Ok(Envelope { + job: urn.to_owned(), + trace_id, + data: Some(data), + meta: Meta { + id: uuid_v4()?, + queue: opts.queue, + lang: SOURCE_LANG.to_owned(), + schema_version: i64::from(SCHEMA_VERSION), + created_at, + }, + attempts: 0, + dead_letter: None, + extras: Vec::new(), + meta_extras: opts.meta, + }) +} + +/// Serializes any value strictly and keeps the text as a raw JSON value. +fn to_raw(value: &T) -> Result, EncodeError> { + let bytes = serialize_strict(value)?; + // `serde_json` produced these bytes, so they are valid UTF-8 and valid JSON. + let text = String::from_utf8(bytes) + .map_err(|e| EncodeError::Serialize(serde::ser::Error::custom(e)))?; + RawValue::from_string(text).map_err(EncodeError::Serialize) +} + +impl Envelope { + /// Renders the envelope as compact UTF-8 JSON in the canonical frame: + /// `{"job","trace_id","data","meta":{"id","queue","lang","schema_version","created_at",},"attempts"[,"dead_letter"][,]}`, without whitespace. + /// + /// `data` and every unknown key are written back as the raw text they were built or decoded + /// from; `job` and `trace_id` are never trimmed. Strings are written by `serde_json`: `/` and + /// non-ASCII are not escaped (the equivalent of `JSON_UNESCAPED_SLASHES|UNICODE`). U+2028 and + /// U+2029 are not escaped either, where PHP and Go escape them; the two forms are the same JSON. + /// + /// # Errors + /// + /// [`EncodeError::ForbiddenKey`] or [`EncodeError::ReservedKey`] when an extra carried by the + /// envelope is a forbidden key (including a leftover `urn`) or collides with a core key. + /// Nothing is produced then. A decoded envelope never carries such a key, so it always + /// re-encodes. + pub fn encode(&self) -> Result, EncodeError> { + self.check_extras()?; + let data_len = self.data.as_deref().map_or(4, |d| d.get().len()); + let mut out = Vec::with_capacity( + 192 + self.job.len() + self.trace_id.len() + data_len + self.meta.queue.len(), + ); + out.extend_from_slice(b"{\"job\":"); + write_str(&mut out, &self.job)?; + out.extend_from_slice(b",\"trace_id\":"); + write_str(&mut out, &self.trace_id)?; + out.extend_from_slice(b",\"data\":"); + out.extend_from_slice( + self.data + .as_deref() + .map_or("null", RawValue::get) + .as_bytes(), + ); + out.extend_from_slice(b",\"meta\":{\"id\":"); + write_str(&mut out, &self.meta.id)?; + out.extend_from_slice(b",\"queue\":"); + write_str(&mut out, &self.meta.queue)?; + out.extend_from_slice(b",\"lang\":"); + write_str(&mut out, &self.meta.lang)?; + write_num(&mut out, b",\"schema_version\":", self.meta.schema_version); + write_num(&mut out, b",\"created_at\":", self.meta.created_at); + write_members(&mut out, &self.meta_extras)?; + out.push(b'}'); + write_num(&mut out, b",\"attempts\":", self.attempts); + if let Some(dl) = &self.dead_letter { + out.extend_from_slice(b",\"dead_letter\":"); + write_dead_letter(&mut out, dl)?; + } + write_members(&mut out, &self.extras)?; + out.push(b'}'); + Ok(out) + } + + /// The encode-reject guard (ADR-0031 (b), (c)): applies to the extras the envelope carries, + /// whatever their origin. + fn check_extras(&self) -> Result<(), EncodeError> { + for (key, _) in &self.extras { + let pointer = || format!("/{key}"); + if FORBIDDEN_TOP_KEYS.contains(&key.as_str()) { + return Err(EncodeError::ForbiddenKey { pointer: pointer() }); + } + if CORE_TOP_KEYS.contains(&key.as_str()) { + return Err(EncodeError::ReservedKey { pointer: pointer() }); + } + } + for (key, _) in &self.meta_extras { + let pointer = || format!("/meta/{key}"); + if FORBIDDEN_META_KEYS.contains(&key.as_str()) { + return Err(EncodeError::ForbiddenKey { pointer: pointer() }); + } + if CORE_META_KEYS.contains(&key.as_str()) { + return Err(EncodeError::ReservedKey { pointer: pointer() }); + } + } + Ok(()) + } +} + +fn write_str(out: &mut Vec, s: &str) -> Result<(), EncodeError> { + serde_json::to_writer(out, s).map_err(EncodeError::Serialize) +} + +fn write_num(out: &mut Vec, prefix: &[u8], n: impl std::fmt::Display) { + out.extend_from_slice(prefix); + // Writing into a `Vec` cannot fail. + let _ = write!(out, "{n}"); +} + +/// Appends `,"key":` for every member. +fn write_members(out: &mut Vec, members: &[RawMember]) -> Result<(), EncodeError> { + for (key, raw) in members { + out.push(b','); + write_str(out, key)?; + out.push(b':'); + out.extend_from_slice(raw.get().as_bytes()); + } + Ok(()) +} + +fn write_opt_str(out: &mut Vec, s: Option<&str>) -> Result<(), EncodeError> { + match s { + Some(s) => write_str(out, s), + None => { + out.extend_from_slice(b"null"); + Ok(()) + } + } +} + +fn write_dead_letter(out: &mut Vec, dl: &DeadLetter) -> Result<(), EncodeError> { + out.extend_from_slice(b"{\"reason\":"); + write_str(out, &dl.reason)?; + out.extend_from_slice(b",\"error\":"); + write_opt_str(out, dl.error.as_deref())?; + out.extend_from_slice(b",\"exception\":"); + write_opt_str(out, dl.exception.as_deref())?; + write_num(out, b",\"failed_at\":", dl.failed_at); + out.extend_from_slice(b",\"original_queue\":"); + write_str(out, &dl.original_queue)?; + write_num(out, b",\"attempts\":", dl.attempts); + out.extend_from_slice(b",\"lang\":"); + write_str(out, &dl.lang)?; + out.push(b'}'); + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde::Serialize; + use serde_json::json; + + use super::*; + use crate::decode; + + #[derive(Serialize)] + struct Payload { + zeta: u8, + alpha: &'static str, + } + + fn payload() -> Payload { + Payload { + zeta: 1, + alpha: "a", + } + } + + #[test] + fn frame_is_canonical_compact_and_keeps_struct_field_order() { + let env = make( + "urn:babel:orders:created", + &payload(), + MakeOptions::new() + .queue("orders") + .trace_id("trace-1") + .meta("vendor", &json!({"a":[1,2]})), + ) + .expect("make"); + let body = String::from_utf8(env.encode().expect("encode")).expect("utf-8"); + let created_at = env.meta().created_at(); + let id = env.meta().id().to_owned(); + assert_eq!( + body, + format!( + r#"{{"job":"urn:babel:orders:created","trace_id":"trace-1","data":{{"zeta":1,"alpha":"a"}},"meta":{{"id":"{id}","queue":"orders","lang":"rust","schema_version":1,"created_at":{created_at},"vendor":{{"a":[1,2]}}}},"attempts":0}}"# + ) + ); + assert!( + created_at > 1_700_000_000_000, + "created_at is Unix milliseconds" + ); + } + + #[test] + fn make_defaults_mint_distinct_uuids() { + let a = make("urn:a", &payload(), MakeOptions::new()).expect("make"); + let b = make("urn:a", &payload(), MakeOptions::new()).expect("make"); + assert_eq!(a.meta().queue(), "default"); + assert_eq!(a.meta().lang(), "rust"); + assert_eq!(a.meta().schema_version(), 1); + assert_eq!(a.attempts(), 0); + assert_ne!(a.trace_id(), b.trace_id()); + assert_ne!(a.meta().id(), b.meta().id()); + assert_ne!(a.trace_id(), a.meta().id()); + } + + #[test] + fn make_trims_ascii_only_and_continues_a_trace_unchanged() { + let env = make( + " \turn:a\n", + &payload(), + MakeOptions::new().trace_id("\n not-a-uuid \t"), + ) + .expect("make"); + assert_eq!(env.job(), "urn:a"); + assert_eq!(env.trace_id(), "not-a-uuid"); + let env = make( + "\u{3000}urn:a", + &payload(), + MakeOptions::new().trace_id(" "), + ) + .expect("make"); + assert_eq!(env.job(), "\u{3000}urn:a"); + assert_eq!( + env.trace_id().len(), + 36, + "a blank trace id is replaced by a fresh UUID" + ); + assert!(matches!( + make(" \t\r\n", &payload(), MakeOptions::new()), + Err(EncodeError::EmptyUrn) + )); + } + + #[test] + fn data_must_be_an_object() { + let empty: BTreeMap = BTreeMap::new(); + let env = make("urn:a", &empty, MakeOptions::new()).expect("make"); + assert_eq!(env.data_json(), Some("{}")); + for bad in [json!([]), json!(null), json!(5), json!("x"), json!(true)] { + assert!( + matches!( + make("urn:a", &bad, MakeOptions::new()), + Err(EncodeError::DataNotObject) + ), + "{bad}" + ); + } + assert!(matches!( + make("urn:a", &vec![1, 2], MakeOptions::new()), + Err(EncodeError::DataNotObject) + )); + // A raw value is passed through the proxy verbatim, so its root is checked on the text. + let raw = RawValue::from_string("[1]".to_owned()).expect("raw"); + assert!(matches!( + make("urn:a", &*raw, MakeOptions::new()), + Err(EncodeError::DataNotObject) + )); + let raw = RawValue::from_string(r#"{"n":1.0e2}"#.to_owned()).expect("raw"); + let env = make("urn:a", &*raw, MakeOptions::new()).expect("make"); + assert_eq!(env.data_json(), Some(r#"{"n":1.0e2}"#)); + } + + #[test] + fn non_finite_floats_are_rejected_in_data_and_meta() { + let data = json!({"ok": 1}); + let mut bad = BTreeMap::new(); + bad.insert("amount", f64::NAN); + assert!(matches!( + make("urn:a", &bad, MakeOptions::new()), + Err(EncodeError::NonFiniteFloat) + )); + bad.insert("amount", f64::INFINITY); + assert!(matches!( + make("urn:a", &bad, MakeOptions::new()), + Err(EncodeError::NonFiniteFloat) + )); + let opts = MakeOptions::new().meta("score", &f64::NEG_INFINITY); + assert!(matches!( + make("urn:a", &data, opts), + Err(EncodeError::NonFiniteFloat) + )); + } + + #[test] + fn meta_write_api_rejects_empty_core_forbidden_and_repeated_keys() { + let ok = json!({"order_id": 1}); + let cases: [(&str, &str); 4] = [ + ("id", "/meta/id"), + ("schema_version", "/meta/schema_version"), + ("ts", "/meta/ts"), + ("source", "/meta/source"), + ]; + for (key, pointer) in cases { + let err = make("urn:a", &ok, MakeOptions::new().meta(key, &1)).expect_err(key); + assert!(err.to_string().contains(pointer), "{err}"); + } + assert!(matches!( + make("urn:a", &ok, MakeOptions::new().meta("", &1)), + Err(EncodeError::EmptyKey) + )); + assert!(matches!( + make( + "urn:a", + &ok, + MakeOptions::new().meta("ext", &1).meta("ext", &2) + ), + Err(EncodeError::DuplicateKey { .. }) + )); + // Matching is case-sensitive: `TS` is an ordinary key. + assert!(make("urn:a", &ok, MakeOptions::new().meta("TS", &1)).is_ok()); + // The first rejection wins. + let err = + make("urn:a", &ok, MakeOptions::new().meta("ts", &1).meta("", &1)).expect_err("first"); + assert!(matches!(err, EncodeError::ForbiddenKey { .. })); + } + + #[test] + fn encode_rejects_extras_with_forbidden_or_core_keys_and_writes_nothing() { + let base = make("urn:a", &payload(), MakeOptions::new()).expect("make"); + type Extras<'a> = &'a [(&'a str, &'a str)]; + let cases: [(Extras, Extras, &str); 6] = [ + (&[("timestamp", "1")], &[], "/timestamp"), + (&[("urn", r#""urn:a""#)], &[], "/urn"), + (&[("job", r#""x""#)], &[], "/job"), + (&[], &[("max_retries", "3")], "/meta/max_retries"), + (&[], &[("created_at", "0")], "/meta/created_at"), + (&[], &[("source", r#""s""#)], "/meta/source"), + ]; + for (top, meta, pointer) in cases { + let mut env = base.clone(); + env.__set_extras_for_conformance(top, meta) + .expect("raw extras"); + let err = env.encode().expect_err(pointer); + assert!(err.to_string().contains(pointer), "{err}"); + } + // Case-variants of forbidden keys are ordinary unknown keys. + let mut env = base; + env.__set_extras_for_conformance(&[("Timestamp", "1")], &[("TS", "1")]) + .expect("raw extras"); + assert!(env.encode().is_ok()); + } + + #[test] + fn re_emit_writes_raw_text_back_byte_for_byte_and_only_attempts_changes() { + let body = r#"{"job":" urn:a\t","trace_id":" t ","data":{"n":1.0e2,"big":18446744073709551616,"s":"é\/","z":-0.0,"o":{"b":1,"a":2}},"meta":{"id":"i","queue":"q","lang":"php","schema_version":1,"created_at":1,"x-foo":1E+2},"attempts":2,"extra":[1, 2 ,{"k":null}]}"#; + let mut env = decode(body.as_bytes()).expect("decode").into_envelope(); + env.increment_attempts(); + let out = String::from_utf8(env.encode().expect("encode")).expect("utf-8"); + // Whitespace inside the raw `extra` array is part of its raw text and is kept. + assert_eq!(out, body.replace(r#""attempts":2"#, r#""attempts":3"#)); + } + + #[test] + fn dead_letter_block_is_written_after_attempts_and_before_extras() { + let mut env = make("urn:a", &payload(), MakeOptions::new()).expect("make"); + let dl = DeadLetter { + reason: "failed".to_owned(), + error: Some("boom \"x\"".to_owned()), + failed_at: 5, + original_queue: "orders".to_owned(), + attempts: 3, + lang: "rust".to_owned(), + ..DeadLetter::empty() + }; + env.set_dead_letter(Some(dl)); + env.__set_extras_for_conformance(&[("extra_top", "1")], &[]) + .expect("extras"); + let out = String::from_utf8(env.encode().expect("encode")).expect("utf-8"); + assert!( + out.ends_with( + r#""attempts":0,"dead_letter":{"reason":"failed","error":"boom \"x\"","exception":null,"failed_at":5,"original_queue":"orders","attempts":3,"lang":"rust"},"extra_top":1}"# + ), + "{out}" + ); + let back = decode(out.as_bytes()).expect("decode").into_envelope(); + assert_eq!( + back.dead_letter().map(|d| d.reason.as_str()), + Some("failed") + ); + } + + #[test] + fn absent_data_re_emits_as_null() { + let env = decode(br#"{"job":"urn:a"}"#) + .expect("decode") + .into_envelope(); + assert!(!env.accepts()); + let out = String::from_utf8(env.encode().expect("encode")).expect("utf-8"); + assert!(out.contains(r#""data":null"#), "{out}"); + } +} diff --git a/crates/babelqueue/src/codec/strict.rs b/crates/babelqueue/src/codec/strict.rs new file mode 100644 index 0000000..a7fe040 --- /dev/null +++ b/crates/babelqueue/src/codec/strict.rs @@ -0,0 +1,519 @@ +//! The strict serializer proxy (ADR-0041 D2, design D3). +//! +//! `serde_json` writes a non-finite float as `null`, which would silently change a payload. The +//! proxy sits between the caller's `Serialize` implementation and `serde_json`'s serializer and +//! fails on a `NaN` or infinite `f32`/`f64` instead. Everything else is delegated untouched, so the +//! caller's field order and `serde_json`'s string escaping (no `/` or non-ASCII escaping) are kept. + +use std::cell::Cell; + +use serde::Serialize; +use serde::ser::{ + Error as _, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, + SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, +}; + +use crate::error::EncodeError; + +/// Serializes `value` to compact JSON bytes, rejecting non-finite floats. +pub(crate) fn serialize_strict(value: &T) -> Result, EncodeError> { + let non_finite = Cell::new(false); + let mut out = Vec::with_capacity(128); + let result = { + let mut serializer = serde_json::Serializer::new(&mut out); + value.serialize(Strict { + inner: &mut serializer, + non_finite: &non_finite, + }) + }; + if non_finite.get() { + return Err(EncodeError::NonFiniteFloat); + } + result.map_err(EncodeError::Serialize)?; + Ok(out) +} + +/// The proxy: wraps a serializer, or one of its compound serializers, and a shared flag that is set +/// when a non-finite float is seen. +struct Strict<'f, S> { + inner: S, + non_finite: &'f Cell, +} + +/// Wraps a nested value so it is serialized through the proxy as well. +struct Wrap<'f, 'v, T: ?Sized> { + value: &'v T, + non_finite: &'f Cell, +} + +impl Serialize for Wrap<'_, '_, T> { + fn serialize(&self, serializer: S) -> Result { + self.value.serialize(Strict { + inner: serializer, + non_finite: self.non_finite, + }) + } +} + +macro_rules! delegate { + ($($method:ident($ty:ty);)*) => { + $( + fn $method(self, v: $ty) -> Result { + self.inner.$method(v) + } + )* + }; +} + +impl<'f, S: Serializer> Strict<'f, S> { + fn reject(&self) -> S::Error { + self.non_finite.set(true); + S::Error::custom("NaN and infinite floats are not valid JSON") + } +} + +impl<'f, S: Serializer> Serializer for Strict<'f, S> { + type Ok = S::Ok; + type Error = S::Error; + type SerializeSeq = Strict<'f, S::SerializeSeq>; + type SerializeTuple = Strict<'f, S::SerializeTuple>; + type SerializeTupleStruct = Strict<'f, S::SerializeTupleStruct>; + type SerializeTupleVariant = Strict<'f, S::SerializeTupleVariant>; + type SerializeMap = Strict<'f, S::SerializeMap>; + type SerializeStruct = Strict<'f, S::SerializeStruct>; + type SerializeStructVariant = Strict<'f, S::SerializeStructVariant>; + + delegate! { + serialize_bool(bool); + serialize_i8(i8); + serialize_i16(i16); + serialize_i32(i32); + serialize_i64(i64); + serialize_i128(i128); + serialize_u8(u8); + serialize_u16(u16); + serialize_u32(u32); + serialize_u64(u64); + serialize_u128(u128); + serialize_char(char); + serialize_str(&str); + serialize_bytes(&[u8]); + } + + fn serialize_f32(self, v: f32) -> Result { + if v.is_finite() { + self.inner.serialize_f32(v) + } else { + Err(self.reject()) + } + } + + fn serialize_f64(self, v: f64) -> Result { + if v.is_finite() { + self.inner.serialize_f64(v) + } else { + Err(self.reject()) + } + } + + fn serialize_none(self) -> Result { + self.inner.serialize_none() + } + + fn serialize_some(self, value: &T) -> Result { + self.inner.serialize_some(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn serialize_unit(self) -> Result { + self.inner.serialize_unit() + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + self.inner.serialize_unit_struct(name) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result { + self.inner + .serialize_unit_variant(name, variant_index, variant) + } + + fn serialize_newtype_struct( + self, + name: &'static str, + value: &T, + ) -> Result { + self.inner.serialize_newtype_struct( + name, + &Wrap { + value, + non_finite: self.non_finite, + }, + ) + } + + fn serialize_newtype_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result { + self.inner.serialize_newtype_variant( + name, + variant_index, + variant, + &Wrap { + value, + non_finite: self.non_finite, + }, + ) + } + + fn serialize_seq(self, len: Option) -> Result { + Ok(Strict { + inner: self.inner.serialize_seq(len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_tuple(self, len: usize) -> Result { + Ok(Strict { + inner: self.inner.serialize_tuple(len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(Strict { + inner: self.inner.serialize_tuple_struct(name, len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(Strict { + inner: self + .inner + .serialize_tuple_variant(name, variant_index, variant, len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_map(self, len: Option) -> Result { + Ok(Strict { + inner: self.inner.serialize_map(len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(Strict { + inner: self.inner.serialize_struct(name, len)?, + non_finite: self.non_finite, + }) + } + + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(Strict { + inner: self + .inner + .serialize_struct_variant(name, variant_index, variant, len)?, + non_finite: self.non_finite, + }) + } + + fn collect_str( + self, + value: &T, + ) -> Result { + self.inner.collect_str(value) + } + + fn is_human_readable(&self) -> bool { + self.inner.is_human_readable() + } +} + +impl SerializeSeq for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> { + self.inner.serialize_element(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeTuple for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> { + self.inner.serialize_element(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeTupleStruct for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> { + self.inner.serialize_field(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeTupleVariant for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> { + self.inner.serialize_field(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeMap for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> { + self.inner.serialize_key(&Wrap { + value: key, + non_finite: self.non_finite, + }) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> { + self.inner.serialize_value(&Wrap { + value, + non_finite: self.non_finite, + }) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeStruct for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> { + self.inner.serialize_field( + key, + &Wrap { + value, + non_finite: self.non_finite, + }, + ) + } + + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + self.inner.skip_field(key) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +impl SerializeStructVariant for Strict<'_, C> { + type Ok = C::Ok; + type Error = C::Error; + + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> { + self.inner.serialize_field( + key, + &Wrap { + value, + non_finite: self.non_finite, + }, + ) + } + + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + self.inner.skip_field(key) + } + + fn end(self) -> Result { + self.inner.end() + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde::Serialize; + use serde::ser::{SerializeMap, SerializeSeq, Serializer}; + + use super::*; + + fn json(value: &T) -> String { + String::from_utf8(serialize_strict(value).expect("serializes")).expect("utf-8") + } + + #[derive(Serialize)] + struct Order<'a> { + zeta: u32, + alpha: &'a str, + amount: f64, + tags: Vec<&'a str>, + note: Option<&'a str>, + } + + #[test] + fn keeps_struct_field_order_and_finite_floats() { + let order = Order { + zeta: 1, + alpha: "a/b é", + amount: 99.9, + tags: vec!["x", "y"], + note: None, + }; + assert_eq!( + json(&order), + r#"{"zeta":1,"alpha":"a/b é","amount":99.9,"tags":["x","y"],"note":null}"# + ); + } + + #[test] + fn does_not_escape_slash_or_non_ascii_but_escapes_controls() { + let mut map = BTreeMap::new(); + map.insert("k", "http://x/y \u{1F600} \u{2028} \"q\" \n"); + assert_eq!( + json(&map), + "{\"k\":\"http://x/y \u{1F600} \u{2028} \\\"q\\\" \\n\"}" + ); + } + + #[test] + fn rejects_nan_and_infinity_at_any_depth() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut map = BTreeMap::new(); + map.insert("a", vec![vec![bad]]); + assert!( + matches!(serialize_strict(&map), Err(EncodeError::NonFiniteFloat)), + "{bad}" + ); + } + let mut map = BTreeMap::new(); + map.insert("a", f32::NAN); + assert!(matches!( + serialize_strict(&map), + Err(EncodeError::NonFiniteFloat) + )); + // `Option`, newtype structs and tuples go through the proxy too. + assert!(matches!( + serialize_strict(&(Some(f64::NAN), 1)), + Err(EncodeError::NonFiniteFloat) + )); + } + + #[test] + fn rejects_non_finite_float_map_keys_and_values_written_by_hand() { + struct Handwritten; + impl Serialize for Handwritten { + fn serialize(&self, s: S) -> Result { + let mut map = s.serialize_map(Some(1))?; + map.serialize_entry("k", &f64::INFINITY)?; + map.end() + } + } + assert!(matches!( + serialize_strict(&Handwritten), + Err(EncodeError::NonFiniteFloat) + )); + + struct Seq; + impl Serialize for Seq { + fn serialize(&self, s: S) -> Result { + let mut seq = s.serialize_seq(None)?; + seq.serialize_element(&1)?; + seq.serialize_element(&f64::NAN)?; + seq.end() + } + } + assert!(matches!( + serialize_strict(&Seq), + Err(EncodeError::NonFiniteFloat) + )); + } + + #[test] + fn a_failing_serialize_impl_is_a_serialize_error_not_a_non_finite_one() { + struct Failing; + impl Serialize for Failing { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("boom")) + } + } + assert!(matches!( + serialize_strict(&Failing), + Err(EncodeError::Serialize(_)) + )); + } +} diff --git a/crates/babelqueue/src/envelope.rs b/crates/babelqueue/src/envelope.rs new file mode 100644 index 0000000..8ec75c8 --- /dev/null +++ b/crates/babelqueue/src/envelope.rs @@ -0,0 +1,300 @@ +//! The envelope value: the in-memory form of the canonical wire message. + +use serde::de::DeserializeOwned; +use serde_json::value::RawValue; + +use crate::SCHEMA_VERSION; +use crate::error::DecodeError; + +/// A raw JSON member kept verbatim, in the order it was seen. +pub(crate) type RawMember = (String, Box); + +/// The canonical BabelQueue message: `{job, trace_id, data, meta, attempts}` plus an optional +/// `dead_letter` block (message-envelope.md sections 2, 3 and 10b). +/// +/// An envelope comes from [`make`](crate::make) (a new message) or [`decode`](crate::decode) (a +/// received one). `data` and every unknown key are kept as the raw JSON text they arrived as, so a +/// re-emit ([`Envelope::encode`]) writes them back byte for byte; only `attempts` changes on a retry. +#[derive(Debug, Clone)] +pub struct Envelope { + pub(crate) job: String, + pub(crate) trace_id: String, + /// `None` when `data` was absent or `null` on the wire. Such an envelope is not accepted + /// ([`Envelope::accepts`]) and re-emits `"data":null`. + pub(crate) data: Option>, + pub(crate) meta: Meta, + pub(crate) attempts: u64, + pub(crate) dead_letter: Option, + /// Unknown top-level members, in insertion order (message-envelope.md section 8 rule 7). + pub(crate) extras: Vec, + /// Unknown `meta` members, in insertion order. + pub(crate) meta_extras: Vec, +} + +/// The immutable producer metadata block (message-envelope.md section 4). +/// +/// A member that was absent or `null` on the wire reads as its zero value (`""`, `0`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Meta { + pub(crate) id: String, + pub(crate) queue: String, + pub(crate) lang: String, + pub(crate) schema_version: i64, + pub(crate) created_at: i64, +} + +impl Meta { + /// The all-zero block of a body whose `meta` was absent or `null`. Crate-private: there is no + /// public way to build an empty envelope. + pub(crate) fn empty() -> Self { + Self { + id: String::new(), + queue: String::new(), + lang: String::new(), + schema_version: 0, + created_at: 0, + } + } + + /// The unique id of this specific message (distinct from `trace_id`). + #[must_use] + pub fn id(&self) -> &str { + &self.id + } + + /// The logical queue name the message was produced onto (not the broker key). + #[must_use] + pub fn queue(&self) -> &str { + &self.queue + } + + /// The producer language tag. Observability only, never routing: it is kept as it arrived, even + /// when it does not match the tag pattern (ADR-0040). + #[must_use] + pub fn lang(&self) -> &str { + &self.lang + } + + /// The envelope schema version the producer declared. + #[must_use] + pub fn schema_version(&self) -> i64 { + self.schema_version + } + + /// Production time as Unix epoch milliseconds, UTC. + #[must_use] + pub fn created_at(&self) -> i64 { + self.created_at + } +} + +/// The additive block carried by a message on a dead-letter queue (message-envelope.md section 10b, +/// ADR-0009). Unknown members of the block are not carried. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct DeadLetter { + /// Why the message was dead-lettered: `failed`, `unknown_urn` or `poison`. + pub reason: String, + /// The failure message, or `None` when no cause was supplied (`null` on the wire). + pub error: Option, + /// The failure type, or `None` when no cause was supplied (`null` on the wire). + pub exception: Option, + /// When the message failed, as Unix epoch milliseconds, UTC. + pub failed_at: i64, + /// The queue the message was consumed from. + pub original_queue: String, + /// The attempts the message had made when it was dead-lettered. + pub attempts: u64, + /// The language tag of the SDK that dead-lettered the message. + pub lang: String, +} + +impl DeadLetter { + /// A block of empty strings and zeros, filled in member by member. Crate-private: a dead-letter + /// block is built by the SDK (the DLQ helper) and read back by callers, never assembled outside. + pub(crate) fn empty() -> Self { + Self { + reason: String::new(), + error: None, + exception: None, + failed_at: 0, + original_queue: String::new(), + attempts: 0, + lang: String::new(), + } + } +} + +impl Envelope { + /// An envelope with no identity and no data, the starting point of `decode`. Crate-private and + /// deliberately not `Default`: an empty envelope is not a valid message and must not be buildable + /// (and encodable) from outside the crate. + pub(crate) fn empty() -> Self { + Self { + job: String::new(), + trace_id: String::new(), + data: None, + meta: Meta::empty(), + attempts: 0, + dead_letter: None, + extras: Vec::new(), + meta_extras: Vec::new(), + } + } + + /// The message URN: the canonical `job`, with the inbound `urn` alias already resolved by + /// [`decode`](crate::decode). Never trimmed on decode or re-emit. + #[must_use] + pub fn job(&self) -> &str { + &self.job + } + + /// Alias of [`Envelope::job`]; identity is the URN, never a class name. + #[must_use] + pub fn urn(&self) -> &str { + &self.job + } + + /// The correlation id, preserved unchanged across every hop. + #[must_use] + pub fn trace_id(&self) -> &str { + &self.trace_id + } + + /// The `meta` block. + #[must_use] + pub fn meta(&self) -> &Meta { + &self.meta + } + + /// The top-level transport retry counter. + #[must_use] + pub fn attempts(&self) -> u64 { + self.attempts + } + + /// Sets the retry counter, saturating at `i64::MAX` (the largest value every SDK reads back). + pub fn set_attempts(&mut self, attempts: u64) { + self.attempts = attempts.min(i64::MAX.unsigned_abs()); + } + + /// Adds one to the retry counter (the step of every retry, redrive and relay hop). + pub fn increment_attempts(&mut self) { + self.set_attempts(self.attempts.saturating_add(1)); + } + + /// The `dead_letter` block, present only on a dead-lettered message. + #[must_use] + pub fn dead_letter(&self) -> Option<&DeadLetter> { + self.dead_letter.as_ref() + } + + /// Attaches, replaces or (with `None`) removes the `dead_letter` block. + pub fn set_dead_letter(&mut self, dead_letter: Option) { + self.dead_letter = dead_letter; + } + + /// The raw JSON text of `data` exactly as received or built, or `None` when it was absent or + /// `null`. + #[must_use] + pub fn data_json(&self) -> Option<&str> { + self.data.as_deref().map(RawValue::get) + } + + /// Reads `data` into a caller type. The text is parsed lazily, here, not on decode. + /// + /// # Errors + /// + /// [`DecodeError::Data`] when `data` is absent or does not fit `T`. + pub fn data(&self) -> Result { + serde_json::from_str(self.data_json().unwrap_or("null")).map_err(DecodeError::Data) + } + + /// The unknown top-level members as `(key, raw JSON text)` pairs, in insertion order. + pub fn extras(&self) -> impl Iterator { + self.extras.iter().map(|(k, v)| (k.as_str(), v.get())) + } + + /// The unknown `meta` members as `(key, raw JSON text)` pairs, in insertion order. + pub fn meta_extras(&self) -> impl Iterator { + self.meta_extras.iter().map(|(k, v)| (k.as_str(), v.get())) + } + + /// Whether a consumer should accept this envelope: a non-blank URN, a supported + /// `meta.schema_version`, a non-blank `trace_id` and a `data` object. It is the consumer-side + /// counterpart of the producer JSON Schema, and it accepts the `urn` alias that the schema does + /// not. + #[must_use] + pub fn accepts(&self) -> bool { + !is_blank_ascii(&self.job) + && self.meta.schema_version == i64::from(SCHEMA_VERSION) + && self.data.is_some() + && !is_blank_ascii(&self.trace_id) + } + + /// Test-only hook for the conformance runner: places raw JSON members directly into the + /// unknown-key containers, standing for extras carried over from an inbound message. Not part + /// of the public API and not covered by semver. + #[doc(hidden)] + pub fn __set_extras_for_conformance( + &mut self, + top: &[(&str, &str)], + meta: &[(&str, &str)], + ) -> Result<(), serde_json::Error> { + for (key, raw) in top { + self.extras + .push(((*key).to_owned(), RawValue::from_string((*raw).to_owned())?)); + } + for (key, raw) in meta { + self.meta_extras + .push(((*key).to_owned(), RawValue::from_string((*raw).to_owned())?)); + } + Ok(()) + } +} + +/// The closed ASCII whitespace set of the conformance suite (ADR-0032 section 5): space, `\t`, +/// `\n`, `\v`, `\f`, `\r`. Unicode spaces (U+00A0, U+2003, U+3000, ...) are part of the value, so +/// this is deliberately not `str::trim`. +fn is_ascii_ws(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r') +} + +/// Trims [`is_ascii_ws`] from both ends. +pub(crate) fn trim_ascii(s: &str) -> &str { + s.trim_matches(is_ascii_ws) +} + +/// Whether `s` is empty or only ASCII whitespace. +pub(crate) fn is_blank_ascii(s: &str) -> bool { + s.chars().all(is_ascii_ws) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ascii_trim_covers_exactly_the_six_characters() { + assert_eq!( + trim_ascii(" \t\n\u{0B}\u{0C}\rurn:a \r\u{0C}\u{0B}\n\t "), + "urn:a" + ); + for unicode_space in ["\u{00A0}", "\u{2003}", "\u{3000}"] { + let s = format!("{unicode_space}urn:a{unicode_space}"); + assert_eq!(trim_ascii(&s), s); + assert!(!is_blank_ascii(unicode_space)); + } + assert!(is_blank_ascii("")); + assert!(is_blank_ascii(" \t\n\u{0B}\u{0C}\r")); + } + + #[test] + fn attempts_saturate_at_i64_max() { + let mut env = Envelope::empty(); + env.set_attempts(u64::MAX); + assert_eq!(env.attempts(), i64::MAX.unsigned_abs()); + env.increment_attempts(); + assert_eq!(env.attempts(), i64::MAX.unsigned_abs()); + } +} diff --git a/crates/babelqueue/src/error.rs b/crates/babelqueue/src/error.rs new file mode 100644 index 0000000..261fd90 --- /dev/null +++ b/crates/babelqueue/src/error.rs @@ -0,0 +1,154 @@ +//! Error types of the codec. Hand-written `Display` + `std::error::Error` (ADR-0041 D2: no +//! `thiserror` in the core). + +use std::error::Error; +use std::fmt; + +use crate::codec::decode::Decoded; + +/// Why a message body could not be decoded, or why its `data` could not be read. +/// +/// On the consume path every variant except [`DecodeError::Data`] means the body is *poison*: it is +/// never handed to a handler (ADR-0035, ADR-0036 decision 4). +#[derive(Debug)] +#[non_exhaustive] +pub enum DecodeError { + /// The body is not valid JSON (empty, truncated, a byte order mark, trailing data, `NaN`, a + /// leading-zero number, invalid UTF-8, ...) or its top-level value is not an object. Line and column + /// count in the body; problems found later inside a member are [`DecodeError::InvalidField`]. + Json(serde_json::Error), + /// A member has the wrong JSON type or an invalid value: a non-object `data`, a `meta` that is + /// not an object, an integer member that is fractional, in exponent form, negative or outside the + /// signed 64-bit range, a `data` holding a number outside the `f64` range or a bad string escape + /// (a lone surrogate), or a string member with a bad escape. + InvalidField { + /// RFC 6901 pointer of the offending member, for example `/meta/created_at`. + pointer: String, + /// What the member must be. + expected: &'static str, + }, + /// Neither a valid string `job` nor a valid string `urn` alias is present (ADR-0032 section 6). + /// The envelope decoded so far, with its warnings, is available through + /// [`DecodeError::partial`]. + NoIdentity(Box), + /// The body decoded, but its `data` does not fit the requested type (or is absent). + Data(serde_json::Error), +} + +impl DecodeError { + /// The envelope decoded so far when the failure is [`DecodeError::NoIdentity`]; `None` for every + /// other failure. A consumer uses it to log the decode warnings and to read `attempts` of a + /// message it is about to dead-letter. + #[must_use] + pub fn partial(&self) -> Option<&Decoded> { + match self { + Self::NoIdentity(decoded) => Some(decoded), + _ => None, + } + } + + /// Whether the failure is a missing identity (as opposed to a malformed body). + #[must_use] + pub fn is_no_identity(&self) -> bool { + matches!(self, Self::NoIdentity(_)) + } +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Json(e) => write!(f, "babelqueue: invalid envelope JSON: {e}"), + Self::InvalidField { pointer, expected } => { + write!( + f, + "babelqueue: envelope member {pointer} must be {expected}" + ) + } + Self::NoIdentity(_) => { + f.write_str("babelqueue: envelope has no valid job or urn identity") + } + Self::Data(e) => write!(f, "babelqueue: envelope data: {e}"), + } + } +} + +impl Error for DecodeError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Json(e) | Self::Data(e) => Some(e), + _ => None, + } + } +} + +/// Why an envelope could not be built or encoded. Nothing is written when encode fails: a forbidden +/// or colliding key is rejected, never silently dropped (message-envelope.md section 10, ADR-0031). +#[derive(Debug)] +#[non_exhaustive] +pub enum EncodeError { + /// The URN is empty after the ASCII trim. + EmptyUrn, + /// A forbidden non-canonical key (message-envelope.md section 10) was supplied. + ForbiddenKey { + /// RFC 6901 pointer of the key, for example `/meta/ts`. + pointer: String, + }, + /// A `meta` entry collides with a core key (`id`, `queue`, `lang`, `schema_version`, + /// `created_at`), or an extra collides with a top-level core key. + ReservedKey { + /// RFC 6901 pointer of the key. + pointer: String, + }, + /// The same `meta` key was supplied more than once. A repeat is rejected, never merged. + DuplicateKey { + /// RFC 6901 pointer of the key. + pointer: String, + }, + /// A `meta` key is the empty string. + EmptyKey, + /// `data` does not serialize to a JSON object (a sequence, `null` or a scalar). + DataNotObject, + /// A `NaN` or infinite float was found; JSON cannot carry it. + NonFiniteFloat, + /// The value's `Serialize` implementation failed. + Serialize(serde_json::Error), + /// The operating system could not provide random bytes for a UUID. + Entropy(String), +} + +impl fmt::Display for EncodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyUrn => f.write_str("babelqueue: URN is empty"), + Self::ForbiddenKey { pointer } => write!( + f, + "babelqueue: forbidden non-canonical envelope key {pointer} (message-envelope.md section 10)" + ), + Self::ReservedKey { pointer } => { + write!( + f, + "babelqueue: key {pointer} collides with a core envelope key" + ) + } + Self::DuplicateKey { pointer } => { + write!(f, "babelqueue: key {pointer} supplied more than once") + } + Self::EmptyKey => f.write_str("babelqueue: meta key must not be empty"), + Self::DataNotObject => f.write_str("babelqueue: data must serialize to a JSON object"), + Self::NonFiniteFloat => { + f.write_str("babelqueue: NaN and infinite floats are not valid JSON") + } + Self::Serialize(e) => write!(f, "babelqueue: cannot serialize value: {e}"), + Self::Entropy(e) => write!(f, "babelqueue: no random bytes for a UUID: {e}"), + } + } +} + +impl Error for EncodeError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Serialize(e) => Some(e), + _ => None, + } + } +} diff --git a/crates/babelqueue/src/lib.rs b/crates/babelqueue/src/lib.rs index 3305f43..7b71475 100644 --- a/crates/babelqueue/src/lib.rs +++ b/crates/babelqueue/src/lib.rs @@ -1,43 +1,38 @@ //! BabelQueue core for Rust: the language-agnostic queue message envelope. //! -//! This crate is a skeleton; the codec and runtime land in later phases of the -//! Rust SDK plan (ADR-0041). The wire envelope stays at `schema_version: 1`. +//! The wire envelope (`{job, trace_id, data, meta, attempts}`) is frozen at `schema_version: 1` +//! (ADR-0041). This crate holds the codec; the runtime lands in a later phase of the Rust SDK plan. +//! +//! * [`make`] builds a new envelope from a URN and any `Serialize` value; [`Envelope::encode`] +//! renders it as compact JSON in the canonical frame. +//! * [`decode`] reads a received body. `data` and every unknown key are kept as raw text, so a +//! re-emit (retry, dead-letter, redrive, relay) writes them back byte for byte and only +//! `attempts` changes. +//! * Failures are values: [`DecodeError`] (a poison body) and [`EncodeError`] (a rejected key or +//! payload). Non-fatal findings of a decode come back as [`Decoded::warnings`]. +//! +//! The codec is synchronous and needs no async runtime. Only `serde`, `serde_json` and `getrandom` +//! are linked (GR-7). +//! +//! # Known encoding difference +//! +//! `serde_json` does not escape U+2028 and U+2029, while the PHP and Go encoders do. Both forms are +//! the same JSON value; the conformance suite compares structure, not bytes. #![forbid(unsafe_code)] -// The three allowed core dependencies (ADR-0041 D3) are declared now so the lockfile, `cargo deny` -// and the MSRV check cover them; the codec phase starts using them for real. -use getrandom as _; -use serde as _; -use serde_json as _; +mod codec; +mod envelope; +mod error; +mod uuid; + +pub use codec::decode::{Decoded, decode}; +pub use codec::encode::{MakeOptions, make}; +pub use envelope::{DeadLetter, Envelope, Meta}; +pub use error::{DecodeError, EncodeError}; /// The wire-envelope `meta.schema_version` this SDK reads and writes. pub const SCHEMA_VERSION: u32 = 1; -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn schema_version_is_frozen_at_one() { - assert_eq!(SCHEMA_VERSION, 1); - } - - // Guards the dependency decisions of ADR-0041 D2/D3 that the codec phase builds on: - // `serde_json` has `raw_value` (verbatim re-emit of numbers), `serde` and `getrandom` link. - #[test] - fn raw_value_keeps_number_text_and_getrandom_links() { - let raw: Box = - serde_json::from_str("1.0e2").expect("valid JSON number"); - assert_eq!(raw.get(), "1.0e2"); - - let mut a = [0u8; 16]; - let mut b = [0u8; 16]; - getrandom::fill(&mut a).expect("getrandom"); - getrandom::fill(&mut b).expect("getrandom"); - assert_ne!(a, b); - - fn is_serialize() {} - is_serialize::(); - } -} +/// The `meta.lang` tag this SDK stamps on the messages it produces. +pub const SOURCE_LANG: &str = "rust"; diff --git a/crates/babelqueue/src/uuid.rs b/crates/babelqueue/src/uuid.rs new file mode 100644 index 0000000..493dbca --- /dev/null +++ b/crates/babelqueue/src/uuid.rs @@ -0,0 +1,60 @@ +//! UUID v4 formatting on top of `getrandom` (ADR-0041 D2). The core does not depend on the `uuid` +//! crate. + +use crate::error::EncodeError; + +const HEX: &[u8; 16] = b"0123456789abcdef"; + +/// A random RFC 4122 version-4 UUID in its lowercase, hyphenated form. +pub(crate) fn uuid_v4() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|e| EncodeError::Entropy(e.to_string()))?; + Ok(format_v4(bytes)) +} + +fn format_v4(mut bytes: [u8; 16]) -> String { + bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10 + let mut out = String::with_capacity(36); + for (i, byte) in bytes.iter().enumerate() { + if matches!(i, 4 | 6 | 8 | 10) { + out.push('-'); + } + out.push(char::from(HEX[usize::from(byte >> 4)])); + out.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_a_fixed_input_as_a_v4_uuid() { + let uuid = format_v4([0xff; 16]); + assert_eq!(uuid, "ffffffff-ffff-4fff-bfff-ffffffffffff"); + let uuid = format_v4([0x00; 16]); + assert_eq!(uuid, "00000000-0000-4000-8000-000000000000"); + } + + #[test] + fn minted_uuids_are_well_formed_and_distinct() { + let a = uuid_v4().expect("entropy"); + let b = uuid_v4().expect("entropy"); + assert_ne!(a, b); + for u in [&a, &b] { + assert_eq!(u.len(), 36); + let bytes = u.as_bytes(); + for (i, c) in bytes.iter().enumerate() { + if matches!(i, 8 | 13 | 18 | 23) { + assert_eq!(*c, b'-'); + } else { + assert!(c.is_ascii_hexdigit() && !c.is_ascii_uppercase()); + } + } + assert_eq!(bytes[14], b'4'); + assert!(matches!(bytes[19], b'8' | b'9' | b'a' | b'b')); + } + } +} diff --git a/crates/babelqueue/tests/conformance.rs b/crates/babelqueue/tests/conformance.rs new file mode 100644 index 0000000..ac87ab3 --- /dev/null +++ b/crates/babelqueue/tests/conformance.rs @@ -0,0 +1,760 @@ +//! The cross-SDK conformance runner (GR-5): the codec sections of the vendored suite under +//! `testdata/conformance/`, run against this core. +//! +//! One test per manifest section, named after it (`cases`, `roundtrip`, `data_shape`, +//! `forbidden_keys`, `extension_write`, `encode_reject`, `trim`, `job_type`, `identity_verdict`). +//! A section missing from the manifest is a hard failure, never a skip, so the suite and the runner +//! move together. `manifest_sections_are_all_classified` fails when the manifest holds a section +//! this runner has not classified, and prints the pass/pending/skip table of every section. +//! +//! Per-message fields (`meta.id`, `trace_id`, `meta.created_at`) are intrinsically unique: they are +//! checked for presence, not for value. Key order and whitespace are not asserted. + +use std::fs; +use std::path::PathBuf; + +use babelqueue::{DecodeError, EncodeError, Envelope, MakeOptions, decode, make}; +use serde_json::{Map, Value, json}; + +// --------------------------------------------------------------------------------------------- +// Suite access +// --------------------------------------------------------------------------------------------- + +fn suite_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../testdata/conformance") +} + +fn manifest() -> Value { + let raw = fs::read(suite_dir().join("manifest.json")).expect("read manifest.json"); + serde_json::from_slice(&raw).expect("parse manifest.json") +} + +/// The `cases` array of one manifest section (the top-level `cases` array for `cases`). +fn section_cases(name: &str) -> Vec { + let manifest = manifest(); + let cases = if name == "cases" { + manifest.get("cases") + } else { + manifest.get(name).and_then(|s| s.get("cases")) + }; + let cases = cases + .unwrap_or_else(|| panic!("manifest has no {name:?} section")) + .as_array() + .unwrap_or_else(|| panic!("{name:?} cases is not an array")) + .clone(); + assert!(!cases.is_empty(), "section {name:?} has no cases"); + cases +} + +fn fixture(file: &str) -> Vec { + fs::read(suite_dir().join(file)).unwrap_or_else(|e| panic!("read fixture {file}: {e}")) +} + +fn text<'a>(case: &'a Value, key: &str) -> &'a str { + case.get(key) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("case lacks string {key:?}: {case}")) +} + +fn name(case: &Value) -> &str { + text(case, "name") +} + +/// Runs `check` on every case of a section and fails with every violation, case by case. +fn run_section(section: &str, check: impl Fn(&Value) -> Vec) { + let cases = section_cases(section); + let mut failures = Vec::new(); + for case in &cases { + for violation in check(case) { + failures.push(format!("[{}] {violation}", name(case))); + } + } + assert!( + failures.is_empty(), + "section {section:?}: {} violations across {} cases:\n{}", + failures.len(), + cases.len(), + failures.join("\n") + ); +} + +// --------------------------------------------------------------------------------------------- +// Assertions shared by the sections +// --------------------------------------------------------------------------------------------- + +fn parse(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|e| format!("emitted bytes are not JSON: {e}")) +} + +/// Evaluates `expect_preserved` (pointer -> value, same JSON type) and +/// `expect_absent_after_reencode` (pointers that must not exist) against one parsed document. +fn check_pointers(doc: &Value, preserved: Option<&Value>, absent: Option<&Value>) -> Vec { + let mut violations = Vec::new(); + if let Some(preserved) = preserved.and_then(Value::as_object) { + for (pointer, want) in preserved { + match doc.pointer(pointer) { + None => violations.push(format!("{pointer} missing after re-encode")), + Some(got) if got != want => { + violations.push(format!("{pointer} = {got}, want {want}")); + } + Some(_) => {} + } + } + } + for pointer in absent + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if doc.pointer(pointer).is_some() { + violations.push(format!("{pointer} present after re-encode, must be absent")); + } + } + violations +} + +/// decode -> attempts + 1 -> encode, the chain every SDK runs on retry, redrive and relay. +fn reemit(body: &[u8]) -> Result<(Envelope, Vec, Value), String> { + let decoded = decode(body).map_err(|e| format!("decode: {e}"))?; + let (mut env, warnings) = decoded.into_parts(); + env.increment_attempts(); + let out = env.encode().map_err(|e| format!("encode: {e}"))?; + let doc = parse(&out)?; + Ok((env, warnings, doc)) +} + +fn json_to_string(v: &Value) -> String { + serde_json::to_string(v).expect("serialize JSON value") +} + +// --------------------------------------------------------------------------------------------- +// Sections +// --------------------------------------------------------------------------------------------- + +/// `cases`: the golden fixtures decode, are accepted (or rejected) and carry the expected values. +#[test] +fn cases() { + run_section("cases", |case| { + let body = fixture(text(case, "file")); + let valid = case.get("valid").and_then(Value::as_bool).expect("valid"); + let decoded = decode(&body); + if !valid { + let accepted = decoded.as_ref().is_ok_and(|d| d.envelope().accepts()); + return if accepted { + vec![format!( + "invalid fixture must be rejected ({})", + text(case, "reason") + )] + } else { + vec![] + }; + } + let decoded = match decoded { + Ok(d) => d, + Err(e) => return vec![format!("valid fixture failed to decode: {e}")], + }; + let env = decoded.envelope(); + let expect = &case["expect"]; + let mut v = Vec::new(); + if !env.accepts() { + v.push("valid fixture must be accepted".to_owned()); + } + if env.job() != text(expect, "urn") { + v.push(format!("urn = {:?}, want {:?}", env.job(), expect["urn"])); + } + if json!(env.attempts()) != expect["attempts"] { + v.push(format!( + "attempts = {}, want {}", + env.attempts(), + expect["attempts"] + )); + } + if env.meta().lang() != text(expect, "lang") { + v.push(format!( + "lang = {:?}, want {}", + env.meta().lang(), + expect["lang"] + )); + } + if json!(env.meta().schema_version()) != expect["schema_version"] { + v.push(format!( + "schema_version = {}, want {}", + env.meta().schema_version(), + expect["schema_version"] + )); + } + if let Some(want) = expect.get("data") { + match env.data::() { + Ok(got) if &got == want => {} + Ok(got) => v.push(format!("data = {got}, want {want}")), + Err(e) => v.push(format!("data: {e}")), + } + } + if env.trace_id().is_empty() || env.meta().id().is_empty() || env.meta().created_at() == 0 { + v.push( + "per-message fields (trace_id, meta.id, meta.created_at) must be present" + .to_owned(), + ); + } + if let Some(want) = expect.get("dead_letter") { + match env.dead_letter() { + None => v.push("expected a dead_letter block".to_owned()), + Some(dl) => { + if let Some(reason) = want.get("reason").and_then(Value::as_str) { + if dl.reason != reason { + v.push(format!( + "dead_letter.reason = {:?}, want {reason:?}", + dl.reason + )); + } + } + if let Some(queue) = want.get("original_queue").and_then(Value::as_str) { + if dl.original_queue != queue { + v.push(format!( + "dead_letter.original_queue = {:?}, want {queue:?}", + dl.original_queue + )); + } + } + } + } + } + v + }); +} + +/// The DLQ helper (`apply_dead_letter`) is part of the runtime phase. Until it lands the runner +/// takes the fallback the manifest allows: a runner that does not know the field runs the case as a +/// plain decode -> attempts + 1 -> encode chain. +fn apply_dead_letter(_env: &mut Envelope, _reason: &str, _original_queue: &str) -> bool { + false +} + +/// `roundtrip`: unknown keys survive decode -> attempts + 1 -> encode with the same value and type. +#[test] +fn roundtrip() { + run_section("roundtrip", |case| { + let body = fixture(text(case, "file")); + let decoded = match decode(&body) { + Ok(d) => d, + Err(e) => return vec![format!("decode: {e}")], + }; + let mut v = Vec::new(); + if !decoded.envelope().accepts() { + v.push("roundtrip fixture must be accepted".to_owned()); + } + if !decoded.warnings().is_empty() { + v.push(format!( + "decode must emit no warning, got {:?}", + decoded.warnings() + )); + } + let (mut env, _) = decoded.into_parts(); + env.increment_attempts(); + let mut dead_lettered = false; + if let Some(apply) = case.get("apply_dead_letter") { + dead_lettered = apply_dead_letter( + &mut env, + text(apply, "reason"), + text(apply, "original_queue"), + ); + } + let doc = match env + .encode() + .map_err(|e| e.to_string()) + .and_then(|b| parse(&b)) + { + Ok(doc) => doc, + Err(e) => return [v, vec![e]].concat(), + }; + if doc.pointer("/attempts") != Some(&case["expect_attempts"]) { + v.push(format!( + "attempts = {:?}, want {}", + doc.pointer("/attempts"), + case["expect_attempts"] + )); + } + v.extend(check_pointers( + &doc, + case.get("expect_preserved"), + case.get("expect_absent_after_reencode"), + )); + if dead_lettered { + if let Some(want) = case.get("expect_dead_letter").and_then(Value::as_object) { + for (key, want) in want { + if doc.pointer(&format!("/dead_letter/{key}")) != Some(want) { + v.push(format!( + "dead_letter.{key} = {:?}, want {want}", + doc.pointer(&format!("/dead_letter/{key}")) + )); + } + } + } + } + v + }); +} + +/// `data_shape`: `data` is always a JSON object; an empty map encodes as `{}` and an array is +/// rejected on decode. +#[test] +fn data_shape() { + run_section("data_shape", |case| match text(case, "mode") { + "encode" => { + let opts = MakeOptions::new().queue(text(case, "queue")); + let env = match make(text(case, "urn"), &case["data"], opts) { + Ok(env) => env, + Err(e) => return vec![format!("make: {e}")], + }; + let out = match env.encode() { + Ok(out) => out, + Err(e) => return vec![format!("encode: {e}")], + }; + let top: Map = match parse(&out) { + Ok(Value::Object(top)) => top, + Ok(other) => return vec![format!("emitted bytes are not a JSON object: {other}")], + Err(e) => return vec![e], + }; + // Compare the raw text of `data` (insignificant whitespace removed), not a parsed value: + // an empty map must be `{}`, never `[]`. + let raw: std::collections::BTreeMap> = + serde_json::from_slice(&out).expect("object of raw values"); + let got: String = raw["data"] + .get() + .chars() + .filter(|c| !c.is_whitespace()) + .collect(); + let mut v = Vec::new(); + if got != text(case, "expect_encoded_data_json") { + v.push(format!( + "data encoded as {got}, want {}", + case["expect_encoded_data_json"] + )); + } + if !top.contains_key("data") { + v.push("emitted envelope has no data".to_owned()); + } + v + } + "decode" => { + let accepted = + decode(&fixture(text(case, "file"))).is_ok_and(|d| d.envelope().accepts()); + let want = case["valid"].as_bool().expect("valid"); + if accepted == want { + vec![] + } else { + vec![format!( + "accepted = {accepted}, want {want} ({})", + case["reason"] + )] + } + } + other => vec![format!("unknown data_shape mode {other:?}")], + }); +} + +/// `forbidden_keys` (K-15): decode succeeds with a warning naming the key, and a re-encode never +/// emits it. +#[test] +fn forbidden_keys() { + run_section("forbidden_keys", |case| { + if text(case, "expect") != "warn" { + return vec![format!("unsupported expect {}", case["expect"])]; + } + let decoded = match decode(&fixture(text(case, "file"))) { + Ok(d) => d, + Err(e) => return vec![format!("decode must succeed (warn, not reject): {e}")], + }; + let mut v = Vec::new(); + let key = text(case, "forbidden_key"); + if !decoded.warnings().iter().any(|w| w.contains(key)) { + v.push(format!( + "no warning names {key}; warnings = {:?}", + decoded.warnings() + )); + } + let out = match decoded.envelope().encode() { + Ok(out) => out, + Err(e) => return [v, vec![format!("encode: {e}")]].concat(), + }; + match parse(&out) { + Ok(doc) => v.extend(check_pointers( + &doc, + case.get("expect_preserved"), + case.get("expect_absent_after_reencode"), + )), + Err(e) => v.push(e), + } + v + }); +} + +/// `extension_write`: the producer `meta` write API lands each entry in `meta`, and the entries +/// survive a decode -> attempts + 1 -> encode retry hop. +#[test] +fn extension_write() { + run_section("extension_write", |case| { + let mut opts = MakeOptions::new().queue(text(case, "queue")); + for (key, value) in case["meta"].as_object().expect("meta object") { + opts = opts.meta(key, value); + } + let env = match make(text(case, "urn"), &case["data"], opts) { + Ok(env) => env, + Err(e) => return vec![format!("make: {e}")], + }; + let out = match env.encode() { + Ok(out) => out, + Err(e) => return vec![format!("encode: {e}")], + }; + let mut v = Vec::new(); + match parse(&out) { + Ok(doc) => v.extend( + check_pointers(&doc, case.get("expect_envelope"), None) + .into_iter() + .map(|m| format!("first emit: {m}")), + ), + Err(e) => return vec![e], + } + match reemit(&out) { + Ok((_, _, doc)) => { + v.extend( + check_pointers(&doc, case.get("expect_envelope"), None) + .into_iter() + .map(|m| format!("after retry hop: {m}")), + ); + if doc.pointer("/attempts") != Some(&json!(1)) { + v.push(format!("attempts = {:?}, want 1", doc.pointer("/attempts"))); + } + } + Err(e) => v.push(e), + } + v + }); +} + +/// `encode_reject`: a forbidden or core-colliding key fails the producer/encode path with an error +/// and no envelope JSON is produced. +#[test] +fn encode_reject() { + run_section("encode_reject", |case| { + if text(case, "expect") != "reject" { + return vec![format!("unsupported expect {}", case["expect"])]; + } + let offending = text(case, "offending_key"); + let mut opts = MakeOptions::new().queue(text(case, "queue")); + if let Some(meta) = case.get("meta").and_then(Value::as_object) { + for (key, value) in meta { + opts = opts.meta(key, value); + } + } + // `meta_entries` is the ordered form that can express a repeated key; the write API takes + // one entry per call, so this runner can run it. + for pair in case + .get("meta_entries") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + opts = opts.meta(pair[0].as_str().expect("meta_entries key"), &pair[1]); + } + let rejected: Result, EncodeError> = make(text(case, "urn"), &case["data"], opts) + .and_then(|mut env| { + let extras = |key: &str| -> Vec<(String, String)> { + case.get(key) + .and_then(Value::as_object) + .map(|m| { + m.iter() + .map(|(k, v)| (k.clone(), json_to_string(v))) + .collect() + }) + .unwrap_or_default() + }; + let (top, meta) = (extras("extras_top"), extras("extras_meta")); + let top: Vec<(&str, &str)> = + top.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + let meta: Vec<(&str, &str)> = + meta.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + env.__set_extras_for_conformance(&top, &meta) + .map_err(EncodeError::Serialize)?; + env.encode() + }); + match rejected { + Ok(out) => vec![format!( + "must be rejected, but produced {}", + String::from_utf8_lossy(&out) + )], + Err(e) if e.to_string().contains(offending) => vec![], + Err(e) => vec![format!( + "rejected, but the error does not name {offending}: {e}" + )], + } + }); +} + +/// `trim` (ADR-0032 section 5): the closed ASCII whitespace set trims on `make` and decides blank on +/// decode/accepts; re-emit never trims. +#[test] +fn trim() { + run_section("trim", |case| match text(case, "mode") { + "make" => { + let mut opts = MakeOptions::new(); + if let Some(trace_id) = case.get("trace_id").and_then(Value::as_str) { + opts = opts.trace_id(trace_id); + } + let made = make(text(case, "urn"), &json!({}), opts); + match (&case["expect"], made) { + (Value::String(s), Err(_)) if s == "reject" => vec![], + (Value::String(s), Ok(env)) if s == "reject" => { + vec![format!("must reject, got job {:?}", env.job())] + } + (Value::Object(want), Ok(env)) => { + let mut v = Vec::new(); + if want.get("job").and_then(Value::as_str) != Some(env.job()) { + v.push(format!( + "job = {:?}, want {}", + env.job(), + case["expect"]["job"] + )); + } + if let Some(trace_id) = want.get("trace_id").and_then(Value::as_str) { + if env.trace_id() != trace_id { + v.push(format!( + "trace_id = {:?}, want {trace_id:?}", + env.trace_id() + )); + } + } + v + } + (_, Err(e)) => vec![format!("make: {e}")], + (other, _) => vec![format!("unsupported expect {other}")], + } + } + "decode" => { + let valid = case["valid"].as_bool().expect("valid"); + match (decode(&fixture(text(case, "file"))), valid) { + (Ok(d), true) => { + let mut v = Vec::new(); + if d.envelope().job() != text(&case["expect"], "urn") { + v.push(format!( + "urn = {:?}, want {}", + d.envelope().job(), + case["expect"]["urn"] + )); + } + let warned = !d.warnings().is_empty(); + if Some(warned) != case["expect_warning"].as_bool() { + v.push(format!( + "warned = {warned}, want {}", + case["expect_warning"] + )); + } + v + } + (Err(_), false) => vec![], + (Ok(d), false) => vec![format!( + "must fail to decode, got job {:?}", + d.envelope().job() + )], + (Err(e), true) => vec![format!("decode: {e}")], + } + } + "accepts" => { + let decoded = decode(&fixture(text(case, "file"))); + let decode_ok = case["expect_decode_ok"] + .as_bool() + .expect("expect_decode_ok"); + let want = case["expect_accepts"].as_bool().expect("expect_accepts"); + match decoded { + Ok(d) if decode_ok => { + if d.envelope().accepts() == want { + vec![] + } else { + vec![format!("accepts = {}, want {want}", d.envelope().accepts())] + } + } + Ok(_) => vec!["decode must fail".to_owned()], + Err(e) => vec![format!("decode must succeed: {e}")], + } + } + "reemit" => match reemit(&fixture(text(case, "file"))) { + Ok((_, _, doc)) => { + let mut v = check_pointers(&doc, case.get("expect_preserved"), None); + if doc.pointer("/attempts") != Some(&case["expect_attempts"]) { + v.push(format!( + "attempts = {:?}, want {}", + doc.pointer("/attempts"), + case["expect_attempts"] + )); + } + v + } + Err(e) => vec![e], + }, + other => vec![format!("unknown trim mode {other:?}")], + }); +} + +/// `job_type` (ADR-0032 section 6): a `job` that is not a string is ignored with a warning and the +/// identity falls back to a string `urn`; without a valid identity decode fails. +#[test] +fn job_type() { + run_section("job_type", |case| { + let valid = case["valid"].as_bool().expect("valid"); + match (decode(&fixture(text(case, "file"))), valid) { + (Ok(d), true) => { + let mut v = Vec::new(); + if d.envelope().job() != text(&case["expect"], "urn") { + v.push(format!( + "urn = {:?}, want {}", + d.envelope().job(), + case["expect"]["urn"] + )); + } + let warned = !d.warnings().is_empty(); + if Some(warned) != case["expect_warning"].as_bool() { + v.push(format!( + "warned = {warned} ({:?}), want {}", + d.warnings(), + case["expect_warning"] + )); + } + v + } + (Err(DecodeError::NoIdentity(_)), false) => vec![], + (Err(e), false) => vec![format!("must fail with no identity, failed with: {e}")], + (Ok(d), false) => vec![format!( + "must fail to decode, got job {:?}", + d.envelope().job() + )], + (Err(e), true) => vec![format!("decode: {e}")], + } + }); +} + +/// `identity_verdict` (ADR-0036 decision 4): the verdict of the core decoder on a raw body. `ok` +/// decodes into an envelope with a valid identity; `poison` does not. +#[test] +fn identity_verdict() { + run_section("identity_verdict", |case| { + let decoded = decode(text(case, "body").as_bytes()); + match (text(case, "expect"), decoded) { + ("ok", Ok(d)) if !d.envelope().job().is_empty() => vec![], + ("ok", Ok(_)) => vec!["decoded without a valid identity".to_owned()], + ("ok", Err(e)) => vec![format!("decode error {e}, expect ok")], + ("poison", Err(_)) => vec![], + ("poison", Ok(d)) => vec![format!( + "body decoded (job {:?}), expect poison", + d.envelope().job() + )], + (other, _) => vec![format!("unknown expect {other:?}")], + } + }); +} + +// --------------------------------------------------------------------------------------------- +// Section bookkeeping +// --------------------------------------------------------------------------------------------- + +enum Status { + /// Run by a test in this file. + Pass, + /// Core scope, but part of a later phase of the plan (the runtime). + Pending(&'static str), + /// Out of this SDK's scope, with the reason. + Skip(&'static str), +} + +fn classify(section: &str) -> Option { + use Status::{Pass, Pending, Skip}; + const BROKER: &str = "broker binding outside the Rust MVP (Redis only)"; + Some(match section { + "cases" | "roundtrip" | "data_shape" | "forbidden_keys" | "extension_write" + | "encode_reject" | "trim" | "job_type" | "identity_verdict" => Pass, + "idempotency" => Pending("idempotency helper, Phase 03 (ADR-0022)"), + "payload_schema" | "payload_schema_unicode" | "payload_schema_keywords" => { + Pending("payload-schema subset, Phase 03 (ADR-0024)") + } + "retry_backoff" => Pending("retry backoff, Phase 03 (ADR-0034 section 9)"), + "poison_dlq" => Pending("poison routing and DLQ block, Phase 03 (ADR-0035/0036/0037)"), + "redis" | "redis_layout" | "redis_delay" => Pending("babelqueue-redis, Phase 04"), + "sqs" | "delay" | "version_gate_sqs" => { + Skip("Amazon SQS binding: no Rust transport in 0.1") + } + "asb" | "version_gate_asb" => Skip("Azure Service Bus binding: no Rust transport in 0.1"), + "pulsar" | "pulsar_exhaustion" | "version_gate_pulsar" => { + Skip("Pulsar binding: no Rust transport in 0.1") + } + "kafka" | "backoff" | "kafka_poison" => { + Skip("Kafka binding: no Rust transport in 0.1 (ADR-0041 decision 5)") + } + "artemis" | "version_gate_artemis" => Skip("Artemis binding: no Rust transport in 0.1"), + "rabbitmq" => Skip(BROKER), + "traceparent" | "span-shape" | "trace-id" | "metrics" => { + Skip("OpenTelemetry (babelqueue-otel, first MINOR; ADR-0041 decision 6)") + } + _ => return None, + }) +} + +#[test] +fn manifest_sections_are_all_classified() { + let manifest = manifest(); + let sections = manifest["sections"].as_object().expect("manifest.sections"); + let mut unclassified = Vec::new(); + println!( + "conformance {} (schema_version {})", + manifest["conformance_version"], manifest["schema_version"] + ); + for (section, info) in sections { + match classify(section) { + Some(Status::Pass) => println!(" pass {section} (scope {})", info["scope"]), + Some(Status::Pending(why)) => { + println!(" pending {section} (scope {}): {why}", info["scope"]) + } + Some(Status::Skip(why)) => { + println!(" skip {section} (scope {}): {why}", info["scope"]) + } + None => unclassified.push(section.clone()), + } + } + assert!( + unclassified.is_empty(), + "the manifest has sections this runner has not classified: {unclassified:?}" + ); + // The sections run here must exist in the manifest, in the shape the runner reads. + for section in sections + .keys() + .filter(|s| matches!(classify(s), Some(Status::Pass))) + { + assert!(!section_cases(section).is_empty()); + } +} + +/// The runner must report a violation when an expectation is broken: a runner that ignored +/// `expect_preserved` or `expect_absent_after_reencode` would stay green on the same input. +#[test] +fn runner_reports_violations() { + let body = br#"{"job":"urn:acme:a","trace_id":"t","data":{"order_id":1},"meta":{"id":"i","queue":"orders","lang":"php","schema_version":1,"created_at":1749132727000},"attempts":0,"extra_top":1}"#; + let (_, _, doc) = reemit(body).expect("reemit"); + assert!(check_pointers(&doc, Some(&json!({"/extra_top": 1})), None).is_empty()); + assert_eq!( + check_pointers(&doc, Some(&json!({"/extra_top": 2})), None).len(), + 1 + ); + assert_eq!( + check_pointers(&doc, Some(&json!({"/missing": 1})), None).len(), + 1 + ); + assert_eq!( + check_pointers(&doc, None, Some(&json!(["/extra_top"]))).len(), + 1 + ); + assert!(check_pointers(&doc, None, Some(&json!(["/absent"]))).is_empty()); + // {} and [] are different JSON types. + assert_eq!( + check_pointers(&json!({"d": {}}), Some(&json!({"/d": []})), None).len(), + 1 + ); +} From b2bc033c7cafed505fb3fb744f7efc446a222449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Fri, 4 Dec 2026 16:36:18 +0300 Subject: [PATCH 2/4] feat(core): runtime with App, Transport trait, in-memory transport, DLQ, poison, backoff, idempotency and schema checks Adds the dispatch runtime on top of the codec: URN routing with unknown-URN strategies, version gate, poison routing, retry with backoff and jitter, dead-letter annotation matching the Go and Python SDKs, handler panic containment via catch_unwind, and a conformance runner that covers every core section and writes results.json. --- crates/babelqueue/src/app.rs | 1113 ++++++++++++++++++++++++ crates/babelqueue/src/backoff.rs | 173 ++++ crates/babelqueue/src/codec/encode.rs | 2 +- crates/babelqueue/src/dlq.rs | 216 +++++ crates/babelqueue/src/idempotency.rs | 134 +++ crates/babelqueue/src/lib.rs | 36 +- crates/babelqueue/src/memory.rs | 126 +++ crates/babelqueue/src/poison.rs | 470 ++++++++++ crates/babelqueue/src/results.rs | 517 +++++++++++ crates/babelqueue/src/schema.rs | 551 ++++++++++++ crates/babelqueue/src/transport.rs | 253 ++++++ crates/babelqueue/tests/app.rs | 1096 +++++++++++++++++++++++ crates/babelqueue/tests/conformance.rs | 790 +++++++++++++++-- 13 files changed, 5407 insertions(+), 70 deletions(-) create mode 100644 crates/babelqueue/src/app.rs create mode 100644 crates/babelqueue/src/backoff.rs create mode 100644 crates/babelqueue/src/dlq.rs create mode 100644 crates/babelqueue/src/idempotency.rs create mode 100644 crates/babelqueue/src/memory.rs create mode 100644 crates/babelqueue/src/poison.rs create mode 100644 crates/babelqueue/src/results.rs create mode 100644 crates/babelqueue/src/schema.rs create mode 100644 crates/babelqueue/src/transport.rs create mode 100644 crates/babelqueue/tests/app.rs diff --git a/crates/babelqueue/src/app.rs b/crates/babelqueue/src/app.rs new file mode 100644 index 0000000..a39d3b1 --- /dev/null +++ b/crates/babelqueue/src/app.rs @@ -0,0 +1,1113 @@ +//! The optional BabelQueue runtime: produce and consume polyglot messages over a +//! [`Transport`]. +//! +//! Routing is by URN; the wire format is the canonical envelope (the same codec the other SDKs +//! use). Retry uses the top-level `attempts` counter; failures past +//! [`App::max_attempts`] go to a dead-letter queue when [`App::dead_letter`] is on. +//! +//! The runtime is not tied to an executor. It never sleeps: waiting is the transport's job +//! ([`Transport::pop`]'s timeout, the delay of [`Releaser::release`]), and shutdown is a future the +//! caller supplies. A handler that panics is caught and counted as a failure, so one bad message +//! cannot take the worker down. + +use std::any::Any; +use std::collections::HashMap; +use std::error::Error; +use std::fmt; +use std::future::Future; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::pin::{Pin, pin}; +use std::str::FromStr; +use std::sync::Arc; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use serde::Serialize; + +use crate::backoff::Backoff; +use crate::codec::decode::decode; +use crate::codec::encode::{MakeOptions, make}; +use crate::dlq::{FailureCause, annotate}; +use crate::envelope::{Envelope, is_blank_ascii}; +use crate::error::{DecodeError, EncodeError}; +use crate::poison::poison_dead_letter_body; +use crate::transport::{ + DeadLetterSettler, Delivery, HeaderPublisher, ReleaseError, Releaser, Transport, TransportError, +}; + +type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// The future a handler returns. +pub type HandlerFuture = BoxFuture<'static, Result<(), HandlerError>>; + +type Handler = Arc, Arc) -> HandlerFuture + Send + Sync>; + +/// The reserved [`Delivery::route_urn`] prefix a transport uses to hand over a delivery it +/// version-gated (broker-bindings section 5.7 step 3). It is not a `urn:babel:` URN, so no handler +/// owns it. The runtime dead-letters such a delivery directly, with no retry and without decoding it. +pub const UNSUPPORTED_SCHEMA_ROUTE_PREFIX: &str = "babelqueue:unsupported-schema-version:"; + +const DECLARED_VERSION_MAX_CHARS: usize = 64; + +/// Caps a rejected `bq-schema-version` value at 64 characters followed by `...`, so a huge header +/// cannot inflate a log line, a route or a dead-letter record. A value of at most 64 characters is +/// returned unchanged. Transports apply it to the rejected value before reporting it or building +/// the reserved route; the gate comparison itself uses the full value. +#[must_use] +pub fn truncate_declared_version(value: &str) -> String { + match value.char_indices().nth(DECLARED_VERSION_MAX_CHARS) { + Some((at, _)) => format!("{}...", &value[..at]), + None => value.to_owned(), + } +} + +// --------------------------------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------------------------------- + +/// What a handler returns on failure. It triggers the retry and dead-letter path; its message and +/// type name are recorded in `dead_letter.error` and `dead_letter.exception`. +/// +/// Any `std::error::Error` converts into it with `?`; [`HandlerError::msg`] builds one from text. +#[derive(Debug, Clone)] +pub struct HandlerError { + message: String, + exception: String, +} + +impl HandlerError { + /// A failure with a plain message. + pub fn msg(message: impl Into) -> Self { + Self { + message: message.into(), + exception: "babelqueue::HandlerError".to_owned(), + } + } + + /// The failure message. + #[must_use] + pub fn message(&self) -> &str { + &self.message + } + + /// The failure type name. + #[must_use] + pub fn exception(&self) -> &str { + &self.exception + } + + fn cause(&self) -> FailureCause { + FailureCause::new(self.message.clone(), self.exception.clone()) + } +} + +impl fmt::Display for HandlerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl From for HandlerError { + fn from(error: E) -> Self { + Self { + message: error.to_string(), + exception: crate::dlq::public_type_name::(), + } + } +} + +/// Why a publish failed. +#[derive(Debug)] +#[non_exhaustive] +pub enum PublishError { + /// The envelope could not be built or encoded; nothing reached the transport. + Encode(EncodeError), + /// The transport rejected the publish. + Transport(TransportError), +} + +impl fmt::Display for PublishError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Encode(e) => write!(f, "babelqueue: publish: {e}"), + Self::Transport(e) => write!(f, "babelqueue: publish: {e}"), + } + } +} + +impl Error for PublishError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Encode(e) => Some(e), + Self::Transport(e) => Some(e), + } + } +} + +impl From for PublishError { + fn from(e: EncodeError) -> Self { + Self::Encode(e) + } +} + +impl From for PublishError { + fn from(e: TransportError) -> Self { + Self::Transport(e) + } +} + +// --------------------------------------------------------------------------------------------- +// Options and hooks +// --------------------------------------------------------------------------------------------- + +/// What happens to a message whose URN has no handler. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum UnknownUrnStrategy { + /// Treat it as a failure: retry up to [`App::max_attempts`], then dead-letter or drop (the + /// default). + #[default] + Fail, + /// Acknowledge and drop it. + Delete, + /// Return it to the queue (after [`App::unknown_urn_release_delay`] on a [`Releaser`]) so a + /// worker that has a handler can take it. + Release, + /// Write it to the dead-letter queue at once, with reason `unknown_urn`. + DeadLetter, +} + +impl UnknownUrnStrategy { + /// The configuration name: `fail`, `delete`, `release` or `dead_letter`. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Fail => "fail", + Self::Delete => "delete", + Self::Release => "release", + Self::DeadLetter => "dead_letter", + } + } +} + +impl FromStr for UnknownUrnStrategy { + type Err = String; + + fn from_str(s: &str) -> Result { + match s { + "fail" => Ok(Self::Fail), + "delete" => Ok(Self::Delete), + "release" => Ok(Self::Release), + "dead_letter" => Ok(Self::DeadLetter), + other => Err(format!( + "unknown strategy {other:?}: expected fail, delete, release or dead_letter" + )), + } + } +} + +/// One dead-letter the runtime itself carried out and confirmed, as reported to the +/// [`App::on_dead_letter`] hook (ADR-0039 section 5.1). +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct DeadLetterEvent { + /// The source queue: `meta.queue` of the message when it has one, else the delivery's queue. + pub queue: String, + /// The dead-letter queue the record was written to. + pub dead_letter_queue: String, + /// The `dead_letter.reason` written into the record (`failed`, `unknown_urn`, `poison`), or + /// `None` for a raw version-gated body, which carries no block. + pub reason: Option, +} + +type ErrorHook = Arc; +type WarningHook = Arc; +type DeadLetterHook = Arc; + +#[derive(Default)] +struct Hooks { + ack_error: Option, + release_error: Option, + dead_letter_error: Option, + warning: Option, + dead_letter: Option, +} + +/// Runs a user hook, discarding a panic so a misbehaving hook never changes how the message is +/// settled or stops the consume loop. +fn guarded(f: impl FnOnce()) { + let _ = catch_unwind(AssertUnwindSafe(f)); +} + +// --------------------------------------------------------------------------------------------- +// Optional transport capabilities +// --------------------------------------------------------------------------------------------- + +type PublishHeadersFn = for<'a> fn( + &'a T, + &'a str, + &'a [u8], + &'a HashMap, +) -> BoxFuture<'a, Result<(), TransportError>>; +type ReleaseFn = + for<'a> fn(&'a T, &'a Delivery, Duration) -> BoxFuture<'a, Result<(), ReleaseError>>; +type DeadLetterFn = + for<'a> fn(&'a T, &'a Delivery, &'a str, &'a [u8]) -> BoxFuture<'a, Result<(), TransportError>>; + +struct Capabilities { + publish_with_headers: Option>, + release: Option>, + dead_letter: Option>, +} + +impl Default for Capabilities { + fn default() -> Self { + Self { + publish_with_headers: None, + release: None, + dead_letter: None, + } + } +} + +fn publish_with_headers_via<'a, T: HeaderPublisher>( + transport: &'a T, + queue: &'a str, + body: &'a [u8], + headers: &'a HashMap, +) -> BoxFuture<'a, Result<(), TransportError>> { + Box::pin(transport.publish_with_headers(queue, body, headers)) +} + +fn release_via<'a, T: Releaser>( + transport: &'a T, + delivery: &'a Delivery, + delay: Duration, +) -> BoxFuture<'a, Result<(), ReleaseError>> { + Box::pin(transport.release(delivery, delay)) +} + +fn dead_letter_via<'a, T: DeadLetterSettler>( + transport: &'a T, + delivery: &'a Delivery, + dlq_queue: &'a str, + body: &'a [u8], +) -> BoxFuture<'a, Result<(), TransportError>> { + Box::pin(transport.dead_letter(delivery, dlq_queue, body)) +} + +// --------------------------------------------------------------------------------------------- +// App +// --------------------------------------------------------------------------------------------- + +/// The runtime: publishes messages and consumes them by URN over a [`Transport`]. +/// +/// ``` +/// use std::sync::Arc; +/// use babelqueue::{App, Envelope, Delivery, HandlerError, InMemoryTransport}; +/// +/// # fn main() { futures_lite_block_on(async { +/// let mut app = App::new(InMemoryTransport::new()).queue("orders"); +/// app.handle("urn:babel:orders:created", |env: Arc, _: Arc| async move { +/// let order: serde_json::Value = env.data()?; +/// assert_eq!(order["order_id"], 1042); +/// Ok::<(), HandlerError>(()) +/// }); +/// app.publish("urn:babel:orders:created", &serde_json::json!({"order_id": 1042})).await.unwrap(); +/// assert_eq!(app.drain("orders", 0).await.unwrap(), 1); +/// # }); } +/// # fn futures_lite_block_on(f: F) -> F::Output { +/// # let mut f = std::pin::pin!(f); +/// # let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); +/// # loop { if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) { return v; } } +/// # } +/// ``` +pub struct App { + transport: T, + queue: String, + unknown_urn: UnknownUrnStrategy, + max_attempts: u64, + dead_letter: bool, + dead_letter_queue: Option, + dead_letter_suffix: String, + poll_timeout: Duration, + backoff: Backoff, + unknown_urn_delay: Duration, + hooks: Hooks, + handlers: HashMap, + capabilities: Capabilities, +} + +impl App { + /// A runtime over `transport`: default queue `default`, [`UnknownUrnStrategy::Fail`], 3 + /// attempts, no dead-lettering, DLQ suffix `.dlq`, a 1 s poll timeout and no backoff. + #[must_use] + pub fn new(transport: T) -> Self { + Self { + transport, + queue: "default".to_owned(), + unknown_urn: UnknownUrnStrategy::Fail, + max_attempts: 3, + dead_letter: false, + dead_letter_queue: None, + dead_letter_suffix: ".dlq".to_owned(), + poll_timeout: Duration::from_secs(1), + backoff: Backoff::default(), + unknown_urn_delay: Duration::ZERO, + hooks: Hooks::default(), + handlers: HashMap::new(), + capabilities: Capabilities::default(), + } + } + + /// Sets the queue `publish`, `run` use when none is given (default `default`). + #[must_use] + pub fn queue(mut self, queue: impl Into) -> Self { + self.queue = queue.into(); + self + } + + /// Sets how many delivery attempts a message gets before it is dead-lettered or dropped + /// (default 3). + #[must_use] + pub fn max_attempts(mut self, attempts: u64) -> Self { + self.max_attempts = attempts; + self + } + + /// Sets what happens to a message whose URN has no handler. + #[must_use] + pub fn unknown_urn_strategy(mut self, strategy: UnknownUrnStrategy) -> Self { + self.unknown_urn = strategy; + self + } + + /// Turns on routing of exhausted and failed messages to a dead-letter queue. + #[must_use] + pub fn dead_letter(mut self, enabled: bool) -> Self { + self.dead_letter = enabled; + self + } + + /// Overrides the dead-letter queue name (default: the source queue plus the suffix). + #[must_use] + pub fn dead_letter_queue(mut self, queue: impl Into) -> Self { + self.dead_letter_queue = Some(queue.into()); + self + } + + /// Sets the suffix appended to the source queue to name its dead-letter queue (default `.dlq`). + #[must_use] + pub fn dead_letter_suffix(mut self, suffix: impl Into) -> Self { + self.dead_letter_suffix = suffix.into(); + self + } + + /// Sets how long [`Transport::pop`] may wait each iteration (default 1 s). A shutdown is + /// noticed between polls, so this bounds the shutdown latency of a blocking transport. + #[must_use] + pub fn poll_timeout(mut self, timeout: Duration) -> Self { + self.poll_timeout = timeout; + self + } + + /// Sets the retry backoff (default none). It takes effect on a transport registered with + /// [`App::with_releaser`]; any other transport re-publishes the retry at once. + #[must_use] + pub fn backoff(mut self, backoff: Backoff) -> Self { + self.backoff = backoff; + self + } + + /// Sets the redelivery delay of [`UnknownUrnStrategy::Release`] (default 0). Like + /// [`App::backoff`], it takes effect on a [`Releaser`]. + #[must_use] + pub fn unknown_urn_release_delay(mut self, delay: Duration) -> Self { + self.unknown_urn_delay = delay; + self + } + + /// Observes a failed acknowledgement. An ack failure is never treated as a handler failure: a + /// message whose handler succeeded is not retried because its ack failed (the broker redelivers + /// it when the reservation lapses, which consumer-side idempotency absorbs). + #[must_use] + pub fn on_ack_error( + mut self, + hook: impl Fn(&Delivery, &(dyn Error + 'static)) + Send + Sync + 'static, + ) -> Self { + self.hooks.ack_error = Some(Arc::new(hook)); + self + } + + /// Observes a failed in-place release or a failed retry re-publish. A failed release still + /// counts as handled: the message is neither re-published nor acked, and the broker redelivers + /// it when its reservation lapses. A failed re-publish leaves the message unacknowledged. + #[must_use] + pub fn on_release_error( + mut self, + hook: impl Fn(&Delivery, &(dyn Error + 'static)) + Send + Sync + 'static, + ) -> Self { + self.hooks.release_error = Some(Arc::new(hook)); + self + } + + /// Observes a failed dead-letter write (the publish to the DLQ, or the record's encoding). The + /// message is never acknowledged: it stays with the broker, which redelivers it when its + /// reservation lapses. + #[must_use] + pub fn on_dead_letter_error( + mut self, + hook: impl Fn(&Delivery, &(dyn Error + 'static)) + Send + Sync + 'static, + ) -> Self { + self.hooks.dead_letter_error = Some(Arc::new(hook)); + self + } + + /// Observes each dead-letter the runtime carried out and confirmed (ADR-0039 section 5.1). It is + /// not called when the write fails, when the broker dead-letters on its own, or when + /// dead-lettering is off and the message is dropped. + #[must_use] + pub fn on_dead_letter( + mut self, + hook: impl Fn(&DeadLetterEvent) + Send + Sync + 'static, + ) -> Self { + self.hooks.dead_letter = Some(Arc::new(hook)); + self + } + + /// Observes the non-fatal findings of a decode (a dropped forbidden key, ADR-0031 (c)). The + /// core has no logger, so they are handed to this hook, before the poison check: a message about + /// to be dead-lettered is the one whose producer most needs to hear about them. + #[must_use] + pub fn on_warning(mut self, hook: impl Fn(&Delivery, &str) + Send + Sync + 'static) -> Self { + self.hooks.warning = Some(Arc::new(hook)); + self + } + + /// Registers `handler` as the consumer of `urn` (the last registration wins). + /// + /// The handler gets the decoded [`Envelope`] and the [`Delivery`] it came with, both shared + /// (`Arc`), and returns `Ok` to acknowledge or an error to take the retry and dead-letter path. + /// A panic is caught and treated as an error. `data` is parsed lazily: `env.data::()`. + pub fn handle(&mut self, urn: impl Into, handler: F) + where + F: Fn(Arc, Arc) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + { + let handler: Handler = Arc::new(move |env, delivery| Box::pin(handler(env, delivery))); + self.handlers.insert(urn.into(), handler); + } + + /// The queue `publish` and `run` use when none is given. + #[must_use] + pub fn default_queue(&self) -> &str { + &self.queue + } + + /// The underlying transport. + #[must_use] + pub fn transport(&self) -> &T { + &self.transport + } + + // ----- publishing ------------------------------------------------------------------------- + + /// Builds the canonical envelope for `(urn, data)` on the default queue and publishes it, + /// returning the message id (`meta.id`). + /// + /// # Errors + /// + /// [`PublishError::Encode`] when the envelope cannot be built (nothing reaches the transport), + /// [`PublishError::Transport`] when the transport rejects it. + pub async fn publish( + &self, + urn: &str, + data: &D, + ) -> Result { + let opts = MakeOptions::new().queue(self.queue.clone()); + let env = self.publish_with(urn, data, opts, &HashMap::new()).await?; + Ok(env.meta().id().to_owned()) + } + + /// Like [`App::publish`] with explicit [`MakeOptions`] (the target queue, a trace to continue, + /// `meta` extensions) and out-of-band transport `headers` (a W3C `traceparent` for cross-hop + /// span linkage, ADR-0028), returning the envelope it published. The headers ride beside the + /// envelope on the transport's per-message metadata channel; the envelope is never touched. + /// + /// Headers are propagated when the transport was registered with + /// [`App::with_header_publisher`] and `headers` is not empty; otherwise this is a plain publish. + /// + /// # Errors + /// + /// As [`App::publish`]. + pub async fn publish_with( + &self, + urn: &str, + data: &D, + opts: MakeOptions, + headers: &HashMap, + ) -> Result { + let env = make(urn, data, opts)?; + let body = env.encode()?; + match self.capabilities.publish_with_headers { + Some(publish) if !headers.is_empty() => { + publish(&self.transport, env.meta().queue(), &body, headers).await?; + } + _ => self.transport.publish(env.meta().queue(), &body).await?, + } + Ok(env) + } + + // ----- consuming -------------------------------------------------------------------------- + + /// Consumes the default queue until `shutdown` resolves. See [`App::consume`]. + /// + /// # Errors + /// + /// The first [`TransportError`] from [`Transport::pop`]. + pub async fn run>(&self, shutdown: S) -> Result<(), TransportError> { + self.consume(&self.queue, shutdown).await + } + + /// Processes messages from `queue` until `shutdown` resolves, then returns `Ok`. A single bad + /// message never stops the loop: it is retried or dead-lettered. `shutdown` is checked between + /// pops (it is polled with a no-op waker), so it is observed within one poll timeout. + /// + /// Run one consume loop per queue per task. The loop yields to the executor only through the + /// transport: a transport whose `pop` never returns `Pending` (a polling or busy one) would + /// starve a single-threaded executor and the task that triggers `shutdown`. + /// [`InMemoryTransport`](crate::InMemoryTransport) yields once on an empty queue for that + /// reason. + /// + /// # Errors + /// + /// The first [`TransportError`] from [`Transport::pop`]; the loop does not retry a failing + /// transport, the caller decides (reconnect, back off, exit). + pub async fn consume>( + &self, + queue: &str, + shutdown: S, + ) -> Result<(), TransportError> { + let mut shutdown = pin!(shutdown); + loop { + if is_ready(shutdown.as_mut()) { + return Ok(()); + } + if let Some(delivery) = self.transport.pop(queue, self.poll_timeout).await? { + self.dispatch(delivery).await; + } + } + } + + /// Processes up to `max` messages from `queue` and returns the count, stopping early when the + /// queue is empty. With `max == 0` it drains until empty. Useful for tests and one-shot workers. + /// + /// # Errors + /// + /// The first [`TransportError`] from [`Transport::pop`]. + pub async fn drain(&self, queue: &str, max: usize) -> Result { + let mut processed = 0; + while max == 0 || processed < max { + let Some(delivery) = self.transport.pop(queue, self.poll_timeout).await? else { + break; + }; + self.dispatch(delivery).await; + processed += 1; + } + Ok(processed) + } + + async fn dispatch(&self, delivery: Delivery) { + // A version-gated delivery can never be handled by any registered handler and a retry cannot + // change that: it is dead-lettered directly, before the body is decoded. + if delivery + .route_urn + .as_deref() + .is_some_and(|r| r.starts_with(UNSUPPORTED_SCHEMA_ROUTE_PREFIX)) + { + self.settle_version_gated(&delivery).await; + return; + } + // A delivery the transport classified as poison is dead-lettered with its body untouched, + // whatever decode would make of it: no handler and no retry may run for it. + if delivery.poison { + let cause = decode(&delivery.body) + .err() + .filter(|e| !e.is_no_identity()) + .map(|e| decode_cause(&e)); + self.settle_raw_poison(&delivery, cause.as_ref()).await; + return; + } + + // A blank routing override (an empty header value) names nothing: it is no override, and the + // body's own URN routes the message. + let route = delivery.route_urn.as_deref().filter(|r| !is_blank_ascii(r)); + let mut env = match decode(&delivery.body) { + Ok(decoded) => { + self.warn_all(&delivery, decoded.warnings()); + decoded.into_envelope() + } + // ADR-0032 section 6: a body with no valid job or urn alias is poison. The one + // exception is a delivery whose transport supplied the identity out of band + // (`route_urn`): the body is not rewritten and the override names the handler. + Err(e) if e.is_no_identity() && route.is_some() => { + let partial = e + .partial() + .map(|d| (d.envelope().clone(), d.warnings().to_vec())); + let Some((env, warnings)) = partial else { + return self.route_poison(&delivery, decode_cause(&e)).await; + }; + self.warn_all(&delivery, &warnings); + env + } + Err(e) => { + if let Some(partial) = e.partial() { + self.warn_all(&delivery, partial.warnings()); + } + self.route_poison(&delivery, decode_cause(&e)).await; + return; + } + }; + // The broker's own delivery count is a floor for attempts: an in-place release does not + // rewrite the body, so without it such a message would never reach `max_attempts`. + let native = delivery.delivery_count.saturating_sub(1); + if native > env.attempts() { + env.set_attempts(native); + } + let urn = route.map_or_else(|| env.urn().to_owned(), str::to_owned); + if is_blank_ascii(&urn) { + let cause = + FailureCause::new("babelqueue: the message names no URN", "babelqueue::Poison"); + self.route_poison(&delivery, cause).await; + return; + } + let Some(handler) = self.handlers.get(&urn) else { + self.route_unknown(&delivery, &urn, env).await; + return; + }; + + let shared_env = Arc::new(env); + let shared_delivery = Arc::new(delivery); + let outcome = call_handler( + handler, + Arc::clone(&shared_env), + Arc::clone(&shared_delivery), + ) + .await; + let delivery = &*shared_delivery; + match outcome { + Ok(()) => self.ack(delivery).await, + Err(failure) => { + let env = Arc::try_unwrap(shared_env).unwrap_or_else(|shared| (*shared).clone()); + self.retry_or_dead_letter(delivery, env, &failure.cause(), false) + .await; + } + } + } + + fn warn_all(&self, delivery: &Delivery, warnings: &[String]) { + if let Some(hook) = &self.hooks.warning { + for warning in warnings { + guarded(|| hook(delivery, warning)); + } + } + } + + async fn ack(&self, delivery: &Delivery) { + if let Err(e) = self.transport.ack(delivery).await { + if let Some(hook) = &self.hooks.ack_error { + guarded(|| hook(delivery, &e)); + } + } + } + + /// Acknowledges `delivery` unless a gated operation already settled it. + async fn settle(&self, delivery: &Delivery, settled: bool) { + if !settled { + self.ack(delivery).await; + } + } + + // ----- failure routing -------------------------------------------------------------------- + + /// A body that does not decode (or has no identity and no routing override). No handler can + /// ever be registered for it, so only the unknown-URN strategies that make sense apply: with + /// dead-lettering on (and not [`UnknownUrnStrategy::Delete`]) it is never retried (a retry could + /// only re-publish a body that cannot be re-encoded) and is written to the DLQ with its original + /// bytes preserved; `Delete` drops it. With dead-lettering off there is nowhere to put it: it is + /// released in place while the broker's delivery count stays under `max_attempts` (on a + /// [`Releaser`]), then dropped. + async fn route_poison(&self, delivery: &Delivery, cause: FailureCause) { + if self.unknown_urn == UnknownUrnStrategy::Delete { + self.ack(delivery).await; + return; + } + if self.dead_letter || self.unknown_urn == UnknownUrnStrategy::DeadLetter { + self.settle_raw_poison(delivery, Some(&cause)).await; + return; + } + let seen = delivery.delivery_count.max(1); + if seen < self.max_attempts && self.release(delivery, self.backoff.delay(seen)).await { + return; + } + self.ack(delivery).await; + } + + /// Dead-letters an undecodable body without retrying it: the record follows ADR-0035 + /// (spliced when the body is a strict JSON object, otherwise wrapped), acknowledged only after + /// the DLQ write succeeded. + async fn settle_raw_poison(&self, delivery: &Delivery, cause: Option<&FailureCause>) { + let attempts = delivery.delivery_count.saturating_sub(1); + let record = poison_dead_letter_body(&delivery.body, &delivery.queue, attempts, cause); + match self + .dead_letter_raw(delivery, &record, Some("poison"), &delivery.queue) + .await + { + Ok(settled) => self.settle(delivery, settled).await, + Err(e) => self.leave_dead_letter_unsettled(delivery, &e), + } + } + + /// Settles a version-gated delivery without retrying it and without ever running a handler: it + /// is acknowledged (dropped) under [`UnknownUrnStrategy::Delete`], dead-lettered when + /// dead-lettering is on (or under [`UnknownUrnStrategy::DeadLetter`]) and otherwise + /// acknowledged (dropped). The DLQ record is the raw body, byte-identical to the incoming one: + /// an unknown schema is never best-effort parsed or re-encoded, so no `dead_letter` block is + /// added. + async fn settle_version_gated(&self, delivery: &Delivery) { + if self.unknown_urn == UnknownUrnStrategy::Delete + || (!self.dead_letter && self.unknown_urn != UnknownUrnStrategy::DeadLetter) + { + self.ack(delivery).await; + return; + } + match self + .dead_letter_raw(delivery, &delivery.body, None, &delivery.queue) + .await + { + Ok(settled) => self.settle(delivery, settled).await, + Err(e) => self.leave_dead_letter_unsettled(delivery, &e), + } + } + + async fn route_unknown(&self, delivery: &Delivery, urn: &str, env: Envelope) { + match self.unknown_urn { + UnknownUrnStrategy::Delete => self.ack(delivery).await, + UnknownUrnStrategy::Release => { + if self.release(delivery, self.unknown_urn_delay).await { + return; + } + match self + .transport + .publish(&delivery.queue, &delivery.body) + .await + { + Ok(()) => self.ack(delivery).await, + Err(e) => self.leave_republish_unsettled(delivery, &e), + } + } + // The immediate dead-letter carries no cause (`error` and `exception` are `null`), like the + // Go and Python SDKs; only the retry path (`fail`) records one. + UnknownUrnStrategy::DeadLetter => { + self.dead_letter_message(delivery, env, "unknown_urn", None) + .await; + } + UnknownUrnStrategy::Fail => { + let cause = unknown_urn_cause(urn); + self.retry_or_dead_letter(delivery, env, &cause, true).await; + } + } + } + + async fn retry_or_dead_letter( + &self, + delivery: &Delivery, + mut env: Envelope, + cause: &FailureCause, + unknown_urn: bool, + ) { + env.increment_attempts(); + if env.attempts() < self.max_attempts { + // A releaser redelivers the original in place; the broker's own delivery count then + // carries the incremented attempt (no re-publish, no ack). + if self + .release(delivery, self.backoff.delay(env.attempts())) + .await + { + return; + } + let published = match env.encode() { + Ok(body) => self + .transport + .publish(&delivery.queue, &body) + .await + .map_err(|e| Box::new(e) as Box), + Err(e) => Err(Box::new(e) as Box), + }; + match published { + Ok(()) => self.ack(delivery).await, + Err(e) => self.leave_republish_unsettled(delivery, &*e), + } + return; + } + if self.dead_letter { + let reason = if unknown_urn { "unknown_urn" } else { "failed" }; + self.dead_letter_message(delivery, env, reason, Some(cause)) + .await; + return; + } + // Retries exhausted and no dead-letter configured: drop it (ack so it leaves the queue). + self.ack(delivery).await; + } + + async fn dead_letter_message( + &self, + delivery: &Delivery, + env: Envelope, + reason: &str, + cause: Option<&FailureCause>, + ) { + // `dead_letter.original_queue` is wire data: `meta.queue` when non-empty, else the + // delivery's queue. The event's queue is not wire data: a blank `meta.queue` names no + // queue, so the delivery's own stands in. + let meta_queue = env.meta().queue().to_owned(); + let original_queue = if meta_queue.is_empty() { + delivery.queue.clone() + } else { + meta_queue.clone() + }; + let event_queue = if is_blank_ascii(&meta_queue) { + delivery.queue.clone() + } else { + meta_queue + }; + let attempts = env.attempts(); + let annotated = annotate(env, reason, &original_queue, attempts, cause); + let body = match annotated.encode() { + Ok(body) => body, + Err(e) => { + self.leave_dead_letter_unsettled(delivery, &e); + return; + } + }; + match self + .dead_letter_raw(delivery, &body, Some(reason), &event_queue) + .await + { + Ok(settled) => self.settle(delivery, settled).await, + Err(e) => self.leave_dead_letter_unsettled(delivery, &e), + } + } + + /// Writes `body` to the dead-letter queue of `delivery`. With a [`DeadLetterSettler`] it is one + /// gated step that also settles the delivery (`Ok(true)`: the caller must not ack); otherwise + /// the body is published and the caller acks. After a confirmed write it notifies the + /// [`App::on_dead_letter`] hook; a failed write notifies nothing. + async fn dead_letter_raw( + &self, + delivery: &Delivery, + body: &[u8], + reason: Option<&str>, + source_queue: &str, + ) -> Result { + let target = self.dead_letter_target(delivery); + let settled = if let Some(settle) = self.capabilities.dead_letter { + settle(&self.transport, delivery, &target, body).await?; + true + } else { + self.transport.publish(&target, body).await?; + false + }; + if let Some(hook) = &self.hooks.dead_letter { + let event = DeadLetterEvent { + queue: source_queue.to_owned(), + dead_letter_queue: target, + reason: reason.map(str::to_owned), + }; + guarded(|| hook(&event)); + } + Ok(settled) + } + + fn dead_letter_target(&self, delivery: &Delivery) -> String { + self.dead_letter_queue + .clone() + .unwrap_or_else(|| format!("{}{}", delivery.queue, self.dead_letter_suffix)) + } + + /// Hands `delivery` back through the transport's in-place release. `false` only when the + /// transport has no releaser or reports it unsupported for this message, so the caller falls + /// back to re-publish plus ack. Any other failure is reported and still counts as handled: the + /// message is neither re-published nor acked and the broker redelivers it when its reservation + /// lapses (a release never deletes the message). + async fn release(&self, delivery: &Delivery, delay: Duration) -> bool { + let Some(release) = self.capabilities.release else { + return false; + }; + match release(&self.transport, delivery, delay).await { + Ok(()) => true, + Err(ReleaseError::Unsupported) => false, + Err(e) => { + if let Some(hook) = &self.hooks.release_error { + guarded(|| hook(delivery, &e)); + } + true + } + } + } + + /// A dead-letter write failed: the message is not acknowledged (acknowledging it would lose + /// it), so it stays with the broker, and the failure is reported. + fn leave_dead_letter_unsettled(&self, delivery: &Delivery, error: &(dyn Error + 'static)) { + if let Some(hook) = &self.hooks.dead_letter_error { + guarded(|| hook(delivery, error)); + } + } + + /// A re-publish that was to replace `delivery` failed: it is not acknowledged and the failure is + /// reported. + fn leave_republish_unsettled(&self, delivery: &Delivery, error: &(dyn Error + 'static)) { + if let Some(hook) = &self.hooks.release_error { + guarded(|| hook(delivery, error)); + } + } +} + +// Capability opt-ins: each is available only for a transport that implements the trait, so what the +// runtime does is decided by what the transport offers, never by its name. + +impl App { + /// Propagates out-of-band headers on [`App::publish_with`] through the transport's + /// [`HeaderPublisher`] capability. + #[must_use] + pub fn with_header_publisher(mut self) -> Self { + self.capabilities.publish_with_headers = Some(publish_with_headers_via::); + self + } +} + +impl App { + /// Retries and [`UnknownUrnStrategy::Release`] return the message to its queue in place through + /// the transport's [`Releaser`] capability (honouring the backoff delay) instead of re-publishing + /// a copy. + #[must_use] + pub fn with_releaser(mut self) -> Self { + self.capabilities.release = Some(release_via::); + self + } +} + +impl App { + /// Dead-letter writes go through the transport's [`DeadLetterSettler`] capability, one gated + /// step that also settles the message. + #[must_use] + pub fn with_dead_letter_settler(mut self) -> Self { + self.capabilities.dead_letter = Some(dead_letter_via::); + self + } +} + +/// Polls `future` once with a no-op waker and reports whether it resolved. The `Context` lives only +/// inside this synchronous function: a `Context` held across an `.await` would make the consume +/// future `!Send`. +fn is_ready>(future: Pin<&mut F>) -> bool { + future + .poll(&mut Context::from_waker(Waker::noop())) + .is_ready() +} + +fn decode_cause(error: &DecodeError) -> FailureCause { + FailureCause::new(error.to_string(), "babelqueue::DecodeError") +} + +fn unknown_urn_cause(urn: &str) -> FailureCause { + FailureCause::new( + format!("babelqueue: no handler registered for URN {urn:?}"), + "babelqueue::UnknownUrn", + ) +} + +// --------------------------------------------------------------------------------------------- +// Panic containment +// --------------------------------------------------------------------------------------------- + +/// Polls a handler future inside `catch_unwind`, so a panic in any poll becomes a value. +struct CatchUnwind { + future: HandlerFuture, +} + +impl Future for CatchUnwind { + type Output = Result, Box>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let future = self.future.as_mut(); + match catch_unwind(AssertUnwindSafe(|| future.poll(cx))) { + Ok(Poll::Pending) => Poll::Pending, + Ok(Poll::Ready(result)) => Poll::Ready(Ok(result)), + Err(payload) => Poll::Ready(Err(payload)), + } + } +} + +/// Calls a handler and awaits it, turning a panic (in the call or in any poll of the future) into +/// a [`HandlerError`] with exception `panic`. Without it one panicking handler would take the whole +/// worker down. +async fn call_handler( + handler: &Handler, + env: Arc, + delivery: Arc, +) -> Result<(), HandlerError> { + let handler = handler.as_ref(); + let future = match catch_unwind(AssertUnwindSafe(|| handler(env, delivery))) { + Ok(future) => future, + Err(payload) => return Err(panic_error(payload.as_ref())), + }; + match (CatchUnwind { future }).await { + Ok(result) => result, + Err(payload) => Err(panic_error(payload.as_ref())), + } +} + +fn panic_error(payload: &(dyn Any + Send)) -> HandlerError { + let text = payload + .downcast_ref::<&str>() + .map(|s| (*s).to_owned()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "non-string panic payload".to_owned()); + HandlerError { + message: format!("handler panicked: {text}"), + exception: "panic".to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn declared_version_is_capped_at_64_characters() { + let long = "v".repeat(100); + let capped = truncate_declared_version(&long); + assert_eq!(capped, format!("{}...", "v".repeat(64))); + assert_eq!(truncate_declared_version("2"), "2"); + let exact = "x".repeat(64); + assert_eq!(truncate_declared_version(&exact), exact); + let multibyte = "\u{e9}".repeat(70); + assert_eq!( + truncate_declared_version(&multibyte), + format!("{}...", "\u{e9}".repeat(64)) + ); + } + + #[test] + fn strategies_parse_by_configuration_name() { + for s in [ + UnknownUrnStrategy::Fail, + UnknownUrnStrategy::Delete, + UnknownUrnStrategy::Release, + UnknownUrnStrategy::DeadLetter, + ] { + assert_eq!(s.as_str().parse::(), Ok(s)); + } + assert!("nope".parse::().is_err()); + } +} diff --git a/crates/babelqueue/src/backoff.rs b/crates/babelqueue/src/backoff.rs new file mode 100644 index 0000000..06c4c11 --- /dev/null +++ b/crates/babelqueue/src/backoff.rs @@ -0,0 +1,173 @@ +//! Worker-side retry backoff (ADR-0034 section 9). + +use std::time::Duration; + +/// How a computed retry delay is randomised. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Jitter { + /// The computed delay is applied exactly (the default). + #[default] + None, + /// The delay is drawn uniformly from `[0, d(n)]`. + Full, +} + +/// The retry delay formula: `d(n) = min(max, base * multiplier^(n-1))` with `n = attempts + 1` +/// (1-based), `max == 0` meaning no cap. With [`Jitter::Full`] the delay is `uniform(0, d(n))`. +/// +/// The defaults (`base` 0, `multiplier` 1, `max` 0) yield a zero delay, so an unconfigured runtime +/// retries at once. +/// +/// ``` +/// use std::time::Duration; +/// use babelqueue::{Backoff, Jitter}; +/// +/// let backoff = Backoff::new(Duration::from_secs(1)) +/// .multiplier(2.0) +/// .max(Duration::from_secs(10)) +/// .jitter(Jitter::None); +/// assert_eq!(backoff.delay(3), Duration::from_secs(4)); +/// assert_eq!(backoff.delay(20), Duration::from_secs(10)); +/// ``` +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Backoff { + base: Duration, + multiplier: f64, + max: Duration, + jitter: Jitter, +} + +impl Default for Backoff { + fn default() -> Self { + Self { + base: Duration::ZERO, + multiplier: 1.0, + max: Duration::ZERO, + jitter: Jitter::None, + } + } +} + +impl Backoff { + /// A backoff with the given base delay, multiplier 1, no cap and no jitter. + #[must_use] + pub fn new(base: Duration) -> Self { + Self { + base, + ..Self::default() + } + } + + /// Sets the growth factor between consecutive retries. A value below 1 (or not finite) is + /// ignored. + #[must_use] + pub fn multiplier(mut self, multiplier: f64) -> Self { + if multiplier.is_finite() && multiplier >= 1.0 { + self.multiplier = multiplier; + } + self + } + + /// Sets the cap on a computed delay (`0` = no cap). + #[must_use] + pub fn max(mut self, max: Duration) -> Self { + self.max = max; + self + } + + /// Sets the jitter mode. + #[must_use] + pub fn jitter(mut self, jitter: Jitter) -> Self { + self.jitter = jitter; + self + } + + /// The deterministic delay `d(n)` for the `n`-th failure (`n = attempts + 1`; `0` is read as + /// `1`), before any jitter. + #[must_use] + pub fn base_delay(&self, n: u64) -> Duration { + let base = self.base.as_secs_f64(); + if base <= 0.0 { + return Duration::ZERO; + } + let exponent = i32::try_from(n.max(1) - 1).unwrap_or(i32::MAX); + let mut seconds = base * self.multiplier.powi(exponent); + let cap = self.max.as_secs_f64(); + if cap > 0.0 && seconds > cap { + seconds = cap; + } + Duration::try_from_secs_f64(seconds).unwrap_or(Duration::MAX) + } + + /// The delay to wait before the `n`-th retry, with jitter applied from the operating system's + /// randomness. + #[must_use] + pub fn delay(&self, n: u64) -> Duration { + self.delay_with(n, random_unit) + } + + /// Like [`Backoff::delay`] with a caller-supplied random source returning a value in `[0, 1)`. + #[must_use] + pub fn delay_with(&self, n: u64, random: impl FnOnce() -> f64) -> Duration { + let d = self.base_delay(n); + match self.jitter { + Jitter::Full if !d.is_zero() => d.mul_f64(random().clamp(0.0, 1.0)), + _ => d, + } + } +} + +/// A uniform value in `[0, 1)` from `getrandom`; `0.5` if the system has no randomness (jitter is +/// best effort and must never fail a retry). +fn random_unit() -> f64 { + let mut bytes = [0u8; 8]; + if getrandom::fill(&mut bytes).is_err() { + return 0.5; + } + // 53 random bits fill an f64 mantissa exactly. + #[allow(clippy::cast_precision_loss)] + let unit = (u64::from_le_bytes(bytes) >> 11) as f64 / (1u64 << 53) as f64; + unit +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_are_zero() { + assert_eq!(Backoff::default().delay(1), Duration::ZERO); + assert_eq!(Backoff::default().delay(5), Duration::ZERO); + } + + #[test] + fn exponential_growth_is_capped() { + let b = Backoff::new(Duration::from_secs(1)) + .multiplier(2.0) + .max(Duration::from_secs(10)); + let secs: Vec = (1..=6).map(|n| b.delay(n).as_secs()).collect(); + assert_eq!(secs, [1, 2, 4, 8, 10, 10]); + } + + #[test] + fn huge_exponent_saturates_instead_of_panicking() { + let b = Backoff::new(Duration::from_secs(2)).multiplier(10.0); + assert_eq!(b.delay(u64::MAX), Duration::MAX); + } + + #[test] + fn full_jitter_is_scaled_by_the_random_draw() { + let b = Backoff::new(Duration::from_secs(4)).jitter(Jitter::Full); + assert_eq!(b.delay_with(1, || 0.5), Duration::from_secs(2)); + assert_eq!(b.delay_with(1, || 0.0), Duration::ZERO); + for _ in 0..50 { + assert!(b.delay(1) <= Duration::from_secs(4)); + } + } + + #[test] + fn multiplier_below_one_is_ignored() { + let b = Backoff::new(Duration::from_secs(3)).multiplier(0.5); + assert_eq!(b.delay(4), Duration::from_secs(3)); + } +} diff --git a/crates/babelqueue/src/codec/encode.rs b/crates/babelqueue/src/codec/encode.rs index 39b62a4..e8761c3 100644 --- a/crates/babelqueue/src/codec/encode.rs +++ b/crates/babelqueue/src/codec/encode.rs @@ -297,7 +297,7 @@ fn write_opt_str(out: &mut Vec, s: Option<&str>) -> Result<(), EncodeError> } } -fn write_dead_letter(out: &mut Vec, dl: &DeadLetter) -> Result<(), EncodeError> { +pub(crate) fn write_dead_letter(out: &mut Vec, dl: &DeadLetter) -> Result<(), EncodeError> { out.extend_from_slice(b"{\"reason\":"); write_str(out, &dl.reason)?; out.extend_from_slice(b",\"error\":"); diff --git a/crates/babelqueue/src/dlq.rs b/crates/babelqueue/src/dlq.rs new file mode 100644 index 0000000..1aab05c --- /dev/null +++ b/crates/babelqueue/src/dlq.rs @@ -0,0 +1,216 @@ +//! The `dead_letter` block (message-envelope.md section 10b, ADR-0009). + +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::SOURCE_LANG; +use crate::envelope::{DeadLetter, Envelope}; + +/// Why a message failed: the error text and the type of the failure, as written to +/// `dead_letter.error` and `dead_letter.exception`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FailureCause { + message: String, + exception: String, +} + +impl FailureCause { + /// A cause with an explicit message and failure type name. + #[must_use] + pub fn new(message: impl Into, exception: impl Into) -> Self { + Self { + message: message.into(), + exception: exception.into(), + } + } + + /// A cause from an error value: its `Display` text and its Rust type name. + #[must_use] + pub fn from_error(error: &E) -> Self { + Self::new(error.to_string(), public_type_name::()) + } + + /// The failure message. + #[must_use] + pub fn message(&self) -> &str { + &self.message + } + + /// The failure type name. + #[must_use] + pub fn exception(&self) -> &str { + &self.exception + } +} + +/// `std::any::type_name::()` with this crate's private module segments removed, so the string +/// recorded in `dead_letter.exception` names the public path (`babelqueue::DecodeError`, not +/// `babelqueue::error::DecodeError`). `type_name` is not guaranteed stable across compiler +/// versions; the SDK's own failures use fixed names instead (see `decode_cause`). +pub(crate) fn public_type_name() -> String { + let mut name = std::any::type_name::().to_owned(); + for private in [ + "error", + "transport", + "app", + "dlq", + "memory", + "poison", + "envelope", + "codec", + ] { + name = strip_segment(&name, &format!("babelqueue::{private}::")); + } + name +} + +/// Replaces `path` (for example `babelqueue::error::`) with `babelqueue::` wherever it starts a path: +/// at the beginning of the name or after a separator such as `<`, `,`, ` `, `(`, `&`, `[`. A match +/// inside a longer crate name (`acme_babelqueue::error::E`) is left alone. +fn strip_segment(name: &str, path: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut rest = name; + while let Some(at) = rest.find(path) { + let boundary = rest[..at] + .chars() + .next_back() + .is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == ':')); + // `out` already holds what precedes `rest`, so the boundary also looks at it at the start. + let boundary = if at == 0 { + out.chars() + .next_back() + .is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == ':')) + } else { + boundary + }; + out.push_str(&rest[..at]); + out.push_str(if boundary { "babelqueue::" } else { path }); + rest = &rest[at + path.len()..]; + } + out.push_str(rest); + out +} + +/// Builds the block this SDK writes: `failed_at` is now (Unix milliseconds, UTC) and `lang` is +/// `rust`. A missing cause is `null` on the wire. +pub(crate) fn dead_letter_block( + reason: &str, + original_queue: &str, + attempts: u64, + cause: Option<&FailureCause>, +) -> DeadLetter { + let failed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|d| i64::try_from(d.as_millis()).ok()) + .unwrap_or_default(); + DeadLetter { + reason: reason.to_owned(), + error: cause.map(|c| c.message.clone()), + exception: cause.map(|c| c.exception.clone()), + failed_at, + original_queue: original_queue.to_owned(), + attempts, + lang: SOURCE_LANG.to_owned(), + } +} + +/// Returns `env` with a `dead_letter` block attached, recording why and where it failed. +/// +/// The envelope is otherwise unchanged: `job`, `trace_id`, `data`, unknown keys and `attempts` are +/// re-emitted as they were. The block is always built afresh: an existing `dead_letter` block (a +/// message that is dead-lettered a second time, for example after a redrive) is replaced as a +/// whole, and unknown members of the old block are not carried. `reason` is `failed`, +/// `unknown_urn` or `poison`. +/// +/// ``` +/// use babelqueue::{MakeOptions, annotate}; +/// +/// let env = babelqueue::make("urn:babel:orders:created", &serde_json::json!({"order_id": 1}), MakeOptions::new())?; +/// let dead = annotate(env, "failed", "orders", 3, None); +/// assert_eq!(dead.dead_letter().map(|d| d.reason.as_str()), Some("failed")); +/// # Ok::<(), babelqueue::EncodeError>(()) +/// ``` +#[must_use] +pub fn annotate( + mut env: Envelope, + reason: &str, + original_queue: &str, + attempts: u64, + cause: Option<&FailureCause>, +) -> Envelope { + env.set_dead_letter(Some(dead_letter_block( + reason, + original_queue, + attempts, + cause, + ))); + env +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MakeOptions, decode, make}; + + #[test] + fn exception_names_use_public_paths() { + assert_eq!( + FailureCause::from_error(&crate::DecodeError::InvalidField { + pointer: String::new(), + expected: "x" + }) + .exception(), + "babelqueue::DecodeError" + ); + assert_eq!( + public_type_name::(), + "babelqueue::TransportError" + ); + // Another crate's path is never rewritten, even when its name contains ours. + assert_eq!( + strip_segment( + "acme_babelqueue::error::PaymentFailed", + "babelqueue::error::" + ), + "acme_babelqueue::error::PaymentFailed" + ); + assert_eq!( + strip_segment( + "Wrapper", + "babelqueue::app::" + ), + "Wrapper" + ); + assert_eq!( + strip_segment("babelqueue::app::E", "babelqueue::app::"), + "babelqueue::E" + ); + assert_eq!( + public_type_name::(), + "babelqueue::schema::InvalidPayload" + ); + } + + #[test] + fn annotate_replaces_an_existing_block_and_keeps_the_payload() { + let env = make("urn:x:y", &serde_json::json!({"a": 1}), MakeOptions::new()).unwrap(); + let first = annotate( + env, + "failed", + "q1", + 1, + Some(&FailureCause::new("boom", "E")), + ); + let second = annotate(first, "unknown_urn", "q2", 4, None); + let block = second.dead_letter().unwrap(); + assert_eq!(block.reason, "unknown_urn"); + assert_eq!(block.original_queue, "q2"); + assert_eq!(block.attempts, 4); + assert_eq!(block.error, None); + assert_eq!(block.lang, "rust"); + assert!(block.failed_at > 1_700_000_000_000); + let back = decode(&second.encode().unwrap()).unwrap().into_envelope(); + assert_eq!(back.data_json(), Some(r#"{"a":1}"#)); + assert_eq!(back.dead_letter(), Some(block)); + } +} diff --git a/crates/babelqueue/src/idempotency.rs b/crates/babelqueue/src/idempotency.rs new file mode 100644 index 0000000..a5986ed --- /dev/null +++ b/crates/babelqueue/src/idempotency.rs @@ -0,0 +1,134 @@ +//! Optional consumer-side dedupe keyed on `meta.id` (ADR-0022). +//! +//! [`wrap`] decorates a handler so a message whose `meta.id` was already processed is skipped +//! instead of run again. The contract is a seen-set: it answers "was this id processed?", not +//! "what did it return". It gives post-success dedupe under at-least-once delivery and idempotent +//! handlers (error-handling.md section 1); it is not exactly-once delivery and not an in-flight +//! concurrency lock. The wire envelope is never touched. + +use std::collections::HashSet; +use std::error::Error; +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; + +use crate::app::{HandlerError, HandlerFuture}; +use crate::envelope::Envelope; +use crate::transport::Delivery; + +type BoxError = Box; + +/// A failure of a [`Store`] (a lost connection, a rejected write). +#[derive(Debug)] +pub struct StoreError(BoxError); + +impl StoreError { + /// Wraps a client error. + pub fn new(source: impl Into) -> Self { + Self(source.into()) + } +} + +impl fmt::Display for StoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "babelqueue: idempotency store: {}", self.0) + } +} + +impl Error for StoreError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&*self.0) + } +} + +/// A pluggable record of message ids that have already been processed, keyed on the envelope's +/// `meta.id` (the canonical per-message identity, distinct from `trace_id`). The reference +/// [`InMemoryStore`] is for tests and single-process consumers; production backends (Redis, a +/// database table) implement the same three methods. +pub trait Store: Send + Sync { + /// Whether this message id has already been processed. + fn seen(&self, message_id: &str) -> impl Future> + Send; + /// Records this message id as processed. + fn remember(&self, message_id: &str) -> impl Future> + Send; + /// Drops a message id (manual eviction; a backend may also expire ids on its own TTL). + fn forget(&self, message_id: &str) -> impl Future> + Send; +} + +/// A process-local [`Store`]. It is shared by reference-counting (`Arc`), not +/// shared across workers and not persistent: use a Redis- or database-backed store for fleets. +#[derive(Debug, Default)] +pub struct InMemoryStore { + seen: Mutex>, +} + +impl InMemoryStore { + /// An empty store. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + fn lock(&self) -> std::sync::MutexGuard<'_, HashSet> { + self.seen + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +impl Store for InMemoryStore { + async fn seen(&self, message_id: &str) -> Result { + Ok(self.lock().contains(message_id)) + } + + async fn remember(&self, message_id: &str) -> Result<(), StoreError> { + self.lock().insert(message_id.to_owned()); + Ok(()) + } + + async fn forget(&self, message_id: &str) -> Result<(), StoreError> { + self.lock().remove(message_id); + Ok(()) + } +} + +/// Decorates `handler` so a message whose `meta.id` was already processed successfully is skipped. +/// It composes with the runtime's ack-on-success, retry-on-error contract: +/// +/// * an already-seen id returns `Ok`, so the runtime acks it and the broker stops redelivering; +/// * a handler error leaves the id unmarked and propagates, so retry and dead-letter still apply +/// and a later delivery runs the handler again; +/// * a store error on lookup is surfaced (the message is retried once the store recovers) rather +/// than guessing the dedupe state; +/// * a message with no usable `meta.id` runs unchanged (fail open); +/// * a failed `remember` after a successful handler is ignored (the documented at-least-once +/// dual-write window: a later redelivery may reprocess). +/// +/// Register the result like any handler: `app.handle(urn, idempotency::wrap(store, handler))`. +pub fn wrap( + store: Arc, + handler: F, +) -> impl Fn(Arc, Arc) -> HandlerFuture + Send + Sync + 'static +where + S: Store + 'static, + F: Fn(Arc, Arc) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let handler = Arc::new(handler); + move |env: Arc, delivery: Arc| -> Pin + Send>> { + let store = Arc::clone(&store); + let handler = Arc::clone(&handler); + Box::pin(async move { + let id = env.meta().id().to_owned(); + if id.is_empty() { + return handler(env, delivery).await; + } + if store.seen(&id).await.map_err(HandlerError::from)? { + return Ok(()); + } + handler(env, delivery).await?; + let _ = store.remember(&id).await; + Ok(()) + }) + } +} diff --git a/crates/babelqueue/src/lib.rs b/crates/babelqueue/src/lib.rs index 7b71475..15a02f5 100644 --- a/crates/babelqueue/src/lib.rs +++ b/crates/babelqueue/src/lib.rs @@ -1,7 +1,7 @@ //! BabelQueue core for Rust: the language-agnostic queue message envelope. //! //! The wire envelope (`{job, trace_id, data, meta, attempts}`) is frozen at `schema_version: 1` -//! (ADR-0041). This crate holds the codec; the runtime lands in a later phase of the Rust SDK plan. +//! (ADR-0041). This crate holds the codec and the broker-agnostic runtime. //! //! * [`make`] builds a new envelope from a URN and any `Serialize` value; [`Envelope::encode`] //! renders it as compact JSON in the canonical frame. @@ -14,6 +14,18 @@ //! The codec is synchronous and needs no async runtime. Only `serde`, `serde_json` and `getrandom` //! are linked (GR-7). //! +//! # Runtime +//! +//! * [`App`] publishes and consumes by URN over a [`Transport`] (`publish` / `pop` / `ack`, native +//! `async fn` in traits, no executor). It implements the unknown-URN strategies, the version gate, +//! poison routing, retry with [`Backoff`], the DLQ `dead_letter` block ([`annotate`], +//! [`poison_dead_letter_body`]) and contains handler panics. +//! * Optional transport capabilities are separate traits ([`HeaderPublisher`], [`Releaser`], +//! [`DeadLetterSettler`]) switched on with `App::with_*`. +//! * [`InMemoryTransport`] backs tests and broker-free runs. +//! * [`idempotency`] (ADR-0022) and [`schema`] (ADR-0024) wrap a handler; [`results`] writes the +//! conformance `results.json`. +//! //! # Known encoding difference //! //! `serde_json` does not escape U+2028 and U+2029, while the PHP and Go encoders do. Both forms are @@ -21,15 +33,37 @@ #![forbid(unsafe_code)] +mod app; +mod backoff; mod codec; +mod dlq; mod envelope; mod error; +mod memory; +mod poison; +mod transport; mod uuid; +pub mod idempotency; +pub mod results; +pub mod schema; + +pub use app::{ + App, DeadLetterEvent, HandlerError, HandlerFuture, PublishError, + UNSUPPORTED_SCHEMA_ROUTE_PREFIX, UnknownUrnStrategy, truncate_declared_version, +}; +pub use backoff::{Backoff, Jitter}; pub use codec::decode::{Decoded, decode}; pub use codec::encode::{MakeOptions, make}; +pub use dlq::{FailureCause, annotate}; pub use envelope::{DeadLetter, Envelope, Meta}; pub use error::{DecodeError, EncodeError}; +pub use memory::InMemoryTransport; +pub use poison::poison_dead_letter_body; +pub use schema::{Schema, SchemaError, SchemaWarning}; +pub use transport::{ + DeadLetterSettler, Delivery, HeaderPublisher, ReleaseError, Releaser, Transport, TransportError, +}; /// The wire-envelope `meta.schema_version` this SDK reads and writes. pub const SCHEMA_VERSION: u32 = 1; diff --git a/crates/babelqueue/src/memory.rs b/crates/babelqueue/src/memory.rs new file mode 100644 index 0000000..56f139f --- /dev/null +++ b/crates/babelqueue/src/memory.rs @@ -0,0 +1,126 @@ +//! An in-process [`Transport`] for tests and broker-free local runs. + +use std::collections::{HashMap, VecDeque}; +use std::future::Future; +use std::pin::Pin; +use std::sync::Mutex; +use std::task::{Context, Poll}; +use std::time::Duration; + +use crate::transport::{Delivery, HeaderPublisher, Transport, TransportError}; + +struct Stored { + body: Vec, + headers: HashMap, +} + +/// An in-process queue set. It is safe for concurrent use. [`Transport::pop`] returns immediately +/// (it does not wait for the timeout) and resolves to `None` on an empty queue. A consume loop over +/// it would spin, so an empty pop yields to the executor once (`Pending` once, after waking itself) +/// before it resolves: a task that triggers shutdown still gets to run on a single-threaded +/// executor. [`App::drain`](crate::App::drain) is still the better fit for tests. A popped message is removed at +/// once, so [`Transport::ack`] is a no-op and nothing is redelivered. +#[derive(Default)] +pub struct InMemoryTransport { + queues: Mutex>>, +} + +impl InMemoryTransport { + /// An empty transport. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap>> { + // A poisoned lock only means another thread panicked mid-operation on a plain map. + self.queues + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn push(&self, queue: &str, body: &[u8], headers: HashMap) { + self.lock() + .entry(queue.to_owned()) + .or_default() + .push_back(Stored { + body: body.to_vec(), + headers, + }); + } + + /// How many messages are pending on `queue`. + #[must_use] + pub fn size(&self, queue: &str) -> usize { + self.lock().get(queue).map_or(0, VecDeque::len) + } + + /// The bodies pending on `queue`, oldest first, without removing them. + #[must_use] + pub fn bodies(&self, queue: &str) -> Vec> { + self.lock() + .get(queue) + .map(|q| q.iter().map(|m| m.body.clone()).collect()) + .unwrap_or_default() + } + + /// The headers of the messages pending on `queue`, oldest first, without removing them. + #[must_use] + pub fn headers(&self, queue: &str) -> Vec> { + self.lock() + .get(queue) + .map(|q| q.iter().map(|m| m.headers.clone()).collect()) + .unwrap_or_default() + } +} + +impl Transport for InMemoryTransport { + async fn publish(&self, queue: &str, body: &[u8]) -> Result<(), TransportError> { + self.push(queue, body, HashMap::new()); + Ok(()) + } + + async fn pop( + &self, + queue: &str, + _timeout: Duration, + ) -> Result, TransportError> { + let stored = self.lock().get_mut(queue).and_then(VecDeque::pop_front); + if stored.is_none() { + YieldOnce(false).await; + } + Ok(stored.map(|m| Delivery::new(queue, m.body).with_headers(m.headers))) + } + + async fn ack(&self, _delivery: &Delivery) -> Result<(), TransportError> { + Ok(()) + } +} + +impl HeaderPublisher for InMemoryTransport { + async fn publish_with_headers( + &self, + queue: &str, + body: &[u8], + headers: &HashMap, + ) -> Result<(), TransportError> { + self.push(queue, body, headers.clone()); + Ok(()) + } +} + +/// Pending exactly once, after scheduling its own wake-up. +struct YieldOnce(bool); + +impl Future for YieldOnce { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if self.0 { + return Poll::Ready(()); + } + self.0 = true; + cx.waker().wake_by_ref(); + Poll::Pending + } +} diff --git a/crates/babelqueue/src/poison.rs b/crates/babelqueue/src/poison.rs new file mode 100644 index 0000000..12d3a20 --- /dev/null +++ b/crates/babelqueue/src/poison.rs @@ -0,0 +1,470 @@ +//! The dead-letter record of a poison body (ADR-0035, error-handling.md section 6). +//! +//! A body that is a strict RFC 8259 JSON object without a top-level `dead_letter` member is +//! *spliced* at byte level: every original byte is kept and only the `dead_letter` member is +//! inserted, so no value is ever re-encoded (a `1e400` or a 64-bit integer stays as written, a +//! repeated member name is not collapsed). Anything else is *wrapped* as +//! `{"raw": , "raw_encoding"?: "base64", "dead_letter": ...}`: `raw` is the body as plain +//! text when it is valid UTF-8 and otherwise the standard base64 of the exact bytes with +//! `raw_encoding` `base64`. U+FFFD substitution never happens. + +use crate::codec::encode::write_dead_letter; +use crate::dlq::{FailureCause, dead_letter_block}; + +/// Builds the dead-letter record of an undecodable `body` read from `original_queue`. +/// +/// The `dead_letter` block carries reason `poison`, the given `attempts` and `cause` (what made the +/// body poison, when known). +/// +/// ``` +/// let record = babelqueue::poison_dead_letter_body(br#"{"job":"urn:x","data":{}}"#, "orders", 0, None); +/// let text = String::from_utf8(record).unwrap(); +/// assert!(text.starts_with(r#"{"job":"urn:x","data":{},"dead_letter":{"reason":"poison""#)); +/// +/// let wrapped = babelqueue::poison_dead_letter_body(b"not json", "orders", 0, None); +/// assert!(String::from_utf8(wrapped).unwrap().starts_with(r#"{"raw":"not json","dead_letter""#)); +/// ``` +#[must_use] +pub fn poison_dead_letter_body( + body: &[u8], + original_queue: &str, + attempts: u64, + cause: Option<&FailureCause>, +) -> Vec { + let block = dead_letter_block("poison", original_queue, attempts, cause); + let mut dead_letter = Vec::new(); + // The block holds only valid UTF-8 strings and integers, so this cannot fail; a minimal block + // still leaves a parseable record if it ever did. + if write_dead_letter(&mut dead_letter, &block).is_err() { + dead_letter = br#"{"reason":"poison"}"#.to_vec(); + } + build_poison_record(body, &dead_letter) +} + +fn build_poison_record(body: &[u8], dead_letter: &[u8]) -> Vec { + let mut out = Vec::with_capacity(body.len() + dead_letter.len() + 32); + if is_spliceable_object(body) { + let trimmed = trim_json_space(body); + let inner = trim_json_space(&trimmed[1..trimmed.len() - 1]); + if inner.is_empty() { + out.extend_from_slice(b"{\"dead_letter\":"); + } else { + out.extend_from_slice(&trimmed[..trimmed.len() - 1]); + out.extend_from_slice(b",\"dead_letter\":"); + } + out.extend_from_slice(dead_letter); + out.push(b'}'); + return out; + } + out.extend_from_slice(b"{\"raw\":"); + match std::str::from_utf8(body) { + Ok(text) => out.extend_from_slice(&json_string(text)), + Err(_) => { + out.extend_from_slice(&json_string(&base64_standard(body))); + out.extend_from_slice(b",\"raw_encoding\":\"base64\""); + } + } + out.extend_from_slice(b",\"dead_letter\":"); + out.extend_from_slice(dead_letter); + out.push(b'}'); + out +} + +fn json_string(text: &str) -> Vec { + // Serializing a `&str` cannot fail. + serde_json::to_vec(text).unwrap_or_else(|_| b"\"\"".to_vec()) +} + +fn is_json_space(c: u8) -> bool { + matches!(c, b' ' | b'\t' | b'\r' | b'\n') +} + +fn trim_json_space(mut bytes: &[u8]) -> &[u8] { + while let [first, rest @ ..] = bytes { + if !is_json_space(*first) { + break; + } + bytes = rest; + } + while let [rest @ .., last] = bytes { + if !is_json_space(*last) { + break; + } + bytes = rest; + } + bytes +} + +/// Standard base64 (RFC 4648 section 4) with padding. +fn base64_standard(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let b0 = u32::from(chunk[0]); + let b1 = chunk.get(1).copied().map_or(0, u32::from); + let b2 = chunk.get(2).copied().map_or(0, u32::from); + let n = (b0 << 16) | (b1 << 8) | b2; + let sextet = |shift: u32| char::from(ALPHABET[((n >> shift) & 0x3f) as usize]); + out.push(sextet(18)); + out.push(sextet(12)); + out.push(if chunk.len() > 1 { sextet(6) } else { '=' }); + out.push(if chunk.len() > 2 { sextet(0) } else { '=' }); + } + out +} + +// --------------------------------------------------------------------------------------------- +// Strict JSON object check +// --------------------------------------------------------------------------------------------- + +/// Whether `body` is a single strict RFC 8259 JSON object that is valid UTF-8, carries no unpaired +/// surrogate escape and has no top-level `dead_letter` member (ADR-0035 section 1). +/// +/// The scan is iterative, so nesting depth is bounded only by the body size: a deeply nested body +/// is still a valid object and is spliced, which a recursive parser with a depth limit could not do. +pub(crate) fn is_spliceable_object(body: &[u8]) -> bool { + if std::str::from_utf8(body).is_err() { + return false; + } + matches!(scan_strict_object(body), Some(false)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Expect { + Value, + ValueOrEnd, + KeyOrEnd, + Key, + Colon, + AfterValue, +} + +/// `Some(has_top_level_dead_letter)` when `b` is a strict JSON object; `None` otherwise. +fn scan_strict_object(b: &[u8]) -> Option { + let mut i = skip_space(b, 0); + if b.get(i) != Some(&b'{') { + return None; + } + let mut stack: Vec = Vec::new(); + let mut expect = Expect::Value; + let mut has_dead_letter = false; + loop { + i = skip_space(b, i); + let c = *b.get(i)?; + match expect { + Expect::Value | Expect::ValueOrEnd => match c { + b'{' => { + stack.push(b'{'); + i += 1; + expect = Expect::KeyOrEnd; + } + b'[' => { + stack.push(b'['); + i += 1; + expect = Expect::ValueOrEnd; + } + b']' if expect == Expect::ValueOrEnd => { + stack.pop(); + i += 1; + expect = Expect::AfterValue; + } + b'"' => { + i = scan_string(b, i, None)?; + expect = Expect::AfterValue; + } + b'-' | b'0'..=b'9' => { + i = scan_number(b, i)?; + expect = Expect::AfterValue; + } + b't' => { + i = scan_literal(b, i, b"true")?; + expect = Expect::AfterValue; + } + b'f' => { + i = scan_literal(b, i, b"false")?; + expect = Expect::AfterValue; + } + b'n' => { + i = scan_literal(b, i, b"null")?; + expect = Expect::AfterValue; + } + _ => return None, + }, + Expect::KeyOrEnd | Expect::Key => match c { + b'}' if expect == Expect::KeyOrEnd => { + stack.pop(); + i += 1; + expect = Expect::AfterValue; + } + b'"' => { + let mut key = (stack.len() == 1).then(String::new); + i = scan_string(b, i, key.as_mut())?; + if key.as_deref() == Some("dead_letter") { + has_dead_letter = true; + } + expect = Expect::Colon; + } + _ => return None, + }, + Expect::Colon => { + if c != b':' { + return None; + } + i += 1; + expect = Expect::Value; + } + Expect::AfterValue => { + let top = *stack.last()?; + match c { + b',' => { + i += 1; + expect = if top == b'{' { + Expect::Key + } else { + Expect::Value + }; + } + b'}' if top == b'{' => { + stack.pop(); + i += 1; + } + b']' if top == b'[' => { + stack.pop(); + i += 1; + } + _ => return None, + } + } + } + if stack.is_empty() { + break; + } + } + (skip_space(b, i) == b.len()).then_some(has_dead_letter) +} + +fn skip_space(b: &[u8], mut i: usize) -> usize { + while b.get(i).is_some_and(|c| is_json_space(*c)) { + i += 1; + } + i +} + +fn scan_literal(b: &[u8], i: usize, literal: &[u8]) -> Option { + b.get(i..i + literal.len()) + .is_some_and(|s| s == literal) + .then_some(i + literal.len()) +} + +/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`, returning the index past the number. +fn scan_number(b: &[u8], mut i: usize) -> Option { + let digits = |b: &[u8], mut i: usize| { + let start = i; + while b.get(i).is_some_and(u8::is_ascii_digit) { + i += 1; + } + (i > start).then_some(i) + }; + if b.get(i) == Some(&b'-') { + i += 1; + } + match b.get(i)? { + b'0' => i += 1, + b'1'..=b'9' => i = digits(b, i)?, + _ => return None, + } + if b.get(i) == Some(&b'.') { + i = digits(b, i + 1)?; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + i = digits(b, i)?; + } + Some(i) +} + +/// Scans the string literal starting at `b[start]` (a quote) and returns the index past its closing +/// quote. `None` for a control character, a bad escape or an unpaired surrogate escape. When `key` +/// is given the unescaped text is collected into it. +fn scan_string(b: &[u8], start: usize, mut key: Option<&mut String>) -> Option { + let mut i = start + 1; + loop { + let c = *b.get(i)?; + match c { + b'"' => return Some(i + 1), + 0x00..=0x1f => return None, + b'\\' => { + let e = *b.get(i + 1)?; + let simple = match e { + b'"' => Some('"'), + b'\\' => Some('\\'), + b'/' => Some('/'), + b'b' => Some('\u{8}'), + b'f' => Some('\u{c}'), + b'n' => Some('\n'), + b'r' => Some('\r'), + b't' => Some('\t'), + b'u' => None, + _ => return None, + }; + if let Some(ch) = simple { + if let Some(k) = key.as_deref_mut() { + k.push(ch); + } + i += 2; + continue; + } + let cp = hex4(b, i + 2)?; + i += 6; + let ch = match cp { + 0xD800..=0xDBFF => { + if b.get(i) != Some(&b'\\') || b.get(i + 1) != Some(&b'u') { + return None; + } + let low = hex4(b, i + 2)?; + if !(0xDC00..=0xDFFF).contains(&low) { + return None; + } + i += 6; + char::from_u32(0x1_0000 + ((cp - 0xD800) << 10) + (low - 0xDC00)) + } + 0xDC00..=0xDFFF => return None, + _ => char::from_u32(cp), + }; + if let (Some(k), Some(ch)) = (key.as_deref_mut(), ch) { + k.push(ch); + } + } + _ => { + // The body is valid UTF-8, so a multi-byte sequence is copied whole. + let len = utf8_len(c); + if let Some(k) = key.as_deref_mut() { + k.push_str(std::str::from_utf8(b.get(i..i + len)?).ok()?); + } + i += len; + } + } + } +} + +fn utf8_len(first: u8) -> usize { + match first { + 0xF0..=0xFF => 4, + 0xE0..=0xEF => 3, + 0xC0..=0xDF => 2, + _ => 1, + } +} + +fn hex4(b: &[u8], at: usize) -> Option { + let digits = b.get(at..at + 4)?; + digits.iter().try_fold(0u32, |acc, c| { + char::from(*c).to_digit(16).map(|d| (acc << 4) | d) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(body: &[u8]) -> String { + String::from_utf8(poison_dead_letter_body(body, "orders", 2, None)).unwrap() + } + + #[test] + fn spliceable_objects() { + for ok in [ + r"{}", + r#" {"a":1} "#, + r#"{"a":[1,2,{"b":null}],"c":"é😀"}"#, + r#"{"n":1e400,"m":-0.0e+5}"#, + r#"{"a":1,"a":2}"#, + ] { + assert!(is_spliceable_object(ok.as_bytes()), "{ok}"); + } + } + + #[test] + fn rejected_bodies() { + for bad in [ + "", + "[]", + "null", + r#"{"a":1,}"#, + r#"{"a":01}"#, + r#"{"a":NaN}"#, + r#"{"a":1} x"#, + "\u{feff}{}", + r#"{"a":"\ud800"}"#, + r#"{"a":"\udc00"}"#, + r#"{"a":"\ud800A"}"#, + "{\"a\":\"tab\tinside\"}", + r#"{"a":[1}"#, + r#"{"a":{]}"#, + r#"{"dead_letter":1}"#, + r#"{"dead_letter":1}"#, + r#"{"a":.5}"#, + r#"{"a":1.}"#, + r#"{"a":"\x"}"#, + ] { + assert!(!is_spliceable_object(bad.as_bytes()), "{bad:?}"); + } + assert!(!is_spliceable_object(b"{\"a\":\"\xff\"}")); + } + + #[test] + fn a_nested_dead_letter_key_does_not_block_a_splice() { + assert!(is_spliceable_object(br#"{"a":{"dead_letter":1}}"#)); + } + + #[test] + fn deep_nesting_is_spliced_without_recursion() { + let mut body = String::from("{\"a\":"); + body.push_str(&"[".repeat(100_000)); + body.push_str(&"]".repeat(100_000)); + body.push('}'); + assert!(is_spliceable_object(body.as_bytes())); + } + + #[test] + fn splice_keeps_every_byte_and_appends_the_block() { + let out = record(br#"{"n":1e400,"n":2}"#); + assert!( + out.starts_with(r#"{"n":1e400,"n":2,"dead_letter":{"reason":"poison","error":null"#) + ); + assert!(out.ends_with(r#""original_queue":"orders","attempts":2,"lang":"rust"}}"#)); + } + + #[test] + fn an_empty_object_gets_only_the_block() { + assert!(record(b" { } ").starts_with(r#"{"dead_letter":{"reason":"poison""#)); + } + + #[test] + fn invalid_utf8_is_base64_never_replacement() { + let out = record(b"{\"a\":\"\xff\xfe\"}"); + assert!(out.contains(r#""raw":"eyJhIjoi//4ifQ==","raw_encoding":"base64","dead_letter""#)); + assert!(!out.contains('\u{fffd}')); + } + + #[test] + fn base64_padding() { + assert_eq!(base64_standard(b""), ""); + assert_eq!(base64_standard(b"f"), "Zg=="); + assert_eq!(base64_standard(b"fo"), "Zm8="); + assert_eq!(base64_standard(b"foo"), "Zm9v"); + assert_eq!(base64_standard(b"foob"), "Zm9vYg=="); + } + + #[test] + fn wrapper_for_non_objects_and_for_an_existing_dead_letter_key() { + assert!(record(b"[1]").starts_with(r#"{"raw":"[1]","dead_letter""#)); + assert!( + record(br#"{"dead_letter":1}"#) + .starts_with(r#"{"raw":"{\"dead_letter\":1}","dead_letter""#) + ); + } +} diff --git a/crates/babelqueue/src/results.rs b/crates/babelqueue/src/results.rs new file mode 100644 index 0000000..438cf92 --- /dev/null +++ b/crates/babelqueue/src/results.rs @@ -0,0 +1,517 @@ +//! The conformance `results.json` model (ADR-0032 section 2). +//! +//! A conformance runner records the outcome of every case it ran with [`Results::record`] and +//! writes the file with [`Results::write`]. The shape follows `schema/results.schema.json` of the +//! vendored suite; [`Results::schema_violations`] re-checks the invariants of that schema in code, +//! so the file is validated without a JSON Schema library. +//! +//! This is conformance tooling, not part of the messaging API: the runners of this workspace use +//! it, and an application has no reason to. + +use std::collections::BTreeMap; +use std::fs; +use std::io; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde_json::{Map, Value, json}; + +/// The outcome of one conformance case. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// The case ran and met its expectation. + Pass, + /// The case ran and did not meet its expectation. + Fail, + /// The case was not run; only legal with a reason that cites an ADR. + Skip, +} + +impl Status { + fn as_str(self) -> &'static str { + match self { + Self::Pass => "pass", + Self::Fail => "fail", + Self::Skip => "skip", + } + } + + fn parse(text: &str) -> Option { + match text { + "pass" => Some(Self::Pass), + "fail" => Some(Self::Fail), + "skip" => Some(Self::Skip), + _ => None, + } + } +} + +/// One case result: a status and, for a failure or a skip, the reason. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CaseResult { + /// The outcome. + pub status: Status, + /// Why the case failed or was skipped. A skip must cite an `ADR-NNNN`. + pub reason: Option, +} + +impl CaseResult { + /// A passing case. + #[must_use] + pub fn pass() -> Self { + Self { + status: Status::Pass, + reason: None, + } + } + + /// A failing case with its reason. + #[must_use] + pub fn fail(reason: impl Into) -> Self { + Self { + status: Status::Fail, + reason: Some(reason.into()), + } + } + + /// A skipped case; `reason` must cite the authorising ADR. + #[must_use] + pub fn skip(reason: impl Into) -> Self { + Self { + status: Status::Skip, + reason: Some(reason.into()), + } + } +} + +/// The results of running one package against the conformance suite. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Results { + /// Package identity, for example `babelqueue-rust/babelqueue`. + pub sdk: String, + /// The version of the package under test. + pub version: String, + /// The suite version the run was made against (the value of `CONFORMANCE_VERSION`). + pub conformance_version: String, + /// RFC 3339 timestamp of the run. + pub generated_at: String, + /// Every binding the package carries, derived from the workspace's transport crates. + pub bindings: Vec, + /// Section name, then case id, then result. + pub sections: BTreeMap>, +} + +const BINDINGS: [&str; 8] = [ + "redis", "amqp", "sqs", "asb", "pulsar", "kafka", "artemis", "otel", +]; + +impl Results { + /// An empty result set stamped with the current time. + #[must_use] + pub fn new( + sdk: impl Into, + version: impl Into, + conformance_version: impl Into, + ) -> Self { + Self { + sdk: sdk.into(), + version: version.into(), + conformance_version: conformance_version.into(), + generated_at: rfc3339_utc(SystemTime::now()), + bindings: Vec::new(), + sections: BTreeMap::new(), + } + } + + /// Records the result of one case, replacing an earlier one with the same id. + pub fn record(&mut self, section: &str, case_id: &str, result: CaseResult) { + self.sections + .entry(section.to_owned()) + .or_default() + .insert(case_id.to_owned(), result); + } + + /// Adds the sections and bindings of `other` into this set (a later runner of the same + /// package, for example a transport crate). Cases of `other` win on a clash. + pub fn merge(&mut self, other: Self) { + for binding in other.bindings { + if !self.bindings.contains(&binding) { + self.bindings.push(binding); + } + } + self.bindings.sort(); + for (section, cases) in other.sections { + self.sections.entry(section).or_default().extend(cases); + } + } + + /// The JSON document, shaped like `schema/results.schema.json`. + #[must_use] + pub fn to_json(&self) -> Value { + let mut sections = Map::new(); + for (section, cases) in &self.sections { + let mut out = Map::new(); + for (id, result) in cases { + let mut entry = Map::new(); + entry.insert("status".to_owned(), json!(result.status.as_str())); + if let Some(reason) = &result.reason { + entry.insert("reason".to_owned(), json!(reason)); + } + out.insert(id.clone(), Value::Object(entry)); + } + sections.insert(section.clone(), Value::Object(out)); + } + json!({ + "sdk": self.sdk, + "version": self.version, + "conformance_version": self.conformance_version, + "generated_at": self.generated_at, + "bindings": self.bindings, + "sections": sections, + }) + } + + /// Reads a results document back. + /// + /// # Errors + /// + /// A description of the first member that is missing or has the wrong type. + pub fn from_json(doc: &Value) -> Result { + let text = |key: &str| -> Result { + doc.get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("{key} must be a string")) + }; + let bindings = doc + .get("bindings") + .and_then(Value::as_array) + .ok_or("bindings must be an array")? + .iter() + .map(|b| { + b.as_str() + .map(str::to_owned) + .ok_or("binding must be a string") + }) + .collect::, _>>()?; + let mut results = Self { + sdk: text("sdk")?, + version: text("version")?, + conformance_version: text("conformance_version")?, + generated_at: text("generated_at")?, + bindings, + sections: BTreeMap::new(), + }; + let sections = doc + .get("sections") + .and_then(Value::as_object) + .ok_or("sections must be an object")?; + for (section, cases) in sections { + let cases = cases + .as_object() + .ok_or_else(|| format!("section {section} must be an object"))?; + for (id, case) in cases { + let status = case + .get("status") + .and_then(Value::as_str) + .and_then(Status::parse) + .ok_or_else(|| format!("{section}/{id}: status must be pass, fail or skip"))?; + let reason = case + .get("reason") + .and_then(Value::as_str) + .map(str::to_owned); + results.record(section, id, CaseResult { status, reason }); + } + } + Ok(results) + } + + /// Reads `path`, or `None` when it does not exist. + /// + /// # Errors + /// + /// An I/O error, or invalid JSON or an invalid shape as [`io::ErrorKind::InvalidData`]. + pub fn read(path: &Path) -> io::Result> { + let raw = match fs::read(path) { + Ok(raw) => raw, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + let invalid = |e: String| io::Error::new(io::ErrorKind::InvalidData, e); + let doc: Value = serde_json::from_slice(&raw).map_err(|e| invalid(e.to_string()))?; + Self::from_json(&doc).map(Some).map_err(invalid) + } + + /// Writes the pretty-printed document to `path`, creating parent directories. + /// + /// # Errors + /// + /// Any I/O error. + pub fn write(&self, path: &Path) -> io::Result<()> { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + let mut text = serde_json::to_string_pretty(&self.to_json()).map_err(io::Error::other)?; + text.push('\n'); + fs::write(path, text) + } + + /// Re-checks the invariants of `schema/results.schema.json`: the member shapes and patterns, the + /// `bindings` enumeration and uniqueness, the status enumeration, and that a `skip` carries a + /// reason citing an `ADR-NNNN`. An empty list means the document conforms. + #[must_use] + pub fn schema_violations(&self) -> Vec { + let mut v = Vec::new(); + if self.sdk.is_empty() { + v.push("sdk must not be empty".to_owned()); + } + if self.version.is_empty() { + v.push("version must not be empty".to_owned()); + } + if !is_semver_triple(&self.conformance_version) { + v.push(format!( + "conformance_version {:?} does not match ^[0-9]+\\.[0-9]+\\.[0-9]+$", + self.conformance_version + )); + } + if !is_rfc3339(&self.generated_at) { + v.push(format!( + "generated_at {:?} is not an RFC 3339 timestamp", + self.generated_at + )); + } + for (i, binding) in self.bindings.iter().enumerate() { + if !BINDINGS.contains(&binding.as_str()) { + v.push(format!("bindings: {binding:?} is not a known binding")); + } + if self.bindings[..i].contains(binding) { + v.push(format!("bindings: {binding:?} is listed twice")); + } + } + for (section, cases) in &self.sections { + for (id, result) in cases { + let reason = result.reason.as_deref(); + if reason.is_some_and(str::is_empty) { + v.push(format!("{section}/{id}: reason must not be empty")); + } + if result.status == Status::Skip && !reason.is_some_and(cites_adr) { + v.push(format!( + "{section}/{id}: a skip needs a reason citing ADR-NNNN" + )); + } + } + } + v + } +} + +fn is_semver_triple(text: &str) -> bool { + let parts: Vec<&str> = text.split('.').collect(); + parts.len() == 3 + && parts + .iter() + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) +} + +fn cites_adr(reason: &str) -> bool { + reason.match_indices("ADR-").any(|(at, _)| { + reason + .as_bytes() + .get(at + 4..at + 8) + .is_some_and(|d| d.iter().all(u8::is_ascii_digit)) + }) +} + +/// `YYYY-MM-DDThh:mm:ss(.f+)?(Z|+hh:mm|-hh:mm)`, the pattern the schema pins. +fn is_rfc3339(text: &str) -> bool { + let b = text.as_bytes(); + let digit = |i: usize| b.get(i).is_some_and(u8::is_ascii_digit); + let shape = b"dddd-dd-ddTdd:dd:dd"; + let head_ok = shape.iter().enumerate().all(|(i, s)| match s { + b'd' => digit(i), + other => b.get(i) == Some(other) || (*other == b'T' && b.get(i) == Some(&b't')), + }); + if !head_ok { + return false; + } + let mut i = 19; + if b.get(i) == Some(&b'.') { + i += 1; + let start = i; + while digit(i) { + i += 1; + } + if i == start { + return false; + } + } + match b.get(i) { + Some(b'Z' | b'z') => i + 1 == b.len(), + Some(b'+' | b'-') => { + b.len() == i + 6 + && digit(i + 1) + && digit(i + 2) + && b[i + 3] == b':' + && digit(i + 4) + && digit(i + 5) + } + _ => false, + } +} + +/// The case ids of a manifest section, by the rule in `results.schema.json`. +/// +/// A section's `cases` array gives one case per element, identified by its `name`, else by +/// `
#<0-based index>` (the top-level `cases` array is the section named `cases`). A +/// sub-key object with its own `cases` array yields `/` (or `/`); +/// any other object sub-key is a single case keyed by the sub-key. `description`, `schema` and +/// `cases` themselves are never cases. +#[must_use] +pub fn manifest_case_ids(manifest: &Value, section: &str) -> Vec { + let body = if section == "cases" { + json!({ "cases": manifest.get("cases").cloned().unwrap_or(Value::Null) }) + } else { + manifest.get(section).cloned().unwrap_or(Value::Null) + }; + let name_of = |case: &Value| { + case.get("name") + .and_then(Value::as_str) + .filter(|n| !n.is_empty()) + .map(str::to_owned) + }; + let mut ids = Vec::new(); + if let Some(cases) = body.get("cases").and_then(Value::as_array) { + for (i, case) in cases.iter().enumerate() { + ids.push(name_of(case).unwrap_or_else(|| format!("{section}#{i}"))); + } + } + if let Some(object) = body.as_object() { + let mut keys: Vec<&String> = object.keys().collect(); + keys.sort(); + for key in keys { + if matches!(key.as_str(), "description" | "schema" | "cases") { + continue; + } + let Some(sub) = object[key].as_object() else { + continue; + }; + if let Some(cases) = sub.get("cases").and_then(Value::as_array) { + for (i, case) in cases.iter().enumerate() { + ids.push(format!( + "{key}/{}", + name_of(case).unwrap_or_else(|| i.to_string()) + )); + } + } else { + ids.push(key.clone()); + } + } + } + ids +} + +/// Formats `time` as an RFC 3339 UTC timestamp with second precision (`2026-12-04T09:30:00Z`). +#[must_use] +pub fn rfc3339_utc(time: SystemTime) -> String { + let secs = time + .duration_since(UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX / 2)); + let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (year, month, day) = civil_from_days(days); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day), after Howard Hinnant's +/// `civil_from_days`. +fn civil_from_days(days: i64) -> (i64, i64, i64) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + (year, month, day) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn timestamps_are_rfc3339() { + assert_eq!(rfc3339_utc(UNIX_EPOCH), "1970-01-01T00:00:00Z"); + assert_eq!( + rfc3339_utc(UNIX_EPOCH + Duration::from_secs(1_749_132_727)), + "2025-06-05T14:12:07Z" + ); + assert_eq!( + rfc3339_utc(UNIX_EPOCH + Duration::from_secs(951_782_400)), + "2000-02-29T00:00:00Z" + ); + assert!(is_rfc3339(&rfc3339_utc(SystemTime::now()))); + assert!(is_rfc3339("2026-12-04T09:30:00.123+03:00")); + assert!(!is_rfc3339("2026-12-04 09:30:00Z")); + assert!(!is_rfc3339("2026-12-04T09:30:00")); + } + + #[test] + fn a_skip_must_cite_an_adr() { + let mut r = Results::new("sdk", "1.0.0", "1.11.0"); + r.record("s", "a", CaseResult::skip("no reason given")); + r.record("s", "b", CaseResult::skip("not carried (ADR-0041)")); + r.record("s", "c", CaseResult::pass()); + let violations = r.schema_violations(); + assert_eq!(violations.len(), 1, "{violations:?}"); + assert!(violations[0].contains("s/a")); + } + + #[test] + fn unknown_and_repeated_bindings_are_violations() { + let mut r = Results::new("sdk", "1.0.0", "1.11"); + r.bindings = vec!["redis".into(), "redis".into(), "nats".into()]; + assert_eq!(r.schema_violations().len(), 3); + } + + #[test] + fn json_round_trips_and_merges() { + let mut a = Results::new("sdk", "dev", "1.11.0"); + a.record("cases", "x", CaseResult::pass()); + let mut b = Results::new("sdk", "dev", "1.11.0"); + b.bindings = vec!["redis".into()]; + b.record("redis", "y", CaseResult::fail("boom")); + a.merge(b); + let back = Results::from_json(&a.to_json()).unwrap(); + assert_eq!(back, a); + assert_eq!(back.bindings, ["redis"]); + assert_eq!(back.sections.len(), 2); + } + + #[test] + fn case_ids_follow_the_schema_rule() { + let manifest = json!({ + "cases": [{"name": "a"}, {}], + "idem": { + "description": "d", + "dedup_key": {"k": 1}, + "sequences": {"cases": [{"name": "s1"}, {}]}, + "schema": {"type": "object"}, + "cases": [{"name": "n"}] + } + }); + assert_eq!(manifest_case_ids(&manifest, "cases"), ["a", "cases#1"]); + assert_eq!( + manifest_case_ids(&manifest, "idem"), + ["n", "dedup_key", "sequences/s1", "sequences/1"] + ); + } +} diff --git a/crates/babelqueue/src/schema.rs b/crates/babelqueue/src/schema.rs new file mode 100644 index 0000000..d4477be --- /dev/null +++ b/crates/babelqueue/src/schema.rs @@ -0,0 +1,551 @@ +//! Optional, dependency-free per-URN payload validation (ADR-0024). +//! +//! A [`Provider`] supplies a JSON Schema for a message URN and the message's `data` is validated +//! against it. It is opt-in: a URN with no registered schema is never validated. +//! +//! The validator is an intentionally small subset of JSON Schema (draft-07), enough to describe a +//! message's `data`: `type` (a name or a union array), `required`, `properties`, +//! `additionalProperties` (boolean), `items`, `enum`, `const`, `minLength`, `maxLength` and +//! `minimum`. A keyword outside the subset never changes a verdict (it is evaluated as if absent), +//! but parsing a schema reports one [`SchemaWarning`] per unsupported keyword occurrence +//! ([`Schema::warnings`]), so a silently unenforced constraint is never a surprise. The `jsonschema` +//! crate is deliberately not used (GR-7). + +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; + +use serde_json::{Number, Value}; + +use crate::app::{HandlerError, HandlerFuture}; +use crate::envelope::Envelope; +use crate::transport::Delivery; + +/// One unsupported keyword found when a schema was parsed. The schema is evaluated as if the +/// keyword were absent, so a warning never changes a verdict. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SchemaWarning { + /// The RFC 6901 JSON Pointer, within the schema document, of the schema object carrying the + /// keyword: `""` for the root, then `/properties/`, `/items`, `/additionalProperties` + /// (property names escaped `~` to `~0`, `/` to `~1`). + pub pointer: String, + /// The unsupported keyword, for example `pattern`. + pub keyword: String, +} + +impl fmt::Display for SchemaWarning { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "schema: unsupported keyword {:?} at {:?} is ignored", + self.keyword, self.pointer + ) + } +} + +/// A schema document that could not be parsed. +#[derive(Debug)] +pub enum SchemaError { + /// The document is not valid JSON. + Json(serde_json::Error), + /// The document is valid JSON but its root is not an object. + NotAnObject, +} + +impl fmt::Display for SchemaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Json(e) => write!(f, "schema: parse: {e}"), + Self::NotAnObject => f.write_str("schema: the document root must be a JSON object"), + } + } +} + +impl Error for SchemaError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Json(e) => Some(e), + Self::NotAnObject => None, + } + } +} + +const TYPE_NAMES: [&str; 7] = [ + "object", "array", "string", "integer", "number", "boolean", "null", +]; + +const SUPPORTED: [&str; 10] = [ + "type", + "required", + "properties", + "additionalProperties", + "items", + "enum", + "const", + "minLength", + "maxLength", + "minimum", +]; + +const ANNOTATION: [&str; 7] = [ + "$schema", + "$id", + "title", + "description", + "examples", + "default", + "$comment", +]; + +/// A parsed (subset) JSON Schema node. +#[derive(Debug, Clone, Default)] +pub struct Schema { + types: Vec, + required: Vec, + properties: BTreeMap, + additional_properties: Option, + items: Option>, + enumeration: Option>, + constant: Option, + min_length: Option, + max_length: Option, + minimum: Option, + warnings: Vec, +} + +impl Schema { + /// Parses a (subset) JSON Schema document. Every unsupported keyword is reported once per + /// occurrence through [`Schema::warnings`]; the annotation keywords (`$schema`, `$id`, `title`, + /// `description`, `examples`, `default`, `$comment`) and every `x-*` extension keyword never warn. + /// + /// # Errors + /// + /// [`SchemaError`] when the document is not a JSON object. + /// + /// ``` + /// use babelqueue::Schema; + /// + /// let schema = Schema::parse(br#"{"type":"object","required":["order_id"],"properties":{"order_id":{"type":"integer","minimum":1}}}"#)?; + /// assert!(schema.validate(&serde_json::json!({"order_id": 7})).is_empty()); + /// assert!(!schema.validate(&serde_json::json!({})).is_empty()); + /// # Ok::<(), babelqueue::SchemaError>(()) + /// ``` + pub fn parse(raw: &[u8]) -> Result { + let doc: Value = serde_json::from_slice(raw).map_err(SchemaError::Json)?; + let Value::Object(map) = &doc else { + return Err(SchemaError::NotAnObject); + }; + let mut schema = Self::from_map(map); + collect_warnings(map, "", &mut schema.warnings); + Ok(schema) + } + + /// The unsupported-keyword warnings [`Schema::parse`] produced for the document, in a + /// deterministic order. Empty for a schema inside the supported subset. + #[must_use] + pub fn warnings(&self) -> &[SchemaWarning] { + &self.warnings + } + + fn from_map(map: &serde_json::Map) -> Self { + let mut s = Self::default(); + match map.get("type") { + Some(Value::String(t)) => s.types.push(t.clone()), + Some(Value::Array(list)) => { + s.types + .extend(list.iter().filter_map(Value::as_str).map(str::to_owned)); + } + _ => {} + } + if let Some(Value::Array(req)) = map.get("required") { + s.required + .extend(req.iter().filter_map(Value::as_str).map(str::to_owned)); + } + if let Some(Value::Object(props)) = map.get("properties") { + for (name, sub) in props { + if let Value::Object(sub) = sub { + s.properties.insert(name.clone(), Self::from_map(sub)); + } + } + } + if let Some(Value::Bool(b)) = map.get("additionalProperties") { + s.additional_properties = Some(*b); + } + if let Some(Value::Object(items)) = map.get("items") { + s.items = Some(Box::new(Self::from_map(items))); + } + if let Some(Value::Array(values)) = map.get("enum") { + s.enumeration = Some(values.clone()); + } + if let Some(c) = map.get("const") { + s.constant = Some(c.clone()); + } + // A fractional length bound is truncated toward zero; the cast saturates. + s.min_length = map.get("minLength").and_then(length_bound); + s.max_length = map.get("maxLength").and_then(length_bound); + s.minimum = map.get("minimum").and_then(Value::as_f64); + s + } + + /// Checks `value` against the schema and returns the sorted, human-readable violations. An + /// empty result means the value is valid. + #[must_use] + pub fn validate(&self, value: &Value) -> Vec { + let mut errors = Vec::new(); + self.check("", value, &mut errors); + errors.sort(); + errors + } + + fn check(&self, path: &str, value: &Value, errors: &mut Vec) { + let at = |msg: String| { + if path.is_empty() { + msg + } else { + format!("{path}: {msg}") + } + }; + if let Some(c) = &self.constant { + if !json_equal(value, c) { + errors.push(at(format!("must equal const {c}"))); + } + } + if let Some(values) = &self.enumeration { + if !values.iter().any(|e| json_equal(value, e)) { + errors.push(at("value is not one of the allowed enum values".to_owned())); + } + } + let types: Vec<&str> = self + .types + .iter() + .map(String::as_str) + .filter(|t| TYPE_NAMES.contains(t)) + .collect(); + if types.is_empty() { + return; + } + let Some(matched) = types.iter().copied().find(|t| matches_type(t, value)) else { + errors.push(at(if let [only] = types.as_slice() { + type_message(only).to_owned() + } else { + format!("must be one of the types {}", types.join(", ")) + })); + return; + }; + match matched { + "object" => self.check_object(path, value, errors, &at), + "array" => self.check_array(path, value, errors), + "string" => { + // Lengths count Unicode code points: not UTF-8 bytes, UTF-16 units or grapheme + // clusters (the cross-SDK rule). + let n = value.as_str().map_or(0, |s| s.chars().count()); + let n = i64::try_from(n).unwrap_or(i64::MAX); + if let Some(min) = self.min_length { + if n < min { + errors.push(at(format!("must be at least {min} characters"))); + } + } + if let Some(max) = self.max_length { + if n > max { + errors.push(at(format!("must be at most {max} characters"))); + } + } + } + "integer" | "number" => { + if let (Some(min), Some(f)) = (self.minimum, value.as_f64()) { + if f < min { + errors.push(at(format!("must be >= {min}"))); + } + } + } + _ => {} + } + } + + fn check_object( + &self, + path: &str, + value: &Value, + errors: &mut Vec, + at: &dyn Fn(String) -> String, + ) { + let Value::Object(obj) = value else { + errors.push(at("must be an object".to_owned())); + return; + }; + for req in &self.required { + if !obj.contains_key(req) { + errors.push(at(format!("missing required property {req:?}"))); + } + } + for (key, v) in obj { + if let Some(sub) = self.properties.get(key) { + sub.check(&join(path, key), v, errors); + } else if self.additional_properties == Some(false) { + errors.push(at(format!("additional property {key:?} is not allowed"))); + } + } + } + + fn check_array(&self, path: &str, value: &Value, errors: &mut Vec) { + let Value::Array(list) = value else { + errors.push(if path.is_empty() { + "must be an array".to_owned() + } else { + format!("{path}: must be an array") + }); + return; + }; + if let Some(items) = &self.items { + for (i, item) in list.iter().enumerate() { + items.check(&format!("{path}[{i}]"), item, errors); + } + } + } +} + +fn length_bound(v: &Value) -> Option { + #[allow(clippy::cast_possible_truncation)] + v.as_f64().filter(|f| f.is_finite()).map(|f| f as i64) +} + +fn join(path: &str, key: &str) -> String { + if path.is_empty() { + key.to_owned() + } else { + format!("{path}.{key}") + } +} + +fn type_message(name: &str) -> &'static str { + match name { + "object" => "must be an object", + "array" => "must be an array", + "string" => "must be a string", + "integer" => "must be an integer", + "number" => "must be a number", + "boolean" => "must be a boolean", + _ => "must be null", + } +} + +fn matches_type(name: &str, value: &Value) -> bool { + match name { + "object" => value.is_object(), + "array" => value.is_array(), + "string" => value.is_string(), + "integer" => matches!(value, Value::Number(n) if is_integral(n)), + "number" => value.is_number(), + "boolean" => value.is_boolean(), + "null" => value.is_null(), + _ => false, + } +} + +/// A number whose mathematical value is integral: `1.0`, `1e0` and `1e2` are integers, `1.5` is not +/// (draft-07). +fn is_integral(n: &Number) -> bool { + n.is_i64() + || n.is_u64() + || n.as_f64() + .is_some_and(|f| f.is_finite() && f.fract() == 0.0) +} + +/// A number as either an exact integer or a non-integral float, so `1`, `1.0` and `1e0` compare +/// equal by mathematical value. +#[derive(PartialEq)] +enum Exact { + Int(i128), + Frac(f64), +} + +fn exact(n: &Number) -> Exact { + if let Some(i) = n.as_i64() { + return Exact::Int(i128::from(i)); + } + if let Some(u) = n.as_u64() { + return Exact::Int(i128::from(u)); + } + let f = n.as_f64().unwrap_or(f64::NAN); + // |f| < 1e38 fits an i128, and an integral f64 converts exactly. + #[allow(clippy::cast_possible_truncation)] + if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e38 { + Exact::Int(f as i128) + } else { + Exact::Frac(f) + } +} + +/// Equality as `const` and `enum` require: numbers by mathematical value, recursively inside arrays +/// (element by element, in order) and objects (same key set, key order irrelevant). A boolean +/// never equals a number, a string never equals a number and `null` equals only `null`. +fn json_equal(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(x), Value::Number(y)) => exact(x) == exact(y), + (Value::Array(x), Value::Array(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(p, q)| json_equal(p, q)) + } + (Value::Object(x), Value::Object(y)) => { + x.len() == y.len() + && x.iter() + .all(|(k, p)| y.get(k).is_some_and(|q| json_equal(p, q))) + } + _ => a == b, + } +} + +/// Walks the schema document the way the conformance suite pins it: only into the values of +/// `properties`, `items` and `additionalProperties` (each when a JSON object), and never into the +/// value of an unsupported keyword. +fn collect_warnings( + map: &serde_json::Map, + pointer: &str, + out: &mut Vec, +) { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + for k in keys { + if SUPPORTED.contains(&k.as_str()) + || ANNOTATION.contains(&k.as_str()) + || k.starts_with("x-") + { + continue; + } + out.push(SchemaWarning { + pointer: pointer.to_owned(), + keyword: k.clone(), + }); + } + if let Some(Value::Object(props)) = map.get("properties") { + let mut names: Vec<&String> = props.keys().collect(); + names.sort(); + for name in names { + if let Some(Value::Object(sub)) = props.get(name) { + let escaped = name.replace('~', "~0").replace('/', "~1"); + collect_warnings(sub, &format!("{pointer}/properties/{escaped}"), out); + } + } + } + if let Some(Value::Object(items)) = map.get("items") { + collect_warnings(items, &format!("{pointer}/items"), out); + } + if let Some(Value::Object(extra)) = map.get("additionalProperties") { + collect_warnings(extra, &format!("{pointer}/additionalProperties"), out); + } +} + +// --------------------------------------------------------------------------------------------- +// Providers and the handler decorator +// --------------------------------------------------------------------------------------------- + +/// A source of per-URN data schemas. [`MapProvider`] is the in-memory reference; a production +/// provider (a registry client, an embedded bundle) implements the same single method. +pub trait Provider: Send + Sync { + /// The schema registered for `urn`, or `None` when it has none (validation is then skipped). + fn schema(&self, urn: &str) -> Option>; +} + +/// An in-memory [`Provider`]. It is read-only after construction. +#[derive(Debug, Clone, Default)] +pub struct MapProvider { + schemas: BTreeMap>, +} + +impl MapProvider { + /// An empty provider. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Registers the raw JSON Schema of `urn`, replacing an earlier one. + /// + /// # Errors + /// + /// [`SchemaError`] when `raw` is not a JSON object. + pub fn with_schema(mut self, urn: impl Into, raw: &[u8]) -> Result { + self.schemas + .insert(urn.into(), Arc::new(Schema::parse(raw)?)); + Ok(self) + } +} + +impl Provider for MapProvider { + fn schema(&self, urn: &str) -> Option> { + self.schemas.get(urn).cloned() + } +} + +/// The message `data` does not match the schema registered for its URN. +#[derive(Debug)] +pub struct InvalidPayload { + /// The URN whose schema was violated. + pub urn: String, + /// The violations, sorted. + pub violations: Vec, +} + +impl fmt::Display for InvalidPayload { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "babelqueue/schema: message data does not match its URN schema for {:?}: {}", + self.urn, + self.violations.join("; ") + ) + } +} + +impl Error for InvalidPayload {} + +/// The producer-side guard: validates `data` against the schema registered for `urn`. It returns +/// `Ok` when the data is valid or when no schema is registered (opt-in). +/// +/// # Errors +/// +/// [`InvalidPayload`] listing the violations. +pub fn check(provider: &dyn Provider, urn: &str, data: &Value) -> Result<(), InvalidPayload> { + let Some(schema) = provider.schema(urn) else { + return Ok(()); + }; + let violations = schema.validate(data); + if violations.is_empty() { + Ok(()) + } else { + Err(InvalidPayload { + urn: urn.to_owned(), + violations, + }) + } +} + +/// Decorates `handler` to validate each message's `data` against its URN schema before the handler +/// runs (a consumer-side safety net). Valid data, or no schema for the URN, runs the handler +/// unchanged; invalid data returns [`InvalidPayload`], so the message takes the retry and +/// dead-letter path. Because invalid data will not become valid on retry it exhausts its attempts +/// and is dead-lettered: prefer [`check`] on the producer side to keep it out of the queue. +pub fn wrap( + provider: Arc

, + handler: F, +) -> impl Fn(Arc, Arc) -> HandlerFuture + Send + Sync + 'static +where + P: Provider + 'static, + F: Fn(Arc, Arc) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let handler = Arc::new(handler); + move |env: Arc, delivery: Arc| -> Pin + Send>> { + let provider = Arc::clone(&provider); + let handler = Arc::clone(&handler); + Box::pin(async move { + if provider.schema(env.urn()).is_some() { + let data: Value = env.data().map_err(HandlerError::from)?; + check(&*provider, env.urn(), &data).map_err(HandlerError::from)?; + } + handler(env, delivery).await + }) + } +} diff --git a/crates/babelqueue/src/transport.rs b/crates/babelqueue/src/transport.rs new file mode 100644 index 0000000..8800f8f --- /dev/null +++ b/crates/babelqueue/src/transport.rs @@ -0,0 +1,253 @@ +//! The broker contract the [`App`](crate::App) runtime talks to. +//! +//! [`Transport`] is the minimal `publish` / `pop` / `ack` triple. Optional capabilities +//! ([`HeaderPublisher`], [`Releaser`], [`DeadLetterSettler`]) are separate traits: a transport that +//! has one opts in with the matching `App::with_*` builder, so the choice is made by what the +//! transport offers and is checked at compile time. +//! +//! The traits use native `async fn` in traits and name the `Send` bound on the returned future +//! (`-> impl Future + Send`), so no `async-trait` macro and no executor is involved. +//! Implement them with plain `async fn`. + +use std::any::Any; +use std::collections::HashMap; +use std::error::Error; +use std::fmt; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +type BoxError = Box; + +/// A broker or store failure, wrapping whatever error the client library produced. +#[derive(Debug)] +pub struct TransportError(BoxError); + +impl TransportError { + /// Wraps a client error. + pub fn new(source: impl Into) -> Self { + Self(source.into()) + } + + /// The wrapped error. + #[must_use] + pub fn inner(&self) -> &(dyn Error + Send + Sync + 'static) { + &*self.0 + } +} + +impl fmt::Display for TransportError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "babelqueue: transport: {}", self.0) + } +} + +impl Error for TransportError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&*self.0) + } +} + +/// Why a [`Releaser::release`] did not release the message. +#[derive(Debug)] +#[non_exhaustive] +pub enum ReleaseError { + /// The transport cannot release this delivery in place. The [`App`](crate::App) falls back to + /// re-publishing the message and acknowledging the original. + Unsupported, + /// The release failed. The message stays reserved and the broker redelivers it when the + /// reservation lapses. + Failed(TransportError), +} + +impl fmt::Display for ReleaseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unsupported => f.write_str("babelqueue: release is not supported"), + Self::Failed(e) => write!(f, "babelqueue: release failed: {e}"), + } + } +} + +impl Error for ReleaseError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Unsupported => None, + Self::Failed(e) => Some(e), + } + } +} + +/// A message reserved from a queue, plus the transport-private handle used to acknowledge it. +/// +/// A transport builds one with [`Delivery::new`] and the `with_*` methods; the struct is +/// `#[non_exhaustive]` so fields can be added without breaking transports. +#[derive(Clone)] +#[non_exhaustive] +pub struct Delivery { + /// The raw message body, exactly as the broker returned it. It is bytes, not text: a body that + /// is not valid UTF-8 is poison and is dead-lettered with its bytes intact. + pub body: Vec, + /// The queue the message was reserved from. + pub queue: String, + /// Out-of-band transport headers that came with the message (a W3C `traceparent`, the + /// replay-bypass marker). Empty for a transport that does not surface them. + pub headers: HashMap, + /// The broker's own delivery count for this reservation (`1` on the first delivery), or `0` when + /// the transport does not track one. The runtime treats `delivery_count - 1` as a floor for the + /// envelope's `attempts`, so the attempt bound still holds when a message is released in place + /// and its body cannot carry the counter. + pub delivery_count: u64, + /// An optional routing override: when set, the handler is looked up by this URN instead of the + /// body's, and the body is left untouched. A transport whose broker carries the URN out of band + /// fills it. + pub route_urn: Option, + /// Set by a transport that classified this delivery as poison itself (the Redis zset reserve + /// script, broker-bindings section 1.1). The runtime then runs no handler and no retry: it + /// writes the body unchanged to the dead-letter queue and settles the reservation. + pub poison: bool, + handle: Option>, +} + +impl Delivery { + /// A delivery of `body` reserved from `queue`, with no headers, no delivery count, no routing + /// override and no handle. + #[must_use] + pub fn new(queue: impl Into, body: impl Into>) -> Self { + Self { + body: body.into(), + queue: queue.into(), + headers: HashMap::new(), + delivery_count: 0, + route_urn: None, + poison: false, + handle: None, + } + } + + /// Sets the out-of-band headers. + #[must_use] + pub fn with_headers(mut self, headers: HashMap) -> Self { + self.headers = headers; + self + } + + /// Sets the broker's delivery count (`1` on the first delivery). + #[must_use] + pub fn with_delivery_count(mut self, count: u64) -> Self { + self.delivery_count = count; + self + } + + /// Sets the routing override URN. + #[must_use] + pub fn with_route_urn(mut self, urn: impl Into) -> Self { + self.route_urn = Some(urn.into()); + self + } + + /// Marks the delivery as poison (see [`Delivery::poison`]). + #[must_use] + pub fn with_poison(mut self, poison: bool) -> Self { + self.poison = poison; + self + } + + /// Attaches the transport-private acknowledgement handle. + #[must_use] + pub fn with_handle(mut self, handle: H) -> Self { + self.handle = Some(Arc::new(handle)); + self + } + + /// The acknowledgement handle, when the transport attached one of type `H`. + #[must_use] + pub fn handle(&self) -> Option<&H> { + self.handle.as_deref().and_then(|h| h.downcast_ref::()) + } +} + +impl fmt::Debug for Delivery { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Delivery") + .field("queue", &self.queue) + .field("body_len", &self.body.len()) + .field("headers", &self.headers) + .field("delivery_count", &self.delivery_count) + .field("route_urn", &self.route_urn) + .field("poison", &self.poison) + .finish_non_exhaustive() + } +} + +/// The minimal broker contract: publish a raw (already encoded) body, reserve the next message and +/// acknowledge it. Implement it to back the runtime with any broker; [`InMemoryTransport`](crate::InMemoryTransport) +/// backs tests and local runs. +pub trait Transport: Send + Sync { + /// Appends an already-encoded envelope to `queue`. + fn publish( + &self, + queue: &str, + body: &[u8], + ) -> impl Future> + Send; + + /// Reserves the next message from `queue`, waiting up to `timeout`. Resolves to `None` when no + /// message arrives in time. Waiting is the transport's job (a blocking pop, a long poll): the + /// core owns no timer. + fn pop( + &self, + queue: &str, + timeout: Duration, + ) -> impl Future, TransportError>> + Send; + + /// Acknowledges (removes) a previously reserved message. + fn ack(&self, delivery: &Delivery) -> impl Future> + Send; +} + +/// Optional capability: publish a body together with out-of-band transport headers, for brokers +/// that carry per-message metadata (ADR-0027, ADR-0028). Opt in with +/// [`App::with_header_publisher`](crate::App::with_header_publisher); without it headers are +/// dropped and the publish is a plain one. +pub trait HeaderPublisher: Transport { + /// Appends `body` to `queue` with `headers`. + fn publish_with_headers( + &self, + queue: &str, + body: &[u8], + headers: &HashMap, + ) -> impl Future> + Send; +} + +/// Optional capability: return a reserved message to its queue in place, to be redelivered after +/// `delay`, instead of re-publishing a copy and acknowledging the original. Opt in with +/// [`App::with_releaser`](crate::App::with_releaser). +/// +/// On [`ReleaseError::Unsupported`] the runtime falls back to re-publish plus ack; on any other +/// error the message stays reserved and the broker redelivers it when the reservation lapses. +pub trait Releaser: Transport { + /// Releases `delivery` back to its queue after `delay`. + fn release( + &self, + delivery: &Delivery, + delay: Duration, + ) -> impl Future> + Send; +} + +/// Optional capability: write `body` to `dlq_queue` and settle `delivery` (the equivalent of an +/// ack) in one gated step. A transport whose acknowledgement is only valid for the consumer that +/// still owns the reservation (Redis: the deadline-member gate of broker-bindings section 1.7) +/// implements it, so a consumer whose reservation expired writes nothing instead of producing a +/// duplicate in the dead-letter queue. Opt in with +/// [`App::with_dead_letter_settler`](crate::App::with_dead_letter_settler). +/// +/// When it returns `Ok` the message is settled and the runtime does not ack it again; on error the +/// message stays unsettled. +pub trait DeadLetterSettler: Transport { + /// Writes `body` to `dlq_queue` and settles `delivery`. + fn dead_letter( + &self, + delivery: &Delivery, + dlq_queue: &str, + body: &[u8], + ) -> impl Future> + Send; +} diff --git a/crates/babelqueue/tests/app.rs b/crates/babelqueue/tests/app.rs new file mode 100644 index 0000000..0db16c6 --- /dev/null +++ b/crates/babelqueue/tests/app.rs @@ -0,0 +1,1096 @@ +//! Behaviour of the `App` runtime over in-memory and instrumented transports: routing, retry, +//! dead-lettering, poison and version-gated deliveries, the optional transport capabilities, panic +//! containment, and the idempotency and schema handler wrappers. +//! +//! No async runtime is linked: the futures here never stay pending on a real event, so a no-op waker +//! drives them. + +use std::collections::HashMap; +use std::future::Future; +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use babelqueue::idempotency::{self, InMemoryStore}; +use babelqueue::schema::{self, MapProvider}; +use babelqueue::{ + App, Backoff, DeadLetterEvent, DeadLetterSettler, Delivery, Envelope, HandlerError, + HeaderPublisher, InMemoryTransport, MakeOptions, ReleaseError, Releaser, Transport, + TransportError, UNSUPPORTED_SCHEMA_ROUTE_PREFIX, UnknownUrnStrategy, decode, make, +}; +use serde_json::{Value, json}; + +const URN: &str = "urn:babel:orders:created"; + +fn block_on(future: F) -> F::Output { + let mut future = std::pin::pin!(future); + let mut cx = Context::from_waker(Waker::noop()); + loop { + if let Poll::Ready(value) = future.as_mut().poll(&mut cx) { + return value; + } + std::thread::yield_now(); + } +} + +fn assert_send(_: &T) {} + +/// A future that is pending exactly once, to give a handler a real suspension point. +struct YieldOnce(bool); + +impl Future for YieldOnce { + type Output = (); + fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if self.0 { + return Poll::Ready(()); + } + self.0 = true; + cx.waker().wake_by_ref(); + Poll::Pending + } +} + +// --------------------------------------------------------------------------------------------- +// An instrumented transport implementing every optional capability +// --------------------------------------------------------------------------------------------- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReleaseMode { + Ok, + Unsupported, + Fail, +} + +struct Spy { + inner: InMemoryTransport, + acks: AtomicUsize, + fail_publish_to: Mutex>, + fail_ack: Mutex, + release_mode: Mutex, + releases: Mutex>, + settled: Mutex)>>, + delivery_counts: Mutex>, +} + +impl Spy { + fn new() -> Self { + Self { + inner: InMemoryTransport::new(), + acks: AtomicUsize::new(0), + fail_publish_to: Mutex::new(None), + fail_ack: Mutex::new(false), + release_mode: Mutex::new(ReleaseMode::Ok), + releases: Mutex::new(Vec::new()), + settled: Mutex::new(Vec::new()), + delivery_counts: Mutex::new(HashMap::new()), + } + } + + fn put(&self, queue: &str, body: &[u8]) { + block_on(self.inner.publish(queue, body)).unwrap(); + } +} + +impl Transport for Spy { + async fn publish(&self, queue: &str, body: &[u8]) -> Result<(), TransportError> { + if self.fail_publish_to.lock().unwrap().as_deref() == Some(queue) { + return Err(TransportError::new("publish refused")); + } + self.inner.publish(queue, body).await + } + + async fn pop( + &self, + queue: &str, + timeout: Duration, + ) -> Result, TransportError> { + let popped = self.inner.pop(queue, timeout).await?; + Ok( + popped.map(|d| match self.delivery_counts.lock().unwrap().get(queue) { + Some(count) => d.with_delivery_count(*count), + None => d, + }), + ) + } + + async fn ack(&self, _delivery: &Delivery) -> Result<(), TransportError> { + if *self.fail_ack.lock().unwrap() { + return Err(TransportError::new("ack refused")); + } + self.acks.fetch_add(1, SeqCst); + Ok(()) + } +} + +impl HeaderPublisher for Spy { + async fn publish_with_headers( + &self, + queue: &str, + body: &[u8], + headers: &HashMap, + ) -> Result<(), TransportError> { + self.inner.publish_with_headers(queue, body, headers).await + } +} + +impl Releaser for Spy { + async fn release(&self, delivery: &Delivery, delay: Duration) -> Result<(), ReleaseError> { + match *self.release_mode.lock().unwrap() { + ReleaseMode::Unsupported => Err(ReleaseError::Unsupported), + ReleaseMode::Fail => Err(ReleaseError::Failed(TransportError::new("release refused"))), + ReleaseMode::Ok => { + self.releases + .lock() + .unwrap() + .push((delivery.queue.clone(), delay)); + Ok(()) + } + } + } +} + +impl DeadLetterSettler for Spy { + async fn dead_letter( + &self, + delivery: &Delivery, + dlq_queue: &str, + body: &[u8], + ) -> Result<(), TransportError> { + let _ = delivery; + self.settled + .lock() + .unwrap() + .push((dlq_queue.to_owned(), body.to_vec())); + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------------------------- + +fn body(urn: &str, data: &Value, queue: &str) -> Vec { + make(urn, data, MakeOptions::new().queue(queue)) + .unwrap() + .encode() + .unwrap() +} + +fn parse(bytes: &[u8]) -> Value { + serde_json::from_slice(bytes).unwrap() +} + +fn memory_app() -> App { + App::new(InMemoryTransport::new()).queue("orders") +} + +fn counting_handler( + counter: &Arc, +) -> impl Fn(Arc, Arc) -> std::future::Ready> ++ Send ++ Sync ++ 'static { + let counter = Arc::clone(counter); + move |_env, _delivery| { + counter.fetch_add(1, SeqCst); + std::future::ready(Ok(())) + } +} + +// --------------------------------------------------------------------------------------------- +// Routing and publish +// --------------------------------------------------------------------------------------------- + +#[test] +fn a_published_message_reaches_its_handler_with_lazy_typed_data() { + #[derive(serde::Deserialize)] + struct Order { + order_id: u64, + } + let seen = Arc::new(Mutex::new(Vec::new())); + let mut app = memory_app(); + let sink = Arc::clone(&seen); + app.handle(URN, move |env: Arc, delivery: Arc| { + let sink = Arc::clone(&sink); + async move { + let order: Order = env.data()?; + sink.lock() + .unwrap() + .push((order.order_id, delivery.queue.clone())); + Ok(()) + } + }); + let id = block_on(app.publish(URN, &json!({"order_id": 1042}))).unwrap(); + assert_eq!(id.len(), 36); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 1); + assert_eq!(*seen.lock().unwrap(), [(1042, "orders".to_owned())]); + assert_eq!(app.transport().size("orders"), 0); +} + +#[test] +fn publish_with_options_targets_the_given_queue_and_keeps_the_trace() { + let app = memory_app(); + let opts = MakeOptions::new().queue("billing").trace_id("trace-7"); + let env = block_on(app.publish_with(URN, &json!({"a": 1}), opts, &HashMap::new())).unwrap(); + assert_eq!(env.trace_id(), "trace-7"); + let bodies = app.transport().bodies("billing"); + assert_eq!(bodies.len(), 1); + assert_eq!(parse(&bodies[0])["meta"]["queue"], "billing"); + assert_eq!(app.transport().size("orders"), 0); +} + +#[test] +fn publish_rejects_a_non_object_payload_before_the_transport_sees_it() { + let app = memory_app(); + let err = block_on(app.publish(URN, &json!([1, 2]))).unwrap_err(); + assert!(matches!(err, babelqueue::PublishError::Encode(_))); + assert_eq!(app.transport().size("orders"), 0); +} + +#[test] +fn headers_travel_only_with_the_header_publisher_capability() { + let headers = HashMap::from([("traceparent".to_owned(), "00-aa-bb-01".to_owned())]); + let plain = memory_app(); + block_on(plain.publish_with( + URN, + &json!({}), + MakeOptions::new().queue("orders"), + &headers, + )) + .unwrap(); + assert_eq!(plain.transport().headers("orders"), [HashMap::new()]); + + let with = memory_app().with_header_publisher(); + block_on(with.publish_with( + URN, + &json!({}), + MakeOptions::new().queue("orders"), + &headers, + )) + .unwrap(); + assert_eq!( + with.transport().headers("orders"), + std::slice::from_ref(&headers) + ); + + let mut seen = Vec::new(); + let delivery = block_on(with.transport().pop("orders", Duration::ZERO)) + .unwrap() + .unwrap(); + seen.push(delivery.headers.get("traceparent").cloned()); + assert_eq!(seen, [Some("00-aa-bb-01".to_owned())]); +} + +#[test] +fn the_route_urn_override_picks_the_handler_and_leaves_the_body_alone() { + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app(); + app.handle("urn:babel:other", counting_handler(&hits)); + let delivery = + Delivery::new("orders", body(URN, &json!({}), "orders")).with_route_urn("urn:babel:other"); + block_on(app.transport().publish("orders", &delivery.body)).unwrap(); + // The in-memory transport cannot carry a route URN, so dispatch through a custom pop. + struct Routed(InMemoryTransport); + impl Transport for Routed { + async fn publish(&self, q: &str, b: &[u8]) -> Result<(), TransportError> { + self.0.publish(q, b).await + } + async fn pop(&self, q: &str, t: Duration) -> Result, TransportError> { + Ok(self + .0 + .pop(q, t) + .await? + .map(|d| d.with_route_urn("urn:babel:other"))) + } + async fn ack(&self, d: &Delivery) -> Result<(), TransportError> { + self.0.ack(d).await + } + } + let mut routed = App::new(Routed(InMemoryTransport::new())).queue("orders"); + routed.handle("urn:babel:other", counting_handler(&hits)); + block_on(routed.transport().publish("orders", &delivery.body)).unwrap(); + assert_eq!(block_on(routed.drain("orders", 0)).unwrap(), 1); + assert_eq!(hits.load(SeqCst), 1); +} + +#[test] +fn consume_stops_when_the_shutdown_future_resolves_and_the_future_is_send() { + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app(); + app.handle(URN, counting_handler(&hits)); + block_on(app.publish(URN, &json!({}))).unwrap(); + block_on(app.publish(URN, &json!({}))).unwrap(); + let polls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&polls); + // Pending for three checks, then ready. + let shutdown = std::future::poll_fn(move |_| { + if counter.fetch_add(1, SeqCst) >= 3 { + Poll::Ready(()) + } else { + Poll::Pending + } + }); + let run = app.run(shutdown); + assert_send(&run); + block_on(run).unwrap(); + assert_eq!(hits.load(SeqCst), 2); + assert_eq!(polls.load(SeqCst), 4); +} + +// --------------------------------------------------------------------------------------------- +// Retry and dead-letter +// --------------------------------------------------------------------------------------------- + +fn failing_app(strategy_dead_letter: bool) -> App { + let mut app = memory_app() + .max_attempts(3) + .dead_letter(strategy_dead_letter); + app.handle(URN, |_env: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("boom")) + }); + app +} + +#[test] +fn a_failure_is_republished_with_attempts_plus_one_and_the_rest_untouched() { + let app = failing_app(true); + let original = body( + URN, + &json!({"order_id": 1, "big": 12345678901234567890u64}), + "orders", + ); + block_on(app.transport().publish("orders", &original)).unwrap(); + assert_eq!(block_on(app.drain("orders", 1)).unwrap(), 1); + let retried = app.transport().bodies("orders"); + assert_eq!(retried.len(), 1); + let (before, after) = (parse(&original), parse(&retried[0])); + assert_eq!(after["attempts"], 1); + assert_eq!(after["data"], before["data"]); + assert_eq!(after["meta"], before["meta"]); + assert_eq!(after["trace_id"], before["trace_id"]); +} + +#[test] +fn exhausted_retries_write_a_dead_letter_record_and_notify_the_observer() { + let events: Arc>> = Arc::default(); + let sink = Arc::clone(&events); + let app = failing_app(true).on_dead_letter(move |e| sink.lock().unwrap().push(e.clone())); + let original = body(URN, &json!({"order_id": 7}), "orders"); + block_on(app.transport().publish("orders", &original)).unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 3); + assert_eq!(app.transport().size("orders"), 0); + let dlq = app.transport().bodies("orders.dlq"); + assert_eq!(dlq.len(), 1); + let record = parse(&dlq[0]); + assert_eq!(record["data"], json!({"order_id": 7})); + assert_eq!(record["job"], URN); + let block = &record["dead_letter"]; + assert_eq!(block["reason"], "failed"); + assert_eq!(block["error"], "boom"); + assert_eq!(block["exception"], "babelqueue::HandlerError"); + assert_eq!(block["original_queue"], "orders"); + assert_eq!(block["attempts"], 3); + assert_eq!(block["lang"], "rust"); + assert!(decode(&dlq[0]).unwrap().envelope().dead_letter().is_some()); + let events = events.lock().unwrap(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].queue, "orders"); + assert_eq!(events[0].dead_letter_queue, "orders.dlq"); + assert_eq!(events[0].reason.as_deref(), Some("failed")); +} + +#[test] +fn exhausted_retries_without_dead_lettering_drop_the_message() { + let app = failing_app(false); + block_on( + app.transport() + .publish("orders", &body(URN, &json!({}), "orders")), + ) + .unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 3); + assert_eq!(app.transport().size("orders"), 0); + assert_eq!(app.transport().size("orders.dlq"), 0); +} + +#[test] +fn the_dead_letter_queue_name_can_be_overridden() { + let mut app = memory_app() + .max_attempts(1) + .dead_letter(true) + .dead_letter_queue("parked"); + app.handle(URN, |_e: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("x")) + }); + block_on(app.publish(URN, &json!({}))).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().size("parked"), 1); + + let mut suffixed = memory_app() + .max_attempts(1) + .dead_letter(true) + .dead_letter_suffix("-dead"); + suffixed.handle(URN, |_e: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("x")) + }); + block_on(suffixed.publish(URN, &json!({}))).unwrap(); + block_on(suffixed.drain("orders", 0)).unwrap(); + assert_eq!(suffixed.transport().size("orders-dead"), 1); +} + +#[test] +fn the_brokers_delivery_count_is_a_floor_for_attempts() { + let spy = Spy::new(); + spy.delivery_counts + .lock() + .unwrap() + .insert("orders".into(), 3); + let mut app = App::new(spy) + .queue("orders") + .max_attempts(3) + .dead_letter(true); + app.handle(URN, |_e: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("x")) + }); + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + // attempts 0 in the body, delivery 3 => floor 2, failing makes 3 => dead-lettered at once. + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().inner.size("orders"), 0); + let dlq = app.transport().inner.bodies("orders.dlq"); + assert_eq!(dlq.len(), 1); + assert_eq!(parse(&dlq[0])["attempts"], 3); +} + +// --------------------------------------------------------------------------------------------- +// Handler panics +// --------------------------------------------------------------------------------------------- + +#[test] +fn a_panicking_handler_does_not_take_the_worker_down_and_takes_the_retry_path() { + let healthy = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app().max_attempts(2).dead_letter(true); + app.handle(URN, |_e: Arc, _d: Arc| async { + let _ = YieldOnce(false).await; + panic!("boom in a later poll"); + }); + app.handle( + "urn:babel:sync-panic", + |_e: Arc, _d: Arc| -> std::future::Ready> { + panic!("boom before the future exists") + }, + ); + app.handle("urn:babel:healthy", counting_handler(&healthy)); + + block_on(app.publish(URN, &json!({}))).unwrap(); + block_on(app.publish("urn:babel:sync-panic", &json!({}))).unwrap(); + block_on(app.publish("urn:babel:healthy", &json!({}))).unwrap(); + // 2 panicking messages x 2 attempts + 1 healthy message; the worker keeps going throughout. + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 5); + assert_eq!(healthy.load(SeqCst), 1); + assert_eq!(app.transport().size("orders"), 0); + + let dlq: Vec = app + .transport() + .bodies("orders.dlq") + .iter() + .map(|b| parse(b)) + .collect(); + assert_eq!(dlq.len(), 2); + let errors: Vec<&str> = dlq + .iter() + .map(|r| r["dead_letter"]["error"].as_str().unwrap()) + .collect(); + assert!(errors.contains(&"handler panicked: boom in a later poll")); + assert!(errors.contains(&"handler panicked: boom before the future exists")); + for record in &dlq { + assert_eq!(record["dead_letter"]["exception"], "panic"); + assert_eq!(record["dead_letter"]["reason"], "failed"); + assert_eq!(record["dead_letter"]["attempts"], 2); + } +} + +#[test] +fn a_panicking_hook_never_changes_how_the_message_is_settled() { + let mut app = memory_app() + .max_attempts(1) + .dead_letter(true) + .on_dead_letter(|_| panic!("hook bug")); + app.handle(URN, |_e: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("x")) + }); + block_on(app.publish(URN, &json!({}))).unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 1); + assert_eq!(app.transport().size("orders.dlq"), 1); +} + +// --------------------------------------------------------------------------------------------- +// Unknown URNs +// --------------------------------------------------------------------------------------------- + +#[test] +fn unknown_urn_fail_retries_then_dead_letters_with_reason_unknown_urn() { + let app = memory_app().max_attempts(2).dead_letter(true); + block_on(app.publish("urn:babel:nobody", &json!({"k": "v"}))).unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 2); + let record = parse(&app.transport().bodies("orders.dlq")[0]); + assert_eq!(record["dead_letter"]["reason"], "unknown_urn"); + assert_eq!(record["dead_letter"]["exception"], "babelqueue::UnknownUrn"); + assert_eq!(record["data"], json!({"k": "v"})); +} + +#[test] +fn unknown_urn_delete_acknowledges_and_drops() { + let app = memory_app() + .unknown_urn_strategy(UnknownUrnStrategy::Delete) + .dead_letter(true); + block_on(app.publish("urn:babel:nobody", &json!({}))).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().size("orders"), 0); + assert_eq!(app.transport().size("orders.dlq"), 0); +} + +#[test] +fn unknown_urn_release_puts_the_same_bytes_back_without_a_new_attempt() { + let app = memory_app().unknown_urn_strategy(UnknownUrnStrategy::Release); + let original = body("urn:babel:nobody", &json!({"x": 1}), "orders"); + block_on(app.transport().publish("orders", &original)).unwrap(); + assert_eq!(block_on(app.drain("orders", 1)).unwrap(), 1); + assert_eq!(app.transport().bodies("orders"), [original]); +} + +#[test] +fn unknown_urn_release_uses_the_in_place_releaser_with_its_delay() { + let spy = Spy::new(); + let app = App::new(spy) + .queue("orders") + .unknown_urn_strategy(UnknownUrnStrategy::Release) + .unknown_urn_release_delay(Duration::from_secs(9)) + .with_releaser(); + app.transport() + .put("orders", &body("urn:babel:nobody", &json!({}), "orders")); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!( + *app.transport().releases.lock().unwrap(), + [("orders".to_owned(), Duration::from_secs(9))] + ); + assert_eq!(app.transport().acks.load(SeqCst), 0); + assert_eq!(app.transport().inner.size("orders"), 0); +} + +#[test] +fn unknown_urn_dead_letter_writes_immediately_even_with_dead_lettering_off() { + let app = memory_app().unknown_urn_strategy(UnknownUrnStrategy::DeadLetter); + block_on(app.publish("urn:babel:nobody", &json!({}))).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + let record = parse(&app.transport().bodies("orders.dlq")[0]); + assert_eq!(record["dead_letter"]["reason"], "unknown_urn"); + assert_eq!(record["attempts"], 0); + // No cause on the immediate dead-letter, like the Go and Python SDKs. + assert_eq!(record["dead_letter"]["error"], Value::Null); + assert_eq!(record["dead_letter"]["exception"], Value::Null); +} + +// --------------------------------------------------------------------------------------------- +// Poison and version-gated deliveries +// --------------------------------------------------------------------------------------------- + +#[test] +fn poison_bodies_are_dead_lettered_with_their_bytes_and_never_retried() { + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app().dead_letter(true); + app.handle(URN, counting_handler(&hits)); + let spliceable = br#"{"a":1e400,"a":2}"#.to_vec(); + let not_json = b"hello \x00 world".to_vec(); + let invalid_utf8 = b"{\"a\":\"\xff\"}".to_vec(); + for raw in [&spliceable, ¬_json, &invalid_utf8, &b"[1,2]".to_vec()] { + block_on(app.transport().publish("orders", raw)).unwrap(); + } + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 4); + assert_eq!(hits.load(SeqCst), 0); + assert_eq!(app.transport().size("orders"), 0); + + let dlq = app.transport().bodies("orders.dlq"); + assert_eq!(dlq.len(), 4); + let texts: Vec = dlq + .iter() + .map(|b| String::from_utf8(b.clone()).unwrap()) + .collect(); + assert!(texts[0].starts_with(r#"{"a":1e400,"a":2,"dead_letter":{"reason":"poison""#)); + assert!(texts[1].starts_with(r#"{"raw":"hello \u0000 world","dead_letter""#)); + assert!(texts[2].contains(r#""raw_encoding":"base64""#)); + assert!(texts[3].starts_with(r#"{"raw":"[1,2]","dead_letter""#)); + for record in &texts { + assert!(record.contains(r#""reason":"poison""#)); + assert!(record.contains(r#""original_queue":"orders""#)); + } +} + +#[test] +fn an_object_without_identity_is_poison_and_spliced() { + let app = memory_app().dead_letter(true); + block_on( + app.transport() + .publish("orders", br#"{"data":{"x":1},"attempts":0}"#), + ) + .unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + let record = parse(&app.transport().bodies("orders.dlq")[0]); + assert_eq!(record["data"], json!({"x": 1})); + assert_eq!(record["dead_letter"]["reason"], "poison"); + assert!( + record["dead_letter"]["error"] + .as_str() + .unwrap() + .contains("no valid job or urn") + ); +} + +#[test] +fn poison_is_dropped_under_delete_and_when_there_is_no_dead_letter_queue() { + for app in [ + memory_app() + .dead_letter(true) + .unknown_urn_strategy(UnknownUrnStrategy::Delete), + memory_app().dead_letter(false), + ] { + block_on(app.transport().publish("orders", b"garbage")).unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 1); + assert_eq!(app.transport().size("orders"), 0); + assert_eq!(app.transport().size("orders.dlq"), 0); + } +} + +#[test] +fn poison_without_a_dead_letter_queue_is_released_in_place_while_attempts_remain() { + let spy = Spy::new(); + spy.delivery_counts + .lock() + .unwrap() + .insert("orders".into(), 1); + let app = App::new(spy) + .queue("orders") + .max_attempts(3) + .with_releaser(); + app.transport().put("orders", b"garbage"); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().releases.lock().unwrap().len(), 1); + assert_eq!(app.transport().acks.load(SeqCst), 0); + + // Third delivery: out of attempts, dropped. + app.transport() + .delivery_counts + .lock() + .unwrap() + .insert("orders".into(), 3); + app.transport().put("orders", b"garbage"); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().releases.lock().unwrap().len(), 1); + assert_eq!(app.transport().acks.load(SeqCst), 1); +} + +#[test] +fn a_blank_route_override_is_no_override_and_follows_the_strategy() { + struct BlankRoute(InMemoryTransport); + impl Transport for BlankRoute { + async fn publish(&self, q: &str, b: &[u8]) -> Result<(), TransportError> { + self.0.publish(q, b).await + } + async fn pop(&self, q: &str, t: Duration) -> Result, TransportError> { + Ok(self.0.pop(q, t).await?.map(|d| d.with_route_urn(" "))) + } + async fn ack(&self, d: &Delivery) -> Result<(), TransportError> { + self.0.ack(d).await + } + } + // A valid envelope still reaches the handler named by its own URN, and nothing is dead-lettered + // even with dead-lettering off or the Delete strategy. + for strategy in [UnknownUrnStrategy::Fail, UnknownUrnStrategy::Delete] { + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = App::new(BlankRoute(InMemoryTransport::new())) + .queue("orders") + .unknown_urn_strategy(strategy); + app.handle(URN, counting_handler(&hits)); + block_on(app.publish(URN, &json!({}))).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(hits.load(SeqCst), 1); + assert_eq!(app.transport().0.size("orders.dlq"), 0); + } + // An identity-less body with a blank override is poison and obeys the strategy: dropped here. + let app = App::new(BlankRoute(InMemoryTransport::new())) + .queue("orders") + .unknown_urn_strategy(UnknownUrnStrategy::Delete); + block_on(app.transport().publish("orders", br#"{"data":{}}"#)).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().0.size("orders.dlq"), 0); + assert_eq!(app.transport().0.size("orders"), 0); +} + +#[test] +fn an_empty_in_memory_pop_yields_to_the_executor_once() { + let transport = InMemoryTransport::new(); + let mut pop = std::pin::pin!(transport.pop("empty", Duration::ZERO)); + let mut cx = Context::from_waker(Waker::noop()); + assert!(pop.as_mut().poll(&mut cx).is_pending()); + assert!(matches!(pop.as_mut().poll(&mut cx), Poll::Ready(Ok(None)))); +} + +#[test] +fn a_decode_failure_is_recorded_under_its_public_type_name() { + let app = memory_app().dead_letter(true); + block_on(app.transport().publish("orders", b"not json")).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + let record = parse(&app.transport().bodies("orders.dlq")[0]); + assert_eq!( + record["dead_letter"]["exception"], + "babelqueue::DecodeError" + ); +} + +#[test] +fn a_transport_flagged_poison_delivery_is_dead_lettered_untouched_whatever_decode_says() { + struct Flagging(InMemoryTransport); + impl Transport for Flagging { + async fn publish(&self, q: &str, b: &[u8]) -> Result<(), TransportError> { + self.0.publish(q, b).await + } + async fn pop(&self, q: &str, t: Duration) -> Result, TransportError> { + Ok(self.0.pop(q, t).await?.map(|d| d.with_poison(true))) + } + async fn ack(&self, d: &Delivery) -> Result<(), TransportError> { + self.0.ack(d).await + } + } + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = App::new(Flagging(InMemoryTransport::new())) + .queue("orders") + .unknown_urn_strategy(UnknownUrnStrategy::DeadLetter); + app.handle(URN, counting_handler(&hits)); + // A body that decodes cleanly, so only the flag makes it poison. + block_on( + app.transport() + .publish("orders", &body(URN, &json!({"ok": true}), "orders")), + ) + .unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(hits.load(SeqCst), 0); + let record = parse(&app.transport().0.bodies("orders.dlq")[0]); + assert_eq!(record["dead_letter"]["reason"], "poison"); + assert_eq!(record["data"], json!({"ok": true})); +} + +struct Gated(InMemoryTransport); +impl Transport for Gated { + async fn publish(&self, q: &str, b: &[u8]) -> Result<(), TransportError> { + self.0.publish(q, b).await + } + async fn pop(&self, q: &str, t: Duration) -> Result, TransportError> { + Ok(self + .0 + .pop(q, t) + .await? + .map(|d| d.with_route_urn(format!("{UNSUPPORTED_SCHEMA_ROUTE_PREFIX}2")))) + } + async fn ack(&self, d: &Delivery) -> Result<(), TransportError> { + self.0.ack(d).await + } +} + +#[test] +fn a_version_gated_delivery_is_dead_lettered_raw_and_never_decoded_or_handled() { + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = App::new(Gated(InMemoryTransport::new())) + .queue("orders") + .dead_letter(true); + app.handle(URN, counting_handler(&hits)); + let raw = + br#"{"job":"urn:babel:orders:created","meta":{"schema_version":2},"unreadable":"#.to_vec(); + block_on(app.transport().publish("orders", &raw)).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(hits.load(SeqCst), 0); + // Byte-identical, no dead_letter block. + assert_eq!(app.transport().0.bodies("orders.dlq"), [raw]); +} + +#[test] +fn a_version_gated_delivery_is_dropped_under_delete_or_without_dead_lettering() { + for app in [ + App::new(Gated(InMemoryTransport::new())) + .queue("orders") + .dead_letter(true) + .unknown_urn_strategy(UnknownUrnStrategy::Delete), + App::new(Gated(InMemoryTransport::new())).queue("orders"), + ] { + block_on(app.transport().publish("orders", b"{}")).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(app.transport().0.size("orders.dlq"), 0); + assert_eq!(app.transport().0.size("orders"), 0); + } +} + +#[test] +fn decode_warnings_reach_the_hook_before_the_handler_runs() { + let warnings: Arc>> = Arc::default(); + let sink = Arc::clone(&warnings); + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app().on_warning(move |_d, w| sink.lock().unwrap().push(w.to_owned())); + app.handle(URN, counting_handler(&hits)); + let with_forbidden = br#"{"job":"urn:babel:orders:created","trace_id":"t","data":{},"timestamp":1,"meta":{"id":"i","queue":"orders","lang":"go","schema_version":1,"created_at":1},"attempts":0}"#; + block_on(app.transport().publish("orders", with_forbidden)).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(hits.load(SeqCst), 1); + assert_eq!(warnings.lock().unwrap().len(), 1); +} + +// --------------------------------------------------------------------------------------------- +// Optional capabilities and failures of the broker +// --------------------------------------------------------------------------------------------- + +fn spy_app() -> App { + let mut app = App::new(Spy::new()).queue("orders").max_attempts(3); + app.handle(URN, |_e: Arc, _d: Arc| async { + Err::<(), _>(HandlerError::msg("x")) + }); + app +} + +#[test] +fn a_releaser_returns_the_message_in_place_with_the_backoff_delay() { + let app = spy_app() + .backoff(Backoff::new(Duration::from_secs(2)).multiplier(2.0)) + .with_releaser(); + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 1); + // n = attempts + 1 = 1 -> 2s. Released, not re-published, not acked. + assert_eq!( + *app.transport().releases.lock().unwrap(), + [("orders".to_owned(), Duration::from_secs(2))] + ); + assert_eq!(app.transport().inner.size("orders"), 0); + assert_eq!(app.transport().acks.load(SeqCst), 0); +} + +#[test] +fn an_unsupported_release_falls_back_to_republish_and_ack() { + let app = spy_app().with_releaser(); + *app.transport().release_mode.lock().unwrap() = ReleaseMode::Unsupported; + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + block_on(app.drain("orders", 1)).unwrap(); + assert_eq!(app.transport().inner.size("orders"), 1); + assert_eq!(app.transport().acks.load(SeqCst), 1); +} + +#[test] +fn a_failed_release_is_reported_and_leaves_the_message_with_the_broker() { + let reported = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&reported); + let app = spy_app().with_releaser().on_release_error(move |_d, _e| { + counter.fetch_add(1, SeqCst); + }); + *app.transport().release_mode.lock().unwrap() = ReleaseMode::Fail; + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + block_on(app.drain("orders", 1)).unwrap(); + assert_eq!(reported.load(SeqCst), 1); + assert_eq!(app.transport().inner.size("orders"), 0, "not re-published"); + assert_eq!(app.transport().acks.load(SeqCst), 0, "not acked"); +} + +#[test] +fn a_dead_letter_settler_writes_and_settles_in_one_step_without_a_second_ack() { + let app = spy_app() + .max_attempts(1) + .dead_letter(true) + .with_dead_letter_settler(); + app.transport() + .put("orders", &body(URN, &json!({"k": 1}), "orders")); + block_on(app.drain("orders", 0)).unwrap(); + let settled = app.transport().settled.lock().unwrap().clone(); + assert_eq!(settled.len(), 1); + assert_eq!(settled[0].0, "orders.dlq"); + assert_eq!(parse(&settled[0].1)["dead_letter"]["reason"], "failed"); + assert_eq!( + app.transport().acks.load(SeqCst), + 0, + "settled by the transport, not acked again" + ); + assert_eq!( + app.transport().inner.size("orders.dlq"), + 0, + "went through the settler, not publish" + ); +} + +#[test] +fn a_failed_dead_letter_write_never_acknowledges_the_message() { + let reported = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&reported); + let app = spy_app() + .max_attempts(1) + .dead_letter(true) + .on_dead_letter_error(move |_d, e| { + assert!(e.to_string().contains("publish refused")); + counter.fetch_add(1, SeqCst); + }); + *app.transport().fail_publish_to.lock().unwrap() = Some("orders.dlq".into()); + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(reported.load(SeqCst), 1); + assert_eq!(app.transport().acks.load(SeqCst), 0); + assert_eq!(app.transport().inner.size("orders.dlq"), 0); +} + +#[test] +fn a_failed_retry_republish_is_reported_and_not_acknowledged() { + let reported = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&reported); + let app = spy_app().on_release_error(move |_d, _e| { + counter.fetch_add(1, SeqCst); + }); + *app.transport().fail_publish_to.lock().unwrap() = Some("orders".into()); + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(reported.load(SeqCst), 1); + assert_eq!(app.transport().acks.load(SeqCst), 0); +} + +#[test] +fn an_ack_failure_is_reported_and_is_not_a_handler_failure() { + let reported = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&reported); + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = App::new(Spy::new()) + .queue("orders") + .max_attempts(3) + .on_ack_error(move |_d, _e| { + counter.fetch_add(1, SeqCst); + }); + app.handle(URN, counting_handler(&hits)); + *app.transport().fail_ack.lock().unwrap() = true; + app.transport() + .put("orders", &body(URN, &json!({}), "orders")); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!(hits.load(SeqCst), 1); + assert_eq!(reported.load(SeqCst), 1); + assert_eq!( + app.transport().inner.size("orders"), + 0, + "no retry was published" + ); +} + +#[test] +fn a_failing_pop_ends_the_loop_with_the_transport_error() { + struct Broken; + impl Transport for Broken { + async fn publish(&self, _: &str, _: &[u8]) -> Result<(), TransportError> { + Ok(()) + } + async fn pop(&self, _: &str, _: Duration) -> Result, TransportError> { + Err(TransportError::new("connection lost")) + } + async fn ack(&self, _: &Delivery) -> Result<(), TransportError> { + Ok(()) + } + } + let app = App::new(Broken); + let err = block_on(app.run(std::future::pending::<()>())).unwrap_err(); + assert!(err.to_string().contains("connection lost")); + assert!(block_on(app.drain("default", 0)).is_err()); +} + +// --------------------------------------------------------------------------------------------- +// Handler wrappers +// --------------------------------------------------------------------------------------------- + +#[test] +fn idempotency_collapses_a_redelivery_to_one_effect() { + let hits = Arc::new(AtomicUsize::new(0)); + let store = Arc::new(InMemoryStore::new()); + let mut app = memory_app(); + app.handle( + URN, + idempotency::wrap(Arc::clone(&store), counting_handler(&hits)), + ); + let one = body(URN, &json!({"n": 1}), "orders"); + block_on(app.transport().publish("orders", &one)).unwrap(); + block_on(app.transport().publish("orders", &one)).unwrap(); + block_on(app.publish(URN, &json!({"n": 1}))).unwrap(); // a distinct meta.id + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 3); + assert_eq!(hits.load(SeqCst), 2); +} + +#[test] +fn a_failed_handler_leaves_the_id_unmarked_so_the_retry_runs_again() { + let hits = Arc::new(AtomicUsize::new(0)); + let attempts = Arc::clone(&hits); + let store = Arc::new(InMemoryStore::new()); + let mut app = memory_app().max_attempts(3); + app.handle( + URN, + idempotency::wrap( + Arc::clone(&store), + move |_e: Arc, _d: Arc| { + let n = attempts.fetch_add(1, SeqCst); + async move { + if n == 0 { + Err(HandlerError::msg("first try fails")) + } else { + Ok(()) + } + } + }, + ), + ); + block_on(app.publish(URN, &json!({}))).unwrap(); + assert_eq!(block_on(app.drain("orders", 0)).unwrap(), 2); + assert_eq!(hits.load(SeqCst), 2); +} + +#[test] +fn schema_wrap_sends_invalid_data_down_the_dead_letter_path() { + let provider = Arc::new( + MapProvider::new() + .with_schema( + URN, + br#"{"type":"object","required":["order_id"],"properties":{"order_id":{"type":"integer","minimum":1}},"additionalProperties":false}"#, + ) + .unwrap(), + ); + let hits = Arc::new(AtomicUsize::new(0)); + let mut app = memory_app().max_attempts(2).dead_letter(true); + app.handle( + URN, + schema::wrap(Arc::clone(&provider), counting_handler(&hits)), + ); + app.handle( + "urn:babel:unregistered", + schema::wrap(Arc::clone(&provider), counting_handler(&hits)), + ); + block_on(app.publish(URN, &json!({"order_id": 5}))).unwrap(); + block_on(app.publish(URN, &json!({"order_id": 0, "extra": true}))).unwrap(); + block_on(app.publish("urn:babel:unregistered", &json!({"anything": 1}))).unwrap(); + block_on(app.drain("orders", 0)).unwrap(); + assert_eq!( + hits.load(SeqCst), + 2, + "the valid one and the unregistered URN" + ); + let dlq = app.transport().bodies("orders.dlq"); + assert_eq!(dlq.len(), 1); + let error = parse(&dlq[0])["dead_letter"]["error"] + .as_str() + .unwrap() + .to_owned(); + assert!( + error.contains("additional property \"extra\" is not allowed"), + "{error}" + ); + assert!(error.contains("must be >= 1"), "{error}"); + assert!(schema::check(&*provider, URN, &json!({"order_id": 9})).is_ok()); + assert!(schema::check(&*provider, URN, &json!({})).is_err()); +} diff --git a/crates/babelqueue/tests/conformance.rs b/crates/babelqueue/tests/conformance.rs index ac87ab3..864d3d1 100644 --- a/crates/babelqueue/tests/conformance.rs +++ b/crates/babelqueue/tests/conformance.rs @@ -1,21 +1,55 @@ -//! The cross-SDK conformance runner (GR-5): the codec sections of the vendored suite under -//! `testdata/conformance/`, run against this core. +//! The cross-SDK conformance runner (GR-5): every `core` section of the vendored suite under +//! `testdata/conformance/`, run against this crate. //! //! One test per manifest section, named after it (`cases`, `roundtrip`, `data_shape`, -//! `forbidden_keys`, `extension_write`, `encode_reject`, `trim`, `job_type`, `identity_verdict`). -//! A section missing from the manifest is a hard failure, never a skip, so the suite and the runner -//! move together. `manifest_sections_are_all_classified` fails when the manifest holds a section -//! this runner has not classified, and prints the pass/pending/skip table of every section. +//! `forbidden_keys`, `extension_write`, `encode_reject`, `trim`, `job_type`, `identity_verdict`, +//! `idempotency`, `payload_schema`, `payload_schema_unicode`, `payload_schema_keywords`, +//! `retry_backoff`, `poison_dlq`). A section missing from the manifest is a hard failure, never a +//! skip, so the suite and the runner move together. `manifest_sections_are_all_classified` fails +//! when the manifest holds a section this runner has not classified, and prints the pass/pending/skip +//! table of every section. +//! +//! `results_json` runs every `core` section again, case by case, and when `BQ_CONFORMANCE_RESULTS` +//! names a path writes the `results.json` of ADR-0032 section 2 there. It fails on any case that +//! failed (after writing the file), on a section or case the manifest has and the run lacks, and +//! on a file that violates `schema/results.schema.json`. //! //! Per-message fields (`meta.id`, `trace_id`, `meta.created_at`) are intrinsically unique: they are //! checked for presence, not for value. Key order and whitespace are not asserted. +use std::collections::BTreeSet; use std::fs; +use std::future::Future; use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; -use babelqueue::{DecodeError, EncodeError, Envelope, MakeOptions, decode, make}; +use babelqueue::idempotency::{self, InMemoryStore, Store}; +use babelqueue::results::{CaseResult, Results, manifest_case_ids}; +use babelqueue::{ + Backoff, DecodeError, Delivery, EncodeError, Envelope, FailureCause, HandlerError, Jitter, + MakeOptions, Schema, annotate, decode, make, poison_dead_letter_body, +}; use serde_json::{Map, Value, json}; +/// One entry per case of a section: the manifest case id and the violations found (empty = pass). +type Outcomes = Vec<(String, Vec)>; + +/// Drives a future to completion on the calling thread. The futures here (in-memory transport and +/// store, handlers that never wait) never stay pending, so a no-op waker is enough; no runtime is +/// linked. +fn block_on(future: F) -> F::Output { + use std::task::{Context, Poll, Waker}; + let mut future = std::pin::pin!(future); + let mut cx = Context::from_waker(Waker::noop()); + loop { + if let Poll::Ready(value) = future.as_mut().poll(&mut cx) { + return value; + } + std::thread::yield_now(); + } +} + // --------------------------------------------------------------------------------------------- // Suite access // --------------------------------------------------------------------------------------------- @@ -60,20 +94,35 @@ fn name(case: &Value) -> &str { text(case, "name") } -/// Runs `check` on every case of a section and fails with every violation, case by case. -fn run_section(section: &str, check: impl Fn(&Value) -> Vec) { - let cases = section_cases(section); - let mut failures = Vec::new(); - for case in &cases { - for violation in check(case) { - failures.push(format!("[{}] {violation}", name(case))); - } - } +/// The manifest case id of the `index`-th element of a `cases` array: its `name`, else +/// `

#` (results.schema.json). +fn case_id(section: &str, index: usize, case: &Value) -> String { + case.get("name") + .and_then(Value::as_str) + .filter(|n| !n.is_empty()) + .map_or_else(|| format!("{section}#{index}"), str::to_owned) +} + +/// Runs `check` on every case of a section and returns the violations case by case. +fn eval_section(section: &str, check: impl Fn(&Value) -> Vec) -> Outcomes { + section_cases(section) + .iter() + .enumerate() + .map(|(i, case)| (case_id(section, i, case), check(case))) + .collect() +} + +/// Fails with every violation of a section, case by case. +fn assert_clean(section: &str, outcomes: &Outcomes) { + let failures: Vec = outcomes + .iter() + .flat_map(|(id, violations)| violations.iter().map(move |v| format!("[{id}] {v}"))) + .collect(); assert!( failures.is_empty(), "section {section:?}: {} violations across {} cases:\n{}", failures.len(), - cases.len(), + outcomes.len(), failures.join("\n") ); } @@ -133,9 +182,8 @@ fn json_to_string(v: &Value) -> String { // --------------------------------------------------------------------------------------------- /// `cases`: the golden fixtures decode, are accepted (or rejected) and carry the expected values. -#[test] -fn cases() { - run_section("cases", |case| { +fn eval_cases() -> Outcomes { + eval_section("cases", |case| { let body = fixture(text(case, "file")); let valid = case.get("valid").and_then(Value::as_bool).expect("valid"); let decoded = decode(&body); @@ -221,20 +269,19 @@ fn cases() { } } v - }); + }) } -/// The DLQ helper (`apply_dead_letter`) is part of the runtime phase. Until it lands the runner -/// takes the fallback the manifest allows: a runner that does not know the field runs the case as a -/// plain decode -> attempts + 1 -> encode chain. -fn apply_dead_letter(_env: &mut Envelope, _reason: &str, _original_queue: &str) -> bool { - false +/// `apply_dead_letter`: moves the message to the dead-letter queue with the SDK's own DLQ helper +/// ([`annotate`]) and reports that it did. +fn apply_dead_letter(env: &mut Envelope, reason: &str, original_queue: &str) -> bool { + *env = annotate(env.clone(), reason, original_queue, env.attempts(), None); + true } /// `roundtrip`: unknown keys survive decode -> attempts + 1 -> encode with the same value and type. -#[test] -fn roundtrip() { - run_section("roundtrip", |case| { +fn eval_roundtrip() -> Outcomes { + eval_section("roundtrip", |case| { let body = fixture(text(case, "file")); let decoded = match decode(&body) { Ok(d) => d, @@ -293,14 +340,13 @@ fn roundtrip() { } } v - }); + }) } /// `data_shape`: `data` is always a JSON object; an empty map encodes as `{}` and an array is /// rejected on decode. -#[test] -fn data_shape() { - run_section("data_shape", |case| match text(case, "mode") { +fn eval_data_shape() -> Outcomes { + eval_section("data_shape", |case| match text(case, "mode") { "encode" => { let opts = MakeOptions::new().queue(text(case, "queue")); let env = match make(text(case, "urn"), &case["data"], opts) { @@ -351,14 +397,13 @@ fn data_shape() { } } other => vec![format!("unknown data_shape mode {other:?}")], - }); + }) } /// `forbidden_keys` (K-15): decode succeeds with a warning naming the key, and a re-encode never /// emits it. -#[test] -fn forbidden_keys() { - run_section("forbidden_keys", |case| { +fn eval_forbidden_keys() -> Outcomes { + eval_section("forbidden_keys", |case| { if text(case, "expect") != "warn" { return vec![format!("unsupported expect {}", case["expect"])]; } @@ -387,14 +432,13 @@ fn forbidden_keys() { Err(e) => v.push(e), } v - }); + }) } /// `extension_write`: the producer `meta` write API lands each entry in `meta`, and the entries /// survive a decode -> attempts + 1 -> encode retry hop. -#[test] -fn extension_write() { - run_section("extension_write", |case| { +fn eval_extension_write() -> Outcomes { + eval_section("extension_write", |case| { let mut opts = MakeOptions::new().queue(text(case, "queue")); for (key, value) in case["meta"].as_object().expect("meta object") { opts = opts.meta(key, value); @@ -430,14 +474,13 @@ fn extension_write() { Err(e) => v.push(e), } v - }); + }) } /// `encode_reject`: a forbidden or core-colliding key fails the producer/encode path with an error /// and no envelope JSON is produced. -#[test] -fn encode_reject() { - run_section("encode_reject", |case| { +fn eval_encode_reject() -> Outcomes { + eval_section("encode_reject", |case| { if text(case, "expect") != "reject" { return vec![format!("unsupported expect {}", case["expect"])]; } @@ -489,14 +532,13 @@ fn encode_reject() { "rejected, but the error does not name {offending}: {e}" )], } - }); + }) } /// `trim` (ADR-0032 section 5): the closed ASCII whitespace set trims on `make` and decides blank on /// decode/accepts; re-emit never trims. -#[test] -fn trim() { - run_section("trim", |case| match text(case, "mode") { +fn eval_trim() -> Outcomes { + eval_section("trim", |case| match text(case, "mode") { "make" => { let mut opts = MakeOptions::new(); if let Some(trace_id) = case.get("trace_id").and_then(Value::as_str) { @@ -593,14 +635,13 @@ fn trim() { Err(e) => vec![e], }, other => vec![format!("unknown trim mode {other:?}")], - }); + }) } /// `job_type` (ADR-0032 section 6): a `job` that is not a string is ignored with a warning and the /// identity falls back to a string `urn`; without a valid identity decode fails. -#[test] -fn job_type() { - run_section("job_type", |case| { +fn eval_job_type() -> Outcomes { + eval_section("job_type", |case| { let valid = case["valid"].as_bool().expect("valid"); match (decode(&fixture(text(case, "file"))), valid) { (Ok(d), true) => { @@ -630,14 +671,13 @@ fn job_type() { )], (Err(e), true) => vec![format!("decode: {e}")], } - }); + }) } /// `identity_verdict` (ADR-0036 decision 4): the verdict of the core decoder on a raw body. `ok` /// decodes into an envelope with a valid identity; `poison` does not. -#[test] -fn identity_verdict() { - run_section("identity_verdict", |case| { +fn eval_identity_verdict() -> Outcomes { + eval_section("identity_verdict", |case| { let decoded = decode(text(case, "body").as_bytes()); match (text(case, "expect"), decoded) { ("ok", Ok(d)) if !d.envelope().job().is_empty() => vec![], @@ -650,7 +690,493 @@ fn identity_verdict() { )], (other, _) => vec![format!("unknown expect {other:?}")], } - }); + }) +} + +/// `idempotency` (ADR-0022): the dedupe key is `meta.id` verbatim, and each sequence collapses +/// at-least-once deliveries to the expected number of effects. +fn eval_idempotency() -> Outcomes { + let manifest = manifest(); + let section = &manifest["idempotency"]; + let mut outcomes: Outcomes = vec![( + "dedup_key".to_owned(), + idempotency_dedup_key(§ion["dedup_key"]), + )]; + let cases = section["sequences"]["cases"] + .as_array() + .expect("idempotency.sequences.cases"); + assert!(!cases.is_empty(), "idempotency section has no sequences"); + for case in cases { + outcomes.push(( + format!("sequences/{}", name(case)), + idempotency_sequence(case), + )); + } + outcomes +} + +fn idempotency_dedup_key(key: &Value) -> Vec { + let body = fixture(text(key, "envelope_file")); + let env = match decode(&body) { + Ok(d) => d.into_envelope(), + Err(e) => return vec![format!("decode: {e}")], + }; + let store = Arc::new(InMemoryStore::new()); + let handler = idempotency::wrap( + Arc::clone(&store), + |_env: Arc, _d: Arc| async { Ok::<(), HandlerError>(()) }, + ); + let expected = text(key, "expected_key"); + let mut v = Vec::new(); + if let Err(e) = block_on(handler( + Arc::new(env.clone()), + Arc::new(Delivery::new("q", body)), + )) { + v.push(format!("handler: {e}")); + } + // A redelivery of this envelope must hit the key the suite pins. + match block_on(store.seen(expected)) { + Ok(true) => {} + other => v.push(format!( + "seen-set is not keyed on meta.id {expected:?}: {other:?}" + )), + } + if env.meta().id() != expected { + v.push(format!( + "meta.id = {:?}, want {expected:?}", + env.meta().id() + )); + } + v +} + +/// An envelope whose only interesting member is `meta.id`, decoded from a literal body. +fn envelope_with_id(id: &str) -> Envelope { + let id = serde_json::to_string(id).expect("id as JSON"); + let body = format!( + r#"{{"job":"urn:conformance:idempotency","trace_id":"t","data":{{}},"meta":{{"id":{id},"queue":"q","lang":"rust","schema_version":1,"created_at":1}},"attempts":0}}"# + ); + decode(body.as_bytes()).expect("decode").into_envelope() +} + +fn idempotency_sequence(case: &Value) -> Vec { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; + + let store = Arc::new(InMemoryStore::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let invoked = Arc::new(AtomicBool::new(false)); + let throwing = Arc::new(AtomicBool::new(false)); + let handler = { + let (effects, invoked, throwing) = ( + Arc::clone(&effects), + Arc::clone(&invoked), + Arc::clone(&throwing), + ); + idempotency::wrap( + Arc::clone(&store), + move |_env: Arc, _d: Arc| { + let (effects, invoked, throwing) = ( + Arc::clone(&effects), + Arc::clone(&invoked), + Arc::clone(&throwing), + ); + async move { + // An effect is every handler invocation: a throwing handler's side effect fired + // too (the id just stays unmarked). + invoked.store(true, SeqCst); + effects.fetch_add(1, SeqCst); + if throwing.load(SeqCst) { + Err(HandlerError::msg("conformance handler failure")) + } else { + Ok(()) + } + } + }, + ) + }; + let mut v = Vec::new(); + for (i, delivery) in case["deliveries"] + .as_array() + .expect("deliveries") + .iter() + .enumerate() + { + let id = text(delivery, "meta_id"); + if delivery.get("forget_before").and_then(Value::as_bool) == Some(true) { + if let Err(e) = block_on(store.forget(id)) { + v.push(format!("delivery {i}: forget: {e}")); + } + } + let outcome = delivery + .get("outcome") + .and_then(Value::as_str) + .unwrap_or("ok"); + throwing.store(outcome == "throw", SeqCst); + invoked.store(false, SeqCst); + let result = block_on(handler( + Arc::new(envelope_with_id(id)), + Arc::new(Delivery::new("q", Vec::new())), + )); + let want_run = text(delivery, "expect_effect") == "run"; + if invoked.load(SeqCst) != want_run { + v.push(format!( + "delivery {i}: handler invoked = {}, want {want_run}", + invoked.load(SeqCst) + )); + } + if want_run && outcome == "throw" && result.is_ok() { + v.push(format!( + "delivery {i}: a throwing handler must propagate its error" + )); + } + if (!want_run || outcome == "ok") && result.is_err() { + v.push(format!("delivery {i}: unexpected error {result:?}")); + } + } + let want = case["expected_effects"].as_u64().expect("expected_effects"); + if effects.load(SeqCst) as u64 != want { + v.push(format!("effects = {}, want {want}", effects.load(SeqCst))); + } + v +} + +fn parse_schema(schema: &Value) -> Result { + Schema::parse(&serde_json::to_vec(schema).expect("schema as JSON")).map_err(|e| e.to_string()) +} + +/// `payload_schema` and `payload_schema_unicode` (ADR-0024): one shared `schema`, each case's +/// `data` must get the case's `valid` verdict. +fn eval_shared_schema(section: &str) -> Outcomes { + let manifest = manifest(); + let schema = match parse_schema(&manifest[section]["schema"]) { + Ok(s) => s, + Err(e) => return vec![(section.to_owned(), vec![format!("parse schema: {e}")])], + }; + eval_section(section, |case| { + let errors = schema.validate(&case["data"]); + let want = case["valid"].as_bool().expect("valid"); + if errors.is_empty() == want { + vec![] + } else { + vec![format!( + "valid = {}, want {want} (errors: {errors:?})", + errors.is_empty() + )] + } + }) +} + +fn eval_payload_schema() -> Outcomes { + eval_shared_schema("payload_schema") +} + +fn eval_payload_schema_unicode() -> Outcomes { + eval_shared_schema("payload_schema_unicode") +} + +/// `payload_schema_keywords` (ADR-0024): every case carries its own schema; it passes when both +/// the verdict and the registration warnings (compared as a multiset of `{pointer, keyword}`, never +/// the message text) match. +fn eval_payload_schema_keywords() -> Outcomes { + eval_section("payload_schema_keywords", |case| { + let schema = match parse_schema(&case["schema"]) { + Ok(s) => s, + Err(e) => return vec![format!("parse schema: {e}")], + }; + let mut v = Vec::new(); + let errors = schema.validate(&case["data"]); + let want = case["valid"].as_bool().expect("valid"); + if errors.is_empty() != want { + v.push(format!( + "valid = {}, want {want} (errors: {errors:?})", + errors.is_empty() + )); + } + let mut got: Vec<(String, String)> = schema + .warnings() + .iter() + .map(|w| (w.pointer.clone(), w.keyword.clone())) + .collect(); + let mut expected: Vec<(String, String)> = case + .get("warnings") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|w| (text(w, "pointer").to_owned(), text(w, "keyword").to_owned())) + .collect(); + got.sort(); + expected.sort(); + if got != expected { + v.push(format!("warnings = {got:?}, want {expected:?}")); + } + v + }) +} + +/// `retry_backoff` (ADR-0034 section 9): `d(n) = min(max, base * multiplier^(n-1))`; with +/// `retry_jitter: none` the delay is exact, with `full` it stays within `[min, max]` over a few +/// draws. +fn eval_retry_backoff() -> Outcomes { + eval_section("retry_backoff", |case| { + let secs = |key: &str| { + case[key] + .as_f64() + .unwrap_or_else(|| panic!("{key}: {case}")) + }; + let jitter = match text(case, "retry_jitter") { + "none" => Jitter::None, + "full" => Jitter::Full, + other => return vec![format!("unknown retry_jitter {other:?}")], + }; + let backoff = Backoff::new(Duration::from_secs_f64(secs("retry_backoff"))) + .multiplier(secs("retry_backoff_multiplier")) + .max(Duration::from_secs_f64(secs("retry_backoff_max"))) + .jitter(jitter); + let n = case["n"].as_u64().expect("n"); + let mut v = Vec::new(); + if let Some(want) = case.get("expect_delay_seconds").and_then(Value::as_f64) { + let got = backoff.delay(n).as_secs_f64(); + if (got - want).abs() > 1e-9 { + v.push(format!("delay = {got}s, want {want}s")); + } + } + if let Some(range) = case.get("expect_delay_range_seconds") { + let (min, max) = ( + range["min"].as_f64().unwrap(), + range["max"].as_f64().unwrap(), + ); + for _ in 0..8 { + let got = backoff.delay(n).as_secs_f64(); + if got < min - 1e-9 || got > max + 1e-9 { + v.push(format!("delay = {got}s outside [{min}, {max}]")); + } + } + } + v + }) +} + +/// Standard base64 decoding for `body_base64` (the suite uses padded RFC 4648 section 4 text). +fn base64_decode(text: &str) -> Vec { + let value = |c: u8| match c { + b'A'..=b'Z' => u32::from(c - b'A'), + b'a'..=b'z' => u32::from(c - b'a') + 26, + b'0'..=b'9' => u32::from(c - b'0') + 52, + b'+' => 62, + b'/' => 63, + other => panic!("not base64: {other}"), + }; + let bytes: Vec = text.bytes().filter(|c| *c != b'=').collect(); + let mut out = Vec::new(); + for chunk in bytes.chunks(4) { + let n = chunk.iter().fold(0u32, |acc, c| (acc << 6) | value(*c)) << (6 * (4 - chunk.len())); + let produced = chunk.len() * 6 / 8; + out.extend_from_slice(&n.to_be_bytes()[1..=produced]); + } + out +} + +/// The top-level members of a JSON object as `(unescaped key, raw value text)`, read by an +/// iterative scanner so a repeated member, an out-of-range number or very deep nesting cannot trip +/// it. The text must be a valid object (the record under test is checked for that by the SDK's own +/// strict scan); `None` when it does not even look like one. +fn top_level_members(record: &str) -> Option> { + let b = record.as_bytes(); + let skip_ws = |mut i: usize| { + while b + .get(i) + .is_some_and(|c| matches!(c, b' ' | b'\t' | b'\r' | b'\n')) + { + i += 1; + } + i + }; + let string_end = |start: usize| { + let mut i = start + 1; + while *b.get(i)? != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + Some(i + 1) + }; + let mut i = skip_ws(0); + if b.get(i) != Some(&b'{') { + return None; + } + i = skip_ws(i + 1); + let mut members = Vec::new(); + if b.get(i) == Some(&b'}') { + return Some(members); + } + loop { + if b.get(i) != Some(&b'"') { + return None; + } + let key_end = string_end(i)?; + let key: String = serde_json::from_str(&record[i..key_end]).ok()?; + i = skip_ws(key_end); + if b.get(i) != Some(&b':') { + return None; + } + i = skip_ws(i + 1); + let value_start = i; + let mut depth = 0usize; + loop { + match *b.get(i)? { + b'"' => { + i = string_end(i)?; + continue; + } + b'{' | b'[' => depth += 1, + b'}' | b']' if depth > 0 => depth -= 1, + b',' | b'}' if depth == 0 => break, + _ => {} + } + i += 1; + } + members.push((key, record[value_start..i].trim_end().to_owned())); + match b[i] { + b',' => i = skip_ws(i + 1), + _ => return Some(members), + } + } +} + +/// `poison_dlq` (ADR-0035): the DLQ record written for a poison body has the specified shape. +fn eval_poison_dlq() -> Outcomes { + let manifest = manifest(); + let original_queue = text(&manifest["poison_dlq"], "original_queue").to_owned(); + eval_section("poison_dlq", |case| { + let body = match case.get("body_base64").and_then(Value::as_str) { + Some(encoded) => base64_decode(encoded), + None => text(case, "body").as_bytes().to_vec(), + }; + let cause = FailureCause::new("poison", "conformance"); + let record = poison_dead_letter_body(&body, &original_queue, 0, Some(&cause)); + let Ok(record) = String::from_utf8(record) else { + return vec!["record is not valid UTF-8".to_owned()]; + }; + let Some(members) = top_level_members(&record) else { + return vec![format!("record is not a JSON object: {record}")]; + }; + let mut v = Vec::new(); + // (1) a top-level dead_letter object with reason poison and the original queue. + let block = members + .iter() + .rev() + .find(|(k, _)| k == "dead_letter") + .and_then(|(_, raw)| serde_json::from_str::(raw).ok()); + match &block { + Some(b) + if b["reason"] == "poison" && b["original_queue"] == original_queue.as_str() => {} + other => v.push(format!( + "dead_letter = {other:?}, want reason poison and original_queue {original_queue:?}" + )), + } + // (2) without dead_letter, the rest equals expect.record as parsed JSON. + let expect = &case["expect"]; + let want = &expect["record"]; + let parsed = serde_json::from_str::(&record).ok().map(|mut doc| { + if let Some(o) = doc.as_object_mut() { + o.remove("dead_letter"); + } + doc + }); + match text(expect, "shape") { + "splice_or_wrapper" => { + if parsed.as_ref() == Some(want) { + return v; // the wrapper + } + // Otherwise a byte-level splice that passes three structural checks. + for literal in expect["splice_literals"] + .as_array() + .expect("splice_literals") + { + let literal = literal.as_str().expect("literal"); + if !record.contains(literal) { + v.push(format!("record does not contain {literal:?} verbatim")); + } + } + let keys: BTreeSet<&str> = members.iter().map(|(k, _)| k.as_str()).collect(); + if keys.contains("raw") || keys.contains("raw_encoding") { + v.push("spliced record has a top-level raw or raw_encoding member".to_owned()); + } + let mut want_keys: BTreeSet<&str> = expect["splice_keys"] + .as_array() + .expect("splice_keys") + .iter() + .filter_map(Value::as_str) + .collect(); + want_keys.insert("dead_letter"); + if keys != want_keys { + v.push(format!("top-level members = {keys:?}, want {want_keys:?}")); + } + } + _ => { + if parsed.as_ref() != Some(want) { + v.push(format!( + "record without dead_letter = {parsed:?}, want {want}" + )); + } + } + } + v + }) +} + +// --------------------------------------------------------------------------------------------- +// The core sections as a table +// --------------------------------------------------------------------------------------------- + +/// The runner of a `core`-scope section, by manifest name. +fn core_runner(section: &str) -> Option Outcomes> { + Some(match section { + "cases" => eval_cases, + "roundtrip" => eval_roundtrip, + "data_shape" => eval_data_shape, + "forbidden_keys" => eval_forbidden_keys, + "extension_write" => eval_extension_write, + "encode_reject" => eval_encode_reject, + "trim" => eval_trim, + "job_type" => eval_job_type, + "identity_verdict" => eval_identity_verdict, + "idempotency" => eval_idempotency, + "payload_schema" => eval_payload_schema, + "payload_schema_unicode" => eval_payload_schema_unicode, + "payload_schema_keywords" => eval_payload_schema_keywords, + "retry_backoff" => eval_retry_backoff, + "poison_dlq" => eval_poison_dlq, + _ => return None, + }) +} + +/// One `#[test]` per section, named after it. +macro_rules! section_tests { + ($($name:ident => $eval:ident),+ $(,)?) => { + $( + #[test] + fn $name() { + assert_clean(stringify!($name), &$eval()); + } + )+ + }; +} + +section_tests! { + cases => eval_cases, + roundtrip => eval_roundtrip, + data_shape => eval_data_shape, + forbidden_keys => eval_forbidden_keys, + extension_write => eval_extension_write, + encode_reject => eval_encode_reject, + trim => eval_trim, + job_type => eval_job_type, + identity_verdict => eval_identity_verdict, + idempotency => eval_idempotency, + payload_schema => eval_payload_schema, + payload_schema_unicode => eval_payload_schema_unicode, + payload_schema_keywords => eval_payload_schema_keywords, + retry_backoff => eval_retry_backoff, + poison_dlq => eval_poison_dlq, } // --------------------------------------------------------------------------------------------- @@ -660,7 +1186,7 @@ fn identity_verdict() { enum Status { /// Run by a test in this file. Pass, - /// Core scope, but part of a later phase of the plan (the runtime). + /// In scope for 0.1 but part of a later phase of the plan. Pending(&'static str), /// Out of this SDK's scope, with the reason. Skip(&'static str), @@ -669,15 +1195,10 @@ enum Status { fn classify(section: &str) -> Option { use Status::{Pass, Pending, Skip}; const BROKER: &str = "broker binding outside the Rust MVP (Redis only)"; + if core_runner(section).is_some() { + return Some(Pass); + } Some(match section { - "cases" | "roundtrip" | "data_shape" | "forbidden_keys" | "extension_write" - | "encode_reject" | "trim" | "job_type" | "identity_verdict" => Pass, - "idempotency" => Pending("idempotency helper, Phase 03 (ADR-0022)"), - "payload_schema" | "payload_schema_unicode" | "payload_schema_keywords" => { - Pending("payload-schema subset, Phase 03 (ADR-0024)") - } - "retry_backoff" => Pending("retry backoff, Phase 03 (ADR-0034 section 9)"), - "poison_dlq" => Pending("poison routing and DLQ block, Phase 03 (ADR-0035/0036/0037)"), "redis" | "redis_layout" | "redis_delay" => Pending("babelqueue-redis, Phase 04"), "sqs" | "delay" | "version_gate_sqs" => { Skip("Amazon SQS binding: no Rust transport in 0.1") @@ -728,7 +1249,7 @@ fn manifest_sections_are_all_classified() { .keys() .filter(|s| matches!(classify(s), Some(Status::Pass))) { - assert!(!section_cases(section).is_empty()); + assert!(!manifest_case_ids(&manifest, section).is_empty()); } } @@ -758,3 +1279,136 @@ fn runner_reports_violations() { 1 ); } + +// --------------------------------------------------------------------------------------------- +// results.json +// --------------------------------------------------------------------------------------------- + +/// The bindings this workspace carries, derived from its transport crates and never hand-listed: a +/// crate in `crates/` that maps to a binding counts once it ships a conformance runner +/// (`tests/conformance.rs`) for that binding's sections. +fn derive_bindings() -> Vec { + const TRANSPORT_CRATES: [(&str, &str); 4] = [ + ("babelqueue-redis", "redis"), + ("babelqueue-rabbitmq", "amqp"), + ("babelqueue-kafka", "kafka"), + ("babelqueue-otel", "otel"), + ]; + let crates_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut bindings: Vec = TRANSPORT_CRATES + .iter() + .filter(|(dir, _)| crates_dir.join(dir).join("tests/conformance.rs").is_file()) + .map(|(_, binding)| (*binding).to_owned()) + .collect(); + bindings.sort(); + bindings +} + +/// Runs every in-scope section case by case, writes `results.json` when `BQ_CONFORMANCE_RESULTS` +/// names a path, and fails on a failed case, a missing section or case, or a document that violates +/// the results schema. The file is written first, so a failing run still leaves it behind. +#[test] +fn results_json() { + let manifest = manifest(); + let version = fs::read_to_string(suite_dir().join("CONFORMANCE_VERSION")) + .map(|v| v.trim().to_owned()) + .unwrap_or_else(|_| { + manifest["conformance_version"] + .as_str() + .unwrap_or("") + .to_owned() + }); + let mut results = Results::new( + "babelqueue-rust/babelqueue", + env!("CARGO_PKG_VERSION"), + version, + ); + results.bindings = derive_bindings(); + let mut carried: BTreeSet = results.bindings.iter().cloned().collect(); + carried.insert("core".to_owned()); + + let mut problems = Vec::new(); + let sections = manifest["sections"].as_object().expect("manifest.sections"); + for (section, info) in sections { + let scope = info["scope"].as_str().expect("scope"); + if !carried.contains(scope) { + continue; + } + let Some(run) = core_runner(section) else { + problems.push(format!( + "compliance gap: section {section:?} (scope {scope:?}) is in scope but has no runner" + )); + continue; + }; + let outcomes = run(); + let ran: BTreeSet<&str> = outcomes.iter().map(|(id, _)| id.as_str()).collect(); + let ids = manifest_case_ids(&manifest, section); + let want: BTreeSet<&str> = ids.iter().map(String::as_str).collect(); + if ran != want || outcomes.len() != ids.len() { + problems.push(format!( + "section {section:?}: ran {} cases, the manifest defines {} (missing {:?}, extra {:?})", + outcomes.len(), + ids.len(), + want.difference(&ran).collect::>(), + ran.difference(&want).collect::>() + )); + } + for (id, violations) in outcomes { + let result = if violations.is_empty() { + CaseResult::pass() + } else { + problems.push(format!( + "conformance fail: {section}/{id}: {}", + violations.join("; ") + )); + CaseResult::fail(violations.join("; ")) + }; + results.record(section, &id, result); + } + } + + if let Ok(path) = std::env::var("BQ_CONFORMANCE_RESULTS") { + if !path.is_empty() { + results + .write(std::path::Path::new(&path)) + .expect("write results.json"); + let cases: usize = results.sections.values().map(|s| s.len()).sum(); + println!( + "wrote {path}: {} sections, {cases} cases, bindings {:?}", + results.sections.len(), + results.bindings + ); + } + } + problems.extend(results.schema_violations()); + problems.extend(schema_drift(&results)); + assert!(problems.is_empty(), "{}", problems.join("\n")); +} + +/// Guards the in-code schema check against drifting from the vendored `results.schema.json`: the +/// document's members must be exactly the schema's required, closed set. +fn schema_drift(results: &Results) -> Vec { + let raw = fs::read(suite_dir().join("schema/results.schema.json")).expect("results schema"); + let schema: Value = serde_json::from_slice(&raw).expect("parse results schema"); + let doc = results.to_json(); + let doc = doc.as_object().expect("results document"); + let mut v = Vec::new(); + for required in schema["required"].as_array().expect("required") { + let key = required.as_str().expect("required key"); + if !doc.contains_key(key) { + v.push(format!("results.json lacks required member {key:?}")); + } + } + let known = schema["properties"].as_object().expect("properties"); + for key in doc.keys() { + if !known.contains_key(key) { + v.push(format!( + "results.json has member {key:?} the schema does not allow" + )); + } + } + if schema["additionalProperties"] != json!(false) { + v.push("the results schema is no longer closed; revisit schema_violations".to_owned()); + } + v +} From f7477aaacc36822b583dd7b1792da1a5eb651f1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Fri, 4 Dec 2026 20:02:25 +0300 Subject: [PATCH 3/4] feat(redis): Redis transport with Laravel zset layout by default and legacy reliable queue Adds babelqueue-redis on the redis crate with tokio: publisher and consumer for the zset layout (Laravel pop script, delay, retry_after recovery) and the legacy reliable-queue layout, a pooled blocking connection so concurrent pops do not starve, poison routing for invalid UTF-8, and a CI redis job. Core and redis conformance runs now merge into one results.json that a check script validates against the manifest and the workspace bindings. --- .github/workflows/ci.yml | 77 +- Cargo.lock | 832 ++++++++++++++++- crates/babelqueue-redis/Cargo.toml | 17 +- crates/babelqueue-redis/src/error.rs | 41 + crates/babelqueue-redis/src/frame.rs | 137 +++ crates/babelqueue-redis/src/keys.rs | 113 +++ crates/babelqueue-redis/src/lib.rs | 53 +- crates/babelqueue-redis/src/options.rs | 166 ++++ crates/babelqueue-redis/src/scripts.rs | 175 ++++ crates/babelqueue-redis/src/transport.rs | 822 +++++++++++++++++ crates/babelqueue-redis/tests/conformance.rs | 922 +++++++++++++++++++ crates/babelqueue-redis/tests/live.rs | 736 +++++++++++++++ crates/babelqueue/tests/conformance.rs | 63 +- deny.toml | 2 + scripts/check-conformance-results.py | 135 +++ scripts/merge-conformance-results.py | 97 ++ 16 files changed, 4352 insertions(+), 36 deletions(-) create mode 100644 crates/babelqueue-redis/src/error.rs create mode 100644 crates/babelqueue-redis/src/frame.rs create mode 100644 crates/babelqueue-redis/src/keys.rs create mode 100644 crates/babelqueue-redis/src/options.rs create mode 100644 crates/babelqueue-redis/src/scripts.rs create mode 100644 crates/babelqueue-redis/src/transport.rs create mode 100644 crates/babelqueue-redis/tests/conformance.rs create mode 100644 crates/babelqueue-redis/tests/live.rs create mode 100755 scripts/check-conformance-results.py create mode 100755 scripts/merge-conformance-results.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb26754..e345ed2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,21 +39,37 @@ jobs: RUSTDOCFLAGS: -D warnings test: - name: Test (${{ matrix.toolchain }}) + name: Test (${{ matrix.name }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: - # `msrv` resolves to the workspace `rust-version`. - toolchain: [ stable, msrv ] + include: + # The whole workspace on stable. No broker here: the live Redis tests skip (the `redis` job + # runs them with a broker and BQ_REQUIRE_REDIS). + - name: stable + toolchain: stable + manifest: Cargo.toml + command: cargo test --workspace --all-features --locked + # Each crate on its own floor: `msrv` resolves to the `rust-version` of the manifest. The + # core stays at the workspace floor; `babelqueue-redis` sets a higher one (the `redis` + # crate's), so its leg builds it, tests included, without running them against a broker. + - name: msrv core + toolchain: msrv + manifest: Cargo.toml + command: cargo test -p babelqueue --locked + - name: msrv redis + toolchain: msrv + manifest: crates/babelqueue-redis/Cargo.toml + command: cargo test -p babelqueue-redis --all-features --locked --no-run steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Resolve toolchain id: tc run: | if [ "${{ matrix.toolchain }}" = "msrv" ]; then - v="$(sed -n 's/^rust-version *= *"\(.*\)"/\1/p' Cargo.toml | head -n1)" - [ -n "$v" ] || { echo "rust-version not found in Cargo.toml" >&2; exit 1; } + v="$(sed -n 's/^rust-version *= *"\(.*\)"/\1/p' "${{ matrix.manifest }}" | head -n1)" + [ -n "$v" ] || { echo "rust-version not found in ${{ matrix.manifest }}" >&2; exit 1; } else v="${{ matrix.toolchain }}" fi @@ -62,8 +78,53 @@ jobs: run: rustup toolchain install "${{ steps.tc.outputs.version }}" --profile minimal && rustup default "${{ steps.tc.outputs.version }}" - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 with: - key: ${{ matrix.toolchain }} - - run: cargo test --workspace --all-features --locked + key: ${{ matrix.name }} + - run: ${{ matrix.command }} + + redis: + name: Redis (live broker) and results.json + runs-on: ubuntu-latest + # The redis conformance sections and the live tests need a real broker: BQ_REQUIRE_REDIS makes a + # missing one fail instead of letting the cases skip (broker-bindings section 1, runner contract). + services: + redis: + image: redis:7 + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s --health-timeout 3s --health-retries 5 + env: + REDIS_URL: redis://localhost:6379/0 + BQ_REQUIRE_REDIS: "1" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - name: Install stable toolchain + run: rustup toolchain install stable --profile minimal && rustup default stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 + # Every crate with a conformance runner writes the sections it ran to a file of its own + # (BQ_CONFORMANCE_RESULTS); merge-conformance-results.py joins them and derives `bindings` + # from the crates in the tree. + - name: Core conformance (partial results) + run: cargo test -p babelqueue --all-features --locked --test conformance + env: + BQ_CONFORMANCE_RESULTS: ${{ runner.temp }}/results/core.json + - name: Redis tests, live and conformance (partial results) + run: cargo test -p babelqueue-redis --all-features --locked + env: + BQ_CONFORMANCE_RESULTS: ${{ runner.temp }}/results/redis.json + - name: Merge results.json (ADR-0032) + run: | + python3 scripts/merge-conformance-results.py "$RUNNER_TEMP/results.json" \ + "$RUNNER_TEMP/results/core.json" "$RUNNER_TEMP/results/redis.json" + # Schema-valid, no `fail`, bindings derived from the crates in the tree, and every in-scope + # section and case present: a transport crate without its sections breaks CI. + - name: Validate results.json + run: | + python3 -m venv "$RUNNER_TEMP/venv" + "$RUNNER_TEMP/venv/bin/pip" install --quiet jsonschema==4.23.0 + "$RUNNER_TEMP/venv/bin/python" -I scripts/check-conformance-results.py \ + "$RUNNER_TEMP/results.json" testdata/conformance "$BQ_CONFORMANCE_VERSION" conformance: name: Conformance suite in sync @@ -91,7 +152,7 @@ jobs: ci-green: name: CI green runs-on: ubuntu-latest - needs: [lint, test, conformance, deny] + needs: [lint, test, redis, conformance, deny] if: ${{ always() }} steps: - name: Fail if any required job did not pass diff --git a/Cargo.lock b/Cargo.lock index e7cc5f1..0d7cf39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,6 +23,32 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7" +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arcstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -34,7 +60,7 @@ name = "babelqueue" version = "0.1.0" dependencies = [ "criterion", - "getrandom", + "getrandom 0.3.4", "serde", "serde_json", ] @@ -44,14 +70,50 @@ name = "babelqueue-redis" version = "0.1.0" dependencies = [ "babelqueue", + "getrandom 0.3.4", + "redis", + "serde_json", + "tokio", + "tracing", ] +[[package]] +name = "backon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa51bf3329e243b4ceebb25fddaa797b3e2d225c733b215548ffd1fa99294d5d" +dependencies = [ + "fastrand", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cast" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "cc" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b4e5299ae8fd0d9e848f3efafd5b4feed729b8c731df9d62375cb1efdc3f4e" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -110,6 +172,36 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "criterion" version = "0.7.0" @@ -147,12 +239,115 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "either" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f35b0b9b788e7109a8eb0607f5c8a13495edee3ef8e246f60f0664a7cd25b277" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[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-core", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -176,6 +371,108 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "itertools" version = "0.13.0" @@ -197,12 +494,29 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -212,12 +526,51 @@ dependencies = [ "autocfg", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "oorandom" version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -242,6 +595,36 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "redis" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85db9332bbc47e826283f0a6058d747c478ed2278976279cefd22154d541b98" +dependencies = [ + "arc-swap", + "arcstr", + "async-lock", + "backon", + "bytes", + "cfg-if", + "combine", + "futures-channel", + "futures-util", + "itoa", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "ryu", + "sha1_smol", + "socket2", + "tokio", + "tokio-rustls", + "tokio-util", + "url", + "xxhash-rust", +] + [[package]] name = "regex" version = "1.13.2" @@ -271,6 +654,77 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86c8de8f13bac4bb046743409c751e2343621c0293a805c143ede57c5c95c3f8" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -280,6 +734,38 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.229" @@ -323,6 +809,52 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -345,6 +877,27 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -355,12 +908,113 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[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 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "walkdir" version = "2.5.1" @@ -371,6 +1025,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.1+wasi-0.2.4" @@ -386,7 +1046,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -395,6 +1055,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -404,12 +1073,111 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "wit-bindgen" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.66" @@ -430,6 +1198,66 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/babelqueue-redis/Cargo.toml b/crates/babelqueue-redis/Cargo.toml index b48e9b9..4c02520 100644 --- a/crates/babelqueue-redis/Cargo.toml +++ b/crates/babelqueue-redis/Cargo.toml @@ -4,7 +4,9 @@ description = "BabelQueue Redis transport (broker-bindings section 1) for Rust." readme = "../../README.md" version.workspace = true edition.workspace = true -rust-version.workspace = true +# The `redis` crate sets this floor (1.88), above the core's 1.85. Re-verify with `cargo msrv` +# whenever a dependency changes; an MSRV bump is a MINOR (ADR-0041 decision 7). +rust-version = "1.88" license.workspace = true authors.workspace = true repository.workspace = true @@ -12,8 +14,21 @@ homepage.workspace = true keywords.workspace = true categories.workspace = true +[features] +default = [] +# TLS for `rediss://` URLs, through rustls (no C toolchain). +tls-rustls = ["redis/tokio-rustls-comp"] + [dependencies] babelqueue = { version = "0.1.0", path = "../babelqueue" } +getrandom.workspace = true +serde_json.workspace = true +redis = { version = "1.8", default-features = false, features = ["tokio-comp", "connection-manager", "script"] } +tokio = { version = "1", default-features = false, features = ["time"] } +tracing = { version = "0.1", default-features = false, features = ["std"] } + +[dev-dependencies] +tokio = { version = "1", default-features = false, features = ["macros", "rt-multi-thread", "time", "sync"] } [lints] workspace = true diff --git a/crates/babelqueue-redis/src/error.rs b/crates/babelqueue-redis/src/error.rs new file mode 100644 index 0000000..84ee1d1 --- /dev/null +++ b/crates/babelqueue-redis/src/error.rs @@ -0,0 +1,41 @@ +//! Errors of this crate that are not the Redis client's. + +use std::error::Error; +use std::fmt; + +/// An operation the configured layout, or the given input, cannot do. It reaches the caller wrapped +/// in a [`TransportError`](babelqueue::TransportError). +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum UsageError { + /// Delayed publishing needs the zset layout: the legacy layout has no delayed set. + DelayNeedsZsetLayout, + /// A body with headers must be UTF-8 to ride inside the legacy header frame. + HeadersNeedUtf8Body, + /// The delivery was not reserved by a Redis transport. + ForeignDelivery, + /// The system random source failed while making a reservation token. + Random(String), + /// Redis answered a reserve with something that is not `{job, reserved}`. + UnexpectedReply(String), +} + +impl fmt::Display for UsageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DelayNeedsZsetLayout => { + f.write_str("babelqueue-redis: delayed publish needs the zset layout") + } + Self::HeadersNeedUtf8Body => { + f.write_str("babelqueue-redis: a body with headers must be valid UTF-8") + } + Self::ForeignDelivery => { + f.write_str("babelqueue-redis: the delivery was not reserved by a Redis transport") + } + Self::Random(e) => write!(f, "babelqueue-redis: random source failed: {e}"), + Self::UnexpectedReply(r) => write!(f, "babelqueue-redis: unexpected reserve reply {r}"), + } + } +} + +impl Error for UsageError {} diff --git a/crates/babelqueue-redis/src/frame.rs b/crates/babelqueue-redis/src/frame.rs new file mode 100644 index 0000000..32c98f0 --- /dev/null +++ b/crates/babelqueue-redis/src/frame.rs @@ -0,0 +1,137 @@ +//! The transport-owned header frame of the legacy layout (ADR-0028). +//! +//! A Redis list value has no metadata channel, so out-of-band headers (a W3C `traceparent`, the +//! replay-bypass marker) ride in a small JSON frame that is not the wire envelope: +//! +//! ```text +//! {"__bq_frame":1,"headers":{"traceparent":"00-..."},"body":""} +//! ``` +//! +//! The frozen envelope never carries `__bq_frame`, so its presence tells a frame from a bare +//! envelope. The frame is written only when there are headers; a plain publish stores the bare +//! envelope byte for byte. The zset layout forbids the frame (it would break Laravel workers and +//! the pop script's `cjson` decode), so headers are dropped there. + +use std::collections::HashMap; + +use serde_json::{Map, Value, json}; + +const SENTINEL: &[u8] = b"\"__bq_frame\""; + +/// The value to push for `body` and `headers`: the body verbatim when no header survives (blank +/// keys and blank values are dropped), the frame otherwise. `None` when headers are present but +/// the body is not UTF-8 and so cannot ride inside a JSON string. +pub(crate) fn frame_value(body: &[u8], headers: &HashMap) -> Option> { + let clean: Map = headers + .iter() + .filter(|(k, v)| !k.is_empty() && !v.is_empty()) + .map(|(k, v)| (k.clone(), Value::String(v.clone()))) + .collect(); + if clean.is_empty() { + return Some(body.to_vec()); + } + let body = std::str::from_utf8(body).ok()?; + serde_json::to_vec(&json!({"__bq_frame": 1, "headers": clean, "body": body})).ok() +} + +/// Interprets a stored list value: a frame yields its body and headers, anything else (a bare +/// envelope, a non-JSON value, JSON without the sentinel) is the body with no headers, so queues +/// written by an older version consume unchanged. +pub(crate) fn unframe(value: &[u8]) -> (Vec, HashMap) { + if value.first() != Some(&b'{') || !value.windows(SENTINEL.len()).any(|w| w == SENTINEL) { + return (value.to_vec(), HashMap::new()); + } + let Ok(Value::Object(frame)) = serde_json::from_slice::(value) else { + return (value.to_vec(), HashMap::new()); + }; + let is_frame = frame + .get("__bq_frame") + .and_then(Value::as_f64) + .is_some_and(|v| v != 0.0); + let Some(Value::String(body)) = frame.get("body").filter(|_| is_frame) else { + return (value.to_vec(), HashMap::new()); + }; + let headers = frame + .get("headers") + .and_then(Value::as_object) + .map(|h| { + h.iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))) + .filter(|(k, v)| !k.is_empty() && !v.is_empty()) + .collect() + }) + .unwrap_or_default(); + (body.clone().into_bytes(), headers) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ENVELOPE: &[u8] = + br#"{"job":"urn:acme:a","trace_id":"t","data":{},"meta":{},"attempts":0}"#; + + fn headers(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect() + } + + #[test] + fn no_headers_stores_the_bare_envelope_byte_for_byte() { + assert_eq!(frame_value(ENVELOPE, &HashMap::new()).unwrap(), ENVELOPE); + let blank = headers(&[("", "x"), ("k", "")]); + assert_eq!(frame_value(ENVELOPE, &blank).unwrap(), ENVELOPE); + } + + #[test] + fn headers_round_trip_through_a_frame() { + let h = headers(&[("traceparent", "00-aa-bb-01")]); + let stored = frame_value(ENVELOPE, &h).unwrap(); + assert!(stored.starts_with(b"{\"__bq_frame\":1")); + let (body, got) = unframe(&stored); + assert_eq!(body, ENVELOPE); + assert_eq!(got, h); + } + + #[test] + fn a_bare_envelope_is_not_a_frame() { + let (body, h) = unframe(ENVELOPE); + assert_eq!(body, ENVELOPE); + assert!(h.is_empty()); + } + + #[test] + fn values_that_only_look_like_frames_stay_bare() { + for value in [ + br#"{"__bq_frame":0,"body":"x"}"#.as_slice(), + br#"{"__bq_frame":1}"#, + br#"{"__bq_frame":1,"body":7}"#, + br#"{"__bq_frame": not json"#, + b"plain text", + b"", + ] { + let (body, h) = unframe(value); + assert_eq!(body, value, "{}", String::from_utf8_lossy(value)); + assert!(h.is_empty()); + } + } + + #[test] + fn a_frame_without_headers_has_an_empty_header_map() { + let (body, h) = unframe(br#"{"__bq_frame":1,"body":"{}"}"#); + assert_eq!(body, b"{}"); + assert!(h.is_empty()); + } + + #[test] + fn headers_cannot_ride_with_a_non_utf8_body() { + let h = headers(&[("k", "v")]); + assert!(frame_value(&[0xff, 0xfe], &h).is_none()); + assert_eq!( + frame_value(&[0xff, 0xfe], &HashMap::new()).unwrap(), + vec![0xff, 0xfe] + ); + } +} diff --git a/crates/babelqueue-redis/src/keys.rs b/crates/babelqueue-redis/src/keys.rs new file mode 100644 index 0000000..85d201e --- /dev/null +++ b/crates/babelqueue-redis/src/keys.rs @@ -0,0 +1,113 @@ +//! Key names and the score formula of broker-bindings section 1. + +use std::time::Duration; + +/// Laravel's default Redis queue key prefix. +pub const DEFAULT_KEY_PREFIX: &str = "queues:"; + +/// The default reservation window (Laravel's `retry_after`, 90 s): a reserved member whose deadline +/// has passed is made ready again. +pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(90); + +/// The Redis key names of one logical queue in the zset layout (broker-bindings section 1.1). +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Keys { + /// The ready list: `RPUSH` on produce, `LPOP` inside the reserve script on consume. + pub ready: String, + /// The delayed set, scored by available-at in epoch seconds (section 1.6). + pub delayed: String, + /// The reserved set of in-flight jobs, scored by the `retry_after` deadline (section 1.7). + pub reserved: String, + /// The blocking-pop wake-up list (section 1.6). + pub notify: String, +} + +/// The Redis key names of one logical queue in the legacy reliable-queue layout (section 1.1). +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct LegacyKeys { + /// The ready list: produce and consume. + pub ready: String, + /// The processing list of in-flight bodies, moved there by the reserve script. + pub processing: String, + /// The sorted set of `:` members scored by the recovery deadline (section 1.7). + pub deadlines: String, +} + +/// The zset-layout key names of `queue` under `prefix` (`queues:` is Laravel's default). +#[must_use] +pub fn zset_keys(prefix: &str, queue: &str) -> Keys { + let ready = format!("{prefix}{queue}"); + Keys { + delayed: format!("{ready}:delayed"), + reserved: format!("{ready}:reserved"), + notify: format!("{ready}:notify"), + ready, + } +} + +/// The legacy-layout key names of `queue`. +#[must_use] +pub fn legacy_keys(queue: &str) -> LegacyKeys { + LegacyKeys { + ready: queue.to_owned(), + processing: format!("{queue}:processing"), + deadlines: format!("{queue}:processing:deadlines"), + } +} + +/// The one score formula of the contract (`redis_delay`): `floor(now) + ceil(delay)`, whole epoch +/// seconds. `now` is fractional epoch seconds from the client clock. The reservation deadline of a +/// reserve is the same function of `retry_after`. +#[must_use] +pub fn delay_score(now: f64, delay: Duration) -> i64 { + let whole = delay + .as_secs() + .saturating_add(u64::from(delay.subsec_nanos() > 0)); + // `as` saturates on overflow and maps NaN to 0, which is the behaviour wanted for a clock. + (now.floor() as i64).saturating_add(i64::try_from(whole).unwrap_or(i64::MAX)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zset_keys_follow_section_1_1() { + let k = zset_keys("queues:", "emails.high"); + assert_eq!(k.ready, "queues:emails.high"); + assert_eq!(k.delayed, "queues:emails.high:delayed"); + assert_eq!(k.reserved, "queues:emails.high:reserved"); + assert_eq!(k.notify, "queues:emails.high:notify"); + } + + #[test] + fn a_custom_prefix_is_used_verbatim() { + assert_eq!(zset_keys("app:", "q").ready, "app:q"); + } + + #[test] + fn legacy_keys_follow_section_1_1() { + let k = legacy_keys("orders"); + assert_eq!(k.ready, "orders"); + assert_eq!(k.processing, "orders:processing"); + assert_eq!(k.deadlines, "orders:processing:deadlines"); + } + + #[test] + fn the_score_is_floor_now_plus_ceil_delay() { + let d = Duration::from_secs_f64; + assert_eq!(delay_score(1000.7, d(1.5)), 1002); + assert_eq!(delay_score(1000.2, d(0.1)), 1001); + assert_eq!(delay_score(1000.5, d(3.0)), 1003); + assert_eq!(delay_score(1000.0, Duration::ZERO), 1000); + assert_eq!(delay_score(1000.0, Duration::from_nanos(1)), 1001); + } + + #[test] + fn a_degenerate_clock_cannot_overflow_the_score() { + assert_eq!(delay_score(f64::NAN, Duration::from_secs(2)), 2); + assert_eq!(delay_score(f64::MAX, Duration::from_secs(2)), i64::MAX); + } +} diff --git a/crates/babelqueue-redis/src/lib.rs b/crates/babelqueue-redis/src/lib.rs index d3bdb1d..25103b7 100644 --- a/crates/babelqueue-redis/src/lib.rs +++ b/crates/babelqueue-redis/src/lib.rs @@ -1,19 +1,48 @@ //! BabelQueue Redis transport (broker-bindings section 1) for Rust. //! -//! This crate is a skeleton; the transport lands in a later phase of the Rust -//! SDK plan (ADR-0041). +//! [`RedisTransport`] implements the core's [`Transport`](babelqueue::Transport) over Redis, with +//! both layouts of section 1.1: +//! +//! * [`Layout::Zset`] (the default): Laravel's `queues:` layout with `:delayed`, `:reserved` +//! and `:notify`, Laravel's pop script, delayed publishing and in-place release. A queue in this +//! layout is shared with Laravel workers and with the other SDKs' zset transports. +//! * [`Layout::Legacy`]: the reliable-queue layout (``, `:processing`, +//! `:processing:deadlines`) with the token-gated settle and the sweep of section 1.7. +//! +//! ```no_run +//! # async fn demo() -> Result<(), Box> { +//! use babelqueue::App; +//! use babelqueue_redis::RedisTransport; +//! +//! let transport = RedisTransport::connect("redis://localhost:6379/0").await?; +//! let app = App::new(transport).queue("orders").with_releaser().with_dead_letter_settler(); +//! # let _ = app; +//! # Ok(()) +//! # } +//! ``` +//! +//! `retry_after` defaults to 90 s (see [`Options::retry_after`]): keep the handler timeout shorter, +//! or a message that is still being processed is recovered and processed twice. Redis Cluster needs +//! a hash tag in the queue name (`{orders}`), chosen by the caller (section 1.5). +//! +//! Enable the `tls-rustls` feature for `rediss://` URLs. #![forbid(unsafe_code)] -/// The core crate's wire `schema_version`, re-exported so the skeleton links the core. -pub const SCHEMA_VERSION: u32 = babelqueue::SCHEMA_VERSION; +mod error; +mod frame; +mod keys; +mod options; +mod scripts; +mod transport; -#[cfg(test)] -mod tests { - use super::*; +pub use error::UsageError; +pub use keys::{ + DEFAULT_KEY_PREFIX, DEFAULT_RETRY_AFTER, Keys, LegacyKeys, delay_score, legacy_keys, zset_keys, +}; +pub use options::{Layout, Options}; +pub use transport::RedisTransport; - #[test] - fn links_the_core() { - assert_eq!(SCHEMA_VERSION, 1); - } -} +/// The Redis client types that appear in this crate's API, re-exported so a caller need not depend +/// on a matching `redis` version to name them. +pub use redis::{Client, RedisError}; diff --git a/crates/babelqueue-redis/src/options.rs b/crates/babelqueue-redis/src/options.rs new file mode 100644 index 0000000..b84c75a --- /dev/null +++ b/crates/babelqueue-redis/src/options.rs @@ -0,0 +1,166 @@ +//! Configuration of a [`RedisTransport`](crate::RedisTransport). + +use std::fmt; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::keys::{DEFAULT_KEY_PREFIX, DEFAULT_RETRY_AFTER}; + +/// Which of the two Redis layouts of broker-bindings section 1.1 a transport speaks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[non_exhaustive] +pub enum Layout { + /// Laravel's layout, canonical and the default here: `queues:` plus `:delayed`, + /// `:reserved` and `:notify`. A queue in this layout is shared with Laravel workers and the + /// other SDKs' zset transports, and supports delayed messages and in-place release. + #[default] + Zset, + /// The legacy reliable-queue layout: ``, `:processing` and + /// `:processing:deadlines`. It has no delayed set. + Legacy, +} + +/// The clock of a transport: fractional epoch seconds. +pub(crate) type Clock = Arc f64 + Send + Sync>; + +/// Settings of a [`RedisTransport`](crate::RedisTransport). Build one with [`Options::new`] and the +/// builder methods; every setting has the default of the contract. +#[derive(Clone)] +pub struct Options { + pub(crate) layout: Layout, + pub(crate) key_prefix: String, + pub(crate) retry_after: Option, + pub(crate) migration_batch_size: Option, + pub(crate) response_timeout: Duration, + pub(crate) clock: Clock, +} + +impl Options { + /// The defaults: zset layout, key prefix `queues:`, `retry_after` 90 s, no migration batch + /// limit, a 5 s response timeout and the system clock. + #[must_use] + pub fn new() -> Self { + Self { + layout: Layout::default(), + key_prefix: DEFAULT_KEY_PREFIX.to_owned(), + retry_after: Some(DEFAULT_RETRY_AFTER), + migration_batch_size: None, + response_timeout: Duration::from_secs(5), + clock: Arc::new(wall_clock), + } + } + + /// Selects the layout (default [`Layout::Zset`]). + #[must_use] + pub fn layout(mut self, layout: Layout) -> Self { + self.layout = layout; + self + } + + /// The key prefix of the zset layout (default `queues:`). The queue name is used as given: + /// the SDK neither adds nor removes braces, so a Redis Cluster hash tag is the caller's choice + /// (section 1.5). + #[must_use] + pub fn key_prefix(mut self, prefix: impl Into) -> Self { + self.key_prefix = prefix.into(); + self + } + + /// The reservation window (default 90 s). In the zset layout an expired `:reserved` member is + /// made ready again and counts as an attempt; in the legacy layout an expired deadline member + /// is swept back to the ready list. A [`Duration`] cannot be negative, which is how the + /// contract's "a negative value is a configuration error" holds here. + #[must_use] + pub fn retry_after(mut self, window: Duration) -> Self { + self.retry_after = Some(window); + self + } + + /// The `retry_after: null` setting: this consumer never recovers expired `:reserved` members + /// (zset layout) and its legacy deadline members score `+inf`. It still sweeps other + /// consumers' expired legacy members. + #[must_use] + pub fn without_retry_after(mut self) -> Self { + self.retry_after = None; + self + } + + /// Bounds how many members one migrate (zset) or sweep (legacy) moves; the default is no + /// limit (`migration_batch_size: -1`). + #[must_use] + pub fn migration_batch_size(mut self, limit: NonZeroU32) -> Self { + self.migration_batch_size = Some(limit); + self + } + + /// How long a command may take before the connection reports a timeout (default 5 s). + #[must_use] + pub fn response_timeout(mut self, timeout: Duration) -> Self { + self.response_timeout = timeout; + self + } + + /// Replaces the clock with `clock`, which returns fractional epoch seconds. The score of a + /// delayed message, a reservation deadline and every migrate use it; it exists so tests can pin + /// time, as the conformance suite does. + #[must_use] + pub fn clock(mut self, clock: impl Fn() -> f64 + Send + Sync + 'static) -> Self { + self.clock = Arc::new(clock); + self + } +} + +impl Default for Options { + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Options { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Options") + .field("layout", &self.layout) + .field("key_prefix", &self.key_prefix) + .field("retry_after", &self.retry_after) + .field("migration_batch_size", &self.migration_batch_size) + .field("response_timeout", &self.response_timeout) + .finish_non_exhaustive() + } +} + +fn wall_clock() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0.0, |d| d.as_secs_f64()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_defaults_are_the_zset_layout_with_a_90_second_window() { + let options = Options::default(); + assert_eq!(options.layout, Layout::Zset); + assert_eq!(Layout::default(), Layout::Zset); + assert_eq!(options.key_prefix, "queues:"); + assert_eq!(options.retry_after, Some(Duration::from_secs(90))); + assert_eq!(options.migration_batch_size, None); + } + + #[test] + fn retry_after_can_be_disabled_and_set_again() { + let options = Options::new() + .without_retry_after() + .retry_after(Duration::from_secs(5)); + assert_eq!(options.retry_after, Some(Duration::from_secs(5))); + assert_eq!(Options::new().without_retry_after().retry_after, None); + } + + #[test] + fn a_pinned_clock_is_what_now_returns() { + let options = Options::new().clock(|| 1234.5); + assert!((options.clock)().to_bits() == 1234.5_f64.to_bits()); + } +} diff --git a/crates/babelqueue-redis/src/scripts.rs b/crates/babelqueue-redis/src/scripts.rs new file mode 100644 index 0000000..91a276a --- /dev/null +++ b/crates/babelqueue-redis/src/scripts.rs @@ -0,0 +1,175 @@ +//! The Lua scripts of broker-bindings section 1. The zset pop script is Laravel's, with the +//! `pcall` guards of ADR-0033 (the same text as `babelqueue-python`'s `redis_transport.py`); the +//! legacy scripts are section 1.7. They run through [`redis::Script`], which sends `EVALSHA` and +//! loads the script then repeats the call on `NOSCRIPT`. + +use std::sync::LazyLock; + +use redis::Script; + +/// KEYS: ready, notify. ARGV: body. Produce in the zset layout: push and signal. +pub(crate) static PUSH: LazyLock