zenobuf-core 0.3.5

A simpler ROS-like framework in Rust with Zenoh transport and Protocol Buffers
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
//! Node abstraction for Zenobuf

use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::client::Client;
use crate::error::{Error, Result};
use crate::executor::CallbackExecutor;
use crate::message::Message;
use crate::parameter::Parameter;
use crate::publisher::Publisher;
use crate::qos::{QosPreset, QosProfile};
use crate::service::Service;
use crate::subscriber::Subscriber;
use crate::transport::ZenohTransport;

/// A guard that automatically cleans up resources when dropped
pub struct DropGuard {
    cleanup: Option<Box<dyn FnOnce() + Send + Sync>>,
}

impl DropGuard {
    pub fn new<F>(cleanup: F) -> Self
    where
        F: FnOnce() + Send + Sync + 'static,
    {
        Self {
            cleanup: Some(Box::new(cleanup)),
        }
    }
}

impl Drop for DropGuard {
    fn drop(&mut self) {
        if let Some(cleanup) = self.cleanup.take() {
            cleanup();
        }
    }
}

/// A handle to a publisher with automatic cleanup
pub struct PublisherHandle<M: Message> {
    publisher: Arc<Publisher<M>>,
    _cleanup: DropGuard,
}

impl<M: Message> PublisherHandle<M> {
    fn new(
        publisher: Arc<Publisher<M>>,
        topic: String,
        publishers_map: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    ) -> Self {
        let cleanup = DropGuard::new(move || {
            publishers_map
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&topic);
            tracing::debug!("Publisher dropped for topic: {}", topic);
        });

        Self {
            publisher,
            _cleanup: cleanup,
        }
    }

    /// Get the underlying publisher
    pub fn publisher(&self) -> &Arc<Publisher<M>> {
        &self.publisher
    }

    /// Publish a message
    pub fn publish(&self, message: &M) -> Result<()> {
        self.publisher.publish(message)
    }

    /// Get the topic name
    pub fn topic(&self) -> &str {
        self.publisher.topic()
    }
}

/// A handle to a subscriber with automatic cleanup
pub struct SubscriberHandle {
    subscriber: Arc<Subscriber>,
    _cleanup: DropGuard,
}

impl SubscriberHandle {
    fn new(
        subscriber: Arc<Subscriber>,
        topic: String,
        subscribers_map: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    ) -> Self {
        let cleanup = DropGuard::new(move || {
            subscribers_map
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&topic);
            tracing::debug!("Subscriber dropped for topic: {}", topic);
        });

        Self {
            subscriber,
            _cleanup: cleanup,
        }
    }

    /// Get the underlying subscriber
    pub fn subscriber(&self) -> &Arc<Subscriber> {
        &self.subscriber
    }
}

/// A handle to a service with automatic cleanup
pub struct ServiceHandle {
    service: Arc<Service>,
    _cleanup: DropGuard,
}

impl ServiceHandle {
    fn new(
        service: Arc<Service>,
        service_name: String,
        services_map: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    ) -> Self {
        let cleanup = DropGuard::new(move || {
            services_map
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&service_name);
            tracing::debug!("Service dropped: {}", service_name);
        });

        Self {
            service,
            _cleanup: cleanup,
        }
    }

    /// Get the underlying service
    pub fn service(&self) -> &Arc<Service> {
        &self.service
    }
}

/// A handle to a client with automatic cleanup
pub struct ClientHandle<Req: Message, Res: Message> {
    client: Arc<Client<Req, Res>>,
    _cleanup: DropGuard,
}

impl<Req: Message, Res: Message> ClientHandle<Req, Res> {
    fn new(
        client: Arc<Client<Req, Res>>,
        service_name: String,
        clients_map: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    ) -> Self {
        let cleanup = DropGuard::new(move || {
            clients_map
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&service_name);
            tracing::debug!("Client dropped for service: {}", service_name);
        });

        Self {
            client,
            _cleanup: cleanup,
        }
    }

    /// Get the underlying client
    pub fn client(&self) -> &Arc<Client<Req, Res>> {
        &self.client
    }

    /// Call the service
    pub fn call(&self, request: &Req) -> Result<Res> {
        self.client.call(request)
    }

    /// Call the service asynchronously
    pub async fn call_async(&self, request: &Req) -> Result<Res> {
        self.client.call_async(request).await
    }
}

/// Node abstraction for Zenobuf
///
/// A Node is the main entry point for using Zenobuf. It provides methods for
/// creating publishers, subscribers, services, and clients.
pub struct Node {
    /// Name of the node
    name: String,
    /// Transport layer
    transport: ZenohTransport,
    /// Callback executor for processing subscriber callbacks
    executor: Arc<CallbackExecutor>,
    /// Publishers
    publishers: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    /// Subscribers
    subscribers: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    /// Services
    services: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    /// Clients
    clients: Arc<Mutex<HashMap<String, Box<dyn std::any::Any + Send + Sync>>>>,
    /// Parameters
    parameters: Mutex<HashMap<String, Parameter>>,
    /// Discovery queryable (keeps node discoverable while alive)
    _discovery_queryable:
        Option<zenoh::query::Queryable<zenoh::handlers::FifoChannelHandler<zenoh::query::Query>>>,
    /// Discovery task handle (detached on drop; terminates when queryable is dropped)
    _discovery_task: Option<tokio::task::JoinHandle<()>>,
}

impl Node {
    /// Prefix for node discovery key expressions
    pub const NODE_PREFIX: &str = "zenobuf/node/";

    /// Creates a new Node with the given name
    pub async fn new(name: &str) -> Result<Self> {
        let transport = ZenohTransport::new().await?;
        Self::with_transport(name, transport).await
    }

    /// Creates a new Node with the given name and transport
    pub async fn with_transport(name: &str, transport: ZenohTransport) -> Result<Self> {
        let (discovery_queryable, discovery_task) =
            Self::create_discovery_queryable(&transport, name).await?;

        Ok(Self {
            name: name.to_string(),
            transport,
            executor: Arc::new(CallbackExecutor::new()),
            publishers: Arc::new(Mutex::new(HashMap::new())),
            subscribers: Arc::new(Mutex::new(HashMap::new())),
            services: Arc::new(Mutex::new(HashMap::new())),
            clients: Arc::new(Mutex::new(HashMap::new())),
            parameters: Mutex::new(HashMap::new()),
            _discovery_queryable: Some(discovery_queryable),
            _discovery_task: Some(discovery_task),
        })
    }

    /// Creates a discovery queryable that responds to node discovery queries
    async fn create_discovery_queryable(
        transport: &ZenohTransport,
        name: &str,
    ) -> Result<(
        zenoh::query::Queryable<zenoh::handlers::FifoChannelHandler<zenoh::query::Query>>,
        tokio::task::JoinHandle<()>,
    )> {
        let key = format!("{}{}", Self::NODE_PREFIX, name);
        let key_expr = zenoh::key_expr::KeyExpr::try_from(key.clone())
            .map_err(|e| Error::node(name, format!("Failed to create discovery key: {}", e)))?;

        let node_info = serde_json::json!({
            "name": name,
            "status": "active",
            "pid": std::process::id(),
        });

        let queryable = transport
            .session()
            .declare_queryable(key_expr)
            .await
            .map_err(Error::from)?;

        // Clone for the spawned task
        let queryable_clone = queryable.clone();
        let info_str = node_info.to_string();
        let key_clone = key.clone();

        let task = tokio::spawn(async move {
            while let Ok(query) = queryable_clone.recv_async().await {
                let _ = query.reply(&key_clone, info_str.clone()).await;
            }
        });

        tracing::debug!("Node '{}' registered for discovery at {}", name, key);

        Ok((queryable, task))
    }

    /// Returns a reference to the callback executor
    ///
    /// This is used internally by the transport layer to queue callbacks.
    #[allow(dead_code)]
    pub(crate) fn executor(&self) -> &Arc<CallbackExecutor> {
        &self.executor
    }

    /// Returns the name of the node
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Creates a publisher for the given topic
    pub async fn create_publisher<M: Message>(
        &self,
        topic: &str,
        qos: QosProfile,
    ) -> Result<Arc<Publisher<M>>> {
        let topic_name = topic.to_string();

        // Fast-path rejection before expensive transport call
        if self.publishers.lock().unwrap().contains_key(&topic_name) {
            return Err(Error::topic_already_exists(&topic_name, &self.name));
        }

        let inner_publisher = self
            .transport
            .create_publisher::<M>(&topic_name, &qos)
            .await?;
        let publisher = Arc::new(Publisher::new(
            topic_name.clone(),
            Box::new(inner_publisher),
        ));

        // Re-check under lock to handle concurrent creation
        let mut publishers = self.publishers.lock().unwrap();
        if publishers.contains_key(&topic_name) {
            return Err(Error::topic_already_exists(&topic_name, &self.name));
        }
        publishers.insert(topic_name, Box::new(publisher.clone()));

        Ok(publisher)
    }

    /// Creates a subscriber for the given topic with a callback
    pub async fn create_subscriber<M: Message, F>(
        &self,
        topic: &str,
        _qos: QosProfile,
        callback: F,
    ) -> Result<Arc<Subscriber>>
    where
        F: Fn(M) + Send + Sync + 'static,
    {
        let topic_name = topic.to_string();

        if self.subscribers.lock().unwrap().contains_key(&topic_name) {
            return Err(Error::topic_already_exists(&topic_name, &self.name));
        }

        let inner_subscriber = self
            .transport
            .create_subscriber::<M, F>(&topic_name, callback, Some(self.executor.clone()))
            .await?;
        let subscriber = Arc::new(Subscriber::new(
            topic_name.clone(),
            Box::new(inner_subscriber),
        ));

        let mut subscribers = self.subscribers.lock().unwrap();
        if subscribers.contains_key(&topic_name) {
            return Err(Error::topic_already_exists(&topic_name, &self.name));
        }
        subscribers.insert(topic_name, Box::new(subscriber.clone()));

        Ok(subscriber)
    }

    /// Creates a service for the given name with a handler
    pub async fn create_service<Req: Message, Res: Message, F>(
        &self,
        service_name: &str,
        handler: F,
    ) -> Result<Arc<Service>>
    where
        F: Fn(Req) -> Result<Res> + Send + Sync + 'static,
    {
        let full_service_name = service_name.to_string();

        if self
            .services
            .lock()
            .unwrap()
            .contains_key(&full_service_name)
        {
            return Err(Error::service_already_exists(
                &full_service_name,
                &self.name,
            ));
        }

        let inner_service = self
            .transport
            .create_service::<Req, Res, F>(&full_service_name, handler)
            .await?;
        let service = Arc::new(Service::new(
            full_service_name.clone(),
            Box::new(inner_service),
        ));

        let mut services = self.services.lock().unwrap();
        if services.contains_key(&full_service_name) {
            return Err(Error::service_already_exists(
                &full_service_name,
                &self.name,
            ));
        }
        services.insert(full_service_name, Box::new(service.clone()));

        Ok(service)
    }

    /// Creates a client for the given service name
    pub fn create_client<Req: Message, Res: Message>(
        &self,
        service_name: &str,
    ) -> Result<Arc<Client<Req, Res>>> {
        // Use the service name as provided by the user (global services by default)
        let full_service_name = service_name.to_string();

        // Check if the client already exists
        let mut clients = self.clients.lock().unwrap();
        if clients.contains_key(&full_service_name) {
            return Err(Error::service_already_exists(
                &full_service_name,
                &self.name,
            ));
        }

        // Create the client
        let inner_client = self
            .transport
            .create_client::<Req, Res>(&full_service_name)?;
        let client = Arc::new(Client::new(
            full_service_name.clone(),
            Box::new(inner_client),
        ));

        // Store the client
        clients.insert(full_service_name, Box::new(client.clone()));

        Ok(client)
    }

    /// Sets a parameter
    pub fn set_parameter<
        T: serde::Serialize + serde::de::DeserializeOwned + Clone + Send + Sync + 'static,
    >(
        &self,
        name: &str,
        value: T,
    ) -> Result<()> {
        let mut parameters = self.parameters.lock().unwrap();
        parameters.insert(name.to_string(), Parameter::new(name, value)?);
        Ok(())
    }

    /// Gets a parameter
    pub fn get_parameter<T: serde::de::DeserializeOwned + Clone + Send + Sync + 'static>(
        &self,
        name: &str,
    ) -> Result<T> {
        let parameters = self.parameters.lock().unwrap();
        parameters
            .get(name)
            .ok_or_else(|| Error::parameter(name, "Parameter not found"))?
            .get_value()
    }

    /// Spins the node once, processing all pending callbacks
    ///
    /// Returns the number of callbacks that were processed.
    pub fn spin_once(&self) -> Result<usize> {
        Ok(self.executor.process_pending())
    }

    /// Spins the node, processing callbacks until the node is shutdown
    ///
    /// This method will block until `shutdown()` is called on the node.
    pub async fn spin(&self) -> Result<()> {
        while !self.executor.is_shutdown() {
            // Register interest in notifications BEFORE draining the queue
            // to avoid a race where enqueue's notify_one fires between
            // process_pending and the await.
            let notified = self.executor.notified();
            let processed = self.spin_once()?;
            if processed == 0 {
                let _ = tokio::time::timeout(Duration::from_secs(1), notified).await;
            }
        }
        Ok(())
    }

    /// Shuts down the node
    ///
    /// This will cause `spin()` to return and prevent new callbacks from being queued.
    pub fn shutdown(&self) {
        self.executor.shutdown();
    }

    /// Returns true if the node has been shutdown
    pub fn is_shutdown(&self) -> bool {
        self.executor.is_shutdown()
    }

    // Builder pattern methods for simplified API

    /// Creates a publisher builder for the given topic
    pub fn publisher<M: Message>(&self, topic: &str) -> PublisherBuilder<'_, M> {
        PublisherBuilder::new(self, topic)
    }

    /// Creates a subscriber builder for the given topic
    pub fn subscriber<M: Message>(&self, topic: &str) -> SubscriberBuilder<'_, M> {
        SubscriberBuilder::new(self, topic)
    }

    /// Creates a service builder for the given service name
    pub fn service<Req: Message, Res: Message>(&self, name: &str) -> ServiceBuilder<'_, Req, Res> {
        ServiceBuilder::new(self, name)
    }

    /// Creates a client builder for the given service name
    pub fn client<Req: Message, Res: Message>(&self, name: &str) -> ClientBuilder<'_, Req, Res> {
        ClientBuilder::new(self, name)
    }

    // Simplified convenience methods

    /// Creates a publisher with default QoS
    pub async fn publish<M: Message>(&self, topic: &str) -> Result<Arc<Publisher<M>>> {
        self.create_publisher(topic, QosProfile::default()).await
    }

    /// Creates a subscriber with default QoS and a callback
    pub async fn subscribe<M: Message, F>(
        &self,
        topic: &str,
        callback: F,
    ) -> Result<Arc<Subscriber>>
    where
        F: Fn(M) + Send + Sync + 'static,
    {
        self.create_subscriber(topic, QosProfile::default(), callback)
            .await
    }
}

/// Builder for creating publishers with fluent API
pub struct PublisherBuilder<'a, M: Message> {
    node: &'a Node,
    topic: String,
    qos: QosProfile,
    _phantom: PhantomData<M>,
}

impl<'a, M: Message> PublisherBuilder<'a, M> {
    fn new(node: &'a Node, topic: &str) -> Self {
        Self {
            node,
            topic: topic.to_string(),
            qos: QosProfile::default(),
            _phantom: PhantomData,
        }
    }

    /// Sets the QoS profile
    pub fn with_qos(mut self, qos: QosProfile) -> Self {
        self.qos = qos;
        self
    }

    /// Sets the QoS preset
    pub fn with_qos_preset(mut self, preset: QosPreset) -> Self {
        self.qos = preset.into();
        self
    }

    /// Sets reliability
    pub fn reliable(mut self) -> Self {
        self.qos.reliability = crate::qos::Reliability::Reliable;
        self
    }

    /// Sets best effort reliability
    pub fn best_effort(mut self) -> Self {
        self.qos.reliability = crate::qos::Reliability::BestEffort;
        self
    }

    /// Sets the history depth
    pub fn with_depth(mut self, depth: usize) -> Self {
        self.qos.depth = depth;
        self
    }

    /// Builds the publisher
    pub async fn build(self) -> Result<PublisherHandle<M>> {
        let topic = self.topic.clone();
        let publisher = self.node.create_publisher(&self.topic, self.qos).await?;
        Ok(PublisherHandle::new(
            publisher,
            topic,
            self.node.publishers.clone(),
        ))
    }
}

/// Builder for creating subscribers with fluent API
pub struct SubscriberBuilder<'a, M: Message> {
    node: &'a Node,
    topic: String,
    qos: QosProfile,
    _phantom: PhantomData<M>,
}

impl<'a, M: Message> SubscriberBuilder<'a, M> {
    fn new(node: &'a Node, topic: &str) -> Self {
        Self {
            node,
            topic: topic.to_string(),
            qos: QosProfile::default(),
            _phantom: PhantomData,
        }
    }

    /// Sets the QoS profile
    pub fn with_qos(mut self, qos: QosProfile) -> Self {
        self.qos = qos;
        self
    }

    /// Sets the QoS preset
    pub fn with_qos_preset(mut self, preset: QosPreset) -> Self {
        self.qos = preset.into();
        self
    }

    /// Sets reliability
    pub fn reliable(mut self) -> Self {
        self.qos.reliability = crate::qos::Reliability::Reliable;
        self
    }

    /// Sets best effort reliability
    pub fn best_effort(mut self) -> Self {
        self.qos.reliability = crate::qos::Reliability::BestEffort;
        self
    }

    /// Sets the history depth
    pub fn with_depth(mut self, depth: usize) -> Self {
        self.qos.depth = depth;
        self
    }

    /// Builds the subscriber with a callback
    pub async fn build<F>(self, callback: F) -> Result<SubscriberHandle>
    where
        F: Fn(M) + Send + Sync + 'static,
    {
        let topic = self.topic.clone();
        let subscriber = self
            .node
            .create_subscriber(&self.topic, self.qos, callback)
            .await?;
        Ok(SubscriberHandle::new(
            subscriber,
            topic,
            self.node.subscribers.clone(),
        ))
    }
}

/// Builder for creating services with fluent API
pub struct ServiceBuilder<'a, Req: Message, Res: Message> {
    node: &'a Node,
    name: String,
    _phantom: PhantomData<(Req, Res)>,
}

impl<'a, Req: Message, Res: Message> ServiceBuilder<'a, Req, Res> {
    fn new(node: &'a Node, name: &str) -> Self {
        Self {
            node,
            name: name.to_string(),
            _phantom: PhantomData,
        }
    }

    /// Builds the service with a handler
    pub async fn build<F>(self, handler: F) -> Result<ServiceHandle>
    where
        F: Fn(Req) -> Result<Res> + Send + Sync + 'static,
    {
        let name = self.name.clone();
        let service = self.node.create_service(&self.name, handler).await?;
        Ok(ServiceHandle::new(
            service,
            name,
            self.node.services.clone(),
        ))
    }
}

/// Builder for creating clients with fluent API
pub struct ClientBuilder<'a, Req: Message, Res: Message> {
    node: &'a Node,
    name: String,
    _phantom: PhantomData<(Req, Res)>,
}

impl<'a, Req: Message, Res: Message> ClientBuilder<'a, Req, Res> {
    fn new(node: &'a Node, name: &str) -> Self {
        Self {
            node,
            name: name.to_string(),
            _phantom: PhantomData,
        }
    }

    /// Builds the client
    pub fn build(self) -> Result<ClientHandle<Req, Res>> {
        let name = self.name.clone();
        let client = self.node.create_client(&self.name)?;
        Ok(ClientHandle::new(client, name, self.node.clients.clone()))
    }
}