1use 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::settings::Settings;
23use crate::sync::{SYNC_ID_FILE, SyncRuntime};
24
25const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
27
28pub struct Current {
30 ctx: &'static AppContext,
31 host: Arc<WorkspaceHost>,
32 sync: Option<Arc<SyncRuntime>>,
33 file: SelectionFile,
34 settings: Option<Settings>,
37 switching: AsyncMutex<()>,
39}
40
41impl std::fmt::Debug for Current {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 f.debug_struct("Current")
44 .field("root", &self.host.root())
45 .finish()
46 }
47}
48
49impl Current {
50 pub fn new(
53 ctx: &'static AppContext,
54 host: Arc<WorkspaceHost>,
55 sync: Option<Arc<SyncRuntime>>,
56 file: SelectionFile,
57 ) -> Current {
58 Current {
59 ctx,
60 host,
61 sync,
62 file,
63 settings: None,
64 switching: AsyncMutex::new(()),
65 }
66 }
67
68 pub(crate) fn with_settings(mut self, settings: Settings) -> Current {
71 self.settings = Some(settings);
72 self
73 }
74
75 pub fn host(&self) -> &Arc<WorkspaceHost> {
77 &self.host
78 }
79
80 pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
82 self.sync.as_ref()
83 }
84
85 pub fn root(&self) -> Option<PathBuf> {
87 self.host.root()
88 }
89
90 pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
92 let root = resolve(dir)?;
93 let sync = has_sync_id(self.ctx, &root);
94 self.switch(&root, sync, false).await?;
95 self.describe().await.ok_or(Error::NoWorkspace)
96 }
97
98 pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
101 let result = init_workspace(self.ctx, dir)?;
102 let sync = has_sync_id(self.ctx, &result.root);
103 self.switch(&result.root, sync, false).await?;
104 Ok(result)
105 }
106
107 pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
114 let runtime = self.runtime()?;
115 let first = !has_sync_id(self.ctx, &resolve(dir)?);
116 let root = runtime.place(selector, dir).await?;
117 if first {
118 let config = Workspace::from_root(self.ctx, &root)?.config_path();
119 if let Err(err) = drop_bare_registry(&config) {
120 tracing::warn!(config = %config.display(), "could not clear the registry-only config: {err}");
121 }
122 }
123 self.switch(&root, false, false).await?;
124 self.enable_sync().await
125 }
126
127 pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
134 {
135 let _one = self.switching.lock().await;
136 let from = self.root().ok_or(Error::NoWorkspace)?;
137 let to = destination(dir)?;
138 if to.starts_with(&from) {
139 return Err(Error::Config(format!(
140 "cannot move {} into itself",
141 from.display()
142 )));
143 }
144 let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
146 let synced = self.let_go(&from).await?;
147 self.host.close();
148 if let Err(err) = std::fs::rename(&from, &to) {
149 self.reopen(&from, synced).await;
151 return Err(match err.kind() {
152 std::io::ErrorKind::CrossesDevices => Error::Config(format!(
153 "cannot move {} to another drive ({}); move it there yourself, then open it",
154 from.display(),
155 to.display()
156 )),
157 _ => Error::Io(std::io::Error::new(
158 err.kind(),
159 format!(
160 "could not move {} to {}: {err}",
161 from.display(),
162 to.display()
163 ),
164 )),
165 });
166 }
167
168 let workspace = Workspace::from_root(self.ctx, &to)?;
169 carry_cache(&from_cache, &workspace.cache_dir(), &to);
170 self.reopen(&to, synced).await;
171 }
172 if let Ok(backend) = self.host.backend().await {
175 tokio::spawn(async move {
176 let started = std::time::Instant::now();
177 let result = backend.sync().await;
178 crate::instrument::reindexed(started, result.is_ok());
179 if let Err(err) = result {
180 tracing::warn!("re-indexing the moved workspace: {err}");
181 }
182 });
183 }
184 self.describe().await.ok_or(Error::NoWorkspace)
185 }
186
187 pub async fn remove(&self, delete: bool) -> Result<()> {
190 let _one = self.switching.lock().await;
191 let root = self.root().ok_or(Error::NoWorkspace)?;
192 let cache = Workspace::from_root(self.ctx, &root)
194 .ok()
195 .map(|w| w.cache_dir());
196 if delete {
199 self.let_go(&root).await?;
200 } else if let Some(runtime) = &self.sync
201 && let Err(err) = runtime.disable(&root).await
202 {
203 tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
204 }
205 self.host.close();
206 self.file.clear()?;
207 self.refresh_settings();
208 if delete {
209 match std::fs::remove_dir_all(&root) {
210 Ok(()) => {}
211 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
212 Err(e) => {
213 return Err(Error::Io(std::io::Error::new(
214 e.kind(),
215 format!("could not delete {}: {e}", root.display()),
216 )));
217 }
218 }
219 if let Some(cache) = cache
220 && let Err(err) = std::fs::remove_dir_all(&cache)
221 && err.kind() != std::io::ErrorKind::NotFound
222 {
223 tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
224 }
225 }
226 Ok(())
227 }
228
229 async fn let_go(&self, root: &Path) -> Result<bool> {
233 let Some(runtime) = &self.sync else {
234 return Ok(false);
235 };
236 if !runtime.roots().await.iter().any(|r| r == root) {
237 return Ok(false);
238 }
239 if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
240 if let Err(again) = runtime.enable(root).await {
241 tracing::warn!(root = %root.display(), "could not restart sync: {again}");
242 }
243 return Err(err);
244 }
245 Ok(true)
246 }
247
248 async fn reopen(&self, root: &Path, sync: bool) {
251 if let Err(err) = self.host.select(root, true).await {
252 tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
253 }
254 if sync
255 && let Some(runtime) = &self.sync
256 && let Err(err) = runtime.enable(root).await
257 {
258 tracing::warn!(root = %root.display(), "could not restart sync: {err}");
259 }
260 self.remember(root, sync);
261 }
262
263 pub async fn enable_sync(&self) -> Result<GrainId> {
265 let runtime = self.runtime()?;
266 let _one = self.switching.lock().await;
267 let root = self.root().ok_or(Error::NoWorkspace)?;
268 let id = match runtime.enable(&root).await {
269 Ok(id) => id,
270 Err(err @ Error::BridgeDisconnected) => {
273 self.remember(&root, true);
274 return Err(err);
275 }
276 Err(err) => return Err(err),
277 };
278 self.remember(&root, true);
279 Ok(id)
280 }
281
282 pub async fn disable_sync(&self) -> Result<()> {
284 let runtime = self.runtime()?;
285 let _one = self.switching.lock().await;
286 let root = self.root().ok_or(Error::NoWorkspace)?;
287 runtime.disable(&root).await?;
288 self.remember(&root, false);
289 Ok(())
290 }
291
292 pub async fn status(&self) -> proto::SyncStatusResult {
294 match &self.sync {
295 Some(runtime) => runtime
298 .status(&self.root().unwrap_or_default())
299 .await
300 .into(),
301 None => proto::SyncStatusResult::not_synced(),
302 }
303 }
304
305 pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
307 let root = self.root()?;
308 let marker = root.join(format!(".{}", self.ctx.app_name));
309 let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
311 .ok()
312 .and_then(|s| s.trim().parse().ok());
313 let sync = match &self.sync {
314 Some(runtime) => runtime.status(&root).await.into(),
315 None => proto::SyncStatusResult::not_synced(),
316 };
317 Some(proto::CurrentWorkspace {
318 reachable: marker.is_dir(),
319 root,
320 workspace_id,
321 sync,
322 })
323 }
324
325 pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
331 let selection = match self.file.load(self.ctx.app_name) {
332 Ok(Some(selection)) => selection,
333 Ok(None) => return None,
334 Err(err) => {
335 tracing::warn!("could not read the selected workspace: {err}");
336 return None;
337 }
338 };
339 {
340 let _one = self.switching.lock().await;
341 if let Err(err) = self.host.select(&selection.root, true).await {
342 tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
343 return None;
344 }
345 crate::api_keys::import_once(self.ctx, &selection.root);
346 self.refresh_settings();
347 }
348 if !selection.sync {
349 return None;
350 }
351 let runtime = self.sync.clone()?;
352 let current = Arc::clone(self);
353 Some(tokio::spawn(async move {
354 let _one = current.switching.lock().await;
357 if current.root().as_deref() != Some(&selection.root) {
358 return;
359 }
360 if let Err(err) = runtime.enable(&selection.root).await {
361 tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
362 }
363 }))
364 }
365
366 async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
371 let _one = self.switching.lock().await;
372 let previous = self.root();
373 self.host.select(root, restoring).await?;
374 crate::api_keys::import_once(self.ctx, root);
375 if let Some(runtime) = &self.sync {
376 if let Some(previous) = previous.filter(|p| p != root)
377 && let Err(err) = runtime.disable(&previous).await
378 {
379 tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
380 }
381 if sync && let Err(err) = runtime.enable(root).await {
382 tracing::warn!(root = %root.display(), "could not start sync: {err}");
385 }
386 }
387 self.remember(root, sync);
388 Ok(())
389 }
390
391 fn remember(&self, root: &Path, sync: bool) {
392 let selection = Selection {
393 root: root.to_owned(),
394 sync,
395 };
396 if let Err(err) = self.file.save(&selection) {
397 tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
398 }
399 self.refresh_settings();
400 }
401
402 fn refresh_settings(&self) {
404 if let Some(settings) = &self.settings
405 && settings.refresh().is_err()
406 {
407 tracing::warn!("could not read the settings of the selected workspace");
409 }
410 }
411
412 fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
413 self.sync
414 .as_ref()
415 .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
416 }
417}
418
419fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
421 root.join(format!(".{}", ctx.app_name))
422 .join(SYNC_ID_FILE)
423 .is_file()
424}
425
426fn resolve(dir: &Path) -> Result<PathBuf> {
428 std::env::current_dir()
429 .map_err(Error::Io)?
430 .join(dir)
431 .canonicalize()
432 .map_err(Error::Io)
433}
434
435fn destination(dir: &Path) -> Result<PathBuf> {
438 let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
439 if dir.exists() {
440 return Err(Error::Config(format!(
441 "{} already exists; choose a new folder name",
442 dir.display()
443 )));
444 }
445 let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
446 return Err(Error::Config(format!(
447 "{} cannot be a workspace root",
448 dir.display()
449 )));
450 };
451 Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
452}
453
454fn carry_cache(from: &Path, to: &Path, root: &Path) {
461 let sync_from = from.join("sync");
462 if sync_from.is_dir() {
463 let sync_to = to.join("sync");
464 let moved =
465 std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
466 match moved {
467 Ok(()) => {
468 let store = sync_to.join("sync.redb");
469 if store.is_file()
470 && let Err(err) =
471 sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
472 {
473 tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
474 }
475 }
476 Err(err) => {
477 tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
478 }
479 }
480 }
481 if let Err(err) = std::fs::remove_dir_all(from)
482 && err.kind() != std::io::ErrorKind::NotFound
483 {
484 tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
485 }
486}
487
488pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
491 let init = Arc::clone(¤t);
492 let select = Arc::clone(¤t);
493 let relocate = Arc::clone(¤t);
494 let remove = Arc::clone(¤t);
495 router
496 .method(proto::WORKSPACE_MOVE, move |req| {
497 let current = Arc::clone(&relocate);
498 async move {
499 let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
500 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
501 let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
502 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
503 }
504 })
505 .method(proto::WORKSPACE_REMOVE, move |req| {
506 let current = Arc::clone(&remove);
507 async move {
508 let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
509 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
510 current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
511 serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
512 }
513 })
514 .method(proto::WORKSPACE_INIT, move |req| {
515 let current = Arc::clone(&init);
516 async move {
517 let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
518 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
519 let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
520 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
521 }
522 })
523 .method(proto::WORKSPACE_SELECT, move |req| {
524 let current = Arc::clone(&select);
525 async move {
526 let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
527 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
528 let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
529 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
530 }
531 })
532 .method(proto::WORKSPACE_CURRENT, move |_| {
533 let current = Arc::clone(¤t);
534 async move {
535 let workspace = current.describe().await;
536 serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
537 .map_err(|e| RpcError::internal(e.to_string()))
538 }
539 })
540}
541
542fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
553 let absolute = std::env::current_dir().map_err(Error::Io)?.join(dir);
556 std::fs::create_dir_all(&absolute).map_err(Error::Io)?;
557 let root = resolve(&absolute)?;
558 let marker = root.join(format!(".{}", ctx.app_name));
559 let created = !marker.is_dir();
560 if created {
561 std::fs::create_dir(&marker).map_err(Error::Io)?;
562 }
563
564 Ok(proto::WorkspaceInitResult {
565 workspace_id: slug(&root),
566 root,
567 created,
568 })
569}
570
571fn drop_bare_registry(path: &Path) -> Result<()> {
574 let config = read_config(path)?;
575 if config.len() == 1 && config.contains_key("workspace") {
576 std::fs::remove_file(path).map_err(Error::Io)?;
577 }
578 Ok(())
579}
580
581fn read_config(path: &Path) -> Result<toml::Table> {
583 match std::fs::read_to_string(path) {
584 Ok(text) => text.parse().map_err(|e: toml::de::Error| {
585 Error::Config(format!(
586 "{}: {}",
587 path.display(),
588 sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message())
589 ))
590 }),
591 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
592 Err(e) => Err(Error::Io(e)),
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599
600 const REGISTRY_ONLY: &str = "[workspace.ledger]\npath = \"/home/me/ledger\"\n";
601
602 #[test]
603 fn only_a_registry_only_config_is_dropped() {
604 let dir = tempfile::tempdir().unwrap();
605 let path = dir.path().join("config.toml");
606
607 std::fs::write(&path, REGISTRY_ONLY).unwrap();
608 drop_bare_registry(&path).unwrap();
609 assert!(!path.exists());
610 drop_bare_registry(&path).unwrap();
612
613 std::fs::write(&path, format!("schema_version = 2\n\n{REGISTRY_ONLY}")).unwrap();
614 drop_bare_registry(&path).unwrap();
615 assert!(path.exists());
616 }
617
618 struct NoteApp(&'static str);
620
621 impl crate::settings::AppSettings for NoteApp {
622 fn defs(&self) -> Vec<sapphire_framework_settings::SettingDef> {
623 vec![sapphire_framework_settings::SettingDef {
624 key: format!("{}.note", self.0),
625 kind: sapphire_framework_settings::Kind::String { non_empty: false },
626 scopes: vec![sapphire_framework_settings::Scope::Workspace],
627 overridable: false,
628 apply: sapphire_framework_settings::Apply::Live,
629 default: None,
630 section: "Test".into(),
631 doc: "test".into(),
632 process: sapphire_framework_settings::Process::App,
633 }]
634 }
635 }
636
637 #[tokio::test(flavor = "multi_thread")]
638 async fn workspace_settings_follow_the_selection() {
639 const APP: &str = "sapphire-curtest";
640 let dir = tempfile::tempdir().unwrap();
641 let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new(APP)));
642 ctx.set_config_dir(dir.path().join("config"));
643 ctx.set_cache_dir(dir.path().join("cache"));
644 ctx.set_data_dir(dir.path().join("data"));
645 let file = SelectionFile::at(dir.path().join("config").join("workspace.toml"));
646 let (a, b) = (dir.path().join("a"), dir.path().join("b"));
647 for (root, value) in [(&a, "from a"), (&b, "from b")] {
648 std::fs::create_dir_all(root).unwrap();
649 init_workspace(ctx, root).unwrap();
650 std::fs::write(
651 root.join(format!(".{APP}")).join("config.toml"),
652 format!("[{APP}]\nnote = \"{value}\"\n"),
653 )
654 .unwrap();
655 }
656 let settings = crate::settings::Settings::load_with(
657 ctx,
658 std::sync::Arc::new(NoteApp(APP)),
659 file.clone(),
660 )
661 .unwrap();
662 let key = format!("{APP}.note");
663 let current = Current::new(ctx, Arc::new(WorkspaceHost::new(ctx)), None, file)
664 .with_settings(settings.clone());
665 let mut changed = settings.changed();
666
667 current.select(&a).await.unwrap();
668 assert!(changed.has_changed().unwrap());
669 changed.mark_unchanged();
670 assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from a"));
671
672 current.select(&b).await.unwrap();
673 assert!(changed.has_changed().unwrap());
674 changed.mark_unchanged();
675 assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from b"));
676
677 current.remove(false).await.unwrap();
679 assert!(changed.has_changed().unwrap());
680 assert_eq!(settings.get(&key), None);
681 }
682
683 #[test]
684 fn an_unparsable_marker_config_is_never_quoted() {
685 let dir = tempfile::tempdir().unwrap();
686 let path = dir.path().join("config.toml");
687 std::fs::write(&path, "[app]\ntoken = \"hunter2\" x\n").unwrap();
688 let err = read_config(&path).unwrap_err().to_string();
689 assert!(err.contains(&path.display().to_string()), "{err}");
690 assert!(err.contains("line 2"), "{err}");
691 assert!(!err.contains("hunter2"), "{err}");
692 }
693
694 #[test]
695 fn init_writes_no_config() {
696 let dir = tempfile::tempdir().unwrap();
697 let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp")));
698 let result = init_workspace(ctx, dir.path()).unwrap();
699 assert!(result.created);
700 let workspace = Workspace::from_root(ctx, dir.path()).unwrap();
701 assert!(workspace.marker_dir().is_dir());
702 assert!(!workspace.config_path().exists());
703 }
704
705 #[test]
706 fn init_makes_a_missing_folder() {
707 let tmp = tempfile::tempdir().unwrap();
708 let dir = tmp.path().join("workspaces").join("default");
709 let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp2")));
710 let result = init_workspace(ctx, &dir).unwrap();
711 assert!(result.created);
712 assert_eq!(result.root, dir.canonicalize().unwrap());
713 assert!(dir.join(".sapphire-initapp2").is_dir());
714 }
715}