Skip to main content

coven_sync/
sequence_state.rs

1//! The installation's actual progress, shared with transfer workers.
2
3use crate::{DeviceIdEvidence, PendingRecord, SyncError, SyncFailure};
4use coven_database::PassMove;
5use coven_foundation::locks::lock_unpoisoned;
6use coven_storage::{ObjectPath, PublicationGate, StorageError, StorageFailure};
7use std::collections::BTreeSet;
8use std::sync::Mutex;
9use tokio::sync::watch;
10
11/// Current sync activity. Reaching the read end says nothing about pending files.
12#[derive(Clone, Debug)]
13pub enum SequenceStatus {
14    /// No pass has established this session's applied end.
15    Opening,
16    /// The pass reached the read end at this slot.
17    Synced {
18        /// Last applied slot.
19        through: u64,
20    },
21    /// A required slot prevents all later reading, reloading and sending.
22    Blocked(Box<PendingRecord>),
23    /// This installation cannot resume from its current identity.
24    Stopped(SyncFailure),
25}
26
27/// Hears each change of this installation's sync activity (`SequenceState::watch`).
28pub(crate) struct SequenceStatusWatch(watch::Receiver<SequenceStatus>);
29
30impl SequenceStatusWatch {
31    /// Resolves at the next change; an error once the sequence state is gone.
32    pub(crate) async fn changed(&mut self) -> Result<(), watch::error::RecvError> {
33        self.0.changed().await
34    }
35}
36
37/// Hears what the running pass moves: each time the last thing it moved
38/// changes between a slot it read that it hadn't and one it claimed
39/// (`SequenceState::pass_begins`).
40pub(crate) struct PassMoves(watch::Receiver<Option<PassMove>>);
41
42impl PassMoves {
43    /// Resolves with what the pass moved, at each move the loop hasn't heard.
44    /// The loop waiting holds the sequence state the pass moves.
45    pub(crate) async fn moved(&mut self) -> PassMove {
46        loop {
47            self.0.changed().await.expect("the sequence state outlives its pass");
48            if let Some(moved) = *self.0.borrow_and_update() {
49                return moved;
50            }
51        }
52    }
53}
54
55/// A provider check's object while permitted (`SequenceState::permit_provider_check`):
56/// removes it when dropped, a dropped future included.
57#[must_use = "dropping the permit ends it at once"]
58pub struct ProviderCheckPermit<'a> {
59    checks: &'a Mutex<BTreeSet<ObjectPath>>,
60    path: &'a ObjectPath,
61}
62
63impl Drop for ProviderCheckPermit<'_> {
64    fn drop(&mut self) {
65        lock_unpoisoned(self.checks).remove(self.path);
66    }
67}
68
69/// Shared state of this open installation. It carries no time-based permission.
70pub struct SequenceState {
71    status: watch::Sender<SequenceStatus>,
72    /// What the running pass moved last, a slot it read that it hadn't or one
73    /// it claimed: what the sync state shows as syncing (§19.1).
74    moving: watch::Sender<Option<PassMove>>,
75    registered: Mutex<bool>,
76    /// App work outside the database that the next pass serves.
77    wake: tokio::sync::Notify,
78    /// The intervals apps hold for idle passes, across connections.
79    often: crate::sync_often::SyncOften,
80    /// Fresh objects a storage setup's provider check writes while it runs,
81    /// which a connection may publish whatever the sync state (§20.8, E5).
82    checks: Mutex<BTreeSet<ObjectPath>>,
83}
84
85impl SequenceState {
86    /// Start before a read pass has established the local binding.
87    pub fn new() -> Self {
88        Self {
89            status: watch::channel(SequenceStatus::Opening).0,
90            moving: watch::channel(None).0,
91            registered: Mutex::new(false),
92            wake: tokio::sync::Notify::new(),
93            often: crate::sync_often::SyncOften::new(),
94            checks: Mutex::new(BTreeSet::new()),
95        }
96    }
97    /// Permit the provider check's own object until the permit drops, however
98    /// the check ends.
99    pub fn permit_provider_check<'a>(&'a self, path: &'a ObjectPath) -> ProviderCheckPermit<'a> {
100        lock_unpoisoned(&self.checks).insert(path.clone());
101        ProviderCheckPermit { checks: &self.checks, path }
102    }
103    /// The sync activity now: progress, or what blocks or stopped it.
104    pub(crate) fn status(&self) -> SequenceStatus {
105        self.status.borrow().clone()
106    }
107    /// Hear each change of the sync activity, for work that waits until sync
108    /// allows it.
109    pub(crate) fn watch(&self) -> SequenceStatusWatch {
110        SequenceStatusWatch(self.status.subscribe())
111    }
112    /// Observe progress and blocked causes, for a test to wait on.
113    #[cfg(test)]
114    pub(crate) fn subscribe(&self) -> watch::Receiver<SequenceStatus> {
115        self.status.subscribe()
116    }
117    /// A pass begins, having moved nothing yet: hear its moves.
118    pub(crate) fn pass_begins(&self) -> PassMoves {
119        self.moving.send_replace(None);
120        PassMoves(self.moving.subscribe())
121    }
122    /// The running pass read a slot it hadn't, or claimed one.
123    pub(crate) fn moved(&self, moved: PassMove) {
124        self.moving.send_if_modified(|moving| moving.replace(moved) != Some(moved));
125    }
126    /// Ask the running loop for a pass, retained until it waits.
127    pub(crate) fn request_pass(&self) {
128        self.wake.notify_one();
129    }
130    /// A pass was requested for app work outside the database.
131    pub(crate) async fn pass_requested(&self) {
132        self.wake.notified().await;
133    }
134    /// Run idle passes at most `interval` apart, instead of every 30
135    /// seconds, until the guard drops. With several held, the shortest wins.
136    /// Connection backoff and provider cooldowns still hold every pass.
137    pub fn sync_often(&self, interval: std::time::Duration) -> crate::SyncOftenGuard {
138        self.often.hold(interval)
139    }
140    /// The wait between idle passes, and its changes.
141    pub(crate) fn idle_interval(&self) -> crate::HeldIntervals {
142        self.often.subscribe()
143    }
144    pub(crate) fn set(&self, status: SequenceStatus) {
145        self.status.send_replace(status);
146    }
147    pub(crate) fn registered(&self, registered: bool) {
148        *lock_unpoisoned(&self.registered) = registered;
149    }
150    pub(crate) fn files_allowed(&self) -> bool {
151        matches!(&*self.status.borrow(), SequenceStatus::Synced { .. })
152            && *lock_unpoisoned(&self.registered)
153    }
154    pub(crate) fn check(&self) -> Result<(), SyncError> {
155        match &*self.status.borrow() {
156            SequenceStatus::Synced { .. } => Ok(()),
157            SequenceStatus::Blocked(record) => Err(SyncError::Pending(record.clone())),
158            SequenceStatus::Stopped(SyncFailure::DeviceIdInUse(evidence)) => {
159                Err(SyncError::DeviceIdInUse(*evidence))
160            }
161            SequenceStatus::Stopped(SyncFailure::Removed(removal)) => {
162                Err(SyncError::Removed(*removal))
163            }
164            SequenceStatus::Stopped(failure) => Err(SyncError::Failed {
165                failure: crate::LocalFailure::Operation,
166                source: std::sync::Arc::new(failure.clone()),
167            }),
168            SequenceStatus::Opening => Err(StorageFailure::CatchUpRequired.into()),
169        }
170    }
171    pub(crate) fn stop_copy(&self, evidence: DeviceIdEvidence) -> SyncError {
172        self.set(SequenceStatus::Stopped(SyncFailure::DeviceIdInUse(evidence)));
173        SyncError::DeviceIdInUse(evidence)
174    }
175}
176impl PublicationGate for SequenceState {
177    fn check(&self, path: &ObjectPath) -> Result<(), StorageError> {
178        if lock_unpoisoned(&self.checks).contains(path) {
179            return Ok(());
180        }
181        // A join request is the bootstrap step before any sequence state
182        // exists; the stuck-device rule governs only sequence-derived sends.
183        if path.join_request_invite().is_some() {
184            return Ok(());
185        }
186        if self.check().is_err()
187            || (path.object_id().is_some() && !*lock_unpoisoned(&self.registered))
188        {
189            Err(StorageFailure::CatchUpRequired.into())
190        } else {
191            Ok(())
192        }
193    }
194}
195
196#[cfg(test)]
197#[path = "sequence_state_tests.rs"]
198mod tests;