sapphire_framework_server/
host.rs1use 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
18const EVENT_CAPACITY: usize = 128;
20
21struct Open {
22 root: PathBuf,
23 backend: Option<Arc<LocalBackend>>,
26}
27
28pub struct WorkspaceHost {
30 ctx: &'static AppContext,
31 open: Mutex<Option<Open>>,
32 opening: AsyncMutex<()>,
36 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 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 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 pub async fn backend(&self) -> Result<Arc<LocalBackend>> {
71 Ok(self.current().await?.1)
72 }
73
74 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 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 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 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 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 if !allow_unreachable {
128 Workspace::from_root(self.ctx, root)?;
129 }
130 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 *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 pub fn close(&self) {
156 self.open.lock().expect("host mutex").take();
157 }
158
159 pub(crate) fn subscribe(&self) -> broadcast::Receiver<(PathBuf, BackendEvent)> {
161 self.events.subscribe()
162 }
163
164 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 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 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 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 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 #[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}