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 = runtime.enable(&root).await?;
244 self.remember(&root, true);
245 Ok(id)
246 }
247
248 pub async fn disable_sync(&self) -> Result<()> {
250 let runtime = self.runtime()?;
251 let _one = self.switching.lock().await;
252 let root = self.root().ok_or(Error::NoWorkspace)?;
253 runtime.disable(&root).await?;
254 self.remember(&root, false);
255 Ok(())
256 }
257
258 pub async fn status(&self) -> proto::SyncStatusResult {
260 match &self.sync {
261 Some(runtime) => runtime
264 .status(&self.root().unwrap_or_default())
265 .await
266 .into(),
267 None => proto::SyncStatusResult::not_synced(),
268 }
269 }
270
271 pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
273 let root = self.root()?;
274 let marker = root.join(format!(".{}", self.ctx.app_name));
275 let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
277 .ok()
278 .and_then(|s| s.trim().parse().ok());
279 let sync = match &self.sync {
280 Some(runtime) => runtime.status(&root).await.into(),
281 None => proto::SyncStatusResult::not_synced(),
282 };
283 Some(proto::CurrentWorkspace {
284 reachable: marker.is_dir(),
285 root,
286 workspace_id,
287 sync,
288 })
289 }
290
291 pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
297 let selection = match self.file.load(self.ctx.app_name) {
298 Ok(Some(selection)) => selection,
299 Ok(None) => return None,
300 Err(err) => {
301 tracing::warn!("could not read the selected workspace: {err}");
302 return None;
303 }
304 };
305 {
306 let _one = self.switching.lock().await;
307 if let Err(err) = self.host.select(&selection.root, true).await {
308 tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
309 return None;
310 }
311 }
312 if !selection.sync {
313 return None;
314 }
315 let runtime = self.sync.clone()?;
316 let current = Arc::clone(self);
317 Some(tokio::spawn(async move {
318 let _one = current.switching.lock().await;
321 if current.root().as_deref() != Some(&selection.root) {
322 return;
323 }
324 if let Err(err) = runtime.enable(&selection.root).await {
325 tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
326 }
327 }))
328 }
329
330 async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
335 let _one = self.switching.lock().await;
336 let previous = self.root();
337 self.host.select(root, restoring).await?;
338 if let Some(runtime) = &self.sync {
339 if let Some(previous) = previous.filter(|p| p != root)
340 && let Err(err) = runtime.disable(&previous).await
341 {
342 tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
343 }
344 if sync && let Err(err) = runtime.enable(root).await {
345 tracing::warn!(root = %root.display(), "could not start sync: {err}");
348 }
349 }
350 self.remember(root, sync);
351 Ok(())
352 }
353
354 fn remember(&self, root: &Path, sync: bool) {
355 let selection = Selection {
356 root: root.to_owned(),
357 sync,
358 };
359 if let Err(err) = self.file.save(&selection) {
360 tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
361 }
362 }
363
364 fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
365 self.sync
366 .as_ref()
367 .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
368 }
369}
370
371fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
373 root.join(format!(".{}", ctx.app_name))
374 .join(SYNC_ID_FILE)
375 .is_file()
376}
377
378fn resolve(dir: &Path) -> Result<PathBuf> {
380 std::env::current_dir()
381 .map_err(Error::Io)?
382 .join(dir)
383 .canonicalize()
384 .map_err(Error::Io)
385}
386
387fn destination(dir: &Path) -> Result<PathBuf> {
390 let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
391 if dir.exists() {
392 return Err(Error::Config(format!(
393 "{} already exists; choose a new folder name",
394 dir.display()
395 )));
396 }
397 let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
398 return Err(Error::Config(format!(
399 "{} cannot be a workspace root",
400 dir.display()
401 )));
402 };
403 Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
404}
405
406fn carry_cache(from: &Path, to: &Path, root: &Path) {
413 let sync_from = from.join("sync");
414 if sync_from.is_dir() {
415 let sync_to = to.join("sync");
416 let moved =
417 std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
418 match moved {
419 Ok(()) => {
420 let store = sync_to.join("sync.redb");
421 if store.is_file()
422 && let Err(err) =
423 sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
424 {
425 tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
426 }
427 }
428 Err(err) => {
429 tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
430 }
431 }
432 }
433 if let Err(err) = std::fs::remove_dir_all(from)
434 && err.kind() != std::io::ErrorKind::NotFound
435 {
436 tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
437 }
438}
439
440fn rebase_registry(config_path: &Path, from: &Path, to: &Path) -> Result<()> {
442 let mut registry = read_registry(config_path)?;
443 let mut changed = false;
444 for entry in registry.0.values_mut() {
445 if entry.path.as_deref() == Some(from) {
446 entry.path = Some(to.to_owned());
447 changed = true;
448 }
449 }
450 if changed {
451 write_registry(config_path, ®istry)?;
452 }
453 Ok(())
454}
455
456pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
459 let init = Arc::clone(¤t);
460 let select = Arc::clone(¤t);
461 let relocate = Arc::clone(¤t);
462 let remove = Arc::clone(¤t);
463 router
464 .method(proto::WORKSPACE_MOVE, move |req| {
465 let current = Arc::clone(&relocate);
466 async move {
467 let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
468 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
469 let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
470 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
471 }
472 })
473 .method(proto::WORKSPACE_REMOVE, move |req| {
474 let current = Arc::clone(&remove);
475 async move {
476 let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
477 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
478 current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
479 serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
480 }
481 })
482 .method(proto::WORKSPACE_INIT, move |req| {
483 let current = Arc::clone(&init);
484 async move {
485 let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
486 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
487 let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
488 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
489 }
490 })
491 .method(proto::WORKSPACE_SELECT, move |req| {
492 let current = Arc::clone(&select);
493 async move {
494 let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
495 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
496 let result = current.select(&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_CURRENT, move |_| {
501 let current = Arc::clone(¤t);
502 async move {
503 let workspace = current.describe().await;
504 serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
505 .map_err(|e| RpcError::internal(e.to_string()))
506 }
507 })
508}
509
510fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
517 let root = resolve(dir)?;
518 let marker = root.join(format!(".{}", ctx.app_name));
519 let created = !marker.is_dir();
520 if created {
521 std::fs::create_dir(&marker).map_err(Error::Io)?;
522 }
523
524 let workspace = Workspace::from_root(ctx, &root)?;
528 let id = slug(&root);
529 let config_path = workspace.config_path();
530 let registry = read_registry(&config_path)?;
531 if registry.get(&id).is_none() {
532 let mut registry = registry;
533 registry.insert(id.clone(), WorkspaceEntry::local(&root));
534 write_registry(&config_path, ®istry)?;
535 }
536
537 Ok(proto::WorkspaceInitResult {
538 root,
539 workspace_id: id,
540 created,
541 })
542}
543
544fn read_registry(path: &Path) -> Result<WorkspaceRegistry> {
550 #[derive(serde::Deserialize, Default)]
551 struct Config {
552 #[serde(default)]
553 workspace: WorkspaceRegistry,
554 }
555 match std::fs::read_to_string(path) {
556 Ok(text) => {
557 let config: Config = toml::from_str(&text).map_err(|e| Error::SyncId(e.to_string()))?;
558 Ok(config.workspace)
559 }
560 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(WorkspaceRegistry::default()),
561 Err(e) => Err(Error::Io(e)),
562 }
563}
564
565fn write_registry(path: &Path, registry: &WorkspaceRegistry) -> Result<()> {
570 #[derive(serde::Deserialize, serde::Serialize, Default)]
571 struct Config {
572 #[serde(default, skip_serializing_if = "WorkspaceRegistry::is_empty")]
573 workspace: WorkspaceRegistry,
574 }
575 let text = match std::fs::read_to_string(path) {
576 Ok(text) => text,
577 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
578 Err(e) => return Err(Error::Io(e)),
579 };
580 let mut config: Config = toml::from_str(&text).unwrap_or_default();
581 config.workspace = registry.clone();
582 let out = toml::to_string_pretty(&config).map_err(|e| Error::SyncId(e.to_string()))?;
583 std::fs::write(path, out).map_err(Error::Io)
584}