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 pub(crate) fn emit(&self, root: &Path, event: BackendEvent) {
168 let _ = self.events.send((root.to_owned(), event));
169 }
170
171 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 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 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 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 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 #[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}