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.request_ack(Request::RegisterService(RegisterServiceParams {
164 name: name.to_string(),
165 backend,
166 allow,
167 }))
168 .await
169 }
170
171 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
174 self.request_typed(Request::Invite(InviteParams { services }), "invite result")
175 .await
176 }
177
178 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
181 self.request_typed(
182 Request::Pair(PairParams {
183 invite_line: invite_line.to_string(),
184 }),
185 "pair result",
186 )
187 .await
188 }
189
190 pub async fn peer_remove(&mut self, petname: &str) -> Result<(), ClientError> {
193 self.request_ack(Request::PeerRemove(PeerRemoveParams {
194 petname: petname.to_string(),
195 }))
196 .await
197 }
198
199 pub async fn peer_rename(
204 &mut self,
205 user_id: Option<String>,
206 petname: Option<String>,
207 to: &str,
208 ) -> Result<(), ClientError> {
209 self.request_ack(Request::PeerRename(PeerRenameParams {
210 user_id,
211 petname,
212 to: to.to_string(),
213 }))
214 .await
215 }
216
217 pub async fn roster_install(
220 &mut self,
221 path: &str,
222 org_root_pk: Option<String>,
223 ) -> Result<RosterInstallResult, ClientError> {
224 self.request_typed(
225 Request::RosterInstall(RosterInstallParams {
226 path: path.to_string(),
227 org_root_pk,
228 }),
229 "roster_install result",
230 )
231 .await
232 }
233
234 pub async fn org_join(
237 &mut self,
238 org_id: &str,
239 org_root_pk: &str,
240 user_id: &str,
241 user_key: &str,
242 ) -> Result<OrgJoinResult, ClientError> {
243 self.request_typed(
244 Request::OrgJoin(OrgJoinParams {
245 org_id: org_id.to_string(),
246 org_root_pk: org_root_pk.to_string(),
247 user_id: user_id.to_string(),
248 user_key: user_key.to_string(),
249 }),
250 "org_join result",
251 )
252 .await
253 }
254
255 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
258 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
259 url: url.to_string(),
260 }))
261 .await
262 }
263
264 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
267 self.request_typed(Request::AuditSummary, "audit_summary result")
268 .await
269 }
270
271 pub async fn blob_publish(
273 &mut self,
274 scope: &str,
275 path: &str,
276 ) -> Result<BlobPublishResult, ClientError> {
277 self.request_typed(
278 Request::BlobPublish(BlobPublishParams {
279 scope: scope.to_string(),
280 path: path.to_string(),
281 }),
282 "blob_publish result",
283 )
284 .await
285 }
286
287 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
289 self.request_typed(Request::BlobList, "blob_list result")
290 .await
291 }
292
293 pub async fn blob_fetch(
296 &mut self,
297 ticket: &str,
298 dest_path: &str,
299 ) -> Result<BlobFetchResult, ClientError> {
300 self.request_typed(
301 Request::BlobFetch(BlobFetchParams {
302 ticket: ticket.to_string(),
303 dest_path: dest_path.to_string(),
304 }),
305 "blob_fetch result",
306 )
307 .await
308 }
309
310 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
316 self.request_ack(Request::BlobGrant(BlobGrantParams {
317 scope: scope.to_string(),
318 principal: principal.to_string(),
319 }))
320 .await
321 }
322
323 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
328 let (reader, writer) = self.open_stream("subscribe").await?;
329 Ok(StreamSubscription {
330 reader,
331 _writer: writer,
332 })
333 }
334}
335
336#[derive(Debug)]
341pub struct StreamSubscription {
342 reader: FrameReader<LocalReadHalf>,
343 _writer: LocalWriteHalf,
344}
345
346impl StreamSubscription {
347 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
352 match self.reader.next().await? {
353 Some(Inbound::Frame(v)) => serde_json::from_value(v)
354 .map(Some)
355 .map_err(|_| ClientError::Malformed("stream frame")),
356 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
357 None => Ok(None),
358 }
359 }
360}
361
362pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
364 let stream = connect_local(path).await?;
365 let (read_half, writer) = split_local(stream);
366 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
367 let hello: Hello = match reader.next().await? {
368 Some(Inbound::Frame(v)) => {
369 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
370 }
371 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
372 None => return Err(ClientError::Closed("hello")),
373 };
374 if hello.api != crate::protocol::API_NAME {
375 return Err(ClientError::WrongApi {
376 got: hello.api,
377 want: crate::protocol::API_NAME,
378 });
379 }
380 Ok(ControlClient {
381 hello,
382 reader,
383 writer,
384 })
385}
386
387pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
392 connect_control(&crate::paths::default_endpoint()?).await
393}
394
395#[cfg(all(test, feature = "service"))]
403mod tests {
404 use super::*;
405 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
406 use crate::transport::{LocalListener, bind_local, split_local};
407 use tokio::io::AsyncWriteExt;
408
409 #[cfg(unix)]
414 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
415 let dir = tempfile::tempdir().unwrap();
416 let path = dir.path().join(format!("{tag}.sock"));
417 (path, dir)
418 }
419 #[cfg(windows)]
420 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
421 use std::sync::atomic::{AtomicU64, Ordering};
422 static SEQ: AtomicU64 = AtomicU64::new(0);
423 let n = SEQ.fetch_add(1, Ordering::Relaxed);
424 let path = std::path::PathBuf::from(format!(
425 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
426 std::process::id()
427 ));
428 (path, ())
429 }
430
431 async fn stub_daemon(mut listener: LocalListener) {
433 let stream = listener.accept().await.unwrap();
434 let (read_half, mut writer) = split_local(stream);
435 write_frame(
436 &mut writer,
437 &serde_json::to_value(Hello {
438 api: API_NAME.into(),
439 api_version: API_VERSION.into(),
440 stack_version: "0.1.0".into(),
441 })
442 .unwrap(),
443 )
444 .await
445 .unwrap();
446 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
447 let req = match reader.next().await.unwrap().unwrap() {
448 Inbound::Frame(v) => v,
449 Inbound::Violation(_) => panic!("violation"),
450 };
451 assert_eq!(req["method"], "status");
452 let result = StatusResult {
453 stack_version: "0.1.0".into(),
454 services: vec![ServiceInfo {
455 name: "kb".into(),
456 allow: vec![],
457 backend: BackendKind::Socket,
458 }],
459 peers: vec![],
460 roster: None,
461 presence: vec![],
462 self_user_id: None,
463 recent_pairings: vec![],
464 reachability: vec![],
465 };
466 write_frame(
467 &mut writer,
468 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
469 )
470 .await
471 .unwrap();
472 writer.flush().await.unwrap();
473 }
474
475 #[tokio::test]
476 async fn connect_reads_hello_asserts_api_and_requests() {
477 let (sock, _guard) = test_endpoint("status");
478 let listener = bind_local(&sock).unwrap();
479 let server = tokio::spawn(stub_daemon(listener));
480
481 let mut client = connect_control(&sock).await.unwrap();
482 assert_eq!(client.hello().api, API_NAME);
483 let result = client.request(Request::Status).await.unwrap();
484 assert_eq!(result["services"][0]["name"], "kb");
485 assert_eq!(result["services"][0]["backend"], "socket");
486 server.await.unwrap();
487 }
488
489 #[tokio::test]
490 async fn wrong_api_hello_is_rejected() {
491 let (sock, _guard) = test_endpoint("wrongapi");
492 let listener = bind_local(&sock).unwrap();
493 tokio::spawn(async move {
494 let mut listener = listener;
495 let stream = listener.accept().await.unwrap();
496 let (_r, mut w) = split_local(stream);
497 write_frame(
498 &mut w,
499 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
500 )
501 .await
502 .unwrap();
503 w.flush().await.unwrap();
504 });
505 match connect_control(&sock).await {
506 Err(ClientError::WrongApi { got, want }) => {
507 assert_eq!(got, "other/1");
508 assert_eq!(want, API_NAME);
509 }
510 other => panic!("expected WrongApi, got {other:?}"),
511 }
512 }
513
514 #[tokio::test]
515 async fn blob_fetch_and_publish_deserialize_typed_results() {
516 use crate::protocol::{BlobFetchResult, BlobPublishResult};
517 let (sock, _guard) = test_endpoint("blob");
518 let listener = bind_local(&sock).unwrap();
519 let server = tokio::spawn(async move {
520 let mut listener = listener;
521 let stream = listener.accept().await.unwrap();
522 let (read_half, mut writer) = split_local(stream);
523 write_frame(
524 &mut writer,
525 &serde_json::to_value(Hello {
526 api: API_NAME.into(),
527 api_version: API_VERSION.into(),
528 stack_version: "0.1.0".into(),
529 })
530 .unwrap(),
531 )
532 .await
533 .unwrap();
534 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
535 let req = match reader.next().await.unwrap().unwrap() {
537 Inbound::Frame(v) => v,
538 Inbound::Violation(_) => panic!("violation"),
539 };
540 assert_eq!(req["method"], "blob_publish");
541 assert_eq!(req["params"]["scope"], "eng");
542 write_frame(
543 &mut writer,
544 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
545 )
546 .await
547 .unwrap();
548 let req = match reader.next().await.unwrap().unwrap() {
550 Inbound::Frame(v) => v,
551 Inbound::Violation(_) => panic!("violation"),
552 };
553 assert_eq!(req["method"], "blob_fetch");
554 assert_eq!(req["params"]["ticket"], "blobT");
555 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
556 write_frame(
557 &mut writer,
558 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
559 )
560 .await
561 .unwrap();
562 let _ = (
563 BlobFetchResult {
564 hash: "cd".into(),
565 bytes_len: 7,
566 },
567 BlobPublishResult {
568 ticket: "blobT".into(),
569 hash: "ab".into(),
570 },
571 );
572 });
573
574 let mut client = connect_control(&sock).await.unwrap();
575 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
576 assert_eq!(pub_res.ticket, "blobT");
577 assert_eq!(pub_res.hash, "ab");
578 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
579 assert_eq!(fetch_res.hash, "cd");
580 assert_eq!(fetch_res.bytes_len, 7);
581 server.await.unwrap();
582 }
583
584 #[tokio::test]
591 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
592 use tokio::io::AsyncRead;
593
594 let (sock, _guard) = test_endpoint("pipelined");
595 let listener = bind_local(&sock).unwrap();
596 let server = tokio::spawn(async move {
597 let mut listener = listener;
598 let stream = listener.accept().await.unwrap();
599 let (read_half, mut writer) = split_local(stream);
600 let mut bytes = serde_json::to_vec(
603 &serde_json::to_value(Hello {
604 api: API_NAME.into(),
605 api_version: API_VERSION.into(),
606 stack_version: "0.1.0".into(),
607 })
608 .unwrap(),
609 )
610 .unwrap();
611 bytes.push(b'\n');
612 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
613 writer.write_all(&bytes).await.unwrap();
614 writer.flush().await.unwrap();
615 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
617 let req = match reader.next().await.unwrap().unwrap() {
618 Inbound::Frame(v) => v,
619 Inbound::Violation(_) => panic!("violation"),
620 };
621 assert_eq!(req["method"], "open_session");
622 });
623
624 let client = connect_control(&sock).await.unwrap();
625 let (reader, _writer) = client
626 .open_session("peer".into(), "kb".into())
627 .await
628 .unwrap();
629 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
631 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
632 match reframed.next().await.unwrap() {
633 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
634 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
635 }
636 server.await.unwrap();
637 }
638
639 #[tokio::test]
640 async fn blob_grant_issues_request_and_acks() {
641 let (sock, _guard) = test_endpoint("grant");
642 let listener = bind_local(&sock).unwrap();
643 let server = tokio::spawn(async move {
644 let mut listener = listener;
645 let stream = listener.accept().await.unwrap();
646 let (read_half, mut writer) = split_local(stream);
647 write_frame(
648 &mut writer,
649 &serde_json::to_value(Hello {
650 api: API_NAME.into(),
651 api_version: API_VERSION.into(),
652 stack_version: "0.1.0".into(),
653 })
654 .unwrap(),
655 )
656 .await
657 .unwrap();
658 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
659 let req = match reader.next().await.unwrap().unwrap() {
660 Inbound::Frame(v) => v,
661 Inbound::Violation(_) => panic!("violation"),
662 };
663 assert_eq!(req["method"], "blob_grant");
664 assert_eq!(req["params"]["scope"], "kb-sync");
665 assert_eq!(req["params"]["principal"], "alice");
666 write_frame(
667 &mut writer,
668 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
669 )
670 .await
671 .unwrap();
672 });
673 let mut client = connect_control(&sock).await.unwrap();
674 client.blob_grant("kb-sync", "alice").await.unwrap();
675 server.await.unwrap();
676 }
677
678 #[tokio::test]
682 async fn typed_status_helper_deserializes_the_result() {
683 let (sock, _guard) = test_endpoint("typedstatus");
684 let listener = bind_local(&sock).unwrap();
685 let server = tokio::spawn(stub_daemon(listener));
686
687 let mut client = connect_control(&sock).await.unwrap();
688 let status = client.status().await.unwrap();
689 assert_eq!(status.stack_version, "0.1.0");
690 assert_eq!(status.services[0].name, "kb");
691 assert_eq!(status.services[0].backend, BackendKind::Socket);
692 assert!(status.peers.is_empty());
693 server.await.unwrap();
694 }
695
696 #[tokio::test]
699 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
700 let (sock, _guard) = test_endpoint("typedack");
701 let listener = bind_local(&sock).unwrap();
702 let server = tokio::spawn(async move {
703 let mut listener = listener;
704 let stream = listener.accept().await.unwrap();
705 let (read_half, mut writer) = split_local(stream);
706 write_frame(
707 &mut writer,
708 &serde_json::to_value(Hello {
709 api: API_NAME.into(),
710 api_version: API_VERSION.into(),
711 stack_version: "0.1.0".into(),
712 })
713 .unwrap(),
714 )
715 .await
716 .unwrap();
717 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
718 let req = match reader.next().await.unwrap().unwrap() {
720 Inbound::Frame(v) => v,
721 Inbound::Violation(_) => panic!("violation"),
722 };
723 assert_eq!(req["method"], "peer_remove");
724 assert_eq!(req["params"]["petname"], "bob");
725 write_frame(
726 &mut writer,
727 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
728 )
729 .await
730 .unwrap();
731 let req = match reader.next().await.unwrap().unwrap() {
733 Inbound::Frame(v) => v,
734 Inbound::Violation(_) => panic!("violation"),
735 };
736 assert_eq!(req["method"], "peer_rename");
737 assert_eq!(req["params"]["to"], "Bobby");
738 write_frame(
739 &mut writer,
740 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
741 )
742 .await
743 .unwrap();
744 });
745
746 let mut client = connect_control(&sock).await.unwrap();
747 client.peer_remove("bob").await.unwrap();
748 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
749 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
750 other => panic!("expected Api error, got {other:?}"),
751 }
752 server.await.unwrap();
753 }
754
755 #[tokio::test]
758 async fn typed_subscribe_yields_frames_then_end() {
759 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
760
761 let (sock, _guard) = test_endpoint("subscribe");
762 let listener = bind_local(&sock).unwrap();
763 let server = tokio::spawn(async move {
764 let mut listener = listener;
765 let stream = listener.accept().await.unwrap();
766 let (read_half, mut writer) = split_local(stream);
767 write_frame(
768 &mut writer,
769 &serde_json::to_value(Hello {
770 api: API_NAME.into(),
771 api_version: API_VERSION.into(),
772 stack_version: "0.1.0".into(),
773 })
774 .unwrap(),
775 )
776 .await
777 .unwrap();
778 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
779 let req = match reader.next().await.unwrap().unwrap() {
780 Inbound::Frame(v) => v,
781 Inbound::Violation(_) => panic!("violation"),
782 };
783 assert_eq!(req["method"], "subscribe");
784 for frame in [
785 StreamFrame::Snapshot {
786 active_sessions: vec![ActiveSession {
787 peer: "bob".into(),
788 service: "notes".into(),
789 opened_at: 7,
790 }],
791 reachability: vec![PeerReachability {
792 name: "bob".into(),
793 reachable: true,
794 rtt_ms: Some(42),
795 age_secs: Some(3),
796 }],
797 },
798 StreamFrame::Event {
799 record: Box::new(AuditRecord::session_open(
800 "2026-07-03T14:02:11.480Z".into(),
801 Some("bob".into()),
802 "notes".into(),
803 )),
804 },
805 StreamFrame::Lagged { dropped: 12 },
806 ] {
807 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
808 .await
809 .unwrap();
810 }
811 writer.flush().await.unwrap();
812 });
814
815 let client = connect_control(&sock).await.unwrap();
816 let mut sub = client.subscribe().await.unwrap();
817 match sub.next().await.unwrap().unwrap() {
818 StreamFrame::Snapshot {
819 active_sessions,
820 reachability,
821 } => {
822 assert_eq!(active_sessions[0].peer, "bob");
823 assert_eq!(reachability[0].rtt_ms, Some(42));
824 }
825 other => panic!("expected the snapshot first, got {other:?}"),
826 }
827 match sub.next().await.unwrap().unwrap() {
828 StreamFrame::Event { record } => {
829 assert_eq!(record.peer.as_deref(), Some("bob"));
830 assert_eq!(record.service.as_deref(), Some("notes"));
831 }
832 other => panic!("expected the event, got {other:?}"),
833 }
834 assert_eq!(
835 sub.next().await.unwrap(),
836 Some(StreamFrame::Lagged { dropped: 12 })
837 );
838 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
839 server.await.unwrap();
840 }
841}