Skip to main content

sapphire_framework_server/sync/
methods.rs

1//! The `sync.*` methods. Each acts on the server's current workspace (#215).
2
3use std::sync::Arc;
4
5use sapphire_backend::protocol as proto;
6use sapphire_backend::protocol::{SYNC_MAP, SyncMapParams};
7use sapphire_ipc::{Router, RpcError};
8
9use crate::current::Current;
10use crate::handlers::rpc_error;
11
12/// Add `sync.enable`, `sync.disable`, `sync.map` and `sync.status` to `router`.
13///
14/// `current` must have a sync runtime: a server without one does not serve `sync.*`.
15pub fn sync_router(current: Arc<Current>, router: Router) -> Router {
16    let enable = Arc::clone(&current);
17    let map = Arc::clone(&current);
18    let disable = Arc::clone(&current);
19    let status = current;
20
21    router
22        .method(proto::SYNC_ENABLE, move |_| {
23            let current = Arc::clone(&enable);
24            async move {
25                let workspace_id = current.enable_sync().await.map_err(|e| rpc_error(&e))?;
26                serde_json::to_value(proto::SyncEnableResult { workspace_id })
27                    .map_err(|e| RpcError::internal(e.to_string()))
28            }
29        })
30        .method(SYNC_MAP, move |ctx| {
31            let current = Arc::clone(&map);
32            async move {
33                let p: SyncMapParams = serde_json::from_value(ctx.params)
34                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
35                let workspace_id = current
36                    .map(&p.workspace, &p.dir)
37                    .await
38                    .map_err(|e| rpc_error(&e))?;
39                serde_json::to_value(proto::SyncEnableResult { workspace_id })
40                    .map_err(|e| RpcError::internal(e.to_string()))
41            }
42        })
43        .method(proto::SYNC_DISABLE, move |_| {
44            let current = Arc::clone(&disable);
45            async move {
46                current.disable_sync().await.map_err(|e| rpc_error(&e))?;
47                serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
48            }
49        })
50        .method(proto::SYNC_STATUS, move |_| {
51            let current = Arc::clone(&status);
52            async move {
53                // Never fails on account of the bridge: a status call that errored when the
54                // bridge was down would read as an outage of the app server itself.
55                serde_json::to_value(current.status().await)
56                    .map_err(|e| RpcError::internal(e.to_string()))
57            }
58        })
59}
60
61impl From<crate::sync::SyncStatus> for proto::SyncStatusResult {
62    fn from(status: crate::sync::SyncStatus) -> Self {
63        proto::SyncStatusResult {
64            enabled: status.enabled,
65            workspace_id: status.workspace_id,
66            peers: status.peers,
67            paused: status.paused,
68            last_error: status.last_error,
69            bridge_available: status.bridge_available,
70            topology: status.topology,
71            embedding: status.embedding,
72            pending_delivery: status.pending_delivery,
73            acknowledging_peers: status.acknowledging_peers,
74        }
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use crate::sync::SyncRuntime;
82    use crate::sync::testing::StubBridge;
83    use crate::test_support;
84    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
85    use sapphire_workspace::{AppContext, AppKind};
86    use std::ffi::OsString;
87    use std::path::PathBuf;
88
89    static CTX: AppContext = AppContext::new("sapphire-syncmethods");
90
91    /// The env vars `CTX.init` reads.
92    const DIR_VARS: [&str; 3] = [
93        "SAPPHIRE_SYNCMETHODS_CACHE_DIR",
94        "SAPPHIRE_SYNCMETHODS_DATA_DIR",
95        "SAPPHIRE_SYNCMETHODS_CONFIG_DIR",
96    ];
97
98    /// Points the context's directories at the test's scratch tree, and restores the
99    /// previous values when dropped — including while unwinding from a panic.
100    struct EnvGuard {
101        previous: [Option<OsString>; 3],
102        _lock: std::sync::MutexGuard<'static, ()>,
103    }
104
105    impl Drop for EnvGuard {
106        fn drop(&mut self) {
107            // SAFETY: `self._lock` still serialises the environment; it is dropped only
108            // after this method returns.
109            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
110                match previous.take() {
111                    Some(value) => unsafe { std::env::set_var(name, value) },
112                    None => test_support::remove(name),
113                }
114            }
115        }
116    }
117
118    /// A server exposing only the sync namespace, plus a workspace root.
119    ///
120    /// The environment lock is held for the whole test, as in the crate's other test
121    /// modules: the context is a `static` shared by this binary, and every env mutation in
122    /// these tests goes through `test_support` for that reason.
123    struct Fixture {
124        _tmp: tempfile::TempDir,
125        _env: EnvGuard,
126        root: PathBuf,
127        client: Client,
128        _stub: StubBridge,
129    }
130
131    /// [`bare`], with its workspace selected.
132    async fn fixture() -> Fixture {
133        let f = bare().await;
134        let _: proto::CurrentWorkspace = f
135            .client
136            .call(
137                proto::WORKSPACE_SELECT,
138                proto::WorkspaceSelectParams {
139                    dir: f.root.clone(),
140                },
141            )
142            .await
143            .unwrap();
144        f
145    }
146
147    async fn bare() -> Fixture {
148        let lock = test_support::lock();
149        let tmp = tempfile::tempdir().unwrap();
150        let previous = DIR_VARS.map(std::env::var_os);
151        // SAFETY (via `test_support::set`): `lock` serialises every read and write of the
152        // process environment in this test binary, and it is held until `drop` has restored
153        // the old values.
154        for (name, dir) in DIR_VARS
155            .iter()
156            .zip(["cache", "data", "config"].map(|cat| tmp.path().join(cat)))
157        {
158            test_support::set(name, &dir);
159        }
160        let env = EnvGuard {
161            previous,
162            _lock: lock,
163        };
164        CTX.init(AppKind::Server);
165
166        let root = tmp.path().join("ws");
167        std::fs::create_dir_all(root.join(".sapphire-syncmethods")).unwrap();
168        let root = root.canonicalize().unwrap();
169
170        let (stub, bridge) = StubBridge::start().await;
171        let runtime = Arc::new(SyncRuntime::new(
172            &CTX,
173            bridge,
174            "/bin/true".into(),
175            ManagedBy::Service,
176        ));
177        let current = Arc::new(crate::current::Current::new(
178            &CTX,
179            Arc::new(crate::host::WorkspaceHost::new(&CTX)),
180            Some(runtime),
181            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
182        ));
183        let router = Arc::new(sync_router(
184            Arc::clone(&current),
185            crate::current::current_methods(current, sapphire_ipc::Router::new()),
186        ));
187
188        let (client_conn, server_conn) = Connection::pair();
189        tokio::spawn(async move {
190            let info = ServerInfo {
191                version: "0.0.0".into(),
192                api: sapphire_backend::protocol::API_VERSION,
193                app_api: None,
194                pid: std::process::id(),
195                managed_by: ManagedBy::Service,
196            };
197            let _ = serve(server_conn, router, "sapphire-syncmethods", info).await;
198        });
199        let info = ClientInfo {
200            kind: "cli".into(),
201            version: "0.0.0".into(),
202            api: sapphire_backend::protocol::API_VERSION,
203            app_api: None,
204            pid: std::process::id(),
205        };
206        let (client, _) = Client::handshake(client_conn, "sapphire-syncmethods", info)
207            .await
208            .unwrap();
209        Fixture {
210            _tmp: tmp,
211            _env: env,
212            root,
213            client,
214            _stub: stub,
215        }
216    }
217
218    #[tokio::test(flavor = "multi_thread")]
219    async fn enabling_returns_the_workspace_id() {
220        let f = fixture().await;
221        let result: proto::SyncEnableResult = f
222            .client
223            .call(proto::SYNC_ENABLE, serde_json::json!({}))
224            .await
225            .unwrap();
226        assert!(!result.workspace_id.to_string().is_empty());
227    }
228
229    #[tokio::test(flavor = "multi_thread")]
230    async fn status_before_enabling_reports_disabled() {
231        let f = fixture().await;
232        let status: proto::SyncStatusResult = f
233            .client
234            .call(proto::SYNC_STATUS, serde_json::json!({}))
235            .await
236            .unwrap();
237        assert!(!status.enabled);
238        assert!(status.workspace_id.is_none());
239    }
240
241    #[tokio::test(flavor = "multi_thread")]
242    async fn status_after_enabling_reports_the_same_id() {
243        let f = fixture().await;
244        let enabled: proto::SyncEnableResult = f
245            .client
246            .call(proto::SYNC_ENABLE, serde_json::json!({}))
247            .await
248            .unwrap();
249        let status: proto::SyncStatusResult = f
250            .client
251            .call(proto::SYNC_STATUS, serde_json::json!({}))
252            .await
253            .unwrap();
254
255        assert!(status.enabled);
256        assert_eq!(status.workspace_id, Some(enabled.workspace_id));
257    }
258
259    #[tokio::test(flavor = "multi_thread")]
260    async fn disabling_an_unsynced_workspace_is_not_an_error() {
261        let f = fixture().await;
262        let _: proto::Ack = f
263            .client
264            .call(proto::SYNC_DISABLE, serde_json::json!({}))
265            .await
266            .expect("disabling what was never enabled is fine");
267    }
268
269    #[tokio::test(flavor = "multi_thread")]
270    async fn without_a_workspace_sync_is_an_invalid_parameter() {
271        let f = bare().await;
272        let err = f
273            .client
274            .call::<_, proto::SyncEnableResult>(proto::SYNC_ENABLE, serde_json::json!({}))
275            .await
276            .unwrap_err();
277        match err {
278            sapphire_ipc::Error::Rpc(e) => {
279                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
280                assert!(e.message.contains("workspace select"), "{}", e.message);
281            }
282            other => panic!("got {other:?}"),
283        }
284    }
285
286    #[tokio::test(flavor = "multi_thread")]
287    async fn enabling_is_remembered_and_selecting_again_resumes_it() {
288        let f = fixture().await;
289        let _: proto::SyncEnableResult = f
290            .client
291            .call(proto::SYNC_ENABLE, serde_json::json!({}))
292            .await
293            .unwrap();
294        let saved = std::fs::read_to_string(f._tmp.path().join("workspace.toml")).unwrap();
295        assert!(saved.contains("sync = true"), "{saved}");
296        // The workspace now has a sync id, so selecting it turns sync on by itself.
297        let _: proto::Ack = f
298            .client
299            .call(proto::SYNC_DISABLE, serde_json::json!({}))
300            .await
301            .unwrap();
302        let again: proto::CurrentWorkspace = f
303            .client
304            .call(
305                proto::WORKSPACE_SELECT,
306                proto::WorkspaceSelectParams {
307                    dir: f.root.clone(),
308                },
309            )
310            .await
311            .unwrap();
312        assert!(again.sync.enabled);
313    }
314}
315
316#[cfg(test)]
317mod map_tests {
318    use super::*;
319    use crate::sync::SyncRuntime;
320    use crate::sync::testing::StubBridge;
321    use crate::test_support;
322    use sapphire_bridge_api::WorkgroupWorkspaceInfo;
323    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
324    use sapphire_workspace::{AppContext, AppKind};
325    use std::ffi::OsString;
326    use std::path::PathBuf;
327
328    static CTX: AppContext = AppContext::new("sapphire-syncmap");
329
330    /// The env vars `CTX.init` reads.
331    const DIR_VARS: [&str; 3] = [
332        "SAPPHIRE_SYNCMAP_CACHE_DIR",
333        "SAPPHIRE_SYNCMAP_DATA_DIR",
334        "SAPPHIRE_SYNCMAP_CONFIG_DIR",
335    ];
336
337    /// Points the context's directories at the test's scratch tree, and restores the
338    /// previous values when dropped — including while unwinding from a panic.
339    struct EnvGuard {
340        previous: [Option<OsString>; 3],
341        _lock: std::sync::MutexGuard<'static, ()>,
342    }
343
344    impl Drop for EnvGuard {
345        fn drop(&mut self) {
346            // SAFETY: `self._lock` still serialises the environment; it is dropped only
347            // after this method returns.
348            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
349                match previous.take() {
350                    Some(value) => unsafe { std::env::set_var(name, value) },
351                    None => test_support::remove(name),
352                }
353            }
354        }
355    }
356
357    /// A server exposing only the sync namespace, plus a workspace root.
358    struct Fixture {
359        _tmp: tempfile::TempDir,
360        _env: EnvGuard,
361        root: PathBuf,
362        client: Client,
363        stub: StubBridge,
364    }
365
366    async fn fixture() -> Fixture {
367        let lock = test_support::lock();
368        let tmp = tempfile::tempdir().unwrap();
369        let previous = DIR_VARS.map(std::env::var_os);
370        // SAFETY (via `test_support::set`): `lock` serialises every read and write of the
371        // process environment in this test binary, and it is held until `drop` has restored
372        // the old values.
373        for (name, dir) in DIR_VARS
374            .iter()
375            .zip(["cache", "data", "config"].map(|cat| tmp.path().join(cat)))
376        {
377            test_support::set(name, &dir);
378        }
379        let env = EnvGuard {
380            previous,
381            _lock: lock,
382        };
383        CTX.init(AppKind::Server);
384
385        let root = tmp.path().join("ws");
386        std::fs::create_dir_all(root.join(".sapphire-syncmap")).unwrap();
387        let root = root.canonicalize().unwrap();
388
389        let (stub, bridge) = StubBridge::start().await;
390        let runtime = Arc::new(SyncRuntime::new(
391            &CTX,
392            bridge,
393            "/bin/true".into(),
394            ManagedBy::Service,
395        ));
396        let current = Arc::new(crate::current::Current::new(
397            &CTX,
398            Arc::new(crate::host::WorkspaceHost::new(&CTX)),
399            Some(runtime),
400            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
401        ));
402        let router = Arc::new(sync_router(
403            Arc::clone(&current),
404            crate::current::current_methods(current, sapphire_ipc::Router::new()),
405        ));
406
407        let (client_conn, server_conn) = Connection::pair();
408        tokio::spawn(async move {
409            let info = ServerInfo {
410                version: "0.0.0".into(),
411                api: sapphire_backend::protocol::API_VERSION,
412                app_api: None,
413                pid: std::process::id(),
414                managed_by: ManagedBy::Service,
415            };
416            let _ = serve(server_conn, router, "sapphire-syncmap", info).await;
417        });
418        let info = ClientInfo {
419            kind: "cli".into(),
420            version: "0.0.0".into(),
421            api: sapphire_backend::protocol::API_VERSION,
422            app_api: None,
423            pid: std::process::id(),
424        };
425        let (client, _) = Client::handshake(client_conn, "sapphire-syncmap", info)
426            .await
427            .unwrap();
428        Fixture {
429            _tmp: tmp,
430            _env: env,
431            root,
432            client,
433            stub,
434        }
435    }
436
437    #[tokio::test(flavor = "multi_thread")]
438    async fn mapping_by_name_writes_the_map_and_enables_sync() {
439        let f = fixture().await;
440        let id = grain_id::GrainId::random();
441        f.stub.list(WorkgroupWorkspaceInfo {
442            workspace_id: id,
443            app_name: "sapphire-syncmap".into(),
444            name: "notes".into(),
445        });
446
447        let result: proto::SyncEnableResult = f
448            .client
449            .call(
450                proto::SYNC_MAP,
451                proto::SyncMapParams {
452                    workspace: "notes".into(),
453                    dir: f.root.clone(),
454                },
455            )
456            .await
457            .unwrap();
458
459        assert_eq!(result.workspace_id, id, "the mapped workspace's id is used");
460        let map = f
461            .root
462            .join(".sapphire-syncmap")
463            .join(crate::sync::WORKSPACE_MAP_FILE);
464        assert_eq!(
465            std::fs::read_to_string(&map).unwrap().trim(),
466            id.to_string(),
467            "the map names the workspace"
468        );
469
470        let status: proto::SyncStatusResult = f
471            .client
472            .call(proto::SYNC_STATUS, serde_json::json!({}))
473            .await
474            .unwrap();
475        assert!(status.enabled, "mapping enabled sync");
476        assert_eq!(status.workspace_id, Some(id));
477    }
478
479    #[tokio::test(flavor = "multi_thread")]
480    async fn mapping_makes_the_marker_and_writes_no_config() {
481        let f = fixture().await;
482        let id = grain_id::GrainId::random();
483        f.stub.list(WorkgroupWorkspaceInfo {
484            workspace_id: id,
485            app_name: "sapphire-syncmap".into(),
486            name: "notes".into(),
487        });
488        let dir = f.root.parent().unwrap().join("fresh");
489        std::fs::create_dir(&dir).unwrap();
490
491        let result: proto::SyncEnableResult = f
492            .client
493            .call(
494                proto::SYNC_MAP,
495                proto::SyncMapParams {
496                    workspace: "notes".into(),
497                    dir: dir.clone(),
498                },
499            )
500            .await
501            .unwrap();
502        assert_eq!(result.workspace_id, id);
503        let marker = dir.join(".sapphire-syncmap");
504        assert!(marker.is_dir(), "mapping made the marker");
505        assert!(
506            !marker.join("config.toml").exists(),
507            "the workspace's config arrives with the sync (#253)"
508        );
509    }
510
511    #[tokio::test(flavor = "multi_thread")]
512    async fn mapping_drops_a_registry_only_config_and_keeps_an_apps() {
513        let f = fixture().await;
514        let id = grain_id::GrainId::random();
515        f.stub.list(WorkgroupWorkspaceInfo {
516            workspace_id: id,
517            app_name: "sapphire-syncmap".into(),
518            name: "notes".into(),
519        });
520        let bare = f.root.parent().unwrap().join("bare");
521        let app = f.root.parent().unwrap().join("app");
522        for (dir, config) in [
523            (&bare, "[workspace.bare]\npath = \"/x\"\n"),
524            (
525                &app,
526                "schema_version = 2\n\n[workspace.app]\npath = \"/x\"\n",
527            ),
528        ] {
529            std::fs::create_dir_all(dir.join(".sapphire-syncmap")).unwrap();
530            std::fs::write(dir.join(".sapphire-syncmap").join("config.toml"), config).unwrap();
531        }
532
533        for dir in [&bare, &app] {
534            let _: proto::SyncEnableResult = f
535                .client
536                .call(
537                    proto::SYNC_MAP,
538                    proto::SyncMapParams {
539                        workspace: "notes".into(),
540                        dir: dir.clone(),
541                    },
542                )
543                .await
544                .unwrap();
545        }
546        assert!(
547            !bare.join(".sapphire-syncmap").join("config.toml").exists(),
548            "a config holding only the registry would win over the workspace's (#253)"
549        );
550        assert!(
551            app.join(".sapphire-syncmap").join("config.toml").exists(),
552            "an application's settings stay"
553        );
554    }
555
556    #[tokio::test(flavor = "multi_thread")]
557    async fn mapping_by_id_works_too() {
558        let f = fixture().await;
559        let id = grain_id::GrainId::random();
560        f.stub.list(WorkgroupWorkspaceInfo {
561            workspace_id: id,
562            app_name: "sapphire-syncmap".into(),
563            name: "notes".into(),
564        });
565
566        let result: proto::SyncEnableResult = f
567            .client
568            .call(
569                proto::SYNC_MAP,
570                proto::SyncMapParams {
571                    workspace: id.to_string(),
572                    dir: f.root.clone(),
573                },
574            )
575            .await
576            .unwrap();
577        assert_eq!(result.workspace_id, id);
578    }
579
580    #[tokio::test(flavor = "multi_thread")]
581    async fn an_unknown_workspace_is_an_invalid_parameter() {
582        let f = fixture().await;
583        let err = f
584            .client
585            .call::<_, proto::SyncEnableResult>(
586                proto::SYNC_MAP,
587                proto::SyncMapParams {
588                    workspace: "nowhere".into(),
589                    dir: f.root.clone(),
590                },
591            )
592            .await
593            .unwrap_err();
594        match err {
595            sapphire_ipc::Error::Rpc(e) => {
596                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
597            }
598            other => panic!("got {other:?}"),
599        }
600    }
601
602    #[tokio::test(flavor = "multi_thread")]
603    async fn another_applications_workspace_is_refused() {
604        let f = fixture().await;
605        let id = grain_id::GrainId::random();
606        f.stub.list(WorkgroupWorkspaceInfo {
607            workspace_id: id,
608            app_name: "sapphire-journal".into(),
609            name: "notes".into(),
610        });
611
612        let err = f
613            .client
614            .call::<_, proto::SyncEnableResult>(
615                proto::SYNC_MAP,
616                proto::SyncMapParams {
617                    workspace: "notes".into(),
618                    dir: f.root.clone(),
619                },
620            )
621            .await
622            .unwrap_err();
623        match err {
624            sapphire_ipc::Error::Rpc(e) => {
625                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
626                assert!(
627                    e.message.contains("sapphire-journal"),
628                    "it names the owning application: {}",
629                    e.message
630                );
631            }
632            other => panic!("got {other:?}"),
633        }
634    }
635
636    #[tokio::test(flavor = "multi_thread")]
637    async fn a_directory_that_does_not_exist_is_refused() {
638        let f = fixture().await;
639        let plain = f._tmp.path().join("plain");
640        let id = grain_id::GrainId::random();
641        f.stub.list(WorkgroupWorkspaceInfo {
642            workspace_id: id,
643            app_name: "sapphire-syncmap".into(),
644            name: "notes".into(),
645        });
646
647        let err = f
648            .client
649            .call::<_, proto::SyncEnableResult>(
650                proto::SYNC_MAP,
651                proto::SyncMapParams {
652                    workspace: "notes".into(),
653                    dir: plain.clone(),
654                },
655            )
656            .await;
657        assert!(err.is_err(), "mapping needs the directory");
658        assert!(!plain.exists(), "and does not make it");
659    }
660}