ice-rpc 0.3.6

RPC over iceoryx2 shared memory: zero-copy header, rkyv payload, reconnection, discovery and more
Documentation
//! Fundamental traits of the ice-rpc service lifecycle.
//!
//! These traits are the contract between the [`ServiceLocator`](crate::ServiceLocator)
//! and the services (Providers and Consumers). They are implemented automatically
//! by the `#[service]` macro — the user only implements them manually
//! for [`ServiceInit`] (initialization hook).

use std::sync::Arc;

/// Consumer factory trait, implemented automatically by the
/// `#[service]` macro on each Proxy type.
///
/// Allows [`ServiceLocator::get`](crate::ServiceLocator::get) to instantiate
/// a Consumer proxy on demand **from the type alone**, with no global
/// registry nor service list.
pub trait ServiceConsumer: ServiceNamed + Send + Sync + 'static {
    /// Builds and returns a Consumer-mode proxy, ready to use.
    fn consume_proxy() -> Arc<Self>;
}

// The JSON view of a service lives in [`crate::json`], in both directions: a
// JSON contract does not belong to the lifecycle traits below.

/// Trait defining the lifecycle of a service.
///
/// The [`init`](ServiceLifecycle::init) method is called during the
/// initialization phase to check that the service is ready to run.
#[async_trait::async_trait]
pub trait ServiceLifecycle: Send + Sync + 'static {
    /// Initializes the service and checks that it is operational.
    ///
    /// # Returns
    /// - `true`  → the service is ready.
    /// - `false` → the initialization of this service failed:
    ///   [`initialize_all`](crate::ServiceLocator::initialize_all)
    ///   **aborts the whole startup** with an error naming this service, and the
    ///   remaining services are left uninitialized. There is **no automatic
    ///   retry**: a `false` is a deterministic failure, not a transient one.
    async fn init(&self) -> bool;
}

/// Trait generated automatically by the `#[service]` macro on the Proxy.
///
/// Provides the logical name of the service both as a **type constant**
/// (`SERVICE_NAME`) for static resolution and as an **instance method**
/// (`service_name()`) for dynamic resolution.
///
/// **The user never implements this trait manually**: the logical name
/// is injected at compile time from the macro parameter.
pub trait ServiceNamed: Send + Sync + 'static {
    /// Logical name of the service, defined via `#[service("Name")]`.
    ///
    /// Used by [`ServiceLocator::get`](crate::ServiceLocator::get) to resolve the service
    /// without any extra parameter — the type alone is sufficient.
    const SERVICE_NAME: &'static str;

    /// Returns the logical name of the service.
    ///
    /// Default implementation: delegates to [`Self::SERVICE_NAME`].
    fn service_name(&self) -> &'static str {
        Self::SERVICE_NAME
    }
}

/// Optional initialization trait that a business type can implement.
///
/// - [`on_init`](ServiceInit::on_init) : hook called before the IPC server starts.
/// - [`dependencies`](ServiceInit::dependencies) : logical names of the services
///   this one depends on, used **only to order the local initialization** — see
///   the method for what it does *not* do.
///
/// The service name itself is **not** to be provided here: it is injected
/// automatically by the macro via [`ServiceNamed`].
#[async_trait::async_trait]
pub trait ServiceInit: Send + Sync + 'static {
    /// Initialization hook called before the IPC server starts.
    ///
    /// # Returns
    /// - `true`  → success.
    /// - `false` → failure: [`initialize_all`](crate::ServiceLocator::initialize_all)
    ///   **aborts the whole startup** with an error naming this service. There is
    ///   **no automatic retry**; return `false` only to fail the provider
    ///   deterministically (a bad configuration file, for instance).
    async fn on_init(&self) -> bool {
        true
    }

    /// Declares the logical names of the services this service depends on.
    ///
    /// # What it does
    ///
    /// The names feed the **topological sort** of
    /// [`initialize_all`](crate::ServiceLocator::initialize_all):
    /// among the services registered in **this** process, a service is
    /// initialized after the ones it lists here.
    ///
    /// # What it does *not* do
    ///
    /// A dependency that is **not registered locally** — that is, provided by
    /// another process — is treated as **external and never blocks**: it is
    /// ignored by the sort, and no attempt is made to discover it, connect to it,
    /// or wait for it. There is therefore **no iceoryx2 discovery check** at
    /// initialization, and a provider reports itself ready even when a declared
    /// external dependency is not running.
    ///
    /// # Where the coupling actually happens
    ///
    /// Lazily, **at call time**. `locator().get::<P>()` builds a Consumer proxy
    /// without any connection; the first RPC then opens the channel — creating it
    /// if no provider exists yet — and waits a **bounded** provider wait (30 s by
    /// default, `ICE_RPC_PROVIDER_WAIT_MS` overrides it) for a subscriber before
    /// failing with a [`TransportError`](crate::RpcError::TransportError) reading
    /// `no subscriber connected`.
    ///
    /// To require an external dependency at startup, implement the check inside
    /// [`on_init`](ServiceInit::on_init) yourself (a typed `ping` with a bounded
    /// retry) and return `false` when it is not reachable.
    fn dependencies(&self) -> Vec<&'static str> {
        vec![]
    }
}

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

    // ── Mock implementations ─────────────────────────────────────────

    struct MyService;
    impl ServiceNamed for MyService {
        const SERVICE_NAME: &'static str = "MyService";
    }

    struct ServiceWithDeps;
    impl ServiceNamed for ServiceWithDeps {
        const SERVICE_NAME: &'static str = "ServiceWithDeps";
    }

    #[async_trait::async_trait]
    impl ServiceInit for ServiceWithDeps {
        fn dependencies(&self) -> Vec<&'static str> {
            vec!["DatabaseService", "ConfigService"]
        }
    }

    struct FailingInitService;
    impl ServiceNamed for FailingInitService {
        const SERVICE_NAME: &'static str = "FailingInitService";
    }

    #[async_trait::async_trait]
    impl ServiceLifecycle for FailingInitService {
        async fn init(&self) -> bool {
            false
        }
    }

    struct SuccessInitService;
    impl ServiceNamed for SuccessInitService {
        const SERVICE_NAME: &'static str = "SuccessInitService";
    }

    #[async_trait::async_trait]
    impl ServiceLifecycle for SuccessInitService {
        async fn init(&self) -> bool {
            true
        }
    }

    // ── ServiceNamed ─────────────────────────────────────────────────

    #[test]
    fn service_named_const_is_accessible() {
        assert_eq!(MyService::SERVICE_NAME, "MyService");
    }

    #[test]
    fn service_named_default_method_delegates_to_const() {
        let svc = MyService;
        assert_eq!(svc.service_name(), "MyService");
    }

    #[test]
    fn service_named_different_services_have_different_names() {
        assert_ne!(MyService::SERVICE_NAME, ServiceWithDeps::SERVICE_NAME);
    }

    // ── ServiceInit defaults ─────────────────────────────────────────

    #[test]
    fn service_init_default_on_init_returns_true() {
        // MyService implements ServiceInit via the default trait (not explicitly)
        // We create a wrapper to test the default behavior.
        struct DefaultInit;
        impl ServiceNamed for DefaultInit {
            const SERVICE_NAME: &'static str = "DefaultInit";
        }
        #[async_trait::async_trait]
        impl ServiceInit for DefaultInit {}

        let svc = DefaultInit;
        assert!(pollster::block_on(svc.on_init()));
    }

    #[test]
    fn service_init_default_dependencies_is_empty() {
        struct DefaultInit;
        impl ServiceNamed for DefaultInit {
            const SERVICE_NAME: &'static str = "DefaultInit";
        }
        #[async_trait::async_trait]
        impl ServiceInit for DefaultInit {}

        let svc = DefaultInit;
        assert!(svc.dependencies().is_empty());
    }

    #[test]
    fn service_init_custom_dependencies() {
        let svc = ServiceWithDeps;
        let deps = svc.dependencies();
        assert_eq!(deps.len(), 2);
        assert!(deps.contains(&"DatabaseService"));
        assert!(deps.contains(&"ConfigService"));
    }

    // ── ServiceLifecycle ─────────────────────────────────────────────

    #[test]
    fn lifecycle_init_success() {
        let svc = SuccessInitService;
        assert!(pollster::block_on(svc.init()));
    }

    #[test]
    fn lifecycle_init_failure() {
        let svc = FailingInitService;
        assert!(!pollster::block_on(svc.init()));
    }
}