ice-rpc 0.3.2

RPC over iceoryx2 shared memory: zero-copy header, rkyv payload, reconnection, discovery and more
Documentation
//! 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;
    }

    /// 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)
    }

    /// 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**.
    ///
    /// A dependency that is not registered locally is treated as external and
    /// never blocks. A cyclic graph falls back to the registration order.
    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 super::topological_order;

    #[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]);
    }
}