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 allow_display: vec![],
531 backend: BackendKind::Socket,
532 ephemeral: false,
533 }],
534 peers: vec![],
535 roster: None,
536 presence: vec![],
537 self_user_id: None,
538 recent_pairings: vec![],
539 reachability: vec![],
540 self_nickname: String::new(),
541 };
542 write_frame(
543 &mut writer,
544 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
545 )
546 .await
547 .unwrap();
548 writer.flush().await.unwrap();
549 }
550
551 #[tokio::test]
554 async fn connect_control_io_handshakes_over_a_duplex() {
555 let (client_io, mut server_io) = tokio::io::duplex(4096);
556 tokio::spawn(async move {
557 write_frame(
558 &mut server_io,
559 &serde_json::to_value(Hello {
560 api: API_NAME.into(),
561 api_version: API_VERSION.into(),
562 api_minor: 0,
563 stack_version: "in-proc".into(),
564 })
565 .unwrap(),
566 )
567 .await
568 .unwrap();
569 });
570 let (r, w) = tokio::io::split(client_io);
571 let client = connect_control_io(r, w).await.expect("handshake");
572 assert_eq!(client.hello().stack_version, "in-proc");
573 }
574
575 #[tokio::test]
576 async fn connect_reads_hello_asserts_api_and_requests() {
577 let (sock, _guard) = test_endpoint("status");
578 let listener = bind_local(&sock).unwrap();
579 let server = tokio::spawn(stub_daemon(listener));
580
581 let mut client = connect_control(&sock).await.unwrap();
582 assert_eq!(client.hello().api, API_NAME);
583 let result = client.request(Request::Status).await.unwrap();
584 assert_eq!(result["services"][0]["name"], "kb");
585 assert_eq!(result["services"][0]["backend"], "socket");
586 server.await.unwrap();
587 }
588
589 #[tokio::test]
590 async fn wrong_api_hello_is_rejected() {
591 let (sock, _guard) = test_endpoint("wrongapi");
592 let listener = bind_local(&sock).unwrap();
593 tokio::spawn(async move {
594 let mut listener = listener;
595 let stream = listener.accept().await.unwrap();
596 let (_r, mut w) = split_local(stream);
597 write_frame(
598 &mut w,
599 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
600 )
601 .await
602 .unwrap();
603 w.flush().await.unwrap();
604 });
605 match connect_control(&sock).await {
606 Err(ClientError::WrongApi { got, want }) => {
607 assert_eq!(got, "other/1");
608 assert_eq!(want, API_NAME);
609 }
610 other => panic!("expected WrongApi, got {other:?}"),
611 }
612 }
613
614 #[tokio::test]
615 async fn blob_fetch_and_publish_deserialize_typed_results() {
616 use crate::protocol::{BlobFetchResult, BlobPublishResult};
617 let (sock, _guard) = test_endpoint("blob");
618 let listener = bind_local(&sock).unwrap();
619 let server = tokio::spawn(async move {
620 let mut listener = listener;
621 let stream = listener.accept().await.unwrap();
622 let (read_half, mut writer) = split_local(stream);
623 write_frame(
624 &mut writer,
625 &serde_json::to_value(Hello {
626 api: API_NAME.into(),
627 api_version: API_VERSION.into(),
628 api_minor: 0,
629 stack_version: "0.1.0".into(),
630 })
631 .unwrap(),
632 )
633 .await
634 .unwrap();
635 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
636 let req = match reader.next().await.unwrap().unwrap() {
638 Inbound::Frame(v) => v,
639 Inbound::Violation(_) => panic!("violation"),
640 };
641 assert_eq!(req["method"], "blob_publish");
642 assert_eq!(req["params"]["scope"], "eng");
643 write_frame(
644 &mut writer,
645 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
646 )
647 .await
648 .unwrap();
649 let req = match reader.next().await.unwrap().unwrap() {
651 Inbound::Frame(v) => v,
652 Inbound::Violation(_) => panic!("violation"),
653 };
654 assert_eq!(req["method"], "blob_fetch");
655 assert_eq!(req["params"]["ticket"], "blobT");
656 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
657 write_frame(
658 &mut writer,
659 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
660 )
661 .await
662 .unwrap();
663 let _ = (
664 BlobFetchResult {
665 hash: "cd".into(),
666 bytes_len: 7,
667 },
668 BlobPublishResult {
669 ticket: "blobT".into(),
670 hash: "ab".into(),
671 },
672 );
673 });
674
675 let mut client = connect_control(&sock).await.unwrap();
676 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
677 assert_eq!(pub_res.ticket, "blobT");
678 assert_eq!(pub_res.hash, "ab");
679 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
680 assert_eq!(fetch_res.hash, "cd");
681 assert_eq!(fetch_res.bytes_len, 7);
682 server.await.unwrap();
683 }
684
685 #[tokio::test]
692 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
693 use tokio::io::AsyncRead;
694
695 let (sock, _guard) = test_endpoint("pipelined");
696 let listener = bind_local(&sock).unwrap();
697 let server = tokio::spawn(async move {
698 let mut listener = listener;
699 let stream = listener.accept().await.unwrap();
700 let (read_half, mut writer) = split_local(stream);
701 let mut bytes = serde_json::to_vec(
704 &serde_json::to_value(Hello {
705 api: API_NAME.into(),
706 api_version: API_VERSION.into(),
707 api_minor: 0,
708 stack_version: "0.1.0".into(),
709 })
710 .unwrap(),
711 )
712 .unwrap();
713 bytes.push(b'\n');
714 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
715 writer.write_all(&bytes).await.unwrap();
716 writer.flush().await.unwrap();
717 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
719 let req = match reader.next().await.unwrap().unwrap() {
720 Inbound::Frame(v) => v,
721 Inbound::Violation(_) => panic!("violation"),
722 };
723 assert_eq!(req["method"], "open_session");
724 });
725
726 let client = connect_control(&sock).await.unwrap();
727 let (reader, _writer) = client
728 .open_session("peer".into(), "kb".into())
729 .await
730 .unwrap();
731 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
733 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
734 match reframed.next().await.unwrap() {
735 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
736 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
737 }
738 server.await.unwrap();
739 }
740
741 #[tokio::test]
742 async fn blob_grant_issues_request_and_acks() {
743 let (sock, _guard) = test_endpoint("grant");
744 let listener = bind_local(&sock).unwrap();
745 let server = tokio::spawn(async move {
746 let mut listener = listener;
747 let stream = listener.accept().await.unwrap();
748 let (read_half, mut writer) = split_local(stream);
749 write_frame(
750 &mut writer,
751 &serde_json::to_value(Hello {
752 api: API_NAME.into(),
753 api_version: API_VERSION.into(),
754 api_minor: 0,
755 stack_version: "0.1.0".into(),
756 })
757 .unwrap(),
758 )
759 .await
760 .unwrap();
761 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
762 let req = match reader.next().await.unwrap().unwrap() {
763 Inbound::Frame(v) => v,
764 Inbound::Violation(_) => panic!("violation"),
765 };
766 assert_eq!(req["method"], "blob_grant");
767 assert_eq!(req["params"]["scope"], "kb-sync");
768 assert_eq!(req["params"]["principal"], "alice");
769 write_frame(
770 &mut writer,
771 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
772 )
773 .await
774 .unwrap();
775 });
776 let mut client = connect_control(&sock).await.unwrap();
777 client.blob_grant("kb-sync", "alice").await.unwrap();
778 server.await.unwrap();
779 }
780
781 #[tokio::test]
785 async fn typed_status_helper_deserializes_the_result() {
786 let (sock, _guard) = test_endpoint("typedstatus");
787 let listener = bind_local(&sock).unwrap();
788 let server = tokio::spawn(stub_daemon(listener));
789
790 let mut client = connect_control(&sock).await.unwrap();
791 let status = client.status().await.unwrap();
792 assert_eq!(status.stack_version, "0.1.0");
793 assert_eq!(status.services[0].name, "kb");
794 assert_eq!(status.services[0].backend, BackendKind::Socket);
795 assert!(status.peers.is_empty());
796 server.await.unwrap();
797 }
798
799 #[tokio::test]
802 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
803 let (sock, _guard) = test_endpoint("typedack");
804 let listener = bind_local(&sock).unwrap();
805 let server = tokio::spawn(async move {
806 let mut listener = listener;
807 let stream = listener.accept().await.unwrap();
808 let (read_half, mut writer) = split_local(stream);
809 write_frame(
810 &mut writer,
811 &serde_json::to_value(Hello {
812 api: API_NAME.into(),
813 api_version: API_VERSION.into(),
814 api_minor: 0,
815 stack_version: "0.1.0".into(),
816 })
817 .unwrap(),
818 )
819 .await
820 .unwrap();
821 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
822 let req = match reader.next().await.unwrap().unwrap() {
824 Inbound::Frame(v) => v,
825 Inbound::Violation(_) => panic!("violation"),
826 };
827 assert_eq!(req["method"], "peer_remove");
828 assert_eq!(req["params"]["nickname"], "bob");
829 write_frame(
830 &mut writer,
831 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
832 )
833 .await
834 .unwrap();
835 let req = match reader.next().await.unwrap().unwrap() {
837 Inbound::Frame(v) => v,
838 Inbound::Violation(_) => panic!("violation"),
839 };
840 assert_eq!(req["method"], "peer_rename");
841 assert_eq!(req["params"]["to"], "Bobby");
842 write_frame(
843 &mut writer,
844 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
845 )
846 .await
847 .unwrap();
848 });
849
850 let mut client = connect_control(&sock).await.unwrap();
851 client.peer_remove("bob").await.unwrap();
852 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
853 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
854 other => panic!("expected Api error, got {other:?}"),
855 }
856 server.await.unwrap();
857 }
858
859 #[tokio::test]
862 async fn typed_subscribe_yields_frames_then_end() {
863 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
864
865 let (sock, _guard) = test_endpoint("subscribe");
866 let listener = bind_local(&sock).unwrap();
867 let server = tokio::spawn(async move {
868 let mut listener = listener;
869 let stream = listener.accept().await.unwrap();
870 let (read_half, mut writer) = split_local(stream);
871 write_frame(
872 &mut writer,
873 &serde_json::to_value(Hello {
874 api: API_NAME.into(),
875 api_version: API_VERSION.into(),
876 api_minor: 0,
877 stack_version: "0.1.0".into(),
878 })
879 .unwrap(),
880 )
881 .await
882 .unwrap();
883 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
884 let req = match reader.next().await.unwrap().unwrap() {
885 Inbound::Frame(v) => v,
886 Inbound::Violation(_) => panic!("violation"),
887 };
888 assert_eq!(req["method"], "subscribe");
889 for frame in [
890 StreamFrame::Snapshot {
891 active_sessions: vec![ActiveSession {
892 peer: "bob".into(),
893 service: "notes".into(),
894 opened_at: 7,
895 }],
896 reachability: vec![PeerReachability {
897 name: "bob".into(),
898 reachable: true,
899 rtt_ms: Some(42),
900 age_secs: Some(3),
901 }],
902 },
903 StreamFrame::Event {
904 record: Box::new(AuditRecord::session_open(
905 "2026-07-03T14:02:11.480Z".into(),
906 Some("bob".into()),
907 "notes".into(),
908 )),
909 },
910 StreamFrame::Lagged { dropped: 12 },
911 ] {
912 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
913 .await
914 .unwrap();
915 }
916 writer.flush().await.unwrap();
917 });
919
920 let client = connect_control(&sock).await.unwrap();
921 let mut sub = client.subscribe().await.unwrap();
922 match sub.next().await.unwrap().unwrap() {
923 StreamFrame::Snapshot {
924 active_sessions,
925 reachability,
926 } => {
927 assert_eq!(active_sessions[0].peer, "bob");
928 assert_eq!(reachability[0].rtt_ms, Some(42));
929 }
930 other => panic!("expected the snapshot first, got {other:?}"),
931 }
932 match sub.next().await.unwrap().unwrap() {
933 StreamFrame::Event { record } => {
934 assert_eq!(record.peer.as_deref(), Some("bob"));
935 assert_eq!(record.service.as_deref(), Some("notes"));
936 }
937 other => panic!("expected the event, got {other:?}"),
938 }
939 assert_eq!(
940 sub.next().await.unwrap(),
941 Some(StreamFrame::Lagged { dropped: 12 })
942 );
943 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
944 server.await.unwrap();
945 }
946}