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 = runtime.enable(&root).await?;
244        self.remember(&root, true);
245        Ok(id)
246    }
247
248    /// Stop syncing the current workspace, and remember that.
249    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    /// The current workspace's sync state; not synced when there is none.
259    pub async fn status(&self) -> proto::SyncStatusResult {
260        match &self.sync {
261            // An empty root names nothing, which the runtime reports as not synced, with
262            // the bridge's view all the same.
263            Some(runtime) => runtime
264                .status(&self.root().unwrap_or_default())
265                .await
266                .into(),
267            None => proto::SyncStatusResult::not_synced(),
268        }
269    }
270
271    /// The current workspace as `workspace.current` reports it.
272    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
273        let root = self.root()?;
274        let marker = root.join(format!(".{}", self.ctx.app_name));
275        // Read, never minted: describing must not create a sync id nobody asked for.
276        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    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
292    /// selected, unopened, so `workspace.current` can say so.
293    ///
294    /// The open happens now, so the first client finds the workspace; sync, which talks to
295    /// the bridge and may dial peers, starts on the returned task.
296    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            // A switch that landed first wins: sync starts only for a workspace still
319            // current.
320            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    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
331    ///
332    /// The open comes first: a workspace that does not open leaves the previous one current,
333    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
334    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                // Selected all the same: the workspace works without sync, and the status
346                // carries the failure.
347                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
371/// Whether `root` has synced before: it carries a sync id.
372fn 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
378/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
379fn 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
387/// Where a move to `dir` puts the root: `dir` made absolute, through its parent's
388/// canonical path, since `dir` itself must not exist yet.
389fn 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
406/// Carry a moved workspace's cache from `from` to `to`, its new key: the replica's state,
407/// rebased onto `root`. The rest — the search index, which records absolute paths — is
408/// dropped, to be rebuilt.
409///
410/// Best-effort: a replica that does not come along is a replica that starts over, and
411/// syncing reports why.
412fn 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
440/// Point the registry entries naming `from` at `to`, in the marker's `config.toml`.
441fn 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, &registry)?;
452    }
453    Ok(())
454}
455
456/// Add `workspace.init`, `workspace.select`, `workspace.current`, `workspace.move` and
457/// `workspace.remove` to `router`.
458pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
459    let init = Arc::clone(&current);
460    let select = Arc::clone(&current);
461    let relocate = Arc::clone(&current);
462    let remove = Arc::clone(&current);
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(&current);
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
510/// Create the workspace home at `dir`: the marker directory and the marker registry's
511/// entry, idempotently. The sync id is `sync.enable` / `sync.map`'s to mint, not this one's.
512///
513/// A relative `dir` is resolved against the server's cwd. The registry entry's id is the
514/// root's directory name, slugified; `created` is `false` when the marker was already there,
515/// and an entry already there is kept as it is.
516fn 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    // Reads the marker's `config.toml`, keyed the way the apps' CLIs key their
525    // `--workspace` selectors. The registry lives in the marker, so it travels with the
526    // workspace when it syncs.
527    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, &registry)?;
535    }
536
537    Ok(proto::WorkspaceInitResult {
538        root,
539        workspace_id: id,
540        created,
541    })
542}
543
544/// The registry as the marker's `config.toml` holds it, or an empty one.
545///
546/// A file another application wrote without a `[workspace]` table is an empty registry,
547/// not an error: the marker's config is the app's own file, and a workspace created
548/// before this table existed is a workspace with no entries.
549fn 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
565/// Write the registry back into the marker's `config.toml`, keeping the rest of the file.
566///
567/// The marker's config is the app's own document, and a rewrite that dropped the rest of
568/// it would eat an application's settings.
569fn 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}