Skip to main content

sapphire_framework_server/
current.rs

1//! The one workspace a server serves, and what changing it does (#215).
2//!
3//! [`WorkspaceHost`] holds the open workspace; this decides which one it is. Selecting
4//! another closes the current one — its index, its replica, its live sessions — and opens
5//! the new one; sync follows the workspace that has it (decision 3 of the spec). Every
6//! `workspace.*` and `sync.*` method acts through here.
7
8use 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
24/// How long a move or a delete waits for the workspace's replica store to close.
25const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
26
27/// The server's current workspace.
28pub struct Current {
29    ctx: &'static AppContext,
30    host: Arc<WorkspaceHost>,
31    sync: Option<Arc<SyncRuntime>>,
32    file: SelectionFile,
33    /// One selection, and one sync switch, at a time.
34    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    /// The current workspace of `host`, synced by `sync` if there is one, remembered in
47    /// `file`.
48    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    /// The host holding the open workspace.
64    pub fn host(&self) -> &Arc<WorkspaceHost> {
65        &self.host
66    }
67
68    /// The sync runtime, when this server syncs.
69    pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
70        self.sync.as_ref()
71    }
72
73    /// The current workspace's root.
74    pub fn root(&self) -> Option<PathBuf> {
75        self.host.root()
76    }
77
78    /// Make the workspace at `dir` current. Sync is on for it when it has a sync id.
79    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    /// Create this app's workspace at `dir` — the marker and the marker registry's entry,
87    /// idempotently — and make it current.
88    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    /// Place the workgroup workspace `selector` at `dir`, make it current and sync it.
96    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    /// Move the current workspace's folder to `dir`, which must not exist yet, and keep
104    /// serving it from there, syncing as before.
105    ///
106    /// The replica's state moves with it, so sync carries on as the same replica rather
107    /// than meeting its own files as strangers. The search index does not — it records
108    /// absolute paths — and is rebuilt in the background.
109    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            // Read before the move: the cache is keyed by the root's path.
121            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                // Back where it was, as it was.
126                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        // Outside the switch lock: a reindex walks every file, and a switch must not wait
152        // on it. One that lands first finds this workspace no longer current, and stops.
153        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    /// Stop serving the current workspace; with `delete`, delete its folder and its cache
164    /// too. Sync stops for this host only: the workgroup and the other devices keep it.
165    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        // Read before anything goes: the cache is keyed by the root's path.
169        let cache = Workspace::from_root(self.ctx, &root)
170            .ok()
171            .map(|w| w.cache_dir());
172        // Stopped first, so the watcher never reports the files going as deletions to
173        // replicate; and, before a delete, closed, so its store can go too.
174        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    /// Stop syncing `root` and close its replica store, before its folder moves or goes,
205    /// returning whether it was synced. A store still in use is the error, and leaves the
206    /// workspace syncing as before.
207    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    /// Open `root` again after [`relocate`](Self::relocate) closed it, and sync it again
224    /// when it was. Failures leave it selected, unopened, the way a restore does.
225    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    /// Start syncing the current workspace, and remember that.
239    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            // The runtime enables it once the bridge is back, so remember it as synced: the
246            // next start tries again too (#244).
247            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    /// Stop syncing the current workspace, and remember that.
258    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    /// The current workspace's sync state; not synced when there is none.
268    pub async fn status(&self) -> proto::SyncStatusResult {
269        match &self.sync {
270            // An empty root names nothing, which the runtime reports as not synced, with
271            // the bridge's view all the same.
272            Some(runtime) => runtime
273                .status(&self.root().unwrap_or_default())
274                .await
275                .into(),
276            None => proto::SyncStatusResult::not_synced(),
277        }
278    }
279
280    /// The current workspace as `workspace.current` reports it.
281    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
282        let root = self.root()?;
283        let marker = root.join(format!(".{}", self.ctx.app_name));
284        // Read, never minted: describing must not create a sync id nobody asked for.
285        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    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
301    /// selected, unopened, so `workspace.current` can say so.
302    ///
303    /// The open happens now, so the first client finds the workspace; sync, which talks to
304    /// the bridge and may dial peers, starts on the returned task.
305    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            // A switch that landed first wins: sync starts only for a workspace still
328            // current.
329            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    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
340    ///
341    /// The open comes first: a workspace that does not open leaves the previous one current,
342    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
343    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                // Selected all the same: the workspace works without sync, and the status
355                // carries the failure.
356                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
380/// Whether `root` has synced before: it carries a sync id.
381fn 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
387/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
388fn 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
396/// Where a move to `dir` puts the root: `dir` made absolute, through its parent's
397/// canonical path, since `dir` itself must not exist yet.
398fn 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
415/// Carry a moved workspace's cache from `from` to `to`, its new key: the replica's state,
416/// rebased onto `root`. The rest — the search index, which records absolute paths — is
417/// dropped, to be rebuilt.
418///
419/// Best-effort: a replica that does not come along is a replica that starts over, and
420/// syncing reports why.
421fn 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
449/// Point the registry entries naming `from` at `to`, in the marker's `config.toml`.
450fn 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, &registry)?;
461    }
462    Ok(())
463}
464
465/// Add `workspace.init`, `workspace.select`, `workspace.current`, `workspace.move` and
466/// `workspace.remove` to `router`.
467pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
468    let init = Arc::clone(&current);
469    let select = Arc::clone(&current);
470    let relocate = Arc::clone(&current);
471    let remove = Arc::clone(&current);
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(&current);
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
519/// Create the workspace home at `dir`: the marker directory and the marker registry's
520/// entry, idempotently. The sync id is `sync.enable` / `sync.map`'s to mint, not this one's.
521///
522/// A relative `dir` is resolved against the server's cwd. The registry entry's id is the
523/// root's directory name, slugified; `created` is `false` when the marker was already there,
524/// and an entry already there is kept as it is.
525fn 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    // Reads the marker's `config.toml`, keyed the way the apps' CLIs key their
534    // `--workspace` selectors. The registry lives in the marker, so it travels with the
535    // workspace when it syncs.
536    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, &registry)?;
544    }
545
546    Ok(proto::WorkspaceInitResult {
547        root,
548        workspace_id: id,
549        created,
550    })
551}
552
553/// The registry as the marker's `config.toml` holds it, or an empty one.
554///
555/// A file another application wrote without a `[workspace]` table is an empty registry,
556/// not an error: the marker's config is the app's own file, and a workspace created
557/// before this table existed is a workspace with no entries.
558fn 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
574/// Write the registry back into the marker's `config.toml`, keeping the rest of the file.
575///
576/// The marker's config is the app's own document, and a rewrite that dropped the rest of
577/// it would eat an application's settings.
578fn 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}