Skip to main content

coven_sync/
file_storage.rs

1//! Whether the file layer has storage, and if not why (§17.7): the four
2//! states every reader follows one rule for.
3
4use crate::{
5    files::{Files, FilesInner, FilesMode},
6    FileReadError,
7};
8use coven_database::DbError;
9use coven_storage::Storage;
10use std::sync::Arc;
11use tokio::sync::watch;
12
13/// What the file layer's storage is. A reader goes ahead when it is
14/// connected, waits while a connection is coming, and fails at once when
15/// none is or the store has closed.
16#[derive(Clone)]
17pub(crate) enum StorageState {
18    /// Storage is connected.
19    Connected(Arc<dyn Storage>),
20    /// A connection attempt is running or backing off, so storage will be
21    /// connected, or the attempt ends and says otherwise.
22    Connecting,
23    /// Sync is stopped or no storage is set up: nothing connects until the
24    /// app starts sync or sets storage up.
25    Released,
26    /// The store has closed.
27    Closed,
28}
29
30/// The facts the four states follow from. Each is written by one owner:
31/// the connection's through `Files::set_storage`, the attempt's through
32/// `ConnectionComing`, and `Files::close`.
33pub(super) struct StorageSlot {
34    storage: Option<Arc<dyn Storage>>,
35    /// A connection attempt is running or backing off.
36    attempting: bool,
37    closed: bool,
38    /// Which connection `storage` is, counting every change of it.
39    connection: u64,
40}
41
42impl StorageSlot {
43    /// The slot of a store as it opens, with the storage its owner loaded, if
44    /// any.
45    pub(super) fn opened(storage: Option<Arc<dyn Storage>>) -> Self {
46        Self { storage, attempting: false, closed: false, connection: 0 }
47    }
48
49    pub(super) fn state(&self) -> StorageState {
50        if self.closed {
51            StorageState::Closed
52        } else if let Some(storage) = &self.storage {
53            StorageState::Connected(storage.clone())
54        } else if self.attempting {
55            StorageState::Connecting
56        } else {
57            StorageState::Released
58        }
59    }
60
61    pub(super) fn connection(&self) -> u64 {
62        self.connection
63    }
64
65    /// Replace the storage, as a new connection or its release.
66    pub(super) fn connect(&mut self, storage: Option<Arc<dyn Storage>>) {
67        self.storage = storage;
68        self.connection += 1;
69    }
70
71    pub(super) fn close(&mut self) {
72        self.storage = None;
73        self.closed = true;
74    }
75
76    /// The store is closing: reads fail as closed, though the storage stays
77    /// until the close releases it.
78    pub(super) fn closing(&mut self) {
79        self.closed = true;
80    }
81}
82
83impl<M: FilesMode> FilesInner<M> {
84    /// The storage's state now.
85    pub(crate) fn storage_state(&self) -> StorageState {
86        self.storage.borrow().state()
87    }
88
89    /// The first state that is not connecting, waiting while a connection
90    /// is coming. A call that stops waiting leaves nothing behind. Callers
91    /// hold none of the locks a connection change takes
92    /// (`Files::set_storage`'s), which the change that ends the wait needs.
93    pub(crate) async fn settled(&self) -> Result<StorageState, FileReadError> {
94        let mut changes = self.storage.subscribe();
95        loop {
96            // Registered before the state is read: a close between them
97            // still wakes this wait.
98            let closing = self.hold_wake.notified();
99            tokio::pin!(closing);
100            closing.as_mut().enable();
101            self.check_open()?;
102            let state = changes.borrow_and_update().state();
103            if !matches!(state, StorageState::Connecting) {
104                return Ok(state);
105            }
106            #[cfg(any(test, feature = "test-utils"))]
107            let _waiting = crate::files::Waiting::new(&self.reads_awaiting_connection);
108            tokio::select! {
109                () = closing => {}
110                changed = changes.changed() => {
111                    if changed.is_err() {
112                        return Err(DbError::StoreClosed.into());
113                    }
114                }
115            }
116        }
117    }
118}
119
120/// The storage `state` holds, or why a read or request has none: no storage
121/// is connected and none is coming, or the store has closed.
122pub(super) fn connected(state: StorageState) -> Result<Arc<dyn Storage>, FileReadError> {
123    match state {
124        StorageState::Connected(storage) => Ok(storage),
125        StorageState::Connecting | StorageState::Released => Err(FileReadError::NoStorage),
126        StorageState::Closed => Err(DbError::StoreClosed.into()),
127    }
128}
129
130impl<M: FilesMode> Files<M> {
131    /// Follow how many reads wait for a coming connection now, for a test
132    /// that goes on once a read waits.
133    #[cfg(any(test, feature = "test-utils"))]
134    pub fn reads_awaiting_connection(&self) -> watch::Receiver<usize> {
135        self.inner.reads_awaiting_connection.subscribe()
136    }
137}
138
139impl Files {
140    /// Note that a connection attempt is running: until the returned guard
141    /// drops, reads that need storage wait for it rather than fail. The
142    /// guard drops when the attempt ends, connected or not, and a store
143    /// with no storage then reads as released.
144    pub fn expect_connection(&self) -> ConnectionComing {
145        self.inner.storage.send_modify(|slot| slot.attempting = true);
146        ConnectionComing { storage: self.inner.storage.clone() }
147    }
148}
149
150impl Files {
151    /// Note that the store is closing, before its connection is released: a
152    /// read waiting for that connection, or asked after this, fails as the
153    /// store closing, not as having no storage.
154    pub fn closing(&self) {
155        self.inner.storage.send_modify(|slot| slot.closing());
156    }
157}
158
159/// A connection attempt's mark on the file layer's storage: while it lives,
160/// a connection is coming (§17.7).
161#[must_use = "the connection is expected only while this lives"]
162pub struct ConnectionComing {
163    storage: watch::Sender<StorageSlot>,
164}
165
166impl Drop for ConnectionComing {
167    fn drop(&mut self) {
168        self.storage.send_if_modified(|slot| std::mem::take(&mut slot.attempting));
169    }
170}