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