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, PeerEndorseParams,
15 PeerEndorseResult, PeerIntroduceParams, PeerRemoveParams, PeerRenameParams, PeerServicesParams,
16 PeerServicesResult, RegisterServiceParams, Request, RosterInstallParams, RosterInstallResult,
17 ServiceAllowParams, SetAppMetadataParams, SetNicknameParams, SetRelaysParams, SetRelaysResult,
18 SetRosterUrlParams, StatusResult, 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 rate_limit_per_min: None,
200 }))
201 .await
202 }
203
204 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
208 self.invite_with(services, None).await
209 }
210
211 pub async fn invite_with(
214 &mut self,
215 services: Vec<String>,
216 app_label: Option<String>,
217 ) -> Result<InviteResult, ClientError> {
218 self.invite_multi(services, app_label, None).await
219 }
220
221 pub async fn invite_multi(
229 &mut self,
230 services: Vec<String>,
231 app_label: Option<String>,
232 max_uses: Option<u32>,
233 ) -> Result<InviteResult, ClientError> {
234 self.invite_named(services, app_label, max_uses, None).await
235 }
236
237 pub async fn invite_named(
243 &mut self,
244 services: Vec<String>,
245 app_label: Option<String>,
246 max_uses: Option<u32>,
247 peer_nickname: Option<String>,
248 ) -> Result<InviteResult, ClientError> {
249 self.invite_full(services, app_label, max_uses, peer_nickname, false)
250 .await
251 }
252
253 pub async fn invite_full(
259 &mut self,
260 services: Vec<String>,
261 app_label: Option<String>,
262 max_uses: Option<u32>,
263 peer_nickname: Option<String>,
264 as_self: bool,
265 ) -> Result<InviteResult, ClientError> {
266 self.request_typed(
267 Request::Invite(InviteParams {
268 services,
269 app_label,
270 max_uses,
271 peer_nickname,
272 as_self,
273 }),
274 "invite result",
275 )
276 .await
277 }
278
279 pub async fn endorse_peer(
284 &mut self,
285 subject: &str,
286 subject_user_id: Option<String>,
287 ) -> Result<PeerEndorseResult, ClientError> {
288 self.request_typed(
289 Request::PeerEndorse(PeerEndorseParams {
290 subject: subject.to_string(),
291 subject_user_id,
292 }),
293 "peer endorse result",
294 )
295 .await
296 }
297
298 pub async fn introduce_peer(&mut self, params: PeerIntroduceParams) -> Result<(), ClientError> {
304 self.request_ack(Request::PeerIntroduce(params)).await
305 }
306
307 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
310 self.pair_as(invite_line, None).await
311 }
312
313 pub async fn pair_as(
320 &mut self,
321 invite_line: &str,
322 as_nickname: Option<String>,
323 ) -> Result<PairResult, ClientError> {
324 self.request_typed(
325 Request::Pair(PairParams {
326 invite_line: invite_line.to_string(),
327 as_nickname,
328 }),
329 "pair result",
330 )
331 .await
332 }
333
334 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
337 self.request_ack(Request::PeerRemove(PeerRemoveParams {
338 nickname: nickname.to_string(),
339 }))
340 .await
341 }
342
343 pub async fn peer_rename(
348 &mut self,
349 user_id: Option<String>,
350 nickname: Option<String>,
351 to: &str,
352 ) -> Result<(), ClientError> {
353 self.request_ack(Request::PeerRename(PeerRenameParams {
354 user_id,
355 nickname,
356 to: to.to_string(),
357 }))
358 .await
359 }
360
361 pub async fn roster_install(
364 &mut self,
365 path: &str,
366 org_root_pk: Option<String>,
367 ) -> Result<RosterInstallResult, ClientError> {
368 self.request_typed(
369 Request::RosterInstall(RosterInstallParams {
370 path: path.to_string(),
371 org_root_pk,
372 }),
373 "roster_install result",
374 )
375 .await
376 }
377
378 pub async fn org_join(
381 &mut self,
382 org_id: &str,
383 org_root_pk: &str,
384 user_id: &str,
385 user_key: &str,
386 ) -> Result<OrgJoinResult, ClientError> {
387 self.request_typed(
388 Request::OrgJoin(OrgJoinParams {
389 org_id: org_id.to_string(),
390 org_root_pk: org_root_pk.to_string(),
391 user_id: user_id.to_string(),
392 user_key: user_key.to_string(),
393 }),
394 "org_join result",
395 )
396 .await
397 }
398
399 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
402 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
403 url: url.to_string(),
404 }))
405 .await
406 }
407
408 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
412 self.request_typed::<PeerServicesResult>(
413 Request::PeerServices(PeerServicesParams {
414 peer: peer.to_string(),
415 }),
416 "peer_services",
417 )
418 .await
419 .map(|r| r.services)
420 }
421
422 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
426 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
427 name: name.to_string(),
428 }))
429 .await
430 }
431
432 pub async fn service_allow_grant(
435 &mut self,
436 service: &str,
437 principal: &str,
438 ) -> Result<(), ClientError> {
439 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
440 service: service.to_string(),
441 principal: principal.to_string(),
442 }))
443 .await
444 }
445
446 pub async fn service_allow_revoke(
450 &mut self,
451 service: &str,
452 principal: &str,
453 ) -> Result<(), ClientError> {
454 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
455 service: service.to_string(),
456 principal: principal.to_string(),
457 }))
458 .await
459 }
460
461 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
465 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
466 metadata: metadata.to_string(),
467 }))
468 .await
469 }
470
471 pub async fn set_relays(
480 &mut self,
481 relay_urls: &[String],
482 ) -> Result<SetRelaysResult, ClientError> {
483 self.request_typed::<SetRelaysResult>(
484 Request::SetRelays(SetRelaysParams {
485 relay_urls: relay_urls.to_vec(),
486 }),
487 "set_relays",
488 )
489 .await
490 }
491
492 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
496 self.request_ack(Request::SetNickname(SetNicknameParams {
497 nickname: nickname.to_string(),
498 }))
499 .await
500 }
501
502 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
505 self.request_typed(Request::AuditSummary, "audit_summary result")
506 .await
507 }
508
509 pub async fn blob_publish(
511 &mut self,
512 scope: &str,
513 path: &str,
514 ) -> Result<BlobPublishResult, ClientError> {
515 self.request_typed(
516 Request::BlobPublish(BlobPublishParams {
517 scope: scope.to_string(),
518 path: path.to_string(),
519 }),
520 "blob_publish result",
521 )
522 .await
523 }
524
525 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
530 self.blob_list_paged(Default::default()).await
531 }
532
533 pub async fn blob_list_paged(
535 &mut self,
536 params: crate::BlobListParams,
537 ) -> Result<BlobScopeList, ClientError> {
538 self.request_typed(Request::BlobList(params), "blob_list result")
539 .await
540 }
541
542 pub async fn blob_fetch(
545 &mut self,
546 ticket: &str,
547 dest_path: &str,
548 ) -> Result<BlobFetchResult, ClientError> {
549 self.request_typed(
550 Request::BlobFetch(BlobFetchParams {
551 ticket: ticket.to_string(),
552 dest_path: dest_path.to_string(),
553 }),
554 "blob_fetch result",
555 )
556 .await
557 }
558
559 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
565 self.request_ack(Request::BlobGrant(BlobGrantParams {
566 scope: scope.to_string(),
567 principal: principal.to_string(),
568 }))
569 .await
570 }
571
572 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
577 let (reader, writer) = self.open_stream("subscribe").await?;
578 Ok(StreamSubscription {
579 reader,
580 _writer: writer,
581 })
582 }
583}
584
585pub struct StreamSubscription {
590 reader: FrameReader<ControlRead>,
591 _writer: ControlWrite,
592}
593
594impl std::fmt::Debug for StreamSubscription {
596 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
597 f.debug_struct("StreamSubscription").finish_non_exhaustive()
598 }
599}
600
601impl StreamSubscription {
602 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
607 match self.reader.next().await? {
608 Some(Inbound::Frame(v)) => serde_json::from_value(v)
609 .map(Some)
610 .map_err(|_| ClientError::Malformed("stream frame")),
611 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
612 None => Ok(None),
613 }
614 }
615}
616
617pub async fn connect_control_io(
621 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
622 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
623) -> Result<ControlClient, ClientError> {
624 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
625 let hello: Hello = match reader.next().await? {
626 Some(Inbound::Frame(v)) => {
627 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
628 }
629 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
630 None => return Err(ClientError::Closed("hello")),
631 };
632 if hello.api != crate::protocol::API_NAME {
633 return Err(ClientError::WrongApi {
634 got: hello.api,
635 want: crate::protocol::API_NAME,
636 });
637 }
638 Ok(ControlClient {
639 hello,
640 reader,
641 writer: Box::new(writer) as ControlWrite,
642 })
643}
644
645pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
647 let stream = connect_local(path).await?;
648 let (read_half, write_half) = split_local(stream);
649 connect_control_io(read_half, write_half).await
650}
651
652pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
657 connect_control(&crate::paths::default_endpoint()?).await
658}
659
660#[cfg(all(test, feature = "service"))]
668mod tests {
669 use super::*;
670 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
671 use crate::transport::{LocalListener, bind_local, split_local};
672 use tokio::io::AsyncWriteExt;
673
674 #[cfg(unix)]
679 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
680 let dir = tempfile::tempdir().unwrap();
681 let path = dir.path().join(format!("{tag}.sock"));
682 (path, dir)
683 }
684 #[cfg(windows)]
685 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
686 use std::sync::atomic::{AtomicU64, Ordering};
687 static SEQ: AtomicU64 = AtomicU64::new(0);
688 let n = SEQ.fetch_add(1, Ordering::Relaxed);
689 let path = std::path::PathBuf::from(format!(
690 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
691 std::process::id()
692 ));
693 (path, ())
694 }
695
696 async fn stub_daemon(mut listener: LocalListener) {
698 let stream = listener.accept().await.unwrap();
699 let (read_half, mut writer) = split_local(stream);
700 write_frame(
701 &mut writer,
702 &serde_json::to_value(Hello {
703 api: API_NAME.into(),
704 api_version: API_VERSION.into(),
705 api_minor: 0,
706 stack_version: "0.1.0".into(),
707 })
708 .unwrap(),
709 )
710 .await
711 .unwrap();
712 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
713 let req = match reader.next().await.unwrap().unwrap() {
714 Inbound::Frame(v) => v,
715 Inbound::Violation(_) => panic!("violation"),
716 };
717 assert_eq!(req["method"], "status");
718 let result = StatusResult {
719 stack_version: "0.1.0".into(),
720 services: vec![ServiceInfo {
721 name: "kb".into(),
722 allow: vec![],
723 allow_display: vec![],
724 backend: BackendKind::Socket,
725 ephemeral: false,
726 }],
727 peers: vec![],
728 roster: None,
729 presence: vec![],
730 self_user_id: None,
731 recent_pairings: vec![],
732 reachability: vec![],
733 self_nickname: String::new(),
734 storage: None,
735 self_network: None,
736 };
737 write_frame(
738 &mut writer,
739 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
740 )
741 .await
742 .unwrap();
743 writer.flush().await.unwrap();
744 }
745
746 #[tokio::test]
749 async fn connect_control_io_handshakes_over_a_duplex() {
750 let (client_io, mut server_io) = tokio::io::duplex(4096);
751 tokio::spawn(async move {
752 write_frame(
753 &mut server_io,
754 &serde_json::to_value(Hello {
755 api: API_NAME.into(),
756 api_version: API_VERSION.into(),
757 api_minor: 0,
758 stack_version: "in-proc".into(),
759 })
760 .unwrap(),
761 )
762 .await
763 .unwrap();
764 });
765 let (r, w) = tokio::io::split(client_io);
766 let client = connect_control_io(r, w).await.expect("handshake");
767 assert_eq!(client.hello().stack_version, "in-proc");
768 }
769
770 #[tokio::test]
771 async fn connect_reads_hello_asserts_api_and_requests() {
772 let (sock, _guard) = test_endpoint("status");
773 let listener = bind_local(&sock).unwrap();
774 let server = tokio::spawn(stub_daemon(listener));
775
776 let mut client = connect_control(&sock).await.unwrap();
777 assert_eq!(client.hello().api, API_NAME);
778 let result = client.request(Request::Status).await.unwrap();
779 assert_eq!(result["services"][0]["name"], "kb");
780 assert_eq!(result["services"][0]["backend"], "socket");
781 server.await.unwrap();
782 }
783
784 #[tokio::test]
785 async fn wrong_api_hello_is_rejected() {
786 let (sock, _guard) = test_endpoint("wrongapi");
787 let listener = bind_local(&sock).unwrap();
788 tokio::spawn(async move {
789 let mut listener = listener;
790 let stream = listener.accept().await.unwrap();
791 let (_r, mut w) = split_local(stream);
792 write_frame(
793 &mut w,
794 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
795 )
796 .await
797 .unwrap();
798 w.flush().await.unwrap();
799 });
800 match connect_control(&sock).await {
801 Err(ClientError::WrongApi { got, want }) => {
802 assert_eq!(got, "other/1");
803 assert_eq!(want, API_NAME);
804 }
805 other => panic!("expected WrongApi, got {other:?}"),
806 }
807 }
808
809 #[tokio::test]
810 async fn blob_fetch_and_publish_deserialize_typed_results() {
811 use crate::protocol::{BlobFetchResult, BlobPublishResult};
812 let (sock, _guard) = test_endpoint("blob");
813 let listener = bind_local(&sock).unwrap();
814 let server = tokio::spawn(async move {
815 let mut listener = listener;
816 let stream = listener.accept().await.unwrap();
817 let (read_half, mut writer) = split_local(stream);
818 write_frame(
819 &mut writer,
820 &serde_json::to_value(Hello {
821 api: API_NAME.into(),
822 api_version: API_VERSION.into(),
823 api_minor: 0,
824 stack_version: "0.1.0".into(),
825 })
826 .unwrap(),
827 )
828 .await
829 .unwrap();
830 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
831 let req = match reader.next().await.unwrap().unwrap() {
833 Inbound::Frame(v) => v,
834 Inbound::Violation(_) => panic!("violation"),
835 };
836 assert_eq!(req["method"], "blob_publish");
837 assert_eq!(req["params"]["scope"], "eng");
838 write_frame(
839 &mut writer,
840 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
841 )
842 .await
843 .unwrap();
844 let req = match reader.next().await.unwrap().unwrap() {
846 Inbound::Frame(v) => v,
847 Inbound::Violation(_) => panic!("violation"),
848 };
849 assert_eq!(req["method"], "blob_fetch");
850 assert_eq!(req["params"]["ticket"], "blobT");
851 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
852 write_frame(
853 &mut writer,
854 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
855 )
856 .await
857 .unwrap();
858 let _ = (
859 BlobFetchResult {
860 hash: "cd".into(),
861 bytes_len: 7,
862 },
863 BlobPublishResult {
864 ticket: "blobT".into(),
865 hash: "ab".into(),
866 },
867 );
868 });
869
870 let mut client = connect_control(&sock).await.unwrap();
871 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
872 assert_eq!(pub_res.ticket, "blobT");
873 assert_eq!(pub_res.hash, "ab");
874 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
875 assert_eq!(fetch_res.hash, "cd");
876 assert_eq!(fetch_res.bytes_len, 7);
877 server.await.unwrap();
878 }
879
880 #[tokio::test]
887 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
888 use tokio::io::AsyncRead;
889
890 let (sock, _guard) = test_endpoint("pipelined");
891 let listener = bind_local(&sock).unwrap();
892 let server = tokio::spawn(async move {
893 let mut listener = listener;
894 let stream = listener.accept().await.unwrap();
895 let (read_half, mut writer) = split_local(stream);
896 let mut bytes = serde_json::to_vec(
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 .unwrap();
908 bytes.push(b'\n');
909 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
910 writer.write_all(&bytes).await.unwrap();
911 writer.flush().await.unwrap();
912 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
914 let req = match reader.next().await.unwrap().unwrap() {
915 Inbound::Frame(v) => v,
916 Inbound::Violation(_) => panic!("violation"),
917 };
918 assert_eq!(req["method"], "open_session");
919 });
920
921 let client = connect_control(&sock).await.unwrap();
922 let (reader, _writer) = client
923 .open_session("peer".into(), "kb".into())
924 .await
925 .unwrap();
926 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
928 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
929 match reframed.next().await.unwrap() {
930 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
931 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
932 }
933 server.await.unwrap();
934 }
935
936 #[tokio::test]
937 async fn blob_grant_issues_request_and_acks() {
938 let (sock, _guard) = test_endpoint("grant");
939 let listener = bind_local(&sock).unwrap();
940 let server = tokio::spawn(async move {
941 let mut listener = listener;
942 let stream = listener.accept().await.unwrap();
943 let (read_half, mut writer) = split_local(stream);
944 write_frame(
945 &mut writer,
946 &serde_json::to_value(Hello {
947 api: API_NAME.into(),
948 api_version: API_VERSION.into(),
949 api_minor: 0,
950 stack_version: "0.1.0".into(),
951 })
952 .unwrap(),
953 )
954 .await
955 .unwrap();
956 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
957 let req = match reader.next().await.unwrap().unwrap() {
958 Inbound::Frame(v) => v,
959 Inbound::Violation(_) => panic!("violation"),
960 };
961 assert_eq!(req["method"], "blob_grant");
962 assert_eq!(req["params"]["scope"], "kb-sync");
963 assert_eq!(req["params"]["principal"], "alice");
964 write_frame(
965 &mut writer,
966 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
967 )
968 .await
969 .unwrap();
970 });
971 let mut client = connect_control(&sock).await.unwrap();
972 client.blob_grant("kb-sync", "alice").await.unwrap();
973 server.await.unwrap();
974 }
975
976 #[tokio::test]
980 async fn typed_status_helper_deserializes_the_result() {
981 let (sock, _guard) = test_endpoint("typedstatus");
982 let listener = bind_local(&sock).unwrap();
983 let server = tokio::spawn(stub_daemon(listener));
984
985 let mut client = connect_control(&sock).await.unwrap();
986 let status = client.status().await.unwrap();
987 assert_eq!(status.stack_version, "0.1.0");
988 assert_eq!(status.services[0].name, "kb");
989 assert_eq!(status.services[0].backend, BackendKind::Socket);
990 assert!(status.peers.is_empty());
991 server.await.unwrap();
992 }
993
994 #[tokio::test]
997 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
998 let (sock, _guard) = test_endpoint("typedack");
999 let listener = bind_local(&sock).unwrap();
1000 let server = tokio::spawn(async move {
1001 let mut listener = listener;
1002 let stream = listener.accept().await.unwrap();
1003 let (read_half, mut writer) = split_local(stream);
1004 write_frame(
1005 &mut writer,
1006 &serde_json::to_value(Hello {
1007 api: API_NAME.into(),
1008 api_version: API_VERSION.into(),
1009 api_minor: 0,
1010 stack_version: "0.1.0".into(),
1011 })
1012 .unwrap(),
1013 )
1014 .await
1015 .unwrap();
1016 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1017 let req = match reader.next().await.unwrap().unwrap() {
1019 Inbound::Frame(v) => v,
1020 Inbound::Violation(_) => panic!("violation"),
1021 };
1022 assert_eq!(req["method"], "peer_remove");
1023 assert_eq!(req["params"]["nickname"], "bob");
1024 write_frame(
1025 &mut writer,
1026 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1027 )
1028 .await
1029 .unwrap();
1030 let req = match reader.next().await.unwrap().unwrap() {
1032 Inbound::Frame(v) => v,
1033 Inbound::Violation(_) => panic!("violation"),
1034 };
1035 assert_eq!(req["method"], "peer_rename");
1036 assert_eq!(req["params"]["to"], "Bobby");
1037 write_frame(
1038 &mut writer,
1039 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1040 )
1041 .await
1042 .unwrap();
1043 });
1044
1045 let mut client = connect_control(&sock).await.unwrap();
1046 client.peer_remove("bob").await.unwrap();
1047 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1048 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1049 other => panic!("expected Api error, got {other:?}"),
1050 }
1051 server.await.unwrap();
1052 }
1053
1054 #[tokio::test]
1057 async fn typed_subscribe_yields_frames_then_end() {
1058 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1059
1060 let (sock, _guard) = test_endpoint("subscribe");
1061 let listener = bind_local(&sock).unwrap();
1062 let server = tokio::spawn(async move {
1063 let mut listener = listener;
1064 let stream = listener.accept().await.unwrap();
1065 let (read_half, mut writer) = split_local(stream);
1066 write_frame(
1067 &mut writer,
1068 &serde_json::to_value(Hello {
1069 api: API_NAME.into(),
1070 api_version: API_VERSION.into(),
1071 api_minor: 0,
1072 stack_version: "0.1.0".into(),
1073 })
1074 .unwrap(),
1075 )
1076 .await
1077 .unwrap();
1078 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1079 let req = match reader.next().await.unwrap().unwrap() {
1080 Inbound::Frame(v) => v,
1081 Inbound::Violation(_) => panic!("violation"),
1082 };
1083 assert_eq!(req["method"], "subscribe");
1084 for frame in [
1085 StreamFrame::Snapshot {
1086 self_network: None,
1087 active_sessions: vec![ActiveSession {
1088 peer: "bob".into(),
1089 service: "notes".into(),
1090 opened_at: 7,
1091 principal: Some("eid:bob".into()),
1092 }],
1093 reachability: vec![PeerReachability {
1094 name: "bob".into(),
1095 reachable: true,
1096 rtt_ms: Some(42),
1097 age_secs: Some(3),
1098 meta: String::new(),
1099 principal: None,
1100 path: Default::default(),
1101 }],
1102 },
1103 StreamFrame::Event {
1104 record: Box::new(AuditRecord::session_open(
1105 "2026-07-03T14:02:11.480Z".into(),
1106 Some("bob".into()),
1107 "notes".into(),
1108 None,
1109 )),
1110 },
1111 StreamFrame::Lagged { dropped: 12 },
1112 ] {
1113 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1114 .await
1115 .unwrap();
1116 }
1117 writer.flush().await.unwrap();
1118 });
1120
1121 let client = connect_control(&sock).await.unwrap();
1122 let mut sub = client.subscribe().await.unwrap();
1123 match sub.next().await.unwrap().unwrap() {
1124 StreamFrame::Snapshot {
1125 active_sessions,
1126 reachability,
1127 ..
1128 } => {
1129 assert_eq!(active_sessions[0].peer, "bob");
1130 assert_eq!(reachability[0].rtt_ms, Some(42));
1131 }
1132 other => panic!("expected the snapshot first, got {other:?}"),
1133 }
1134 match sub.next().await.unwrap().unwrap() {
1135 StreamFrame::Event { record } => {
1136 assert_eq!(record.peer.as_deref(), Some("bob"));
1137 assert_eq!(record.service.as_deref(), Some("notes"));
1138 }
1139 other => panic!("expected the event, got {other:?}"),
1140 }
1141 assert_eq!(
1142 sub.next().await.unwrap(),
1143 Some(StreamFrame::Lagged { dropped: 12 })
1144 );
1145 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1146 server.await.unwrap();
1147 }
1148}