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::{LocalReadHalf, LocalWriteHalf, connect_local, split_local};
19
20#[derive(Debug)]
24pub struct ControlClient {
25 hello: Hello,
26 reader: FrameReader<LocalReadHalf>,
27 writer: LocalWriteHalf,
28}
29
30#[derive(Debug)]
37pub enum ClientError {
38 Io(std::io::Error),
39 Closed(&'static str),
40 Malformed(&'static str),
41 WrongApi { got: String, want: &'static str },
42 Api(Value),
43}
44
45impl std::fmt::Display for ClientError {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self {
48 ClientError::Io(err) => write!(f, "io: {err}"),
49 ClientError::Closed(what) => write!(f, "connection closed before {what}"),
50 ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
51 ClientError::WrongApi { got, want } => {
52 write!(f, "unexpected api: got {got:?}, want {want:?}")
53 }
54 ClientError::Api(err) => write!(f, "control API error: {err}"),
55 }
56 }
57}
58
59impl std::error::Error for ClientError {}
60
61impl From<std::io::Error> for ClientError {
62 fn from(err: std::io::Error) -> Self {
63 ClientError::Io(err)
64 }
65}
66
67impl ControlClient {
68 pub fn hello(&self) -> &Hello {
69 &self.hello
70 }
71
72 pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
75 let frame = serde_json::to_value(&request).expect("Request serializes");
76 self.request_value(&frame).await
77 }
78
79 pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
84 write_frame(&mut self.writer, request).await?;
85 match self.reader.next().await? {
86 Some(Inbound::Frame(resp)) => {
87 if let Some(err) = resp.get("error") {
88 return Err(ClientError::Api(err.clone()));
89 }
90 Ok(resp.get("result").cloned().unwrap_or(Value::Null))
91 }
92 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
93 None => Err(ClientError::Closed("response")),
94 }
95 }
96
97 pub async fn open_session(
104 mut self,
105 peer: String,
106 service: String,
107 ) -> Result<(FrameReader<LocalReadHalf>, LocalWriteHalf), ClientError> {
108 let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
109 .expect("Request serializes");
110 write_frame(&mut self.writer, &frame).await?;
111 Ok((self.reader, self.writer))
112 }
113
114 pub async fn open_stream(
122 mut self,
123 method: &str,
124 ) -> Result<(FrameReader<LocalReadHalf>, LocalWriteHalf), ClientError> {
125 let frame = serde_json::json!({ "method": method });
126 write_frame(&mut self.writer, &frame).await?;
127 Ok((self.reader, self.writer))
128 }
129
130 async fn request_typed<T: serde::de::DeserializeOwned>(
135 &mut self,
136 request: Request,
137 what: &'static str,
138 ) -> Result<T, ClientError> {
139 let v = self.request(request).await?;
140 serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
141 }
142
143 async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
146 self.request(request).await.map(|_| ())
147 }
148
149 pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
152 self.request_typed(Request::Status, "status result").await
153 }
154
155 pub async fn register_service(
158 &mut self,
159 name: &str,
160 backend: BackendSpec,
161 allow: Vec<String>,
162 ) -> Result<(), ClientError> {
163 self.register_service_with(name, backend, allow, false)
164 .await
165 }
166
167 pub async fn register_service_with(
172 &mut self,
173 name: &str,
174 backend: BackendSpec,
175 allow: Vec<String>,
176 ephemeral: bool,
177 ) -> Result<(), ClientError> {
178 self.request_ack(Request::RegisterService(RegisterServiceParams {
179 name: name.to_string(),
180 backend,
181 allow,
182 ephemeral,
183 }))
184 .await
185 }
186
187 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
190 self.invite_with(services, None).await
191 }
192
193 pub async fn invite_with(
196 &mut self,
197 services: Vec<String>,
198 app_label: Option<String>,
199 ) -> Result<InviteResult, ClientError> {
200 self.request_typed(
201 Request::Invite(InviteParams {
202 services,
203 app_label,
204 }),
205 "invite result",
206 )
207 .await
208 }
209
210 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
213 self.request_typed(
214 Request::Pair(PairParams {
215 invite_line: invite_line.to_string(),
216 }),
217 "pair result",
218 )
219 .await
220 }
221
222 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
225 self.request_ack(Request::PeerRemove(PeerRemoveParams {
226 nickname: nickname.to_string(),
227 }))
228 .await
229 }
230
231 pub async fn peer_rename(
236 &mut self,
237 user_id: Option<String>,
238 nickname: Option<String>,
239 to: &str,
240 ) -> Result<(), ClientError> {
241 self.request_ack(Request::PeerRename(PeerRenameParams {
242 user_id,
243 nickname,
244 to: to.to_string(),
245 }))
246 .await
247 }
248
249 pub async fn roster_install(
252 &mut self,
253 path: &str,
254 org_root_pk: Option<String>,
255 ) -> Result<RosterInstallResult, ClientError> {
256 self.request_typed(
257 Request::RosterInstall(RosterInstallParams {
258 path: path.to_string(),
259 org_root_pk,
260 }),
261 "roster_install result",
262 )
263 .await
264 }
265
266 pub async fn org_join(
269 &mut self,
270 org_id: &str,
271 org_root_pk: &str,
272 user_id: &str,
273 user_key: &str,
274 ) -> Result<OrgJoinResult, ClientError> {
275 self.request_typed(
276 Request::OrgJoin(OrgJoinParams {
277 org_id: org_id.to_string(),
278 org_root_pk: org_root_pk.to_string(),
279 user_id: user_id.to_string(),
280 user_key: user_key.to_string(),
281 }),
282 "org_join result",
283 )
284 .await
285 }
286
287 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
290 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
291 url: url.to_string(),
292 }))
293 .await
294 }
295
296 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
299 self.request_typed(Request::AuditSummary, "audit_summary result")
300 .await
301 }
302
303 pub async fn blob_publish(
305 &mut self,
306 scope: &str,
307 path: &str,
308 ) -> Result<BlobPublishResult, ClientError> {
309 self.request_typed(
310 Request::BlobPublish(BlobPublishParams {
311 scope: scope.to_string(),
312 path: path.to_string(),
313 }),
314 "blob_publish result",
315 )
316 .await
317 }
318
319 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
321 self.request_typed(Request::BlobList, "blob_list result")
322 .await
323 }
324
325 pub async fn blob_fetch(
328 &mut self,
329 ticket: &str,
330 dest_path: &str,
331 ) -> Result<BlobFetchResult, ClientError> {
332 self.request_typed(
333 Request::BlobFetch(BlobFetchParams {
334 ticket: ticket.to_string(),
335 dest_path: dest_path.to_string(),
336 }),
337 "blob_fetch result",
338 )
339 .await
340 }
341
342 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
348 self.request_ack(Request::BlobGrant(BlobGrantParams {
349 scope: scope.to_string(),
350 principal: principal.to_string(),
351 }))
352 .await
353 }
354
355 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
360 let (reader, writer) = self.open_stream("subscribe").await?;
361 Ok(StreamSubscription {
362 reader,
363 _writer: writer,
364 })
365 }
366}
367
368#[derive(Debug)]
373pub struct StreamSubscription {
374 reader: FrameReader<LocalReadHalf>,
375 _writer: LocalWriteHalf,
376}
377
378impl StreamSubscription {
379 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
384 match self.reader.next().await? {
385 Some(Inbound::Frame(v)) => serde_json::from_value(v)
386 .map(Some)
387 .map_err(|_| ClientError::Malformed("stream frame")),
388 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
389 None => Ok(None),
390 }
391 }
392}
393
394pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
396 let stream = connect_local(path).await?;
397 let (read_half, writer) = split_local(stream);
398 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
399 let hello: Hello = match reader.next().await? {
400 Some(Inbound::Frame(v)) => {
401 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
402 }
403 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
404 None => return Err(ClientError::Closed("hello")),
405 };
406 if hello.api != crate::protocol::API_NAME {
407 return Err(ClientError::WrongApi {
408 got: hello.api,
409 want: crate::protocol::API_NAME,
410 });
411 }
412 Ok(ControlClient {
413 hello,
414 reader,
415 writer,
416 })
417}
418
419pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
424 connect_control(&crate::paths::default_endpoint()?).await
425}
426
427#[cfg(all(test, feature = "service"))]
435mod tests {
436 use super::*;
437 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
438 use crate::transport::{LocalListener, bind_local, split_local};
439 use tokio::io::AsyncWriteExt;
440
441 #[cfg(unix)]
446 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
447 let dir = tempfile::tempdir().unwrap();
448 let path = dir.path().join(format!("{tag}.sock"));
449 (path, dir)
450 }
451 #[cfg(windows)]
452 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
453 use std::sync::atomic::{AtomicU64, Ordering};
454 static SEQ: AtomicU64 = AtomicU64::new(0);
455 let n = SEQ.fetch_add(1, Ordering::Relaxed);
456 let path = std::path::PathBuf::from(format!(
457 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
458 std::process::id()
459 ));
460 (path, ())
461 }
462
463 async fn stub_daemon(mut listener: LocalListener) {
465 let stream = listener.accept().await.unwrap();
466 let (read_half, mut writer) = split_local(stream);
467 write_frame(
468 &mut writer,
469 &serde_json::to_value(Hello {
470 api: API_NAME.into(),
471 api_version: API_VERSION.into(),
472 api_minor: 0,
473 stack_version: "0.1.0".into(),
474 })
475 .unwrap(),
476 )
477 .await
478 .unwrap();
479 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
480 let req = match reader.next().await.unwrap().unwrap() {
481 Inbound::Frame(v) => v,
482 Inbound::Violation(_) => panic!("violation"),
483 };
484 assert_eq!(req["method"], "status");
485 let result = StatusResult {
486 stack_version: "0.1.0".into(),
487 services: vec![ServiceInfo {
488 name: "kb".into(),
489 allow: vec![],
490 backend: BackendKind::Socket,
491 ephemeral: false,
492 }],
493 peers: vec![],
494 roster: None,
495 presence: vec![],
496 self_user_id: None,
497 recent_pairings: vec![],
498 reachability: vec![],
499 };
500 write_frame(
501 &mut writer,
502 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
503 )
504 .await
505 .unwrap();
506 writer.flush().await.unwrap();
507 }
508
509 #[tokio::test]
510 async fn connect_reads_hello_asserts_api_and_requests() {
511 let (sock, _guard) = test_endpoint("status");
512 let listener = bind_local(&sock).unwrap();
513 let server = tokio::spawn(stub_daemon(listener));
514
515 let mut client = connect_control(&sock).await.unwrap();
516 assert_eq!(client.hello().api, API_NAME);
517 let result = client.request(Request::Status).await.unwrap();
518 assert_eq!(result["services"][0]["name"], "kb");
519 assert_eq!(result["services"][0]["backend"], "socket");
520 server.await.unwrap();
521 }
522
523 #[tokio::test]
524 async fn wrong_api_hello_is_rejected() {
525 let (sock, _guard) = test_endpoint("wrongapi");
526 let listener = bind_local(&sock).unwrap();
527 tokio::spawn(async move {
528 let mut listener = listener;
529 let stream = listener.accept().await.unwrap();
530 let (_r, mut w) = split_local(stream);
531 write_frame(
532 &mut w,
533 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
534 )
535 .await
536 .unwrap();
537 w.flush().await.unwrap();
538 });
539 match connect_control(&sock).await {
540 Err(ClientError::WrongApi { got, want }) => {
541 assert_eq!(got, "other/1");
542 assert_eq!(want, API_NAME);
543 }
544 other => panic!("expected WrongApi, got {other:?}"),
545 }
546 }
547
548 #[tokio::test]
549 async fn blob_fetch_and_publish_deserialize_typed_results() {
550 use crate::protocol::{BlobFetchResult, BlobPublishResult};
551 let (sock, _guard) = test_endpoint("blob");
552 let listener = bind_local(&sock).unwrap();
553 let server = tokio::spawn(async move {
554 let mut listener = listener;
555 let stream = listener.accept().await.unwrap();
556 let (read_half, mut writer) = split_local(stream);
557 write_frame(
558 &mut writer,
559 &serde_json::to_value(Hello {
560 api: API_NAME.into(),
561 api_version: API_VERSION.into(),
562 api_minor: 0,
563 stack_version: "0.1.0".into(),
564 })
565 .unwrap(),
566 )
567 .await
568 .unwrap();
569 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
570 let req = match reader.next().await.unwrap().unwrap() {
572 Inbound::Frame(v) => v,
573 Inbound::Violation(_) => panic!("violation"),
574 };
575 assert_eq!(req["method"], "blob_publish");
576 assert_eq!(req["params"]["scope"], "eng");
577 write_frame(
578 &mut writer,
579 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
580 )
581 .await
582 .unwrap();
583 let req = match reader.next().await.unwrap().unwrap() {
585 Inbound::Frame(v) => v,
586 Inbound::Violation(_) => panic!("violation"),
587 };
588 assert_eq!(req["method"], "blob_fetch");
589 assert_eq!(req["params"]["ticket"], "blobT");
590 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
591 write_frame(
592 &mut writer,
593 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
594 )
595 .await
596 .unwrap();
597 let _ = (
598 BlobFetchResult {
599 hash: "cd".into(),
600 bytes_len: 7,
601 },
602 BlobPublishResult {
603 ticket: "blobT".into(),
604 hash: "ab".into(),
605 },
606 );
607 });
608
609 let mut client = connect_control(&sock).await.unwrap();
610 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
611 assert_eq!(pub_res.ticket, "blobT");
612 assert_eq!(pub_res.hash, "ab");
613 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
614 assert_eq!(fetch_res.hash, "cd");
615 assert_eq!(fetch_res.bytes_len, 7);
616 server.await.unwrap();
617 }
618
619 #[tokio::test]
626 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
627 use tokio::io::AsyncRead;
628
629 let (sock, _guard) = test_endpoint("pipelined");
630 let listener = bind_local(&sock).unwrap();
631 let server = tokio::spawn(async move {
632 let mut listener = listener;
633 let stream = listener.accept().await.unwrap();
634 let (read_half, mut writer) = split_local(stream);
635 let mut bytes = serde_json::to_vec(
638 &serde_json::to_value(Hello {
639 api: API_NAME.into(),
640 api_version: API_VERSION.into(),
641 api_minor: 0,
642 stack_version: "0.1.0".into(),
643 })
644 .unwrap(),
645 )
646 .unwrap();
647 bytes.push(b'\n');
648 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
649 writer.write_all(&bytes).await.unwrap();
650 writer.flush().await.unwrap();
651 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
653 let req = match reader.next().await.unwrap().unwrap() {
654 Inbound::Frame(v) => v,
655 Inbound::Violation(_) => panic!("violation"),
656 };
657 assert_eq!(req["method"], "open_session");
658 });
659
660 let client = connect_control(&sock).await.unwrap();
661 let (reader, _writer) = client
662 .open_session("peer".into(), "kb".into())
663 .await
664 .unwrap();
665 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
667 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
668 match reframed.next().await.unwrap() {
669 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
670 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
671 }
672 server.await.unwrap();
673 }
674
675 #[tokio::test]
676 async fn blob_grant_issues_request_and_acks() {
677 let (sock, _guard) = test_endpoint("grant");
678 let listener = bind_local(&sock).unwrap();
679 let server = tokio::spawn(async move {
680 let mut listener = listener;
681 let stream = listener.accept().await.unwrap();
682 let (read_half, mut writer) = split_local(stream);
683 write_frame(
684 &mut writer,
685 &serde_json::to_value(Hello {
686 api: API_NAME.into(),
687 api_version: API_VERSION.into(),
688 api_minor: 0,
689 stack_version: "0.1.0".into(),
690 })
691 .unwrap(),
692 )
693 .await
694 .unwrap();
695 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
696 let req = match reader.next().await.unwrap().unwrap() {
697 Inbound::Frame(v) => v,
698 Inbound::Violation(_) => panic!("violation"),
699 };
700 assert_eq!(req["method"], "blob_grant");
701 assert_eq!(req["params"]["scope"], "kb-sync");
702 assert_eq!(req["params"]["principal"], "alice");
703 write_frame(
704 &mut writer,
705 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
706 )
707 .await
708 .unwrap();
709 });
710 let mut client = connect_control(&sock).await.unwrap();
711 client.blob_grant("kb-sync", "alice").await.unwrap();
712 server.await.unwrap();
713 }
714
715 #[tokio::test]
719 async fn typed_status_helper_deserializes_the_result() {
720 let (sock, _guard) = test_endpoint("typedstatus");
721 let listener = bind_local(&sock).unwrap();
722 let server = tokio::spawn(stub_daemon(listener));
723
724 let mut client = connect_control(&sock).await.unwrap();
725 let status = client.status().await.unwrap();
726 assert_eq!(status.stack_version, "0.1.0");
727 assert_eq!(status.services[0].name, "kb");
728 assert_eq!(status.services[0].backend, BackendKind::Socket);
729 assert!(status.peers.is_empty());
730 server.await.unwrap();
731 }
732
733 #[tokio::test]
736 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
737 let (sock, _guard) = test_endpoint("typedack");
738 let listener = bind_local(&sock).unwrap();
739 let server = tokio::spawn(async move {
740 let mut listener = listener;
741 let stream = listener.accept().await.unwrap();
742 let (read_half, mut writer) = split_local(stream);
743 write_frame(
744 &mut writer,
745 &serde_json::to_value(Hello {
746 api: API_NAME.into(),
747 api_version: API_VERSION.into(),
748 api_minor: 0,
749 stack_version: "0.1.0".into(),
750 })
751 .unwrap(),
752 )
753 .await
754 .unwrap();
755 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
756 let req = match reader.next().await.unwrap().unwrap() {
758 Inbound::Frame(v) => v,
759 Inbound::Violation(_) => panic!("violation"),
760 };
761 assert_eq!(req["method"], "peer_remove");
762 assert_eq!(req["params"]["nickname"], "bob");
763 write_frame(
764 &mut writer,
765 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
766 )
767 .await
768 .unwrap();
769 let req = match reader.next().await.unwrap().unwrap() {
771 Inbound::Frame(v) => v,
772 Inbound::Violation(_) => panic!("violation"),
773 };
774 assert_eq!(req["method"], "peer_rename");
775 assert_eq!(req["params"]["to"], "Bobby");
776 write_frame(
777 &mut writer,
778 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
779 )
780 .await
781 .unwrap();
782 });
783
784 let mut client = connect_control(&sock).await.unwrap();
785 client.peer_remove("bob").await.unwrap();
786 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
787 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
788 other => panic!("expected Api error, got {other:?}"),
789 }
790 server.await.unwrap();
791 }
792
793 #[tokio::test]
796 async fn typed_subscribe_yields_frames_then_end() {
797 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
798
799 let (sock, _guard) = test_endpoint("subscribe");
800 let listener = bind_local(&sock).unwrap();
801 let server = tokio::spawn(async move {
802 let mut listener = listener;
803 let stream = listener.accept().await.unwrap();
804 let (read_half, mut writer) = split_local(stream);
805 write_frame(
806 &mut writer,
807 &serde_json::to_value(Hello {
808 api: API_NAME.into(),
809 api_version: API_VERSION.into(),
810 api_minor: 0,
811 stack_version: "0.1.0".into(),
812 })
813 .unwrap(),
814 )
815 .await
816 .unwrap();
817 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
818 let req = match reader.next().await.unwrap().unwrap() {
819 Inbound::Frame(v) => v,
820 Inbound::Violation(_) => panic!("violation"),
821 };
822 assert_eq!(req["method"], "subscribe");
823 for frame in [
824 StreamFrame::Snapshot {
825 active_sessions: vec![ActiveSession {
826 peer: "bob".into(),
827 service: "notes".into(),
828 opened_at: 7,
829 }],
830 reachability: vec![PeerReachability {
831 name: "bob".into(),
832 reachable: true,
833 rtt_ms: Some(42),
834 age_secs: Some(3),
835 }],
836 },
837 StreamFrame::Event {
838 record: Box::new(AuditRecord::session_open(
839 "2026-07-03T14:02:11.480Z".into(),
840 Some("bob".into()),
841 "notes".into(),
842 )),
843 },
844 StreamFrame::Lagged { dropped: 12 },
845 ] {
846 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
847 .await
848 .unwrap();
849 }
850 writer.flush().await.unwrap();
851 });
853
854 let client = connect_control(&sock).await.unwrap();
855 let mut sub = client.subscribe().await.unwrap();
856 match sub.next().await.unwrap().unwrap() {
857 StreamFrame::Snapshot {
858 active_sessions,
859 reachability,
860 } => {
861 assert_eq!(active_sessions[0].peer, "bob");
862 assert_eq!(reachability[0].rtt_ms, Some(42));
863 }
864 other => panic!("expected the snapshot first, got {other:?}"),
865 }
866 match sub.next().await.unwrap().unwrap() {
867 StreamFrame::Event { record } => {
868 assert_eq!(record.peer.as_deref(), Some("bob"));
869 assert_eq!(record.service.as_deref(), Some("notes"));
870 }
871 other => panic!("expected the event, got {other:?}"),
872 }
873 assert_eq!(
874 sub.next().await.unwrap(),
875 Some(StreamFrame::Lagged { dropped: 12 })
876 );
877 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
878 server.await.unwrap();
879 }
880}