Skip to main content

lexe/unstable/
payments_db.rs

1//! Local payments db and payment sync
2
3/// NOTE: Be careful about `pub`! This module is part of the stable API.
4///
5/// ### [`PaymentsDb`]
6///
7/// The app's [`PaymentsDb`] maintains a local copy of all [`BasicPaymentV2`]s,
8/// synced from the user node. The user nodes are the source-of-truth for
9/// payment state; consequently, this payment db is effectively a projection of
10/// the user node's payment state.
11///
12/// Currently the [`BasicPaymentV2`]s in the [`PaymentsDb`] are just dumped into
13/// a subdirectory of the app's data directory as unencrypted json blobs. On
14/// startup, we just load all on-disk [`BasicPaymentV2`]s into memory.
15///
16/// In the future, this could be a SQLite DB or something.
17///
18/// ### Payment Syncing
19///
20/// Syncing payments is done by tailing payments from the user node by
21/// [`PaymentUpdatedIndex`]. We simply keep track of the latest updated at index
22/// in our DB, and fetch batches of updated payments, merging them into our DB,
23/// until no payments are returned.
24///
25/// ## Design goals
26///
27/// We want efficient random access for pending payments, which are always
28/// displayed, and efficient fetching for the last N finalized payments, which
29/// are the first payments displayed in the finalized payments list.
30///
31/// Cursors don't work well with flutter's lazy lists, since they want random
32/// access from scroll index -> content.
33///
34/// Performance when syncing payments is secondary, since that's done
35/// asynchronously and off the main UI thread, which is highly latency
36/// sensitive.
37///
38/// In the future, we could be even more clever and serialize+store the pending
39/// index on-disk. If we also added a finalized index, we could avoid the need
40/// to load all the payments on startup and could instead lazy load them.
41///
42/// [`BasicPaymentV2`]: lexe_api::types::payments::BasicPaymentV2
43/// [`PaymentsDb`]: crate::unstable::payments_db::PaymentsDb
44/// [`PaymentUpdatedIndex`]: lexe_api::types::payments::PaymentUpdatedIndex
45mod docs {}
46
47use std::{
48    collections::{BTreeMap, BTreeSet, HashMap},
49    io,
50    ops::Bound,
51    str::FromStr,
52    sync::RwLock,
53};
54
55use anyhow::Context;
56#[cfg(doc)]
57use lexe_api::types::{Empty, payments::VecDbPaymentV2};
58use lexe_api::{
59    def::{UserGatewayApi, UserNodeRunApi},
60    error::{GatewayApiError, NodeApiError},
61    models::command::{self, LatestPaymentUpdateResponse},
62    types::payments::{
63        BasicPaymentV2, PaymentCreatedIndex, PaymentId, PaymentStatus,
64        PaymentUpdatedIndex, VecBasicPaymentV2,
65    },
66};
67use lexe_common::{api::auth::BearerAuthToken, time::TimestampMs};
68use lexe_node_client::client::{GatewayClient, NodeClient};
69use serde::{Deserialize, Serialize};
70use tracing::warn;
71
72use crate::{
73    types::{
74        command::PaymentSyncSummary,
75        payment::{Order, PaymentFilter},
76    },
77    unstable::ffs::Ffs,
78};
79
80/// The app's local [`BasicPaymentV2`] database, synced from the user node.
81pub struct PaymentsDb<F> {
82    ffs: F,
83    state: RwLock<PaymentsDbState>,
84}
85
86/// Pure in-memory state of the [`PaymentsDb`].
87#[derive(Debug, PartialEq)]
88struct PaymentsDbState {
89    /// All locally synced payments,
90    /// from oldest to newest (reverse of the UI scroll order).
91    payments: BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
92
93    /// An index of currently pending payments, sorted by `created_at` index.
94    //
95    // For now, we only have a `pending_index`, because it is sparse - there's
96    // no point in indexing `finalized` as most payments are finalized. If we
97    // later want filters for "offers only" or similar, we can add more.
98    pending_index: BTreeSet<PaymentCreatedIndex>,
99
100    /// An index of every payment, sorted by `updated_at` index.
101    ///
102    /// Invariant:
103    ///
104    /// ```ignore
105    /// updates_index == payments.values()
106    ///     .map(|p| (p.updated_index(), p.created_index()))
107    ///     .collect()
108    /// ```
109    updates_index: BTreeMap<PaymentUpdatedIndex, PaymentCreatedIndex>,
110
111    /// An index of every payment's [`PaymentCreatedIndex`] by [`PaymentId`].
112    ///
113    /// Invariants:
114    ///
115    /// ```ignore
116    /// id_index == payments.keys().map(|idx| (idx.id, *idx)).collect()
117    /// id_index.len() == payments.len() // Ids are unique
118    /// ```
119    id_index: HashMap<PaymentId, PaymentCreatedIndex>,
120
121    /// The time we last successfully synced, or `None` if we've never synced.
122    ///
123    /// Tracks when we last *checked* for updates, so unlike
124    /// [`latest_updated_index`] it stays current even when no new payments
125    /// arrive.
126    ///
127    /// NOTE: This is measured by the device's local clock, not the node's
128    /// clock, so it's subject to clock skew.
129    ///
130    /// [`latest_updated_index`]: Self::latest_updated_index
131    last_synced_at: Option<TimestampMs>,
132}
133
134/// Payments DB metadata, persisted at [`METADATA_FILENAME`] in the same folder
135/// as the per-payment files.
136#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
137struct PaymentsDbMetadata {
138    /// See [`PaymentsDbState::last_synced_at`].
139    last_synced_at: Option<TimestampMs>,
140}
141
142/// Filename of the [`PaymentsDbMetadata`] file. It is not a valid
143/// [`PaymentCreatedIndex`], so it never collides with a payment file.
144const METADATA_FILENAME: &str = "metadata.json";
145
146/// Sync the app's local payment state from the user node.
147/// Only wakes the node if there are actually updates to fetch.
148///
149/// We tail updated payments from the user node, merging results into our DB
150/// until there are no more updates left to sync.
151//
152// Unstable: Takes Ffs as a param which is still evolving
153#[allow(private_bounds)]
154pub(crate) async fn sync_payments<F: Ffs>(
155    db: &PaymentsDb<F>,
156    gateway_client: &impl UserGatewaySyncApi,
157    node_client: &impl UserNodeRunSyncApi,
158    auth: BearerAuthToken,
159    batch_size: u16,
160) -> anyhow::Result<PaymentSyncSummary> {
161    // Ask the gateway if there are new updates, and short circuit if none.
162    // This avoids needlessly waking up the node.
163    // (If the gateway query is failing we expect the node query to fail too.)
164    let latest_update = gateway_client
165        .latest_payment_update(auth)
166        .await
167        .context("Failed to fetch the latest payment update")?
168        .latest_update;
169    if latest_update <= db.latest_updated_index() {
170        // Record the local-clock sync time, even if nothing changed, so we can
171        // later tell users how fresh their local cache is.
172        db.record_synced_at(TimestampMs::now())
173            .context("Failed to persist sync timestamp")?;
174        return Ok(PaymentSyncSummary {
175            latest_updated_index: db.latest_updated_index(),
176            num_new: 0,
177            num_updated: 0,
178        });
179    }
180
181    force_sync_payments(db, node_client, batch_size).await
182}
183
184/// Like [`sync_payments`], but syncs from the node without first asking the
185/// gateway whether there are updates.
186#[allow(private_bounds)]
187pub(crate) async fn force_sync_payments<F: Ffs>(
188    db: &PaymentsDb<F>,
189    node_client: &impl UserNodeRunSyncApi,
190    batch_size: u16,
191) -> anyhow::Result<PaymentSyncSummary> {
192    assert!(batch_size > 0);
193
194    let mut summary = PaymentSyncSummary {
195        latest_updated_index: db.latest_updated_index(),
196        num_new: 0,
197        num_updated: 0,
198    };
199
200    loop {
201        // In every loop iteration, we fetch one batch of updated payments.
202
203        let req = command::GetUpdatedPayments {
204            // Remember, this start index is _exclusive_.
205            // The payment w/ this index will _NOT_ be included in the response.
206            start_index: summary.latest_updated_index,
207            limit: Some(batch_size),
208        };
209
210        let updated_payments = node_client
211            .get_updated_payments(req)
212            .await
213            .context("Failed to fetch updated payments")?
214            .payments;
215        let updated_payments_len = updated_payments.len();
216
217        // Update the db: persist, then update in-memory state.
218        let (new, updated, latest_updated_index) = db
219            .upsert_payments(updated_payments)
220            .context("Failed to upsert payments")?;
221        summary.num_new += new;
222        summary.num_updated += updated;
223        summary.latest_updated_index = latest_updated_index;
224
225        // If the node returned fewer payments than our requested batch size,
226        // then we are done (there are no more new payments after this batch).
227        if updated_payments_len < usize::from(batch_size) {
228            break;
229        }
230    }
231
232    // Record the local-clock sync time, even if nothing changed, so we can
233    // later tell users how fresh their local cache is.
234    db.record_synced_at(TimestampMs::now())
235        .context("Failed to persist sync timestamp")?;
236
237    Ok(summary)
238}
239
240/// The gateway API method that we need to sync payments.
241///
242/// This lets us mock out the method in the tests below,
243/// without also mocking out the entire `UserGatewayApi` trait.
244trait UserGatewaySyncApi {
245    /// GET /user/v1/latest_payment_update [`Empty`]
246    ///                                 -> [`LatestPaymentUpdateResponse`]
247    async fn latest_payment_update(
248        &self,
249        auth: BearerAuthToken,
250    ) -> Result<LatestPaymentUpdateResponse, GatewayApiError>;
251}
252
253impl UserGatewaySyncApi for GatewayClient {
254    async fn latest_payment_update(
255        &self,
256        auth: BearerAuthToken,
257    ) -> Result<LatestPaymentUpdateResponse, GatewayApiError> {
258        UserGatewayApi::latest_payment_update(self, auth).await
259    }
260}
261
262/// The node API method that we need to sync payments.
263///
264/// This lets us mock out the method in the tests below,
265/// without also mocking out the entire `UserNodeRunApi` trait.
266trait UserNodeRunSyncApi {
267    /// GET /node/v1/payments/updated [`command::GetUpdatedPayments`]
268    ///                            -> [`VecDbPaymentV2`]
269    async fn get_updated_payments(
270        &self,
271        req: command::GetUpdatedPayments,
272    ) -> Result<VecBasicPaymentV2, NodeApiError>;
273}
274
275impl UserNodeRunSyncApi for NodeClient {
276    async fn get_updated_payments(
277        &self,
278        req: command::GetUpdatedPayments,
279    ) -> Result<VecBasicPaymentV2, NodeApiError> {
280        UserNodeRunApi::get_updated_payments(self, req).await
281    }
282}
283
284impl<F: Ffs> PaymentsDb<F> {
285    // --- Constructors (unstable b/c Ffs is still in flux) --- //
286
287    /// Read all the payments on-disk into a new `PaymentsDb`.
288    pub(crate) fn read(ffs: F) -> anyhow::Result<Self> {
289        let state = PaymentsDbState::read(&ffs)
290            .map(RwLock::new)
291            .context("Failed to read on-disk PaymentsDb state")?;
292
293        Ok(Self { ffs, state })
294    }
295
296    /// Create a new empty `PaymentsDb`. Does not touch disk/storage.
297    pub(crate) fn empty(ffs: F) -> Self {
298        let state = RwLock::new(PaymentsDbState::empty());
299        Self { ffs, state }
300    }
301
302    // --- Public API  --- //
303
304    /// Clear the in-memory state and delete the on-disk payment db.
305    pub fn clear(&self) -> io::Result<()> {
306        *self.state.write().unwrap() = PaymentsDbState::empty();
307        self.ffs.delete_all()
308    }
309
310    /// Total number of payments in the database.
311    pub fn num_payments(&self) -> usize {
312        self.state.read().unwrap().num_payments()
313    }
314
315    /// Number of pending (unfinalized) payments.
316    pub fn num_pending(&self) -> usize {
317        self.state.read().unwrap().num_pending()
318    }
319
320    /// Number of finalized payments.
321    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
322    pub fn num_finalized(&self) -> usize {
323        self.state.read().unwrap().num_finalized()
324    }
325
326    /// Number of pending payments that are not junk.
327    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
328    pub fn num_pending_not_junk(&self) -> usize {
329        self.state.read().unwrap().num_pending_not_junk()
330    }
331
332    /// Number of finalized payments that are not junk.
333    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
334    pub fn num_finalized_not_junk(&self) -> usize {
335        self.state.read().unwrap().num_finalized_not_junk()
336    }
337
338    /// The latest `updated_at` index of any payment in the db.
339    pub fn latest_updated_index(&self) -> Option<PaymentUpdatedIndex> {
340        self.state.read().unwrap().latest_updated_index()
341    }
342
343    /// The time we last successfully synced with the user node, or `None` if
344    /// we've never synced.
345    ///
346    /// Tracks when we last *checked* for updates, so it can be much more recent
347    /// than the newest payment's `updated_at` if a sync turned up no new
348    /// payments.
349    ///
350    /// NOTE: This is measured by the device's local clock, not the node's
351    /// clock, so it's subject to clock skew.
352    pub fn last_synced_at(&self) -> Option<TimestampMs> {
353        self.state.read().unwrap().last_synced_at
354    }
355
356    /// Get a payment by its [`PaymentId`].
357    pub fn get_payment_by_id(&self, id: &PaymentId) -> Option<BasicPaymentV2> {
358        self.state.read().unwrap().get_payment_by_id(id).cloned()
359    }
360
361    /// Get a payment by scroll index in UI order (newest to oldest).
362    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
363    pub fn get_payment_by_scroll_idx(
364        &self,
365        scroll_idx: usize,
366    ) -> Option<BasicPaymentV2> {
367        self.state
368            .read()
369            .unwrap()
370            .get_payment_by_scroll_idx(scroll_idx)
371            .cloned()
372    }
373
374    /// Get a pending payment by scroll index in UI order (newest to oldest).
375    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
376    pub fn get_pending_payment_by_scroll_idx(
377        &self,
378        scroll_idx: usize,
379    ) -> Option<BasicPaymentV2> {
380        self.state
381            .read()
382            .unwrap()
383            .get_pending_payment_by_scroll_idx(scroll_idx)
384            .cloned()
385    }
386
387    /// Get a "pending and not junk" payment by scroll index in UI order.
388    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
389    pub fn get_pending_not_junk_payment_by_scroll_idx(
390        &self,
391        scroll_idx: usize,
392    ) -> Option<BasicPaymentV2> {
393        self.state
394            .read()
395            .unwrap()
396            .get_pending_not_junk_payment_by_scroll_idx(scroll_idx)
397            .cloned()
398    }
399
400    /// Get a finalized payment by scroll index in UI order (newest to oldest).
401    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
402    pub fn get_finalized_payment_by_scroll_idx(
403        &self,
404        scroll_idx: usize,
405    ) -> Option<BasicPaymentV2> {
406        self.state
407            .read()
408            .unwrap()
409            .get_finalized_payment_by_scroll_idx(scroll_idx)
410            .cloned()
411    }
412
413    /// Get a "finalized and not junk" payment by scroll index in UI order.
414    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
415    pub fn get_finalized_not_junk_payment_by_scroll_idx(
416        &self,
417        scroll_idx: usize,
418    ) -> Option<BasicPaymentV2> {
419        self.state
420            .read()
421            .unwrap()
422            .get_finalized_not_junk_payment_by_scroll_idx(scroll_idx)
423            .cloned()
424    }
425
426    /// List payments from local storage with cursor-based pagination.
427    ///
428    /// Returns `(payments, next_index)` where `next_index` is the cursor
429    /// for fetching the next page (`None` when there are no more results).
430    pub fn list_payments(
431        &self,
432        filter: &PaymentFilter,
433        order: Order,
434        limit: usize,
435        after: Option<&PaymentCreatedIndex>,
436    ) -> (Vec<BasicPaymentV2>, Option<PaymentCreatedIndex>) {
437        self.state
438            .read()
439            .unwrap()
440            .list_payments(filter, order, limit, after)
441    }
442
443    /// Get a batch of locally synced payments in ascending `updated_at` order,
444    /// starting from `start_index`, exclusive. If `None`, starts from the
445    /// oldest-updated payment, inclusive.
446    pub fn get_updated_payments(
447        &self,
448        start_index: Option<PaymentUpdatedIndex>,
449        limit: usize,
450    ) -> Vec<BasicPaymentV2> {
451        self.state
452            .read()
453            .unwrap()
454            .get_updated_payments(start_index, limit)
455    }
456
457    // --- Private helpers --- //
458
459    /// Upsert a batch of payments synced from the user node.
460    ///
461    /// Returns `(num_new, num_updated, latest_updated_index)`.
462    /// May return `(0, 0, _)` if nothing was inserted or updated.
463    fn upsert_payments(
464        &self,
465        payments: impl IntoIterator<Item = BasicPaymentV2>,
466    ) -> io::Result<(usize, usize, Option<PaymentUpdatedIndex>)> {
467        let mut state = self.state.write().unwrap();
468
469        let mut num_new = 0;
470        let mut num_updated = 0;
471        for payment in payments {
472            let (new, updated) =
473                Self::upsert_payment(&self.ffs, &mut state, payment)?;
474            num_new += new;
475            num_updated += updated;
476        }
477
478        Ok((num_new, num_updated, state.latest_updated_index()))
479    }
480
481    /// Upserts a payment into the db.
482    ///
483    /// Persists the payment and updates in-memory state, including indices.
484    ///
485    /// Returns the number of new and updated payments, respectively.
486    /// May return `(0, 0)` if nothing was inserted or updated.
487    fn upsert_payment(
488        ffs: &F,
489        state: &mut PaymentsDbState,
490        payment: BasicPaymentV2,
491    ) -> io::Result<(usize, usize)> {
492        let created_index = payment.created_index();
493
494        let maybe_existing = state.payments.get(&created_index);
495        let already_existed = maybe_existing.is_some();
496
497        // Skip if payment exists and there is no change to it.
498        if let Some(existing) = maybe_existing
499            && payment == *existing
500        {
501            return Ok((0, 0));
502        }
503
504        // Persist the updated payment to storage. Since this is fallible, we
505        // do this first, otherwise we may corrupt our in-memory state.
506        Self::write_payment(ffs, &payment)?;
507
508        // --- 'Commit' by updating our in-memory state --- //
509
510        // Update our indexes
511        if payment.is_pending() {
512            state.pending_index.insert(created_index);
513        } else {
514            state.pending_index.remove(&created_index);
515        }
516        if let Some(old_index) = maybe_existing.map(|p| p.updated_index()) {
517            state.updates_index.remove(&old_index);
518        }
519        state
520            .updates_index
521            .insert(payment.updated_index(), created_index);
522        state.id_index.insert(payment.id, created_index);
523
524        // Update main payments map at the end to avoid a clone
525        state.payments.insert(created_index, payment);
526
527        if already_existed {
528            Ok((0, 1))
529        } else {
530            Ok((1, 0))
531        }
532    }
533
534    /// Write a payment to on-disk storage as JSON bytes. The caller is
535    /// responsible for updating the in-memory [`PaymentsDb`] state and indices.
536    // Making this an associated fn avoids some borrow checker issues.
537    fn write_payment(ffs: &F, payment: &BasicPaymentV2) -> io::Result<()> {
538        let filename = payment.created_index().to_string();
539        let data =
540            serde_json::to_vec(&payment).expect("Failed to serialize payment");
541        ffs.write(&filename, &data)
542    }
543
544    /// Record that a successful sync just completed at the given local time.
545    ///
546    /// Persists the metadata first, then updates in-memory state.
547    fn record_synced_at(&self, now: TimestampMs) -> io::Result<()> {
548        let metadata = PaymentsDbMetadata {
549            last_synced_at: Some(now),
550        };
551        let data = serde_json::to_vec(&metadata)
552            .expect("Failed to serialize metadata");
553        self.ffs.write(METADATA_FILENAME, &data)?;
554
555        self.state.write().unwrap().last_synced_at = Some(now);
556        Ok(())
557    }
558
559    /// Check the integrity of the whole PaymentsDb.
560    ///
561    /// (1.) The in-memory state should not be corrupted.
562    /// (2.) The current on-disk state should match the in-memory state.
563    #[cfg(test)]
564    fn debug_assert_invariants(&self) {
565        if cfg!(not(debug_assertions)) {
566            return;
567        }
568
569        let state = self.state.read().unwrap();
570
571        // (1.)
572        state.debug_assert_invariants();
573
574        // (2.)
575        let on_disk_state = PaymentsDbState::read(&self.ffs)
576            .expect("Failed to re-read on-disk state");
577        assert_eq!(on_disk_state, *state);
578    }
579}
580
581impl PaymentsDbState {
582    /// Create a new empty [`PaymentsDbState`]. Does not touch disk/storage.
583    fn empty() -> Self {
584        Self {
585            payments: BTreeMap::new(),
586            pending_index: BTreeSet::new(),
587            updates_index: BTreeMap::new(),
588            id_index: HashMap::new(),
589            last_synced_at: None,
590        }
591    }
592
593    /// Read the DB state from disk.
594    fn read(ffs: &impl Ffs) -> anyhow::Result<Self> {
595        let mut buf = Vec::<u8>::new();
596        let mut payments = Vec::<BasicPaymentV2>::new();
597        let mut last_synced_at = None;
598
599        ffs.read_dir_visitor(|filename| {
600            // The metadata file lives alongside the payment files.
601            if filename == METADATA_FILENAME {
602                buf.clear();
603                ffs.read_into(filename, &mut buf)?;
604                let metadata =
605                    serde_json::from_slice::<PaymentsDbMetadata>(&buf)
606                        .context(METADATA_FILENAME)
607                        .context("Failed to deserialize payments db metadata")
608                        .map_err(io_error_invalid_data)?;
609                last_synced_at = metadata.last_synced_at;
610                return Ok(());
611            }
612
613            // Parse created_at index from filename; skip unrecognized files.
614            let created_index = match PaymentCreatedIndex::from_str(filename) {
615                Ok(idx) => idx,
616                Err(e) => {
617                    warn!(
618                        %filename,
619                        "Error: unrecognized filename in payments dir: {e:#}"
620                    );
621                    return Ok(());
622                }
623            };
624
625            // Read payment into buffer
626            buf.clear();
627            ffs.read_into(filename, &mut buf)?;
628
629            // Deserialize payment
630            let payment = serde_json::from_slice::<BasicPaymentV2>(&buf)
631                .with_context(|| filename.to_owned())
632                .context("Failed to deserialize payment file")
633                .map_err(io_error_invalid_data)?;
634
635            // Sanity check: Index in filename should match index in payment.
636            let payment_created_index = payment.created_index();
637            if created_index != payment_created_index {
638                return Err(io_error_invalid_data(format!(
639                    "Payment DB corruption: filename index '{filename}'
640                     different from index in contents '{payment_created_index}'"
641                )));
642            }
643
644            // Collect the payment
645            payments.push(payment);
646
647            Ok(())
648        })
649        .context("Failed to read payments db, possibly corrupted?")?;
650
651        Ok(Self::from_vec(payments, last_synced_at))
652    }
653
654    fn from_vec(
655        payments: Vec<BasicPaymentV2>,
656        last_synced_at: Option<TimestampMs>,
657    ) -> Self {
658        let payments = payments
659            .into_iter()
660            .map(|p| (p.created_index(), p))
661            .collect();
662
663        let pending_index = build_index::pending_index(&payments);
664        let updates_index = build_index::updates_index(&payments);
665        let id_index = build_index::id_index(&payments);
666
667        Self {
668            payments,
669            pending_index,
670            updates_index,
671            id_index,
672            last_synced_at,
673        }
674    }
675
676    fn num_payments(&self) -> usize {
677        self.payments.len()
678    }
679
680    fn num_pending(&self) -> usize {
681        self.pending_index.len()
682    }
683
684    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
685    fn num_finalized(&self) -> usize {
686        self.payments.len() - self.pending_index.len()
687    }
688
689    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
690    fn num_pending_not_junk(&self) -> usize {
691        self.pending_index
692            .iter()
693            .filter_map(|created_idx| self.payments.get(created_idx))
694            .filter(|p| p.is_pending_not_junk())
695            .count()
696    }
697
698    // TODO(max): If needed, we can add an index for this.
699    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
700    fn num_finalized_not_junk(&self) -> usize {
701        self.payments
702            .values()
703            .filter(|p| p.is_finalized_not_junk())
704            .count()
705    }
706
707    fn latest_updated_index(&self) -> Option<PaymentUpdatedIndex> {
708        self.updates_index.last_key_value().map(|(idx, _)| *idx)
709    }
710
711    fn get_payment_by_id(&self, id: &PaymentId) -> Option<&BasicPaymentV2> {
712        self.payments.get(self.id_index.get(id)?)
713    }
714
715    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
716    fn get_payment_by_scroll_idx(
717        &self,
718        scroll_idx: usize,
719    ) -> Option<&BasicPaymentV2> {
720        self.payments.values().nth_back(scroll_idx)
721    }
722
723    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
724    fn get_pending_payment_by_scroll_idx(
725        &self,
726        scroll_idx: usize,
727    ) -> Option<&BasicPaymentV2> {
728        self.pending_index
729            .iter()
730            .nth_back(scroll_idx)
731            .and_then(|created_idx| self.payments.get(created_idx))
732    }
733
734    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
735    fn get_pending_not_junk_payment_by_scroll_idx(
736        &self,
737        scroll_idx: usize,
738    ) -> Option<&BasicPaymentV2> {
739        self.pending_index
740            .iter()
741            .rev()
742            .filter_map(|created_idx| self.payments.get(created_idx))
743            .filter(|p| p.is_pending_not_junk())
744            .nth_back(scroll_idx)
745    }
746
747    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
748    fn get_finalized_payment_by_scroll_idx(
749        &self,
750        scroll_idx: usize,
751    ) -> Option<&BasicPaymentV2> {
752        self.payments
753            .values()
754            .filter(|p| p.is_finalized())
755            .nth_back(scroll_idx)
756    }
757
758    #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
759    fn get_finalized_not_junk_payment_by_scroll_idx(
760        &self,
761        scroll_idx: usize,
762    ) -> Option<&BasicPaymentV2> {
763        self.payments
764            .values()
765            .filter(|p| p.is_finalized_not_junk())
766            .nth_back(scroll_idx)
767    }
768
769    /// List payments with cursor-based pagination.
770    ///
771    /// Returns `(payments, next_index)`.
772    fn list_payments(
773        &self,
774        filter: &PaymentFilter,
775        order: Order,
776        limit: usize,
777        after: Option<&PaymentCreatedIndex>,
778    ) -> (Vec<BasicPaymentV2>, Option<PaymentCreatedIndex>) {
779        if limit == 0 {
780            return (Vec::new(), None);
781        }
782
783        let matches_filter = |p: &&BasicPaymentV2| match filter {
784            PaymentFilter::All => true,
785            PaymentFilter::Pending => p.status == PaymentStatus::Pending,
786            PaymentFilter::Completed => p.status == PaymentStatus::Completed,
787            PaymentFilter::Failed => p.status == PaymentStatus::Failed,
788            PaymentFilter::Finalized => p.status != PaymentStatus::Pending,
789        };
790
791        // Fetch `limit + 1` to detect whether there's a next page.
792        let take = limit.saturating_add(1);
793
794        let mut payments: Vec<BasicPaymentV2> = match (order, after) {
795            (Order::Asc, Some(c)) => self
796                .payments
797                .range((Bound::Excluded(c), Bound::Unbounded))
798                .map(|(_, p)| p)
799                .filter(matches_filter)
800                .take(take)
801                .cloned()
802                .collect(),
803            (Order::Asc, None) => self
804                .payments
805                .values()
806                .filter(matches_filter)
807                .take(take)
808                .cloned()
809                .collect(),
810            (Order::Desc, Some(c)) => self
811                .payments
812                .range(..c)
813                .rev()
814                .map(|(_, p)| p)
815                .filter(matches_filter)
816                .take(take)
817                .cloned()
818                .collect(),
819            (Order::Desc, None) => self
820                .payments
821                .values()
822                .rev()
823                .filter(matches_filter)
824                .take(take)
825                .cloned()
826                .collect(),
827        };
828
829        // If we got more than `limit`, there's a next page.
830        let has_more = payments.len() > limit;
831        if has_more {
832            payments.truncate(limit);
833        }
834        let next_index = has_more.then(|| {
835            payments
836                .last()
837                .expect("has_more implies non-empty")
838                .created_index()
839        });
840
841        (payments, next_index)
842    }
843
844    /// Get a batch of payments in ascending `updated_at` order, starting from
845    /// `start_index`, exclusive. If `None`, starts from the oldest-updated
846    /// payment, inclusive.
847    fn get_updated_payments(
848        &self,
849        start_index: Option<PaymentUpdatedIndex>,
850        limit: usize,
851    ) -> Vec<BasicPaymentV2> {
852        let start = match start_index {
853            Some(start_index) => Bound::Excluded(start_index),
854            None => Bound::Unbounded,
855        };
856
857        self.updates_index
858            .range((start, Bound::Unbounded))
859            .filter_map(|(_, created_idx)| self.payments.get(created_idx))
860            .take(limit)
861            .cloned()
862            .collect()
863    }
864
865    #[cfg(test)]
866    fn is_empty(&self) -> bool {
867        self.payments.is_empty()
868    }
869
870    /// Check the integrity of the in-memory state.
871    #[cfg(test)]
872    fn debug_assert_invariants(&self) {
873        if cfg!(not(debug_assertions)) {
874            return;
875        }
876
877        // --- `payments` invariants: --- //
878
879        // Each payment is stored under its own created_at index
880        for (idx, payment) in &self.payments {
881            assert_eq!(*idx, payment.created_index());
882        }
883
884        // --- `pending_index` invariants: --- //
885
886        // Rebuilding the index recreates the same index exactly
887        let rebuilt_pending_index = build_index::pending_index(&self.payments);
888        assert_eq!(rebuilt_pending_index, self.pending_index);
889
890        // All pending payments are in the index
891        // (in case there is a bug in `build_index::pending_index`)
892        assert!(
893            self.payments
894                .values()
895                .filter(|p| p.is_pending())
896                .all(|p| self.pending_index.contains(&p.created_index()))
897        );
898
899        // --- `updates_index` invariants: --- //
900
901        // Rebuilding the index recreates the same index exactly
902        let rebuilt_updates_index = build_index::updates_index(&self.payments);
903        assert_eq!(rebuilt_updates_index, self.updates_index);
904
905        // Every payment is indexed
906        assert_eq!(self.updates_index.len(), self.payments.len());
907
908        // --- `id_index` invariants: --- //
909
910        // Rebuilding the index recreates the same index exactly
911        let rebuilt_id_index = build_index::id_index(&self.payments);
912        assert_eq!(rebuilt_id_index, self.id_index);
913
914        // Every payment is indexed (i.e. no two payments share an id)
915        assert_eq!(self.id_index.len(), self.payments.len());
916    }
917}
918
919mod build_index {
920    use super::*;
921
922    /// Build the `pending_index` from the given payments.
923    pub(super) fn pending_index(
924        payments: &BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
925    ) -> BTreeSet<PaymentCreatedIndex> {
926        payments
927            .iter()
928            .filter(|(_, p)| p.is_pending())
929            .map(|(idx, _)| *idx)
930            .collect()
931    }
932
933    /// Build the `updates_index` from the given payments.
934    pub(super) fn updates_index(
935        payments: &BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
936    ) -> BTreeMap<PaymentUpdatedIndex, PaymentCreatedIndex> {
937        payments
938            .iter()
939            .map(|(created_idx, p)| (p.updated_index(), *created_idx))
940            .collect()
941    }
942
943    /// Build the `id_index` from the given payments.
944    pub(super) fn id_index(
945        payments: &BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
946    ) -> HashMap<PaymentId, PaymentCreatedIndex> {
947        payments.keys().map(|idx| (idx.id, *idx)).collect()
948    }
949}
950
951/// Construct an [`io::Error`] of kind `InvalidData` from the given error.
952fn io_error_invalid_data(
953    error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
954) -> io::Error {
955    io::Error::new(io::ErrorKind::InvalidData, error)
956}
957
958#[cfg(test)]
959mod test_utils {
960    use std::{
961        cell::{Cell, RefCell},
962        rc::Rc,
963    };
964
965    use lexe_common::byte_str::ByteStr;
966    use proptest::{
967        prelude::{Strategy, any},
968        sample::SizeRange,
969    };
970
971    use super::*;
972
973    /// Payment state shared by the [`MockNode`] and [`MockGateway`], so a test
974    /// can mutate it and have both mocks see the change.
975    pub(super) type MockPayments =
976        Rc<RefCell<BTreeMap<PaymentUpdatedIndex, BasicPaymentV2>>>;
977
978    /// Build [`MockPayments`] from a map of created_at index -> payment.
979    pub(super) fn mock_payments_from_created_at(
980        payments: BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
981    ) -> MockPayments {
982        let payments = payments
983            .into_values()
984            .map(|p| (p.updated_index(), p))
985            .collect();
986        Rc::new(RefCell::new(payments))
987    }
988
989    // --- Node --- //
990
991    pub(super) struct MockNode {
992        pub payments: MockPayments,
993        /// The number of times this MockNode's endpoint was invoked.
994        pub call_counter: Cell<usize>,
995    }
996
997    impl MockNode {
998        pub(super) fn new(payments: MockPayments) -> Self {
999            Self {
1000                payments,
1001                call_counter: Cell::new(0),
1002            }
1003        }
1004    }
1005
1006    impl UserNodeRunSyncApi for MockNode {
1007        /// GET /node/v1/payments/updated [`command::GetUpdatedPayments`]
1008        ///                            -> [`VecDbPaymentV2`]
1009        async fn get_updated_payments(
1010            &self,
1011            req: command::GetUpdatedPayments,
1012        ) -> Result<VecBasicPaymentV2, NodeApiError> {
1013            self.call_counter.update(|n| n + 1);
1014
1015            let limit = req.limit.unwrap_or(u16::MAX);
1016
1017            let payments = match req.start_index {
1018                Some(start_index) => self
1019                    .payments
1020                    .borrow()
1021                    .iter()
1022                    .filter(|(idx, _)| &start_index < *idx)
1023                    .take(limit as usize)
1024                    .map(|(_idx, payment)| payment.clone())
1025                    .collect(),
1026                None => self
1027                    .payments
1028                    .borrow()
1029                    .iter()
1030                    .take(limit as usize)
1031                    .map(|(_idx, payment)| payment.clone())
1032                    .collect(),
1033            };
1034
1035            Ok(VecBasicPaymentV2 { payments })
1036        }
1037    }
1038
1039    /// A dummy token.
1040    pub(super) fn mock_auth() -> BearerAuthToken {
1041        BearerAuthToken(ByteStr::from_static("mock-token"))
1042    }
1043
1044    // --- Gateway --- //
1045
1046    /// A mock gateway that reports the latest update among the payments in an
1047    /// external payments `BTreeMap`. Intended for use with [`MockNode`].
1048    pub(super) struct MockGateway {
1049        pub payments: MockPayments,
1050    }
1051
1052    impl MockGateway {
1053        pub(super) fn new(payments: MockPayments) -> Self {
1054            Self { payments }
1055        }
1056    }
1057
1058    impl UserGatewaySyncApi for MockGateway {
1059        async fn latest_payment_update(
1060            &self,
1061            _auth: BearerAuthToken,
1062        ) -> Result<LatestPaymentUpdateResponse, GatewayApiError> {
1063            let resp = LatestPaymentUpdateResponse {
1064                latest_update: self
1065                    .payments
1066                    .borrow()
1067                    .last_key_value()
1068                    .map(|kv| *kv.0),
1069            };
1070            Ok(resp)
1071        }
1072    }
1073
1074    // --- Payments --- //
1075
1076    pub(super) fn any_payments(
1077        approx_size: impl Into<SizeRange>,
1078    ) -> impl Strategy<Value = BTreeMap<PaymentCreatedIndex, BasicPaymentV2>>
1079    {
1080        proptest::collection::vec(any::<BasicPaymentV2>(), approx_size)
1081            .prop_map(|payments| {
1082                payments
1083                    .into_iter()
1084                    .map(|payment| (payment.created_index(), payment))
1085                    .collect::<BTreeMap<_, _>>()
1086            })
1087    }
1088}
1089
1090#[cfg(test)]
1091mod test {
1092    use std::{collections::HashSet, rc::Rc, time::Duration};
1093
1094    use lexe_api::types::payments::PaymentStatus;
1095    use lexe_crypto::rng::{FastRng, RngExt};
1096    use proptest::{
1097        collection::vec, prelude::any, proptest, sample::Index,
1098        test_runner::Config,
1099    };
1100    use tempfile::tempdir;
1101
1102    use super::{test_utils::*, *};
1103    use crate::unstable::ffs::{DiskFs, test_utils::InMemoryFfs};
1104
1105    #[test]
1106    fn read_from_empty() {
1107        let mock_ffs = InMemoryFfs::new();
1108        let mock_ffs_db = PaymentsDb::read(mock_ffs).unwrap();
1109        assert!(mock_ffs_db.state.read().unwrap().is_empty());
1110        mock_ffs_db.debug_assert_invariants();
1111
1112        let tempdir = tempfile::tempdir().unwrap();
1113        let temp_fs =
1114            DiskFs::create_dir_all(tempdir.path().to_path_buf()).unwrap();
1115        let temp_fs_db = PaymentsDb::read(temp_fs).unwrap();
1116        assert!(temp_fs_db.state.read().unwrap().is_empty());
1117        temp_fs_db.debug_assert_invariants();
1118
1119        assert_eq!(
1120            *mock_ffs_db.state.read().unwrap(),
1121            *temp_fs_db.state.read().unwrap()
1122        );
1123    }
1124
1125    #[test]
1126    fn test_upsert() {
1127        fn visit_batches<T>(
1128            iter: &mut impl Iterator<Item = T>,
1129            batch_sizes: Vec<usize>,
1130            mut f: impl FnMut(Vec<T>),
1131        ) {
1132            let batch_sizes = batch_sizes.into_iter();
1133
1134            for batch_size in batch_sizes {
1135                let batch = take_n(iter, batch_size);
1136                let batch_len = batch.len();
1137
1138                if batch_len == 0 {
1139                    return;
1140                }
1141
1142                f(batch);
1143
1144                if batch_len < batch_size {
1145                    return;
1146                }
1147            }
1148
1149            let batch = iter.collect::<Vec<_>>();
1150
1151            if !batch.is_empty() {
1152                f(batch);
1153            }
1154        }
1155
1156        fn take_n<T>(iter: &mut impl Iterator<Item = T>, n: usize) -> Vec<T> {
1157            let mut out = Vec::with_capacity(n);
1158
1159            while out.len() < n {
1160                match iter.next() {
1161                    Some(value) => out.push(value),
1162                    None => break,
1163                }
1164            }
1165
1166            out
1167        }
1168
1169        proptest!(
1170            Config::with_cases(10),
1171            |(
1172                rng: FastRng,
1173                payments in test_utils::any_payments(0..20),
1174                batch_sizes in vec(1_usize..20, 0..5),
1175            )| {
1176                let tempdir = tempdir().unwrap();
1177                let temp_fs = DiskFs::create_dir_all(tempdir.path().to_path_buf()).unwrap();
1178                let temp_fs_db = PaymentsDb::empty(temp_fs);
1179
1180                let mock_ffs = InMemoryFfs::from_rng(rng);
1181                let mock_ffs_db = PaymentsDb::empty(mock_ffs);
1182
1183                let mut payments_iter = payments.clone().into_values();
1184                visit_batches(&mut payments_iter, batch_sizes, |new_payment_batch| {
1185                    let _ = mock_ffs_db.upsert_payments(
1186                        new_payment_batch.clone()
1187                    ).unwrap();
1188                    let _ = temp_fs_db.upsert_payments(new_payment_batch).unwrap();
1189
1190                    mock_ffs_db.debug_assert_invariants();
1191                    temp_fs_db.debug_assert_invariants();
1192                });
1193
1194                assert_eq!(
1195                    *mock_ffs_db.state.read().unwrap(),
1196                    *temp_fs_db.state.read().unwrap()
1197                );
1198            }
1199        );
1200    }
1201
1202    /// Tailing the db by `updated_at` index visits every payment exactly once,
1203    /// in update order.
1204    #[test]
1205    fn test_get_updated_payments() {
1206        proptest!(Config::with_cases(16), |(payments in test_utils::any_payments(0..20))| {
1207            let db = PaymentsDb::empty(InMemoryFfs::new());
1208            db.upsert_payments(payments.clone().into_values()).unwrap();
1209
1210            let mut expected = payments.into_values().collect::<Vec<_>>();
1211            expected.sort_unstable_by_key(BasicPaymentV2::updated_index);
1212
1213            // No start index returns everything, in update order.
1214            assert_eq!(db.get_updated_payments(None, usize::MAX), expected);
1215
1216            // Tailing one at a time yields the same sequence.
1217            let mut start_index = None;
1218            for expected_payment in &expected {
1219                assert_eq!(
1220                    &db.get_updated_payments(start_index, 1),
1221                    std::slice::from_ref(expected_payment),
1222                );
1223                start_index = Some(expected_payment.updated_index());
1224            }
1225            assert!(db.get_updated_payments(start_index, 1).is_empty());
1226        });
1227    }
1228
1229    /// Every payment can be looked up by its id, both after upserts and after
1230    /// a reload from disk; unknown ids miss.
1231    #[test]
1232    fn test_get_payment_by_id() {
1233        proptest!(Config::with_cases(16), |(mut payments in test_utils::any_payments(1..20))| {
1234            // Hold one payment back so we can look up an unknown id.
1235            let (_, unknown) = payments.pop_last().unwrap();
1236
1237            let assert_lookups = |db: &PaymentsDb<InMemoryFfs>| {
1238                for payment in payments.values() {
1239                    let found = db.get_payment_by_id(&payment.id);
1240                    assert_eq!(found.as_ref(), Some(payment));
1241                }
1242                assert_eq!(db.get_payment_by_id(&unknown.id), None);
1243            };
1244
1245            let db = PaymentsDb::empty(InMemoryFfs::new());
1246            db.upsert_payments(payments.clone().into_values()).unwrap();
1247            assert_lookups(&db);
1248
1249            let db = PaymentsDb::read(db.ffs).unwrap();
1250            assert_lookups(&db);
1251        });
1252    }
1253
1254    #[tokio::test]
1255    async fn test_sync_empty() {
1256        let mock_node_client = MockNode::new(MockPayments::default());
1257        let mock_ffs = InMemoryFfs::new();
1258        let db = PaymentsDb::empty(mock_ffs);
1259
1260        sync_payments(
1261            &db,
1262            &MockGateway::new(Rc::clone(&mock_node_client.payments)),
1263            &mock_node_client,
1264            mock_auth(),
1265            5,
1266        )
1267        .await
1268        .unwrap();
1269
1270        assert!(db.state.read().unwrap().is_empty());
1271        db.debug_assert_invariants();
1272    }
1273
1274    /// When the gateway reports no updates, we skip the node entirely, but
1275    /// still record the sync time so the cache reads as fresh.
1276    #[tokio::test]
1277    async fn test_sync_skips_node() {
1278        let mock_node = MockNode::new(MockPayments::default());
1279        let mock_gateway = MockGateway::new(Rc::clone(&mock_node.payments));
1280        let db = PaymentsDb::empty(InMemoryFfs::new());
1281
1282        let summary =
1283            sync_payments(&db, &mock_gateway, &mock_node, mock_auth(), 5)
1284                .await
1285                .unwrap();
1286
1287        assert_eq!(mock_node.call_counter.get(), 0);
1288        assert_eq!(summary.num_new, 0);
1289        assert_eq!(summary.num_updated, 0);
1290        assert_eq!(summary.latest_updated_index, None);
1291        assert!(db.last_synced_at().is_some());
1292        db.debug_assert_invariants();
1293    }
1294
1295    /// `last_synced_at` is set on every sync (even with no payments),
1296    /// survives a reload from disk, and is reset by `clear`.
1297    #[tokio::test]
1298    async fn test_last_synced_at() {
1299        let mock_node = MockNode::new(MockPayments::default());
1300        let mock_gateway = MockGateway::new(Rc::clone(&mock_node.payments));
1301        let db = PaymentsDb::empty(InMemoryFfs::new());
1302
1303        // Never synced yet.
1304        assert_eq!(db.last_synced_at(), None);
1305
1306        // A sync records the local-clock sync time, even with no payments.
1307        let before = TimestampMs::now();
1308        sync_payments(&db, &mock_gateway, &mock_node, mock_auth(), 5)
1309            .await
1310            .unwrap();
1311        let after = TimestampMs::now();
1312        let synced_at = db.last_synced_at().expect("sync should set time");
1313        assert!((before..=after).contains(&synced_at));
1314        db.debug_assert_invariants();
1315
1316        // The sync time survives a reload from disk.
1317        let db = PaymentsDb::read(db.ffs).unwrap();
1318        assert_eq!(db.last_synced_at(), Some(synced_at));
1319
1320        // Clearing resets it.
1321        db.clear().unwrap();
1322        assert_eq!(db.last_synced_at(), None);
1323
1324        // Re-sync, then deleting `metadata.json` also resets it on reload.
1325        sync_payments(&db, &mock_gateway, &mock_node, mock_auth(), 5)
1326            .await
1327            .unwrap();
1328        assert!(db.last_synced_at().is_some());
1329        db.ffs.delete(METADATA_FILENAME).unwrap();
1330        let db = PaymentsDb::read(db.ffs).unwrap();
1331        assert_eq!(db.last_synced_at(), None);
1332    }
1333
1334    /// Backwards compat: pre-existing dbs with no `metadata.json` still read
1335    /// fine, with `last_synced_at` defaulting to `None`.
1336    #[test]
1337    fn test_read_without_metadata() {
1338        proptest!(Config::with_cases(8), |(payments in test_utils::any_payments(0..10))| {
1339            let ffs = InMemoryFfs::new();
1340
1341            // Write only payment files; no metadata.json (simulates old db).
1342            for payment in payments.values() {
1343                PaymentsDb::<InMemoryFfs>::write_payment(&ffs, payment).unwrap();
1344            }
1345
1346            let db = PaymentsDb::read(ffs).unwrap();
1347            assert_eq!(db.last_synced_at(), None);
1348            assert_eq!(db.num_payments(), payments.len());
1349            db.debug_assert_invariants();
1350        });
1351    }
1352
1353    #[test]
1354    fn test_sync() {
1355        /// Assert that the payments in the db equal those in the mock node.
1356        fn assert_db_payments_eq(
1357            db_payments: &BTreeMap<PaymentCreatedIndex, BasicPaymentV2>,
1358            node_payments: &BTreeMap<PaymentUpdatedIndex, BasicPaymentV2>,
1359        ) {
1360            assert_eq!(db_payments.len(), node_payments.len());
1361            db_payments.iter().for_each(|(_created_idx, payment)| {
1362                let node_payment =
1363                    node_payments.get(&payment.updated_index()).unwrap();
1364                assert_eq!(payment, node_payment);
1365            });
1366            node_payments.iter().for_each(|(_updated_idx, payment)| {
1367                let db_payment =
1368                    db_payments.get(&payment.created_index()).unwrap();
1369                assert_eq!(payment, db_payment);
1370            });
1371        }
1372
1373        let rt = tokio::runtime::Builder::new_current_thread()
1374            .build()
1375            .unwrap();
1376
1377        proptest!(
1378            Config::with_cases(4),
1379            |(
1380                mut rng: FastRng,
1381                payments in test_utils::any_payments(1..20),
1382                req_batch_size in 1_u16..5,
1383                finalize_indexes in
1384                    proptest::collection::vec(any::<Index>(), 1..5),
1385            )| {
1386                let mock_node =
1387                    MockNode::new(mock_payments_from_created_at(payments));
1388                let mock_gateway =
1389                    MockGateway::new(Rc::clone(&mock_node.payments));
1390
1391                let mut rng2 = FastRng::from_u64(rng.gen_u64());
1392                let mock_ffs = InMemoryFfs::from_rng(rng);
1393
1394                // Sync empty DB from node
1395                let db = PaymentsDb::empty(mock_ffs);
1396                let summary = rt.block_on(sync_payments(
1397                    &db,
1398                    &mock_gateway,
1399                    &mock_node,
1400                    mock_auth(),
1401                    req_batch_size,
1402                ))
1403                .unwrap();
1404                assert_eq!(
1405                    summary.latest_updated_index,
1406                    db.latest_updated_index(),
1407                );
1408                assert_db_payments_eq(
1409                    &db.state.read().unwrap().payments,
1410                    &mock_node.payments.borrow(),
1411                );
1412                db.debug_assert_invariants();
1413
1414                // Reread db from ffs and resync - should still match node
1415                let mock_ffs = db.ffs;
1416                let db = PaymentsDb::read(mock_ffs).unwrap();
1417                let summary = rt.block_on(sync_payments(
1418                    &db,
1419                    &mock_gateway,
1420                    &mock_node,
1421                    mock_auth(),
1422                    req_batch_size,
1423                ))
1424                .unwrap();
1425                assert_eq!(summary.num_new, 0);
1426                assert_eq!(summary.num_updated, 0);
1427                assert_eq!(
1428                    summary.latest_updated_index,
1429                    db.latest_updated_index(),
1430                );
1431                assert!(summary.latest_updated_index.is_some());
1432                assert_db_payments_eq(
1433                    &db.state.read().unwrap().payments,
1434                    &mock_node.payments.borrow(),
1435                );
1436                db.debug_assert_invariants();
1437
1438                // Finalize some payments
1439                let finalize_some_payments = || {
1440                    let pending_payments = mock_node
1441                        .payments
1442                        .borrow()
1443                        .values()
1444                        .filter(|p| p.is_pending())
1445                        .cloned()
1446                        .collect::<Vec<_>>();
1447
1448                    if pending_payments.is_empty() {
1449                        return;
1450                    }
1451
1452                    // Simulates the current time
1453                    //
1454                    // We bump it before every update to ensure finalized
1455                    // payments have a later updated_at than in our DB
1456                    let mut current_time = db
1457                        .state
1458                        .read()
1459                        .unwrap()
1460                        .latest_updated_index()
1461                        .expect("DB should have payments")
1462                        .updated_at;
1463
1464                    // The array indices of the payments inside
1465                    // `pending_payments` to finalize
1466                    let finalize_idxs = finalize_indexes
1467                        .into_iter()
1468                        .map(|index| index.index(pending_payments.len()))
1469                        // Collect into HashSet to dedup without sorting
1470                        .collect::<HashSet<_>>();
1471
1472                    for finalize_idx in finalize_idxs {
1473                        // The updated_at index of the payment to finalize
1474                        let final_updated_idx =
1475                            pending_payments[finalize_idx].updated_index();
1476
1477                        // Remove the payment to finalize from map
1478                        let mut payment = mock_node
1479                            .payments
1480                            .borrow_mut()
1481                            .remove(&final_updated_idx)
1482                            .unwrap();
1483
1484                        // The finalized status to set for this payment
1485                        let new_status = if rng2.gen_boolean() {
1486                            PaymentStatus::Completed
1487                        } else {
1488                            PaymentStatus::Failed
1489                        };
1490
1491                        // Bump the current time so new updated_at is fresh
1492                        let bump_u64 = u64::from(rng2.gen_range_u32(1..11));
1493                        let bump_dur = Duration::from_millis(bump_u64);
1494                        current_time = current_time.saturating_add(bump_dur);
1495
1496                        // Update payment
1497                        payment.status = new_status;
1498                        payment.updated_at = current_time;
1499
1500                        // Re-insert with new updated_at as the key
1501                        let new_updated_index = payment.updated_index();
1502                        mock_node
1503                            .payments
1504                            .borrow_mut()
1505                            .insert(new_updated_index, payment);
1506                        }
1507                };
1508
1509                finalize_some_payments();
1510
1511                // resync -- should pick up the finalized payments
1512                let summary = rt.block_on(sync_payments(
1513                    &db,
1514                    &mock_gateway,
1515                    &mock_node,
1516                    mock_auth(),
1517                    req_batch_size,
1518                ))
1519                .unwrap();
1520                assert_eq!(
1521                    summary.latest_updated_index,
1522                    db.latest_updated_index(),
1523                );
1524
1525                assert_db_payments_eq(
1526                    &db.state.read().unwrap().payments,
1527                    &mock_node.payments.borrow(),
1528                );
1529                db.debug_assert_invariants();
1530            }
1531        );
1532    }
1533}