sqlive/database_changes.rs
1//! Commit notifications for work that waits on what the database holds.
2
3use crate::handle::{CommitSubscription, Failed};
4
5/// A live commit observation. `DatabaseChanges` merges several commits into
6/// one change and ends when the writer closes. Its methods convert the
7/// handle's failure into `E` and return that.
8pub struct DatabaseChanges<E> {
9 commits: CommitSubscription,
10 reads: crate::ReadSet,
11 first: bool,
12 failed: Failed<E>,
13}
14
15impl<E> DatabaseChanges<E> {
16 /// Report each commit `commits` sees that changes what `reads` read, and
17 /// turn the handle's failure into `E` with `failed`. With `first`, the
18 /// first report is the state now.
19 pub(crate) fn new(
20 commits: CommitSubscription,
21 reads: crate::ReadSet,
22 first: bool,
23 failed: Failed<E>,
24 ) -> Self {
25 Self { commits, reads, first, failed }
26 }
27
28 /// Whether a relevant commit happened since the previous observation,
29 /// without waiting; the first call reports the initial state.
30 pub fn take_changed(&mut self) -> Result<bool, E> {
31 let state = self.commits.state();
32 if let Some(stop) = state.stopped_by() {
33 return Err((self.failed)(stop));
34 }
35 if self.first || state.changed {
36 self.first = false;
37 self.commits.begin();
38 self.commits.finish(self.reads.clone());
39 return Ok(true);
40 }
41 Ok(false)
42 }
43
44 /// Resolves once a relevant commit happened since the previous
45 /// observation, or the handle failed or closed. The future owns a clone
46 /// of the subscription, so a worker can wait on it beside other futures;
47 /// `take_changed` then consumes the change.
48 pub fn changed(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
49 let mut commits = self.commits.clone();
50 let first = self.first;
51 async move {
52 loop {
53 let state = commits.state();
54 if first || state.changed || state.stopped() {
55 return;
56 }
57 commits.changed().await;
58 }
59 }
60 }
61
62 /// The initial state, then each relevant commit. `next` waits on the
63 /// commit subscription, with no timer or polling.
64 pub async fn next(&mut self) -> Result<(), E> {
65 loop {
66 let state = self.commits.state();
67 if let Some(stop) = state.stopped_by() {
68 return Err((self.failed)(stop));
69 }
70 if self.first || state.changed {
71 self.first = false;
72 self.commits.begin();
73 self.commits.finish(self.reads.clone());
74 return Ok(());
75 }
76 self.commits.changed().await;
77 }
78 }
79}