1use 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
12pub fn sync_router(current: Arc<Current>, router: Router) -> Router {
16 let enable = Arc::clone(¤t);
17 let map = Arc::clone(¤t);
18 let disable = Arc::clone(¤t);
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 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 const DIR_VARS: [&str; 3] = [
91 "SAPPHIRE_SYNCMETHODS_CACHE_DIR",
92 "SAPPHIRE_SYNCMETHODS_DATA_DIR",
93 "SAPPHIRE_SYNCMETHODS_CONFIG_DIR",
94 ];
95
96 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 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 struct Fixture {
122 _tmp: tempfile::TempDir,
123 _env: EnvGuard,
124 root: PathBuf,
125 client: Client,
126 _stub: StubBridge,
127 }
128
129 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 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(¤t),
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 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 const DIR_VARS: [&str; 3] = [
330 "SAPPHIRE_SYNCMAP_CACHE_DIR",
331 "SAPPHIRE_SYNCMAP_DATA_DIR",
332 "SAPPHIRE_SYNCMAP_CONFIG_DIR",
333 ];
334
335 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 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 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 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(¤t),
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_makes_the_marker_and_writes_no_config() {
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 let dir = f.root.parent().unwrap().join("fresh");
487 std::fs::create_dir(&dir).unwrap();
488
489 let result: proto::SyncEnableResult = f
490 .client
491 .call(
492 proto::SYNC_MAP,
493 proto::SyncMapParams {
494 workspace: "notes".into(),
495 dir: dir.clone(),
496 },
497 )
498 .await
499 .unwrap();
500 assert_eq!(result.workspace_id, id);
501 let marker = dir.join(".sapphire-syncmap");
502 assert!(marker.is_dir(), "mapping made the marker");
503 assert!(
504 !marker.join("config.toml").exists(),
505 "the workspace's config arrives with the sync (#253)"
506 );
507 }
508
509 #[tokio::test(flavor = "multi_thread")]
510 async fn mapping_drops_a_registry_only_config_and_keeps_an_apps() {
511 let f = fixture().await;
512 let id = grain_id::GrainId::random();
513 f.stub.list(WorkgroupWorkspaceInfo {
514 workspace_id: id,
515 app_name: "sapphire-syncmap".into(),
516 name: "notes".into(),
517 });
518 let bare = f.root.parent().unwrap().join("bare");
519 let app = f.root.parent().unwrap().join("app");
520 for (dir, config) in [
521 (&bare, "[workspace.bare]\npath = \"/x\"\n"),
522 (
523 &app,
524 "schema_version = 2\n\n[workspace.app]\npath = \"/x\"\n",
525 ),
526 ] {
527 std::fs::create_dir_all(dir.join(".sapphire-syncmap")).unwrap();
528 std::fs::write(dir.join(".sapphire-syncmap").join("config.toml"), config).unwrap();
529 }
530
531 for dir in [&bare, &app] {
532 let _: proto::SyncEnableResult = f
533 .client
534 .call(
535 proto::SYNC_MAP,
536 proto::SyncMapParams {
537 workspace: "notes".into(),
538 dir: dir.clone(),
539 },
540 )
541 .await
542 .unwrap();
543 }
544 assert!(
545 !bare.join(".sapphire-syncmap").join("config.toml").exists(),
546 "a config holding only the registry would win over the workspace's (#253)"
547 );
548 assert!(
549 app.join(".sapphire-syncmap").join("config.toml").exists(),
550 "an application's settings stay"
551 );
552 }
553
554 #[tokio::test(flavor = "multi_thread")]
555 async fn mapping_by_id_works_too() {
556 let f = fixture().await;
557 let id = grain_id::GrainId::random();
558 f.stub.list(WorkgroupWorkspaceInfo {
559 workspace_id: id,
560 app_name: "sapphire-syncmap".into(),
561 name: "notes".into(),
562 });
563
564 let result: proto::SyncEnableResult = f
565 .client
566 .call(
567 proto::SYNC_MAP,
568 proto::SyncMapParams {
569 workspace: id.to_string(),
570 dir: f.root.clone(),
571 },
572 )
573 .await
574 .unwrap();
575 assert_eq!(result.workspace_id, id);
576 }
577
578 #[tokio::test(flavor = "multi_thread")]
579 async fn an_unknown_workspace_is_an_invalid_parameter() {
580 let f = fixture().await;
581 let err = f
582 .client
583 .call::<_, proto::SyncEnableResult>(
584 proto::SYNC_MAP,
585 proto::SyncMapParams {
586 workspace: "nowhere".into(),
587 dir: f.root.clone(),
588 },
589 )
590 .await
591 .unwrap_err();
592 match err {
593 sapphire_ipc::Error::Rpc(e) => {
594 assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
595 }
596 other => panic!("got {other:?}"),
597 }
598 }
599
600 #[tokio::test(flavor = "multi_thread")]
601 async fn another_applications_workspace_is_refused() {
602 let f = fixture().await;
603 let id = grain_id::GrainId::random();
604 f.stub.list(WorkgroupWorkspaceInfo {
605 workspace_id: id,
606 app_name: "sapphire-journal".into(),
607 name: "notes".into(),
608 });
609
610 let err = f
611 .client
612 .call::<_, proto::SyncEnableResult>(
613 proto::SYNC_MAP,
614 proto::SyncMapParams {
615 workspace: "notes".into(),
616 dir: f.root.clone(),
617 },
618 )
619 .await
620 .unwrap_err();
621 match err {
622 sapphire_ipc::Error::Rpc(e) => {
623 assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
624 assert!(
625 e.message.contains("sapphire-journal"),
626 "it names the owning application: {}",
627 e.message
628 );
629 }
630 other => panic!("got {other:?}"),
631 }
632 }
633
634 #[tokio::test(flavor = "multi_thread")]
635 async fn a_directory_that_does_not_exist_is_refused() {
636 let f = fixture().await;
637 let plain = f._tmp.path().join("plain");
638 let id = grain_id::GrainId::random();
639 f.stub.list(WorkgroupWorkspaceInfo {
640 workspace_id: id,
641 app_name: "sapphire-syncmap".into(),
642 name: "notes".into(),
643 });
644
645 let err = f
646 .client
647 .call::<_, proto::SyncEnableResult>(
648 proto::SYNC_MAP,
649 proto::SyncMapParams {
650 workspace: "notes".into(),
651 dir: plain.clone(),
652 },
653 )
654 .await;
655 assert!(err.is_err(), "mapping needs the directory");
656 assert!(!plain.exists(), "and does not make it");
657 }
658}