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    /// Open `root`'s state and forward its events to the host's channel.
165    async fn open_state(&self, root: &Path) -> Result<Arc<LocalBackend>> {
166        let ctx = self.ctx;
167        let for_task = root.to_owned();
168        let state = tokio::task::spawn_blocking(move || -> Result<WorkspaceState> {
169            let workspace = Workspace::from_root(ctx, &for_task)?;
170            Ok(WorkspaceState::open(workspace)?)
171        })
172        .await
173        .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))??;
174        let backend = Arc::new(LocalBackend::new(Arc::new(state)));
175
176        // Ends when the backend is dropped and its channel closes: a switch stops it.
177        let mut events = backend.subscribe();
178        let out = self.events.clone();
179        let root = root.to_owned();
180        tokio::spawn(async move {
181            loop {
182                match events.recv().await {
183                    Ok(event) => {
184                        let _ = out.send((root.clone(), event));
185                    }
186                    Err(broadcast::error::RecvError::Lagged(_)) => {}
187                    Err(broadcast::error::RecvError::Closed) => break,
188                }
189            }
190        });
191        Ok(backend)
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use std::ffi::OsString;
198    use std::sync::MutexGuard;
199
200    use super::*;
201    use sapphire_workspace::{AppContext, AppKind};
202
203    use crate::test_support;
204
205    static CTX: AppContext = AppContext::new("sapphire-hosttest");
206
207    /// A scratch tree with the three context directories pointed into it, held under the
208    /// crate-wide env lock and restoring the previous values when dropped — including while
209    /// unwinding.
210    ///
211    /// The guard owns the tree so it is deleted while the lock is still held: [`CTX`] is
212    /// first-writer-wins, so every later test resolves into the first test's tree, and a
213    /// test that woke on the lock while that tree was still being deleted failed with
214    /// `NotFound` (seen on Windows, where the deletion is slow).
215    struct EnvGuard {
216        previous: [Option<OsString>; 3],
217        tmp: tempfile::TempDir,
218        _lock: MutexGuard<'static, ()>,
219    }
220
221    impl EnvGuard {
222        fn path(&self) -> &Path {
223            self.tmp.path()
224        }
225    }
226
227    const DIR_VARS: [&str; 3] = [
228        "SAPPHIRE_HOSTTEST_CACHE_DIR",
229        "SAPPHIRE_HOSTTEST_DATA_DIR",
230        "SAPPHIRE_HOSTTEST_CONFIG_DIR",
231    ];
232
233    impl Drop for EnvGuard {
234        fn drop(&mut self) {
235            // SAFETY: `self._lock` still serialises the environment; it is dropped only
236            // after this method returns.
237            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
238                match previous.take() {
239                    Some(value) => unsafe { std::env::set_var(name, value) },
240                    None => test_support::remove(name),
241                }
242            }
243        }
244    }
245
246    fn init_ctx() -> EnvGuard {
247        let lock = test_support::lock();
248        let tmp = tempfile::tempdir().unwrap();
249        let previous = DIR_VARS.map(std::env::var_os);
250        for (name, dir) in DIR_VARS
251            .iter()
252            .zip(["cache", "data", "config"].map(|c| tmp.path().join(c)))
253        {
254            test_support::set(name, &dir);
255        }
256        CTX.init(AppKind::Server);
257        EnvGuard {
258            previous,
259            tmp,
260            _lock: lock,
261        }
262    }
263
264    fn workspace(parent: &Path, name: &str) -> PathBuf {
265        let root = parent.join(name);
266        std::fs::create_dir_all(root.join(".sapphire-hosttest")).unwrap();
267        root.canonicalize().unwrap()
268    }
269
270    #[tokio::test]
271    async fn without_a_selection_there_is_no_backend() {
272        let _env = init_ctx();
273        let host = WorkspaceHost::new(&CTX);
274        assert!(matches!(host.backend().await, Err(Error::NoWorkspace)));
275    }
276
277    #[tokio::test]
278    async fn the_selected_workspace_is_opened_once() {
279        let env = init_ctx();
280        let tmp = env.path();
281        let root = workspace(tmp, "ws");
282        let host = WorkspaceHost::new(&CTX);
283        host.select(&root, false).await.unwrap();
284        let a = host.backend().await.unwrap();
285        let b = host.backend().await.unwrap();
286        assert!(Arc::ptr_eq(&a, &b));
287        assert_eq!(host.root(), Some(root));
288    }
289
290    #[tokio::test]
291    async fn switching_closes_the_old_workspace_and_reselecting_reopens_it() {
292        let env = init_ctx();
293        let tmp = env.path();
294        let a = workspace(tmp, "a");
295        let b = workspace(tmp, "b");
296        let host = WorkspaceHost::new(&CTX);
297        host.select(&a, false).await.unwrap();
298        host.backend().await.unwrap();
299        host.select(&b, false).await.unwrap();
300        assert!(host.open_backend(&a).is_none());
301        assert!(matches!(host.backend_at(&a).await, Err(Error::NoWorkspace)));
302        // If the switch had left a's database open, this open would fail.
303        host.select(&a, false).await.unwrap();
304        host.backend().await.unwrap();
305    }
306
307    #[tokio::test]
308    async fn a_directory_without_a_marker_is_refused_and_the_old_one_kept() {
309        let env = init_ctx();
310        let tmp = env.path();
311        let a = workspace(tmp, "a");
312        let plain = tmp.join("plain");
313        std::fs::create_dir_all(&plain).unwrap();
314        let host = WorkspaceHost::new(&CTX);
315        host.select(&a, false).await.unwrap();
316        assert!(host.select(&plain, false).await.is_err());
317        assert_eq!(host.root(), Some(a.clone()));
318        assert!(host.open_backend(&a).is_some(), "never closed");
319    }
320
321    /// Eight callers at once get one backend, not eight opens: an open that overlapped
322    /// another of the same workspace would fail with `Database already open`.
323    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
324    async fn concurrent_first_uses_are_serialised() {
325        let env = init_ctx();
326        let tmp = env.path();
327        let root = workspace(tmp, "ws");
328        let host = Arc::new(WorkspaceHost::new(&CTX));
329        host.select(&root, true).await.unwrap();
330        host.close();
331        host.select(&root, false).await.unwrap();
332        let mut tasks = Vec::new();
333        for _ in 0..8 {
334            let host = Arc::clone(&host);
335            tasks.push(tokio::spawn(async move { host.backend().await }));
336        }
337        let mut backends = Vec::new();
338        for task in tasks {
339            backends.push(task.await.unwrap().unwrap());
340        }
341        assert!(backends.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])));
342    }
343}