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::settings::Settings;
23use crate::sync::{SYNC_ID_FILE, SyncRuntime};
24
25/// How long a move or a delete waits for the workspace's replica store to close.
26const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
27
28/// The server's current workspace.
29pub struct Current {
30    ctx: &'static AppContext,
31    host: Arc<WorkspaceHost>,
32    sync: Option<Arc<SyncRuntime>>,
33    file: SelectionFile,
34    /// The settings whose workspace scope is the selected workspace's file, read again
35    /// whenever the selection changes.
36    settings: Option<Settings>,
37    /// One selection, and one sync switch, at a time.
38    switching: AsyncMutex<()>,
39}
40
41impl std::fmt::Debug for Current {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("Current")
44            .field("root", &self.host.root())
45            .finish()
46    }
47}
48
49impl Current {
50    /// The current workspace of `host`, synced by `sync` if there is one, remembered in
51    /// `file`.
52    pub fn new(
53        ctx: &'static AppContext,
54        host: Arc<WorkspaceHost>,
55        sync: Option<Arc<SyncRuntime>>,
56        file: SelectionFile,
57    ) -> Current {
58        Current {
59            ctx,
60            host,
61            sync,
62            file,
63            settings: None,
64            switching: AsyncMutex::new(()),
65        }
66    }
67
68    /// Read `settings` again whenever the selected workspace changes, so its workspace
69    /// keys follow the selection.
70    pub(crate) fn with_settings(mut self, settings: Settings) -> Current {
71        self.settings = Some(settings);
72        self
73    }
74
75    /// The host holding the open workspace.
76    pub fn host(&self) -> &Arc<WorkspaceHost> {
77        &self.host
78    }
79
80    /// The sync runtime, when this server syncs.
81    pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
82        self.sync.as_ref()
83    }
84
85    /// The current workspace's root.
86    pub fn root(&self) -> Option<PathBuf> {
87        self.host.root()
88    }
89
90    /// Make the workspace at `dir` current. Sync is on for it when it has a sync id.
91    pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
92        let root = resolve(dir)?;
93        let sync = has_sync_id(self.ctx, &root);
94        self.switch(&root, sync, false).await?;
95        self.describe().await.ok_or(Error::NoWorkspace)
96    }
97
98    /// Create this app's workspace at `dir` — the folder when missing, and its marker,
99    /// idempotently — and make it current.
100    pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
101        let result = init_workspace(self.ctx, dir)?;
102        let sync = has_sync_id(self.ctx, &result.root);
103        self.switch(&result.root, sync, false).await?;
104        Ok(result)
105    }
106
107    /// Place the workgroup workspace `selector` at `dir`, make it current and sync it.
108    ///
109    /// `dir` needs no marker: placing makes one. One that an older `workspace.init` made
110    /// first may hold a `config.toml` with nothing but the `[workspace]` registry, which
111    /// would meet the workspace's own `config.toml` as a conflict on the first sync and win
112    /// (#253), so a directory mapped for the first time loses it.
113    pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
114        let runtime = self.runtime()?;
115        let first = !has_sync_id(self.ctx, &resolve(dir)?);
116        let root = runtime.place(selector, dir).await?;
117        if first {
118            let config = Workspace::from_root(self.ctx, &root)?.config_path();
119            if let Err(err) = drop_bare_registry(&config) {
120                tracing::warn!(config = %config.display(), "could not clear the registry-only config: {err}");
121            }
122        }
123        self.switch(&root, false, false).await?;
124        self.enable_sync().await
125    }
126
127    /// Move the current workspace's folder to `dir`, which must not exist yet, and keep
128    /// serving it from there, syncing as before.
129    ///
130    /// The replica's state moves with it, so sync carries on as the same replica rather
131    /// than meeting its own files as strangers. The search index does not — it records
132    /// absolute paths — and is rebuilt in the background.
133    pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
134        {
135            let _one = self.switching.lock().await;
136            let from = self.root().ok_or(Error::NoWorkspace)?;
137            let to = destination(dir)?;
138            if to.starts_with(&from) {
139                return Err(Error::Config(format!(
140                    "cannot move {} into itself",
141                    from.display()
142                )));
143            }
144            // Read before the move: the cache is keyed by the root's path.
145            let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
146            let synced = self.let_go(&from).await?;
147            self.host.close();
148            if let Err(err) = std::fs::rename(&from, &to) {
149                // Back where it was, as it was.
150                self.reopen(&from, synced).await;
151                return Err(match err.kind() {
152                    std::io::ErrorKind::CrossesDevices => Error::Config(format!(
153                        "cannot move {} to another drive ({}); move it there yourself, then open it",
154                        from.display(),
155                        to.display()
156                    )),
157                    _ => Error::Io(std::io::Error::new(
158                        err.kind(),
159                        format!(
160                            "could not move {} to {}: {err}",
161                            from.display(),
162                            to.display()
163                        ),
164                    )),
165                });
166            }
167
168            let workspace = Workspace::from_root(self.ctx, &to)?;
169            carry_cache(&from_cache, &workspace.cache_dir(), &to);
170            self.reopen(&to, synced).await;
171        }
172        // Outside the switch lock: a reindex walks every file, and a switch must not wait
173        // on it. One that lands first finds this workspace no longer current, and stops.
174        if let Ok(backend) = self.host.backend().await {
175            tokio::spawn(async move {
176                let started = std::time::Instant::now();
177                let result = backend.sync().await;
178                crate::instrument::reindexed(started, result.is_ok());
179                if let Err(err) = result {
180                    tracing::warn!("re-indexing the moved workspace: {err}");
181                }
182            });
183        }
184        self.describe().await.ok_or(Error::NoWorkspace)
185    }
186
187    /// Stop serving the current workspace; with `delete`, delete its folder and its cache
188    /// too. Sync stops for this host only: the workgroup and the other devices keep it.
189    pub async fn remove(&self, delete: bool) -> Result<()> {
190        let _one = self.switching.lock().await;
191        let root = self.root().ok_or(Error::NoWorkspace)?;
192        // Read before anything goes: the cache is keyed by the root's path.
193        let cache = Workspace::from_root(self.ctx, &root)
194            .ok()
195            .map(|w| w.cache_dir());
196        // Stopped first, so the watcher never reports the files going as deletions to
197        // replicate; and, before a delete, closed, so its store can go too.
198        if delete {
199            self.let_go(&root).await?;
200        } else if let Some(runtime) = &self.sync
201            && let Err(err) = runtime.disable(&root).await
202        {
203            tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
204        }
205        self.host.close();
206        self.file.clear()?;
207        self.refresh_settings();
208        if delete {
209            match std::fs::remove_dir_all(&root) {
210                Ok(()) => {}
211                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
212                Err(e) => {
213                    return Err(Error::Io(std::io::Error::new(
214                        e.kind(),
215                        format!("could not delete {}: {e}", root.display()),
216                    )));
217                }
218            }
219            if let Some(cache) = cache
220                && let Err(err) = std::fs::remove_dir_all(&cache)
221                && err.kind() != std::io::ErrorKind::NotFound
222            {
223                tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
224            }
225        }
226        Ok(())
227    }
228
229    /// Stop syncing `root` and close its replica store, before its folder moves or goes,
230    /// returning whether it was synced. A store still in use is the error, and leaves the
231    /// workspace syncing as before.
232    async fn let_go(&self, root: &Path) -> Result<bool> {
233        let Some(runtime) = &self.sync else {
234            return Ok(false);
235        };
236        if !runtime.roots().await.iter().any(|r| r == root) {
237            return Ok(false);
238        }
239        if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
240            if let Err(again) = runtime.enable(root).await {
241                tracing::warn!(root = %root.display(), "could not restart sync: {again}");
242            }
243            return Err(err);
244        }
245        Ok(true)
246    }
247
248    /// Open `root` again after [`relocate`](Self::relocate) closed it, and sync it again
249    /// when it was. Failures leave it selected, unopened, the way a restore does.
250    async fn reopen(&self, root: &Path, sync: bool) {
251        if let Err(err) = self.host.select(root, true).await {
252            tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
253        }
254        if sync
255            && let Some(runtime) = &self.sync
256            && let Err(err) = runtime.enable(root).await
257        {
258            tracing::warn!(root = %root.display(), "could not restart sync: {err}");
259        }
260        self.remember(root, sync);
261    }
262
263    /// Start syncing the current workspace, and remember that.
264    pub async fn enable_sync(&self) -> Result<GrainId> {
265        let runtime = self.runtime()?;
266        let _one = self.switching.lock().await;
267        let root = self.root().ok_or(Error::NoWorkspace)?;
268        let id = match runtime.enable(&root).await {
269            Ok(id) => id,
270            // The runtime enables it once the bridge is back, so remember it as synced: the
271            // next start tries again too (#244).
272            Err(err @ Error::BridgeDisconnected) => {
273                self.remember(&root, true);
274                return Err(err);
275            }
276            Err(err) => return Err(err),
277        };
278        self.remember(&root, true);
279        Ok(id)
280    }
281
282    /// Stop syncing the current workspace, and remember that.
283    pub async fn disable_sync(&self) -> Result<()> {
284        let runtime = self.runtime()?;
285        let _one = self.switching.lock().await;
286        let root = self.root().ok_or(Error::NoWorkspace)?;
287        runtime.disable(&root).await?;
288        self.remember(&root, false);
289        Ok(())
290    }
291
292    /// The current workspace's sync state; not synced when there is none.
293    pub async fn status(&self) -> proto::SyncStatusResult {
294        match &self.sync {
295            // An empty root names nothing, which the runtime reports as not synced, with
296            // the bridge's view all the same.
297            Some(runtime) => runtime
298                .status(&self.root().unwrap_or_default())
299                .await
300                .into(),
301            None => proto::SyncStatusResult::not_synced(),
302        }
303    }
304
305    /// The current workspace as `workspace.current` reports it.
306    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
307        let root = self.root()?;
308        let marker = root.join(format!(".{}", self.ctx.app_name));
309        // Read, never minted: describing must not create a sync id nobody asked for.
310        let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
311            .ok()
312            .and_then(|s| s.trim().parse().ok());
313        let sync = match &self.sync {
314            Some(runtime) => runtime.status(&root).await.into(),
315            None => proto::SyncStatusResult::not_synced(),
316        };
317        Some(proto::CurrentWorkspace {
318            reachable: marker.is_dir(),
319            root,
320            workspace_id,
321            sync,
322        })
323    }
324
325    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
326    /// selected, unopened, so `workspace.current` can say so.
327    ///
328    /// The open happens now, so the first client finds the workspace; sync, which talks to
329    /// the bridge and may dial peers, starts on the returned task.
330    pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
331        let selection = match self.file.load(self.ctx.app_name) {
332            Ok(Some(selection)) => selection,
333            Ok(None) => return None,
334            Err(err) => {
335                tracing::warn!("could not read the selected workspace: {err}");
336                return None;
337            }
338        };
339        {
340            let _one = self.switching.lock().await;
341            if let Err(err) = self.host.select(&selection.root, true).await {
342                tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
343                return None;
344            }
345            crate::api_keys::import_once(self.ctx, &selection.root);
346            self.refresh_settings();
347        }
348        if !selection.sync {
349            return None;
350        }
351        let runtime = self.sync.clone()?;
352        let current = Arc::clone(self);
353        Some(tokio::spawn(async move {
354            // A switch that landed first wins: sync starts only for a workspace still
355            // current.
356            let _one = current.switching.lock().await;
357            if current.root().as_deref() != Some(&selection.root) {
358                return;
359            }
360            if let Err(err) = runtime.enable(&selection.root).await {
361                tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
362            }
363        }))
364    }
365
366    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
367    ///
368    /// The open comes first: a workspace that does not open leaves the previous one current,
369    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
370    async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
371        let _one = self.switching.lock().await;
372        let previous = self.root();
373        self.host.select(root, restoring).await?;
374        crate::api_keys::import_once(self.ctx, root);
375        if let Some(runtime) = &self.sync {
376            if let Some(previous) = previous.filter(|p| p != root)
377                && let Err(err) = runtime.disable(&previous).await
378            {
379                tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
380            }
381            if sync && let Err(err) = runtime.enable(root).await {
382                // Selected all the same: the workspace works without sync, and the status
383                // carries the failure.
384                tracing::warn!(root = %root.display(), "could not start sync: {err}");
385            }
386        }
387        self.remember(root, sync);
388        Ok(())
389    }
390
391    fn remember(&self, root: &Path, sync: bool) {
392        let selection = Selection {
393            root: root.to_owned(),
394            sync,
395        };
396        if let Err(err) = self.file.save(&selection) {
397            tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
398        }
399        self.refresh_settings();
400    }
401
402    /// Read the settings again, the workspace scope now the selected workspace's file.
403    fn refresh_settings(&self) {
404        if let Some(settings) = &self.settings
405            && settings.refresh().is_err()
406        {
407            // The error may quote the file; the selection itself succeeded.
408            tracing::warn!("could not read the settings of the selected workspace");
409        }
410    }
411
412    fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
413        self.sync
414            .as_ref()
415            .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
416    }
417}
418
419/// Whether `root` has synced before: it carries a sync id.
420fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
421    root.join(format!(".{}", ctx.app_name))
422        .join(SYNC_ID_FILE)
423        .is_file()
424}
425
426/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
427fn resolve(dir: &Path) -> Result<PathBuf> {
428    std::env::current_dir()
429        .map_err(Error::Io)?
430        .join(dir)
431        .canonicalize()
432        .map_err(Error::Io)
433}
434
435/// Where a move to `dir` puts the root: `dir` made absolute, through its parent's
436/// canonical path, since `dir` itself must not exist yet.
437fn destination(dir: &Path) -> Result<PathBuf> {
438    let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
439    if dir.exists() {
440        return Err(Error::Config(format!(
441            "{} already exists; choose a new folder name",
442            dir.display()
443        )));
444    }
445    let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
446        return Err(Error::Config(format!(
447            "{} cannot be a workspace root",
448            dir.display()
449        )));
450    };
451    Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
452}
453
454/// Carry a moved workspace's cache from `from` to `to`, its new key: the replica's state,
455/// rebased onto `root`. The rest — the search index, which records absolute paths — is
456/// dropped, to be rebuilt.
457///
458/// Best-effort: a replica that does not come along is a replica that starts over, and
459/// syncing reports why.
460fn carry_cache(from: &Path, to: &Path, root: &Path) {
461    let sync_from = from.join("sync");
462    if sync_from.is_dir() {
463        let sync_to = to.join("sync");
464        let moved =
465            std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
466        match moved {
467            Ok(()) => {
468                let store = sync_to.join("sync.redb");
469                if store.is_file()
470                    && let Err(err) =
471                        sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
472                {
473                    tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
474                }
475            }
476            Err(err) => {
477                tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
478            }
479        }
480    }
481    if let Err(err) = std::fs::remove_dir_all(from)
482        && err.kind() != std::io::ErrorKind::NotFound
483    {
484        tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
485    }
486}
487
488/// Add `workspace.init`, `workspace.select`, `workspace.current`, `workspace.move` and
489/// `workspace.remove` to `router`.
490pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
491    let init = Arc::clone(&current);
492    let select = Arc::clone(&current);
493    let relocate = Arc::clone(&current);
494    let remove = Arc::clone(&current);
495    router
496        .method(proto::WORKSPACE_MOVE, move |req| {
497            let current = Arc::clone(&relocate);
498            async move {
499                let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
500                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
501                let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
502                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
503            }
504        })
505        .method(proto::WORKSPACE_REMOVE, move |req| {
506            let current = Arc::clone(&remove);
507            async move {
508                let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
509                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
510                current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
511                serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
512            }
513        })
514        .method(proto::WORKSPACE_INIT, move |req| {
515            let current = Arc::clone(&init);
516            async move {
517                let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
518                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
519                let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
520                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
521            }
522        })
523        .method(proto::WORKSPACE_SELECT, move |req| {
524            let current = Arc::clone(&select);
525            async move {
526                let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
527                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
528                let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
529                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
530            }
531        })
532        .method(proto::WORKSPACE_CURRENT, move |_| {
533            let current = Arc::clone(&current);
534            async move {
535                let workspace = current.describe().await;
536                serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
537                    .map_err(|e| RpcError::internal(e.to_string()))
538            }
539        })
540}
541
542/// Create the workspace home at `dir`: the marker directory, idempotently. The sync id is
543/// `sync.enable` / `sync.map`'s to mint, not this one's.
544///
545/// A relative `dir` is resolved against the server's cwd. `created` is `false` when the
546/// marker was already there.
547///
548/// No `[workspace]` registry is written into the marker's `config.toml` any more (#217):
549/// it keyed the apps' `--workspace` selectors, which went with the server serving one
550/// workspace, and a `config.toml` holding only it lost the application's settings on the
551/// first sync (#253).
552fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
553    // A new workspace's folder need not exist yet: the default one
554    // (`<data dir>/workspaces/default`) does not on a fresh install.
555    let absolute = std::env::current_dir().map_err(Error::Io)?.join(dir);
556    std::fs::create_dir_all(&absolute).map_err(Error::Io)?;
557    let root = resolve(&absolute)?;
558    let marker = root.join(format!(".{}", ctx.app_name));
559    let created = !marker.is_dir();
560    if created {
561        std::fs::create_dir(&marker).map_err(Error::Io)?;
562    }
563
564    Ok(proto::WorkspaceInitResult {
565        workspace_id: slug(&root),
566        root,
567        created,
568    })
569}
570
571/// Delete the marker's `config.toml` when it holds the `[workspace]` registry an older
572/// `workspace.init` wrote, and nothing else.
573fn drop_bare_registry(path: &Path) -> Result<()> {
574    let config = read_config(path)?;
575    if config.len() == 1 && config.contains_key("workspace") {
576        std::fs::remove_file(path).map_err(Error::Io)?;
577    }
578    Ok(())
579}
580
581/// The marker's `config.toml` as a table; an empty one when there is no file.
582fn read_config(path: &Path) -> Result<toml::Table> {
583    match std::fs::read_to_string(path) {
584        Ok(text) => text.parse().map_err(|e: toml::de::Error| {
585            Error::Config(format!(
586                "{}: {}",
587                path.display(),
588                sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message())
589            ))
590        }),
591        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
592        Err(e) => Err(Error::Io(e)),
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    const REGISTRY_ONLY: &str = "[workspace.ledger]\npath = \"/home/me/ledger\"\n";
601
602    #[test]
603    fn only_a_registry_only_config_is_dropped() {
604        let dir = tempfile::tempdir().unwrap();
605        let path = dir.path().join("config.toml");
606
607        std::fs::write(&path, REGISTRY_ONLY).unwrap();
608        drop_bare_registry(&path).unwrap();
609        assert!(!path.exists());
610        // Nothing there is nothing to drop.
611        drop_bare_registry(&path).unwrap();
612
613        std::fs::write(&path, format!("schema_version = 2\n\n{REGISTRY_ONLY}")).unwrap();
614        drop_bare_registry(&path).unwrap();
615        assert!(path.exists());
616    }
617
618    /// An application with one `Live` key in the workspace: `<app>.note`.
619    struct NoteApp(&'static str);
620
621    impl crate::settings::AppSettings for NoteApp {
622        fn defs(&self) -> Vec<sapphire_framework_settings::SettingDef> {
623            vec![sapphire_framework_settings::SettingDef {
624                key: format!("{}.note", self.0),
625                kind: sapphire_framework_settings::Kind::String { non_empty: false },
626                scopes: vec![sapphire_framework_settings::Scope::Workspace],
627                overridable: false,
628                apply: sapphire_framework_settings::Apply::Live,
629                default: None,
630                section: "Test".into(),
631                doc: "test".into(),
632                process: sapphire_framework_settings::Process::App,
633            }]
634        }
635    }
636
637    #[tokio::test(flavor = "multi_thread")]
638    async fn workspace_settings_follow_the_selection() {
639        const APP: &str = "sapphire-curtest";
640        let dir = tempfile::tempdir().unwrap();
641        let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new(APP)));
642        ctx.set_config_dir(dir.path().join("config"));
643        ctx.set_cache_dir(dir.path().join("cache"));
644        ctx.set_data_dir(dir.path().join("data"));
645        let file = SelectionFile::at(dir.path().join("config").join("workspace.toml"));
646        let (a, b) = (dir.path().join("a"), dir.path().join("b"));
647        for (root, value) in [(&a, "from a"), (&b, "from b")] {
648            std::fs::create_dir_all(root).unwrap();
649            init_workspace(ctx, root).unwrap();
650            std::fs::write(
651                root.join(format!(".{APP}")).join("config.toml"),
652                format!("[{APP}]\nnote = \"{value}\"\n"),
653            )
654            .unwrap();
655        }
656        let settings = crate::settings::Settings::load_with(
657            ctx,
658            std::sync::Arc::new(NoteApp(APP)),
659            file.clone(),
660        )
661        .unwrap();
662        let key = format!("{APP}.note");
663        let current = Current::new(ctx, Arc::new(WorkspaceHost::new(ctx)), None, file)
664            .with_settings(settings.clone());
665        let mut changed = settings.changed();
666
667        current.select(&a).await.unwrap();
668        assert!(changed.has_changed().unwrap());
669        changed.mark_unchanged();
670        assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from a"));
671
672        current.select(&b).await.unwrap();
673        assert!(changed.has_changed().unwrap());
674        changed.mark_unchanged();
675        assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from b"));
676
677        // No workspace, no workspace value.
678        current.remove(false).await.unwrap();
679        assert!(changed.has_changed().unwrap());
680        assert_eq!(settings.get(&key), None);
681    }
682
683    #[test]
684    fn an_unparsable_marker_config_is_never_quoted() {
685        let dir = tempfile::tempdir().unwrap();
686        let path = dir.path().join("config.toml");
687        std::fs::write(&path, "[app]\ntoken = \"hunter2\" x\n").unwrap();
688        let err = read_config(&path).unwrap_err().to_string();
689        assert!(err.contains(&path.display().to_string()), "{err}");
690        assert!(err.contains("line 2"), "{err}");
691        assert!(!err.contains("hunter2"), "{err}");
692    }
693
694    #[test]
695    fn init_writes_no_config() {
696        let dir = tempfile::tempdir().unwrap();
697        let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp")));
698        let result = init_workspace(ctx, dir.path()).unwrap();
699        assert!(result.created);
700        let workspace = Workspace::from_root(ctx, dir.path()).unwrap();
701        assert!(workspace.marker_dir().is_dir());
702        assert!(!workspace.config_path().exists());
703    }
704
705    #[test]
706    fn init_makes_a_missing_folder() {
707        let tmp = tempfile::tempdir().unwrap();
708        let dir = tmp.path().join("workspaces").join("default");
709        let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp2")));
710        let result = init_workspace(ctx, &dir).unwrap();
711        assert!(result.created);
712        assert_eq!(result.root, dir.canonicalize().unwrap());
713        assert!(dir.join(".sapphire-initapp2").is_dir());
714    }
715}