Skip to main content

adk_kernel/conformance/
channel_binding_store.rs

1//! Conformance cases for [`ChannelBindingStore`] backends (spec 3.3 §10 K1; feature
2//! `channels`).
3//!
4//! | Case | Contract |
5//! |------|----------|
6//! | [`binding_round_trip`] | A binding reads back exactly as put, with the characters a backend must escape |
7//! | [`put_binding_replaces`] | A second put of one binding replaces it, as a revocation does |
8//! | [`list_bindings_orders_by_pairing_then_id`] | `list_bindings` orders by pairing time, then id |
9//! | [`request_round_trip`] | A request reads back by channel and account, and is taken once by its code |
10//! | [`put_request_replaces_the_accounts_request`] | An account's second request replaces its first; the first code takes nothing |
11//! | [`take_returns_expired_requests`] | A take returns a request past its expiry; the caller decides |
12//! | [`prune_removes_expired_requests`] | `prune_requests` removes the requests expired at or before the instant, and only those |
13//! | [`list_requests_orders_by_time_then_account`] | `list_requests` orders by request time, then channel and account |
14//! | [`unknown_ids`] | An unknown binding, request and code are `None` |
15//! | [`records_survive_a_restart`] | Bindings and requests read back through a new handle (durable backends only) |
16//! | [`concurrent_takes_take_once`] | Eight concurrent takes of one code from two handles take it once |
17//!
18//! Every case writes under fresh channels and accounts, so a harness may point every case
19//! at one shared database.
20
21use std::sync::Arc;
22
23use async_trait::async_trait;
24use chrono::{DateTime, TimeZone, Utc};
25
26use crate::channels::{ChannelBinding, ChannelBindingStore, ChannelPairingRequest};
27
28/// Opens a [`ChannelBindingStore`] backend for the conformance suite.
29///
30/// # Example
31///
32/// ```rust
33/// use std::sync::Arc;
34/// use adk_kernel::channels::{ChannelBindingStore, InMemoryChannelBindingStore};
35/// use adk_kernel::conformance::ChannelBindingStoreHarness;
36///
37/// struct InMemory;
38///
39/// #[async_trait::async_trait]
40/// impl ChannelBindingStoreHarness for InMemory {
41///     async fn open(&self) -> Arc<dyn ChannelBindingStore> {
42///         Arc::new(InMemoryChannelBindingStore::new())
43///     }
44///
45///     fn is_durable(&self) -> bool {
46///         false
47///     }
48/// }
49/// ```
50#[async_trait]
51pub trait ChannelBindingStoreHarness: Send + Sync {
52    /// Opens a store. For a durable backend every call returns a new handle over the same
53    /// stored data. Panics when the backend cannot be opened.
54    async fn open(&self) -> Arc<dyn ChannelBindingStore>;
55
56    /// Whether data written through one handle is visible through the next.
57    fn is_durable(&self) -> bool {
58        true
59    }
60}
61
62async fn two(harness: &dyn ChannelBindingStoreHarness) -> [Arc<dyn ChannelBindingStore>; 2] {
63    if harness.is_durable() {
64        [harness.open().await, harness.open().await]
65    } else {
66        let store = harness.open().await;
67        [store.clone(), store]
68    }
69}
70
71fn fresh() -> String {
72    uuid::Uuid::new_v4().simple().to_string()
73}
74
75/// A fresh channel with the characters a backend must escape.
76fn channel() -> String {
77    format!("chat:ü/{}", fresh())
78}
79
80/// An instant with microseconds, so a backend that rounds timestamps is caught.
81fn instant(seconds: i64) -> DateTime<Utc> {
82    Utc.timestamp_opt(1_800_000_000 + seconds, 654_321_000).single().expect("valid instant")
83}
84
85fn binding(channel: &str, paired: i64) -> ChannelBinding {
86    let mut binding = ChannelBinding::new(
87        channel,
88        format!("acct %2F/{}", fresh()),
89        "-100/日本",
90        "user/ü",
91        instant(paired),
92    )
93    .with_groups(["operator", "on-call"]);
94    binding.display_name = Some("Ana \"A\" 日本".into());
95    binding
96}
97
98fn request(channel: &str, account: &str, at: i64, expires: i64) -> ChannelPairingRequest {
99    let mut request = ChannelPairingRequest::new(
100        fresh(),
101        channel,
102        account,
103        "thread/1",
104        instant(at),
105        instant(expires),
106    );
107    request.display_name = Some("Bo".into());
108    request
109}
110
111/// A binding reads back exactly as put.
112pub async fn binding_round_trip(harness: &dyn ChannelBindingStoreHarness) {
113    let store = harness.open().await;
114    let mut binding = binding(&channel(), 0);
115    store.put_binding(binding.clone()).await.expect("put");
116    assert_eq!(store.get_binding(&binding.id).await.expect("get"), Some(binding.clone()));
117    binding.revoked_at = Some(instant(10));
118    binding.display_name = None;
119    store.put_binding(binding.clone()).await.expect("put");
120    assert_eq!(store.get_binding(&binding.id).await.expect("get"), Some(binding));
121}
122
123/// A second put of one binding replaces it.
124pub async fn put_binding_replaces(harness: &dyn ChannelBindingStoreHarness) {
125    let store = harness.open().await;
126    let mut binding = binding(&channel(), 0);
127    store.put_binding(binding.clone()).await.expect("put");
128    binding.revoked_at = Some(instant(60));
129    store.put_binding(binding.clone()).await.expect("put again");
130    let listed = store.list_bindings().await.expect("list");
131    assert_eq!(
132        listed.iter().filter(|listed| listed.id == binding.id).collect::<Vec<_>>(),
133        [&binding]
134    );
135}
136
137/// `list_bindings` orders by pairing time, then id.
138pub async fn list_bindings_orders_by_pairing_then_id(harness: &dyn ChannelBindingStoreHarness) {
139    let store = harness.open().await;
140    let channel = channel();
141    let early = binding(&channel, 100);
142    let mut late = binding(&channel, 200);
143    let mut tied = binding(&channel, 200);
144    if tied.id < late.id {
145        std::mem::swap(&mut tied, &mut late);
146    }
147    for binding in [&tied, &late, &early] {
148        store.put_binding(binding.clone()).await.expect("put");
149    }
150    let listed: Vec<String> = store
151        .list_bindings()
152        .await
153        .expect("list")
154        .into_iter()
155        .filter(|binding| binding.channel == channel)
156        .map(|binding| binding.id)
157        .collect();
158    assert_eq!(listed, [early.id, late.id, tied.id]);
159}
160
161/// A request reads back by channel and account, and is taken once by its code.
162pub async fn request_round_trip(harness: &dyn ChannelBindingStoreHarness) {
163    let store = harness.open().await;
164    let channel = channel();
165    let request = request(&channel, "acct/ü 1", 0, 3_600);
166    store.put_request(request.clone()).await.expect("put");
167    assert_eq!(store.get_request(&channel, "acct/ü 1").await.expect("get"), Some(request.clone()));
168    assert_eq!(store.take_request(&request.code_hash).await.expect("take"), Some(request.clone()));
169    assert_eq!(store.take_request(&request.code_hash).await.expect("take again"), None);
170    assert_eq!(store.get_request(&channel, "acct/ü 1").await.expect("get"), None);
171}
172
173/// An account's second request replaces its first.
174pub async fn put_request_replaces_the_accounts_request(harness: &dyn ChannelBindingStoreHarness) {
175    let store = harness.open().await;
176    let channel = channel();
177    let first = request(&channel, "acct", 0, 3_600);
178    let second = request(&channel, "acct", 10, 3_610);
179    store.put_request(first.clone()).await.expect("put");
180    store.put_request(second.clone()).await.expect("put again");
181    assert_eq!(store.get_request(&channel, "acct").await.expect("get"), Some(second.clone()));
182    assert_eq!(store.take_request(&first.code_hash).await.expect("take first"), None);
183    let ours = store
184        .list_requests()
185        .await
186        .expect("list")
187        .into_iter()
188        .filter(|request| request.channel == channel)
189        .count();
190    assert_eq!(ours, 1);
191    assert_eq!(store.take_request(&second.code_hash).await.expect("take"), Some(second));
192}
193
194/// A take returns a request past its expiry.
195pub async fn take_returns_expired_requests(harness: &dyn ChannelBindingStoreHarness) {
196    let store = harness.open().await;
197    let request = request(&channel(), "acct", -7_200, -3_600);
198    store.put_request(request.clone()).await.expect("put");
199    assert_eq!(store.take_request(&request.code_hash).await.expect("take"), Some(request));
200}
201
202/// `prune_requests` removes the requests expired at or before the instant, and only those.
203pub async fn prune_removes_expired_requests(harness: &dyn ChannelBindingStoreHarness) {
204    let store = harness.open().await;
205    let channel = channel();
206    let expired = request(&channel, "a", -1_000_001_000, -1_000_000_000);
207    let edge = request(&channel, "b", -1_000_001_000, -999_999_000);
208    let live = request(&channel, "c", 0, 1_000_000_000);
209    for request in [&expired, &edge, &live] {
210        store.put_request(request.clone()).await.expect("put");
211    }
212    let removed = store.prune_requests(edge.expires_at).await.expect("prune");
213    assert!(removed >= 2, "removed {removed}");
214    assert_eq!(store.get_request(&channel, "a").await.expect("get"), None);
215    assert_eq!(store.take_request(&edge.code_hash).await.expect("take"), None);
216    assert_eq!(store.get_request(&channel, "c").await.expect("get"), Some(live));
217}
218
219/// `list_requests` orders by request time, then channel and account.
220pub async fn list_requests_orders_by_time_then_account(harness: &dyn ChannelBindingStoreHarness) {
221    let store = harness.open().await;
222    let channel = channel();
223    let requests = [
224        request(&channel, "b", 100, 4_000),
225        request(&channel, "a", 100, 4_000),
226        request(&channel, "c", 50, 4_000),
227    ];
228    for request in &requests {
229        store.put_request(request.clone()).await.expect("put");
230    }
231    let listed: Vec<String> = store
232        .list_requests()
233        .await
234        .expect("list")
235        .into_iter()
236        .filter(|request| request.channel == channel)
237        .map(|request| request.account)
238        .collect();
239    assert_eq!(listed, ["c", "a", "b"]);
240}
241
242/// An unknown binding, request and code are `None`.
243pub async fn unknown_ids(harness: &dyn ChannelBindingStoreHarness) {
244    let store = harness.open().await;
245    assert_eq!(store.get_binding(&fresh()).await.expect("get"), None);
246    assert_eq!(store.get_request(&channel(), "nobody").await.expect("get"), None);
247    assert_eq!(store.take_request(&fresh()).await.expect("take"), None);
248}
249
250/// Bindings and requests read back through a new handle.
251pub async fn records_survive_a_restart(harness: &dyn ChannelBindingStoreHarness) {
252    if !harness.is_durable() {
253        return;
254    }
255    let channel = channel();
256    let binding = binding(&channel, 0);
257    let request = request(&channel, "acct", 0, 3_600);
258    {
259        let store = harness.open().await;
260        store.put_binding(binding.clone()).await.expect("put");
261        store.put_request(request.clone()).await.expect("put");
262    }
263    let store = harness.open().await;
264    assert_eq!(store.get_binding(&binding.id).await.expect("get"), Some(binding));
265    assert_eq!(store.get_request(&channel, "acct").await.expect("get"), Some(request));
266}
267
268/// Eight concurrent takes of one code from two handles take it once.
269pub async fn concurrent_takes_take_once(harness: &dyn ChannelBindingStoreHarness) {
270    let stores = two(harness).await;
271    let request = request(&channel(), "acct", 0, 3_600);
272    stores[0].put_request(request.clone()).await.expect("put");
273    let mut takes = Vec::new();
274    for index in 0..8 {
275        let store = stores[index % 2].clone();
276        let hash = request.code_hash.clone();
277        takes.push(tokio::spawn(async move { store.take_request(&hash).await.expect("take") }));
278    }
279    let mut taken = 0;
280    for take in takes {
281        if take.await.expect("take completes").is_some() {
282            taken += 1;
283        }
284    }
285    assert_eq!(taken, 1);
286}
287
288/// Generates one test per [`channel_binding_store`](self) case for a `ChannelBindingStoreHarness` (spec 3.3 §10 K1; feature `channels`).
289///
290/// Used as [`process_store_conformance_tests!`](crate::process_store_conformance_tests) is;
291/// see the [module documentation](crate::conformance).
292#[cfg(feature = "channels")]
293#[macro_export]
294macro_rules! channel_binding_store_conformance_tests {
295    ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
296        $(#[$attr])*
297        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
298        async fn channel_binding_store_binding_round_trip() {
299            $crate::conformance::channel_binding_store::binding_round_trip(&$harness).await;
300        }
301        $(#[$attr])*
302        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
303        async fn channel_binding_store_put_binding_replaces() {
304            $crate::conformance::channel_binding_store::put_binding_replaces(&$harness).await;
305        }
306        $(#[$attr])*
307        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
308        async fn channel_binding_store_list_bindings_orders_by_pairing_then_id() {
309            $crate::conformance::channel_binding_store::list_bindings_orders_by_pairing_then_id(&$harness).await;
310        }
311        $(#[$attr])*
312        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
313        async fn channel_binding_store_request_round_trip() {
314            $crate::conformance::channel_binding_store::request_round_trip(&$harness).await;
315        }
316        $(#[$attr])*
317        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
318        async fn channel_binding_store_put_request_replaces_the_accounts_request() {
319            $crate::conformance::channel_binding_store::put_request_replaces_the_accounts_request(&$harness).await;
320        }
321        $(#[$attr])*
322        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
323        async fn channel_binding_store_take_returns_expired_requests() {
324            $crate::conformance::channel_binding_store::take_returns_expired_requests(&$harness).await;
325        }
326        $(#[$attr])*
327        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
328        async fn channel_binding_store_prune_removes_expired_requests() {
329            $crate::conformance::channel_binding_store::prune_removes_expired_requests(&$harness).await;
330        }
331        $(#[$attr])*
332        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
333        async fn channel_binding_store_list_requests_orders_by_time_then_account() {
334            $crate::conformance::channel_binding_store::list_requests_orders_by_time_then_account(&$harness).await;
335        }
336        $(#[$attr])*
337        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
338        async fn channel_binding_store_unknown_ids() {
339            $crate::conformance::channel_binding_store::unknown_ids(&$harness).await;
340        }
341        $(#[$attr])*
342        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
343        async fn channel_binding_store_records_survive_a_restart() {
344            $crate::conformance::channel_binding_store::records_survive_a_restart(&$harness).await;
345        }
346        $(#[$attr])*
347        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
348        async fn channel_binding_store_concurrent_takes_take_once() {
349            $crate::conformance::channel_binding_store::concurrent_takes_take_once(&$harness).await;
350        }
351    };
352}