zenoh 1.9.0

Zenoh: The Zero Overhead Pub/Sub/Query Protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//
use std::time::Duration;

use zenoh_config::WhatAmI;
use zenoh_core::ztimeout;
use zenoh_link::EndPoint;

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_wonly() {
    const TIMEOUT: Duration = Duration::from_secs(60);

    zenoh_util::init_log_from_env_or("error");

    let router = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(false).unwrap();
        c.adminspace.permissions.set_write(true).unwrap();
        let s = ztimeout!(zenoh::open(c)).unwrap();
        s
    };
    let zid = router.zid();
    let root = router
        .get(format!("@/{zid}/router"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(root.is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_read() {
    const TIMEOUT: Duration = Duration::from_secs(60);
    const ROUTER_ENDPOINT: &str = "tcp/localhost:31000";
    const MULTICAST_ENDPOINT: &str = "udp/224.0.0.224:31000";

    zenoh_util::init_log_from_env_or("error");

    let router = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen
            .endpoints
            .set(vec![
                ROUTER_ENDPOINT.parse::<EndPoint>().unwrap(),
                MULTICAST_ENDPOINT.parse::<EndPoint>().unwrap(),
            ])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(true).unwrap();
        c.adminspace.permissions.set_write(false).unwrap();
        c.plugins_loading.set_enabled(true).unwrap();
        let plugin_search_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .join("target/debug");
        c.plugins_loading
            .set_search_dirs(zenoh_util::LibSearchDirs::from_paths(&[plugin_search_dir
                .to_str()
                .unwrap()]))
            .unwrap();
        c.insert_json5("plugins/rest/http_port", "\"8080\"")
            .unwrap();
        c.insert_json5("plugins/rest/__required__", "true").unwrap();
        let s = ztimeout!(zenoh::open(c)).unwrap();
        s
    };
    let zid = router.zid();
    let router2 = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.connect
            .endpoints
            .set(vec![ROUTER_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };
    let zid2 = router2.zid();
    let peer = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Peer)).unwrap();
        c.listen
            .endpoints
            .set(vec![MULTICAST_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };

    let root = router
        .get(format!("@/{zid}/router"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(root.is_some());
    let metrics = router
        .get(format!("@/{zid}/router/metrics"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(metrics.is_some());
    let routers_graph = router
        .get(format!("@/{zid}/router/linkstate/north"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(routers_graph.is_some());

    let subscribers: Vec<String> = router
        .get(format!("@/{zid}/router/subscriber/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(subscribers, vec![] as Vec<String>);
    let subscriber = router.declare_subscriber("some/key").await.unwrap();
    let subscribers: Vec<String> = router
        .get(format!("@/{zid}/router/subscriber/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(
        subscribers,
        vec![format!("@/{zid}/router/subscriber/some/key")]
    );
    subscriber.undeclare().await.unwrap();
    let subscribers: Vec<String> = router
        .get(format!("@/{zid}/router/subscriber/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(subscribers, vec![] as Vec<String>);

    let publishers: Vec<String> = router
        .get(format!("@/{zid}/router/publisher/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(publishers, vec![] as Vec<String>);
    let publisher = router.declare_publisher("some/key").await.unwrap();
    let publishers: Vec<String> = router
        .get(format!("@/{zid}/router/publisher/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(
        publishers,
        vec![format!("@/{zid}/router/publisher/some/key")]
    );
    publisher.undeclare().await.unwrap();
    let publishers: Vec<String> = router
        .get(format!("@/{zid}/router/publisher/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(publishers, vec![] as Vec<String>);

    let queryables: Vec<String> = router
        .get(format!("@/{zid}/router/queryable/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(queryables, vec![] as Vec<String>);
    let queryable = router.declare_queryable("some/key").await.unwrap();
    let queryables: Vec<String> = router
        .get(format!("@/{zid}/router/queryable/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(
        queryables,
        vec![format!("@/{zid}/router/queryable/some/key")]
    );
    queryable.undeclare().await.unwrap();
    let queryables: Vec<String> = router
        .get(format!("@/{zid}/router/queryable/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(queryables, vec![] as Vec<String>);

    let queriers: Vec<String> = router
        .get(format!("@/{zid}/router/querier/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(queriers, vec![] as Vec<String>);
    let querier = router.declare_querier("some/key").await.unwrap();
    let queriers: Vec<String> = router
        .get(format!("@/{zid}/router/querier/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(queriers, vec![format!("@/{zid}/router/querier/some/key")]);
    querier.undeclare().await.unwrap();
    let queriers: Vec<String> = router
        .get(format!("@/{zid}/router/querier/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(queriers, vec![] as Vec<String>);

    let tokens: Vec<String> = router
        .get(format!("@/{zid}/router/token/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(tokens, vec![] as Vec<String>);
    let token = router.liveliness().declare_token("some/key").await.unwrap();
    let tokens: Vec<String> = router
        .get(format!("@/{zid}/router/token/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(tokens, vec![format!("@/{zid}/router/token/some/key")]);
    token.undeclare().await.unwrap();
    let tokens: Vec<String> = router
        .get(format!("@/{zid}/router/token/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert_eq!(tokens, vec![] as Vec<String>);

    let routes: Vec<String> = router
        .get(format!("@/{zid}/router/route/successor/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert!(!routes.is_empty());
    let route = router
        .get(format!(
            "@/{zid}/router/route/successor/src/{zid}/dst/{zid2}"
        ))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(route.is_some());

    let plugins = router
        .get(format!("@/{zid}/router/plugins/**"))
        .await
        .unwrap()
        .into_iter()
        .next();
    #[cfg(feature = "plugins")]
    assert!(plugins.is_some());
    #[cfg(not(feature = "plugins"))]
    assert!(plugins.is_none());

    let plugins_status = router
        .get(format!("@/{zid}/router/status/plugins/**"))
        .await
        .unwrap()
        .into_iter()
        .next();
    #[cfg(feature = "plugins")]
    assert!(plugins_status.is_some());
    #[cfg(not(feature = "plugins"))]
    assert!(plugins_status.is_none());

    let count = router.get("@/**").await.unwrap().iter().count();
    assert!(count > 0);

    let count = router.get("@/*/**").await.unwrap().iter().count();
    assert!(count > 0);

    peer.close().await.unwrap();
    router2.close().await.unwrap();
    router.close().await.unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_ronly() {
    const TIMEOUT: Duration = Duration::from_secs(60);

    zenoh_util::init_log_from_env_or("error");

    let router = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(true).unwrap();
        c.adminspace.permissions.set_write(false).unwrap();
        let s = ztimeout!(zenoh::open(c)).unwrap();
        s
    };
    let zid = router.zid();

    router
        .put(format!("@/{zid}/router/config/zid"), "1")
        .await
        .unwrap();
    router
        .delete(format!("@/{zid}/router/config/zid"))
        .await
        .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_write() {
    const TIMEOUT: Duration = Duration::from_secs(60);

    zenoh_util::init_log_from_env_or("error");

    let router = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(true).unwrap();
        c.adminspace.permissions.set_write(true).unwrap();
        let s = ztimeout!(zenoh::open(c)).unwrap();
        s
    };
    let zid = router.zid();

    router
        .put(format!("@/{zid}/router/config/zid"), "1")
        .await
        .unwrap();
    router
        .delete(format!("@/{zid}/router/config/zid"))
        .await
        .unwrap();
}

/// Helper macro to navigate JSON path and return the value at that path
macro_rules! navigate_json_path {
    ($json:expr, $field_path:expr) => {{
        let field_path = $field_path;
        let parts: Vec<&str> = field_path.split('.').collect();
        let mut current = &$json;

        // Navigate to the field
        for (i, part) in parts.iter().enumerate() {
            assert!(
                current.get(part).is_some(),
                "JSON field '{}' does not exist (failed at '{}')",
                field_path,
                parts[..=i].join(".")
            );
            current = &current[part];
        }

        (field_path, current)
    }};
}

/// Macro to assert JSON field equals an exact value
///
/// Supports nested field paths using dot notation (e.g., "priorities.start")
///
/// Usage:
/// - `assert_json_field_eq!(json, "field", "expected")` - String equality
/// - `assert_json_field_eq!(json, "field.nested", 42)` - Number equality
/// - `assert_json_field_eq!(json, "field", true)` - Boolean equality
macro_rules! assert_json_field_eq {
    ($json:expr, $field:expr, $expected:expr) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        let expected_value = serde_json::json!($expected);

        assert_eq!(
            current, &expected_value,
            "JSON field '{}' should equal {:?}, got: {:?}",
            field_path, expected_value, current
        );
    }};
}

/// Macro to assert JSON field properties with automatic error messages
///
/// Supports nested field paths using dot notation (e.g., "priorities.start")
///
/// Usage:
/// - `assert_json_field!(json, "field", bool)` - Check field is boolean type
/// - `assert_json_field!(json, "field.nested", str, |v| v == "expected")` - String validator with path
/// - `assert_json_field!(json, "field", number)` - Check field is number type
/// - `assert_json_field!(json, "field", array)` - Check field is array type
/// - `assert_json_field!(json, "field", object)` - Check field is object type
/// - `assert_json_field!(json, "field", bool, |v| v)` - Boolean validator
/// - `assert_json_field!(json, "field", number, |v| v > 0)` - Number validator
macro_rules! assert_json_field {
    // Check field is boolean type
    ($json:expr, $field:expr, bool) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        assert!(
            current.is_boolean(),
            "JSON field '{}' should be a boolean, got: {:?}",
            field_path,
            current
        );
    }};

    // Check field is str type
    ($json:expr, $field:expr, str) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        assert!(
            current.is_string(),
            "JSON field '{}' should be a string, got: {:?}",
            field_path,
            current
        );
    }};

    // Check field is number type
    ($json:expr, $field:expr, number) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        assert!(
            current.is_number(),
            "JSON field '{}' should be a number, got: {:?}",
            field_path,
            current
        );
    }};

    // Check field is array type
    ($json:expr, $field:expr, array) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        assert!(
            current.is_array(),
            "JSON field '{}' should be an array, got: {:?}",
            field_path,
            current
        );
    }};

    // Check field is object type
    ($json:expr, $field:expr, object) => {{
        let (field_path, current) = navigate_json_path!($json, $field);
        assert!(
            current.is_object(),
            "JSON field '{}' should be an object, got: {:?}",
            field_path,
            current
        );
    }};
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_transports_and_links() {
    const TIMEOUT: Duration = Duration::from_secs(60);
    const ROUTER_ENDPOINT: &str = "tcp/localhost:31001";
    const ROUTER_CONNECT_ENDPOINT: &str = "tcp/localhost:31001?rel=1;prio=1-7";

    zenoh_util::init_log_from_env_or("error");

    // Create router1 with adminspace enabled
    let router1 = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen
            .endpoints
            .set(vec![ROUTER_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(true).unwrap();
        c.adminspace.permissions.set_write(false).unwrap();
        // Enable QoS for priorities and reliability support
        c.transport.unicast.qos.set_enabled(true).unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };
    let zid1 = router1.zid();

    // Test 1: Query transports when none exist (except self-connections)
    let transports_unicast: Vec<String> = router1
        .get(format!("@/{zid1}/session/transport/unicast/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    // Initially, there should be no unicast transports to other peers
    assert_eq!(transports_unicast, vec![] as Vec<String>);

    // Test: Subscribe to transport and link keys to receive notifications
    // Create channels to collect subscription samples
    let (transport_tx, mut transport_rx) = tokio::sync::mpsc::unbounded_channel();
    let (link_tx, mut link_rx) = tokio::sync::mpsc::unbounded_channel();

    // Subscribe to unicast transports only (single * matches one level)
    let transport_subscriber = router1
        .declare_subscriber(format!("@/{zid1}/session/transport/unicast/*"))
        .callback(move |sample| {
            transport_tx.send(sample).unwrap();
        })
        .await
        .unwrap();

    // Subscribe to all links (we'll filter for the specific transport after router2 connects)
    let link_subscriber = router1
        .declare_subscriber(format!("@/{zid1}/session/transport/unicast/**/link/*"))
        .callback(move |sample| {
            link_tx.send(sample).unwrap();
        })
        .await
        .unwrap();

    // Create router2 that connects to router1 (creates unicast transport)
    let router2 = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.connect
            .endpoints
            .set(vec![ROUTER_CONNECT_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        // Enable QoS for priorities and reliability support
        c.transport.unicast.qos.set_enabled(true).unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };
    let zid2 = router2.zid();

    // Give some time for the connection to establish
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Test: Verify transport subscription notification
    // Give time for subscription notifications to arrive
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Receive exactly one transport sample
    let transport_sample_sub = transport_rx
        .try_recv()
        .expect("Should receive transport notification");
    assert!(
        transport_rx.try_recv().is_err(),
        "Should receive exactly one transport notification"
    );
    assert_eq!(
        transport_sample_sub.key_expr().as_str(),
        format!("@/{zid1}/session/transport/unicast/{zid2}")
    );
    assert_eq!(
        transport_sample_sub.encoding(),
        &zenoh::bytes::Encoding::APPLICATION_JSON
    );

    // Parse and verify JSON from subscription
    let transport_bytes_sub = transport_sample_sub.payload().to_bytes();
    let transport_json_sub: serde_json::Value = serde_json::from_slice(&transport_bytes_sub)
        .expect("Failed to parse transport JSON from subscription");

    println!(
        "\nTransport JSON from subscription:\n{}",
        serde_json::to_string_pretty(&transport_json_sub).unwrap()
    );

    // Verify transport JSON from subscription
    assert_json_field_eq!(transport_json_sub, "zid", &zid2.to_string());
    assert_json_field_eq!(transport_json_sub, "whatami", "router");
    assert_json_field!(transport_json_sub, "is_qos", bool);
    #[cfg(feature = "shared-memory")]
    assert_json_field!(transport_json_sub, "is_shm", bool);

    // Test: Verify link subscription notification
    // Receive exactly one link sample
    let link_sample_sub = link_rx
        .try_recv()
        .expect("Should receive link notification");
    assert!(
        link_rx.try_recv().is_err(),
        "Should receive exactly one link notification"
    );
    assert!(
        link_sample_sub
            .key_expr()
            .as_str()
            .contains(&format!("@/{zid1}/session/transport/unicast/{zid2}/link/")),
        "Link key expression should contain the expected transport path"
    );
    assert_eq!(
        link_sample_sub.encoding(),
        &zenoh::bytes::Encoding::APPLICATION_JSON
    );

    // Parse and verify link JSON from subscription
    let link_bytes_sub = link_sample_sub.payload().to_bytes();
    let link_json_sub: serde_json::Value = serde_json::from_slice(&link_bytes_sub)
        .expect("Failed to parse link JSON from subscription");

    println!(
        "\nLink JSON from subscription:\n{}",
        serde_json::to_string_pretty(&link_json_sub).unwrap()
    );

    // Verify link JSON from subscription has all required fields
    assert_json_field!(link_json_sub, "src", str);
    assert_json_field!(link_json_sub, "dst", str);
    assert_json_field!(link_json_sub, "mtu", number);
    assert_json_field_eq!(link_json_sub, "is_streamed", true);
    assert_json_field!(link_json_sub, "interfaces", array);
    assert_json_field_eq!(link_json_sub, "priorities.start", "RealTime");
    assert_json_field_eq!(link_json_sub, "priorities.end", "Background");
    assert_json_field_eq!(link_json_sub, "reliability", "Reliable");

    // Test 2: Query all unicast transports - should now find router2
    let transports_unicast: Vec<String> = router1
        .get(format!("@/{zid1}/session/transport/unicast/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert!(!transports_unicast.is_empty());
    assert!(transports_unicast
        .iter()
        .any(|k| k.contains(&zid2.to_string())));

    // Test 3: Query specific unicast transport and parse JSON
    let transport_reply = router1
        .get(format!("@/{zid1}/session/transport/unicast/{zid2}"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(transport_reply.is_some());
    let binding = transport_reply.unwrap();
    let transport_sample = binding.result().ok().unwrap();
    assert_eq!(
        transport_sample.key_expr().as_str(),
        format!("@/{zid1}/session/transport/unicast/{zid2}")
    );
    // Verify it's JSON encoded
    assert_eq!(
        transport_sample.encoding(),
        &zenoh::bytes::Encoding::APPLICATION_JSON
    );

    // Parse and verify JSON content
    let transport_bytes = transport_sample.payload().to_bytes();
    let transport_json: serde_json::Value =
        serde_json::from_slice(&transport_bytes).expect("Failed to parse transport JSON");

    // Print TransportPeer JSON
    println!(
        "TransportPeer JSON:\n{}",
        serde_json::to_string_pretty(&transport_json).unwrap()
    );

    // Verify all TransportPeer fields using macro
    assert_json_field_eq!(transport_json, "zid", &zid2.to_string());
    assert_json_field_eq!(transport_json, "whatami", "router");
    assert_json_field!(transport_json, "is_qos", bool);
    #[cfg(feature = "shared-memory")]
    assert_json_field!(transport_json, "is_shm", bool);

    // Note: 'links' field is skipped in serialization (see TransportPeer serde(skip))

    // Test 4: Query links for the unicast transport
    let links: Vec<String> = router1
        .get(format!("@/{zid1}/session/transport/unicast/{zid2}/link/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert!(!links.is_empty());
    // Extract link_id from the first link key expression
    let link_key = &links[0];
    let link_id = link_key.split('/').next_back().unwrap();

    // Test 5: Query specific link and parse JSON
    let link_reply = router1
        .get(format!(
            "@/{zid1}/session/transport/unicast/{zid2}/link/{link_id}"
        ))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(link_reply.is_some());
    let binding = link_reply.unwrap();
    let link_sample = binding.result().ok().unwrap();
    assert_eq!(
        link_sample.encoding(),
        &zenoh::bytes::Encoding::APPLICATION_JSON
    );

    // Parse and verify link JSON content
    let link_bytes = link_sample.payload().to_bytes();
    let link_json: serde_json::Value =
        serde_json::from_slice(&link_bytes).expect("Failed to parse link JSON");

    // Print Link JSON
    println!(
        "\nLink JSON:\n{}",
        serde_json::to_string_pretty(&link_json).unwrap()
    );
    println!("\nNote: 'priorities' and 'reliability' are set via endpoint metadata (e.g., ?rel=1;prio=1-7)");

    // Verify all Link fields comprehensively
    assert_json_field!(link_json, "src", str);
    assert_json_field!(link_json, "dst", str);
    assert_json_field!(link_json, "mtu", number);
    assert_json_field_eq!(link_json, "is_streamed", true);
    assert_json_field!(link_json, "interfaces", array);

    // Verify priorities object and its nested fields
    // With prio=1-7, priority 1 maps to RealTime and priority 7 maps to Background
    assert_json_field_eq!(link_json, "priorities.start", "RealTime");
    assert_json_field_eq!(link_json, "priorities.end", "Background");

    // Verify reliability field (rel=1 means Reliable)
    assert_json_field_eq!(link_json, "reliability", "Reliable");

    // Test 6: Verify transport query with wildcard works for all transports
    let all_transports: Vec<String> = router1
        .get(format!("@/{zid1}/session/**"))
        .await
        .unwrap()
        .iter()
        .map(|r| r.result().ok().unwrap().key_expr().to_string())
        .collect();
    assert!(all_transports
        .iter()
        .any(|k| k.contains("transport/unicast") && k.contains(&zid2.to_string())));

    // Cleanup subscribers
    transport_subscriber.undeclare().await.unwrap();
    link_subscriber.undeclare().await.unwrap();

    // Cleanup
    router2.close().await.unwrap();
    router1.close().await.unwrap();
}

#[cfg(feature = "stats")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_adminspace_regression_1() {
    const TIMEOUT: Duration = Duration::from_secs(60);
    const ROUTER_ENDPOINT: &str = "tcp/localhost:31002";
    const ROUTER_CONNECT_ENDPOINT: &str = "tcp/localhost:31002?rel=1;prio=1-7";

    zenoh_util::init_log_from_env_or("error");

    // Create router1 with adminspace enabled
    let router1 = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen
            .endpoints
            .set(vec![ROUTER_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        c.adminspace.set_enabled(true).unwrap();
        c.adminspace.permissions.set_read(true).unwrap();
        c.adminspace.permissions.set_write(false).unwrap();
        // Enable QoS for priorities and reliability support
        c.transport.unicast.qos.set_enabled(true).unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };
    let zid1 = router1.zid();

    // Create router2 that connects to router1 (creates unicast transport)
    let _router2 = {
        let mut c = zenoh_config::Config::default();
        c.set_mode(Some(WhatAmI::Router)).unwrap();
        c.listen.endpoints.set(vec![]).unwrap();
        c.connect
            .endpoints
            .set(vec![ROUTER_CONNECT_ENDPOINT.parse::<EndPoint>().unwrap()])
            .unwrap();
        c.scouting.multicast.set_enabled(Some(false)).unwrap();
        // Enable QoS for priorities and reliability support
        c.transport.unicast.qos.set_enabled(true).unwrap();
        ztimeout!(zenoh::open(c)).unwrap()
    };

    // Give some time for the connection to establish
    tokio::time::sleep(Duration::from_millis(500)).await;

    let reply = router1
        .get(format!("@/{zid1}/router?_stats=true"))
        .await
        .unwrap()
        .into_iter()
        .next();
    assert!(reply.is_some());
    let binding = reply.unwrap();
    let sample = binding.result().ok().unwrap();

    // Verify it's JSON encoded
    assert_eq!(sample.encoding(), &zenoh::bytes::Encoding::APPLICATION_JSON);

    // Parse and verify JSON content
    let bytes = sample.payload().to_bytes();
    let json: serde_json::Value =
        serde_json::from_slice(&bytes).expect("Failed to parse transport JSON");

    let sessions = navigate_json_path!(json, "sessions").1.as_array().unwrap();
    assert_eq!(sessions.len(), 1);
    let rx_t_bytes = navigate_json_path!(sessions[0], "stats.rx_bytes")
        .1
        .as_u64()
        .unwrap();
    let tx_t_bytes = navigate_json_path!(sessions[0], "stats.tx_bytes")
        .1
        .as_u64()
        .unwrap();
    let links = navigate_json_path!(sessions[0], "links")
        .1
        .as_array()
        .unwrap();
    assert_eq!(links.len(), 1);
    let rx_l_bytes = navigate_json_path!(links[0], "stats.rx_bytes")
        .1
        .as_u64()
        .unwrap();
    let tx_l_bytes = navigate_json_path!(links[0], "stats.tx_bytes")
        .1
        .as_u64()
        .unwrap();

    assert_ne!(rx_t_bytes, 0);
    assert_ne!(tx_t_bytes, 0);
    assert_ne!(rx_l_bytes, 0);
    assert_ne!(tx_l_bytes, 0);

    assert_eq!(rx_t_bytes, rx_l_bytes);
    assert_eq!(tx_t_bytes, tx_l_bytes);
}