ice-rpc 0.2.2

Zero-copy RPC over iceoryx2 with automatic reconnection, service discovery and HTTP gateway
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
//! Centralized communication hub of the ice-rpc node.
//!
//! Manages the outgoing publishers (one per target node), the incoming
//! request handlers (Provider mode) and the response handlers (Consumer mode).
//! The dispatch loop drains the `node_{pid}_default`/`node_{pid}_large`
//! subscribers and routes messages to the registered handlers.

use crate::types::{
    node_default_topic, node_large_topic, node_notify_topic, NodeId, RpcHeader,
    LARGE_PAYLOAD_THRESHOLD,
};
use iceoryx2::port::DegradationAction;
use iceoryx2::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, RwLock};

/// Publishers towards a target node, shared under `Arc<NodePublishersArc>`.
///
/// An iceoryx2 publisher does not support simultaneous loans from several
/// threads (ExceedsMaxLoans). The Mutex serializes loan+send.
type NodePublishersArc = Arc<NodePublishersInner>;
struct NodePublishersInner {
    default: Mutex<IpcPublisher>,
    large: Option<Mutex<IpcPublisher>>,
    notifier: iceoryx2::port::notifier::Notifier<iceoryx2::service::ipc_threadsafe::Service>,
}

/// Type of a request handler: called from the dispatch loop.
pub type RequestHandler = Arc<dyn Fn(RpcHeader, &[u8]) + Send + Sync + 'static>;
/// Type of a response handler: called from the dispatch loop.
pub type ResponseHandler = Arc<dyn Fn(Result<&[u8], crate::RpcError>) + Send + Sync + 'static>;

type IpcPublisher = iceoryx2::port::publisher::Publisher<
    iceoryx2::service::ipc_threadsafe::Service,
    [u8],
    RpcHeader,
>;

/// Centralized IPC communication hub of the node.
///
/// Manages the outgoing publishers (one per target node), the incoming
/// request handlers (Provider mode) and the response handlers (Consumer mode).
pub struct NodeHub {
    request_handlers: RwLock<HashMap<String, Vec<RequestHandler>>>,
    response_handlers: Mutex<HashMap<[u8; 16], ResponseHandler>>,
    dispatch_started: std::sync::atomic::AtomicBool,
    publishers: RwLock<HashMap<u32, NodePublishersArc>>,
    publishers_create_lock: Mutex<()>,
    large_payload_enabled: std::sync::atomic::AtomicBool,
    default_message_size_bytes: std::sync::atomic::AtomicUsize,
}

impl NodeHub {
    pub(crate) fn new() -> Self {
        Self {
            request_handlers: RwLock::new(HashMap::new()),
            response_handlers: Mutex::new(HashMap::new()),
            dispatch_started: std::sync::atomic::AtomicBool::new(false),
            publishers: RwLock::new(HashMap::new()),
            publishers_create_lock: Mutex::new(()),
            large_payload_enabled: std::sync::atomic::AtomicBool::new(false),
            default_message_size_bytes: std::sync::atomic::AtomicUsize::new(
                crate::PUBLISHER_DEFAULT_MAX_SLICE_LEN,
            ),
        }
    }

    /// Registers a request handler for a given service.
    pub fn register_request_handler(&self, service_name: &str, handler: RequestHandler) {
        let mut map = self
            .request_handlers
            .write()
            .expect("request_handlers write lock poisoning");
        map.entry(service_name.to_string())
            .or_default()
            .push(handler);
        drop(map);
    }

    /// Returns the list of service names that have a registered handler.
    pub fn registered_services(&self) -> Vec<String> {
        self.request_handlers
            .read()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Registers a response handler for a given correlation_id.
    pub fn register_response_handler(&self, correlation_id: [u8; 16], handler: ResponseHandler) {
        self.response_handlers
            .lock()
            .expect("response_handlers lock poisoning")
            .insert(correlation_id, handler);
    }

    /// Removes the response handler associated with a correlation_id.
    pub fn remove_response_handler(&self, correlation_id: &[u8; 16]) {
        self.response_handlers
            .lock()
            .expect("response_handlers lock poisoning")
            .remove(correlation_id);
    }

    /// Checks whether publishers already exist for a target node.
    pub fn has_publishers(&self, target_node_id: NodeId) -> bool {
        self.publishers
            .read()
            .expect("publishers read lock poisoning")
            .contains_key(&target_node_id.0)
    }

    /// Enables the creation of the large-payload shared-memory segment.
    ///
    /// Called by the code generated by `#[service(allow_large_payload = true)]`.
    /// Once enabled for this process, the `_large` publisher/subscriber pair is
    /// created alongside the `_default` one. The value is monotonic: enabling it
    /// for one service enables it for the whole node.
    pub fn enable_large_payload(&self) {
        self.large_payload_enabled
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    /// Returns `true` when at least one service allows large payloads.
    pub fn is_large_payload_enabled(&self) -> bool {
        self.large_payload_enabled
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Defines the initial slice size of the `_default` publisher.
    ///
    /// Called by the code generated by
    /// `#[service(default_size_message = N)]` (value in bytes). The hub keeps
    /// the largest requested value so that every service can send its messages
    /// through the default shared-memory segment.
    pub fn set_default_message_size_bytes(&self, bytes: usize) {
        self.default_message_size_bytes
            .fetch_max(bytes, std::sync::atomic::Ordering::Relaxed);
    }

    /// Returns the initial slice size used for the `_default` publisher.
    pub fn default_message_size_bytes(&self) -> usize {
        self.default_message_size_bytes
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Sends an RPC message to a target node through the appropriate publisher.
    ///
    /// On failure, the publishers are invalidated and the node_down callbacks
    /// are fired.
    pub fn send_to_node(
        &self,
        target_node_id: NodeId,
        header: RpcHeader,
        payload: &[u8],
    ) -> Result<(), crate::RpcError> {
        let is_large = payload.len() > LARGE_PAYLOAD_THRESHOLD;

        let node_pubs = {
            let publishers = self
                .publishers
                .read()
                .expect("publishers read lock poisoning");
            publishers
                .get(&target_node_id.0)
                .ok_or_else(|| crate::RpcError::ProviderUnavailable {
                    node: target_node_id.0,
                })?
                .clone()
        };

        // A large publisher exists only when `allow_large_payload` was enabled
        // on this node. When it is absent, oversized payloads fall back to the
        // default segment so that the call still works without the second
        // shared-memory segment.
        let use_large = is_large && node_pubs.large.is_some();

        let send_result = {
            let guard = if use_large {
                node_pubs
                    .large
                    .as_ref()
                    .expect("large publisher missing")
                    .lock()
                    .expect("large publisher lock poisoning")
            } else {
                node_pubs
                    .default
                    .lock()
                    .expect("default publisher lock poisoning")
            };
            Self::do_send(&guard, header, payload)
        };
        if send_result.is_ok() {
            let _ = node_pubs
                .notifier
                .notify_with_custom_event_id(EventId::new(1));
        }

        if let Err(ref e) = send_result {
            log::error!(
                "Send failure to {}: {} -- invalidation + callbacks",
                target_node_id,
                e
            );
            self.invalidate_publishers(target_node_id);
            crate::node_supervisor::fire(target_node_id.0);
        }
        send_result
    }

    /// Invalidates the publishers of a target node (following a detected crash).
    pub fn invalidate_publishers(&self, target_node_id: NodeId) {
        self.publishers
            .write()
            .expect("publishers write lock poisoning")
            .remove(&target_node_id.0);
        log::warn!("Publishers invalidated for {}", target_node_id);
    }

    /// Performs the low-level send: `loan_slice_uninit` → write → send.
    #[inline]
    fn do_send(
        pub_guard: &std::sync::MutexGuard<'_, IpcPublisher>,
        header: RpcHeader,
        payload: &[u8],
    ) -> Result<(), crate::RpcError> {
        match pub_guard
            .loan_slice_uninit(payload.len())
            .map_err(|e| crate::RpcError::TransportError(format!("loan_slice_uninit: {:?}", e)))
        {
            Ok(mut sample) => {
                *sample.user_header_mut() = header;
                let sample = sample.write_from_slice(payload);
                sample
                    .send()
                    .map(|_| ())
                    .map_err(|e| crate::RpcError::TransportError(format!("send failed: {:?}", e)))
            }
            Err(e) => Err(e),
        }
    }

    /// Creates the publishers towards a target node if they do not exist yet
    /// (double-checked locking).
    pub fn ensure_publishers(&self, target_node_id: NodeId) -> Result<(), crate::RpcError> {
        if self
            .publishers
            .read()
            .expect("publishers read lock poisoning")
            .contains_key(&target_node_id.0)
        {
            return Ok(());
        }

        let _create_guard = self
            .publishers_create_lock
            .lock()
            .expect("publishers_create_lock poisoning");

        if self
            .publishers
            .read()
            .expect("publishers read lock poisoning")
            .contains_key(&target_node_id.0)
        {
            return Ok(());
        }

        let node = crate::ServiceLocator::global()
            .get_node_sync()
            .map_err(|e| crate::RpcError::TransportError(format!("get_node_sync: {}", e)))?;
        let np = Arc::new(Self::create_node_publishers(
            &node,
            target_node_id,
            self.is_large_payload_enabled(),
            self.default_message_size_bytes(),
        )?);

        self.publishers
            .write()
            .expect("publishers write lock poisoning")
            .insert(target_node_id.0, np);
        Ok(())
    }

    /// Creates the publishers (default, optionally large, notifier) for a target node.
    ///
    /// The `_large` publisher — the second shared-memory segment — is only
    /// created when `allow_large` is `true`. The `_default` publisher uses the
    /// initial slice size configured through `default_size_message`.
    fn create_node_publishers(
        node: &Arc<iceoryx2::node::Node<iceoryx2::service::ipc_threadsafe::Service>>,
        target_node_id: NodeId,
        allow_large: bool,
        default_size: usize,
    ) -> Result<NodePublishersInner, crate::RpcError> {
        let default_pub =
            Self::create_pubsub_publisher(node, &node_default_topic(target_node_id), default_size)?;
        let large_pub = if allow_large {
            Some(Mutex::new(Self::create_pubsub_publisher(
                node,
                &node_large_topic(target_node_id),
                crate::PUBLISHER_LARGE_MAX_SLICE_LEN,
            )?))
        } else {
            None
        };
        let notifier = Self::create_notifier(node, &node_notify_topic(target_node_id))?;
        Ok(NodePublishersInner {
            default: Mutex::new(default_pub),
            large: large_pub,
            notifier,
        })
    }

    /// Creates an iceoryx2 pub-sub publisher on a given topic.
    fn create_pubsub_publisher(
        node: &Arc<iceoryx2::node::Node<iceoryx2::service::ipc_threadsafe::Service>>,
        topic: &str,
        initial_max_slice_len: usize,
    ) -> Result<IpcPublisher, crate::RpcError> {
        let name = ServiceName::new(topic)
            .map_err(|e| crate::RpcError::TransportError(format!("ServiceName({topic}): {e:?}")))?;

        let is_large_topic = topic.ends_with("_large");
        let subscriber_buffer = if is_large_topic {
            crate::LARGE_TOPIC_BUFFER_SIZE
        } else {
            crate::DEFAULT_TOPIC_BUFFER_SIZE
        };

        let svc = node
            .service_builder(&name)
            .publish_subscribe::<[u8]>()
            .user_header::<RpcHeader>()
            .subscriber_max_buffer_size(subscriber_buffer)
            .max_publishers(16)
            .open_or_create()
            .map_err(|e| crate::RpcError::TransportError(format!("open_or_create({topic}): {e:?}")))?;
        svc.publisher_builder()
            .initial_max_slice_len(initial_max_slice_len)
            .allocation_strategy(AllocationStrategy::PowerOfTwo)
            .set_degradation_handler(|_, _| DegradationAction::DegradeAndFail)
            .create()
            .map_err(|e| crate::RpcError::TransportError(format!("publisher create({topic}): {e:?}")))
    }

    /// Creates an iceoryx2 notifier on a given topic.
    fn create_notifier(
        node: &Arc<iceoryx2::node::Node<iceoryx2::service::ipc_threadsafe::Service>>,
        topic: &str,
    ) -> Result<
        iceoryx2::port::notifier::Notifier<iceoryx2::service::ipc_threadsafe::Service>,
        crate::RpcError,
    > {
        let name = ServiceName::new(topic)
            .map_err(|e| crate::RpcError::TransportError(format!("ServiceName({topic}): {e:?}")))?;
        let svc = node
            .service_builder(&name)
            .event()
            .open_or_create()
            .map_err(|e| crate::RpcError::TransportError(format!("open_or_create({topic}): {e:?}")))?;
        svc.notifier_builder()
            .create()
            .map_err(|e| crate::RpcError::TransportError(format!("notifier create({topic}): {e:?}")))
    }

    /// Starts the dispatch loop (IPC message pump) in a `spawn_blocking`.
    ///
    /// Idempotent via [`dispatch_started`]. Receives requests and responses
    /// on the `node_{pid}_default`/`node_{pid}_large` topics and dispatches them
    /// to the registered handlers.
    pub(crate) fn start_dispatch_loop(&self) {
        if self
            .dispatch_started
            .swap(true, std::sync::atomic::Ordering::Relaxed)
        {
            return;
        }

        let node = match crate::ServiceLocator::global().get_node_sync() {
            Ok(n) => n,
            Err(e) => {
                log::error!("get_node_sync failed: {}", e);
                return;
            }
        };

        let local_pid = std::process::id();
        let default_topic = node_default_topic(NodeId(local_pid));
        let large_topic = node_large_topic(NodeId(local_pid));
        let notify_topic = node_notify_topic(NodeId(local_pid));

        let default_sub = Self::open_subscriber(&node, &default_topic);
        let large_sub = if self.is_large_payload_enabled() {
            Self::open_subscriber(&node, &large_topic)
        } else {
            None
        };
        log::debug!(
            "Subscribers: default={} large={}",
            default_sub.is_some(),
            large_sub.is_some()
        );

        let listener = match ServiceName::new(&notify_topic)
            .ok()
            .and_then(|n| node.service_builder(&n).event().open_or_create().ok())
            .and_then(|s| s.listener_builder().create().ok())
        {
            Some(l) => l,
            None => {
                log::error!("Failed to create listener on {}", notify_topic);
                return;
            }
        };

        let cancel = crate::global_cancel_token().clone();

        let handle = crate::rt::spawn_blocking(move || {
            log::info!(
                "Dispatch loop started (pid={}, topics: {}, {})",
                local_pid,
                default_topic,
                large_topic
            );

            let wait_set = WaitSetBuilder::new()
                .create::<iceoryx2::service::ipc_threadsafe::Service>()
                .expect("WaitSetBuilder creation failed");
            let _guard = wait_set
                .attach_notification(&listener)
                .expect("attach_notification failed");

            loop {
                if cancel.is_cancelled() {
                    break;
                }

                let result = wait_set.wait_and_process_once_with_timeout(
                    |_| {
                        while let Ok(Some(_)) = listener.try_wait_one() {}
                        Self::drain_subscriber(&default_sub, &cancel);
                        Self::drain_subscriber(&large_sub, &cancel);
                        CallbackProgression::Continue
                    },
                    std::time::Duration::from_micros(crate::WAITSET_TIMEOUT_US),
                );

                loop {
                    let s = Self::drain_subscriber(&default_sub, &cancel);
                    let l = Self::drain_subscriber(&large_sub, &cancel);
                    if !s && !l {
                        break;
                    }
                    if cancel.is_cancelled() {
                        break;
                    }
                }

                if let Err(_) | Ok(iceoryx2::waitset::WaitSetRunResult::TerminationRequest) = result
                {
                    crate::global_cancel_token().cancel();
                    break;
                }
            }

            log::info!("Dispatch loop stopped.");
        });

        crate::ServiceLocator::global().register_shutdown_handle(handle);
    }

    /// Opens an iceoryx2 subscriber on a given topic.
    fn open_subscriber(
        node: &Arc<iceoryx2::node::Node<iceoryx2::service::ipc_threadsafe::Service>>,
        topic: &str,
    ) -> Option<
        iceoryx2::port::subscriber::Subscriber<
            iceoryx2::service::ipc_threadsafe::Service,
            [u8],
            RpcHeader,
        >,
    > {
        let name = ServiceName::new(topic).ok()?;
        let is_large_topic = topic.ends_with("_large");
        let subscriber_buffer = if is_large_topic {
            crate::LARGE_TOPIC_BUFFER_SIZE
        } else {
            crate::DEFAULT_TOPIC_BUFFER_SIZE
        };
        let svc = node
            .service_builder(&name)
            .publish_subscribe::<[u8]>()
            .user_header::<RpcHeader>()
            .subscriber_max_buffer_size(subscriber_buffer)
            .max_publishers(16)
            .open_or_create()
            .ok()?;
        svc.subscriber_builder()
            .buffer_size(subscriber_buffer)
            .set_degradation_handler(|_, _| DegradationAction::Ignore)
            .create()
            .ok()
    }

    /// Drains a subscriber and returns `true` if at least one sample was processed.
    ///
    /// The hub and the request_handlers snapshot are resolved only once
    /// outside the loop. The handlers never change after init.
    fn drain_subscriber(
        sub: &Option<
            iceoryx2::port::subscriber::Subscriber<
                iceoryx2::service::ipc_threadsafe::Service,
                [u8],
                RpcHeader,
            >,
        >,
        cancel: &crate::rt::CancellationToken,
    ) -> bool {
        let Some(sub) = sub else {
            return false;
        };
        let hub = crate::ServiceLocator::global().hub();
        let req_handlers_snapshot = hub
            .request_handlers
            .read()
            .expect("request_handlers read lock poisoning")
            .clone();
        let mut had_work = false;

        while let Ok(Some(sample)) = sub.receive() {
            if cancel.is_cancelled() {
                break;
            }
            had_work = true;
            let hdr = *sample.user_header();
            let payload = sample.payload();
            let svc = hdr.service();

            if hdr.is_request() {
                if let Some(handlers) = req_handlers_snapshot.get(svc) {
                    for handler in handlers {
                        handler(hdr, payload);
                    }
                }
            } else {
                let cid = hdr.correlation_id;
                let terminal = hdr.event_kind.is_terminal();
                let resp_guard = hub
                    .response_handlers
                    .lock()
                    .expect("response_handlers lock poisoning");
                if let Some(handler) = resp_guard.get(&cid).cloned() {
                    drop(resp_guard);
                    handler(Ok(payload));
                    if terminal {
                        hub.response_handlers
                            .lock()
                            .expect("response_handlers lock poisoning")
                            .remove(&cid);
                    }
                }
            }
        }
        had_work
    }
}

impl crate::ServiceLocator {
    /// Returns the global [`NodeHub`] (singleton).
    pub fn hub(&self) -> &NodeHub {
        static HUB: OnceLock<NodeHub> = OnceLock::new();
        HUB.get_or_init(NodeHub::new)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn new_hub() -> NodeHub {
        NodeHub::new()
    }

    #[test]
    fn register_request_handlers_and_list_services() {
        let hub = new_hub();
        let handler: RequestHandler = Arc::new(|_, _| {});
        hub.register_request_handler("DatabaseService", handler.clone());
        hub.register_request_handler("ConfigService", handler);

        let mut services = hub.registered_services();
        services.sort();
        assert_eq!(
            services,
            vec!["ConfigService".to_string(), "DatabaseService".to_string()]
        );
    }

    #[test]
    fn response_handler_register_and_remove_are_noop_safe() {
        let hub = new_hub();
        let cid = [1u8; 16];
        let handler: ResponseHandler = Arc::new(|_| {});
        hub.register_response_handler(cid, handler);
        hub.remove_response_handler(&cid);
        // Removing an unknown correlation id must not panic.
        hub.remove_response_handler(&cid);
    }

    #[test]
    fn publishers_start_empty_and_invalidate_is_noop() {
        let hub = new_hub();
        let node = NodeId(0x1234_5678);
        assert!(!hub.has_publishers(node));
        hub.invalidate_publishers(node);
        assert!(!hub.has_publishers(node));
    }

    #[test]
    fn large_payload_is_disabled_by_default() {
        let hub = new_hub();
        assert!(!hub.is_large_payload_enabled());
    }

    #[test]
    fn enable_large_payload_is_monotonic() {
        let hub = new_hub();
        hub.enable_large_payload();
        assert!(hub.is_large_payload_enabled());
        // Enabling again must not toggle it back off.
        hub.enable_large_payload();
        assert!(hub.is_large_payload_enabled());
    }

    #[test]
    fn default_message_size_uses_publisher_default() {
        let hub = new_hub();
        assert_eq!(
            hub.default_message_size_bytes(),
            crate::PUBLISHER_DEFAULT_MAX_SLICE_LEN
        );
    }

    #[test]
    fn default_message_size_keeps_largest_requested_value() {
        let hub = new_hub();
        hub.set_default_message_size_bytes(1024);
        hub.set_default_message_size_bytes(512);
        assert_eq!(hub.default_message_size_bytes(), 1024);
    }
}