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, BlobFetchCancelParams, BlobFetchCancelResult, BlobFetchParams,
13 BlobFetchResult, BlobGrantParams, BlobPublishParams, BlobPublishResult, BlobScopeList, Hello,
14 InviteParams, InviteResult, OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams,
15 PairResult, PeerEndorseParams, PeerEndorseResult, PeerIntroduceParams, PeerRemoveParams,
16 PeerRenameParams, PeerServicesParams, PeerServicesResult, RegisterServiceParams, Request,
17 RosterInstallParams, RosterInstallResult, ServiceAllowParams, SetAppMetadataParams,
18 SetNicknameParams, SetRelaysParams, SetRelaysResult, SetRosterUrlParams, StatusResult,
19 StreamFrame, UnregisterServiceParams,
20};
21use crate::transport::{connect_local, split_local};
22
23pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
27pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
29
30pub struct ControlClient {
32 hello: Hello,
33 reader: FrameReader<ControlRead>,
34 writer: ControlWrite,
35}
36
37impl std::fmt::Debug for ControlClient {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.debug_struct("ControlClient")
42 .field("hello", &self.hello)
43 .finish_non_exhaustive()
44 }
45}
46
47#[derive(Debug)]
54pub enum ClientError {
55 Io(std::io::Error),
56 Closed(&'static str),
57 Malformed(&'static str),
58 WrongApi { got: String, want: &'static str },
59 Api(Value),
60}
61
62impl std::fmt::Display for ClientError {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 match self {
65 ClientError::Io(err) => write!(f, "io: {err}"),
66 ClientError::Closed(what) => write!(f, "connection closed before {what}"),
67 ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
68 ClientError::WrongApi { got, want } => {
69 write!(f, "unexpected api: got {got:?}, want {want:?}")
70 }
71 ClientError::Api(err) => write!(f, "control API error: {err}"),
72 }
73 }
74}
75
76impl std::error::Error for ClientError {}
77
78impl From<std::io::Error> for ClientError {
79 fn from(err: std::io::Error) -> Self {
80 ClientError::Io(err)
81 }
82}
83
84impl ControlClient {
85 pub fn hello(&self) -> &Hello {
86 &self.hello
87 }
88
89 pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
92 let frame = serde_json::to_value(&request).expect("Request serializes");
93 self.request_value(&frame).await
94 }
95
96 pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
101 write_frame(&mut self.writer, request).await?;
102 match self.reader.next().await? {
103 Some(Inbound::Frame(resp)) => {
104 if let Some(err) = resp.get("error") {
105 return Err(ClientError::Api(err.clone()));
106 }
107 Ok(resp.get("result").cloned().unwrap_or(Value::Null))
108 }
109 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
110 None => Err(ClientError::Closed("response")),
111 }
112 }
113
114 pub async fn open_session(
121 mut self,
122 peer: String,
123 service: String,
124 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
125 let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
126 .expect("Request serializes");
127 write_frame(&mut self.writer, &frame).await?;
128 Ok((self.reader, self.writer))
129 }
130
131 pub async fn open_stream(
139 mut self,
140 method: &str,
141 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
142 let frame = serde_json::json!({ "method": method });
143 write_frame(&mut self.writer, &frame).await?;
144 Ok((self.reader, self.writer))
145 }
146
147 async fn request_typed<T: serde::de::DeserializeOwned>(
152 &mut self,
153 request: Request,
154 what: &'static str,
155 ) -> Result<T, ClientError> {
156 let v = self.request(request).await?;
157 serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
158 }
159
160 async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
163 self.request(request).await.map(|_| ())
164 }
165
166 pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
169 self.request_typed(Request::Status, "status result").await
170 }
171
172 pub async fn register_service(
175 &mut self,
176 name: &str,
177 backend: BackendSpec,
178 allow: Vec<String>,
179 ) -> Result<(), ClientError> {
180 self.register_service_with(name, backend, allow, false)
181 .await
182 }
183
184 pub async fn register_service_with(
189 &mut self,
190 name: &str,
191 backend: BackendSpec,
192 allow: Vec<String>,
193 ephemeral: bool,
194 ) -> Result<(), ClientError> {
195 self.request_ack(Request::RegisterService(RegisterServiceParams {
196 name: name.to_string(),
197 backend,
198 allow,
199 ephemeral,
200 rate_limit_per_min: None,
201 }))
202 .await
203 }
204
205 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
209 self.invite_with(services, None).await
210 }
211
212 pub async fn invite_with(
215 &mut self,
216 services: Vec<String>,
217 app_label: Option<String>,
218 ) -> Result<InviteResult, ClientError> {
219 self.invite_multi(services, app_label, None).await
220 }
221
222 pub async fn invite_multi(
230 &mut self,
231 services: Vec<String>,
232 app_label: Option<String>,
233 max_uses: Option<u32>,
234 ) -> Result<InviteResult, ClientError> {
235 self.invite_named(services, app_label, max_uses, None).await
236 }
237
238 pub async fn invite_named(
244 &mut self,
245 services: Vec<String>,
246 app_label: Option<String>,
247 max_uses: Option<u32>,
248 peer_nickname: Option<String>,
249 ) -> Result<InviteResult, ClientError> {
250 self.invite_full(services, app_label, max_uses, peer_nickname, false)
251 .await
252 }
253
254 pub async fn invite_full(
260 &mut self,
261 services: Vec<String>,
262 app_label: Option<String>,
263 max_uses: Option<u32>,
264 peer_nickname: Option<String>,
265 as_self: bool,
266 ) -> Result<InviteResult, ClientError> {
267 self.request_typed(
268 Request::Invite(InviteParams {
269 services,
270 app_label,
271 max_uses,
272 peer_nickname,
273 as_self,
274 }),
275 "invite result",
276 )
277 .await
278 }
279
280 pub async fn endorse_peer(
285 &mut self,
286 subject: &str,
287 subject_user_id: Option<String>,
288 ) -> Result<PeerEndorseResult, ClientError> {
289 self.request_typed(
290 Request::PeerEndorse(PeerEndorseParams {
291 subject: subject.to_string(),
292 subject_user_id,
293 }),
294 "peer endorse result",
295 )
296 .await
297 }
298
299 pub async fn introduce_peer(&mut self, params: PeerIntroduceParams) -> Result<(), ClientError> {
305 self.request_ack(Request::PeerIntroduce(params)).await
306 }
307
308 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
311 self.pair_as(invite_line, None).await
312 }
313
314 pub async fn pair_as(
321 &mut self,
322 invite_line: &str,
323 as_nickname: Option<String>,
324 ) -> Result<PairResult, ClientError> {
325 self.request_typed(
326 Request::Pair(PairParams {
327 invite_line: invite_line.to_string(),
328 as_nickname,
329 }),
330 "pair result",
331 )
332 .await
333 }
334
335 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
338 self.request_ack(Request::PeerRemove(PeerRemoveParams {
339 nickname: nickname.to_string(),
340 }))
341 .await
342 }
343
344 pub async fn peer_rename(
349 &mut self,
350 user_id: Option<String>,
351 nickname: Option<String>,
352 to: &str,
353 ) -> Result<(), ClientError> {
354 self.request_ack(Request::PeerRename(PeerRenameParams {
355 user_id,
356 nickname,
357 to: to.to_string(),
358 }))
359 .await
360 }
361
362 pub async fn roster_install(
365 &mut self,
366 path: &str,
367 org_root_pk: Option<String>,
368 ) -> Result<RosterInstallResult, ClientError> {
369 self.request_typed(
370 Request::RosterInstall(RosterInstallParams {
371 path: path.to_string(),
372 org_root_pk,
373 }),
374 "roster_install result",
375 )
376 .await
377 }
378
379 pub async fn org_join(
382 &mut self,
383 org_id: &str,
384 org_root_pk: &str,
385 user_id: &str,
386 user_key: &str,
387 ) -> Result<OrgJoinResult, ClientError> {
388 self.request_typed(
389 Request::OrgJoin(OrgJoinParams {
390 org_id: org_id.to_string(),
391 org_root_pk: org_root_pk.to_string(),
392 user_id: user_id.to_string(),
393 user_key: user_key.to_string(),
394 }),
395 "org_join result",
396 )
397 .await
398 }
399
400 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
403 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
404 url: url.to_string(),
405 }))
406 .await
407 }
408
409 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
413 self.request_typed::<PeerServicesResult>(
414 Request::PeerServices(PeerServicesParams {
415 peer: peer.to_string(),
416 }),
417 "peer_services",
418 )
419 .await
420 .map(|r| r.services)
421 }
422
423 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
427 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
428 name: name.to_string(),
429 }))
430 .await
431 }
432
433 pub async fn service_allow_grant(
436 &mut self,
437 service: &str,
438 principal: &str,
439 ) -> Result<(), ClientError> {
440 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
441 service: service.to_string(),
442 principal: principal.to_string(),
443 }))
444 .await
445 }
446
447 pub async fn service_allow_revoke(
451 &mut self,
452 service: &str,
453 principal: &str,
454 ) -> Result<(), ClientError> {
455 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
456 service: service.to_string(),
457 principal: principal.to_string(),
458 }))
459 .await
460 }
461
462 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
466 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
467 metadata: metadata.to_string(),
468 }))
469 .await
470 }
471
472 pub async fn set_relays(
481 &mut self,
482 relay_urls: &[String],
483 ) -> Result<SetRelaysResult, ClientError> {
484 self.request_typed::<SetRelaysResult>(
485 Request::SetRelays(SetRelaysParams {
486 relay_urls: relay_urls.to_vec(),
487 }),
488 "set_relays",
489 )
490 .await
491 }
492
493 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
497 self.request_ack(Request::SetNickname(SetNicknameParams {
498 nickname: nickname.to_string(),
499 }))
500 .await
501 }
502
503 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
506 self.request_typed(Request::AuditSummary, "audit_summary result")
507 .await
508 }
509
510 pub async fn blob_publish(
512 &mut self,
513 scope: &str,
514 path: &str,
515 ) -> Result<BlobPublishResult, ClientError> {
516 self.request_typed(
517 Request::BlobPublish(BlobPublishParams {
518 scope: scope.to_string(),
519 path: path.to_string(),
520 }),
521 "blob_publish result",
522 )
523 .await
524 }
525
526 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
531 self.blob_list_paged(Default::default()).await
532 }
533
534 pub async fn blob_list_paged(
536 &mut self,
537 params: crate::BlobListParams,
538 ) -> Result<BlobScopeList, ClientError> {
539 self.request_typed(Request::BlobList(params), "blob_list result")
540 .await
541 }
542
543 pub async fn blob_fetch(
546 &mut self,
547 ticket: &str,
548 dest_path: &str,
549 ) -> Result<BlobFetchResult, ClientError> {
550 self.request_typed(
551 Request::BlobFetch(BlobFetchParams {
552 ticket: ticket.to_string(),
553 dest_path: dest_path.to_string(),
554 }),
555 "blob_fetch result",
556 )
557 .await
558 }
559
560 pub async fn blob_fetch_cancel(
572 &mut self,
573 hash: &str,
574 ) -> Result<BlobFetchCancelResult, ClientError> {
575 self.request_typed(
576 Request::BlobFetchCancel(BlobFetchCancelParams {
577 hash: hash.to_string(),
578 }),
579 "blob_fetch_cancel result",
580 )
581 .await
582 }
583
584 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
590 self.request_ack(Request::BlobGrant(BlobGrantParams {
591 scope: scope.to_string(),
592 principal: principal.to_string(),
593 }))
594 .await
595 }
596
597 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
602 let (reader, writer) = self.open_stream("subscribe").await?;
603 Ok(StreamSubscription {
604 reader,
605 _writer: writer,
606 })
607 }
608}
609
610pub struct StreamSubscription {
615 reader: FrameReader<ControlRead>,
616 _writer: ControlWrite,
617}
618
619impl std::fmt::Debug for StreamSubscription {
621 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
622 f.debug_struct("StreamSubscription").finish_non_exhaustive()
623 }
624}
625
626impl StreamSubscription {
627 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
632 match self.reader.next().await? {
633 Some(Inbound::Frame(v)) => serde_json::from_value(v)
634 .map(Some)
635 .map_err(|_| ClientError::Malformed("stream frame")),
636 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
637 None => Ok(None),
638 }
639 }
640}
641
642pub async fn connect_control_io(
646 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
647 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
648) -> Result<ControlClient, ClientError> {
649 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
650 let hello: Hello = match reader.next().await? {
651 Some(Inbound::Frame(v)) => {
652 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
653 }
654 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
655 None => return Err(ClientError::Closed("hello")),
656 };
657 if hello.api != crate::protocol::API_NAME {
658 return Err(ClientError::WrongApi {
659 got: hello.api,
660 want: crate::protocol::API_NAME,
661 });
662 }
663 Ok(ControlClient {
664 hello,
665 reader,
666 writer: Box::new(writer) as ControlWrite,
667 })
668}
669
670pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
672 let stream = connect_local(path).await?;
673 let (read_half, write_half) = split_local(stream);
674 connect_control_io(read_half, write_half).await
675}
676
677pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
682 connect_control(&crate::paths::default_endpoint()?).await
683}
684
685#[cfg(all(test, feature = "service"))]
693mod tests {
694 use super::*;
695 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
696 use crate::transport::{LocalListener, bind_local, split_local};
697 use tokio::io::AsyncWriteExt;
698
699 #[cfg(unix)]
704 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
705 let dir = tempfile::tempdir().unwrap();
706 let path = dir.path().join(format!("{tag}.sock"));
707 (path, dir)
708 }
709 #[cfg(windows)]
710 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
711 use std::sync::atomic::{AtomicU64, Ordering};
712 static SEQ: AtomicU64 = AtomicU64::new(0);
713 let n = SEQ.fetch_add(1, Ordering::Relaxed);
714 let path = std::path::PathBuf::from(format!(
715 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
716 std::process::id()
717 ));
718 (path, ())
719 }
720
721 async fn stub_daemon(mut listener: LocalListener) {
723 let stream = listener.accept().await.unwrap();
724 let (read_half, mut writer) = split_local(stream);
725 write_frame(
726 &mut writer,
727 &serde_json::to_value(Hello {
728 api: API_NAME.into(),
729 api_version: API_VERSION.into(),
730 api_minor: 0,
731 stack_version: "0.1.0".into(),
732 })
733 .unwrap(),
734 )
735 .await
736 .unwrap();
737 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
738 let req = match reader.next().await.unwrap().unwrap() {
739 Inbound::Frame(v) => v,
740 Inbound::Violation(_) => panic!("violation"),
741 };
742 assert_eq!(req["method"], "status");
743 let result = StatusResult {
744 stack_version: "0.1.0".into(),
745 services: vec![ServiceInfo {
746 name: "kb".into(),
747 allow: vec![],
748 allow_display: vec![],
749 backend: BackendKind::Socket,
750 ephemeral: false,
751 }],
752 peers: vec![],
753 roster: None,
754 presence: vec![],
755 self_user_id: None,
756 recent_pairings: vec![],
757 reachability: vec![],
758 self_nickname: String::new(),
759 storage: None,
760 self_network: None,
761 };
762 write_frame(
763 &mut writer,
764 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
765 )
766 .await
767 .unwrap();
768 writer.flush().await.unwrap();
769 }
770
771 #[tokio::test]
774 async fn connect_control_io_handshakes_over_a_duplex() {
775 let (client_io, mut server_io) = tokio::io::duplex(4096);
776 tokio::spawn(async move {
777 write_frame(
778 &mut server_io,
779 &serde_json::to_value(Hello {
780 api: API_NAME.into(),
781 api_version: API_VERSION.into(),
782 api_minor: 0,
783 stack_version: "in-proc".into(),
784 })
785 .unwrap(),
786 )
787 .await
788 .unwrap();
789 });
790 let (r, w) = tokio::io::split(client_io);
791 let client = connect_control_io(r, w).await.expect("handshake");
792 assert_eq!(client.hello().stack_version, "in-proc");
793 }
794
795 #[tokio::test]
796 async fn connect_reads_hello_asserts_api_and_requests() {
797 let (sock, _guard) = test_endpoint("status");
798 let listener = bind_local(&sock).unwrap();
799 let server = tokio::spawn(stub_daemon(listener));
800
801 let mut client = connect_control(&sock).await.unwrap();
802 assert_eq!(client.hello().api, API_NAME);
803 let result = client.request(Request::Status).await.unwrap();
804 assert_eq!(result["services"][0]["name"], "kb");
805 assert_eq!(result["services"][0]["backend"], "socket");
806 server.await.unwrap();
807 }
808
809 #[tokio::test]
810 async fn wrong_api_hello_is_rejected() {
811 let (sock, _guard) = test_endpoint("wrongapi");
812 let listener = bind_local(&sock).unwrap();
813 tokio::spawn(async move {
814 let mut listener = listener;
815 let stream = listener.accept().await.unwrap();
816 let (_r, mut w) = split_local(stream);
817 write_frame(
818 &mut w,
819 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
820 )
821 .await
822 .unwrap();
823 w.flush().await.unwrap();
824 });
825 match connect_control(&sock).await {
826 Err(ClientError::WrongApi { got, want }) => {
827 assert_eq!(got, "other/1");
828 assert_eq!(want, API_NAME);
829 }
830 other => panic!("expected WrongApi, got {other:?}"),
831 }
832 }
833
834 #[tokio::test]
835 async fn blob_fetch_and_publish_deserialize_typed_results() {
836 use crate::protocol::{BlobFetchResult, BlobPublishResult};
837 let (sock, _guard) = test_endpoint("blob");
838 let listener = bind_local(&sock).unwrap();
839 let server = tokio::spawn(async move {
840 let mut listener = listener;
841 let stream = listener.accept().await.unwrap();
842 let (read_half, mut writer) = split_local(stream);
843 write_frame(
844 &mut writer,
845 &serde_json::to_value(Hello {
846 api: API_NAME.into(),
847 api_version: API_VERSION.into(),
848 api_minor: 0,
849 stack_version: "0.1.0".into(),
850 })
851 .unwrap(),
852 )
853 .await
854 .unwrap();
855 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
856 let req = match reader.next().await.unwrap().unwrap() {
858 Inbound::Frame(v) => v,
859 Inbound::Violation(_) => panic!("violation"),
860 };
861 assert_eq!(req["method"], "blob_publish");
862 assert_eq!(req["params"]["scope"], "eng");
863 write_frame(
864 &mut writer,
865 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
866 )
867 .await
868 .unwrap();
869 let req = match reader.next().await.unwrap().unwrap() {
871 Inbound::Frame(v) => v,
872 Inbound::Violation(_) => panic!("violation"),
873 };
874 assert_eq!(req["method"], "blob_fetch");
875 assert_eq!(req["params"]["ticket"], "blobT");
876 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
877 write_frame(
878 &mut writer,
879 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
880 )
881 .await
882 .unwrap();
883 let _ = (
884 BlobFetchResult {
885 hash: "cd".into(),
886 bytes_len: 7,
887 },
888 BlobPublishResult {
889 ticket: "blobT".into(),
890 hash: "ab".into(),
891 },
892 );
893 });
894
895 let mut client = connect_control(&sock).await.unwrap();
896 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
897 assert_eq!(pub_res.ticket, "blobT");
898 assert_eq!(pub_res.hash, "ab");
899 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
900 assert_eq!(fetch_res.hash, "cd");
901 assert_eq!(fetch_res.bytes_len, 7);
902 server.await.unwrap();
903 }
904
905 #[tokio::test]
912 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
913 use tokio::io::AsyncRead;
914
915 let (sock, _guard) = test_endpoint("pipelined");
916 let listener = bind_local(&sock).unwrap();
917 let server = tokio::spawn(async move {
918 let mut listener = listener;
919 let stream = listener.accept().await.unwrap();
920 let (read_half, mut writer) = split_local(stream);
921 let mut bytes = serde_json::to_vec(
924 &serde_json::to_value(Hello {
925 api: API_NAME.into(),
926 api_version: API_VERSION.into(),
927 api_minor: 0,
928 stack_version: "0.1.0".into(),
929 })
930 .unwrap(),
931 )
932 .unwrap();
933 bytes.push(b'\n');
934 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
935 writer.write_all(&bytes).await.unwrap();
936 writer.flush().await.unwrap();
937 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"], "open_session");
944 });
945
946 let client = connect_control(&sock).await.unwrap();
947 let (reader, _writer) = client
948 .open_session("peer".into(), "kb".into())
949 .await
950 .unwrap();
951 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
953 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
954 match reframed.next().await.unwrap() {
955 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
956 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
957 }
958 server.await.unwrap();
959 }
960
961 #[tokio::test]
962 async fn blob_grant_issues_request_and_acks() {
963 let (sock, _guard) = test_endpoint("grant");
964 let listener = bind_local(&sock).unwrap();
965 let server = tokio::spawn(async move {
966 let mut listener = listener;
967 let stream = listener.accept().await.unwrap();
968 let (read_half, mut writer) = split_local(stream);
969 write_frame(
970 &mut writer,
971 &serde_json::to_value(Hello {
972 api: API_NAME.into(),
973 api_version: API_VERSION.into(),
974 api_minor: 0,
975 stack_version: "0.1.0".into(),
976 })
977 .unwrap(),
978 )
979 .await
980 .unwrap();
981 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
982 let req = match reader.next().await.unwrap().unwrap() {
983 Inbound::Frame(v) => v,
984 Inbound::Violation(_) => panic!("violation"),
985 };
986 assert_eq!(req["method"], "blob_grant");
987 assert_eq!(req["params"]["scope"], "kb-sync");
988 assert_eq!(req["params"]["principal"], "alice");
989 write_frame(
990 &mut writer,
991 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
992 )
993 .await
994 .unwrap();
995 });
996 let mut client = connect_control(&sock).await.unwrap();
997 client.blob_grant("kb-sync", "alice").await.unwrap();
998 server.await.unwrap();
999 }
1000
1001 #[tokio::test]
1005 async fn typed_status_helper_deserializes_the_result() {
1006 let (sock, _guard) = test_endpoint("typedstatus");
1007 let listener = bind_local(&sock).unwrap();
1008 let server = tokio::spawn(stub_daemon(listener));
1009
1010 let mut client = connect_control(&sock).await.unwrap();
1011 let status = client.status().await.unwrap();
1012 assert_eq!(status.stack_version, "0.1.0");
1013 assert_eq!(status.services[0].name, "kb");
1014 assert_eq!(status.services[0].backend, BackendKind::Socket);
1015 assert!(status.peers.is_empty());
1016 server.await.unwrap();
1017 }
1018
1019 #[tokio::test]
1022 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
1023 let (sock, _guard) = test_endpoint("typedack");
1024 let listener = bind_local(&sock).unwrap();
1025 let server = tokio::spawn(async move {
1026 let mut listener = listener;
1027 let stream = listener.accept().await.unwrap();
1028 let (read_half, mut writer) = split_local(stream);
1029 write_frame(
1030 &mut writer,
1031 &serde_json::to_value(Hello {
1032 api: API_NAME.into(),
1033 api_version: API_VERSION.into(),
1034 api_minor: 0,
1035 stack_version: "0.1.0".into(),
1036 })
1037 .unwrap(),
1038 )
1039 .await
1040 .unwrap();
1041 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1042 let req = match reader.next().await.unwrap().unwrap() {
1044 Inbound::Frame(v) => v,
1045 Inbound::Violation(_) => panic!("violation"),
1046 };
1047 assert_eq!(req["method"], "peer_remove");
1048 assert_eq!(req["params"]["nickname"], "bob");
1049 write_frame(
1050 &mut writer,
1051 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1052 )
1053 .await
1054 .unwrap();
1055 let req = match reader.next().await.unwrap().unwrap() {
1057 Inbound::Frame(v) => v,
1058 Inbound::Violation(_) => panic!("violation"),
1059 };
1060 assert_eq!(req["method"], "peer_rename");
1061 assert_eq!(req["params"]["to"], "Bobby");
1062 write_frame(
1063 &mut writer,
1064 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1065 )
1066 .await
1067 .unwrap();
1068 });
1069
1070 let mut client = connect_control(&sock).await.unwrap();
1071 client.peer_remove("bob").await.unwrap();
1072 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1073 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1074 other => panic!("expected Api error, got {other:?}"),
1075 }
1076 server.await.unwrap();
1077 }
1078
1079 #[tokio::test]
1082 async fn typed_subscribe_yields_frames_then_end() {
1083 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1084
1085 let (sock, _guard) = test_endpoint("subscribe");
1086 let listener = bind_local(&sock).unwrap();
1087 let server = tokio::spawn(async move {
1088 let mut listener = listener;
1089 let stream = listener.accept().await.unwrap();
1090 let (read_half, mut writer) = split_local(stream);
1091 write_frame(
1092 &mut writer,
1093 &serde_json::to_value(Hello {
1094 api: API_NAME.into(),
1095 api_version: API_VERSION.into(),
1096 api_minor: 0,
1097 stack_version: "0.1.0".into(),
1098 })
1099 .unwrap(),
1100 )
1101 .await
1102 .unwrap();
1103 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1104 let req = match reader.next().await.unwrap().unwrap() {
1105 Inbound::Frame(v) => v,
1106 Inbound::Violation(_) => panic!("violation"),
1107 };
1108 assert_eq!(req["method"], "subscribe");
1109 for frame in [
1110 StreamFrame::Snapshot {
1111 self_network: None,
1112 active_sessions: vec![ActiveSession {
1113 peer: "bob".into(),
1114 service: "notes".into(),
1115 opened_at: 7,
1116 principal: Some("eid:bob".into()),
1117 }],
1118 reachability: vec![PeerReachability {
1119 name: "bob".into(),
1120 reachable: true,
1121 rtt_ms: Some(42),
1122 age_secs: Some(3),
1123 meta: String::new(),
1124 principal: None,
1125 path: Default::default(),
1126 }],
1127 },
1128 StreamFrame::Event {
1129 record: Box::new(AuditRecord::session_open(
1130 "2026-07-03T14:02:11.480Z".into(),
1131 Some("bob".into()),
1132 "notes".into(),
1133 None,
1134 )),
1135 },
1136 StreamFrame::Lagged { dropped: 12 },
1137 ] {
1138 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1139 .await
1140 .unwrap();
1141 }
1142 writer.flush().await.unwrap();
1143 });
1145
1146 let client = connect_control(&sock).await.unwrap();
1147 let mut sub = client.subscribe().await.unwrap();
1148 match sub.next().await.unwrap().unwrap() {
1149 StreamFrame::Snapshot {
1150 active_sessions,
1151 reachability,
1152 ..
1153 } => {
1154 assert_eq!(active_sessions[0].peer, "bob");
1155 assert_eq!(reachability[0].rtt_ms, Some(42));
1156 }
1157 other => panic!("expected the snapshot first, got {other:?}"),
1158 }
1159 match sub.next().await.unwrap().unwrap() {
1160 StreamFrame::Event { record } => {
1161 assert_eq!(record.peer.as_deref(), Some("bob"));
1162 assert_eq!(record.service.as_deref(), Some("notes"));
1163 }
1164 other => panic!("expected the event, got {other:?}"),
1165 }
1166 assert_eq!(
1167 sub.next().await.unwrap(),
1168 Some(StreamFrame::Lagged { dropped: 12 })
1169 );
1170 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1171 server.await.unwrap();
1172 }
1173}