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::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
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` — its marker, idempotently — and make it
87    /// 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    ///
97    /// `dir` needs no marker: placing makes one. One that an older `workspace.init` made
98    /// first may hold a `config.toml` with nothing but the `[workspace]` registry, which
99    /// would meet the workspace's own `config.toml` as a conflict on the first sync and win
100    /// (#253), so a directory mapped for the first time loses it.
101    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    /// Move the current workspace's folder to `dir`, which must not exist yet, and keep
116    /// serving it from there, syncing as before.
117    ///
118    /// The replica's state moves with it, so sync carries on as the same replica rather
119    /// than meeting its own files as strangers. The search index does not — it records
120    /// absolute paths — and is rebuilt in the background.
121    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            // Read before the move: the cache is keyed by the root's path.
133            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                // Back where it was, as it was.
138                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        // Outside the switch lock: a reindex walks every file, and a switch must not wait
161        // on it. One that lands first finds this workspace no longer current, and stops.
162        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    /// Stop serving the current workspace; with `delete`, delete its folder and its cache
173    /// too. Sync stops for this host only: the workgroup and the other devices keep it.
174    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        // Read before anything goes: the cache is keyed by the root's path.
178        let cache = Workspace::from_root(self.ctx, &root)
179            .ok()
180            .map(|w| w.cache_dir());
181        // Stopped first, so the watcher never reports the files going as deletions to
182        // replicate; and, before a delete, closed, so its store can go too.
183        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    /// Stop syncing `root` and close its replica store, before its folder moves or goes,
214    /// returning whether it was synced. A store still in use is the error, and leaves the
215    /// workspace syncing as before.
216    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    /// Open `root` again after [`relocate`](Self::relocate) closed it, and sync it again
233    /// when it was. Failures leave it selected, unopened, the way a restore does.
234    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    /// Start syncing the current workspace, and remember that.
248    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            // The runtime enables it once the bridge is back, so remember it as synced: the
255            // next start tries again too (#244).
256            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    /// Stop syncing the current workspace, and remember that.
267    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    /// The current workspace's sync state; not synced when there is none.
277    pub async fn status(&self) -> proto::SyncStatusResult {
278        match &self.sync {
279            // An empty root names nothing, which the runtime reports as not synced, with
280            // the bridge's view all the same.
281            Some(runtime) => runtime
282                .status(&self.root().unwrap_or_default())
283                .await
284                .into(),
285            None => proto::SyncStatusResult::not_synced(),
286        }
287    }
288
289    /// The current workspace as `workspace.current` reports it.
290    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
291        let root = self.root()?;
292        let marker = root.join(format!(".{}", self.ctx.app_name));
293        // Read, never minted: describing must not create a sync id nobody asked for.
294        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    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
310    /// selected, unopened, so `workspace.current` can say so.
311    ///
312    /// The open happens now, so the first client finds the workspace; sync, which talks to
313    /// the bridge and may dial peers, starts on the returned task.
314    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            // A switch that landed first wins: sync starts only for a workspace still
337            // current.
338            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    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
349    ///
350    /// The open comes first: a workspace that does not open leaves the previous one current,
351    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
352    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                // Selected all the same: the workspace works without sync, and the status
364                // carries the failure.
365                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
389/// Whether `root` has synced before: it carries a sync id.
390fn 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
396/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
397fn 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
405/// Where a move to `dir` puts the root: `dir` made absolute, through its parent's
406/// canonical path, since `dir` itself must not exist yet.
407fn 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
424/// Carry a moved workspace's cache from `from` to `to`, its new key: the replica's state,
425/// rebased onto `root`. The rest — the search index, which records absolute paths — is
426/// dropped, to be rebuilt.
427///
428/// Best-effort: a replica that does not come along is a replica that starts over, and
429/// syncing reports why.
430fn 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
458/// Add `workspace.init`, `workspace.select`, `workspace.current`, `workspace.move` and
459/// `workspace.remove` to `router`.
460pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
461    let init = Arc::clone(&current);
462    let select = Arc::clone(&current);
463    let relocate = Arc::clone(&current);
464    let remove = Arc::clone(&current);
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(&current);
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
512/// Create the workspace home at `dir`: the marker directory, idempotently. The sync id is
513/// `sync.enable` / `sync.map`'s to mint, not this one's.
514///
515/// A relative `dir` is resolved against the server's cwd. `created` is `false` when the
516/// marker was already there.
517///
518/// No `[workspace]` registry is written into the marker's `config.toml` any more (#217):
519/// it keyed the apps' `--workspace` selectors, which went with the server serving one
520/// workspace, and a `config.toml` holding only it lost the application's settings on the
521/// first sync (#253).
522fn 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
537/// Delete the marker's `config.toml` when it holds the `[workspace]` registry an older
538/// `workspace.init` wrote, and nothing else.
539fn 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
547/// The marker's `config.toml` as a table; an empty one when there is no file.
548fn 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        // Nothing there is nothing to drop.
573        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}