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    /// Point the three context directories at `tmp` while holding the crate-wide env
208    /// lock, restoring the previous values when dropped — including while unwinding.
209    struct EnvGuard {
210        previous: [Option<OsString>; 3],
211        _lock: MutexGuard<'static, ()>,
212    }
213
214    const DIR_VARS: [&str; 3] = [
215        "SAPPHIRE_HOSTTEST_CACHE_DIR",
216        "SAPPHIRE_HOSTTEST_DATA_DIR",
217        "SAPPHIRE_HOSTTEST_CONFIG_DIR",
218    ];
219
220    impl Drop for EnvGuard {
221        fn drop(&mut self) {
222            // SAFETY: `self._lock` still serialises the environment; it is dropped only
223            // after this method returns.
224            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
225                match previous.take() {
226                    Some(value) => unsafe { std::env::set_var(name, value) },
227                    None => test_support::remove(name),
228                }
229            }
230        }
231    }
232
233    fn init_ctx(tmp: &Path) -> EnvGuard {
234        let lock = test_support::lock();
235        let previous = DIR_VARS.map(std::env::var_os);
236        for (name, dir) in DIR_VARS
237            .iter()
238            .zip(["cache", "data", "config"].map(|c| tmp.join(c)))
239        {
240            test_support::set(name, &dir);
241        }
242        CTX.init(AppKind::Server);
243        EnvGuard {
244            previous,
245            _lock: lock,
246        }
247    }
248
249    fn workspace(parent: &Path, name: &str) -> PathBuf {
250        let root = parent.join(name);
251        std::fs::create_dir_all(root.join(".sapphire-hosttest")).unwrap();
252        root.canonicalize().unwrap()
253    }
254
255    #[tokio::test]
256    async fn without_a_selection_there_is_no_backend() {
257        let tmp = tempfile::tempdir().unwrap();
258        let _env = init_ctx(tmp.path());
259        let host = WorkspaceHost::new(&CTX);
260        assert!(matches!(host.backend().await, Err(Error::NoWorkspace)));
261    }
262
263    #[tokio::test]
264    async fn the_selected_workspace_is_opened_once() {
265        let tmp = tempfile::tempdir().unwrap();
266        let _env = init_ctx(tmp.path());
267        let root = workspace(tmp.path(), "ws");
268        let host = WorkspaceHost::new(&CTX);
269        host.select(&root, false).await.unwrap();
270        let a = host.backend().await.unwrap();
271        let b = host.backend().await.unwrap();
272        assert!(Arc::ptr_eq(&a, &b));
273        assert_eq!(host.root(), Some(root));
274    }
275
276    #[tokio::test]
277    async fn switching_closes_the_old_workspace_and_reselecting_reopens_it() {
278        let tmp = tempfile::tempdir().unwrap();
279        let _env = init_ctx(tmp.path());
280        let a = workspace(tmp.path(), "a");
281        let b = workspace(tmp.path(), "b");
282        let host = WorkspaceHost::new(&CTX);
283        host.select(&a, false).await.unwrap();
284        host.backend().await.unwrap();
285        host.select(&b, false).await.unwrap();
286        assert!(host.open_backend(&a).is_none());
287        assert!(matches!(host.backend_at(&a).await, Err(Error::NoWorkspace)));
288        // If the switch had left a's database open, this open would fail.
289        host.select(&a, false).await.unwrap();
290        host.backend().await.unwrap();
291    }
292
293    #[tokio::test]
294    async fn a_directory_without_a_marker_is_refused_and_the_old_one_kept() {
295        let tmp = tempfile::tempdir().unwrap();
296        let _env = init_ctx(tmp.path());
297        let a = workspace(tmp.path(), "a");
298        let plain = tmp.path().join("plain");
299        std::fs::create_dir_all(&plain).unwrap();
300        let host = WorkspaceHost::new(&CTX);
301        host.select(&a, false).await.unwrap();
302        assert!(host.select(&plain, false).await.is_err());
303        assert_eq!(host.root(), Some(a.clone()));
304        assert!(host.open_backend(&a).is_some(), "never closed");
305    }
306
307    /// Eight callers at once get one backend, not eight opens: an open that overlapped
308    /// another of the same workspace would fail with `Database already open`.
309    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
310    async fn concurrent_first_uses_are_serialised() {
311        let tmp = tempfile::tempdir().unwrap();
312        let _env = init_ctx(tmp.path());
313        let root = workspace(tmp.path(), "ws");
314        let host = Arc::new(WorkspaceHost::new(&CTX));
315        host.select(&root, true).await.unwrap();
316        host.close();
317        host.select(&root, false).await.unwrap();
318        let mut tasks = Vec::new();
319        for _ in 0..8 {
320            let host = Arc::clone(&host);
321            tasks.push(tokio::spawn(async move { host.backend().await }));
322        }
323        let mut backends = Vec::new();
324        for task in tasks {
325            backends.push(task.await.unwrap().unwrap());
326        }
327        assert!(backends.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])));
328    }
329}