1use std::sync::Arc;
20
21use async_trait::async_trait;
22use chrono::{DateTime, TimeZone, Utc};
23
24use crate::control::{AreaSettings, AreaStart, AwayCursor, Change, ControlStore};
25use crate::partition::{PartitionId, PartitionMode};
26use crate::sched::QuietHours;
27
28#[async_trait]
51pub trait ControlStoreHarness: Send + Sync {
52 async fn open(&self) -> Arc<dyn ControlStore>;
55
56 fn is_durable(&self) -> bool {
58 true
59 }
60}
61
62async fn two(harness: &dyn ControlStoreHarness) -> [Arc<dyn ControlStore>; 2] {
64 if harness.is_durable() {
65 [harness.open().await, harness.open().await]
66 } else {
67 let store = harness.open().await;
68 [store.clone(), store]
69 }
70}
71
72fn fresh(prefix: &str) -> String {
74 format!("{prefix}-{}-ü", uuid::Uuid::new_v4().simple())
75}
76
77fn instant(seconds: i64) -> DateTime<Utc> {
79 Utc.timestamp_opt(1_800_000_000 + seconds, 123_456_000).single().expect("valid instant")
80}
81
82fn settings(partition: &PartitionId) -> AreaSettings {
83 let window = "22:00-07:00".parse::<QuietHours>().expect("window").with_utc_offset_minutes(180);
84 let mut settings = AreaSettings::new(partition.clone())
85 .with_quiet_time(Change::new(Some(window), "ana \"home\"", instant(1)))
86 .with_daily_spending_limit(Change::new(None, "ana", instant(2)))
87 .with_mode(Change::new(PartitionMode::Ask, "ana", instant(3)))
88 .with_start(AreaStart::new(vec![window], Some(5_000_000), Some(PartitionMode::Auto)));
89 settings.earlier_quiet_time.push(Change::new(None, "ana", instant(0)));
90 settings
91}
92
93pub async fn settings_round_trip(harness: &dyn ControlStoreHarness) {
95 let store = harness.open().await;
96 let partition = PartitionId::new(fresh("area"));
97 let settings = settings(&partition);
98 store.put_area_settings(settings.clone()).await.expect("put");
99 assert_eq!(store.area_settings(&partition).await.expect("get"), Some(settings));
100}
101
102pub async fn put_settings_replaces(harness: &dyn ControlStoreHarness) {
104 let store = harness.open().await;
105 let partition = PartitionId::new(fresh("area"));
106 store.put_area_settings(settings(&partition)).await.expect("put");
107 let replaced = AreaSettings::new(partition.clone()).with_daily_spending_limit(Change::new(
108 Some(5_000_000),
109 "ana",
110 instant(9),
111 ));
112 store.put_area_settings(replaced.clone()).await.expect("put again");
113 assert_eq!(store.area_settings(&partition).await.expect("get"), Some(replaced));
114}
115
116pub async fn list_settings_orders_by_partition(harness: &dyn ControlStoreHarness) {
118 let store = harness.open().await;
119 let stem = fresh("order");
120 let ids = [format!("{stem}-b"), format!("{stem}-a"), format!("{stem}-c")];
121 for id in &ids {
122 store.put_area_settings(AreaSettings::new(id.as_str())).await.expect("put");
123 }
124 let listed: Vec<String> = store
125 .list_area_settings()
126 .await
127 .expect("list")
128 .into_iter()
129 .map(|settings| settings.partition.as_str().to_string())
130 .filter(|id| id.starts_with(&stem))
131 .collect();
132 let mut sorted = ids.to_vec();
133 sorted.sort();
134 assert_eq!(listed, sorted);
135 let all: Vec<String> = store
136 .list_area_settings()
137 .await
138 .expect("list")
139 .into_iter()
140 .map(|settings| settings.partition.as_str().to_string())
141 .collect();
142 let mut ordered = all.clone();
143 ordered.sort();
144 assert_eq!(all, ordered, "every area is ordered by id");
145}
146
147pub async fn unknown_keys(harness: &dyn ControlStoreHarness) {
149 let store = harness.open().await;
150 assert_eq!(store.area_settings(&PartitionId::new(fresh("none"))).await.expect("get"), None);
151 assert_eq!(store.cursor(&fresh("user"), "home").await.expect("get"), None);
152}
153
154pub async fn cursor_never_moves_back(harness: &dyn ControlStoreHarness) {
156 let store = harness.open().await;
157 let user = fresh("user");
158 let first = AwayCursor::new(user.clone(), "device:0a1b", 40, instant(10));
159 assert_eq!(store.advance_cursor(first.clone()).await.expect("advance"), first);
160 let back = AwayCursor::new(user.clone(), "device:0a1b", 12, instant(20));
161 assert_eq!(store.advance_cursor(back).await.expect("advance"), first, "never back");
162 let again = AwayCursor::new(user.clone(), "device:0a1b", 40, instant(30));
163 assert_eq!(
164 store.advance_cursor(again.clone()).await.expect("advance"),
165 again,
166 "same row, seen later"
167 );
168 let on = AwayCursor::new(user.clone(), "device:0a1b", 41, instant(40));
169 assert_eq!(store.advance_cursor(on.clone()).await.expect("advance"), on);
170 assert_eq!(store.cursor(&user, "device:0a1b").await.expect("get"), Some(on));
171}
172
173pub async fn cursors_are_per_user_and_viewer(harness: &dyn ControlStoreHarness) {
175 let store = harness.open().await;
176 let (ana, bo) = (fresh("ana"), fresh("bo"));
177 let cursors = [
178 AwayCursor::new(ana.clone(), "home", 5, instant(1)),
179 AwayCursor::new(ana.clone(), "terminal", 9, instant(2)),
180 AwayCursor::new(bo.clone(), "home", 7, instant(3)),
181 ];
182 for cursor in &cursors {
183 store.advance_cursor(cursor.clone()).await.expect("advance");
184 }
185 for cursor in cursors {
186 assert_eq!(store.cursor(&cursor.user, &cursor.viewer).await.expect("get"), Some(cursor));
187 }
188}
189
190pub async fn records_survive_a_restart(harness: &dyn ControlStoreHarness) {
192 if !harness.is_durable() {
193 return;
194 }
195 let partition = PartitionId::new(fresh("area"));
196 let cursor = AwayCursor::new(fresh("user"), "home", 77, instant(5));
197 {
198 let store = harness.open().await;
199 store.put_area_settings(settings(&partition)).await.expect("put");
200 store.advance_cursor(cursor.clone()).await.expect("advance");
201 }
202 let store = harness.open().await;
203 assert_eq!(store.area_settings(&partition).await.expect("get"), Some(settings(&partition)));
204 assert_eq!(store.cursor(&cursor.user, "home").await.expect("get"), Some(cursor));
205}
206
207pub async fn concurrent_advances_keep_the_highest(harness: &dyn ControlStoreHarness) {
209 let stores = two(harness).await;
210 let user = fresh("user");
211 let mut advances = Vec::new();
212 for (index, seq) in
213 [3, 14, 1, 15, 9, 2, 6, 5, 13, 8, 12, 4, 10, 16, 7, 11].into_iter().enumerate()
214 {
215 let store = stores[index % 2].clone();
216 let cursor = AwayCursor::new(user.clone(), "home", seq, instant(seq.cast_signed()));
217 advances.push(tokio::spawn(
218 async move { store.advance_cursor(cursor).await.expect("advance") },
219 ));
220 }
221 for advance in advances {
222 advance.await.expect("advance completes");
223 }
224 let stored = stores[0].cursor(&user, "home").await.expect("get").expect("a cursor");
225 assert_eq!(stored.seq, 16);
226}
227
228pub async fn update_changes_one_setting(harness: &dyn ControlStoreHarness) {
231 let store = harness.open().await;
232 let partition = PartitionId::new(fresh("area"));
233 let plan = Change::new(PartitionMode::Plan, "ana", instant(4));
234 let stored = store
235 .update_area_settings(&partition, &|settings: &mut AreaSettings| {
236 settings.mode = Some(plan.clone());
237 })
238 .await
239 .expect("update");
240 let created = AreaSettings::new(partition.clone()).with_mode(plan.clone());
241 assert_eq!(stored, created);
242 assert_eq!(store.area_settings(&partition).await.expect("get"), Some(created));
243
244 store.put_area_settings(settings(&partition)).await.expect("put");
245 let limit = Change::new(Some(7_000_000), "ana", instant(6));
246 let stored = store
247 .update_area_settings(&partition, &|settings: &mut AreaSettings| {
248 settings.daily_spending_limit = Some(limit.clone());
249 })
250 .await
251 .expect("update");
252 let changed = settings(&partition).with_daily_spending_limit(limit);
253 assert_eq!(stored, changed);
254 assert_eq!(store.area_settings(&partition).await.expect("get"), Some(changed));
255}
256
257pub async fn concurrent_updates_all_hold(harness: &dyn ControlStoreHarness) {
260 let stores = two(harness).await;
261 let partition = PartitionId::new(fresh("area"));
262 let mut updates = Vec::new();
263 for index in 0..16_i64 {
264 let store = stores[usize::try_from(index).expect("small") % 2].clone();
265 let partition = partition.clone();
266 updates.push(tokio::spawn(async move {
267 let change = Change::new(None, format!("person-{index}"), instant(index));
268 store
269 .update_area_settings(&partition, &|settings: &mut AreaSettings| {
270 settings.earlier_quiet_time.push(change.clone());
271 })
272 .await
273 .expect("update")
274 }));
275 }
276 for update in updates {
277 update.await.expect("update completes");
278 }
279 let stored = stores[0].area_settings(&partition).await.expect("get").expect("a record");
280 let mut by: Vec<String> =
281 stored.earlier_quiet_time.iter().map(|change| change.by.clone()).collect();
282 by.sort();
283 let mut expected: Vec<String> = (0..16).map(|index| format!("person-{index}")).collect();
284 expected.sort();
285 assert_eq!(by, expected);
286}
287
288#[macro_export]
294macro_rules! control_store_conformance_tests {
295 ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
296 $(#[$attr])*
297 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
298 async fn control_store_settings_round_trip() {
299 $crate::conformance::control_store::settings_round_trip(&$harness).await;
300 }
301 $(#[$attr])*
302 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
303 async fn control_store_put_settings_replaces() {
304 $crate::conformance::control_store::put_settings_replaces(&$harness).await;
305 }
306 $(#[$attr])*
307 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
308 async fn control_store_list_settings_orders_by_partition() {
309 $crate::conformance::control_store::list_settings_orders_by_partition(&$harness).await;
310 }
311 $(#[$attr])*
312 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
313 async fn control_store_unknown_keys() {
314 $crate::conformance::control_store::unknown_keys(&$harness).await;
315 }
316 $(#[$attr])*
317 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
318 async fn control_store_cursor_never_moves_back() {
319 $crate::conformance::control_store::cursor_never_moves_back(&$harness).await;
320 }
321 $(#[$attr])*
322 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
323 async fn control_store_cursors_are_per_user_and_viewer() {
324 $crate::conformance::control_store::cursors_are_per_user_and_viewer(&$harness).await;
325 }
326 $(#[$attr])*
327 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
328 async fn control_store_records_survive_a_restart() {
329 $crate::conformance::control_store::records_survive_a_restart(&$harness).await;
330 }
331 $(#[$attr])*
332 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
333 async fn control_store_concurrent_advances_keep_the_highest() {
334 $crate::conformance::control_store::concurrent_advances_keep_the_highest(&$harness)
335 .await;
336 }
337 $(#[$attr])*
338 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
339 async fn control_store_update_changes_one_setting() {
340 $crate::conformance::control_store::update_changes_one_setting(&$harness).await;
341 }
342 $(#[$attr])*
343 #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
344 async fn control_store_concurrent_updates_all_hold() {
345 $crate::conformance::control_store::concurrent_updates_all_hold(&$harness).await;
346 }
347 };
348}