1use std::collections::{HashMap, hash_map::Entry};
10
11use lexe_std::backoff::Backoff;
12use lexe_tokio::notify;
13use tokio::sync::watch;
14use tracing::warn;
15
16use crate::types::{
17 command::{
18 GetPaymentByIdRequest, GetPaymentResponse, GetUpdatedPaymentsRequest,
19 GetUpdatedPaymentsResponse,
20 },
21 payment::{Payment, PaymentId, PaymentUpdatedIndex},
22};
23
24pub(crate) struct PaymentsBus {
25 cursor_rx: watch::Receiver<Option<PaymentUpdatedIndex>>,
27 payment_txs:
29 std::sync::Mutex<HashMap<PaymentId, watch::Sender<Option<Payment>>>>,
30 poll_state: tokio::sync::Mutex<PollState>,
32 poll_now_tx: notify::Sender,
34}
35
36pub(crate) trait WalletUpdatesApi {
38 async fn get_updated_payments(
39 &self,
40 req: GetUpdatedPaymentsRequest,
41 ) -> anyhow::Result<GetUpdatedPaymentsResponse>;
42
43 async fn get_payment_by_id(
44 &self,
45 req: GetPaymentByIdRequest,
46 ) -> anyhow::Result<GetPaymentResponse>;
47}
48
49struct PollState {
51 backoff: Backoff,
52 cursor_tx: watch::Sender<Option<PaymentUpdatedIndex>>,
55 poll_now_rx: notify::Receiver,
56}
57
58struct PaymentSubscription<'a> {
60 rx: watch::Receiver<Option<Payment>>,
62 _guard: SubscriptionGuard<'a>,
63}
64
65struct SubscriptionGuard<'a> {
67 bus: &'a PaymentsBus,
68 id: PaymentId,
69}
70
71impl PaymentsBus {
72 const INITIAL_WAIT_MS: u64 = 250;
75 const MAX_WAIT_MS: u64 = 1_500;
76
77 pub(crate) fn new(latest_update: Option<PaymentUpdatedIndex>) -> Self {
79 let (cursor_tx, cursor_rx) = watch::channel(latest_update);
80 let (poll_now_tx, poll_now_rx) = notify::channel();
81 Self {
82 cursor_rx,
83 payment_txs: std::sync::Mutex::new(HashMap::new()),
84 poll_state: tokio::sync::Mutex::new(PollState {
85 backoff: Backoff::new(Self::INITIAL_WAIT_MS, Self::MAX_WAIT_MS),
86 cursor_tx,
87 poll_now_rx,
88 }),
89 poll_now_tx,
90 }
91 }
92
93 pub(crate) async fn wait_for_payment_condition(
95 &self,
96 api: &impl WalletUpdatesApi,
97 id: PaymentId,
98 mut condition: impl FnMut(&Payment) -> bool,
99 ) -> anyhow::Result<Payment> {
100 let mut subscription = self.subscribe(id);
101
102 let req = GetPaymentByIdRequest { id };
104 if let Some(payment) = api.get_payment_by_id(req).await?.payment
105 && condition(&payment)
106 {
107 return Ok(payment);
108 }
109
110 let payment = self
111 .poll_until(api, &mut subscription.rx, |maybe_payment| {
112 maybe_payment.as_ref().filter(|p| condition(p)).cloned()
113 })
114 .await;
115
116 Ok(payment)
117 }
118
119 pub(crate) async fn wait_for_next_update(
121 &self,
122 api: &impl WalletUpdatesApi,
123 start_index: Option<PaymentUpdatedIndex>,
124 ) -> anyhow::Result<()> {
125 let mut cursor_rx = self.cursor_rx.clone();
126
127 self.poll_until(api, &mut cursor_rx, |cursor| {
128 (*cursor > start_index).then_some(())
130 })
131 .await;
132
133 Ok(())
134 }
135
136 fn subscribe(&self, id: PaymentId) -> PaymentSubscription<'_> {
137 let rx = match self.payment_txs.lock().unwrap().entry(id) {
138 Entry::Occupied(entry) => entry.get().subscribe(),
139 Entry::Vacant(entry) =>
140 entry.insert(watch::Sender::new(None)).subscribe(),
141 };
142
143 let _guard = SubscriptionGuard { bus: self, id };
144 PaymentSubscription { rx, _guard }
145 }
146
147 async fn poll_until<T, U>(
149 &self,
150 api: &impl WalletUpdatesApi,
151 rx: &mut watch::Receiver<T>,
152 mut extract: impl FnMut(&T) -> Option<U>,
153 ) -> U {
154 self.poll_now_tx.send();
155
156 loop {
157 if let Some(value) = extract(&rx.borrow_and_update()) {
158 return value;
159 }
160
161 tokio::select! {
162 biased;
165 _ = rx.changed() => (),
167 mut locked_poll_state = self.poll_state.lock() =>
168 self.poll_once(api, &mut locked_poll_state).await,
169 }
170 }
171 }
172
173 async fn poll_once(
176 &self,
177 api: &impl WalletUpdatesApi,
178 poll_state: &mut PollState,
179 ) {
180 let delay = poll_state.backoff.next_delay();
181 let poll_now =
182 tokio::time::timeout(delay, poll_state.poll_now_rx.recv()).await;
183 if poll_now.is_ok() {
184 poll_state.backoff.reset();
185 }
186
187 match self.publish_updates(api, poll_state).await {
188 Ok(true) => poll_state.backoff.reset(),
189 Ok(false) => (),
190 Err(e) => warn!("Payment update poll failed: {e:#}"),
191 }
192 }
193
194 async fn publish_updates(
197 &self,
198 api: &impl WalletUpdatesApi,
199 poll_state: &mut PollState,
200 ) -> anyhow::Result<bool> {
201 let cursor_tx = &poll_state.cursor_tx;
202 let req = GetUpdatedPaymentsRequest {
203 start_index: *cursor_tx.borrow(),
204 limit: None,
205 };
206 let resp = api.get_updated_payments(req).await?;
207
208 let Some(latest) = resp.updated_index else {
209 return Ok(false);
210 };
211
212 let locked_payment_txs = self.payment_txs.lock().unwrap();
213 for payment in resp.payments {
214 if let Some(payment_tx) = locked_payment_txs.get(&payment.index.id)
215 {
216 payment_tx.send_replace(Some(payment));
217 }
218 }
219
220 cursor_tx.send_replace(Some(latest));
221
222 Ok(true)
223 }
224}
225
226impl Drop for SubscriptionGuard<'_> {
227 fn drop(&mut self) {
228 let mut locked_payment_txs = self.bus.payment_txs.lock().unwrap();
229 if let Entry::Occupied(entry) = locked_payment_txs.entry(self.id)
230 && entry.get().receiver_count() == 0
231 {
232 entry.remove();
233 }
234 }
235}
236
237#[cfg(test)]
238mod test {
239 use std::{
240 collections::BTreeMap,
241 future::Future,
242 ops::Bound,
243 sync::{
244 Arc, Mutex, OnceLock,
245 atomic::{AtomicUsize, Ordering},
246 },
247 time::Duration,
248 };
249
250 use lexe_api::types::payments::{BasicPaymentV2, PaymentStatus};
251 use lexe_common::{test_utils::arbitrary, time::TimestampMs};
252 use lexe_crypto::rng::FastRng;
253 use lexe_tokio::task::LxTask;
254 use proptest::arbitrary::any;
255 use tokio::time::Instant;
256
257 use super::*;
258
259 #[derive(Default)]
261 struct MockWallet {
262 payments: Mutex<BTreeMap<PaymentUpdatedIndex, Payment>>,
264 polls: Mutex<Vec<(Instant, Option<PaymentUpdatedIndex>)>>,
266 failures: AtomicUsize,
268 update_after_read: Mutex<Option<Payment>>,
270 update_after_poll: Mutex<Option<Payment>>,
272 }
273
274 struct TestBus {
277 wallet: Arc<MockWallet>,
278 bus: OnceLock<Arc<PaymentsBus>>,
279 }
280
281 impl MockWallet {
282 fn update(&self, payment: Payment) {
284 let mut locked_payments = self.payments.lock().unwrap();
285 locked_payments.retain(|_, p| p.index.id != payment.index.id);
286 locked_payments.insert(payment.updated_index(), payment);
287 }
288
289 fn poll_times(&self) -> Vec<Instant> {
290 let locked_polls = self.polls.lock().unwrap();
291 locked_polls.iter().map(|(time, _)| *time).collect()
292 }
293
294 fn latest_updated_index(&self) -> Option<PaymentUpdatedIndex> {
295 let locked_payments = self.payments.lock().unwrap();
296 locked_payments.last_key_value().map(|(idx, _)| *idx)
297 }
298 }
299
300 impl WalletUpdatesApi for MockWallet {
301 async fn get_updated_payments(
302 &self,
303 req: GetUpdatedPaymentsRequest,
304 ) -> anyhow::Result<GetUpdatedPaymentsResponse> {
305 self.polls
306 .lock()
307 .unwrap()
308 .push((Instant::now(), req.start_index));
309
310 let fail = self
311 .failures
312 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| {
313 n.checked_sub(1)
314 })
315 .is_ok();
316 anyhow::ensure!(!fail, "Mock poll failure");
317
318 let start =
319 req.start_index.map_or(Bound::Unbounded, Bound::Excluded);
320 let payments = self
321 .payments
322 .lock()
323 .unwrap()
324 .range((start, Bound::Unbounded))
325 .take(req.limit.unwrap_or(usize::MAX))
326 .map(|(_, p)| p.clone())
327 .collect::<Vec<_>>();
328 let updated_index = payments.last().map(Payment::updated_index);
329
330 if let Some(update) = self.update_after_poll.lock().unwrap().take()
331 {
332 self.update(update);
333 }
334
335 Ok(GetUpdatedPaymentsResponse {
336 payments,
337 updated_index,
338 })
339 }
340
341 async fn get_payment_by_id(
342 &self,
343 req: GetPaymentByIdRequest,
344 ) -> anyhow::Result<GetPaymentResponse> {
345 let payment = self
346 .payments
347 .lock()
348 .unwrap()
349 .values()
350 .find(|p| p.index.id == req.id)
351 .cloned();
352
353 if let Some(update) = self.update_after_read.lock().unwrap().take()
354 {
355 self.update(update);
356 }
357
358 Ok(GetPaymentResponse { payment })
359 }
360 }
361
362 impl TestBus {
363 fn new() -> Self {
364 Self {
365 wallet: Arc::default(),
366 bus: OnceLock::new(),
367 }
368 }
369
370 fn bus(&self) -> &Arc<PaymentsBus> {
371 self.bus.get_or_init(|| {
372 let latest_update = self.wallet.latest_updated_index();
373 Arc::new(PaymentsBus::new(latest_update))
374 })
375 }
376
377 fn wait_finalized(&self, n: u64) -> LxTask<Payment> {
379 self.spawn(|wallet, bus| async move {
380 bus.wait_for_payment_condition(&*wallet, id(n), |p| {
381 p.status.is_finalized()
382 })
383 .await
384 .unwrap()
385 })
386 }
387
388 fn wait_for_next_update(
390 &self,
391 start_index: Option<PaymentUpdatedIndex>,
392 ) -> LxTask<()> {
393 self.spawn(|wallet, bus| async move {
394 bus.wait_for_next_update(&*wallet, start_index)
395 .await
396 .unwrap()
397 })
398 }
399
400 fn spawn<F: Future + Send + 'static>(
401 &self,
402 wait: impl FnOnce(Arc<MockWallet>, Arc<PaymentsBus>) -> F,
403 ) -> LxTask<F::Output>
404 where
405 F::Output: Send + 'static,
406 {
407 let (wallet, bus) =
408 (Arc::clone(&self.wallet), Arc::clone(self.bus()));
409 LxTask::spawn_unnamed(wait(wallet, bus))
410 }
411
412 fn num_subscriptions(&self) -> usize {
413 self.bus().payment_txs.lock().unwrap().len()
414 }
415
416 fn published_status(&self, n: u64) -> Option<PaymentStatus> {
418 let locked_payment_txs = self.bus().payment_txs.lock().unwrap();
419 let published = locked_payment_txs[&id(n)].borrow();
420 published.as_ref().map(|p| p.status)
421 }
422 }
423
424 fn payment(n: u64, updated_at_ms: i64, status: PaymentStatus) -> Payment {
426 let mut rng = FastRng::from_u64(n);
427 let mut payment =
428 arbitrary::gen_value(&mut rng, any::<BasicPaymentV2>());
429 payment.status = status;
430 payment.updated_at = TimestampMs::try_from(updated_at_ms).unwrap();
431 Payment::from(payment)
432 }
433
434 fn id(n: u64) -> PaymentId {
435 payment(n, 0, PaymentStatus::Pending).index.id
436 }
437
438 fn poll_schedule(from: Instant, until: Instant) -> Vec<Instant> {
440 let mut backoff = Backoff::new(
441 PaymentsBus::INITIAL_WAIT_MS,
442 PaymentsBus::MAX_WAIT_MS,
443 );
444 let mut times = Vec::new();
445 let mut time = from;
446 while time < until {
447 times.push(time);
448 time += backoff.next_delay();
449 }
450
451 times
452 }
453
454 async fn next_poll() {
457 tokio::time::sleep(Duration::from_millis(PaymentsBus::MAX_WAIT_MS + 1))
458 .await
459 }
460
461 async fn finish<T>(waiter: LxTask<T>) -> T {
463 tokio::time::timeout(Duration::from_secs(60), waiter)
464 .await
465 .expect("Waiter never finished")
466 .unwrap()
467 }
468
469 #[tokio::test(start_paused = true)]
470 async fn publishes_each_update_to_its_waiters() {
471 let test = TestBus::new();
472 let first = test.wait_finalized(1);
473 let second = test.wait_finalized(1);
474 let unrelated = test.wait_finalized(2);
475 next_poll().await;
476 assert_eq!(test.num_subscriptions(), 2);
477
478 test.wallet.update(payment(1, 10, PaymentStatus::Pending));
479 next_poll().await;
480 assert_eq!(test.published_status(1), Some(PaymentStatus::Pending));
481 assert_eq!(test.published_status(2), None);
482 assert!(!first.is_finished());
483
484 test.wallet.update(payment(1, 20, PaymentStatus::Completed));
485 for waiter in [first, second] {
486 let payment = finish(waiter).await;
487 assert_eq!(payment.status, PaymentStatus::Completed);
488 }
489 assert!(!unrelated.is_finished());
490 }
491
492 #[tokio::test(start_paused = true)]
493 async fn waiters_share_one_poll_loop() {
494 let test = TestBus::new();
495 let start = Instant::now();
496 let _waiters =
497 (1..=5).map(|n| test.wait_finalized(n)).collect::<Vec<_>>();
498 tokio::time::sleep(Duration::from_secs(30)).await;
499
500 let mut times = test.wallet.poll_times();
503 times.dedup();
504 assert_eq!(times, poll_schedule(start, Instant::now()));
505 }
506
507 #[tokio::test(start_paused = true)]
508 async fn stops_polling_once_nobody_waits() {
509 let test = TestBus::new();
510 let first = test.wait_finalized(1);
511 let second = test.wait_finalized(2);
512 next_poll().await;
513 assert_eq!(test.num_subscriptions(), 2);
514
515 first.abort();
516 next_poll().await;
517 assert_eq!(test.num_subscriptions(), 1);
518 second.abort();
519 next_poll().await;
520 assert_eq!(test.num_subscriptions(), 0);
521
522 let num_polls = test.wallet.poll_times().len();
523 tokio::time::sleep(Duration::from_secs(30)).await;
524 assert_eq!(test.wallet.poll_times().len(), num_polls);
525 }
526
527 #[tokio::test(start_paused = true)]
528 async fn an_aborted_waiter_keeps_the_others_subscription() {
529 let test = TestBus::new();
530 let first = test.wait_finalized(1);
531 let second = test.wait_finalized(1);
532 next_poll().await;
533 assert_eq!(test.num_subscriptions(), 1);
534
535 first.abort();
536 next_poll().await;
537 assert_eq!(test.num_subscriptions(), 1);
538
539 test.wallet.update(payment(1, 10, PaymentStatus::Completed));
540 let payment = finish(second).await;
541 assert_eq!(payment.status, PaymentStatus::Completed);
542 assert_eq!(test.num_subscriptions(), 0);
543 }
544
545 #[tokio::test(start_paused = true)]
546 async fn starts_the_cursor_at_the_latest_update() {
547 let test = TestBus::new();
548 let history = payment(1, 10, PaymentStatus::Completed);
549 let latest = history.updated_index();
550 test.wallet.update(history);
551
552 let _waiter = test.wait_finalized(2);
553 next_poll().await;
554
555 assert_eq!(test.wallet.polls.lock().unwrap()[0].1, Some(latest));
557 }
558
559 #[tokio::test(start_paused = true)]
560 async fn resumes_from_the_cursor_after_idling() {
561 let test = TestBus::new();
562 let waiter = test.wait_finalized(1);
563 next_poll().await;
564 let first = payment(1, 10, PaymentStatus::Completed);
565 let first_index = first.updated_index();
566 test.wallet.update(first);
567 finish(waiter).await;
568
569 tokio::time::sleep(Duration::from_secs(30)).await;
571 let num_polls = test.wallet.poll_times().len();
572 let waiter = test.wait_finalized(2);
573 next_poll().await;
574 test.wallet.update(payment(2, 20, PaymentStatus::Completed));
575 finish(waiter).await;
576
577 let resumed_at = test.wallet.polls.lock().unwrap()[num_polls].1;
578 assert_eq!(resumed_at, Some(first_index));
579 }
580
581 #[tokio::test(start_paused = true)]
582 async fn idle_polling_backs_off_until_something_changes() {
583 let test = TestBus::new();
584 let start = Instant::now();
585 let _waiter = test.wait_finalized(1);
586
587 tokio::time::sleep(Duration::from_secs(30)).await;
589 let times = test.wallet.poll_times();
590 assert_eq!(times, poll_schedule(start, Instant::now()));
591
592 let subscribed_at = Instant::now();
594 let _other = test.wait_finalized(2);
595 tokio::time::sleep(Duration::from_secs(30)).await;
596 let times = test.wallet.poll_times();
597 let expected = poll_schedule(subscribed_at, Instant::now());
598 assert_eq!(times[times.len() - expected.len()..], expected);
599
600 test.wallet.update(payment(3, 10, PaymentStatus::Pending));
602 let num_polls = test.wallet.poll_times().len();
603 tokio::time::sleep(Duration::from_secs(5)).await;
604 let times = test.wallet.poll_times();
605 let saw_update = times[num_polls];
606 let expected = poll_schedule(saw_update, Instant::now());
607 assert_eq!(times[num_polls..], expected);
608 }
609
610 #[tokio::test(start_paused = true)]
611 async fn poll_failures_do_not_stop_the_bus() {
612 let test = TestBus::new();
613 let waiter = test.wait_finalized(1);
614 next_poll().await;
615
616 test.wallet.failures.store(3, Ordering::Relaxed);
617 test.wallet.update(payment(1, 10, PaymentStatus::Completed));
618 let payment = finish(waiter).await;
619 assert_eq!(payment.status, PaymentStatus::Completed);
620 assert_eq!(test.wallet.failures.load(Ordering::Relaxed), 0);
621 }
622
623 #[tokio::test(start_paused = true)]
624 async fn returns_without_polling_if_already_satisfied() {
625 let test = TestBus::new();
626 test.wallet.update(payment(1, 10, PaymentStatus::Completed));
627
628 let payment = finish(test.wait_finalized(1)).await;
629 assert_eq!(payment.status, PaymentStatus::Completed);
630 assert!(test.wallet.poll_times().is_empty());
631 assert_eq!(test.num_subscriptions(), 0);
632 }
633
634 #[tokio::test(start_paused = true)]
635 async fn catches_an_update_right_after_the_initial_read() {
636 let test = TestBus::new();
637 test.wallet.update(payment(1, 10, PaymentStatus::Pending));
638 *test.wallet.update_after_read.lock().unwrap() =
639 Some(payment(1, 20, PaymentStatus::Completed));
640
641 let payment = finish(test.wait_finalized(1)).await;
642 assert_eq!(payment.status, PaymentStatus::Completed);
643 }
644
645 #[tokio::test(start_paused = true)]
648 async fn publishes_the_first_payment_of_a_fresh_wallet() {
649 let test = TestBus::new();
650 let first = test.wait_finalized(1);
651 tokio::time::sleep(Duration::from_millis(
653 PaymentsBus::INITIAL_WAIT_MS / 2,
654 ))
655 .await;
656
657 *test.wallet.update_after_poll.lock().unwrap() =
660 Some(payment(1, 10, PaymentStatus::Completed));
661 let _second = test.wait_finalized(2);
662
663 let payment = finish(first).await;
664 assert_eq!(payment.status, PaymentStatus::Completed);
665 }
666
667 #[tokio::test(start_paused = true)]
668 async fn waits_for_the_next_update_after_an_index() {
669 let test = TestBus::new();
670 let old = payment(1, 10, PaymentStatus::Completed);
671 let start_index = Some(old.updated_index());
672 test.wallet.update(old);
673
674 let waiter = test.wait_for_next_update(start_index);
675 next_poll().await;
676 assert!(!waiter.is_finished());
677
678 test.wallet.update(payment(2, 20, PaymentStatus::Pending));
679 finish(waiter).await;
680 }
681}