sapphire_framework_server/
current.rs1use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use grain_id::GrainId;
12use sapphire_backend::WorkspaceBackend;
13use sapphire_backend::protocol as proto;
14use sapphire_ipc::{Router, RpcError};
15use sapphire_workspace::{AppContext, Workspace};
16use tokio::sync::Mutex as AsyncMutex;
17
18use crate::error::{Error, Result};
19use crate::handlers::rpc_error;
20use crate::host::WorkspaceHost;
21use crate::selection::{Selection, SelectionFile, slug};
22use crate::sync::{SYNC_ID_FILE, SyncRuntime};
23
24const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
26
27pub struct Current {
29 ctx: &'static AppContext,
30 host: Arc<WorkspaceHost>,
31 sync: Option<Arc<SyncRuntime>>,
32 file: SelectionFile,
33 switching: AsyncMutex<()>,
35}
36
37impl std::fmt::Debug for Current {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_struct("Current")
40 .field("root", &self.host.root())
41 .finish()
42 }
43}
44
45impl Current {
46 pub fn new(
49 ctx: &'static AppContext,
50 host: Arc<WorkspaceHost>,
51 sync: Option<Arc<SyncRuntime>>,
52 file: SelectionFile,
53 ) -> Current {
54 Current {
55 ctx,
56 host,
57 sync,
58 file,
59 switching: AsyncMutex::new(()),
60 }
61 }
62
63 pub fn host(&self) -> &Arc<WorkspaceHost> {
65 &self.host
66 }
67
68 pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
70 self.sync.as_ref()
71 }
72
73 pub fn root(&self) -> Option<PathBuf> {
75 self.host.root()
76 }
77
78 pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
80 let root = resolve(dir)?;
81 let sync = has_sync_id(self.ctx, &root);
82 self.switch(&root, sync, false).await?;
83 self.describe().await.ok_or(Error::NoWorkspace)
84 }
85
86 pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
89 let result = init_workspace(self.ctx, dir)?;
90 let sync = has_sync_id(self.ctx, &result.root);
91 self.switch(&result.root, sync, false).await?;
92 Ok(result)
93 }
94
95 pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
102 let runtime = self.runtime()?;
103 let first = !has_sync_id(self.ctx, &resolve(dir)?);
104 let root = runtime.place(selector, dir).await?;
105 if first {
106 let config = Workspace::from_root(self.ctx, &root)?.config_path();
107 if let Err(err) = drop_bare_registry(&config) {
108 tracing::warn!(config = %config.display(), "could not clear the registry-only config: {err}");
109 }
110 }
111 self.switch(&root, false, false).await?;
112 self.enable_sync().await
113 }
114
115 pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
122 {
123 let _one = self.switching.lock().await;
124 let from = self.root().ok_or(Error::NoWorkspace)?;
125 let to = destination(dir)?;
126 if to.starts_with(&from) {
127 return Err(Error::Config(format!(
128 "cannot move {} into itself",
129 from.display()
130 )));
131 }
132 let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
134 let synced = self.let_go(&from).await?;
135 self.host.close();
136 if let Err(err) = std::fs::rename(&from, &to) {
137 self.reopen(&from, synced).await;
139 return Err(match err.kind() {
140 std::io::ErrorKind::CrossesDevices => Error::Config(format!(
141 "cannot move {} to another drive ({}); move it there yourself, then open it",
142 from.display(),
143 to.display()
144 )),
145 _ => Error::Io(std::io::Error::new(
146 err.kind(),
147 format!(
148 "could not move {} to {}: {err}",
149 from.display(),
150 to.display()
151 ),
152 )),
153 });
154 }
155
156 let workspace = Workspace::from_root(self.ctx, &to)?;
157 carry_cache(&from_cache, &workspace.cache_dir(), &to);
158 self.reopen(&to, synced).await;
159 }
160 if let Ok(backend) = self.host.backend().await {
163 tokio::spawn(async move {
164 if let Err(err) = backend.sync().await {
165 tracing::warn!("re-indexing the moved workspace: {err}");
166 }
167 });
168 }
169 self.describe().await.ok_or(Error::NoWorkspace)
170 }
171
172 pub async fn remove(&self, delete: bool) -> Result<()> {
175 let _one = self.switching.lock().await;
176 let root = self.root().ok_or(Error::NoWorkspace)?;
177 let cache = Workspace::from_root(self.ctx, &root)
179 .ok()
180 .map(|w| w.cache_dir());
181 if delete {
184 self.let_go(&root).await?;
185 } else if let Some(runtime) = &self.sync
186 && let Err(err) = runtime.disable(&root).await
187 {
188 tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
189 }
190 self.host.close();
191 self.file.clear()?;
192 if delete {
193 match std::fs::remove_dir_all(&root) {
194 Ok(()) => {}
195 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
196 Err(e) => {
197 return Err(Error::Io(std::io::Error::new(
198 e.kind(),
199 format!("could not delete {}: {e}", root.display()),
200 )));
201 }
202 }
203 if let Some(cache) = cache
204 && let Err(err) = std::fs::remove_dir_all(&cache)
205 && err.kind() != std::io::ErrorKind::NotFound
206 {
207 tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
208 }
209 }
210 Ok(())
211 }
212
213 async fn let_go(&self, root: &Path) -> Result<bool> {
217 let Some(runtime) = &self.sync else {
218 return Ok(false);
219 };
220 if !runtime.roots().await.iter().any(|r| r == root) {
221 return Ok(false);
222 }
223 if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
224 if let Err(again) = runtime.enable(root).await {
225 tracing::warn!(root = %root.display(), "could not restart sync: {again}");
226 }
227 return Err(err);
228 }
229 Ok(true)
230 }
231
232 async fn reopen(&self, root: &Path, sync: bool) {
235 if let Err(err) = self.host.select(root, true).await {
236 tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
237 }
238 if sync
239 && let Some(runtime) = &self.sync
240 && let Err(err) = runtime.enable(root).await
241 {
242 tracing::warn!(root = %root.display(), "could not restart sync: {err}");
243 }
244 self.remember(root, sync);
245 }
246
247 pub async fn enable_sync(&self) -> Result<GrainId> {
249 let runtime = self.runtime()?;
250 let _one = self.switching.lock().await;
251 let root = self.root().ok_or(Error::NoWorkspace)?;
252 let id = match runtime.enable(&root).await {
253 Ok(id) => id,
254 Err(err @ Error::BridgeDisconnected) => {
257 self.remember(&root, true);
258 return Err(err);
259 }
260 Err(err) => return Err(err),
261 };
262 self.remember(&root, true);
263 Ok(id)
264 }
265
266 pub async fn disable_sync(&self) -> Result<()> {
268 let runtime = self.runtime()?;
269 let _one = self.switching.lock().await;
270 let root = self.root().ok_or(Error::NoWorkspace)?;
271 runtime.disable(&root).await?;
272 self.remember(&root, false);
273 Ok(())
274 }
275
276 pub async fn status(&self) -> proto::SyncStatusResult {
278 match &self.sync {
279 Some(runtime) => runtime
282 .status(&self.root().unwrap_or_default())
283 .await
284 .into(),
285 None => proto::SyncStatusResult::not_synced(),
286 }
287 }
288
289 pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
291 let root = self.root()?;
292 let marker = root.join(format!(".{}", self.ctx.app_name));
293 let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
295 .ok()
296 .and_then(|s| s.trim().parse().ok());
297 let sync = match &self.sync {
298 Some(runtime) => runtime.status(&root).await.into(),
299 None => proto::SyncStatusResult::not_synced(),
300 };
301 Some(proto::CurrentWorkspace {
302 reachable: marker.is_dir(),
303 root,
304 workspace_id,
305 sync,
306 })
307 }
308
309 pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
315 let selection = match self.file.load(self.ctx.app_name) {
316 Ok(Some(selection)) => selection,
317 Ok(None) => return None,
318 Err(err) => {
319 tracing::warn!("could not read the selected workspace: {err}");
320 return None;
321 }
322 };
323 {
324 let _one = self.switching.lock().await;
325 if let Err(err) = self.host.select(&selection.root, true).await {
326 tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
327 return None;
328 }
329 }
330 if !selection.sync {
331 return None;
332 }
333 let runtime = self.sync.clone()?;
334 let current = Arc::clone(self);
335 Some(tokio::spawn(async move {
336 let _one = current.switching.lock().await;
339 if current.root().as_deref() != Some(&selection.root) {
340 return;
341 }
342 if let Err(err) = runtime.enable(&selection.root).await {
343 tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
344 }
345 }))
346 }
347
348 async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
353 let _one = self.switching.lock().await;
354 let previous = self.root();
355 self.host.select(root, restoring).await?;
356 if let Some(runtime) = &self.sync {
357 if let Some(previous) = previous.filter(|p| p != root)
358 && let Err(err) = runtime.disable(&previous).await
359 {
360 tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
361 }
362 if sync && let Err(err) = runtime.enable(root).await {
363 tracing::warn!(root = %root.display(), "could not start sync: {err}");
366 }
367 }
368 self.remember(root, sync);
369 Ok(())
370 }
371
372 fn remember(&self, root: &Path, sync: bool) {
373 let selection = Selection {
374 root: root.to_owned(),
375 sync,
376 };
377 if let Err(err) = self.file.save(&selection) {
378 tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
379 }
380 }
381
382 fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
383 self.sync
384 .as_ref()
385 .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
386 }
387}
388
389fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
391 root.join(format!(".{}", ctx.app_name))
392 .join(SYNC_ID_FILE)
393 .is_file()
394}
395
396fn resolve(dir: &Path) -> Result<PathBuf> {
398 std::env::current_dir()
399 .map_err(Error::Io)?
400 .join(dir)
401 .canonicalize()
402 .map_err(Error::Io)
403}
404
405fn destination(dir: &Path) -> Result<PathBuf> {
408 let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
409 if dir.exists() {
410 return Err(Error::Config(format!(
411 "{} already exists; choose a new folder name",
412 dir.display()
413 )));
414 }
415 let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
416 return Err(Error::Config(format!(
417 "{} cannot be a workspace root",
418 dir.display()
419 )));
420 };
421 Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
422}
423
424fn carry_cache(from: &Path, to: &Path, root: &Path) {
431 let sync_from = from.join("sync");
432 if sync_from.is_dir() {
433 let sync_to = to.join("sync");
434 let moved =
435 std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
436 match moved {
437 Ok(()) => {
438 let store = sync_to.join("sync.redb");
439 if store.is_file()
440 && let Err(err) =
441 sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
442 {
443 tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
444 }
445 }
446 Err(err) => {
447 tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
448 }
449 }
450 }
451 if let Err(err) = std::fs::remove_dir_all(from)
452 && err.kind() != std::io::ErrorKind::NotFound
453 {
454 tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
455 }
456}
457
458pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
461 let init = Arc::clone(¤t);
462 let select = Arc::clone(¤t);
463 let relocate = Arc::clone(¤t);
464 let remove = Arc::clone(¤t);
465 router
466 .method(proto::WORKSPACE_MOVE, move |req| {
467 let current = Arc::clone(&relocate);
468 async move {
469 let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
470 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
471 let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
472 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
473 }
474 })
475 .method(proto::WORKSPACE_REMOVE, move |req| {
476 let current = Arc::clone(&remove);
477 async move {
478 let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
479 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
480 current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
481 serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
482 }
483 })
484 .method(proto::WORKSPACE_INIT, move |req| {
485 let current = Arc::clone(&init);
486 async move {
487 let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
488 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
489 let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
490 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
491 }
492 })
493 .method(proto::WORKSPACE_SELECT, move |req| {
494 let current = Arc::clone(&select);
495 async move {
496 let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
497 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
498 let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
499 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
500 }
501 })
502 .method(proto::WORKSPACE_CURRENT, move |_| {
503 let current = Arc::clone(¤t);
504 async move {
505 let workspace = current.describe().await;
506 serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
507 .map_err(|e| RpcError::internal(e.to_string()))
508 }
509 })
510}
511
512fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
523 let root = resolve(dir)?;
524 let marker = root.join(format!(".{}", ctx.app_name));
525 let created = !marker.is_dir();
526 if created {
527 std::fs::create_dir(&marker).map_err(Error::Io)?;
528 }
529
530 Ok(proto::WorkspaceInitResult {
531 workspace_id: slug(&root),
532 root,
533 created,
534 })
535}
536
537fn drop_bare_registry(path: &Path) -> Result<()> {
540 let config = read_config(path)?;
541 if config.len() == 1 && config.contains_key("workspace") {
542 std::fs::remove_file(path).map_err(Error::Io)?;
543 }
544 Ok(())
545}
546
547fn read_config(path: &Path) -> Result<toml::Table> {
549 match std::fs::read_to_string(path) {
550 Ok(text) => text
551 .parse()
552 .map_err(|e: toml::de::Error| Error::Config(format!("{}: {e}", path.display()))),
553 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
554 Err(e) => Err(Error::Io(e)),
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 const REGISTRY_ONLY: &str = "[workspace.ledger]\npath = \"/home/me/ledger\"\n";
563
564 #[test]
565 fn only_a_registry_only_config_is_dropped() {
566 let dir = tempfile::tempdir().unwrap();
567 let path = dir.path().join("config.toml");
568
569 std::fs::write(&path, REGISTRY_ONLY).unwrap();
570 drop_bare_registry(&path).unwrap();
571 assert!(!path.exists());
572 drop_bare_registry(&path).unwrap();
574
575 std::fs::write(&path, format!("schema_version = 2\n\n{REGISTRY_ONLY}")).unwrap();
576 drop_bare_registry(&path).unwrap();
577 assert!(path.exists());
578 }
579
580 #[test]
581 fn init_writes_no_config() {
582 let dir = tempfile::tempdir().unwrap();
583 let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp")));
584 let result = init_workspace(ctx, dir.path()).unwrap();
585 assert!(result.created);
586 let workspace = Workspace::from_root(ctx, dir.path()).unwrap();
587 assert!(workspace.marker_dir().is_dir());
588 assert!(!workspace.config_path().exists());
589 }
590}