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.request_typed(
250 Request::Invite(InviteParams {
251 services,
252 app_label,
253 max_uses,
254 peer_nickname,
255 }),
256 "invite result",
257 )
258 .await
259 }
260
261 pub async fn endorse_peer(
266 &mut self,
267 subject: &str,
268 subject_user_id: Option<String>,
269 ) -> Result<PeerEndorseResult, ClientError> {
270 self.request_typed(
271 Request::PeerEndorse(PeerEndorseParams {
272 subject: subject.to_string(),
273 subject_user_id,
274 }),
275 "peer endorse result",
276 )
277 .await
278 }
279
280 pub async fn introduce_peer(&mut self, params: PeerIntroduceParams) -> Result<(), ClientError> {
286 self.request_ack(Request::PeerIntroduce(params)).await
287 }
288
289 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
292 self.pair_as(invite_line, None).await
293 }
294
295 pub async fn pair_as(
302 &mut self,
303 invite_line: &str,
304 as_nickname: Option<String>,
305 ) -> Result<PairResult, ClientError> {
306 self.request_typed(
307 Request::Pair(PairParams {
308 invite_line: invite_line.to_string(),
309 as_nickname,
310 }),
311 "pair result",
312 )
313 .await
314 }
315
316 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
319 self.request_ack(Request::PeerRemove(PeerRemoveParams {
320 nickname: nickname.to_string(),
321 }))
322 .await
323 }
324
325 pub async fn peer_rename(
330 &mut self,
331 user_id: Option<String>,
332 nickname: Option<String>,
333 to: &str,
334 ) -> Result<(), ClientError> {
335 self.request_ack(Request::PeerRename(PeerRenameParams {
336 user_id,
337 nickname,
338 to: to.to_string(),
339 }))
340 .await
341 }
342
343 pub async fn roster_install(
346 &mut self,
347 path: &str,
348 org_root_pk: Option<String>,
349 ) -> Result<RosterInstallResult, ClientError> {
350 self.request_typed(
351 Request::RosterInstall(RosterInstallParams {
352 path: path.to_string(),
353 org_root_pk,
354 }),
355 "roster_install result",
356 )
357 .await
358 }
359
360 pub async fn org_join(
363 &mut self,
364 org_id: &str,
365 org_root_pk: &str,
366 user_id: &str,
367 user_key: &str,
368 ) -> Result<OrgJoinResult, ClientError> {
369 self.request_typed(
370 Request::OrgJoin(OrgJoinParams {
371 org_id: org_id.to_string(),
372 org_root_pk: org_root_pk.to_string(),
373 user_id: user_id.to_string(),
374 user_key: user_key.to_string(),
375 }),
376 "org_join result",
377 )
378 .await
379 }
380
381 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
384 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
385 url: url.to_string(),
386 }))
387 .await
388 }
389
390 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
394 self.request_typed::<PeerServicesResult>(
395 Request::PeerServices(PeerServicesParams {
396 peer: peer.to_string(),
397 }),
398 "peer_services",
399 )
400 .await
401 .map(|r| r.services)
402 }
403
404 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
408 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
409 name: name.to_string(),
410 }))
411 .await
412 }
413
414 pub async fn service_allow_grant(
417 &mut self,
418 service: &str,
419 principal: &str,
420 ) -> Result<(), ClientError> {
421 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
422 service: service.to_string(),
423 principal: principal.to_string(),
424 }))
425 .await
426 }
427
428 pub async fn service_allow_revoke(
432 &mut self,
433 service: &str,
434 principal: &str,
435 ) -> Result<(), ClientError> {
436 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
437 service: service.to_string(),
438 principal: principal.to_string(),
439 }))
440 .await
441 }
442
443 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
447 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
448 metadata: metadata.to_string(),
449 }))
450 .await
451 }
452
453 pub async fn set_relays(
462 &mut self,
463 relay_urls: &[String],
464 ) -> Result<SetRelaysResult, ClientError> {
465 self.request_typed::<SetRelaysResult>(
466 Request::SetRelays(SetRelaysParams {
467 relay_urls: relay_urls.to_vec(),
468 }),
469 "set_relays",
470 )
471 .await
472 }
473
474 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
478 self.request_ack(Request::SetNickname(SetNicknameParams {
479 nickname: nickname.to_string(),
480 }))
481 .await
482 }
483
484 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
487 self.request_typed(Request::AuditSummary, "audit_summary result")
488 .await
489 }
490
491 pub async fn blob_publish(
493 &mut self,
494 scope: &str,
495 path: &str,
496 ) -> Result<BlobPublishResult, ClientError> {
497 self.request_typed(
498 Request::BlobPublish(BlobPublishParams {
499 scope: scope.to_string(),
500 path: path.to_string(),
501 }),
502 "blob_publish result",
503 )
504 .await
505 }
506
507 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
512 self.blob_list_paged(Default::default()).await
513 }
514
515 pub async fn blob_list_paged(
517 &mut self,
518 params: crate::BlobListParams,
519 ) -> Result<BlobScopeList, ClientError> {
520 self.request_typed(Request::BlobList(params), "blob_list result")
521 .await
522 }
523
524 pub async fn blob_fetch(
527 &mut self,
528 ticket: &str,
529 dest_path: &str,
530 ) -> Result<BlobFetchResult, ClientError> {
531 self.request_typed(
532 Request::BlobFetch(BlobFetchParams {
533 ticket: ticket.to_string(),
534 dest_path: dest_path.to_string(),
535 }),
536 "blob_fetch result",
537 )
538 .await
539 }
540
541 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
547 self.request_ack(Request::BlobGrant(BlobGrantParams {
548 scope: scope.to_string(),
549 principal: principal.to_string(),
550 }))
551 .await
552 }
553
554 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
559 let (reader, writer) = self.open_stream("subscribe").await?;
560 Ok(StreamSubscription {
561 reader,
562 _writer: writer,
563 })
564 }
565}
566
567pub struct StreamSubscription {
572 reader: FrameReader<ControlRead>,
573 _writer: ControlWrite,
574}
575
576impl std::fmt::Debug for StreamSubscription {
578 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
579 f.debug_struct("StreamSubscription").finish_non_exhaustive()
580 }
581}
582
583impl StreamSubscription {
584 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
589 match self.reader.next().await? {
590 Some(Inbound::Frame(v)) => serde_json::from_value(v)
591 .map(Some)
592 .map_err(|_| ClientError::Malformed("stream frame")),
593 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
594 None => Ok(None),
595 }
596 }
597}
598
599pub async fn connect_control_io(
603 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
604 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
605) -> Result<ControlClient, ClientError> {
606 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
607 let hello: Hello = match reader.next().await? {
608 Some(Inbound::Frame(v)) => {
609 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
610 }
611 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
612 None => return Err(ClientError::Closed("hello")),
613 };
614 if hello.api != crate::protocol::API_NAME {
615 return Err(ClientError::WrongApi {
616 got: hello.api,
617 want: crate::protocol::API_NAME,
618 });
619 }
620 Ok(ControlClient {
621 hello,
622 reader,
623 writer: Box::new(writer) as ControlWrite,
624 })
625}
626
627pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
629 let stream = connect_local(path).await?;
630 let (read_half, write_half) = split_local(stream);
631 connect_control_io(read_half, write_half).await
632}
633
634pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
639 connect_control(&crate::paths::default_endpoint()?).await
640}
641
642#[cfg(all(test, feature = "service"))]
650mod tests {
651 use super::*;
652 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
653 use crate::transport::{LocalListener, bind_local, split_local};
654 use tokio::io::AsyncWriteExt;
655
656 #[cfg(unix)]
661 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
662 let dir = tempfile::tempdir().unwrap();
663 let path = dir.path().join(format!("{tag}.sock"));
664 (path, dir)
665 }
666 #[cfg(windows)]
667 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
668 use std::sync::atomic::{AtomicU64, Ordering};
669 static SEQ: AtomicU64 = AtomicU64::new(0);
670 let n = SEQ.fetch_add(1, Ordering::Relaxed);
671 let path = std::path::PathBuf::from(format!(
672 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
673 std::process::id()
674 ));
675 (path, ())
676 }
677
678 async fn stub_daemon(mut listener: LocalListener) {
680 let stream = listener.accept().await.unwrap();
681 let (read_half, mut writer) = split_local(stream);
682 write_frame(
683 &mut writer,
684 &serde_json::to_value(Hello {
685 api: API_NAME.into(),
686 api_version: API_VERSION.into(),
687 api_minor: 0,
688 stack_version: "0.1.0".into(),
689 })
690 .unwrap(),
691 )
692 .await
693 .unwrap();
694 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
695 let req = match reader.next().await.unwrap().unwrap() {
696 Inbound::Frame(v) => v,
697 Inbound::Violation(_) => panic!("violation"),
698 };
699 assert_eq!(req["method"], "status");
700 let result = StatusResult {
701 stack_version: "0.1.0".into(),
702 services: vec![ServiceInfo {
703 name: "kb".into(),
704 allow: vec![],
705 allow_display: vec![],
706 backend: BackendKind::Socket,
707 ephemeral: false,
708 }],
709 peers: vec![],
710 roster: None,
711 presence: vec![],
712 self_user_id: None,
713 recent_pairings: vec![],
714 reachability: vec![],
715 self_nickname: String::new(),
716 storage: None,
717 self_network: None,
718 };
719 write_frame(
720 &mut writer,
721 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
722 )
723 .await
724 .unwrap();
725 writer.flush().await.unwrap();
726 }
727
728 #[tokio::test]
731 async fn connect_control_io_handshakes_over_a_duplex() {
732 let (client_io, mut server_io) = tokio::io::duplex(4096);
733 tokio::spawn(async move {
734 write_frame(
735 &mut server_io,
736 &serde_json::to_value(Hello {
737 api: API_NAME.into(),
738 api_version: API_VERSION.into(),
739 api_minor: 0,
740 stack_version: "in-proc".into(),
741 })
742 .unwrap(),
743 )
744 .await
745 .unwrap();
746 });
747 let (r, w) = tokio::io::split(client_io);
748 let client = connect_control_io(r, w).await.expect("handshake");
749 assert_eq!(client.hello().stack_version, "in-proc");
750 }
751
752 #[tokio::test]
753 async fn connect_reads_hello_asserts_api_and_requests() {
754 let (sock, _guard) = test_endpoint("status");
755 let listener = bind_local(&sock).unwrap();
756 let server = tokio::spawn(stub_daemon(listener));
757
758 let mut client = connect_control(&sock).await.unwrap();
759 assert_eq!(client.hello().api, API_NAME);
760 let result = client.request(Request::Status).await.unwrap();
761 assert_eq!(result["services"][0]["name"], "kb");
762 assert_eq!(result["services"][0]["backend"], "socket");
763 server.await.unwrap();
764 }
765
766 #[tokio::test]
767 async fn wrong_api_hello_is_rejected() {
768 let (sock, _guard) = test_endpoint("wrongapi");
769 let listener = bind_local(&sock).unwrap();
770 tokio::spawn(async move {
771 let mut listener = listener;
772 let stream = listener.accept().await.unwrap();
773 let (_r, mut w) = split_local(stream);
774 write_frame(
775 &mut w,
776 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
777 )
778 .await
779 .unwrap();
780 w.flush().await.unwrap();
781 });
782 match connect_control(&sock).await {
783 Err(ClientError::WrongApi { got, want }) => {
784 assert_eq!(got, "other/1");
785 assert_eq!(want, API_NAME);
786 }
787 other => panic!("expected WrongApi, got {other:?}"),
788 }
789 }
790
791 #[tokio::test]
792 async fn blob_fetch_and_publish_deserialize_typed_results() {
793 use crate::protocol::{BlobFetchResult, BlobPublishResult};
794 let (sock, _guard) = test_endpoint("blob");
795 let listener = bind_local(&sock).unwrap();
796 let server = tokio::spawn(async move {
797 let mut listener = listener;
798 let stream = listener.accept().await.unwrap();
799 let (read_half, mut writer) = split_local(stream);
800 write_frame(
801 &mut writer,
802 &serde_json::to_value(Hello {
803 api: API_NAME.into(),
804 api_version: API_VERSION.into(),
805 api_minor: 0,
806 stack_version: "0.1.0".into(),
807 })
808 .unwrap(),
809 )
810 .await
811 .unwrap();
812 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
813 let req = match reader.next().await.unwrap().unwrap() {
815 Inbound::Frame(v) => v,
816 Inbound::Violation(_) => panic!("violation"),
817 };
818 assert_eq!(req["method"], "blob_publish");
819 assert_eq!(req["params"]["scope"], "eng");
820 write_frame(
821 &mut writer,
822 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
823 )
824 .await
825 .unwrap();
826 let req = match reader.next().await.unwrap().unwrap() {
828 Inbound::Frame(v) => v,
829 Inbound::Violation(_) => panic!("violation"),
830 };
831 assert_eq!(req["method"], "blob_fetch");
832 assert_eq!(req["params"]["ticket"], "blobT");
833 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
834 write_frame(
835 &mut writer,
836 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
837 )
838 .await
839 .unwrap();
840 let _ = (
841 BlobFetchResult {
842 hash: "cd".into(),
843 bytes_len: 7,
844 },
845 BlobPublishResult {
846 ticket: "blobT".into(),
847 hash: "ab".into(),
848 },
849 );
850 });
851
852 let mut client = connect_control(&sock).await.unwrap();
853 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
854 assert_eq!(pub_res.ticket, "blobT");
855 assert_eq!(pub_res.hash, "ab");
856 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
857 assert_eq!(fetch_res.hash, "cd");
858 assert_eq!(fetch_res.bytes_len, 7);
859 server.await.unwrap();
860 }
861
862 #[tokio::test]
869 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
870 use tokio::io::AsyncRead;
871
872 let (sock, _guard) = test_endpoint("pipelined");
873 let listener = bind_local(&sock).unwrap();
874 let server = tokio::spawn(async move {
875 let mut listener = listener;
876 let stream = listener.accept().await.unwrap();
877 let (read_half, mut writer) = split_local(stream);
878 let mut bytes = serde_json::to_vec(
881 &serde_json::to_value(Hello {
882 api: API_NAME.into(),
883 api_version: API_VERSION.into(),
884 api_minor: 0,
885 stack_version: "0.1.0".into(),
886 })
887 .unwrap(),
888 )
889 .unwrap();
890 bytes.push(b'\n');
891 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
892 writer.write_all(&bytes).await.unwrap();
893 writer.flush().await.unwrap();
894 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
896 let req = match reader.next().await.unwrap().unwrap() {
897 Inbound::Frame(v) => v,
898 Inbound::Violation(_) => panic!("violation"),
899 };
900 assert_eq!(req["method"], "open_session");
901 });
902
903 let client = connect_control(&sock).await.unwrap();
904 let (reader, _writer) = client
905 .open_session("peer".into(), "kb".into())
906 .await
907 .unwrap();
908 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
910 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
911 match reframed.next().await.unwrap() {
912 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
913 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
914 }
915 server.await.unwrap();
916 }
917
918 #[tokio::test]
919 async fn blob_grant_issues_request_and_acks() {
920 let (sock, _guard) = test_endpoint("grant");
921 let listener = bind_local(&sock).unwrap();
922 let server = tokio::spawn(async move {
923 let mut listener = listener;
924 let stream = listener.accept().await.unwrap();
925 let (read_half, mut writer) = split_local(stream);
926 write_frame(
927 &mut writer,
928 &serde_json::to_value(Hello {
929 api: API_NAME.into(),
930 api_version: API_VERSION.into(),
931 api_minor: 0,
932 stack_version: "0.1.0".into(),
933 })
934 .unwrap(),
935 )
936 .await
937 .unwrap();
938 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
939 let req = match reader.next().await.unwrap().unwrap() {
940 Inbound::Frame(v) => v,
941 Inbound::Violation(_) => panic!("violation"),
942 };
943 assert_eq!(req["method"], "blob_grant");
944 assert_eq!(req["params"]["scope"], "kb-sync");
945 assert_eq!(req["params"]["principal"], "alice");
946 write_frame(
947 &mut writer,
948 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
949 )
950 .await
951 .unwrap();
952 });
953 let mut client = connect_control(&sock).await.unwrap();
954 client.blob_grant("kb-sync", "alice").await.unwrap();
955 server.await.unwrap();
956 }
957
958 #[tokio::test]
962 async fn typed_status_helper_deserializes_the_result() {
963 let (sock, _guard) = test_endpoint("typedstatus");
964 let listener = bind_local(&sock).unwrap();
965 let server = tokio::spawn(stub_daemon(listener));
966
967 let mut client = connect_control(&sock).await.unwrap();
968 let status = client.status().await.unwrap();
969 assert_eq!(status.stack_version, "0.1.0");
970 assert_eq!(status.services[0].name, "kb");
971 assert_eq!(status.services[0].backend, BackendKind::Socket);
972 assert!(status.peers.is_empty());
973 server.await.unwrap();
974 }
975
976 #[tokio::test]
979 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
980 let (sock, _guard) = test_endpoint("typedack");
981 let listener = bind_local(&sock).unwrap();
982 let server = tokio::spawn(async move {
983 let mut listener = listener;
984 let stream = listener.accept().await.unwrap();
985 let (read_half, mut writer) = split_local(stream);
986 write_frame(
987 &mut writer,
988 &serde_json::to_value(Hello {
989 api: API_NAME.into(),
990 api_version: API_VERSION.into(),
991 api_minor: 0,
992 stack_version: "0.1.0".into(),
993 })
994 .unwrap(),
995 )
996 .await
997 .unwrap();
998 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
999 let req = match reader.next().await.unwrap().unwrap() {
1001 Inbound::Frame(v) => v,
1002 Inbound::Violation(_) => panic!("violation"),
1003 };
1004 assert_eq!(req["method"], "peer_remove");
1005 assert_eq!(req["params"]["nickname"], "bob");
1006 write_frame(
1007 &mut writer,
1008 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1009 )
1010 .await
1011 .unwrap();
1012 let req = match reader.next().await.unwrap().unwrap() {
1014 Inbound::Frame(v) => v,
1015 Inbound::Violation(_) => panic!("violation"),
1016 };
1017 assert_eq!(req["method"], "peer_rename");
1018 assert_eq!(req["params"]["to"], "Bobby");
1019 write_frame(
1020 &mut writer,
1021 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1022 )
1023 .await
1024 .unwrap();
1025 });
1026
1027 let mut client = connect_control(&sock).await.unwrap();
1028 client.peer_remove("bob").await.unwrap();
1029 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1030 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1031 other => panic!("expected Api error, got {other:?}"),
1032 }
1033 server.await.unwrap();
1034 }
1035
1036 #[tokio::test]
1039 async fn typed_subscribe_yields_frames_then_end() {
1040 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1041
1042 let (sock, _guard) = test_endpoint("subscribe");
1043 let listener = bind_local(&sock).unwrap();
1044 let server = tokio::spawn(async move {
1045 let mut listener = listener;
1046 let stream = listener.accept().await.unwrap();
1047 let (read_half, mut writer) = split_local(stream);
1048 write_frame(
1049 &mut writer,
1050 &serde_json::to_value(Hello {
1051 api: API_NAME.into(),
1052 api_version: API_VERSION.into(),
1053 api_minor: 0,
1054 stack_version: "0.1.0".into(),
1055 })
1056 .unwrap(),
1057 )
1058 .await
1059 .unwrap();
1060 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1061 let req = match reader.next().await.unwrap().unwrap() {
1062 Inbound::Frame(v) => v,
1063 Inbound::Violation(_) => panic!("violation"),
1064 };
1065 assert_eq!(req["method"], "subscribe");
1066 for frame in [
1067 StreamFrame::Snapshot {
1068 self_network: None,
1069 active_sessions: vec![ActiveSession {
1070 peer: "bob".into(),
1071 service: "notes".into(),
1072 opened_at: 7,
1073 principal: Some("eid:bob".into()),
1074 }],
1075 reachability: vec![PeerReachability {
1076 name: "bob".into(),
1077 reachable: true,
1078 rtt_ms: Some(42),
1079 age_secs: Some(3),
1080 meta: String::new(),
1081 principal: None,
1082 path: Default::default(),
1083 }],
1084 },
1085 StreamFrame::Event {
1086 record: Box::new(AuditRecord::session_open(
1087 "2026-07-03T14:02:11.480Z".into(),
1088 Some("bob".into()),
1089 "notes".into(),
1090 None,
1091 )),
1092 },
1093 StreamFrame::Lagged { dropped: 12 },
1094 ] {
1095 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1096 .await
1097 .unwrap();
1098 }
1099 writer.flush().await.unwrap();
1100 });
1102
1103 let client = connect_control(&sock).await.unwrap();
1104 let mut sub = client.subscribe().await.unwrap();
1105 match sub.next().await.unwrap().unwrap() {
1106 StreamFrame::Snapshot {
1107 active_sessions,
1108 reachability,
1109 ..
1110 } => {
1111 assert_eq!(active_sessions[0].peer, "bob");
1112 assert_eq!(reachability[0].rtt_ms, Some(42));
1113 }
1114 other => panic!("expected the snapshot first, got {other:?}"),
1115 }
1116 match sub.next().await.unwrap().unwrap() {
1117 StreamFrame::Event { record } => {
1118 assert_eq!(record.peer.as_deref(), Some("bob"));
1119 assert_eq!(record.service.as_deref(), Some("notes"));
1120 }
1121 other => panic!("expected the event, got {other:?}"),
1122 }
1123 assert_eq!(
1124 sub.next().await.unwrap(),
1125 Some(StreamFrame::Lagged { dropped: 12 })
1126 );
1127 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1128 server.await.unwrap();
1129 }
1130}