coven_sync/
sequence_state.rs1use 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#[derive(Clone, Debug)]
13pub enum SequenceStatus {
14 Opening,
16 Synced {
18 through: u64,
20 },
21 Blocked(Box<PendingRecord>),
23 Stopped(SyncFailure),
25}
26
27pub(crate) struct SequenceStatusWatch(watch::Receiver<SequenceStatus>);
29
30impl SequenceStatusWatch {
31 pub(crate) async fn changed(&mut self) -> Result<(), watch::error::RecvError> {
33 self.0.changed().await
34 }
35}
36
37pub(crate) struct PassMoves(watch::Receiver<Option<PassMove>>);
41
42impl PassMoves {
43 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#[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
69pub struct SequenceState {
71 status: watch::Sender<SequenceStatus>,
72 moving: watch::Sender<Option<PassMove>>,
75 registered: Mutex<bool>,
76 wake: tokio::sync::Notify,
78 often: crate::sync_often::SyncOften,
80 checks: Mutex<BTreeSet<ObjectPath>>,
83}
84
85impl SequenceState {
86 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 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 pub(crate) fn status(&self) -> SequenceStatus {
105 self.status.borrow().clone()
106 }
107 pub(crate) fn watch(&self) -> SequenceStatusWatch {
110 SequenceStatusWatch(self.status.subscribe())
111 }
112 #[cfg(test)]
114 pub(crate) fn subscribe(&self) -> watch::Receiver<SequenceStatus> {
115 self.status.subscribe()
116 }
117 pub(crate) fn pass_begins(&self) -> PassMoves {
119 self.moving.send_replace(None);
120 PassMoves(self.moving.subscribe())
121 }
122 pub(crate) fn moved(&self, moved: PassMove) {
124 self.moving.send_if_modified(|moving| moving.replace(moved) != Some(moved));
125 }
126 pub(crate) fn request_pass(&self) {
128 self.wake.notify_one();
129 }
130 pub(crate) async fn pass_requested(&self) {
132 self.wake.notified().await;
133 }
134 pub fn sync_often(&self, interval: std::time::Duration) -> crate::SyncOftenGuard {
138 self.often.hold(interval)
139 }
140 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 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;