Skip to main content

osmflow_sync/
follow.rs

1//! Keeping a database current: updates in a loop that waits for newer diffs and stops when asked.
2
3use std::error::Error;
4use std::time::Duration;
5
6use osmflow::osc::Replication;
7
8use crate::db::DbState;
9use crate::update::batch_end;
10use crate::{OpenMirror, Stop, StopReason, SyncError, UpdateOpts, UpdateStats};
11
12/// How [`OpenMirror::follow`] keeps up with the replication stream.
13#[derive(Debug, Clone)]
14pub struct FollowOpts {
15    /// The most diffs applied in one transaction, as [`UpdateOpts::max_diffs`]; 60 by default.
16    pub max_diffs: u64,
17    /// How long to wait for a newer diff when up to date, 60 seconds by default. Unused with `once`.
18    pub wait: Duration,
19    /// Return when up to date instead of waiting for newer diffs.
20    pub once: bool,
21    /// Asks to stop; checked before each batch and while waiting.
22    pub stop: Stop,
23}
24
25impl Default for FollowOpts {
26    fn default() -> Self {
27        Self {
28            max_diffs: 60,
29            wait: Duration::from_secs(60),
30            once: false,
31            stop: Stop::default(),
32        }
33    }
34}
35
36/// An error of [`OpenMirror::follow`]: the update's, or the one the caller's function returned.
37#[derive(Debug, thiserror::Error)]
38pub enum FollowError<E: Error + 'static> {
39    /// Reading the stream or applying a batch failed.
40    #[error(transparent)]
41    Sync(#[from] SyncError),
42    /// The function called after a batch failed. The batch itself was committed.
43    #[error(transparent)]
44    Batch(E),
45}
46
47impl OpenMirror {
48    /// Applies the diffs after the database's sequence one batch at a time, and keeps doing it as the stream grows,
49    /// until the database is up to date with `once`, or a stop is asked for through [`FollowOpts::stop`].
50    ///
51    /// After each batch commits, `after_batch` gets the mirror, to read from it, and that batch's statistics: the
52    /// place for work that follows the database, such as updating tables derived from it. A stop is looked at before
53    /// each batch and while waiting, so the function always runs for a batch before the loop returns. An error from
54    /// it ends the loop with [`FollowError::Batch`].
55    ///
56    /// The statistics returned add up the batches. [`UpdateStats::stopped`] says why a stop ended the loop, except
57    /// for the time limit passing while the database is up to date, waiting for a newer diff: that is how a follow
58    /// with a time limit ends when all went well, as `once` does.
59    pub fn follow<E: Error + 'static>(
60        &mut self,
61        replication: &Replication,
62        opts: &FollowOpts,
63        mut after_batch: impl FnMut(&Self, &UpdateStats) -> Result<(), E>,
64    ) -> Result<UpdateStats, FollowError<E>> {
65        let mut total = UpdateStats {
66            sequence: DbState::read(&mut self.client)?.sequence,
67            ..UpdateStats::default()
68        };
69        loop {
70            // Up to date is looked at before the stop, so a time limit that passes during the last batch ends the
71            // loop as up to date, as it does while waiting
72            let next = total.sequence.cast_unsigned() + 1;
73            let latest = replication.state().map_err(SyncError::from)?.sequence;
74            if latest < next {
75                if opts.once {
76                    return Ok(total);
77                }
78                match opts.stop.wait(opts.wait) {
79                    None => continue,
80                    Some(StopReason::TimeLimit) => return Ok(total),
81                    Some(StopReason::Requested) => {
82                        total.stopped = Some(StopReason::Requested);
83                        return Ok(total);
84                    }
85                }
86            }
87            let batch = self.update(
88                replication,
89                &UpdateOpts {
90                    max_diffs: opts.max_diffs,
91                    until: Some(batch_end(next, latest, opts.max_diffs)),
92                    stop: opts.stop.clone(),
93                },
94            )?;
95            total.add(&batch);
96            if batch.stopped.is_some() {
97                return Ok(total);
98            }
99            after_batch(self, &batch).map_err(FollowError::Batch)?;
100        }
101    }
102}