1use std::path::Path;
7
8use serde_json::Value;
9
10use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES, write_frame};
11use crate::protocol::{
12 AuditSummaryResult, BackendSpec, BlobFetchParams, BlobFetchResult, BlobGrantParams,
13 BlobPublishParams, BlobPublishResult, BlobScopeList, Hello, InviteParams, InviteResult,
14 OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams, PairResult, PeerRemoveParams,
15 PeerRenameParams, PeerServicesParams, PeerServicesResult, RegisterServiceParams, Request,
16 RosterInstallParams, RosterInstallResult, ServiceAllowParams, SetAppMetadataParams,
17 SetNicknameParams, SetRelaysParams, SetRelaysResult, SetRosterUrlParams, StatusResult,
18 StreamFrame, UnregisterServiceParams,
19};
20use crate::transport::{connect_local, split_local};
21
22pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
26pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
28
29pub struct ControlClient {
31 hello: Hello,
32 reader: FrameReader<ControlRead>,
33 writer: ControlWrite,
34}
35
36impl std::fmt::Debug for ControlClient {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("ControlClient")
41 .field("hello", &self.hello)
42 .finish_non_exhaustive()
43 }
44}
45
46#[derive(Debug)]
53pub enum ClientError {
54 Io(std::io::Error),
55 Closed(&'static str),
56 Malformed(&'static str),
57 WrongApi { got: String, want: &'static str },
58 Api(Value),
59}
60
61impl std::fmt::Display for ClientError {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self {
64 ClientError::Io(err) => write!(f, "io: {err}"),
65 ClientError::Closed(what) => write!(f, "connection closed before {what}"),
66 ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
67 ClientError::WrongApi { got, want } => {
68 write!(f, "unexpected api: got {got:?}, want {want:?}")
69 }
70 ClientError::Api(err) => write!(f, "control API error: {err}"),
71 }
72 }
73}
74
75impl std::error::Error for ClientError {}
76
77impl From<std::io::Error> for ClientError {
78 fn from(err: std::io::Error) -> Self {
79 ClientError::Io(err)
80 }
81}
82
83impl ControlClient {
84 pub fn hello(&self) -> &Hello {
85 &self.hello
86 }
87
88 pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
91 let frame = serde_json::to_value(&request).expect("Request serializes");
92 self.request_value(&frame).await
93 }
94
95 pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
100 write_frame(&mut self.writer, request).await?;
101 match self.reader.next().await? {
102 Some(Inbound::Frame(resp)) => {
103 if let Some(err) = resp.get("error") {
104 return Err(ClientError::Api(err.clone()));
105 }
106 Ok(resp.get("result").cloned().unwrap_or(Value::Null))
107 }
108 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
109 None => Err(ClientError::Closed("response")),
110 }
111 }
112
113 pub async fn open_session(
120 mut self,
121 peer: String,
122 service: String,
123 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
124 let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
125 .expect("Request serializes");
126 write_frame(&mut self.writer, &frame).await?;
127 Ok((self.reader, self.writer))
128 }
129
130 pub async fn open_stream(
138 mut self,
139 method: &str,
140 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
141 let frame = serde_json::json!({ "method": method });
142 write_frame(&mut self.writer, &frame).await?;
143 Ok((self.reader, self.writer))
144 }
145
146 async fn request_typed<T: serde::de::DeserializeOwned>(
151 &mut self,
152 request: Request,
153 what: &'static str,
154 ) -> Result<T, ClientError> {
155 let v = self.request(request).await?;
156 serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
157 }
158
159 async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
162 self.request(request).await.map(|_| ())
163 }
164
165 pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
168 self.request_typed(Request::Status, "status result").await
169 }
170
171 pub async fn register_service(
174 &mut self,
175 name: &str,
176 backend: BackendSpec,
177 allow: Vec<String>,
178 ) -> Result<(), ClientError> {
179 self.register_service_with(name, backend, allow, false)
180 .await
181 }
182
183 pub async fn register_service_with(
188 &mut self,
189 name: &str,
190 backend: BackendSpec,
191 allow: Vec<String>,
192 ephemeral: bool,
193 ) -> Result<(), ClientError> {
194 self.request_ack(Request::RegisterService(RegisterServiceParams {
195 name: name.to_string(),
196 backend,
197 allow,
198 ephemeral,
199 }))
200 .await
201 }
202
203 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
207 self.invite_with(services, None).await
208 }
209
210 pub async fn invite_with(
213 &mut self,
214 services: Vec<String>,
215 app_label: Option<String>,
216 ) -> Result<InviteResult, ClientError> {
217 self.invite_multi(services, app_label, None).await
218 }
219
220 pub async fn invite_multi(
228 &mut self,
229 services: Vec<String>,
230 app_label: Option<String>,
231 max_uses: Option<u32>,
232 ) -> Result<InviteResult, ClientError> {
233 self.invite_named(services, app_label, max_uses, None).await
234 }
235
236 pub async fn invite_named(
242 &mut self,
243 services: Vec<String>,
244 app_label: Option<String>,
245 max_uses: Option<u32>,
246 peer_nickname: Option<String>,
247 ) -> Result<InviteResult, ClientError> {
248 self.request_typed(
249 Request::Invite(InviteParams {
250 services,
251 app_label,
252 max_uses,
253 peer_nickname,
254 }),
255 "invite result",
256 )
257 .await
258 }
259
260 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
263 self.pair_as(invite_line, None).await
264 }
265
266 pub async fn pair_as(
273 &mut self,
274 invite_line: &str,
275 as_nickname: Option<String>,
276 ) -> Result<PairResult, ClientError> {
277 self.request_typed(
278 Request::Pair(PairParams {
279 invite_line: invite_line.to_string(),
280 as_nickname,
281 }),
282 "pair result",
283 )
284 .await
285 }
286
287 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
290 self.request_ack(Request::PeerRemove(PeerRemoveParams {
291 nickname: nickname.to_string(),
292 }))
293 .await
294 }
295
296 pub async fn peer_rename(
301 &mut self,
302 user_id: Option<String>,
303 nickname: Option<String>,
304 to: &str,
305 ) -> Result<(), ClientError> {
306 self.request_ack(Request::PeerRename(PeerRenameParams {
307 user_id,
308 nickname,
309 to: to.to_string(),
310 }))
311 .await
312 }
313
314 pub async fn roster_install(
317 &mut self,
318 path: &str,
319 org_root_pk: Option<String>,
320 ) -> Result<RosterInstallResult, ClientError> {
321 self.request_typed(
322 Request::RosterInstall(RosterInstallParams {
323 path: path.to_string(),
324 org_root_pk,
325 }),
326 "roster_install result",
327 )
328 .await
329 }
330
331 pub async fn org_join(
334 &mut self,
335 org_id: &str,
336 org_root_pk: &str,
337 user_id: &str,
338 user_key: &str,
339 ) -> Result<OrgJoinResult, ClientError> {
340 self.request_typed(
341 Request::OrgJoin(OrgJoinParams {
342 org_id: org_id.to_string(),
343 org_root_pk: org_root_pk.to_string(),
344 user_id: user_id.to_string(),
345 user_key: user_key.to_string(),
346 }),
347 "org_join result",
348 )
349 .await
350 }
351
352 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
355 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
356 url: url.to_string(),
357 }))
358 .await
359 }
360
361 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
365 self.request_typed::<PeerServicesResult>(
366 Request::PeerServices(PeerServicesParams {
367 peer: peer.to_string(),
368 }),
369 "peer_services",
370 )
371 .await
372 .map(|r| r.services)
373 }
374
375 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
379 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
380 name: name.to_string(),
381 }))
382 .await
383 }
384
385 pub async fn service_allow_grant(
388 &mut self,
389 service: &str,
390 principal: &str,
391 ) -> Result<(), ClientError> {
392 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
393 service: service.to_string(),
394 principal: principal.to_string(),
395 }))
396 .await
397 }
398
399 pub async fn service_allow_revoke(
403 &mut self,
404 service: &str,
405 principal: &str,
406 ) -> Result<(), ClientError> {
407 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
408 service: service.to_string(),
409 principal: principal.to_string(),
410 }))
411 .await
412 }
413
414 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
418 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
419 metadata: metadata.to_string(),
420 }))
421 .await
422 }
423
424 pub async fn set_relays(
433 &mut self,
434 relay_urls: &[String],
435 ) -> Result<SetRelaysResult, ClientError> {
436 self.request_typed::<SetRelaysResult>(
437 Request::SetRelays(SetRelaysParams {
438 relay_urls: relay_urls.to_vec(),
439 }),
440 "set_relays",
441 )
442 .await
443 }
444
445 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
449 self.request_ack(Request::SetNickname(SetNicknameParams {
450 nickname: nickname.to_string(),
451 }))
452 .await
453 }
454
455 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
458 self.request_typed(Request::AuditSummary, "audit_summary result")
459 .await
460 }
461
462 pub async fn blob_publish(
464 &mut self,
465 scope: &str,
466 path: &str,
467 ) -> Result<BlobPublishResult, ClientError> {
468 self.request_typed(
469 Request::BlobPublish(BlobPublishParams {
470 scope: scope.to_string(),
471 path: path.to_string(),
472 }),
473 "blob_publish result",
474 )
475 .await
476 }
477
478 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
483 self.blob_list_paged(Default::default()).await
484 }
485
486 pub async fn blob_list_paged(
488 &mut self,
489 params: crate::BlobListParams,
490 ) -> Result<BlobScopeList, ClientError> {
491 self.request_typed(Request::BlobList(params), "blob_list result")
492 .await
493 }
494
495 pub async fn blob_fetch(
498 &mut self,
499 ticket: &str,
500 dest_path: &str,
501 ) -> Result<BlobFetchResult, ClientError> {
502 self.request_typed(
503 Request::BlobFetch(BlobFetchParams {
504 ticket: ticket.to_string(),
505 dest_path: dest_path.to_string(),
506 }),
507 "blob_fetch result",
508 )
509 .await
510 }
511
512 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
518 self.request_ack(Request::BlobGrant(BlobGrantParams {
519 scope: scope.to_string(),
520 principal: principal.to_string(),
521 }))
522 .await
523 }
524
525 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
530 let (reader, writer) = self.open_stream("subscribe").await?;
531 Ok(StreamSubscription {
532 reader,
533 _writer: writer,
534 })
535 }
536}
537
538pub struct StreamSubscription {
543 reader: FrameReader<ControlRead>,
544 _writer: ControlWrite,
545}
546
547impl std::fmt::Debug for StreamSubscription {
549 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
550 f.debug_struct("StreamSubscription").finish_non_exhaustive()
551 }
552}
553
554impl StreamSubscription {
555 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
560 match self.reader.next().await? {
561 Some(Inbound::Frame(v)) => serde_json::from_value(v)
562 .map(Some)
563 .map_err(|_| ClientError::Malformed("stream frame")),
564 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
565 None => Ok(None),
566 }
567 }
568}
569
570pub async fn connect_control_io(
574 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
575 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
576) -> Result<ControlClient, ClientError> {
577 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
578 let hello: Hello = match reader.next().await? {
579 Some(Inbound::Frame(v)) => {
580 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
581 }
582 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
583 None => return Err(ClientError::Closed("hello")),
584 };
585 if hello.api != crate::protocol::API_NAME {
586 return Err(ClientError::WrongApi {
587 got: hello.api,
588 want: crate::protocol::API_NAME,
589 });
590 }
591 Ok(ControlClient {
592 hello,
593 reader,
594 writer: Box::new(writer) as ControlWrite,
595 })
596}
597
598pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
600 let stream = connect_local(path).await?;
601 let (read_half, write_half) = split_local(stream);
602 connect_control_io(read_half, write_half).await
603}
604
605pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
610 connect_control(&crate::paths::default_endpoint()?).await
611}
612
613#[cfg(all(test, feature = "service"))]
621mod tests {
622 use super::*;
623 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
624 use crate::transport::{LocalListener, bind_local, split_local};
625 use tokio::io::AsyncWriteExt;
626
627 #[cfg(unix)]
632 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
633 let dir = tempfile::tempdir().unwrap();
634 let path = dir.path().join(format!("{tag}.sock"));
635 (path, dir)
636 }
637 #[cfg(windows)]
638 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
639 use std::sync::atomic::{AtomicU64, Ordering};
640 static SEQ: AtomicU64 = AtomicU64::new(0);
641 let n = SEQ.fetch_add(1, Ordering::Relaxed);
642 let path = std::path::PathBuf::from(format!(
643 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
644 std::process::id()
645 ));
646 (path, ())
647 }
648
649 async fn stub_daemon(mut listener: LocalListener) {
651 let stream = listener.accept().await.unwrap();
652 let (read_half, mut writer) = split_local(stream);
653 write_frame(
654 &mut writer,
655 &serde_json::to_value(Hello {
656 api: API_NAME.into(),
657 api_version: API_VERSION.into(),
658 api_minor: 0,
659 stack_version: "0.1.0".into(),
660 })
661 .unwrap(),
662 )
663 .await
664 .unwrap();
665 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
666 let req = match reader.next().await.unwrap().unwrap() {
667 Inbound::Frame(v) => v,
668 Inbound::Violation(_) => panic!("violation"),
669 };
670 assert_eq!(req["method"], "status");
671 let result = StatusResult {
672 stack_version: "0.1.0".into(),
673 services: vec![ServiceInfo {
674 name: "kb".into(),
675 allow: vec![],
676 allow_display: vec![],
677 backend: BackendKind::Socket,
678 ephemeral: false,
679 }],
680 peers: vec![],
681 roster: None,
682 presence: vec![],
683 self_user_id: None,
684 recent_pairings: vec![],
685 reachability: vec![],
686 self_nickname: String::new(),
687 storage: None,
688 self_network: None,
689 };
690 write_frame(
691 &mut writer,
692 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
693 )
694 .await
695 .unwrap();
696 writer.flush().await.unwrap();
697 }
698
699 #[tokio::test]
702 async fn connect_control_io_handshakes_over_a_duplex() {
703 let (client_io, mut server_io) = tokio::io::duplex(4096);
704 tokio::spawn(async move {
705 write_frame(
706 &mut server_io,
707 &serde_json::to_value(Hello {
708 api: API_NAME.into(),
709 api_version: API_VERSION.into(),
710 api_minor: 0,
711 stack_version: "in-proc".into(),
712 })
713 .unwrap(),
714 )
715 .await
716 .unwrap();
717 });
718 let (r, w) = tokio::io::split(client_io);
719 let client = connect_control_io(r, w).await.expect("handshake");
720 assert_eq!(client.hello().stack_version, "in-proc");
721 }
722
723 #[tokio::test]
724 async fn connect_reads_hello_asserts_api_and_requests() {
725 let (sock, _guard) = test_endpoint("status");
726 let listener = bind_local(&sock).unwrap();
727 let server = tokio::spawn(stub_daemon(listener));
728
729 let mut client = connect_control(&sock).await.unwrap();
730 assert_eq!(client.hello().api, API_NAME);
731 let result = client.request(Request::Status).await.unwrap();
732 assert_eq!(result["services"][0]["name"], "kb");
733 assert_eq!(result["services"][0]["backend"], "socket");
734 server.await.unwrap();
735 }
736
737 #[tokio::test]
738 async fn wrong_api_hello_is_rejected() {
739 let (sock, _guard) = test_endpoint("wrongapi");
740 let listener = bind_local(&sock).unwrap();
741 tokio::spawn(async move {
742 let mut listener = listener;
743 let stream = listener.accept().await.unwrap();
744 let (_r, mut w) = split_local(stream);
745 write_frame(
746 &mut w,
747 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
748 )
749 .await
750 .unwrap();
751 w.flush().await.unwrap();
752 });
753 match connect_control(&sock).await {
754 Err(ClientError::WrongApi { got, want }) => {
755 assert_eq!(got, "other/1");
756 assert_eq!(want, API_NAME);
757 }
758 other => panic!("expected WrongApi, got {other:?}"),
759 }
760 }
761
762 #[tokio::test]
763 async fn blob_fetch_and_publish_deserialize_typed_results() {
764 use crate::protocol::{BlobFetchResult, BlobPublishResult};
765 let (sock, _guard) = test_endpoint("blob");
766 let listener = bind_local(&sock).unwrap();
767 let server = tokio::spawn(async move {
768 let mut listener = listener;
769 let stream = listener.accept().await.unwrap();
770 let (read_half, mut writer) = split_local(stream);
771 write_frame(
772 &mut writer,
773 &serde_json::to_value(Hello {
774 api: API_NAME.into(),
775 api_version: API_VERSION.into(),
776 api_minor: 0,
777 stack_version: "0.1.0".into(),
778 })
779 .unwrap(),
780 )
781 .await
782 .unwrap();
783 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
784 let req = match reader.next().await.unwrap().unwrap() {
786 Inbound::Frame(v) => v,
787 Inbound::Violation(_) => panic!("violation"),
788 };
789 assert_eq!(req["method"], "blob_publish");
790 assert_eq!(req["params"]["scope"], "eng");
791 write_frame(
792 &mut writer,
793 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
794 )
795 .await
796 .unwrap();
797 let req = match reader.next().await.unwrap().unwrap() {
799 Inbound::Frame(v) => v,
800 Inbound::Violation(_) => panic!("violation"),
801 };
802 assert_eq!(req["method"], "blob_fetch");
803 assert_eq!(req["params"]["ticket"], "blobT");
804 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
805 write_frame(
806 &mut writer,
807 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
808 )
809 .await
810 .unwrap();
811 let _ = (
812 BlobFetchResult {
813 hash: "cd".into(),
814 bytes_len: 7,
815 },
816 BlobPublishResult {
817 ticket: "blobT".into(),
818 hash: "ab".into(),
819 },
820 );
821 });
822
823 let mut client = connect_control(&sock).await.unwrap();
824 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
825 assert_eq!(pub_res.ticket, "blobT");
826 assert_eq!(pub_res.hash, "ab");
827 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
828 assert_eq!(fetch_res.hash, "cd");
829 assert_eq!(fetch_res.bytes_len, 7);
830 server.await.unwrap();
831 }
832
833 #[tokio::test]
840 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
841 use tokio::io::AsyncRead;
842
843 let (sock, _guard) = test_endpoint("pipelined");
844 let listener = bind_local(&sock).unwrap();
845 let server = tokio::spawn(async move {
846 let mut listener = listener;
847 let stream = listener.accept().await.unwrap();
848 let (read_half, mut writer) = split_local(stream);
849 let mut bytes = serde_json::to_vec(
852 &serde_json::to_value(Hello {
853 api: API_NAME.into(),
854 api_version: API_VERSION.into(),
855 api_minor: 0,
856 stack_version: "0.1.0".into(),
857 })
858 .unwrap(),
859 )
860 .unwrap();
861 bytes.push(b'\n');
862 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
863 writer.write_all(&bytes).await.unwrap();
864 writer.flush().await.unwrap();
865 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
867 let req = match reader.next().await.unwrap().unwrap() {
868 Inbound::Frame(v) => v,
869 Inbound::Violation(_) => panic!("violation"),
870 };
871 assert_eq!(req["method"], "open_session");
872 });
873
874 let client = connect_control(&sock).await.unwrap();
875 let (reader, _writer) = client
876 .open_session("peer".into(), "kb".into())
877 .await
878 .unwrap();
879 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
881 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
882 match reframed.next().await.unwrap() {
883 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
884 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
885 }
886 server.await.unwrap();
887 }
888
889 #[tokio::test]
890 async fn blob_grant_issues_request_and_acks() {
891 let (sock, _guard) = test_endpoint("grant");
892 let listener = bind_local(&sock).unwrap();
893 let server = tokio::spawn(async move {
894 let mut listener = listener;
895 let stream = listener.accept().await.unwrap();
896 let (read_half, mut writer) = split_local(stream);
897 write_frame(
898 &mut writer,
899 &serde_json::to_value(Hello {
900 api: API_NAME.into(),
901 api_version: API_VERSION.into(),
902 api_minor: 0,
903 stack_version: "0.1.0".into(),
904 })
905 .unwrap(),
906 )
907 .await
908 .unwrap();
909 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
910 let req = match reader.next().await.unwrap().unwrap() {
911 Inbound::Frame(v) => v,
912 Inbound::Violation(_) => panic!("violation"),
913 };
914 assert_eq!(req["method"], "blob_grant");
915 assert_eq!(req["params"]["scope"], "kb-sync");
916 assert_eq!(req["params"]["principal"], "alice");
917 write_frame(
918 &mut writer,
919 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
920 )
921 .await
922 .unwrap();
923 });
924 let mut client = connect_control(&sock).await.unwrap();
925 client.blob_grant("kb-sync", "alice").await.unwrap();
926 server.await.unwrap();
927 }
928
929 #[tokio::test]
933 async fn typed_status_helper_deserializes_the_result() {
934 let (sock, _guard) = test_endpoint("typedstatus");
935 let listener = bind_local(&sock).unwrap();
936 let server = tokio::spawn(stub_daemon(listener));
937
938 let mut client = connect_control(&sock).await.unwrap();
939 let status = client.status().await.unwrap();
940 assert_eq!(status.stack_version, "0.1.0");
941 assert_eq!(status.services[0].name, "kb");
942 assert_eq!(status.services[0].backend, BackendKind::Socket);
943 assert!(status.peers.is_empty());
944 server.await.unwrap();
945 }
946
947 #[tokio::test]
950 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
951 let (sock, _guard) = test_endpoint("typedack");
952 let listener = bind_local(&sock).unwrap();
953 let server = tokio::spawn(async move {
954 let mut listener = listener;
955 let stream = listener.accept().await.unwrap();
956 let (read_half, mut writer) = split_local(stream);
957 write_frame(
958 &mut writer,
959 &serde_json::to_value(Hello {
960 api: API_NAME.into(),
961 api_version: API_VERSION.into(),
962 api_minor: 0,
963 stack_version: "0.1.0".into(),
964 })
965 .unwrap(),
966 )
967 .await
968 .unwrap();
969 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
970 let req = match reader.next().await.unwrap().unwrap() {
972 Inbound::Frame(v) => v,
973 Inbound::Violation(_) => panic!("violation"),
974 };
975 assert_eq!(req["method"], "peer_remove");
976 assert_eq!(req["params"]["nickname"], "bob");
977 write_frame(
978 &mut writer,
979 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
980 )
981 .await
982 .unwrap();
983 let req = match reader.next().await.unwrap().unwrap() {
985 Inbound::Frame(v) => v,
986 Inbound::Violation(_) => panic!("violation"),
987 };
988 assert_eq!(req["method"], "peer_rename");
989 assert_eq!(req["params"]["to"], "Bobby");
990 write_frame(
991 &mut writer,
992 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
993 )
994 .await
995 .unwrap();
996 });
997
998 let mut client = connect_control(&sock).await.unwrap();
999 client.peer_remove("bob").await.unwrap();
1000 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1001 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1002 other => panic!("expected Api error, got {other:?}"),
1003 }
1004 server.await.unwrap();
1005 }
1006
1007 #[tokio::test]
1010 async fn typed_subscribe_yields_frames_then_end() {
1011 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1012
1013 let (sock, _guard) = test_endpoint("subscribe");
1014 let listener = bind_local(&sock).unwrap();
1015 let server = tokio::spawn(async move {
1016 let mut listener = listener;
1017 let stream = listener.accept().await.unwrap();
1018 let (read_half, mut writer) = split_local(stream);
1019 write_frame(
1020 &mut writer,
1021 &serde_json::to_value(Hello {
1022 api: API_NAME.into(),
1023 api_version: API_VERSION.into(),
1024 api_minor: 0,
1025 stack_version: "0.1.0".into(),
1026 })
1027 .unwrap(),
1028 )
1029 .await
1030 .unwrap();
1031 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1032 let req = match reader.next().await.unwrap().unwrap() {
1033 Inbound::Frame(v) => v,
1034 Inbound::Violation(_) => panic!("violation"),
1035 };
1036 assert_eq!(req["method"], "subscribe");
1037 for frame in [
1038 StreamFrame::Snapshot {
1039 self_network: None,
1040 active_sessions: vec![ActiveSession {
1041 peer: "bob".into(),
1042 service: "notes".into(),
1043 opened_at: 7,
1044 principal: Some("eid:bob".into()),
1045 }],
1046 reachability: vec![PeerReachability {
1047 name: "bob".into(),
1048 reachable: true,
1049 rtt_ms: Some(42),
1050 age_secs: Some(3),
1051 meta: String::new(),
1052 principal: None,
1053 path: Default::default(),
1054 }],
1055 },
1056 StreamFrame::Event {
1057 record: Box::new(AuditRecord::session_open(
1058 "2026-07-03T14:02:11.480Z".into(),
1059 Some("bob".into()),
1060 "notes".into(),
1061 None,
1062 )),
1063 },
1064 StreamFrame::Lagged { dropped: 12 },
1065 ] {
1066 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1067 .await
1068 .unwrap();
1069 }
1070 writer.flush().await.unwrap();
1071 });
1073
1074 let client = connect_control(&sock).await.unwrap();
1075 let mut sub = client.subscribe().await.unwrap();
1076 match sub.next().await.unwrap().unwrap() {
1077 StreamFrame::Snapshot {
1078 active_sessions,
1079 reachability,
1080 ..
1081 } => {
1082 assert_eq!(active_sessions[0].peer, "bob");
1083 assert_eq!(reachability[0].rtt_ms, Some(42));
1084 }
1085 other => panic!("expected the snapshot first, got {other:?}"),
1086 }
1087 match sub.next().await.unwrap().unwrap() {
1088 StreamFrame::Event { record } => {
1089 assert_eq!(record.peer.as_deref(), Some("bob"));
1090 assert_eq!(record.service.as_deref(), Some("notes"));
1091 }
1092 other => panic!("expected the event, got {other:?}"),
1093 }
1094 assert_eq!(
1095 sub.next().await.unwrap(),
1096 Some(StreamFrame::Lagged { dropped: 12 })
1097 );
1098 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1099 server.await.unwrap();
1100 }
1101}