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.pair_opts(invite_line, as_nickname, false).await
326 }
327
328 pub async fn pair_opts(
341 &mut self,
342 invite_line: &str,
343 as_nickname: Option<String>,
344 allow_self_enroll: bool,
345 ) -> Result<PairResult, ClientError> {
346 self.request_typed(
347 Request::Pair(PairParams {
348 invite_line: invite_line.to_string(),
349 as_nickname,
350 allow_self_enroll,
351 }),
352 "pair result",
353 )
354 .await
355 }
356
357 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
360 self.request_ack(Request::PeerRemove(PeerRemoveParams {
361 nickname: nickname.to_string(),
362 }))
363 .await
364 }
365
366 pub async fn peer_rename(
371 &mut self,
372 user_id: Option<String>,
373 nickname: Option<String>,
374 to: &str,
375 ) -> Result<(), ClientError> {
376 self.request_ack(Request::PeerRename(PeerRenameParams {
377 user_id,
378 nickname,
379 to: to.to_string(),
380 }))
381 .await
382 }
383
384 pub async fn roster_install(
387 &mut self,
388 path: &str,
389 org_root_pk: Option<String>,
390 ) -> Result<RosterInstallResult, ClientError> {
391 self.request_typed(
392 Request::RosterInstall(RosterInstallParams {
393 path: path.to_string(),
394 org_root_pk,
395 }),
396 "roster_install result",
397 )
398 .await
399 }
400
401 pub async fn roster_members(
411 &mut self,
412 ) -> Result<crate::protocol::RosterMembersResult, ClientError> {
413 self.request_typed(Request::RosterMembers, "roster_members result")
414 .await
415 }
416
417 pub async fn org_create(
426 &mut self,
427 name: &str,
428 expires_secs: Option<i64>,
429 roster_url: Option<String>,
430 ) -> Result<crate::protocol::OrgCreateResult, ClientError> {
431 self.request_typed(
432 Request::OrgCreate(crate::protocol::OrgCreateParams {
433 name: name.to_string(),
434 expires_secs,
435 roster_url,
436 }),
437 "org_create result",
438 )
439 .await
440 }
441
442 pub async fn org_approve(
453 &mut self,
454 join_code: &str,
455 groups: Vec<String>,
456 user_id: Option<String>,
457 ) -> Result<crate::protocol::OrgApproveResult, ClientError> {
458 self.request_typed(
459 Request::OrgApprove(crate::protocol::OrgApproveParams {
460 join_code: join_code.to_string(),
461 groups,
462 user_id,
463 }),
464 "org_approve result",
465 )
466 .await
467 }
468
469 pub async fn org_join_code(
482 &mut self,
483 join_code: &str,
484 ) -> Result<crate::protocol::OrgJoinCodeResult, ClientError> {
485 self.request_typed(
486 Request::OrgJoinCode(crate::protocol::OrgJoinCodeParams {
487 join_code: join_code.to_string(),
488 }),
489 "org_join_code result",
490 )
491 .await
492 }
493
494 pub async fn org_revoke(
502 &mut self,
503 target: &str,
504 user_key: bool,
505 ) -> Result<crate::protocol::OrgRevokeResult, ClientError> {
506 self.request_typed(
507 Request::OrgRevoke(crate::protocol::OrgRevokeParams {
508 target: target.to_string(),
509 user_key,
510 }),
511 "org_revoke result",
512 )
513 .await
514 }
515
516 pub async fn org_join(
519 &mut self,
520 org_id: &str,
521 org_root_pk: &str,
522 user_id: &str,
523 user_key: &str,
524 ) -> Result<OrgJoinResult, ClientError> {
525 self.request_typed(
526 Request::OrgJoin(OrgJoinParams {
527 org_id: org_id.to_string(),
528 org_root_pk: org_root_pk.to_string(),
529 user_id: user_id.to_string(),
530 user_key: user_key.to_string(),
531 }),
532 "org_join result",
533 )
534 .await
535 }
536
537 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
540 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
541 url: url.to_string(),
542 }))
543 .await
544 }
545
546 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
550 self.request_typed::<PeerServicesResult>(
551 Request::PeerServices(PeerServicesParams {
552 peer: peer.to_string(),
553 }),
554 "peer_services",
555 )
556 .await
557 .map(|r| r.services)
558 }
559
560 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
564 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
565 name: name.to_string(),
566 }))
567 .await
568 }
569
570 pub async fn service_allow_grant(
573 &mut self,
574 service: &str,
575 principal: &str,
576 ) -> Result<(), ClientError> {
577 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
578 service: service.to_string(),
579 principal: principal.to_string(),
580 }))
581 .await
582 }
583
584 pub async fn service_allow_revoke(
588 &mut self,
589 service: &str,
590 principal: &str,
591 ) -> Result<(), ClientError> {
592 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
593 service: service.to_string(),
594 principal: principal.to_string(),
595 }))
596 .await
597 }
598
599 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
603 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
604 metadata: metadata.to_string(),
605 }))
606 .await
607 }
608
609 pub async fn set_relays(
618 &mut self,
619 relay_urls: &[String],
620 ) -> Result<SetRelaysResult, ClientError> {
621 self.request_typed::<SetRelaysResult>(
622 Request::SetRelays(SetRelaysParams {
623 relay_urls: relay_urls.to_vec(),
624 }),
625 "set_relays",
626 )
627 .await
628 }
629
630 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
634 self.request_ack(Request::SetNickname(SetNicknameParams {
635 nickname: nickname.to_string(),
636 }))
637 .await
638 }
639
640 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
643 self.request_typed(Request::AuditSummary, "audit_summary result")
644 .await
645 }
646
647 pub async fn blob_publish(
649 &mut self,
650 scope: &str,
651 path: &str,
652 ) -> Result<BlobPublishResult, ClientError> {
653 self.request_typed(
654 Request::BlobPublish(BlobPublishParams {
655 scope: scope.to_string(),
656 path: path.to_string(),
657 }),
658 "blob_publish result",
659 )
660 .await
661 }
662
663 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
668 self.blob_list_paged(Default::default()).await
669 }
670
671 pub async fn blob_list_paged(
673 &mut self,
674 params: crate::BlobListParams,
675 ) -> Result<BlobScopeList, ClientError> {
676 self.request_typed(Request::BlobList(params), "blob_list result")
677 .await
678 }
679
680 pub async fn blob_fetch(
683 &mut self,
684 ticket: &str,
685 dest_path: &str,
686 ) -> Result<BlobFetchResult, ClientError> {
687 self.request_typed(
688 Request::BlobFetch(BlobFetchParams {
689 ticket: ticket.to_string(),
690 dest_path: dest_path.to_string(),
691 }),
692 "blob_fetch result",
693 )
694 .await
695 }
696
697 pub async fn blob_fetch_cancel(
709 &mut self,
710 hash: &str,
711 ) -> Result<BlobFetchCancelResult, ClientError> {
712 self.request_typed(
713 Request::BlobFetchCancel(BlobFetchCancelParams {
714 hash: hash.to_string(),
715 }),
716 "blob_fetch_cancel result",
717 )
718 .await
719 }
720
721 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
727 self.request_ack(Request::BlobGrant(BlobGrantParams {
728 scope: scope.to_string(),
729 principal: principal.to_string(),
730 }))
731 .await
732 }
733
734 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
739 let (reader, writer) = self.open_stream("subscribe").await?;
740 Ok(StreamSubscription {
741 reader,
742 _writer: writer,
743 })
744 }
745}
746
747pub struct StreamSubscription {
752 reader: FrameReader<ControlRead>,
753 _writer: ControlWrite,
754}
755
756impl std::fmt::Debug for StreamSubscription {
758 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
759 f.debug_struct("StreamSubscription").finish_non_exhaustive()
760 }
761}
762
763impl StreamSubscription {
764 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
769 match self.reader.next().await? {
770 Some(Inbound::Frame(v)) => serde_json::from_value(v)
771 .map(Some)
772 .map_err(|_| ClientError::Malformed("stream frame")),
773 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
774 None => Ok(None),
775 }
776 }
777}
778
779pub async fn connect_control_io(
783 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
784 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
785) -> Result<ControlClient, ClientError> {
786 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
787 let hello: Hello = match reader.next().await? {
788 Some(Inbound::Frame(v)) => {
789 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
790 }
791 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
792 None => return Err(ClientError::Closed("hello")),
793 };
794 if hello.api != crate::protocol::API_NAME {
795 return Err(ClientError::WrongApi {
796 got: hello.api,
797 want: crate::protocol::API_NAME,
798 });
799 }
800 Ok(ControlClient {
801 hello,
802 reader,
803 writer: Box::new(writer) as ControlWrite,
804 })
805}
806
807pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
809 let stream = connect_local(path).await?;
810 let (read_half, write_half) = split_local(stream);
811 connect_control_io(read_half, write_half).await
812}
813
814pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
819 connect_control(&crate::paths::default_endpoint()?).await
820}
821
822#[cfg(all(test, feature = "service"))]
830mod tests {
831 use super::*;
832 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
833 use crate::transport::{LocalListener, bind_local, split_local};
834 use tokio::io::AsyncWriteExt;
835
836 #[cfg(unix)]
841 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
842 let dir = tempfile::tempdir().unwrap();
843 let path = dir.path().join(format!("{tag}.sock"));
844 (path, dir)
845 }
846 #[cfg(windows)]
847 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
848 use std::sync::atomic::{AtomicU64, Ordering};
849 static SEQ: AtomicU64 = AtomicU64::new(0);
850 let n = SEQ.fetch_add(1, Ordering::Relaxed);
851 let path = std::path::PathBuf::from(format!(
852 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
853 std::process::id()
854 ));
855 (path, ())
856 }
857
858 async fn stub_daemon(mut listener: LocalListener) {
860 let stream = listener.accept().await.unwrap();
861 let (read_half, mut writer) = split_local(stream);
862 write_frame(
863 &mut writer,
864 &serde_json::to_value(Hello {
865 api: API_NAME.into(),
866 api_version: API_VERSION.into(),
867 api_minor: 0,
868 stack_version: "0.1.0".into(),
869 })
870 .unwrap(),
871 )
872 .await
873 .unwrap();
874 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
875 let req = match reader.next().await.unwrap().unwrap() {
876 Inbound::Frame(v) => v,
877 Inbound::Violation(_) => panic!("violation"),
878 };
879 assert_eq!(req["method"], "status");
880 let result = StatusResult {
881 stack_version: "0.1.0".into(),
882 services: vec![ServiceInfo {
883 name: "kb".into(),
884 allow: vec![],
885 allow_display: vec![],
886 backend: BackendKind::Socket,
887 ephemeral: false,
888 }],
889 peers: vec![],
890 roster: None,
891 presence: vec![],
892 self_user_id: None,
893 recent_pairings: vec![],
894 reachability: vec![],
895 self_nickname: String::new(),
896 storage: None,
897 self_network: None,
898 };
899 write_frame(
900 &mut writer,
901 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
902 )
903 .await
904 .unwrap();
905 writer.flush().await.unwrap();
906 }
907
908 #[tokio::test]
911 async fn connect_control_io_handshakes_over_a_duplex() {
912 let (client_io, mut server_io) = tokio::io::duplex(4096);
913 tokio::spawn(async move {
914 write_frame(
915 &mut server_io,
916 &serde_json::to_value(Hello {
917 api: API_NAME.into(),
918 api_version: API_VERSION.into(),
919 api_minor: 0,
920 stack_version: "in-proc".into(),
921 })
922 .unwrap(),
923 )
924 .await
925 .unwrap();
926 });
927 let (r, w) = tokio::io::split(client_io);
928 let client = connect_control_io(r, w).await.expect("handshake");
929 assert_eq!(client.hello().stack_version, "in-proc");
930 }
931
932 #[tokio::test]
933 async fn connect_reads_hello_asserts_api_and_requests() {
934 let (sock, _guard) = test_endpoint("status");
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 assert_eq!(client.hello().api, API_NAME);
940 let result = client.request(Request::Status).await.unwrap();
941 assert_eq!(result["services"][0]["name"], "kb");
942 assert_eq!(result["services"][0]["backend"], "socket");
943 server.await.unwrap();
944 }
945
946 #[tokio::test]
947 async fn wrong_api_hello_is_rejected() {
948 let (sock, _guard) = test_endpoint("wrongapi");
949 let listener = bind_local(&sock).unwrap();
950 tokio::spawn(async move {
951 let mut listener = listener;
952 let stream = listener.accept().await.unwrap();
953 let (_r, mut w) = split_local(stream);
954 write_frame(
955 &mut w,
956 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
957 )
958 .await
959 .unwrap();
960 w.flush().await.unwrap();
961 });
962 match connect_control(&sock).await {
963 Err(ClientError::WrongApi { got, want }) => {
964 assert_eq!(got, "other/1");
965 assert_eq!(want, API_NAME);
966 }
967 other => panic!("expected WrongApi, got {other:?}"),
968 }
969 }
970
971 #[tokio::test]
972 async fn blob_fetch_and_publish_deserialize_typed_results() {
973 use crate::protocol::{BlobFetchResult, BlobPublishResult};
974 let (sock, _guard) = test_endpoint("blob");
975 let listener = bind_local(&sock).unwrap();
976 let server = tokio::spawn(async move {
977 let mut listener = listener;
978 let stream = listener.accept().await.unwrap();
979 let (read_half, mut writer) = split_local(stream);
980 write_frame(
981 &mut writer,
982 &serde_json::to_value(Hello {
983 api: API_NAME.into(),
984 api_version: API_VERSION.into(),
985 api_minor: 0,
986 stack_version: "0.1.0".into(),
987 })
988 .unwrap(),
989 )
990 .await
991 .unwrap();
992 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
993 let req = match reader.next().await.unwrap().unwrap() {
995 Inbound::Frame(v) => v,
996 Inbound::Violation(_) => panic!("violation"),
997 };
998 assert_eq!(req["method"], "blob_publish");
999 assert_eq!(req["params"]["scope"], "eng");
1000 write_frame(
1001 &mut writer,
1002 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
1003 )
1004 .await
1005 .unwrap();
1006 let req = match reader.next().await.unwrap().unwrap() {
1008 Inbound::Frame(v) => v,
1009 Inbound::Violation(_) => panic!("violation"),
1010 };
1011 assert_eq!(req["method"], "blob_fetch");
1012 assert_eq!(req["params"]["ticket"], "blobT");
1013 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
1014 write_frame(
1015 &mut writer,
1016 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
1017 )
1018 .await
1019 .unwrap();
1020 let _ = (
1021 BlobFetchResult {
1022 hash: "cd".into(),
1023 bytes_len: 7,
1024 },
1025 BlobPublishResult {
1026 ticket: "blobT".into(),
1027 hash: "ab".into(),
1028 },
1029 );
1030 });
1031
1032 let mut client = connect_control(&sock).await.unwrap();
1033 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
1034 assert_eq!(pub_res.ticket, "blobT");
1035 assert_eq!(pub_res.hash, "ab");
1036 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
1037 assert_eq!(fetch_res.hash, "cd");
1038 assert_eq!(fetch_res.bytes_len, 7);
1039 server.await.unwrap();
1040 }
1041
1042 #[tokio::test]
1049 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
1050 use tokio::io::AsyncRead;
1051
1052 let (sock, _guard) = test_endpoint("pipelined");
1053 let listener = bind_local(&sock).unwrap();
1054 let server = tokio::spawn(async move {
1055 let mut listener = listener;
1056 let stream = listener.accept().await.unwrap();
1057 let (read_half, mut writer) = split_local(stream);
1058 let mut bytes = serde_json::to_vec(
1061 &serde_json::to_value(Hello {
1062 api: API_NAME.into(),
1063 api_version: API_VERSION.into(),
1064 api_minor: 0,
1065 stack_version: "0.1.0".into(),
1066 })
1067 .unwrap(),
1068 )
1069 .unwrap();
1070 bytes.push(b'\n');
1071 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
1072 writer.write_all(&bytes).await.unwrap();
1073 writer.flush().await.unwrap();
1074 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1076 let req = match reader.next().await.unwrap().unwrap() {
1077 Inbound::Frame(v) => v,
1078 Inbound::Violation(_) => panic!("violation"),
1079 };
1080 assert_eq!(req["method"], "open_session");
1081 });
1082
1083 let client = connect_control(&sock).await.unwrap();
1084 let (reader, _writer) = client
1085 .open_session("peer".into(), "kb".into())
1086 .await
1087 .unwrap();
1088 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
1090 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
1091 match reframed.next().await.unwrap() {
1092 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
1093 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
1094 }
1095 server.await.unwrap();
1096 }
1097
1098 #[tokio::test]
1099 async fn blob_grant_issues_request_and_acks() {
1100 let (sock, _guard) = test_endpoint("grant");
1101 let listener = bind_local(&sock).unwrap();
1102 let server = tokio::spawn(async move {
1103 let mut listener = listener;
1104 let stream = listener.accept().await.unwrap();
1105 let (read_half, mut writer) = split_local(stream);
1106 write_frame(
1107 &mut writer,
1108 &serde_json::to_value(Hello {
1109 api: API_NAME.into(),
1110 api_version: API_VERSION.into(),
1111 api_minor: 0,
1112 stack_version: "0.1.0".into(),
1113 })
1114 .unwrap(),
1115 )
1116 .await
1117 .unwrap();
1118 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1119 let req = match reader.next().await.unwrap().unwrap() {
1120 Inbound::Frame(v) => v,
1121 Inbound::Violation(_) => panic!("violation"),
1122 };
1123 assert_eq!(req["method"], "blob_grant");
1124 assert_eq!(req["params"]["scope"], "kb-sync");
1125 assert_eq!(req["params"]["principal"], "alice");
1126 write_frame(
1127 &mut writer,
1128 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
1129 )
1130 .await
1131 .unwrap();
1132 });
1133 let mut client = connect_control(&sock).await.unwrap();
1134 client.blob_grant("kb-sync", "alice").await.unwrap();
1135 server.await.unwrap();
1136 }
1137
1138 #[tokio::test]
1142 async fn typed_status_helper_deserializes_the_result() {
1143 let (sock, _guard) = test_endpoint("typedstatus");
1144 let listener = bind_local(&sock).unwrap();
1145 let server = tokio::spawn(stub_daemon(listener));
1146
1147 let mut client = connect_control(&sock).await.unwrap();
1148 let status = client.status().await.unwrap();
1149 assert_eq!(status.stack_version, "0.1.0");
1150 assert_eq!(status.services[0].name, "kb");
1151 assert_eq!(status.services[0].backend, BackendKind::Socket);
1152 assert!(status.peers.is_empty());
1153 server.await.unwrap();
1154 }
1155
1156 #[tokio::test]
1159 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
1160 let (sock, _guard) = test_endpoint("typedack");
1161 let listener = bind_local(&sock).unwrap();
1162 let server = tokio::spawn(async move {
1163 let mut listener = listener;
1164 let stream = listener.accept().await.unwrap();
1165 let (read_half, mut writer) = split_local(stream);
1166 write_frame(
1167 &mut writer,
1168 &serde_json::to_value(Hello {
1169 api: API_NAME.into(),
1170 api_version: API_VERSION.into(),
1171 api_minor: 0,
1172 stack_version: "0.1.0".into(),
1173 })
1174 .unwrap(),
1175 )
1176 .await
1177 .unwrap();
1178 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1179 let req = match reader.next().await.unwrap().unwrap() {
1181 Inbound::Frame(v) => v,
1182 Inbound::Violation(_) => panic!("violation"),
1183 };
1184 assert_eq!(req["method"], "peer_remove");
1185 assert_eq!(req["params"]["nickname"], "bob");
1186 write_frame(
1187 &mut writer,
1188 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1189 )
1190 .await
1191 .unwrap();
1192 let req = match reader.next().await.unwrap().unwrap() {
1194 Inbound::Frame(v) => v,
1195 Inbound::Violation(_) => panic!("violation"),
1196 };
1197 assert_eq!(req["method"], "peer_rename");
1198 assert_eq!(req["params"]["to"], "Bobby");
1199 write_frame(
1200 &mut writer,
1201 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1202 )
1203 .await
1204 .unwrap();
1205 });
1206
1207 let mut client = connect_control(&sock).await.unwrap();
1208 client.peer_remove("bob").await.unwrap();
1209 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1210 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1211 other => panic!("expected Api error, got {other:?}"),
1212 }
1213 server.await.unwrap();
1214 }
1215
1216 #[tokio::test]
1219 async fn typed_subscribe_yields_frames_then_end() {
1220 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1221
1222 let (sock, _guard) = test_endpoint("subscribe");
1223 let listener = bind_local(&sock).unwrap();
1224 let server = tokio::spawn(async move {
1225 let mut listener = listener;
1226 let stream = listener.accept().await.unwrap();
1227 let (read_half, mut writer) = split_local(stream);
1228 write_frame(
1229 &mut writer,
1230 &serde_json::to_value(Hello {
1231 api: API_NAME.into(),
1232 api_version: API_VERSION.into(),
1233 api_minor: 0,
1234 stack_version: "0.1.0".into(),
1235 })
1236 .unwrap(),
1237 )
1238 .await
1239 .unwrap();
1240 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1241 let req = match reader.next().await.unwrap().unwrap() {
1242 Inbound::Frame(v) => v,
1243 Inbound::Violation(_) => panic!("violation"),
1244 };
1245 assert_eq!(req["method"], "subscribe");
1246 for frame in [
1247 StreamFrame::Snapshot {
1248 self_network: None,
1249 active_sessions: vec![ActiveSession {
1250 peer: "bob".into(),
1251 service: "notes".into(),
1252 opened_at: 7,
1253 principal: Some("eid:bob".into()),
1254 }],
1255 reachability: vec![PeerReachability {
1256 name: "bob".into(),
1257 reachable: true,
1258 rtt_ms: Some(42),
1259 age_secs: Some(3),
1260 meta: String::new(),
1261 principal: None,
1262 path: Default::default(),
1263 }],
1264 },
1265 StreamFrame::Event {
1266 record: Box::new(AuditRecord::session_open(
1267 "2026-07-03T14:02:11.480Z".into(),
1268 Some("bob".into()),
1269 "notes".into(),
1270 None,
1271 )),
1272 },
1273 StreamFrame::Lagged { dropped: 12 },
1274 ] {
1275 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1276 .await
1277 .unwrap();
1278 }
1279 writer.flush().await.unwrap();
1280 });
1282
1283 let client = connect_control(&sock).await.unwrap();
1284 let mut sub = client.subscribe().await.unwrap();
1285 match sub.next().await.unwrap().unwrap() {
1286 StreamFrame::Snapshot {
1287 active_sessions,
1288 reachability,
1289 ..
1290 } => {
1291 assert_eq!(active_sessions[0].peer, "bob");
1292 assert_eq!(reachability[0].rtt_ms, Some(42));
1293 }
1294 other => panic!("expected the snapshot first, got {other:?}"),
1295 }
1296 match sub.next().await.unwrap().unwrap() {
1297 StreamFrame::Event { record } => {
1298 assert_eq!(record.peer.as_deref(), Some("bob"));
1299 assert_eq!(record.service.as_deref(), Some("notes"));
1300 }
1301 other => panic!("expected the event, got {other:?}"),
1302 }
1303 assert_eq!(
1304 sub.next().await.unwrap(),
1305 Some(StreamFrame::Lagged { dropped: 12 })
1306 );
1307 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1308 server.await.unwrap();
1309 }
1310}