1use std::sync::Arc;
22
23use async_trait::async_trait;
24use chrono::{DateTime, TimeZone, Utc};
25
26use crate::channels::{ChannelBinding, ChannelBindingStore, ChannelPairingRequest};
27
28#[async_trait]
51pub trait ChannelBindingStoreHarness: Send + Sync {
52 async fn open(&self) -> Arc<dyn ChannelBindingStore>;
55
56 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
75fn channel() -> String {
77 format!("chat:ü/{}", fresh())
78}
79
80fn 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
111pub 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
123pub 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
137pub 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
161pub 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
173pub 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
194pub 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
202pub 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
219pub 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
242pub 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
250pub 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
268pub 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#[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}