use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, TimeZone, Utc};
use crate::pairing::{
AttachmentHolder, DeviceAttachment, DeviceKind, DeviceRecord, DeviceScope, DeviceStore,
PairingCode,
};
#[async_trait]
pub trait DeviceStoreHarness: Send + Sync {
async fn open(&self) -> Arc<dyn DeviceStore>;
fn is_durable(&self) -> bool {
true
}
}
async fn two(harness: &dyn DeviceStoreHarness) -> [Arc<dyn DeviceStore>; 2] {
if harness.is_durable() {
[harness.open().await, harness.open().await]
} else {
let store = harness.open().await;
[store.clone(), store]
}
}
fn fresh() -> String {
uuid::Uuid::new_v4().simple().to_string()
}
fn instant(seconds: i64) -> DateTime<Utc> {
Utc.timestamp_opt(1_800_000_000 + seconds, 123_456_000).single().expect("valid instant")
}
fn code(owner: &str, expires: i64) -> PairingCode {
let mut code = PairingCode::new(
fresh(),
owner,
Duration::from_secs(90 * 86_400),
instant(0),
instant(expires),
);
code.groups = vec!["operator".into(), "on-call/日本".into()];
code.scopes = vec![DeviceScope::Decide, DeviceScope::Stop];
code.name = Some("Ana's phone \u{1F4F1}".into());
code.kind = Some(DeviceKind::Tray);
code
}
fn device(created: i64) -> DeviceRecord {
DeviceRecord::new(
fresh(),
"Ana's \"phone\" 日本",
"user/ü",
fresh(),
instant(created),
instant(created + 86_400),
)
.with_scopes([DeviceScope::Read, DeviceScope::Decide])
.with_groups(["operator"])
.with_kind(DeviceKind::Phone)
}
fn attachment(holder: &AttachmentHolder, kind: &str, key: &str, at: i64) -> DeviceAttachment {
DeviceAttachment::new(
holder.clone(),
kind,
key,
serde_json::json!({ "endpoint": format!("https://web.push.apple.com/{key}"), "keys": { "auth": "日本" }, "at": at }),
instant(at),
)
}
pub async fn attachments_round_trip_per_kind(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let phone = AttachmentHolder::Device(fresh());
let person = AttachmentHolder::User(format!("user/ü {}", fresh()));
let push = attachment(&phone, "push", "subscription", 1);
let b = attachment(&phone, "wake", "b:1", 2);
let a = attachment(&phone, "wake", "a:1", 3);
let theirs = attachment(&person, "push", "subscription", 4);
for row in [&push, &b, &a, &theirs] {
store.put_attachment(row.clone()).await.expect("put");
}
assert_eq!(store.attachments(&phone, "push").await.expect("list"), vec![push]);
assert_eq!(store.attachments(&phone, "wake").await.expect("list"), vec![a, b]);
assert_eq!(store.attachments(&person, "push").await.expect("list"), vec![theirs]);
assert_eq!(store.attachments(&phone, "passkey").await.expect("list"), vec![]);
}
pub async fn put_attachment_replaces(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let phone = AttachmentHolder::Device(fresh());
store.put_attachment(attachment(&phone, "passkey", "only", 1)).await.expect("put");
let replaced = attachment(&phone, "passkey", "only", 2);
store.put_attachment(replaced.clone()).await.expect("put again");
assert_eq!(store.attachments(&phone, "passkey").await.expect("list"), vec![replaced]);
}
pub async fn put_attachment_if_absent_writes_once(harness: &dyn DeviceStoreHarness) {
let [first, second] = two(harness).await;
let phone = AttachmentHolder::Device(fresh());
let tasks: Vec<_> = (0..8)
.map(|index| {
let store = if index % 2 == 0 { first.clone() } else { second.clone() };
let row = attachment(&phone, "wake", "apr-1:3", index);
tokio::spawn(async move { store.put_attachment_if_absent(row).await.expect("put") })
})
.collect();
let mut wrote = 0;
for task in tasks {
if task.await.expect("join") {
wrote += 1;
}
}
assert_eq!(wrote, 1, "one of eight puts wrote");
assert_eq!(first.attachments(&phone, "wake").await.expect("list").len(), 1);
assert!(
!second
.put_attachment_if_absent(attachment(&phone, "wake", "apr-1:3", 9))
.await
.expect("put")
);
}
pub async fn remove_attachment_removes_one(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let phone = AttachmentHolder::Device(fresh());
let kept = attachment(&phone, "push", "kept", 1);
store.put_attachment(attachment(&phone, "push", "gone", 0)).await.expect("put");
store.put_attachment(kept.clone()).await.expect("put");
assert!(store.remove_attachment(&phone, "push", "gone").await.expect("remove"));
assert!(!store.remove_attachment(&phone, "push", "gone").await.expect("remove again"));
assert_eq!(store.attachments(&phone, "push").await.expect("list"), vec![kept]);
}
pub async fn remove_attachments_removes_the_holders(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let phone = AttachmentHolder::Device(fresh());
let other = AttachmentHolder::Device(fresh());
for (kind, key) in [("push", "subscription"), ("passkey", "only"), ("wake", "a:1")] {
store.put_attachment(attachment(&phone, kind, key, 1)).await.expect("put");
}
let theirs = attachment(&other, "push", "subscription", 1);
store.put_attachment(theirs.clone()).await.expect("put");
assert_eq!(store.remove_attachments(&phone).await.expect("remove"), 3);
for kind in ["push", "passkey", "wake"] {
assert_eq!(store.attachments(&phone, kind).await.expect("list"), vec![], "{kind}");
}
assert_eq!(store.attachments(&other, "push").await.expect("list"), vec![theirs]);
assert_eq!(store.remove_attachments(&phone).await.expect("remove again"), 0);
}
pub async fn attachments_survive_a_restart(harness: &dyn DeviceStoreHarness) {
if !harness.is_durable() {
return;
}
let phone = AttachmentHolder::Device(fresh());
let row = attachment(&phone, "passkey", "only", 5);
harness.open().await.put_attachment(row.clone()).await.expect("put");
let reopened = harness.open().await;
assert_eq!(reopened.attachments(&phone, "passkey").await.expect("list"), vec![row]);
}
pub async fn code_round_trip_and_take_once(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let code = code("ana", 600);
store.put_code(code.clone()).await.expect("put");
assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code.clone()));
assert_eq!(store.take_code(&code.code_hash).await.expect("take again"), None);
}
pub async fn take_returns_expired_codes(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let code = code("ana", -600);
store.put_code(code.clone()).await.expect("put");
assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
}
pub async fn prune_removes_expired_codes(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let expired = code("ana", -1_000_000_000);
let edge = code("ana", -999_999_000);
let live = code("ana", 1_000_000_000);
for code in [&expired, &edge, &live] {
store.put_code(code.clone()).await.expect("put");
}
let removed = store.prune_codes(edge.expires_at).await.expect("prune");
assert!(removed >= 2, "removed {removed}");
assert_eq!(store.take_code(&expired.code_hash).await.expect("take"), None);
assert_eq!(store.take_code(&edge.code_hash).await.expect("take"), None);
assert_eq!(store.take_code(&live.code_hash).await.expect("take"), Some(live));
}
pub async fn clear_removes_every_code(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let codes = [code("ana", 600), code("bo", 600)];
for code in &codes {
store.put_code(code.clone()).await.expect("put");
}
assert!(store.clear_codes().await.expect("clear") >= 2);
for code in &codes {
assert_eq!(store.take_code(&code.code_hash).await.expect("take"), None);
}
}
pub async fn device_round_trip(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
for scopes in [DeviceScope::ALL.to_vec(), vec![DeviceScope::Read], vec![DeviceScope::Stop]] {
let mut device = device(0).with_scopes(scopes);
device.revoked_at = Some(instant(30));
store.put_device(device.clone()).await.expect("put");
assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device));
}
}
pub async fn put_device_replaces(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let mut device = device(0);
store.put_device(device.clone()).await.expect("put");
device.revoked_at = Some(instant(60));
store.put_device(device.clone()).await.expect("put again");
assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device.clone()));
let listed = store.list_devices().await.expect("list");
assert_eq!(listed.iter().filter(|listed| listed.id == device.id).count(), 1);
}
pub async fn list_devices_orders_by_pairing_then_id(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
let mut late = device(200);
let early = device(100);
let mut tied = device(200);
if tied.id < late.id {
std::mem::swap(&mut tied.id, &mut late.id);
}
for device in [&late, &tied, &early] {
store.put_device(device.clone()).await.expect("put");
}
let ours = [&early.id, &late.id, &tied.id];
let listed: Vec<String> = store
.list_devices()
.await
.expect("list")
.into_iter()
.filter(|device| ours.contains(&&device.id))
.map(|device| device.id)
.collect();
assert_eq!(listed, [early.id.clone(), late.id.clone(), tied.id.clone()]);
}
pub async fn unknown_ids(harness: &dyn DeviceStoreHarness) {
let store = harness.open().await;
assert_eq!(store.get_device(&fresh()).await.expect("get"), None);
assert_eq!(store.take_code(&fresh()).await.expect("take"), None);
}
pub async fn records_survive_a_restart(harness: &dyn DeviceStoreHarness) {
if !harness.is_durable() {
return;
}
let device = device(0);
let code = code("ana", 600);
{
let store = harness.open().await;
store.put_device(device.clone()).await.expect("put");
store.put_code(code.clone()).await.expect("put");
}
let store = harness.open().await;
assert_eq!(store.get_device(&device.id).await.expect("get"), Some(device));
assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
}
pub async fn concurrent_takes_take_once(harness: &dyn DeviceStoreHarness) {
let stores = two(harness).await;
let code = code("ana", 600);
stores[0].put_code(code.clone()).await.expect("put");
let mut takes = Vec::new();
for index in 0..8 {
let store = stores[index % 2].clone();
let hash = code.code_hash.clone();
takes.push(tokio::spawn(async move { store.take_code(&hash).await.expect("take") }));
}
let mut taken = 0;
for take in takes {
if take.await.expect("take completes").is_some() {
taken += 1;
}
}
assert_eq!(taken, 1);
}
pub async fn concurrent_writers(harness: &dyn DeviceStoreHarness) {
let stores = two(harness).await;
let mut writes = Vec::new();
let mut devices = Vec::new();
let mut codes = Vec::new();
for index in 0..16 {
let store = stores[index % 2].clone();
let device = device(i64::try_from(index).expect("small"));
let code = code("ana", 600);
devices.push(device.clone());
codes.push(code.clone());
writes.push(tokio::spawn(async move {
store.put_device(device).await.expect("put device");
store.put_code(code).await.expect("put code");
}));
}
for write in writes {
write.await.expect("write completes");
}
let store = &stores[1];
for device in devices {
assert_eq!(store.get_device(&device.id).await.expect("get").as_ref(), Some(&device));
}
for code in codes {
assert_eq!(store.take_code(&code.code_hash).await.expect("take"), Some(code));
}
}
pub async fn claim_attempts_are_counted_once_and_shared(harness: &dyn DeviceStoreHarness) {
let stores = two(harness).await;
stores[0].reset_claim_attempts().await.expect("reset");
let mut counts = Vec::new();
for index in 0..16 {
let store = stores[index % 2].clone();
counts.push(tokio::spawn(async move { store.count_claim_attempt().await.expect("count") }));
}
let mut seen = Vec::new();
for count in counts {
seen.push(count.await.expect("count completes"));
}
seen.sort_unstable();
assert_eq!(seen, (1..=16).collect::<Vec<u64>>(), "every count is distinct");
stores[1].reset_claim_attempts().await.expect("reset");
assert_eq!(stores[0].count_claim_attempt().await.expect("count"), 1);
if harness.is_durable() {
let reopened = harness.open().await;
assert_eq!(reopened.count_claim_attempt().await.expect("count"), 2);
}
}
#[macro_export]
macro_rules! device_store_conformance_tests {
($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_code_round_trip_and_take_once() {
$crate::conformance::device_store::code_round_trip_and_take_once(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_take_returns_expired_codes() {
$crate::conformance::device_store::take_returns_expired_codes(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_prune_removes_expired_codes() {
$crate::conformance::device_store::prune_removes_expired_codes(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_clear_removes_every_code() {
$crate::conformance::device_store::clear_removes_every_code(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_device_round_trip() {
$crate::conformance::device_store::device_round_trip(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_put_device_replaces() {
$crate::conformance::device_store::put_device_replaces(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_list_devices_orders_by_pairing_then_id() {
$crate::conformance::device_store::list_devices_orders_by_pairing_then_id(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_unknown_ids() {
$crate::conformance::device_store::unknown_ids(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_records_survive_a_restart() {
$crate::conformance::device_store::records_survive_a_restart(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_concurrent_takes_take_once() {
$crate::conformance::device_store::concurrent_takes_take_once(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_concurrent_writers() {
$crate::conformance::device_store::concurrent_writers(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_claim_attempts_are_counted_once_and_shared() {
$crate::conformance::device_store::claim_attempts_are_counted_once_and_shared(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_attachments_round_trip_per_kind() {
$crate::conformance::device_store::attachments_round_trip_per_kind(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_put_attachment_replaces() {
$crate::conformance::device_store::put_attachment_replaces(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_put_attachment_if_absent_writes_once() {
$crate::conformance::device_store::put_attachment_if_absent_writes_once(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_remove_attachment_removes_one() {
$crate::conformance::device_store::remove_attachment_removes_one(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_remove_attachments_removes_the_holders() {
$crate::conformance::device_store::remove_attachments_removes_the_holders(&$harness).await;
}
$(#[$attr])*
#[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn device_store_attachments_survive_a_restart() {
$crate::conformance::device_store::attachments_survive_a_restart(&$harness).await;
}
};
}