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> {
431 self.request_typed(Request::BlobList, "blob_list result")
432 .await
433 }
434
435 pub async fn blob_fetch(
438 &mut self,
439 ticket: &str,
440 dest_path: &str,
441 ) -> Result<BlobFetchResult, ClientError> {
442 self.request_typed(
443 Request::BlobFetch(BlobFetchParams {
444 ticket: ticket.to_string(),
445 dest_path: dest_path.to_string(),
446 }),
447 "blob_fetch result",
448 )
449 .await
450 }
451
452 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
458 self.request_ack(Request::BlobGrant(BlobGrantParams {
459 scope: scope.to_string(),
460 principal: principal.to_string(),
461 }))
462 .await
463 }
464
465 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
470 let (reader, writer) = self.open_stream("subscribe").await?;
471 Ok(StreamSubscription {
472 reader,
473 _writer: writer,
474 })
475 }
476}
477
478pub struct StreamSubscription {
483 reader: FrameReader<ControlRead>,
484 _writer: ControlWrite,
485}
486
487impl std::fmt::Debug for StreamSubscription {
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 f.debug_struct("StreamSubscription").finish_non_exhaustive()
491 }
492}
493
494impl StreamSubscription {
495 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
500 match self.reader.next().await? {
501 Some(Inbound::Frame(v)) => serde_json::from_value(v)
502 .map(Some)
503 .map_err(|_| ClientError::Malformed("stream frame")),
504 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
505 None => Ok(None),
506 }
507 }
508}
509
510pub async fn connect_control_io(
514 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
515 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
516) -> Result<ControlClient, ClientError> {
517 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
518 let hello: Hello = match reader.next().await? {
519 Some(Inbound::Frame(v)) => {
520 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
521 }
522 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
523 None => return Err(ClientError::Closed("hello")),
524 };
525 if hello.api != crate::protocol::API_NAME {
526 return Err(ClientError::WrongApi {
527 got: hello.api,
528 want: crate::protocol::API_NAME,
529 });
530 }
531 Ok(ControlClient {
532 hello,
533 reader,
534 writer: Box::new(writer) as ControlWrite,
535 })
536}
537
538pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
540 let stream = connect_local(path).await?;
541 let (read_half, write_half) = split_local(stream);
542 connect_control_io(read_half, write_half).await
543}
544
545pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
550 connect_control(&crate::paths::default_endpoint()?).await
551}
552
553#[cfg(all(test, feature = "service"))]
561mod tests {
562 use super::*;
563 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
564 use crate::transport::{LocalListener, bind_local, split_local};
565 use tokio::io::AsyncWriteExt;
566
567 #[cfg(unix)]
572 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
573 let dir = tempfile::tempdir().unwrap();
574 let path = dir.path().join(format!("{tag}.sock"));
575 (path, dir)
576 }
577 #[cfg(windows)]
578 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
579 use std::sync::atomic::{AtomicU64, Ordering};
580 static SEQ: AtomicU64 = AtomicU64::new(0);
581 let n = SEQ.fetch_add(1, Ordering::Relaxed);
582 let path = std::path::PathBuf::from(format!(
583 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
584 std::process::id()
585 ));
586 (path, ())
587 }
588
589 async fn stub_daemon(mut listener: LocalListener) {
591 let stream = listener.accept().await.unwrap();
592 let (read_half, mut writer) = split_local(stream);
593 write_frame(
594 &mut writer,
595 &serde_json::to_value(Hello {
596 api: API_NAME.into(),
597 api_version: API_VERSION.into(),
598 api_minor: 0,
599 stack_version: "0.1.0".into(),
600 })
601 .unwrap(),
602 )
603 .await
604 .unwrap();
605 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
606 let req = match reader.next().await.unwrap().unwrap() {
607 Inbound::Frame(v) => v,
608 Inbound::Violation(_) => panic!("violation"),
609 };
610 assert_eq!(req["method"], "status");
611 let result = StatusResult {
612 stack_version: "0.1.0".into(),
613 services: vec![ServiceInfo {
614 name: "kb".into(),
615 allow: vec![],
616 allow_display: vec![],
617 backend: BackendKind::Socket,
618 ephemeral: false,
619 }],
620 peers: vec![],
621 roster: None,
622 presence: vec![],
623 self_user_id: None,
624 recent_pairings: vec![],
625 reachability: vec![],
626 self_nickname: String::new(),
627 };
628 write_frame(
629 &mut writer,
630 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
631 )
632 .await
633 .unwrap();
634 writer.flush().await.unwrap();
635 }
636
637 #[tokio::test]
640 async fn connect_control_io_handshakes_over_a_duplex() {
641 let (client_io, mut server_io) = tokio::io::duplex(4096);
642 tokio::spawn(async move {
643 write_frame(
644 &mut server_io,
645 &serde_json::to_value(Hello {
646 api: API_NAME.into(),
647 api_version: API_VERSION.into(),
648 api_minor: 0,
649 stack_version: "in-proc".into(),
650 })
651 .unwrap(),
652 )
653 .await
654 .unwrap();
655 });
656 let (r, w) = tokio::io::split(client_io);
657 let client = connect_control_io(r, w).await.expect("handshake");
658 assert_eq!(client.hello().stack_version, "in-proc");
659 }
660
661 #[tokio::test]
662 async fn connect_reads_hello_asserts_api_and_requests() {
663 let (sock, _guard) = test_endpoint("status");
664 let listener = bind_local(&sock).unwrap();
665 let server = tokio::spawn(stub_daemon(listener));
666
667 let mut client = connect_control(&sock).await.unwrap();
668 assert_eq!(client.hello().api, API_NAME);
669 let result = client.request(Request::Status).await.unwrap();
670 assert_eq!(result["services"][0]["name"], "kb");
671 assert_eq!(result["services"][0]["backend"], "socket");
672 server.await.unwrap();
673 }
674
675 #[tokio::test]
676 async fn wrong_api_hello_is_rejected() {
677 let (sock, _guard) = test_endpoint("wrongapi");
678 let listener = bind_local(&sock).unwrap();
679 tokio::spawn(async move {
680 let mut listener = listener;
681 let stream = listener.accept().await.unwrap();
682 let (_r, mut w) = split_local(stream);
683 write_frame(
684 &mut w,
685 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
686 )
687 .await
688 .unwrap();
689 w.flush().await.unwrap();
690 });
691 match connect_control(&sock).await {
692 Err(ClientError::WrongApi { got, want }) => {
693 assert_eq!(got, "other/1");
694 assert_eq!(want, API_NAME);
695 }
696 other => panic!("expected WrongApi, got {other:?}"),
697 }
698 }
699
700 #[tokio::test]
701 async fn blob_fetch_and_publish_deserialize_typed_results() {
702 use crate::protocol::{BlobFetchResult, BlobPublishResult};
703 let (sock, _guard) = test_endpoint("blob");
704 let listener = bind_local(&sock).unwrap();
705 let server = tokio::spawn(async move {
706 let mut listener = listener;
707 let stream = listener.accept().await.unwrap();
708 let (read_half, mut writer) = split_local(stream);
709 write_frame(
710 &mut writer,
711 &serde_json::to_value(Hello {
712 api: API_NAME.into(),
713 api_version: API_VERSION.into(),
714 api_minor: 0,
715 stack_version: "0.1.0".into(),
716 })
717 .unwrap(),
718 )
719 .await
720 .unwrap();
721 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
722 let req = match reader.next().await.unwrap().unwrap() {
724 Inbound::Frame(v) => v,
725 Inbound::Violation(_) => panic!("violation"),
726 };
727 assert_eq!(req["method"], "blob_publish");
728 assert_eq!(req["params"]["scope"], "eng");
729 write_frame(
730 &mut writer,
731 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
732 )
733 .await
734 .unwrap();
735 let req = match reader.next().await.unwrap().unwrap() {
737 Inbound::Frame(v) => v,
738 Inbound::Violation(_) => panic!("violation"),
739 };
740 assert_eq!(req["method"], "blob_fetch");
741 assert_eq!(req["params"]["ticket"], "blobT");
742 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
743 write_frame(
744 &mut writer,
745 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
746 )
747 .await
748 .unwrap();
749 let _ = (
750 BlobFetchResult {
751 hash: "cd".into(),
752 bytes_len: 7,
753 },
754 BlobPublishResult {
755 ticket: "blobT".into(),
756 hash: "ab".into(),
757 },
758 );
759 });
760
761 let mut client = connect_control(&sock).await.unwrap();
762 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
763 assert_eq!(pub_res.ticket, "blobT");
764 assert_eq!(pub_res.hash, "ab");
765 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
766 assert_eq!(fetch_res.hash, "cd");
767 assert_eq!(fetch_res.bytes_len, 7);
768 server.await.unwrap();
769 }
770
771 #[tokio::test]
778 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
779 use tokio::io::AsyncRead;
780
781 let (sock, _guard) = test_endpoint("pipelined");
782 let listener = bind_local(&sock).unwrap();
783 let server = tokio::spawn(async move {
784 let mut listener = listener;
785 let stream = listener.accept().await.unwrap();
786 let (read_half, mut writer) = split_local(stream);
787 let mut bytes = serde_json::to_vec(
790 &serde_json::to_value(Hello {
791 api: API_NAME.into(),
792 api_version: API_VERSION.into(),
793 api_minor: 0,
794 stack_version: "0.1.0".into(),
795 })
796 .unwrap(),
797 )
798 .unwrap();
799 bytes.push(b'\n');
800 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
801 writer.write_all(&bytes).await.unwrap();
802 writer.flush().await.unwrap();
803 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
805 let req = match reader.next().await.unwrap().unwrap() {
806 Inbound::Frame(v) => v,
807 Inbound::Violation(_) => panic!("violation"),
808 };
809 assert_eq!(req["method"], "open_session");
810 });
811
812 let client = connect_control(&sock).await.unwrap();
813 let (reader, _writer) = client
814 .open_session("peer".into(), "kb".into())
815 .await
816 .unwrap();
817 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
819 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
820 match reframed.next().await.unwrap() {
821 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
822 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
823 }
824 server.await.unwrap();
825 }
826
827 #[tokio::test]
828 async fn blob_grant_issues_request_and_acks() {
829 let (sock, _guard) = test_endpoint("grant");
830 let listener = bind_local(&sock).unwrap();
831 let server = tokio::spawn(async move {
832 let mut listener = listener;
833 let stream = listener.accept().await.unwrap();
834 let (read_half, mut writer) = split_local(stream);
835 write_frame(
836 &mut writer,
837 &serde_json::to_value(Hello {
838 api: API_NAME.into(),
839 api_version: API_VERSION.into(),
840 api_minor: 0,
841 stack_version: "0.1.0".into(),
842 })
843 .unwrap(),
844 )
845 .await
846 .unwrap();
847 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
848 let req = match reader.next().await.unwrap().unwrap() {
849 Inbound::Frame(v) => v,
850 Inbound::Violation(_) => panic!("violation"),
851 };
852 assert_eq!(req["method"], "blob_grant");
853 assert_eq!(req["params"]["scope"], "kb-sync");
854 assert_eq!(req["params"]["principal"], "alice");
855 write_frame(
856 &mut writer,
857 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
858 )
859 .await
860 .unwrap();
861 });
862 let mut client = connect_control(&sock).await.unwrap();
863 client.blob_grant("kb-sync", "alice").await.unwrap();
864 server.await.unwrap();
865 }
866
867 #[tokio::test]
871 async fn typed_status_helper_deserializes_the_result() {
872 let (sock, _guard) = test_endpoint("typedstatus");
873 let listener = bind_local(&sock).unwrap();
874 let server = tokio::spawn(stub_daemon(listener));
875
876 let mut client = connect_control(&sock).await.unwrap();
877 let status = client.status().await.unwrap();
878 assert_eq!(status.stack_version, "0.1.0");
879 assert_eq!(status.services[0].name, "kb");
880 assert_eq!(status.services[0].backend, BackendKind::Socket);
881 assert!(status.peers.is_empty());
882 server.await.unwrap();
883 }
884
885 #[tokio::test]
888 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
889 let (sock, _guard) = test_endpoint("typedack");
890 let listener = bind_local(&sock).unwrap();
891 let server = tokio::spawn(async move {
892 let mut listener = listener;
893 let stream = listener.accept().await.unwrap();
894 let (read_half, mut writer) = split_local(stream);
895 write_frame(
896 &mut writer,
897 &serde_json::to_value(Hello {
898 api: API_NAME.into(),
899 api_version: API_VERSION.into(),
900 api_minor: 0,
901 stack_version: "0.1.0".into(),
902 })
903 .unwrap(),
904 )
905 .await
906 .unwrap();
907 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
908 let req = match reader.next().await.unwrap().unwrap() {
910 Inbound::Frame(v) => v,
911 Inbound::Violation(_) => panic!("violation"),
912 };
913 assert_eq!(req["method"], "peer_remove");
914 assert_eq!(req["params"]["nickname"], "bob");
915 write_frame(
916 &mut writer,
917 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
918 )
919 .await
920 .unwrap();
921 let req = match reader.next().await.unwrap().unwrap() {
923 Inbound::Frame(v) => v,
924 Inbound::Violation(_) => panic!("violation"),
925 };
926 assert_eq!(req["method"], "peer_rename");
927 assert_eq!(req["params"]["to"], "Bobby");
928 write_frame(
929 &mut writer,
930 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
931 )
932 .await
933 .unwrap();
934 });
935
936 let mut client = connect_control(&sock).await.unwrap();
937 client.peer_remove("bob").await.unwrap();
938 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
939 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
940 other => panic!("expected Api error, got {other:?}"),
941 }
942 server.await.unwrap();
943 }
944
945 #[tokio::test]
948 async fn typed_subscribe_yields_frames_then_end() {
949 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
950
951 let (sock, _guard) = test_endpoint("subscribe");
952 let listener = bind_local(&sock).unwrap();
953 let server = tokio::spawn(async move {
954 let mut listener = listener;
955 let stream = listener.accept().await.unwrap();
956 let (read_half, mut writer) = split_local(stream);
957 write_frame(
958 &mut writer,
959 &serde_json::to_value(Hello {
960 api: API_NAME.into(),
961 api_version: API_VERSION.into(),
962 api_minor: 0,
963 stack_version: "0.1.0".into(),
964 })
965 .unwrap(),
966 )
967 .await
968 .unwrap();
969 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
970 let req = match reader.next().await.unwrap().unwrap() {
971 Inbound::Frame(v) => v,
972 Inbound::Violation(_) => panic!("violation"),
973 };
974 assert_eq!(req["method"], "subscribe");
975 for frame in [
976 StreamFrame::Snapshot {
977 active_sessions: vec![ActiveSession {
978 peer: "bob".into(),
979 service: "notes".into(),
980 opened_at: 7,
981 }],
982 reachability: vec![PeerReachability {
983 name: "bob".into(),
984 reachable: true,
985 rtt_ms: Some(42),
986 age_secs: Some(3),
987 meta: String::new(),
988 principal: None,
989 path: Default::default(),
990 }],
991 },
992 StreamFrame::Event {
993 record: Box::new(AuditRecord::session_open(
994 "2026-07-03T14:02:11.480Z".into(),
995 Some("bob".into()),
996 "notes".into(),
997 )),
998 },
999 StreamFrame::Lagged { dropped: 12 },
1000 ] {
1001 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1002 .await
1003 .unwrap();
1004 }
1005 writer.flush().await.unwrap();
1006 });
1008
1009 let client = connect_control(&sock).await.unwrap();
1010 let mut sub = client.subscribe().await.unwrap();
1011 match sub.next().await.unwrap().unwrap() {
1012 StreamFrame::Snapshot {
1013 active_sessions,
1014 reachability,
1015 } => {
1016 assert_eq!(active_sessions[0].peer, "bob");
1017 assert_eq!(reachability[0].rtt_ms, Some(42));
1018 }
1019 other => panic!("expected the snapshot first, got {other:?}"),
1020 }
1021 match sub.next().await.unwrap().unwrap() {
1022 StreamFrame::Event { record } => {
1023 assert_eq!(record.peer.as_deref(), Some("bob"));
1024 assert_eq!(record.service.as_deref(), Some("notes"));
1025 }
1026 other => panic!("expected the event, got {other:?}"),
1027 }
1028 assert_eq!(
1029 sub.next().await.unwrap(),
1030 Some(StreamFrame::Lagged { dropped: 12 })
1031 );
1032 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1033 server.await.unwrap();
1034 }
1035}