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