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
//
// Copyright (c) 2025 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>
//
#![cfg(feature = "internal")]

use std::str::FromStr;

use zenoh_buffers::ZBuf;
use zenoh_keyexpr::keyexpr;
use zenoh_protocol::{
    network::{NetworkBodyMut, NetworkMessageMut, Push},
    zenoh::PushBody,
};
use zenoh_transport::{multicast::TransportMulticast, unicast::TransportUnicast};

use crate::net::routing::interceptor::*;

#[derive(Clone)]
struct TestInterceptorConf {
    flow: InterceptorFlow,
    data: String,
}

fn test_interceptor_factories(config: &Vec<TestInterceptorConf>) -> Vec<InterceptorFactory> {
    let mut res: Vec<InterceptorFactory> = vec![];
    for c in config {
        res.push(Box::new(TestInterceptorFactory::new(c.clone())));
    }
    res
}

struct TestInterceptorFactory {
    conf: TestInterceptorConf,
}

impl TestInterceptorFactory {
    pub fn new(conf: TestInterceptorConf) -> Self {
        Self { conf }
    }
}

impl InterceptorFactoryTrait for TestInterceptorFactory {
    fn new_transport_unicast(
        &self,
        _transport: &TransportUnicast,
    ) -> (Option<IngressInterceptor>, Option<EgressInterceptor>) {
        match self.conf.flow {
            InterceptorFlow::Egress => {
                (None, Some(Box::new(TestInterceptor::new(&self.conf.data))))
            }
            InterceptorFlow::Ingress => {
                (Some(Box::new(TestInterceptor::new(&self.conf.data))), None)
            }
        }
    }

    fn new_transport_multicast(
        &self,
        _transport: &TransportMulticast,
    ) -> Option<EgressInterceptor> {
        None
    }

    fn new_peer_multicast(&self, _transport: &TransportMulticast) -> Option<IngressInterceptor> {
        None
    }
}

struct TestInterceptor {
    data: String,
}

impl TestInterceptor {
    fn new(data: &str) -> Self {
        TestInterceptor {
            data: data.to_owned(),
        }
    }
}

impl InterceptorTrait for TestInterceptor {
    fn compute_keyexpr_cache(&self, _key_expr: &keyexpr) -> Option<Box<dyn Any + Send + Sync>> {
        Some(Box::new(self.data.clone()))
    }

    fn intercept(&self, msg: &mut NetworkMessageMut, ctx: &mut dyn InterceptorContext) -> bool {
        let cache_hit = ctx.get_cache(msg).is_some();
        if let NetworkBodyMut::Push(&mut Push {
            payload: PushBody::Put(ref mut p),
            ..
        }) = &mut msg.body
        {
            let out = format!("Cache hit: {cache_hit}, data: {}", &self.data);
            p.payload = ZBuf::from(out.as_bytes().to_owned());
        }
        true
    }
}

use std::{any::Any, time::Duration};

use zenoh_config::{Config, InterceptorFlow, ZenohId};
use zenoh_core::ztimeout;

use crate::{config::WhatAmI, init_log_from_env_or, open};

const TIMEOUT: Duration = Duration::from_secs(60);
const SLEEP: Duration = Duration::from_secs(1);

async fn get_basic_router_config(port: u16) -> Config {
    let mut config = Config::default();
    config.set_mode(Some(WhatAmI::Router)).unwrap();
    config
        .listen
        .endpoints
        .set(vec![format!("tcp/127.0.0.1:{port}").parse().unwrap()])
        .unwrap();
    config.scouting.multicast.set_enabled(Some(false)).unwrap();
    config
}

async fn get_basic_client_config(port: u16) -> Config {
    let mut config = Config::default();
    config.set_mode(Some(WhatAmI::Client)).unwrap();
    config
        .connect
        .endpoints
        .set(vec![format!("tcp/127.0.0.1:{port}").parse().unwrap()])
        .unwrap();
    config.scouting.multicast.set_enabled(Some(false)).unwrap();
    config
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_interceptors_cache_update_ingress() {
    let router_id = ZenohId::from_str("a1").unwrap();
    let c = TestInterceptorConf {
        flow: InterceptorFlow::Ingress,
        data: "1".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    init_log_from_env_or("error");
    let mut config_router = get_basic_router_config(27701).await;
    config_router.set_id(Some(router_id)).unwrap();

    let config_client1 = get_basic_client_config(27701).await;
    let config_client2 = get_basic_client_config(27701).await;

    let router = ztimeout!(open(config_router.clone())).unwrap();
    tokio::time::sleep(SLEEP).await;
    let session1 = ztimeout!(open(config_client1)).unwrap();
    let session2 = ztimeout!(open(config_client2)).unwrap();
    tokio::time::sleep(SLEEP).await;
    let sub = ztimeout!(session2.declare_subscriber("test/cache")).unwrap();
    let pub1 = ztimeout!(session1.declare_publisher("test/cache")).unwrap();
    let pub2 = ztimeout!(session1.declare_publisher("test/*")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 1"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 1"
    );

    let c = TestInterceptorConf {
        flow: InterceptorFlow::Ingress,
        data: "2".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    router
        .static_runtime()
        .unwrap()
        .router()
        .tables
        .update_config(&config_router)
        .unwrap();
    tokio::time::sleep(SLEEP).await;

    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();
    let sub2 = ztimeout!(session2.declare_subscriber("test2/cache")).unwrap();
    let pub3 = ztimeout!(session1.declare_publisher("test2/cache")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub3.put("some_data_3")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();
    let msg3 = ztimeout!(sub2.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 2"
    );
    assert_eq!(
        msg3.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_interceptors_cache_update_egress() {
    let router_id = ZenohId::from_str("a1").unwrap();
    let c = TestInterceptorConf {
        flow: InterceptorFlow::Egress,
        data: "1".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    init_log_from_env_or("error");
    let mut config_router = get_basic_router_config(27702).await;
    config_router.set_id(Some(router_id)).unwrap();

    let config_client1 = get_basic_client_config(27702).await;
    let config_client2 = get_basic_client_config(27702).await;

    let router = ztimeout!(open(config_router.clone())).unwrap();
    tokio::time::sleep(SLEEP).await;
    let session1 = ztimeout!(open(config_client1)).unwrap();
    let session2 = ztimeout!(open(config_client2)).unwrap();
    tokio::time::sleep(SLEEP).await;
    let sub = ztimeout!(session2.declare_subscriber("test/cache")).unwrap();
    let pub1 = ztimeout!(session1.declare_publisher("test/cache")).unwrap();
    let pub2 = ztimeout!(session1.declare_publisher("test/*")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 1"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 1"
    );

    let c = TestInterceptorConf {
        flow: InterceptorFlow::Egress,
        data: "2".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    router
        .static_runtime()
        .unwrap()
        .router()
        .tables
        .update_config(&config_router)
        .unwrap();
    tokio::time::sleep(SLEEP).await;

    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();
    let sub2 = ztimeout!(session2.declare_subscriber("test2/cache")).unwrap();
    let pub3 = ztimeout!(session1.declare_publisher("test2/cache")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub3.put("some_data_3")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();
    let msg3 = ztimeout!(sub2.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 2"
    );
    assert_eq!(
        msg3.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_interceptors_cache_update_egress_then_ingress() {
    let router_id = ZenohId::from_str("a1").unwrap();
    let c = TestInterceptorConf {
        flow: InterceptorFlow::Egress,
        data: "1".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    init_log_from_env_or("error");
    let mut config_router = get_basic_router_config(27703).await;
    config_router.set_id(Some(router_id)).unwrap();

    let config_client1 = get_basic_client_config(27703).await;
    let config_client2 = get_basic_client_config(27703).await;

    let router = ztimeout!(open(config_router.clone())).unwrap();
    tokio::time::sleep(SLEEP).await;
    let session1 = ztimeout!(open(config_client1)).unwrap();
    let session2 = ztimeout!(open(config_client2)).unwrap();
    tokio::time::sleep(SLEEP).await;
    let sub = ztimeout!(session2.declare_subscriber("test/cache")).unwrap();
    let pub1 = ztimeout!(session1.declare_publisher("test/cache")).unwrap();
    let pub2 = ztimeout!(session1.declare_publisher("test/*")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 1"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 1"
    );

    let c = TestInterceptorConf {
        flow: InterceptorFlow::Ingress,
        data: "2".to_string(),
    };
    let f = move || test_interceptor_factories(&vec![c.clone()]);
    let _ = crate::net::routing::interceptor::tests::ID_TO_INTERCEPTOR_FACTORIES
        .lock()
        .unwrap()
        .insert(router_id, Box::new(f));

    router
        .static_runtime()
        .unwrap()
        .router()
        .tables
        .update_config(&config_router)
        .unwrap();
    tokio::time::sleep(SLEEP).await;

    ztimeout!(pub1.put("some_data_1")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub2.put("some_data_2")).unwrap();
    let sub2 = ztimeout!(session2.declare_subscriber("test2/cache")).unwrap();
    let pub3 = ztimeout!(session1.declare_publisher("test2/cache")).unwrap();
    tokio::time::sleep(SLEEP).await;
    ztimeout!(pub3.put("some_data_3")).unwrap();

    let msg1 = ztimeout!(sub.recv_async()).unwrap();
    let msg2 = ztimeout!(sub.recv_async()).unwrap();
    let msg3 = ztimeout!(sub2.recv_async()).unwrap();

    assert_eq!(
        msg1.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
    assert_eq!(
        msg2.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: false, data: 2"
    );
    assert_eq!(
        msg3.payload().try_to_string().unwrap().as_ref(),
        "Cache hit: true, data: 2"
    );
}