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 SetNicknameParams, 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 set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
314 self.request_ack(Request::SetNickname(SetNicknameParams {
315 nickname: nickname.to_string(),
316 }))
317 .await
318 }
319
320 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
323 self.request_typed(Request::AuditSummary, "audit_summary result")
324 .await
325 }
326
327 pub async fn blob_publish(
329 &mut self,
330 scope: &str,
331 path: &str,
332 ) -> Result<BlobPublishResult, ClientError> {
333 self.request_typed(
334 Request::BlobPublish(BlobPublishParams {
335 scope: scope.to_string(),
336 path: path.to_string(),
337 }),
338 "blob_publish result",
339 )
340 .await
341 }
342
343 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
345 self.request_typed(Request::BlobList, "blob_list result")
346 .await
347 }
348
349 pub async fn blob_fetch(
352 &mut self,
353 ticket: &str,
354 dest_path: &str,
355 ) -> Result<BlobFetchResult, ClientError> {
356 self.request_typed(
357 Request::BlobFetch(BlobFetchParams {
358 ticket: ticket.to_string(),
359 dest_path: dest_path.to_string(),
360 }),
361 "blob_fetch result",
362 )
363 .await
364 }
365
366 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
372 self.request_ack(Request::BlobGrant(BlobGrantParams {
373 scope: scope.to_string(),
374 principal: principal.to_string(),
375 }))
376 .await
377 }
378
379 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
384 let (reader, writer) = self.open_stream("subscribe").await?;
385 Ok(StreamSubscription {
386 reader,
387 _writer: writer,
388 })
389 }
390}
391
392pub struct StreamSubscription {
397 reader: FrameReader<ControlRead>,
398 _writer: ControlWrite,
399}
400
401impl std::fmt::Debug for StreamSubscription {
403 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404 f.debug_struct("StreamSubscription").finish_non_exhaustive()
405 }
406}
407
408impl StreamSubscription {
409 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
414 match self.reader.next().await? {
415 Some(Inbound::Frame(v)) => serde_json::from_value(v)
416 .map(Some)
417 .map_err(|_| ClientError::Malformed("stream frame")),
418 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
419 None => Ok(None),
420 }
421 }
422}
423
424pub async fn connect_control_io(
428 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
429 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
430) -> Result<ControlClient, ClientError> {
431 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
432 let hello: Hello = match reader.next().await? {
433 Some(Inbound::Frame(v)) => {
434 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
435 }
436 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
437 None => return Err(ClientError::Closed("hello")),
438 };
439 if hello.api != crate::protocol::API_NAME {
440 return Err(ClientError::WrongApi {
441 got: hello.api,
442 want: crate::protocol::API_NAME,
443 });
444 }
445 Ok(ControlClient {
446 hello,
447 reader,
448 writer: Box::new(writer) as ControlWrite,
449 })
450}
451
452pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
454 let stream = connect_local(path).await?;
455 let (read_half, write_half) = split_local(stream);
456 connect_control_io(read_half, write_half).await
457}
458
459pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
464 connect_control(&crate::paths::default_endpoint()?).await
465}
466
467#[cfg(all(test, feature = "service"))]
475mod tests {
476 use super::*;
477 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
478 use crate::transport::{LocalListener, bind_local, split_local};
479 use tokio::io::AsyncWriteExt;
480
481 #[cfg(unix)]
486 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
487 let dir = tempfile::tempdir().unwrap();
488 let path = dir.path().join(format!("{tag}.sock"));
489 (path, dir)
490 }
491 #[cfg(windows)]
492 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
493 use std::sync::atomic::{AtomicU64, Ordering};
494 static SEQ: AtomicU64 = AtomicU64::new(0);
495 let n = SEQ.fetch_add(1, Ordering::Relaxed);
496 let path = std::path::PathBuf::from(format!(
497 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
498 std::process::id()
499 ));
500 (path, ())
501 }
502
503 async fn stub_daemon(mut listener: LocalListener) {
505 let stream = listener.accept().await.unwrap();
506 let (read_half, mut writer) = split_local(stream);
507 write_frame(
508 &mut writer,
509 &serde_json::to_value(Hello {
510 api: API_NAME.into(),
511 api_version: API_VERSION.into(),
512 api_minor: 0,
513 stack_version: "0.1.0".into(),
514 })
515 .unwrap(),
516 )
517 .await
518 .unwrap();
519 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
520 let req = match reader.next().await.unwrap().unwrap() {
521 Inbound::Frame(v) => v,
522 Inbound::Violation(_) => panic!("violation"),
523 };
524 assert_eq!(req["method"], "status");
525 let result = StatusResult {
526 stack_version: "0.1.0".into(),
527 services: vec![ServiceInfo {
528 name: "kb".into(),
529 allow: vec![],
530 backend: BackendKind::Socket,
531 ephemeral: false,
532 }],
533 peers: vec![],
534 roster: None,
535 presence: vec![],
536 self_user_id: None,
537 recent_pairings: vec![],
538 reachability: vec![],
539 self_nickname: String::new(),
540 };
541 write_frame(
542 &mut writer,
543 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
544 )
545 .await
546 .unwrap();
547 writer.flush().await.unwrap();
548 }
549
550 #[tokio::test]
553 async fn connect_control_io_handshakes_over_a_duplex() {
554 let (client_io, mut server_io) = tokio::io::duplex(4096);
555 tokio::spawn(async move {
556 write_frame(
557 &mut server_io,
558 &serde_json::to_value(Hello {
559 api: API_NAME.into(),
560 api_version: API_VERSION.into(),
561 api_minor: 0,
562 stack_version: "in-proc".into(),
563 })
564 .unwrap(),
565 )
566 .await
567 .unwrap();
568 });
569 let (r, w) = tokio::io::split(client_io);
570 let client = connect_control_io(r, w).await.expect("handshake");
571 assert_eq!(client.hello().stack_version, "in-proc");
572 }
573
574 #[tokio::test]
575 async fn connect_reads_hello_asserts_api_and_requests() {
576 let (sock, _guard) = test_endpoint("status");
577 let listener = bind_local(&sock).unwrap();
578 let server = tokio::spawn(stub_daemon(listener));
579
580 let mut client = connect_control(&sock).await.unwrap();
581 assert_eq!(client.hello().api, API_NAME);
582 let result = client.request(Request::Status).await.unwrap();
583 assert_eq!(result["services"][0]["name"], "kb");
584 assert_eq!(result["services"][0]["backend"], "socket");
585 server.await.unwrap();
586 }
587
588 #[tokio::test]
589 async fn wrong_api_hello_is_rejected() {
590 let (sock, _guard) = test_endpoint("wrongapi");
591 let listener = bind_local(&sock).unwrap();
592 tokio::spawn(async move {
593 let mut listener = listener;
594 let stream = listener.accept().await.unwrap();
595 let (_r, mut w) = split_local(stream);
596 write_frame(
597 &mut w,
598 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
599 )
600 .await
601 .unwrap();
602 w.flush().await.unwrap();
603 });
604 match connect_control(&sock).await {
605 Err(ClientError::WrongApi { got, want }) => {
606 assert_eq!(got, "other/1");
607 assert_eq!(want, API_NAME);
608 }
609 other => panic!("expected WrongApi, got {other:?}"),
610 }
611 }
612
613 #[tokio::test]
614 async fn blob_fetch_and_publish_deserialize_typed_results() {
615 use crate::protocol::{BlobFetchResult, BlobPublishResult};
616 let (sock, _guard) = test_endpoint("blob");
617 let listener = bind_local(&sock).unwrap();
618 let server = tokio::spawn(async move {
619 let mut listener = listener;
620 let stream = listener.accept().await.unwrap();
621 let (read_half, mut writer) = split_local(stream);
622 write_frame(
623 &mut writer,
624 &serde_json::to_value(Hello {
625 api: API_NAME.into(),
626 api_version: API_VERSION.into(),
627 api_minor: 0,
628 stack_version: "0.1.0".into(),
629 })
630 .unwrap(),
631 )
632 .await
633 .unwrap();
634 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
635 let req = match reader.next().await.unwrap().unwrap() {
637 Inbound::Frame(v) => v,
638 Inbound::Violation(_) => panic!("violation"),
639 };
640 assert_eq!(req["method"], "blob_publish");
641 assert_eq!(req["params"]["scope"], "eng");
642 write_frame(
643 &mut writer,
644 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
645 )
646 .await
647 .unwrap();
648 let req = match reader.next().await.unwrap().unwrap() {
650 Inbound::Frame(v) => v,
651 Inbound::Violation(_) => panic!("violation"),
652 };
653 assert_eq!(req["method"], "blob_fetch");
654 assert_eq!(req["params"]["ticket"], "blobT");
655 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
656 write_frame(
657 &mut writer,
658 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
659 )
660 .await
661 .unwrap();
662 let _ = (
663 BlobFetchResult {
664 hash: "cd".into(),
665 bytes_len: 7,
666 },
667 BlobPublishResult {
668 ticket: "blobT".into(),
669 hash: "ab".into(),
670 },
671 );
672 });
673
674 let mut client = connect_control(&sock).await.unwrap();
675 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
676 assert_eq!(pub_res.ticket, "blobT");
677 assert_eq!(pub_res.hash, "ab");
678 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
679 assert_eq!(fetch_res.hash, "cd");
680 assert_eq!(fetch_res.bytes_len, 7);
681 server.await.unwrap();
682 }
683
684 #[tokio::test]
691 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
692 use tokio::io::AsyncRead;
693
694 let (sock, _guard) = test_endpoint("pipelined");
695 let listener = bind_local(&sock).unwrap();
696 let server = tokio::spawn(async move {
697 let mut listener = listener;
698 let stream = listener.accept().await.unwrap();
699 let (read_half, mut writer) = split_local(stream);
700 let mut bytes = serde_json::to_vec(
703 &serde_json::to_value(Hello {
704 api: API_NAME.into(),
705 api_version: API_VERSION.into(),
706 api_minor: 0,
707 stack_version: "0.1.0".into(),
708 })
709 .unwrap(),
710 )
711 .unwrap();
712 bytes.push(b'\n');
713 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
714 writer.write_all(&bytes).await.unwrap();
715 writer.flush().await.unwrap();
716 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
718 let req = match reader.next().await.unwrap().unwrap() {
719 Inbound::Frame(v) => v,
720 Inbound::Violation(_) => panic!("violation"),
721 };
722 assert_eq!(req["method"], "open_session");
723 });
724
725 let client = connect_control(&sock).await.unwrap();
726 let (reader, _writer) = client
727 .open_session("peer".into(), "kb".into())
728 .await
729 .unwrap();
730 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
732 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
733 match reframed.next().await.unwrap() {
734 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
735 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
736 }
737 server.await.unwrap();
738 }
739
740 #[tokio::test]
741 async fn blob_grant_issues_request_and_acks() {
742 let (sock, _guard) = test_endpoint("grant");
743 let listener = bind_local(&sock).unwrap();
744 let server = tokio::spawn(async move {
745 let mut listener = listener;
746 let stream = listener.accept().await.unwrap();
747 let (read_half, mut writer) = split_local(stream);
748 write_frame(
749 &mut writer,
750 &serde_json::to_value(Hello {
751 api: API_NAME.into(),
752 api_version: API_VERSION.into(),
753 api_minor: 0,
754 stack_version: "0.1.0".into(),
755 })
756 .unwrap(),
757 )
758 .await
759 .unwrap();
760 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
761 let req = match reader.next().await.unwrap().unwrap() {
762 Inbound::Frame(v) => v,
763 Inbound::Violation(_) => panic!("violation"),
764 };
765 assert_eq!(req["method"], "blob_grant");
766 assert_eq!(req["params"]["scope"], "kb-sync");
767 assert_eq!(req["params"]["principal"], "alice");
768 write_frame(
769 &mut writer,
770 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
771 )
772 .await
773 .unwrap();
774 });
775 let mut client = connect_control(&sock).await.unwrap();
776 client.blob_grant("kb-sync", "alice").await.unwrap();
777 server.await.unwrap();
778 }
779
780 #[tokio::test]
784 async fn typed_status_helper_deserializes_the_result() {
785 let (sock, _guard) = test_endpoint("typedstatus");
786 let listener = bind_local(&sock).unwrap();
787 let server = tokio::spawn(stub_daemon(listener));
788
789 let mut client = connect_control(&sock).await.unwrap();
790 let status = client.status().await.unwrap();
791 assert_eq!(status.stack_version, "0.1.0");
792 assert_eq!(status.services[0].name, "kb");
793 assert_eq!(status.services[0].backend, BackendKind::Socket);
794 assert!(status.peers.is_empty());
795 server.await.unwrap();
796 }
797
798 #[tokio::test]
801 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
802 let (sock, _guard) = test_endpoint("typedack");
803 let listener = bind_local(&sock).unwrap();
804 let server = tokio::spawn(async move {
805 let mut listener = listener;
806 let stream = listener.accept().await.unwrap();
807 let (read_half, mut writer) = split_local(stream);
808 write_frame(
809 &mut writer,
810 &serde_json::to_value(Hello {
811 api: API_NAME.into(),
812 api_version: API_VERSION.into(),
813 api_minor: 0,
814 stack_version: "0.1.0".into(),
815 })
816 .unwrap(),
817 )
818 .await
819 .unwrap();
820 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
821 let req = match reader.next().await.unwrap().unwrap() {
823 Inbound::Frame(v) => v,
824 Inbound::Violation(_) => panic!("violation"),
825 };
826 assert_eq!(req["method"], "peer_remove");
827 assert_eq!(req["params"]["nickname"], "bob");
828 write_frame(
829 &mut writer,
830 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
831 )
832 .await
833 .unwrap();
834 let req = match reader.next().await.unwrap().unwrap() {
836 Inbound::Frame(v) => v,
837 Inbound::Violation(_) => panic!("violation"),
838 };
839 assert_eq!(req["method"], "peer_rename");
840 assert_eq!(req["params"]["to"], "Bobby");
841 write_frame(
842 &mut writer,
843 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
844 )
845 .await
846 .unwrap();
847 });
848
849 let mut client = connect_control(&sock).await.unwrap();
850 client.peer_remove("bob").await.unwrap();
851 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
852 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
853 other => panic!("expected Api error, got {other:?}"),
854 }
855 server.await.unwrap();
856 }
857
858 #[tokio::test]
861 async fn typed_subscribe_yields_frames_then_end() {
862 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
863
864 let (sock, _guard) = test_endpoint("subscribe");
865 let listener = bind_local(&sock).unwrap();
866 let server = tokio::spawn(async move {
867 let mut listener = listener;
868 let stream = listener.accept().await.unwrap();
869 let (read_half, mut writer) = split_local(stream);
870 write_frame(
871 &mut writer,
872 &serde_json::to_value(Hello {
873 api: API_NAME.into(),
874 api_version: API_VERSION.into(),
875 api_minor: 0,
876 stack_version: "0.1.0".into(),
877 })
878 .unwrap(),
879 )
880 .await
881 .unwrap();
882 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
883 let req = match reader.next().await.unwrap().unwrap() {
884 Inbound::Frame(v) => v,
885 Inbound::Violation(_) => panic!("violation"),
886 };
887 assert_eq!(req["method"], "subscribe");
888 for frame in [
889 StreamFrame::Snapshot {
890 active_sessions: vec![ActiveSession {
891 peer: "bob".into(),
892 service: "notes".into(),
893 opened_at: 7,
894 }],
895 reachability: vec![PeerReachability {
896 name: "bob".into(),
897 reachable: true,
898 rtt_ms: Some(42),
899 age_secs: Some(3),
900 }],
901 },
902 StreamFrame::Event {
903 record: Box::new(AuditRecord::session_open(
904 "2026-07-03T14:02:11.480Z".into(),
905 Some("bob".into()),
906 "notes".into(),
907 )),
908 },
909 StreamFrame::Lagged { dropped: 12 },
910 ] {
911 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
912 .await
913 .unwrap();
914 }
915 writer.flush().await.unwrap();
916 });
918
919 let client = connect_control(&sock).await.unwrap();
920 let mut sub = client.subscribe().await.unwrap();
921 match sub.next().await.unwrap().unwrap() {
922 StreamFrame::Snapshot {
923 active_sessions,
924 reachability,
925 } => {
926 assert_eq!(active_sessions[0].peer, "bob");
927 assert_eq!(reachability[0].rtt_ms, Some(42));
928 }
929 other => panic!("expected the snapshot first, got {other:?}"),
930 }
931 match sub.next().await.unwrap().unwrap() {
932 StreamFrame::Event { record } => {
933 assert_eq!(record.peer.as_deref(), Some("bob"));
934 assert_eq!(record.service.as_deref(), Some("notes"));
935 }
936 other => panic!("expected the event, got {other:?}"),
937 }
938 assert_eq!(
939 sub.next().await.unwrap(),
940 Some(StreamFrame::Lagged { dropped: 12 })
941 );
942 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
943 server.await.unwrap();
944 }
945}