1use 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#[async_trait]
63pub trait DeviceStoreHarness: Send + Sync {
64 async fn open(&self) -> Arc<dyn DeviceStore>;
67
68 fn is_durable(&self) -> bool {
70 true
71 }
72}
73
74async 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
84fn fresh() -> String {
86 uuid::Uuid::new_v4().simple().to_string()
87}
88
89fn 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
123fn 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
134pub 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
153pub 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
163pub 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
190pub 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
202pub 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
220pub 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
232pub 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
241pub 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
249pub async fn prune_removes_expired_codes(harness: &dyn DeviceStoreHarness) {
251 let store = harness.open().await;
252 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
267pub 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
280pub 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
291pub 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
303pub 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 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
328pub 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
335pub 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
352pub 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
372pub 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
401pub 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#[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}