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        }
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::sync::SyncRuntime;
80    use crate::sync::testing::StubBridge;
81    use crate::test_support;
82    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
83    use sapphire_workspace::{AppContext, AppKind};
84    use std::ffi::OsString;
85    use std::path::PathBuf;
86
87    static CTX: AppContext = AppContext::new("sapphire-syncmethods");
88
89    /// The env vars `CTX.init` reads.
90    const DIR_VARS: [&str; 3] = [
91        "SAPPHIRE_SYNCMETHODS_CACHE_DIR",
92        "SAPPHIRE_SYNCMETHODS_DATA_DIR",
93        "SAPPHIRE_SYNCMETHODS_CONFIG_DIR",
94    ];
95
96    /// Points the context's directories at the test's scratch tree, and restores the
97    /// previous values when dropped — including while unwinding from a panic.
98    struct EnvGuard {
99        previous: [Option<OsString>; 3],
100        _lock: std::sync::MutexGuard<'static, ()>,
101    }
102
103    impl Drop for EnvGuard {
104        fn drop(&mut self) {
105            // SAFETY: `self._lock` still serialises the environment; it is dropped only
106            // after this method returns.
107            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
108                match previous.take() {
109                    Some(value) => unsafe { std::env::set_var(name, value) },
110                    None => test_support::remove(name),
111                }
112            }
113        }
114    }
115
116    /// A server exposing only the sync namespace, plus a workspace root.
117    ///
118    /// The environment lock is held for the whole test, as in the crate's other test
119    /// modules: the context is a `static` shared by this binary, and every env mutation in
120    /// these tests goes through `test_support` for that reason.
121    struct Fixture {
122        _tmp: tempfile::TempDir,
123        _env: EnvGuard,
124        root: PathBuf,
125        client: Client,
126        _stub: StubBridge,
127    }
128
129    /// [`bare`], with its workspace selected.
130    async fn fixture() -> Fixture {
131        let f = bare().await;
132        let _: proto::CurrentWorkspace = f
133            .client
134            .call(
135                proto::WORKSPACE_SELECT,
136                proto::WorkspaceSelectParams {
137                    dir: f.root.clone(),
138                },
139            )
140            .await
141            .unwrap();
142        f
143    }
144
145    async fn bare() -> Fixture {
146        let lock = test_support::lock();
147        let tmp = tempfile::tempdir().unwrap();
148        let previous = DIR_VARS.map(std::env::var_os);
149        // SAFETY (via `test_support::set`): `lock` serialises every read and write of the
150        // process environment in this test binary, and it is held until `drop` has restored
151        // the old values.
152        for (name, dir) in DIR_VARS
153            .iter()
154            .zip(["cache", "data", "config"].map(|cat| tmp.path().join(cat)))
155        {
156            test_support::set(name, &dir);
157        }
158        let env = EnvGuard {
159            previous,
160            _lock: lock,
161        };
162        CTX.init(AppKind::Server);
163
164        let root = tmp.path().join("ws");
165        std::fs::create_dir_all(root.join(".sapphire-syncmethods")).unwrap();
166        let root = root.canonicalize().unwrap();
167
168        let (stub, bridge) = StubBridge::start().await;
169        let runtime = Arc::new(SyncRuntime::new(
170            &CTX,
171            bridge,
172            "/bin/true".into(),
173            ManagedBy::Service,
174        ));
175        let current = Arc::new(crate::current::Current::new(
176            &CTX,
177            Arc::new(crate::host::WorkspaceHost::new(&CTX)),
178            Some(runtime),
179            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
180        ));
181        let router = Arc::new(sync_router(
182            Arc::clone(&current),
183            crate::current::current_methods(current, sapphire_ipc::Router::new()),
184        ));
185
186        let (client_conn, server_conn) = Connection::pair();
187        tokio::spawn(async move {
188            let info = ServerInfo {
189                version: "0.0.0".into(),
190                api: sapphire_backend::protocol::API_VERSION,
191                app_api: None,
192                pid: std::process::id(),
193                managed_by: ManagedBy::Service,
194            };
195            let _ = serve(server_conn, router, "sapphire-syncmethods", info).await;
196        });
197        let info = ClientInfo {
198            kind: "cli".into(),
199            version: "0.0.0".into(),
200            api: sapphire_backend::protocol::API_VERSION,
201            app_api: None,
202            pid: std::process::id(),
203        };
204        let (client, _) = Client::handshake(client_conn, "sapphire-syncmethods", info)
205            .await
206            .unwrap();
207        Fixture {
208            _tmp: tmp,
209            _env: env,
210            root,
211            client,
212            _stub: stub,
213        }
214    }
215
216    #[tokio::test(flavor = "multi_thread")]
217    async fn enabling_returns_the_workspace_id() {
218        let f = fixture().await;
219        let result: proto::SyncEnableResult = f
220            .client
221            .call(proto::SYNC_ENABLE, serde_json::json!({}))
222            .await
223            .unwrap();
224        assert!(!result.workspace_id.to_string().is_empty());
225    }
226
227    #[tokio::test(flavor = "multi_thread")]
228    async fn status_before_enabling_reports_disabled() {
229        let f = fixture().await;
230        let status: proto::SyncStatusResult = f
231            .client
232            .call(proto::SYNC_STATUS, serde_json::json!({}))
233            .await
234            .unwrap();
235        assert!(!status.enabled);
236        assert!(status.workspace_id.is_none());
237    }
238
239    #[tokio::test(flavor = "multi_thread")]
240    async fn status_after_enabling_reports_the_same_id() {
241        let f = fixture().await;
242        let enabled: proto::SyncEnableResult = f
243            .client
244            .call(proto::SYNC_ENABLE, serde_json::json!({}))
245            .await
246            .unwrap();
247        let status: proto::SyncStatusResult = f
248            .client
249            .call(proto::SYNC_STATUS, serde_json::json!({}))
250            .await
251            .unwrap();
252
253        assert!(status.enabled);
254        assert_eq!(status.workspace_id, Some(enabled.workspace_id));
255    }
256
257    #[tokio::test(flavor = "multi_thread")]
258    async fn disabling_an_unsynced_workspace_is_not_an_error() {
259        let f = fixture().await;
260        let _: proto::Ack = f
261            .client
262            .call(proto::SYNC_DISABLE, serde_json::json!({}))
263            .await
264            .expect("disabling what was never enabled is fine");
265    }
266
267    #[tokio::test(flavor = "multi_thread")]
268    async fn without_a_workspace_sync_is_an_invalid_parameter() {
269        let f = bare().await;
270        let err = f
271            .client
272            .call::<_, proto::SyncEnableResult>(proto::SYNC_ENABLE, serde_json::json!({}))
273            .await
274            .unwrap_err();
275        match err {
276            sapphire_ipc::Error::Rpc(e) => {
277                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
278                assert!(e.message.contains("workspace select"), "{}", e.message);
279            }
280            other => panic!("got {other:?}"),
281        }
282    }
283
284    #[tokio::test(flavor = "multi_thread")]
285    async fn enabling_is_remembered_and_selecting_again_resumes_it() {
286        let f = fixture().await;
287        let _: proto::SyncEnableResult = f
288            .client
289            .call(proto::SYNC_ENABLE, serde_json::json!({}))
290            .await
291            .unwrap();
292        let saved = std::fs::read_to_string(f._tmp.path().join("workspace.toml")).unwrap();
293        assert!(saved.contains("sync = true"), "{saved}");
294        // The workspace now has a sync id, so selecting it turns sync on by itself.
295        let _: proto::Ack = f
296            .client
297            .call(proto::SYNC_DISABLE, serde_json::json!({}))
298            .await
299            .unwrap();
300        let again: proto::CurrentWorkspace = f
301            .client
302            .call(
303                proto::WORKSPACE_SELECT,
304                proto::WorkspaceSelectParams {
305                    dir: f.root.clone(),
306                },
307            )
308            .await
309            .unwrap();
310        assert!(again.sync.enabled);
311    }
312}
313
314#[cfg(test)]
315mod map_tests {
316    use super::*;
317    use crate::sync::SyncRuntime;
318    use crate::sync::testing::StubBridge;
319    use crate::test_support;
320    use sapphire_bridge_api::WorkgroupWorkspaceInfo;
321    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
322    use sapphire_workspace::{AppContext, AppKind};
323    use std::ffi::OsString;
324    use std::path::PathBuf;
325
326    static CTX: AppContext = AppContext::new("sapphire-syncmap");
327
328    /// The env vars `CTX.init` reads.
329    const DIR_VARS: [&str; 3] = [
330        "SAPPHIRE_SYNCMAP_CACHE_DIR",
331        "SAPPHIRE_SYNCMAP_DATA_DIR",
332        "SAPPHIRE_SYNCMAP_CONFIG_DIR",
333    ];
334
335    /// Points the context's directories at the test's scratch tree, and restores the
336    /// previous values when dropped — including while unwinding from a panic.
337    struct EnvGuard {
338        previous: [Option<OsString>; 3],
339        _lock: std::sync::MutexGuard<'static, ()>,
340    }
341
342    impl Drop for EnvGuard {
343        fn drop(&mut self) {
344            // SAFETY: `self._lock` still serialises the environment; it is dropped only
345            // after this method returns.
346            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
347                match previous.take() {
348                    Some(value) => unsafe { std::env::set_var(name, value) },
349                    None => test_support::remove(name),
350                }
351            }
352        }
353    }
354
355    /// A server exposing only the sync namespace, plus a workspace root.
356    struct Fixture {
357        _tmp: tempfile::TempDir,
358        _env: EnvGuard,
359        root: PathBuf,
360        client: Client,
361        stub: StubBridge,
362    }
363
364    async fn fixture() -> Fixture {
365        let lock = test_support::lock();
366        let tmp = tempfile::tempdir().unwrap();
367        let previous = DIR_VARS.map(std::env::var_os);
368        // SAFETY (via `test_support::set`): `lock` serialises every read and write of the
369        // process environment in this test binary, and it is held until `drop` has restored
370        // the old values.
371        for (name, dir) in DIR_VARS
372            .iter()
373            .zip(["cache", "data", "config"].map(|cat| tmp.path().join(cat)))
374        {
375            test_support::set(name, &dir);
376        }
377        let env = EnvGuard {
378            previous,
379            _lock: lock,
380        };
381        CTX.init(AppKind::Server);
382
383        let root = tmp.path().join("ws");
384        std::fs::create_dir_all(root.join(".sapphire-syncmap")).unwrap();
385        let root = root.canonicalize().unwrap();
386
387        let (stub, bridge) = StubBridge::start().await;
388        let runtime = Arc::new(SyncRuntime::new(
389            &CTX,
390            bridge,
391            "/bin/true".into(),
392            ManagedBy::Service,
393        ));
394        let current = Arc::new(crate::current::Current::new(
395            &CTX,
396            Arc::new(crate::host::WorkspaceHost::new(&CTX)),
397            Some(runtime),
398            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
399        ));
400        let router = Arc::new(sync_router(
401            Arc::clone(&current),
402            crate::current::current_methods(current, sapphire_ipc::Router::new()),
403        ));
404
405        let (client_conn, server_conn) = Connection::pair();
406        tokio::spawn(async move {
407            let info = ServerInfo {
408                version: "0.0.0".into(),
409                api: sapphire_backend::protocol::API_VERSION,
410                app_api: None,
411                pid: std::process::id(),
412                managed_by: ManagedBy::Service,
413            };
414            let _ = serve(server_conn, router, "sapphire-syncmap", info).await;
415        });
416        let info = ClientInfo {
417            kind: "cli".into(),
418            version: "0.0.0".into(),
419            api: sapphire_backend::protocol::API_VERSION,
420            app_api: None,
421            pid: std::process::id(),
422        };
423        let (client, _) = Client::handshake(client_conn, "sapphire-syncmap", info)
424            .await
425            .unwrap();
426        Fixture {
427            _tmp: tmp,
428            _env: env,
429            root,
430            client,
431            stub,
432        }
433    }
434
435    #[tokio::test(flavor = "multi_thread")]
436    async fn mapping_by_name_writes_the_map_and_enables_sync() {
437        let f = fixture().await;
438        let id = grain_id::GrainId::random();
439        f.stub.list(WorkgroupWorkspaceInfo {
440            workspace_id: id,
441            app_name: "sapphire-syncmap".into(),
442            name: "notes".into(),
443        });
444
445        let result: proto::SyncEnableResult = f
446            .client
447            .call(
448                proto::SYNC_MAP,
449                proto::SyncMapParams {
450                    workspace: "notes".into(),
451                    dir: f.root.clone(),
452                },
453            )
454            .await
455            .unwrap();
456
457        assert_eq!(result.workspace_id, id, "the mapped workspace's id is used");
458        let map = f
459            .root
460            .join(".sapphire-syncmap")
461            .join(crate::sync::WORKSPACE_MAP_FILE);
462        assert_eq!(
463            std::fs::read_to_string(&map).unwrap().trim(),
464            id.to_string(),
465            "the map names the workspace"
466        );
467
468        let status: proto::SyncStatusResult = f
469            .client
470            .call(proto::SYNC_STATUS, serde_json::json!({}))
471            .await
472            .unwrap();
473        assert!(status.enabled, "mapping enabled sync");
474        assert_eq!(status.workspace_id, Some(id));
475    }
476
477    #[tokio::test(flavor = "multi_thread")]
478    async fn mapping_by_id_works_too() {
479        let f = fixture().await;
480        let id = grain_id::GrainId::random();
481        f.stub.list(WorkgroupWorkspaceInfo {
482            workspace_id: id,
483            app_name: "sapphire-syncmap".into(),
484            name: "notes".into(),
485        });
486
487        let result: proto::SyncEnableResult = f
488            .client
489            .call(
490                proto::SYNC_MAP,
491                proto::SyncMapParams {
492                    workspace: id.to_string(),
493                    dir: f.root.clone(),
494                },
495            )
496            .await
497            .unwrap();
498        assert_eq!(result.workspace_id, id);
499    }
500
501    #[tokio::test(flavor = "multi_thread")]
502    async fn an_unknown_workspace_is_an_invalid_parameter() {
503        let f = fixture().await;
504        let err = f
505            .client
506            .call::<_, proto::SyncEnableResult>(
507                proto::SYNC_MAP,
508                proto::SyncMapParams {
509                    workspace: "nowhere".into(),
510                    dir: f.root.clone(),
511                },
512            )
513            .await
514            .unwrap_err();
515        match err {
516            sapphire_ipc::Error::Rpc(e) => {
517                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
518            }
519            other => panic!("got {other:?}"),
520        }
521    }
522
523    #[tokio::test(flavor = "multi_thread")]
524    async fn another_applications_workspace_is_refused() {
525        let f = fixture().await;
526        let id = grain_id::GrainId::random();
527        f.stub.list(WorkgroupWorkspaceInfo {
528            workspace_id: id,
529            app_name: "sapphire-journal".into(),
530            name: "notes".into(),
531        });
532
533        let err = f
534            .client
535            .call::<_, proto::SyncEnableResult>(
536                proto::SYNC_MAP,
537                proto::SyncMapParams {
538                    workspace: "notes".into(),
539                    dir: f.root.clone(),
540                },
541            )
542            .await
543            .unwrap_err();
544        match err {
545            sapphire_ipc::Error::Rpc(e) => {
546                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
547                assert!(
548                    e.message.contains("sapphire-journal"),
549                    "it names the owning application: {}",
550                    e.message
551                );
552            }
553            other => panic!("got {other:?}"),
554        }
555    }
556
557    #[tokio::test(flavor = "multi_thread")]
558    async fn a_directory_that_is_not_a_workspace_is_refused() {
559        let f = fixture().await;
560        let plain = f._tmp.path().join("plain");
561        std::fs::create_dir_all(&plain).unwrap();
562        let id = grain_id::GrainId::random();
563        f.stub.list(WorkgroupWorkspaceInfo {
564            workspace_id: id,
565            app_name: "sapphire-syncmap".into(),
566            name: "notes".into(),
567        });
568
569        let err = f
570            .client
571            .call::<_, proto::SyncEnableResult>(
572                proto::SYNC_MAP,
573                proto::SyncMapParams {
574                    workspace: "notes".into(),
575                    dir: plain,
576                },
577            )
578            .await
579            .unwrap_err();
580        match err {
581            sapphire_ipc::Error::Rpc(e) => {
582                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
583            }
584            other => panic!("got {other:?}"),
585        }
586    }
587}