ice-rpc 0.3.6

RPC over iceoryx2 shared memory: zero-copy header, rkyv payload, reconnection, discovery and more
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
//! Central service registry (Service Locator pattern).
//!
//! Providers call [`ServiceLocator::register`] (via `run_provider!`); consumers
//! are instantiated lazily on the first [`ServiceLocator::get`]. Service
//! discovery and the transport itself are handled by iceoryx2.

use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use async_lock::RwLock;

use crate::global::Global;
use crate::service_traits::{ServiceConsumer, ServiceInit, ServiceLifecycle, ServiceNamed};

/// Groups the facets of a registered service.
#[derive(Clone)]
struct ServiceEntry {
    instance: Arc<dyn Any + Send + Sync>,
    lifecycle: Arc<dyn ServiceLifecycle>,
    init: Arc<dyn ServiceInit>,
}

/// Central registry of the application services (Service Locator pattern).
pub struct ServiceLocator {
    /// Services explicitly registered via [`register`](Self::register)
    /// (Providers). Only these are initialized by
    /// [`initialize_all`](Self::initialize_all).
    entries: RwLock<HashMap<&'static str, ServiceEntry>>,
    /// Cache of Consumer proxies instantiated lazily via
    /// [`get`](Self::get).
    lazy_cache: RwLock<HashMap<&'static str, Arc<dyn Any + Send + Sync>>>,
    /// Blocking IPC thread handles joined at shutdown.
    shutdown_registry: crate::shutdown::ShutdownRegistry,
}

impl ServiceLocator {
    /// Returns the unique global instance of the [`ServiceLocator`] (singleton).
    pub fn global() -> &'static Self {
        static INSTANCE: Global<ServiceLocator> = Global::new();
        INSTANCE.get_or_init(|| Self {
            entries: RwLock::new(HashMap::new()),
            lazy_cache: RwLock::new(HashMap::new()),
            shutdown_registry: crate::shutdown::ShutdownRegistry::new(),
        })
    }

    /// Returns the number of currently registered services.
    pub fn service_count(&self) -> u8 {
        self.entries.try_read().map(|e| e.len() as u8).unwrap_or(0)
    }

    /// Returns the logical names of all the registered local services.
    pub fn service_names(&self) -> Vec<&'static str> {
        self.entries
            .try_read()
            .map(|e| e.keys().copied().collect())
            .unwrap_or_default()
    }

    /// Registers a blocking IPC thread handle in the shutdown registry.
    pub fn register_shutdown_handle(&self, handle: crate::rt::BlockingHandle) {
        self.shutdown_registry.register(handle);
    }

    /// Registers a dispatch thread owning iceoryx2 ports in the shutdown registry.
    ///
    /// The ports are dropped when the thread returns, and dropping them is what
    /// unlinks the shared-memory files of the services it created. A process that
    /// exits without waiting for these threads therefore leaves its services
    /// behind — on a clean shutdown, not only after a kill.
    pub fn register_shutdown_thread(&self, handle: std::thread::JoinHandle<()>) {
        self.shutdown_registry.register_thread(handle);
    }

    /// Waits for the registered blocking threads and releases the node.
    pub async fn release_node(&self) {
        self.shutdown_registry.join_all().await;
    }

    /// Waits for the registered IPC threads, **blocking the current thread**.
    ///
    /// Synchronous twin of [`release_node`](Self::release_node), for a consumer
    /// that runs no async runtime: it joins the dispatch threads at exit so the
    /// iceoryx2 ports are dropped and their shared-memory files unlinked.
    pub fn release_node_blocking(&self) {
        crate::rt::block_on(self.release_node());
    }

    /// Retrieves a proxy by its **type** and returns it ready to use.
    ///
    /// If the proxy is not yet cached, it is instantiated via
    /// [`ServiceConsumer::consume_proxy`] (generated by `#[service]`), cached,
    /// then returned.
    pub async fn get<T: ServiceConsumer>(&self) -> Option<Arc<T>> {
        let name = T::SERVICE_NAME;

        // Fast-path 1: already registered as a Provider.
        {
            let entries = self.entries.read().await;
            if let Some(entry) = entries.get(name) {
                return entry.instance.clone().downcast::<T>().ok();
            }
        }

        // Fast-path 2: already in the lazy cache.
        {
            let cache = self.lazy_cache.read().await;
            if let Some(instance) = cache.get(name) {
                return instance.clone().downcast::<T>().ok();
            }
        }

        // Slow-path: instantiate the Consumer proxy and cache it.
        let proxy: Arc<T> = T::consume_proxy();
        self.lazy_cache
            .write()
            .await
            .entry(name)
            .or_insert_with(|| proxy.clone() as Arc<dyn Any + Send + Sync>);

        Some(proxy)
    }

    /// Retrieves a proxy by its **type**, **blocking the current thread**.
    ///
    /// Synchronous twin of [`get`](Self::get): the same two fast paths (registered
    /// provider, then lazy cache) and the same lazy build through
    /// [`ServiceConsumer::consume_proxy`], with
    /// [`async_lock::RwLock::read_blocking`] / `write_blocking` in place of the
    /// awaited guards.
    ///
    /// Blocks on the locator's lock, so call it from a synchronous entry point (a
    /// `fn main` with no runtime) rather than from inside an async task.
    pub fn get_blocking<T: ServiceConsumer>(&self) -> Option<Arc<T>> {
        let name = T::SERVICE_NAME;

        // Fast-path 1: already registered as a Provider.
        {
            let entries = self.entries.read_blocking();
            if let Some(entry) = entries.get(name) {
                return entry.instance.clone().downcast::<T>().ok();
            }
        }

        // Fast-path 2: already in the lazy cache.
        {
            let cache = self.lazy_cache.read_blocking();
            if let Some(instance) = cache.get(name) {
                return instance.clone().downcast::<T>().ok();
            }
        }

        // Slow-path: instantiate the Consumer proxy and cache it.
        let proxy: Arc<T> = T::consume_proxy();
        self.lazy_cache
            .write_blocking()
            .entry(name)
            .or_insert_with(|| proxy.clone() as Arc<dyn Any + Send + Sync>);

        Some(proxy)
    }

    /// Registers a Provider service, storing its instance and lifecycle.
    pub async fn register<T>(&self, service: Arc<T>)
    where
        T: ServiceLifecycle + ServiceNamed + ServiceInit + Any + Send + Sync + 'static,
    {
        let name: &'static str = T::SERVICE_NAME;
        let instance = service.clone() as Arc<dyn Any + Send + Sync>;
        let init = service.clone() as Arc<dyn ServiceInit>;
        let lifecycle = service as Arc<dyn ServiceLifecycle>;
        self.entries.write().await.insert(
            name,
            ServiceEntry {
                instance,
                lifecycle,
                init,
            },
        );
    }

    /// Initializes all the registered services, **in dependency order**.
    ///
    /// The order comes from [`ServiceInit::dependencies`],
    /// and it only concerns the services registered in **this** process: a
    /// dependency that is not registered locally is treated as **external and
    /// never blocks** — it is ignored by the sort, with no discovery, no
    /// connection and no wait. A cyclic graph falls back to the registration
    /// order.
    ///
    /// A service whose `init()` returns `false` aborts the whole startup: the
    /// first failure is returned as `Err` and the remaining services are **not**
    /// initialized. There is no automatic retry.
    pub async fn initialize_all(&self) -> Result<(), String> {
        let snapshot: Vec<(&'static str, Arc<dyn ServiceLifecycle>, Vec<&'static str>)> = {
            let entries = self.entries.read().await;
            entries
                .iter()
                .map(|(name, entry)| (*name, entry.lifecycle.clone(), entry.init.dependencies()))
                .collect()
        };

        let names: Vec<&'static str> = snapshot.iter().map(|(name, _, _)| *name).collect();
        let deps: Vec<Vec<&'static str>> =
            snapshot.iter().map(|(_, _, deps)| deps.clone()).collect();

        for i in topological_order(&names, &deps) {
            let (name, lifecycle, _) = &snapshot[i];
            if !lifecycle.init().await {
                log::error!("[ServiceLocator] service '{name}' failed to initialize");
                return Err(format!("service '{name}' failed to initialize"));
            }
        }

        // Every provider has registered its channel: start the channel threads.
        crate::transport::start_registered_channels();
        Ok(())
    }
}

/// Returns the initialization indices in dependency order (Kahn's algorithm).
///
/// A dependency that is not in `names` is treated as **external** (provided by
/// another process) and never blocks. A dependency cycle falls back to the
/// registration order instead of dead-locking the process.
fn topological_order(names: &[&'static str], deps: &[Vec<&'static str>]) -> Vec<usize> {
    let registered: HashSet<&'static str> = names.iter().copied().collect();

    let mut remaining: Vec<usize> = (0..names.len()).collect();
    let mut done: HashSet<&'static str> = HashSet::with_capacity(names.len());
    let mut order: Vec<usize> = Vec::with_capacity(names.len());

    while !remaining.is_empty() {
        let mut next_remaining = Vec::new();
        let mut progressed = false;
        for &i in &remaining {
            let ready = deps[i]
                .iter()
                .all(|dep| done.contains(dep) || !registered.contains(dep));
            if ready {
                order.push(i);
                done.insert(names[i]);
                progressed = true;
            } else {
                next_remaining.push(i);
            }
        }
        remaining = next_remaining;
        if !progressed {
            log::warn!(
                "[ServiceLocator] dependency cycle among {:?}; using registration order",
                remaining.iter().map(|&i| names[i]).collect::<Vec<_>>()
            );
            order.append(&mut remaining);
        }
    }
    order
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    /// The locator is a process-global singleton: its tests must not interleave,
    /// or one test's registrations would land in another's counts.
    fn locator_lock() -> &'static Mutex<()> {
        static LOCK: Mutex<()> = Mutex::new(());
        &LOCK
    }

    /// What a mock provider remembers: how it answers, and who observed it.
    struct MockState {
        init_result: bool,
        dependencies: Vec<&'static str>,
        init_calls: Arc<AtomicUsize>,
        init_order: Arc<Mutex<Vec<&'static str>>>,
    }

    impl Default for MockState {
        fn default() -> Self {
            Self {
                init_result: true,
                dependencies: Vec::new(),
                init_calls: Arc::new(AtomicUsize::new(0)),
                init_order: Arc::new(Mutex::new(Vec::new())),
            }
        }
    }

    /// Declares a provider mock. `SERVICE_NAME` is a constant, so two names need
    /// two types; every instance shares the same [`MockState`] shape.
    macro_rules! provider_mock {
        ($name:ident, $service:literal) => {
            struct $name(MockState);

            impl ServiceNamed for $name {
                const SERVICE_NAME: &'static str = $service;
            }

            #[async_trait::async_trait]
            impl ServiceInit for $name {
                fn dependencies(&self) -> Vec<&'static str> {
                    self.0.dependencies.clone()
                }
            }

            #[async_trait::async_trait]
            impl ServiceLifecycle for $name {
                async fn init(&self) -> bool {
                    self.0.init_calls.fetch_add(1, Ordering::Relaxed);
                    if let Ok(mut order) = self.0.init_order.lock() {
                        order.push($service);
                    }
                    self.0.init_result
                }
            }
        };
    }

    // A provider that is also its own consumer: `get::<T>` must hand back the
    // registered instance without ever building a proxy.
    provider_mock!(EchoService, "LocatorEcho");

    static ECHO_PROXY_CREATIONS: AtomicUsize = AtomicUsize::new(0);

    impl ServiceConsumer for EchoService {
        fn consume_proxy() -> Arc<Self> {
            ECHO_PROXY_CREATIONS.fetch_add(1, Ordering::Relaxed);
            Arc::new(EchoService(MockState::default()))
        }
    }

    // A consumer-only service: `get::<T>` must build it lazily, once.
    static CONFIG_PROXY_CREATIONS: AtomicUsize = AtomicUsize::new(0);

    struct ConfigService;

    impl ServiceNamed for ConfigService {
        const SERVICE_NAME: &'static str = "LocatorConfig";
    }

    impl ServiceConsumer for ConfigService {
        fn consume_proxy() -> Arc<Self> {
            CONFIG_PROXY_CREATIONS.fetch_add(1, Ordering::Relaxed);
            Arc::new(ConfigService)
        }
    }

    // A name shared by a provider and an unrelated consumer type.
    provider_mock!(NamesakeProvider, "LocatorNamesake");

    struct NamesakeConsumer;

    impl ServiceNamed for NamesakeConsumer {
        const SERVICE_NAME: &'static str = "LocatorNamesake";
    }

    impl ServiceConsumer for NamesakeConsumer {
        fn consume_proxy() -> Arc<Self> {
            Arc::new(NamesakeConsumer)
        }
    }

    provider_mock!(FirstService, "LocatorFirst");
    provider_mock!(SecondService, "LocatorSecond");
    provider_mock!(BrokenService, "LocatorBroken");

    #[test]
    fn a_registered_provider_is_handed_back_without_a_proxy() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();

        let state = MockState {
            init_result: true,
            ..MockState::default()
        };
        let init_calls = state.init_calls.clone();
        let provider = Arc::new(EchoService(state));

        let before = locator.service_count();
        pollster::block_on(locator.register(provider.clone()));

        assert_eq!(locator.service_count(), before + 1);
        assert!(locator.service_names().contains(&"LocatorEcho"));

        // Fast-path 1: the registered provider, by type.
        let fetched = pollster::block_on(locator.get::<EchoService>())
            .expect("a registered provider is returned");
        assert!(
            Arc::ptr_eq(&fetched, &provider),
            "the very same instance must come back"
        );
        assert_eq!(
            ECHO_PROXY_CREATIONS.load(Ordering::Relaxed),
            0,
            "the registered path must not build a proxy"
        );
        assert_eq!(
            init_calls.load(Ordering::Relaxed),
            0,
            "registering a service runs no initialization hook"
        );
    }

    #[test]
    fn an_unregistered_service_is_built_once_and_cached() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();

        // Slow path: the proxy is built, then cached (fast-path 2 answers next).
        let first = pollster::block_on(locator.get::<ConfigService>()).expect("a proxy is built");
        let second = pollster::block_on(locator.get::<ConfigService>()).expect("the cache answers");

        assert!(Arc::ptr_eq(&first, &second), "the cached proxy is reused");
        assert_eq!(first.service_name(), "LocatorConfig");
        assert_eq!(CONFIG_PROXY_CREATIONS.load(Ordering::Relaxed), 1);
        // A lazily built proxy is not a registered provider.
        assert!(!locator.service_names().contains(&"LocatorConfig"));
    }

    #[test]
    fn a_name_registered_under_another_type_is_not_returned() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();
        pollster::block_on(locator.register(Arc::new(NamesakeProvider(MockState::default()))));

        // The name is registered, but the entry holds another concrete type: the
        // lookup reports nothing rather than handing back a foreign instance.
        assert!(pollster::block_on(locator.get::<NamesakeConsumer>()).is_none());
    }

    #[test]
    fn initialize_all_orders_dependencies_and_reports_a_failure() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();

        let init_order: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let second = Arc::new(SecondService(MockState {
            init_order: init_order.clone(),
            ..MockState::default()
        }));
        // `First` depends on `Second`, registered first: the sort must reorder.
        let first = Arc::new(FirstService(MockState {
            dependencies: vec!["LocatorSecond"],
            init_order: init_order.clone(),
            ..MockState::default()
        }));
        pollster::block_on(locator.register(first.clone()));
        pollster::block_on(locator.register(second.clone()));

        pollster::block_on(locator.initialize_all()).expect("every service initializes");

        let recorded = init_order.lock().expect("init order").clone();
        let first_at = recorded
            .iter()
            .position(|name| *name == "LocatorFirst")
            .expect("First was initialized");
        let second_at = recorded
            .iter()
            .position(|name| *name == "LocatorSecond")
            .expect("Second was initialized");
        assert!(
            second_at < first_at,
            "a dependency must initialize first: {recorded:?}"
        );
        assert_eq!(first.0.init_calls.load(Ordering::Relaxed), 1);
        assert_eq!(second.0.init_calls.load(Ordering::Relaxed), 1);

        // A provider that refuses to initialize aborts the pass, and names itself.
        let broken = Arc::new(BrokenService(MockState {
            init_result: false,
            ..MockState::default()
        }));
        pollster::block_on(locator.register(broken));
        let error = pollster::block_on(locator.initialize_all()).expect_err("the pass fails");
        assert!(error.contains("LocatorBroken"), "{error}");
    }

    #[test]
    fn shutdown_handles_are_registered_on_the_locator() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();
        // Both registrations complete immediately, so a later `release_node` (from
        // another test) joins them without blocking.
        locator.register_shutdown_handle(crate::rt::spawn_blocking(|| {}));
        locator.register_shutdown_thread(std::thread::spawn(|| {}));
    }

    #[test]
    fn dependencies_come_first() {
        // `DatabaseService` depends on `ConfigService`, registered after it.
        let names = ["DatabaseService", "ConfigService"];
        let deps = [vec!["ConfigService"], vec![]];
        assert_eq!(topological_order(&names, &deps), vec![1, 0]);
    }

    #[test]
    fn independent_services_keep_the_registration_order() {
        let names = ["A", "B", "C"];
        let deps = [vec![], vec![], vec![]];
        assert_eq!(topological_order(&names, &deps), vec![0, 1, 2]);
    }

    #[test]
    fn external_dependencies_do_not_block() {
        // `A` depends on a service provided by another process.
        let names = ["A"];
        let deps = [vec!["RemoteService"]];
        assert_eq!(topological_order(&names, &deps), vec![0]);
    }

    #[test]
    fn a_cycle_falls_back_to_the_registration_order() {
        let names = ["A", "B"];
        let deps = [vec!["B"], vec!["A"]];
        let order = topological_order(&names, &deps);
        assert_eq!(order.len(), 2);
        assert!(order.contains(&0) && order.contains(&1));
    }

    #[test]
    fn chained_dependencies_are_fully_ordered() {
        let names = ["C", "B", "A"];
        let deps = [vec!["B"], vec!["A"], vec![]];
        assert_eq!(topological_order(&names, &deps), vec![2, 1, 0]);
    }

    #[test]
    fn a_dependency_registered_by_another_process_is_external() {
        // Only `First` is local; its dependency belongs to another process and
        // must never hold the pass up.
        let names = ["LocatorFirst"];
        let deps = [vec!["LocatorSecond"]];
        assert_eq!(topological_order(&names, &deps), vec![0]);
    }

    #[test]
    fn a_self_dependency_is_a_cycle() {
        let names = ["A"];
        let deps = [vec!["A"]];
        // The fallback returns the remaining indices rather than looping forever.
        assert_eq!(topological_order(&names, &deps), vec![0]);
    }

    #[test]
    fn an_empty_registry_orders_nothing() {
        assert!(topological_order(&[], &[]).is_empty());
    }

    /// The blocking twin returns the very same registered instance, without
    /// entering a runtime.
    #[test]
    fn get_blocking_hands_back_the_registered_provider() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();

        let provider = Arc::new(EchoService(MockState::default()));
        pollster::block_on(locator.register(provider.clone()));

        let fetched = locator
            .get_blocking::<EchoService>()
            .expect("a registered provider is returned");
        assert!(Arc::ptr_eq(&fetched, &provider));
    }

    /// The blocking twin builds a consumer proxy lazily, then serves it from the
    /// cache — a lazily built proxy is never a registered provider.
    #[test]
    fn get_blocking_builds_and_caches_a_consumer_proxy() {
        let _guard = locator_lock().lock().unwrap_or_else(|e| e.into_inner());
        let locator = ServiceLocator::global();

        let first = locator
            .get_blocking::<ConfigService>()
            .expect("a proxy is built");
        let second = locator
            .get_blocking::<ConfigService>()
            .expect("the cache answers");

        assert!(Arc::ptr_eq(&first, &second), "the cached proxy is reused");
        assert_eq!(first.service_name(), "LocatorConfig");
        assert!(!locator.service_names().contains(&"LocatorConfig"));
    }
}