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