sapphire_framework_server/
current.rs1use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use grain_id::GrainId;
12use sapphire_backend::protocol as proto;
13use sapphire_backend::{WorkspaceBackend, WorkspaceEntry, WorkspaceRegistry};
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> {
97 let runtime = self.runtime()?;
98 let root = runtime.place(selector, dir).await?;
99 self.switch(&root, false, false).await?;
100 self.enable_sync().await
101 }
102
103 pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
110 {
111 let _one = self.switching.lock().await;
112 let from = self.root().ok_or(Error::NoWorkspace)?;
113 let to = destination(dir)?;
114 if to.starts_with(&from) {
115 return Err(Error::Config(format!(
116 "cannot move {} into itself",
117 from.display()
118 )));
119 }
120 let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
122 let synced = self.let_go(&from).await?;
123 self.host.close();
124 if let Err(err) = std::fs::rename(&from, &to) {
125 self.reopen(&from, synced).await;
127 return Err(match err.kind() {
128 std::io::ErrorKind::CrossesDevices => Error::Config(format!(
129 "cannot move {} to another drive ({}); move it there yourself, then open it",
130 from.display(),
131 to.display()
132 )),
133 _ => Error::Io(std::io::Error::new(
134 err.kind(),
135 format!(
136 "could not move {} to {}: {err}",
137 from.display(),
138 to.display()
139 ),
140 )),
141 });
142 }
143
144 let workspace = Workspace::from_root(self.ctx, &to)?;
145 carry_cache(&from_cache, &workspace.cache_dir(), &to);
146 if let Err(err) = rebase_registry(&workspace.config_path(), &from, &to) {
147 tracing::warn!(root = %to.display(), "could not update the workspace registry: {err}");
148 }
149 self.reopen(&to, synced).await;
150 }
151 if let Ok(backend) = self.host.backend().await {
154 tokio::spawn(async move {
155 if let Err(err) = backend.sync().await {
156 tracing::warn!("re-indexing the moved workspace: {err}");
157 }
158 });
159 }
160 self.describe().await.ok_or(Error::NoWorkspace)
161 }
162
163 pub async fn remove(&self, delete: bool) -> Result<()> {
166 let _one = self.switching.lock().await;
167 let root = self.root().ok_or(Error::NoWorkspace)?;
168 let cache = Workspace::from_root(self.ctx, &root)
170 .ok()
171 .map(|w| w.cache_dir());
172 if delete {
175 self.let_go(&root).await?;
176 } else if let Some(runtime) = &self.sync
177 && let Err(err) = runtime.disable(&root).await
178 {
179 tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
180 }
181 self.host.close();
182 self.file.clear()?;
183 if delete {
184 match std::fs::remove_dir_all(&root) {
185 Ok(()) => {}
186 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
187 Err(e) => {
188 return Err(Error::Io(std::io::Error::new(
189 e.kind(),
190 format!("could not delete {}: {e}", root.display()),
191 )));
192 }
193 }
194 if let Some(cache) = cache
195 && let Err(err) = std::fs::remove_dir_all(&cache)
196 && err.kind() != std::io::ErrorKind::NotFound
197 {
198 tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
199 }
200 }
201 Ok(())
202 }
203
204 async fn let_go(&self, root: &Path) -> Result<bool> {
208 let Some(runtime) = &self.sync else {
209 return Ok(false);
210 };
211 if !runtime.roots().await.iter().any(|r| r == root) {
212 return Ok(false);
213 }
214 if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
215 if let Err(again) = runtime.enable(root).await {
216 tracing::warn!(root = %root.display(), "could not restart sync: {again}");
217 }
218 return Err(err);
219 }
220 Ok(true)
221 }
222
223 async fn reopen(&self, root: &Path, sync: bool) {
226 if let Err(err) = self.host.select(root, true).await {
227 tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
228 }
229 if sync
230 && let Some(runtime) = &self.sync
231 && let Err(err) = runtime.enable(root).await
232 {
233 tracing::warn!(root = %root.display(), "could not restart sync: {err}");
234 }
235 self.remember(root, sync);
236 }
237
238 pub async fn enable_sync(&self) -> Result<GrainId> {
240 let runtime = self.runtime()?;
241 let _one = self.switching.lock().await;
242 let root = self.root().ok_or(Error::NoWorkspace)?;
243 let id = match runtime.enable(&root).await {
244 Ok(id) => id,
245 Err(err @ Error::BridgeDisconnected) => {
248 self.remember(&root, true);
249 return Err(err);
250 }
251 Err(err) => return Err(err),
252 };
253 self.remember(&root, true);
254 Ok(id)
255 }
256
257 pub async fn disable_sync(&self) -> Result<()> {
259 let runtime = self.runtime()?;
260 let _one = self.switching.lock().await;
261 let root = self.root().ok_or(Error::NoWorkspace)?;
262 runtime.disable(&root).await?;
263 self.remember(&root, false);
264 Ok(())
265 }
266
267 pub async fn status(&self) -> proto::SyncStatusResult {
269 match &self.sync {
270 Some(runtime) => runtime
273 .status(&self.root().unwrap_or_default())
274 .await
275 .into(),
276 None => proto::SyncStatusResult::not_synced(),
277 }
278 }
279
280 pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
282 let root = self.root()?;
283 let marker = root.join(format!(".{}", self.ctx.app_name));
284 let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
286 .ok()
287 .and_then(|s| s.trim().parse().ok());
288 let sync = match &self.sync {
289 Some(runtime) => runtime.status(&root).await.into(),
290 None => proto::SyncStatusResult::not_synced(),
291 };
292 Some(proto::CurrentWorkspace {
293 reachable: marker.is_dir(),
294 root,
295 workspace_id,
296 sync,
297 })
298 }
299
300 pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
306 let selection = match self.file.load(self.ctx.app_name) {
307 Ok(Some(selection)) => selection,
308 Ok(None) => return None,
309 Err(err) => {
310 tracing::warn!("could not read the selected workspace: {err}");
311 return None;
312 }
313 };
314 {
315 let _one = self.switching.lock().await;
316 if let Err(err) = self.host.select(&selection.root, true).await {
317 tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
318 return None;
319 }
320 }
321 if !selection.sync {
322 return None;
323 }
324 let runtime = self.sync.clone()?;
325 let current = Arc::clone(self);
326 Some(tokio::spawn(async move {
327 let _one = current.switching.lock().await;
330 if current.root().as_deref() != Some(&selection.root) {
331 return;
332 }
333 if let Err(err) = runtime.enable(&selection.root).await {
334 tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
335 }
336 }))
337 }
338
339 async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
344 let _one = self.switching.lock().await;
345 let previous = self.root();
346 self.host.select(root, restoring).await?;
347 if let Some(runtime) = &self.sync {
348 if let Some(previous) = previous.filter(|p| p != root)
349 && let Err(err) = runtime.disable(&previous).await
350 {
351 tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
352 }
353 if sync && let Err(err) = runtime.enable(root).await {
354 tracing::warn!(root = %root.display(), "could not start sync: {err}");
357 }
358 }
359 self.remember(root, sync);
360 Ok(())
361 }
362
363 fn remember(&self, root: &Path, sync: bool) {
364 let selection = Selection {
365 root: root.to_owned(),
366 sync,
367 };
368 if let Err(err) = self.file.save(&selection) {
369 tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
370 }
371 }
372
373 fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
374 self.sync
375 .as_ref()
376 .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
377 }
378}
379
380fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
382 root.join(format!(".{}", ctx.app_name))
383 .join(SYNC_ID_FILE)
384 .is_file()
385}
386
387fn resolve(dir: &Path) -> Result<PathBuf> {
389 std::env::current_dir()
390 .map_err(Error::Io)?
391 .join(dir)
392 .canonicalize()
393 .map_err(Error::Io)
394}
395
396fn destination(dir: &Path) -> Result<PathBuf> {
399 let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
400 if dir.exists() {
401 return Err(Error::Config(format!(
402 "{} already exists; choose a new folder name",
403 dir.display()
404 )));
405 }
406 let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
407 return Err(Error::Config(format!(
408 "{} cannot be a workspace root",
409 dir.display()
410 )));
411 };
412 Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
413}
414
415fn carry_cache(from: &Path, to: &Path, root: &Path) {
422 let sync_from = from.join("sync");
423 if sync_from.is_dir() {
424 let sync_to = to.join("sync");
425 let moved =
426 std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
427 match moved {
428 Ok(()) => {
429 let store = sync_to.join("sync.redb");
430 if store.is_file()
431 && let Err(err) =
432 sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
433 {
434 tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
435 }
436 }
437 Err(err) => {
438 tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
439 }
440 }
441 }
442 if let Err(err) = std::fs::remove_dir_all(from)
443 && err.kind() != std::io::ErrorKind::NotFound
444 {
445 tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
446 }
447}
448
449fn rebase_registry(config_path: &Path, from: &Path, to: &Path) -> Result<()> {
451 let mut registry = read_registry(config_path)?;
452 let mut changed = false;
453 for entry in registry.0.values_mut() {
454 if entry.path.as_deref() == Some(from) {
455 entry.path = Some(to.to_owned());
456 changed = true;
457 }
458 }
459 if changed {
460 write_registry(config_path, ®istry)?;
461 }
462 Ok(())
463}
464
465pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
468 let init = Arc::clone(¤t);
469 let select = Arc::clone(¤t);
470 let relocate = Arc::clone(¤t);
471 let remove = Arc::clone(¤t);
472 router
473 .method(proto::WORKSPACE_MOVE, move |req| {
474 let current = Arc::clone(&relocate);
475 async move {
476 let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
477 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
478 let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
479 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
480 }
481 })
482 .method(proto::WORKSPACE_REMOVE, move |req| {
483 let current = Arc::clone(&remove);
484 async move {
485 let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
486 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
487 current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
488 serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
489 }
490 })
491 .method(proto::WORKSPACE_INIT, move |req| {
492 let current = Arc::clone(&init);
493 async move {
494 let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
495 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
496 let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
497 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
498 }
499 })
500 .method(proto::WORKSPACE_SELECT, move |req| {
501 let current = Arc::clone(&select);
502 async move {
503 let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
504 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
505 let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
506 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
507 }
508 })
509 .method(proto::WORKSPACE_CURRENT, move |_| {
510 let current = Arc::clone(¤t);
511 async move {
512 let workspace = current.describe().await;
513 serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
514 .map_err(|e| RpcError::internal(e.to_string()))
515 }
516 })
517}
518
519fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
526 let root = resolve(dir)?;
527 let marker = root.join(format!(".{}", ctx.app_name));
528 let created = !marker.is_dir();
529 if created {
530 std::fs::create_dir(&marker).map_err(Error::Io)?;
531 }
532
533 let workspace = Workspace::from_root(ctx, &root)?;
537 let id = slug(&root);
538 let config_path = workspace.config_path();
539 let registry = read_registry(&config_path)?;
540 if registry.get(&id).is_none() {
541 let mut registry = registry;
542 registry.insert(id.clone(), WorkspaceEntry::local(&root));
543 write_registry(&config_path, ®istry)?;
544 }
545
546 Ok(proto::WorkspaceInitResult {
547 root,
548 workspace_id: id,
549 created,
550 })
551}
552
553fn read_registry(path: &Path) -> Result<WorkspaceRegistry> {
559 #[derive(serde::Deserialize, Default)]
560 struct Config {
561 #[serde(default)]
562 workspace: WorkspaceRegistry,
563 }
564 match std::fs::read_to_string(path) {
565 Ok(text) => {
566 let config: Config = toml::from_str(&text).map_err(|e| Error::SyncId(e.to_string()))?;
567 Ok(config.workspace)
568 }
569 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(WorkspaceRegistry::default()),
570 Err(e) => Err(Error::Io(e)),
571 }
572}
573
574fn write_registry(path: &Path, registry: &WorkspaceRegistry) -> Result<()> {
579 #[derive(serde::Deserialize, serde::Serialize, Default)]
580 struct Config {
581 #[serde(default, skip_serializing_if = "WorkspaceRegistry::is_empty")]
582 workspace: WorkspaceRegistry,
583 }
584 let text = match std::fs::read_to_string(path) {
585 Ok(text) => text,
586 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
587 Err(e) => return Err(Error::Io(e)),
588 };
589 let mut config: Config = toml::from_str(&text).unwrap_or_default();
590 config.workspace = registry.clone();
591 let out = toml::to_string_pretty(&config).map_err(|e| Error::SyncId(e.to_string()))?;
592 std::fs::write(path, out).map_err(Error::Io)
593}