ice-rpc 0.3.2

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>;
}

/// Trait allowing dynamic invocation of an ice-rpc service through HTTP/JSON.
///
/// Implemented automatically by the `#[service]` macro on each Proxy type.
/// The `HttpGateway` uses this trait to
/// route `/{service}/{method}` HTTP requests to the RPC methods.
///
/// # Example (generated by the macro)
///
/// ```rust,ignore
/// // For a DatabaseService with a get_user_age(name: String) method:
/// let proxy: Arc<dyn HttpCallable> = ...;
/// let response = proxy.http_invoke(
///     "get_user_age",
///     serde_json::json!({"name": "Alice"})
/// ).await?;
/// // → {"status":"ok","data":30}
/// ```
#[async_trait::async_trait]
pub trait HttpCallable: Send + Sync {
    /// Returns the logical name of the service.
    fn service_name(&self) -> &'static str;

    /// Invokes an RPC method dynamically from JSON parameters.
    ///
    /// # Arguments
    /// * `method` — Name of the method to call.
    /// * `params` — Parameters in JSON format. For a GET, the query params
    ///   are converted into a JSON object `{"arg1":"val1",...}`. For a POST,
    ///   the JSON body is passed directly.
    ///
    /// # Returns
    /// * `Ok(Value)` — JSON object `{"status":"ok","data":...}` or `{"status":"error","error":"..."}`.
    /// * `Err(String)` — Technical error (unknown method, invalid parameters, etc.).
    async fn http_invoke(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value, String>;
}

/// 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` → initialization failed, a retry will be performed.
    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) : declares the logical names
///   of the required services for the topological sort and the IPC check.
///
/// 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 (triggers a retry).
    async fn on_init(&self) -> bool {
        true
    }

    /// Declares the logical names of the services this service depends on.
    ///
    /// Used by [`initialize_all`](crate::ServiceLocator::initialize_all) for:
    /// - the topological sort (initialization order);
    /// - the check via iceoryx2 discovery (dependency already active
    ///   in IPC in another process).
    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()));
    }
}