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