Skip to main content

sapphire_framework_server/
host.rs

1//! The one workspace a server serves (#215), opened once and kept open.
2//!
3//! The server is the only process that may open an app's cache. It serves one workspace at
4//! a time, so it holds at most one open [`LocalBackend`]; [`Current`](crate::Current)
5//! decides which, and switches it.
6
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex};
9
10use tokio::sync::Mutex as AsyncMutex;
11use tokio::sync::broadcast;
12
13use sapphire_backend::{BackendEvent, LocalBackend, WorkspaceBackend};
14use sapphire_workspace::{AppContext, Workspace, WorkspaceState};
15
16use crate::error::{Error, Result};
17
18/// Capacity of the server-wide event channel, matching a backend's own.
19const EVENT_CAPACITY: usize = 128;
20
21struct Open {
22    root: PathBuf,
23    /// `None` while the workspace could not be opened (its root is gone): it stays the
24    /// current one, so `workspace.current` can say so, and opening is retried on use.
25    backend: Option<Arc<LocalBackend>>,
26}
27
28/// The workspace this server has open.
29pub struct WorkspaceHost {
30    ctx: &'static AppContext,
31    open: Mutex<Option<Open>>,
32    /// One open at a time: redb takes an exclusive lock on its file, so two concurrent
33    /// [`WorkspaceState::open`]s of one workspace fail with `Database already open`. Held
34    /// across the blocking open so the loser waits instead of failing.
35    opening: AsyncMutex<()>,
36    /// Every event of whichever workspace is open, so a subscription outlives a switch.
37    events: broadcast::Sender<(PathBuf, BackendEvent)>,
38}
39
40impl std::fmt::Debug for WorkspaceHost {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("WorkspaceHost")
43            .field("app", &self.ctx.app_name)
44            .field("root", &self.root())
45            .finish()
46    }
47}
48
49impl WorkspaceHost {
50    /// A host with no workspace.
51    pub fn new(ctx: &'static AppContext) -> WorkspaceHost {
52        WorkspaceHost {
53            ctx,
54            open: Mutex::new(None),
55            opening: AsyncMutex::new(()),
56            events: broadcast::channel(EVENT_CAPACITY).0,
57        }
58    }
59
60    /// The current workspace's root, if there is one.
61    pub fn root(&self) -> Option<PathBuf> {
62        self.open
63            .lock()
64            .expect("host mutex")
65            .as_ref()
66            .map(|o| o.root.clone())
67    }
68
69    /// The current workspace's backend, opening it if it is not open yet.
70    pub async fn backend(&self) -> Result<Arc<LocalBackend>> {
71        Ok(self.current().await?.1)
72    }
73
74    /// The current workspace's root and backend, read together, so a switch between the
75    /// two reads cannot pair one workspace's root with another's backend.
76    pub async fn current(&self) -> Result<(PathBuf, Arc<LocalBackend>)> {
77        let root = self.root().ok_or(Error::NoWorkspace)?;
78        Ok((root.clone(), self.backend_at(&root).await?))
79    }
80
81    /// The backend of `root`, when it is the current workspace; opened if need be.
82    ///
83    /// For the sync runtime, which works on a root it was handed: a workspace switched
84    /// away from in the meantime is an error, never a second open.
85    pub(crate) async fn backend_at(&self, root: &Path) -> Result<Arc<LocalBackend>> {
86        if let Some(backend) = self.open_backend(root) {
87            return Ok(backend);
88        }
89        let _opening = self.opening.lock().await;
90        if let Some(backend) = self.open_backend(root) {
91            return Ok(backend);
92        }
93        if self.root().as_deref() != Some(root) {
94            return Err(Error::NoWorkspace);
95        }
96        let backend = self.open_state(root).await?;
97        let mut open = self.open.lock().expect("host mutex");
98        match open.as_mut() {
99            // Still current: keep it. A switch that landed during the open wins.
100            Some(o) if o.root == root => {
101                o.backend = Some(Arc::clone(&backend));
102                Ok(backend)
103            }
104            _ => Err(Error::NoWorkspace),
105        }
106    }
107
108    /// The backend of `root` if it is the current workspace and open now; never opens.
109    pub(crate) fn open_backend(&self, root: &Path) -> Option<Arc<LocalBackend>> {
110        let open = self.open.lock().expect("host mutex");
111        let o = open.as_ref()?;
112        (o.root == root).then(|| o.backend.clone()).flatten()
113    }
114
115    /// Make `root` (canonical) the current workspace, opening it first.
116    ///
117    /// A workspace that fails to open is an error and leaves the current one as it was.
118    /// With `allow_unreachable`, a root that is gone is selected anyway, unopened — the
119    /// restore at start, which must keep the user's choice visible.
120    pub(crate) async fn select(&self, root: &Path, allow_unreachable: bool) -> Result<()> {
121        let _opening = self.opening.lock().await;
122        if self.root().as_deref() == Some(root) && self.open_backend(root).is_some() {
123            return Ok(());
124        }
125        // The cheap refusal first, while the old workspace is still open: a directory that
126        // is not this app's workspace never closes anything.
127        if !allow_unreachable {
128            Workspace::from_root(self.ctx, root)?;
129        }
130        // Close the old one before opening: its index and the new one's may be the same
131        // files (the same root), and an open that overlapped would fail on redb's lock.
132        let previous = self.open.lock().expect("host mutex").take();
133        let previous_root = previous.as_ref().map(|o| o.root.clone());
134        drop(previous);
135        let backend = match self.open_state(root).await {
136            Ok(backend) => Some(backend),
137            Err(_) if allow_unreachable => None,
138            Err(err) => {
139                // The old one stays current, unopened; it reopens on its next use.
140                *self.open.lock().expect("host mutex") = previous_root.map(|root| Open {
141                    root,
142                    backend: None,
143                });
144                return Err(err);
145            }
146        };
147        *self.open.lock().expect("host mutex") = Some(Open {
148            root: root.to_owned(),
149            backend,
150        });
151        Ok(())
152    }
153
154    /// Close the workspace and forget it: the host has none afterwards.
155    pub fn close(&self) {
156        self.open.lock().expect("host mutex").take();
157    }
158
159    /// Every event of the current workspace, and of the next after a switch.
160    pub(crate) fn subscribe(&self) -> broadcast::Receiver<(PathBuf, BackendEvent)> {
161        self.events.subscribe()
162    }
163
164    /// Publish `event` of the workspace at `root` to every subscriber, as the open backend's
165    /// own events are. For what happens outside the backend — replication. Nobody listening
166    /// is not an error.
167    pub(crate) fn emit(&self, root: &Path, event: BackendEvent) {
168        let _ = self.events.send((root.to_owned(), event));
169    }
170
171    /// Open `root`'s state and forward its events to the host's channel.
172    async fn open_state(&self, root: &Path) -> Result<Arc<LocalBackend>> {
173        let ctx = self.ctx;
174        let for_task = root.to_owned();
175        let state = tokio::task::spawn_blocking(move || -> Result<WorkspaceState> {
176            let workspace = Workspace::from_root(ctx, &for_task)?;
177            Ok(WorkspaceState::open(workspace)?)
178        })
179        .await
180        .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))??;
181        let backend = Arc::new(LocalBackend::new(Arc::new(state)));
182
183        // Ends when the backend is dropped and its channel closes: a switch stops it.
184        let mut events = backend.subscribe();
185        let out = self.events.clone();
186        let root = root.to_owned();
187        tokio::spawn(async move {
188            loop {
189                match events.recv().await {
190                    Ok(event) => {
191                        let _ = out.send((root.clone(), event));
192                    }
193                    Err(broadcast::error::RecvError::Lagged(_)) => {}
194                    Err(broadcast::error::RecvError::Closed) => break,
195                }
196            }
197        });
198        Ok(backend)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use std::ffi::OsString;
205    use std::sync::MutexGuard;
206
207    use super::*;
208    use sapphire_workspace::{AppContext, AppKind};
209
210    use crate::test_support;
211
212    static CTX: AppContext = AppContext::new("sapphire-hosttest");
213
214    /// A scratch tree with the three context directories pointed into it, held under the
215    /// crate-wide env lock and restoring the previous values when dropped — including while
216    /// unwinding.
217    ///
218    /// The guard owns the tree so it is deleted while the lock is still held: [`CTX`] is
219    /// first-writer-wins, so every later test resolves into the first test's tree, and a
220    /// test that woke on the lock while that tree was still being deleted failed with
221    /// `NotFound` (seen on Windows, where the deletion is slow).
222    struct EnvGuard {
223        previous: [Option<OsString>; 3],
224        tmp: tempfile::TempDir,
225        _lock: MutexGuard<'static, ()>,
226    }
227
228    impl EnvGuard {
229        fn path(&self) -> &Path {
230            self.tmp.path()
231        }
232    }
233
234    const DIR_VARS: [&str; 3] = [
235        "SAPPHIRE_HOSTTEST_CACHE_DIR",
236        "SAPPHIRE_HOSTTEST_DATA_DIR",
237        "SAPPHIRE_HOSTTEST_CONFIG_DIR",
238    ];
239
240    impl Drop for EnvGuard {
241        fn drop(&mut self) {
242            // SAFETY: `self._lock` still serialises the environment; it is dropped only
243            // after this method returns.
244            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
245                match previous.take() {
246                    Some(value) => unsafe { std::env::set_var(name, value) },
247                    None => test_support::remove(name),
248                }
249            }
250        }
251    }
252
253    fn init_ctx() -> EnvGuard {
254        let lock = test_support::lock();
255        let tmp = tempfile::tempdir().unwrap();
256        let previous = DIR_VARS.map(std::env::var_os);
257        for (name, dir) in DIR_VARS
258            .iter()
259            .zip(["cache", "data", "config"].map(|c| tmp.path().join(c)))
260        {
261            test_support::set(name, &dir);
262        }
263        CTX.init(AppKind::Server);
264        EnvGuard {
265            previous,
266            tmp,
267            _lock: lock,
268        }
269    }
270
271    fn workspace(parent: &Path, name: &str) -> PathBuf {
272        let root = parent.join(name);
273        std::fs::create_dir_all(root.join(".sapphire-hosttest")).unwrap();
274        root.canonicalize().unwrap()
275    }
276
277    #[tokio::test]
278    async fn without_a_selection_there_is_no_backend() {
279        let _env = init_ctx();
280        let host = WorkspaceHost::new(&CTX);
281        assert!(matches!(host.backend().await, Err(Error::NoWorkspace)));
282    }
283
284    #[tokio::test]
285    async fn the_selected_workspace_is_opened_once() {
286        let env = init_ctx();
287        let tmp = env.path();
288        let root = workspace(tmp, "ws");
289        let host = WorkspaceHost::new(&CTX);
290        host.select(&root, false).await.unwrap();
291        let a = host.backend().await.unwrap();
292        let b = host.backend().await.unwrap();
293        assert!(Arc::ptr_eq(&a, &b));
294        assert_eq!(host.root(), Some(root));
295    }
296
297    #[tokio::test]
298    async fn switching_closes_the_old_workspace_and_reselecting_reopens_it() {
299        let env = init_ctx();
300        let tmp = env.path();
301        let a = workspace(tmp, "a");
302        let b = workspace(tmp, "b");
303        let host = WorkspaceHost::new(&CTX);
304        host.select(&a, false).await.unwrap();
305        host.backend().await.unwrap();
306        host.select(&b, false).await.unwrap();
307        assert!(host.open_backend(&a).is_none());
308        assert!(matches!(host.backend_at(&a).await, Err(Error::NoWorkspace)));
309        // If the switch had left a's database open, this open would fail.
310        host.select(&a, false).await.unwrap();
311        host.backend().await.unwrap();
312    }
313
314    #[tokio::test]
315    async fn a_directory_without_a_marker_is_refused_and_the_old_one_kept() {
316        let env = init_ctx();
317        let tmp = env.path();
318        let a = workspace(tmp, "a");
319        let plain = tmp.join("plain");
320        std::fs::create_dir_all(&plain).unwrap();
321        let host = WorkspaceHost::new(&CTX);
322        host.select(&a, false).await.unwrap();
323        assert!(host.select(&plain, false).await.is_err());
324        assert_eq!(host.root(), Some(a.clone()));
325        assert!(host.open_backend(&a).is_some(), "never closed");
326    }
327
328    /// Eight callers at once get one backend, not eight opens: an open that overlapped
329    /// another of the same workspace would fail with `Database already open`.
330    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
331    async fn concurrent_first_uses_are_serialised() {
332        let env = init_ctx();
333        let tmp = env.path();
334        let root = workspace(tmp, "ws");
335        let host = Arc::new(WorkspaceHost::new(&CTX));
336        host.select(&root, true).await.unwrap();
337        host.close();
338        host.select(&root, false).await.unwrap();
339        let mut tasks = Vec::new();
340        for _ in 0..8 {
341            let host = Arc::clone(&host);
342            tasks.push(tokio::spawn(async move { host.backend().await }));
343        }
344        let mut backends = Vec::new();
345        for task in tasks {
346            backends.push(task.await.unwrap().unwrap());
347        }
348        assert!(backends.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])));
349    }
350}