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::{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/// The server's current workspace.
25pub struct Current {
26    ctx: &'static AppContext,
27    host: Arc<WorkspaceHost>,
28    sync: Option<Arc<SyncRuntime>>,
29    file: SelectionFile,
30    /// One selection, and one sync switch, at a time.
31    switching: AsyncMutex<()>,
32}
33
34impl std::fmt::Debug for Current {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("Current")
37            .field("root", &self.host.root())
38            .finish()
39    }
40}
41
42impl Current {
43    /// The current workspace of `host`, synced by `sync` if there is one, remembered in
44    /// `file`.
45    pub fn new(
46        ctx: &'static AppContext,
47        host: Arc<WorkspaceHost>,
48        sync: Option<Arc<SyncRuntime>>,
49        file: SelectionFile,
50    ) -> Current {
51        Current {
52            ctx,
53            host,
54            sync,
55            file,
56            switching: AsyncMutex::new(()),
57        }
58    }
59
60    /// The host holding the open workspace.
61    pub fn host(&self) -> &Arc<WorkspaceHost> {
62        &self.host
63    }
64
65    /// The sync runtime, when this server syncs.
66    pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
67        self.sync.as_ref()
68    }
69
70    /// The current workspace's root.
71    pub fn root(&self) -> Option<PathBuf> {
72        self.host.root()
73    }
74
75    /// Make the workspace at `dir` current. Sync is on for it when it has a sync id.
76    pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
77        let root = resolve(dir)?;
78        let sync = has_sync_id(self.ctx, &root);
79        self.switch(&root, sync, false).await?;
80        self.describe().await.ok_or(Error::NoWorkspace)
81    }
82
83    /// Create this app's workspace at `dir` — the marker and the marker registry's entry,
84    /// idempotently — and make it current.
85    pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
86        let result = init_workspace(self.ctx, dir)?;
87        let sync = has_sync_id(self.ctx, &result.root);
88        self.switch(&result.root, sync, false).await?;
89        Ok(result)
90    }
91
92    /// Place the workgroup workspace `selector` at `dir`, make it current and sync it.
93    pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
94        let runtime = self.runtime()?;
95        let root = runtime.place(selector, dir).await?;
96        self.switch(&root, false, false).await?;
97        self.enable_sync().await
98    }
99
100    /// Start syncing the current workspace, and remember that.
101    pub async fn enable_sync(&self) -> Result<GrainId> {
102        let runtime = self.runtime()?;
103        let _one = self.switching.lock().await;
104        let root = self.root().ok_or(Error::NoWorkspace)?;
105        let id = runtime.enable(&root).await?;
106        self.remember(&root, true);
107        Ok(id)
108    }
109
110    /// Stop syncing the current workspace, and remember that.
111    pub async fn disable_sync(&self) -> Result<()> {
112        let runtime = self.runtime()?;
113        let _one = self.switching.lock().await;
114        let root = self.root().ok_or(Error::NoWorkspace)?;
115        runtime.disable(&root).await?;
116        self.remember(&root, false);
117        Ok(())
118    }
119
120    /// The current workspace's sync state; not synced when there is none.
121    pub async fn status(&self) -> proto::SyncStatusResult {
122        match &self.sync {
123            // An empty root names nothing, which the runtime reports as not synced, with
124            // the bridge's view all the same.
125            Some(runtime) => runtime
126                .status(&self.root().unwrap_or_default())
127                .await
128                .into(),
129            None => proto::SyncStatusResult::not_synced(),
130        }
131    }
132
133    /// The current workspace as `workspace.current` reports it.
134    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
135        let root = self.root()?;
136        let marker = root.join(format!(".{}", self.ctx.app_name));
137        // Read, never minted: describing must not create a sync id nobody asked for.
138        let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
139            .ok()
140            .and_then(|s| s.trim().parse().ok());
141        let sync = match &self.sync {
142            Some(runtime) => runtime.status(&root).await.into(),
143            None => proto::SyncStatusResult::not_synced(),
144        };
145        Some(proto::CurrentWorkspace {
146            reachable: marker.is_dir(),
147            root,
148            workspace_id,
149            sync,
150        })
151    }
152
153    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
154    /// selected, unopened, so `workspace.current` can say so.
155    ///
156    /// The open happens now, so the first client finds the workspace; sync, which talks to
157    /// the bridge and may dial peers, starts on the returned task.
158    pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
159        let selection = match self.file.load(self.ctx.app_name) {
160            Ok(Some(selection)) => selection,
161            Ok(None) => return None,
162            Err(err) => {
163                tracing::warn!("could not read the selected workspace: {err}");
164                return None;
165            }
166        };
167        {
168            let _one = self.switching.lock().await;
169            if let Err(err) = self.host.select(&selection.root, true).await {
170                tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
171                return None;
172            }
173        }
174        if !selection.sync {
175            return None;
176        }
177        let runtime = self.sync.clone()?;
178        let current = Arc::clone(self);
179        Some(tokio::spawn(async move {
180            // A switch that landed first wins: sync starts only for a workspace still
181            // current.
182            let _one = current.switching.lock().await;
183            if current.root().as_deref() != Some(&selection.root) {
184                return;
185            }
186            if let Err(err) = runtime.enable(&selection.root).await {
187                tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
188            }
189        }))
190    }
191
192    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
193    ///
194    /// The open comes first: a workspace that does not open leaves the previous one current,
195    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
196    async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
197        let _one = self.switching.lock().await;
198        let previous = self.root();
199        self.host.select(root, restoring).await?;
200        if let Some(runtime) = &self.sync {
201            if let Some(previous) = previous.filter(|p| p != root)
202                && let Err(err) = runtime.disable(&previous).await
203            {
204                tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
205            }
206            if sync && let Err(err) = runtime.enable(root).await {
207                // Selected all the same: the workspace works without sync, and the status
208                // carries the failure.
209                tracing::warn!(root = %root.display(), "could not start sync: {err}");
210            }
211        }
212        self.remember(root, sync);
213        Ok(())
214    }
215
216    fn remember(&self, root: &Path, sync: bool) {
217        let selection = Selection {
218            root: root.to_owned(),
219            sync,
220        };
221        if let Err(err) = self.file.save(&selection) {
222            tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
223        }
224    }
225
226    fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
227        self.sync
228            .as_ref()
229            .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
230    }
231}
232
233/// Whether `root` has synced before: it carries a sync id.
234fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
235    root.join(format!(".{}", ctx.app_name))
236        .join(SYNC_ID_FILE)
237        .is_file()
238}
239
240/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
241fn resolve(dir: &Path) -> Result<PathBuf> {
242    std::env::current_dir()
243        .map_err(Error::Io)?
244        .join(dir)
245        .canonicalize()
246        .map_err(Error::Io)
247}
248
249/// Add `workspace.init`, `workspace.select` and `workspace.current` to `router`.
250pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
251    let init = Arc::clone(&current);
252    let select = Arc::clone(&current);
253    router
254        .method(proto::WORKSPACE_INIT, move |req| {
255            let current = Arc::clone(&init);
256            async move {
257                let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
258                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
259                let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
260                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
261            }
262        })
263        .method(proto::WORKSPACE_SELECT, move |req| {
264            let current = Arc::clone(&select);
265            async move {
266                let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
267                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
268                let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
269                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
270            }
271        })
272        .method(proto::WORKSPACE_CURRENT, move |_| {
273            let current = Arc::clone(&current);
274            async move {
275                let workspace = current.describe().await;
276                serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
277                    .map_err(|e| RpcError::internal(e.to_string()))
278            }
279        })
280}
281
282/// Create the workspace home at `dir`: the marker directory and the marker registry's
283/// entry, idempotently. The sync id is `sync.enable` / `sync.map`'s to mint, not this one's.
284///
285/// A relative `dir` is resolved against the server's cwd. The registry entry's id is the
286/// root's directory name, slugified; `created` is `false` when the marker was already there,
287/// and an entry already there is kept as it is.
288fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
289    let root = resolve(dir)?;
290    let marker = root.join(format!(".{}", ctx.app_name));
291    let created = !marker.is_dir();
292    if created {
293        std::fs::create_dir(&marker).map_err(Error::Io)?;
294    }
295
296    // Reads the marker's `config.toml`, keyed the way the apps' CLIs key their
297    // `--workspace` selectors. The registry lives in the marker, so it travels with the
298    // workspace when it syncs.
299    let workspace = Workspace::from_root(ctx, &root)?;
300    let id = slug(&root);
301    let config_path = workspace.config_path();
302    let registry = read_registry(&config_path)?;
303    if registry.get(&id).is_none() {
304        let mut registry = registry;
305        registry.insert(id.clone(), WorkspaceEntry::local(&root));
306        write_registry(&config_path, &registry)?;
307    }
308
309    Ok(proto::WorkspaceInitResult {
310        root,
311        workspace_id: id,
312        created,
313    })
314}
315
316/// The registry as the marker's `config.toml` holds it, or an empty one.
317///
318/// A file another application wrote without a `[workspace]` table is an empty registry,
319/// not an error: the marker's config is the app's own file, and a workspace created
320/// before this table existed is a workspace with no entries.
321fn read_registry(path: &Path) -> Result<WorkspaceRegistry> {
322    #[derive(serde::Deserialize, Default)]
323    struct Config {
324        #[serde(default)]
325        workspace: WorkspaceRegistry,
326    }
327    match std::fs::read_to_string(path) {
328        Ok(text) => {
329            let config: Config = toml::from_str(&text).map_err(|e| Error::SyncId(e.to_string()))?;
330            Ok(config.workspace)
331        }
332        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(WorkspaceRegistry::default()),
333        Err(e) => Err(Error::Io(e)),
334    }
335}
336
337/// Write the registry back into the marker's `config.toml`, keeping the rest of the file.
338///
339/// The marker's config is the app's own document, and a rewrite that dropped the rest of
340/// it would eat an application's settings.
341fn write_registry(path: &Path, registry: &WorkspaceRegistry) -> Result<()> {
342    #[derive(serde::Deserialize, serde::Serialize, Default)]
343    struct Config {
344        #[serde(default, skip_serializing_if = "WorkspaceRegistry::is_empty")]
345        workspace: WorkspaceRegistry,
346    }
347    let text = match std::fs::read_to_string(path) {
348        Ok(text) => text,
349        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
350        Err(e) => return Err(Error::Io(e)),
351    };
352    let mut config: Config = toml::from_str(&text).unwrap_or_default();
353    config.workspace = registry.clone();
354    let out = toml::to_string_pretty(&config).map_err(|e| Error::SyncId(e.to_string()))?;
355    std::fs::write(path, out).map_err(Error::Io)
356}