Skip to main content

adk_kernel/conformance/
device_store.rs

1//! Conformance cases for [`DeviceStore`] backends (spec 3.3 §10 K2, §11 S-I7).
2//!
3//! | Case | Contract |
4//! |------|----------|
5//! | [`code_round_trip_and_take_once`] | A code reads back exactly as put, once: a second take finds nothing |
6//! | [`take_returns_expired_codes`] | A take returns a code past its expiry; the caller decides |
7//! | [`prune_removes_expired_codes`] | `prune_codes` removes the codes expired at or before the instant, and only those |
8//! | [`clear_removes_every_code`] | `clear_codes` removes every waiting code |
9//! | [`device_round_trip`] | A device reads back exactly as put: every field, every scope |
10//! | [`put_device_replaces`] | A second put of one device replaces it, as a revocation does |
11//! | [`list_devices_orders_by_pairing_then_id`] | `list_devices` orders by pairing time, then id |
12//! | [`unknown_ids`] | An unknown device and an unknown code are `None` |
13//! | [`records_survive_a_restart`] | Devices and codes read back through a new handle (durable backends only) |
14//! | [`concurrent_takes_take_once`] | Eight concurrent takes of one code from two handles take it once |
15//! | [`concurrent_writers`] | Concurrent puts from two handles over distinct devices and codes lose none |
16//! | [`claim_attempts_are_counted_once_and_shared`] | Concurrent claim counts from two handles each get a distinct count, a reset starts again at one, and the count survives a restart |
17//! | [`attachments_round_trip_per_kind`] | An attachment reads back exactly as put, listed under its holder and kind only, in key order |
18//! | [`put_attachment_replaces`] | A second put of one holder, kind and key replaces it |
19//! | [`put_attachment_if_absent_writes_once`] | Eight concurrent puts-if-absent of one attachment from two handles write it once |
20//! | [`remove_attachment_removes_one`] | Removing one attachment says whether it was there and leaves the rest |
21//! | [`remove_attachments_removes_the_holders`] | Removing a holder's attachments removes every kind of it and nothing of another holder |
22//! | [`attachments_survive_a_restart`] | Attachments read back through a new handle (durable backends only) |
23//!
24//! Every case writes under fresh ids and hashes, so a harness may point every case at one
25//! shared database, except [`clear_removes_every_code`], which removes every code, and
26//! [`claim_attempts_are_counted_once_and_shared`], which uses the one count of claims: give
27//! each a database of its own, as the harnesses of this crate give every case.
28
29use std::sync::Arc;
30use std::time::Duration;
31
32use async_trait::async_trait;
33use chrono::{DateTime, TimeZone, Utc};
34
35use crate::pairing::{
36    AttachmentHolder, DeviceAttachment, DeviceKind, DeviceRecord, DeviceScope, DeviceStore,
37    PairingCode,
38};
39
40/// Opens a [`DeviceStore`] backend for the conformance suite.
41///
42/// # Example
43///
44/// ```rust
45/// use std::sync::Arc;
46/// use adk_kernel::conformance::DeviceStoreHarness;
47/// use adk_kernel::pairing::{DeviceStore, InMemoryDeviceStore};
48///
49/// struct InMemory;
50///
51/// #[async_trait::async_trait]
52/// impl DeviceStoreHarness for InMemory {
53///     async fn open(&self) -> Arc<dyn DeviceStore> {
54///         Arc::new(InMemoryDeviceStore::new())
55///     }
56///
57///     fn is_durable(&self) -> bool {
58///         false
59///     }
60/// }
61/// ```
62#[async_trait]
63pub trait DeviceStoreHarness: Send + Sync {
64    /// Opens a store. For a durable backend every call returns a new handle over the same
65    /// stored data. Panics when the backend cannot be opened.
66    async fn open(&self) -> Arc<dyn DeviceStore>;
67
68    /// Whether data written through one handle is visible through the next.
69    fn is_durable(&self) -> bool {
70        true
71    }
72}
73
74/// Two handles over one store: two opens of a durable backend, one store twice otherwise.
75async fn two(harness: &dyn DeviceStoreHarness) -> [Arc<dyn DeviceStore>; 2] {
76    if harness.is_durable() {
77        [harness.open().await, harness.open().await]
78    } else {
79        let store = harness.open().await;
80        [store.clone(), store]
81    }
82}
83
84/// A fresh hex id, as the pairing service makes them.
85fn fresh() -> String {
86    uuid::Uuid::new_v4().simple().to_string()
87}
88
89/// An instant with microseconds, so a backend that rounds timestamps is caught.
90fn instant(seconds: i64) -> DateTime<Utc> {
91    Utc.timestamp_opt(1_800_000_000 + seconds, 123_456_000).single().expect("valid instant")
92}
93
94fn code(owner: &str, expires: i64) -> PairingCode {
95    let mut code = PairingCode::new(
96        fresh(),
97        owner,
98        Duration::from_secs(90 * 86_400),
99        instant(0),
100        instant(expires),
101    );
102    code.groups = vec!["operator".into(), "on-call/日本".into()];
103    code.scopes = vec![DeviceScope::Decide, DeviceScope::Stop];
104    code.name = Some("Ana's phone \u{1F4F1}".into());
105    code.kind = Some(DeviceKind::Tray);
106    code
107}
108
109fn device(created: i64) -> DeviceRecord {
110    DeviceRecord::new(
111        fresh(),
112        "Ana's \"phone\" 日本",
113        "user/ü",
114        fresh(),
115        instant(created),
116        instant(created + 86_400),
117    )
118    .with_scopes([DeviceScope::Read, DeviceScope::Decide])
119    .with_groups(["operator"])
120    .with_kind(DeviceKind::Phone)
121}
122
123/// An attachment of `holder` with a record that has nested JSON and text outside ASCII.
124fn attachment(holder: &AttachmentHolder, kind: &str, key: &str, at: i64) -> DeviceAttachment {
125    DeviceAttachment::new(
126        holder.clone(),
127        kind,
128        key,
129        serde_json::json!({ "endpoint": format!("https://web.push.apple.com/{key}"), "keys": { "auth": "日本" }, "at": at }),
130        instant(at),
131    )
132}
133
134/// An attachment reads back exactly as put, listed under its holder and kind only, in key
135/// order.
136pub async fn attachments_round_trip_per_kind(harness: &dyn DeviceStoreHarness) {
137    let store = harness.open().await;
138    let phone = AttachmentHolder::Device(fresh());
139    let person = AttachmentHolder::User(format!("user/ü {}", fresh()));
140    let push = attachment(&phone, "push", "subscription", 1);
141    let b = attachment(&phone, "wake", "b:1", 2);
142    let a = attachment(&phone, "wake", "a:1", 3);
143    let theirs = attachment(&person, "push", "subscription", 4);
144    for row in [&push, &b, &a, &theirs] {
145        store.put_attachment(row.clone()).await.expect("put");
146    }
147    assert_eq!(store.attachments(&phone, "push").await.expect("list"), vec![push]);
148    assert_eq!(store.attachments(&phone, "wake").await.expect("list"), vec![a, b]);
149    assert_eq!(store.attachments(&person, "push").await.expect("list"), vec![theirs]);
150    assert_eq!(store.attachments(&phone, "passkey").await.expect("list"), vec![]);
151}
152
153/// A second put of one holder, kind and key replaces it.
154pub async fn put_attachment_replaces(harness: &dyn DeviceStoreHarness) {
155    let store = harness.open().await;
156    let phone = AttachmentHolder::Device(fresh());
157    store.put_attachment(attachment(&phone, "passkey", "only", 1)).await.expect("put");
158    let replaced = attachment(&phone, "passkey", "only", 2);
159    store.put_attachment(replaced.clone()).await.expect("put again");
160    assert_eq!(store.attachments(&phone, "passkey").await.expect("list"), vec![replaced]);
161}
162
163/// Eight concurrent puts-if-absent of one attachment from two handles write it once.
164pub async fn put_attachment_if_absent_writes_once(harness: &dyn DeviceStoreHarness) {
165    let [first, second] = two(harness).await;
166    let phone = AttachmentHolder::Device(fresh());
167    let tasks: Vec<_> = (0..8)
168        .map(|index| {
169            let store = if index % 2 == 0 { first.clone() } else { second.clone() };
170            let row = attachment(&phone, "wake", "apr-1:3", index);
171            tokio::spawn(async move { store.put_attachment_if_absent(row).await.expect("put") })
172        })
173        .collect();
174    let mut wrote = 0;
175    for task in tasks {
176        if task.await.expect("join") {
177            wrote += 1;
178        }
179    }
180    assert_eq!(wrote, 1, "one of eight puts wrote");
181    assert_eq!(first.attachments(&phone, "wake").await.expect("list").len(), 1);
182    assert!(
183        !second
184            .put_attachment_if_absent(attachment(&phone, "wake", "apr-1:3", 9))
185            .await
186            .expect("put")
187    );
188}
189
190/// Removing one attachment says whether it was there and leaves the rest.
191pub async fn remove_attachment_removes_one(harness: &dyn DeviceStoreHarness) {
192    let store = harness.open().await;
193    let phone = AttachmentHolder::Device(fresh());
194    let kept = attachment(&phone, "push", "kept", 1);
195    store.put_attachment(attachment(&phone, "push", "gone", 0)).await.expect("put");
196    store.put_attachment(kept.clone()).await.expect("put");
197    assert!(store.remove_attachment(&phone, "push", "gone").await.expect("remove"));
198    assert!(!store.remove_attachment(&phone, "push", "gone").await.expect("remove again"));
199    assert_eq!(store.attachments(&phone, "push").await.expect("list"), vec![kept]);
200}
201
202/// Removing a holder's attachments removes every kind of it and nothing of another holder.
203pub async fn remove_attachments_removes_the_holders(harness: &dyn DeviceStoreHarness) {
204    let store = harness.open().await;
205    let phone = AttachmentHolder::Device(fresh());
206    let other = AttachmentHolder::Device(fresh());
207    for (kind, key) in [("push", "subscription"), ("passkey", "only"), ("wake", "a:1")] {
208        store.put_attachment(attachment(&phone, kind, key, 1)).await.expect("put");
209    }
210    let theirs = attachment(&other, "push", "subscription", 1);
211    store.put_attachment(theirs.clone()).await.expect("put");
212    assert_eq!(store.remove_attachments(&phone).await.expect("remove"), 3);
213    for kind in ["push", "passkey", "wake"] {
214        assert_eq!(store.attachments(&phone, kind).await.expect("list"), vec![], "{kind}");
215    }
216    assert_eq!(store.attachments(&other, "push").await.expect("list"), vec![theirs]);
217    assert_eq!(store.remove_attachments(&phone).await.expect("remove again"), 0);
218}
219
220/// Attachments read back through a new handle (durable backends only).
221pub async fn attachments_survive_a_restart(harness: &dyn DeviceStoreHarness) {
222    if !harness.is_durable() {
223        return;
224    }
225    let phone = AttachmentHolder::Device(fresh());
226    let row = attachment(&phone, "passkey", "only", 5);
227    harness.open().await.put_attachment(row.clone()).await.expect("put");
228    let reopened = harness.open().await;
229    assert_eq!(reopened.attachments(&phone, "passkey").await.expect("list"), vec![row]);
230}
231
232/// A code reads back exactly as put, once.
233pub async fn code_round_trip_and_take_once(harness: &dyn DeviceStoreHarness) {
234    let store = harness.open().await;
235    let code = code("ana", 600);
236    store.put_code(code.clone()).await.expect("put");
237    assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code.clone()));
238    assert_eq!(store.take_code(&code.code_hash).await.expect("take again"), None);
239}
240
241/// A take returns a code past its expiry.
242pub async fn take_returns_expired_codes(harness: &dyn DeviceStoreHarness) {
243    let store = harness.open().await;
244    let code = code("ana", -600);
245    store.put_code(code.clone()).await.expect("put");
246    assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
247}
248
249/// `prune_codes` removes the codes expired at or before the instant, and only those.
250pub async fn prune_removes_expired_codes(harness: &dyn DeviceStoreHarness) {
251    let store = harness.open().await;
252    // Far in the past, so codes other cases left in a shared database are pruned too and
253    // the count stays exact only for this case's codes below the cut.
254    let expired = code("ana", -1_000_000_000);
255    let edge = code("ana", -999_999_000);
256    let live = code("ana", 1_000_000_000);
257    for code in [&expired, &edge, &live] {
258        store.put_code(code.clone()).await.expect("put");
259    }
260    let removed = store.prune_codes(edge.expires_at).await.expect("prune");
261    assert!(removed >= 2, "removed {removed}");
262    assert_eq!(store.take_code(&expired.code_hash).await.expect("take"), None);
263    assert_eq!(store.take_code(&edge.code_hash).await.expect("take"), None);
264    assert_eq!(store.take_code(&live.code_hash).await.expect("take"), Some(live));
265}
266
267/// `clear_codes` removes every waiting code.
268pub async fn clear_removes_every_code(harness: &dyn DeviceStoreHarness) {
269    let store = harness.open().await;
270    let codes = [code("ana", 600), code("bo", 600)];
271    for code in &codes {
272        store.put_code(code.clone()).await.expect("put");
273    }
274    assert!(store.clear_codes().await.expect("clear") >= 2);
275    for code in &codes {
276        assert_eq!(store.take_code(&code.code_hash).await.expect("take"), None);
277    }
278}
279
280/// A device reads back exactly as put.
281pub async fn device_round_trip(harness: &dyn DeviceStoreHarness) {
282    let store = harness.open().await;
283    for scopes in [DeviceScope::ALL.to_vec(), vec![DeviceScope::Read], vec![DeviceScope::Stop]] {
284        let mut device = device(0).with_scopes(scopes);
285        device.revoked_at = Some(instant(30));
286        store.put_device(device.clone()).await.expect("put");
287        assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device));
288    }
289}
290
291/// A second put of one device replaces it.
292pub async fn put_device_replaces(harness: &dyn DeviceStoreHarness) {
293    let store = harness.open().await;
294    let mut device = device(0);
295    store.put_device(device.clone()).await.expect("put");
296    device.revoked_at = Some(instant(60));
297    store.put_device(device.clone()).await.expect("put again");
298    assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device.clone()));
299    let listed = store.list_devices().await.expect("list");
300    assert_eq!(listed.iter().filter(|listed| listed.id == device.id).count(), 1);
301}
302
303/// `list_devices` orders by pairing time, then id.
304pub async fn list_devices_orders_by_pairing_then_id(harness: &dyn DeviceStoreHarness) {
305    let store = harness.open().await;
306    let mut late = device(200);
307    let early = device(100);
308    let mut tied = device(200);
309    // Two devices paired at one instant order by id.
310    if tied.id < late.id {
311        std::mem::swap(&mut tied.id, &mut late.id);
312    }
313    for device in [&late, &tied, &early] {
314        store.put_device(device.clone()).await.expect("put");
315    }
316    let ours = [&early.id, &late.id, &tied.id];
317    let listed: Vec<String> = store
318        .list_devices()
319        .await
320        .expect("list")
321        .into_iter()
322        .filter(|device| ours.contains(&&device.id))
323        .map(|device| device.id)
324        .collect();
325    assert_eq!(listed, [early.id.clone(), late.id.clone(), tied.id.clone()]);
326}
327
328/// An unknown device and an unknown code are `None`.
329pub async fn unknown_ids(harness: &dyn DeviceStoreHarness) {
330    let store = harness.open().await;
331    assert_eq!(store.get_device(&fresh()).await.expect("get"), None);
332    assert_eq!(store.take_code(&fresh()).await.expect("take"), None);
333}
334
335/// Devices and codes read back through a new handle.
336pub async fn records_survive_a_restart(harness: &dyn DeviceStoreHarness) {
337    if !harness.is_durable() {
338        return;
339    }
340    let device = device(0);
341    let code = code("ana", 600);
342    {
343        let store = harness.open().await;
344        store.put_device(device.clone()).await.expect("put");
345        store.put_code(code.clone()).await.expect("put");
346    }
347    let store = harness.open().await;
348    assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device));
349    assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
350}
351
352/// Eight concurrent takes of one code from two handles take it once.
353pub async fn concurrent_takes_take_once(harness: &dyn DeviceStoreHarness) {
354    let stores = two(harness).await;
355    let code = code("ana", 600);
356    stores[0].put_code(code.clone()).await.expect("put");
357    let mut takes = Vec::new();
358    for index in 0..8 {
359        let store = stores[index % 2].clone();
360        let hash = code.code_hash.clone();
361        takes.push(tokio::spawn(async move { store.take_code(&hash).await.expect("take") }));
362    }
363    let mut taken = 0;
364    for take in takes {
365        if take.await.expect("take completes").is_some() {
366            taken += 1;
367        }
368    }
369    assert_eq!(taken, 1);
370}
371
372/// Concurrent puts from two handles over distinct devices and codes lose none.
373pub async fn concurrent_writers(harness: &dyn DeviceStoreHarness) {
374    let stores = two(harness).await;
375    let mut writes = Vec::new();
376    let mut devices = Vec::new();
377    let mut codes = Vec::new();
378    for index in 0..16 {
379        let store = stores[index % 2].clone();
380        let device = device(i64::try_from(index).expect("small"));
381        let code = code("ana", 600);
382        devices.push(device.clone());
383        codes.push(code.clone());
384        writes.push(tokio::spawn(async move {
385            store.put_device(device).await.expect("put device");
386            store.put_code(code).await.expect("put code");
387        }));
388    }
389    for write in writes {
390        write.await.expect("write completes");
391    }
392    let store = &stores[1];
393    for device in devices {
394        assert_eq!(store.get_device(&device.id).await.expect("get").as_ref(), Some(&device));
395    }
396    for code in codes {
397        assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
398    }
399}
400
401/// Concurrent claim counts from two handles each get a distinct count, a reset starts the
402/// count again at one, and a durable count survives a restart, so replicas share the
403/// count of wrong codes.
404pub async fn claim_attempts_are_counted_once_and_shared(harness: &dyn DeviceStoreHarness) {
405    let stores = two(harness).await;
406    stores[0].reset_claim_attempts().await.expect("reset");
407    let mut counts = Vec::new();
408    for index in 0..16 {
409        let store = stores[index % 2].clone();
410        counts.push(tokio::spawn(async move { store.count_claim_attempt().await.expect("count") }));
411    }
412    let mut seen = Vec::new();
413    for count in counts {
414        seen.push(count.await.expect("count completes"));
415    }
416    seen.sort_unstable();
417    assert_eq!(seen, (1..=16).collect::<Vec<u64>>(), "every count is distinct");
418    stores[1].reset_claim_attempts().await.expect("reset");
419    assert_eq!(stores[0].count_claim_attempt().await.expect("count"), 1);
420    if harness.is_durable() {
421        let reopened = harness.open().await;
422        assert_eq!(reopened.count_claim_attempt().await.expect("count"), 2);
423    }
424}
425
426/// Generates one test per [`device_store`](self) case for a `DeviceStoreHarness` (spec 3.3 §10 K2).
427///
428/// Used as [`process_store_conformance_tests!`](crate::process_store_conformance_tests) is;
429/// see the [module documentation](crate::conformance).
430#[macro_export]
431macro_rules! device_store_conformance_tests {
432    ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
433        $(#[$attr])*
434        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
435        async fn device_store_code_round_trip_and_take_once() {
436            $crate::conformance::device_store::code_round_trip_and_take_once(&$harness).await;
437        }
438        $(#[$attr])*
439        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
440        async fn device_store_take_returns_expired_codes() {
441            $crate::conformance::device_store::take_returns_expired_codes(&$harness).await;
442        }
443        $(#[$attr])*
444        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
445        async fn device_store_prune_removes_expired_codes() {
446            $crate::conformance::device_store::prune_removes_expired_codes(&$harness).await;
447        }
448        $(#[$attr])*
449        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
450        async fn device_store_clear_removes_every_code() {
451            $crate::conformance::device_store::clear_removes_every_code(&$harness).await;
452        }
453        $(#[$attr])*
454        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
455        async fn device_store_device_round_trip() {
456            $crate::conformance::device_store::device_round_trip(&$harness).await;
457        }
458        $(#[$attr])*
459        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
460        async fn device_store_put_device_replaces() {
461            $crate::conformance::device_store::put_device_replaces(&$harness).await;
462        }
463        $(#[$attr])*
464        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
465        async fn device_store_list_devices_orders_by_pairing_then_id() {
466            $crate::conformance::device_store::list_devices_orders_by_pairing_then_id(&$harness).await;
467        }
468        $(#[$attr])*
469        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
470        async fn device_store_unknown_ids() {
471            $crate::conformance::device_store::unknown_ids(&$harness).await;
472        }
473        $(#[$attr])*
474        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
475        async fn device_store_records_survive_a_restart() {
476            $crate::conformance::device_store::records_survive_a_restart(&$harness).await;
477        }
478        $(#[$attr])*
479        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
480        async fn device_store_concurrent_takes_take_once() {
481            $crate::conformance::device_store::concurrent_takes_take_once(&$harness).await;
482        }
483        $(#[$attr])*
484        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
485        async fn device_store_concurrent_writers() {
486            $crate::conformance::device_store::concurrent_writers(&$harness).await;
487        }
488        $(#[$attr])*
489        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
490        async fn device_store_claim_attempts_are_counted_once_and_shared() {
491            $crate::conformance::device_store::claim_attempts_are_counted_once_and_shared(&$harness).await;
492        }
493        $(#[$attr])*
494        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
495        async fn device_store_attachments_round_trip_per_kind() {
496            $crate::conformance::device_store::attachments_round_trip_per_kind(&$harness).await;
497        }
498        $(#[$attr])*
499        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
500        async fn device_store_put_attachment_replaces() {
501            $crate::conformance::device_store::put_attachment_replaces(&$harness).await;
502        }
503        $(#[$attr])*
504        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
505        async fn device_store_put_attachment_if_absent_writes_once() {
506            $crate::conformance::device_store::put_attachment_if_absent_writes_once(&$harness).await;
507        }
508        $(#[$attr])*
509        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
510        async fn device_store_remove_attachment_removes_one() {
511            $crate::conformance::device_store::remove_attachment_removes_one(&$harness).await;
512        }
513        $(#[$attr])*
514        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
515        async fn device_store_remove_attachments_removes_the_holders() {
516            $crate::conformance::device_store::remove_attachments_removes_the_holders(&$harness).await;
517        }
518        $(#[$attr])*
519        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
520        async fn device_store_attachments_survive_a_restart() {
521            $crate::conformance::device_store::attachments_survive_a_restart(&$harness).await;
522        }
523    };
524}