Skip to main content

ice_rpc/
lib.rs

1//! ice-rpc — High-performance RPC framework over iceoryx2 shared memory.
2//!
3//! # Overview
4//!
5//! ice-rpc is a client/server RPC framework using iceoryx2 shared memory
6//! as transport. From a simple Rust trait annotated with `#[service]`,
7//! the procedural macro automatically generates the entire IPC code:
8//! client, server, proxy and lifecycle.
9//!
10//! ## Quick start
11//!
12//! A complete, runnable example lives in `examples/quickstart.rs`: one file
13//! holding the service, its provider and its consumer — the two roles picked by
14//! a command-line argument. The steps below are that file.
15//!
16//! ### 1. Define a service
17//!
18//! ```rust,ignore
19//! use ice_rpc::{Observable, service};
20//!
21//! /// The business error of the service.
22//! ///
23//! /// `#[ice_rpc::payload]` supplies the rkyv derives (and `Debug`) — no `rkyv`
24//! /// dependency of your own. The `serde` derives are the ones the optional `json`
25//! /// and `http` features require on every service type.
26//! #[ice_rpc::payload]
27//! #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
28//! pub enum GreeterError {
29//!     /// The name was empty.
30//!     EmptyName,
31//! }
32//!
33//! #[service("GreeterService")]
34//! pub trait GreeterService {
35//!     /// Returns a greeting for `name`.
36//!     async fn hello(&self, name: String) -> Observable<String, GreeterError>;
37//! }
38//! ```
39//!
40//! The `#[service("GreeterService")]` macro automatically generates:
41//! - `GreeterServiceRequest` — rkyv enum for serialization
42//! - `GreeterServiceClient` — IPC client (publish/subscribe, one call per request id)
43//! - `GreeterServiceServer` — IPC server exposing the method dispatcher
44//! - `GreeterServiceProxy` — unified entry point (3 modes)
45//!
46//! ### 2. Start a Provider
47//!
48//! ```rust,ignore
49//! struct Greeter;
50//!
51//! #[ice_rpc::async_trait]
52//! impl GreeterService for Greeter {
53//!     async fn hello(&self, name: String) -> Observable<String, GreeterError> {
54//!         if name.is_empty() {
55//!             // A business error is an observable too: it travels inside the flux.
56//!             return ice_rpc::throw_error(GreeterError::EmptyName);
57//!         }
58//!         // One value, then completion. A handler streaming several values uses
59//!         // the wire-level `ice_rpc::codegen::channel(capacity)`, which returns a
60//!         // `(Sender, Observable)` pair whose `send_complete_with` closes the
61//!         // stream with its last value.
62//!         ice_rpc::of(format!("Hello {name}!"))
63//!     }
64//! }
65//!
66//! #[ice_rpc::main(tokio)]
67//! async fn main() {
68//!     // `#[ice_rpc::main]` owns the bootstrap (init + runtime) and the clean
69//!     // shutdown; `run_provider!` starts the services and waits for Ctrl+C.
70//!     if let Err(error) = ice_rpc::run_provider!(GreeterServiceProxy::provide(Greeter)).await {
71//!         log::error!("provider stopped: {error}");
72//!     }
73//! }
74//! ```
75//!
76//! If an implementation calls `locator().get()` on a service of the **same**
77//! process, declare it in `dependencies()`: the topological sort then initializes
78//! the dependency first.
79//!
80//! ```rust,ignore
81//! #[ice_rpc::main(tokio)]
82//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
83//!     // ServiceBImpl calls ServiceA via locator().get(); both are local, so
84//!     // `ServiceBImpl::dependencies()` lists "ServiceA" and the sort runs
85//!     // ServiceA first.
86//!     ice_rpc::run_provider!(
87//!         ServiceAProxy::provide_with_init(ServiceAImpl::new()),
88//!         ServiceBProxy::provide_with_init(ServiceBImpl::new()),
89//!     ).await
90//! }
91//! ```
92//!
93//! A dependency provided by **another process** is external and never blocks the
94//! startup: no discovery, no connection, no wait — see
95//! [`ServiceInit::dependencies`].
96//!
97//! ### 3. Call from a Consumer
98//!
99//! ```rust,ignore
100//! #[ice_rpc::main(tokio)]
101//! async fn main() {
102//!     // Proxy instantiated lazily, IPC connection on the first RPC call.
103//!     let proxy = ice_rpc::locator()
104//!         .get::<GreeterServiceProxy>().await
105//!         .expect("GreeterService unknown");
106//!
107//!     match proxy.hello("Alice".into()).await.first_value().await {
108//!         Ok(greeting) => log::info!("{greeting}"),
109//!         Err(error) => log::error!("call failed: {error}"),
110//!     }
111//! }
112//! ```
113//!
114//! ### 4. Provider *and* consumer in the same process
115//!
116//! `run_provider!` **never returns before shutdown**: it awaits
117//! `wait_for_shutdown()` and therefore blocks the task that calls it. Code
118//! written *after* its `.await`, in the same task, runs only once the process is
119//! stopping. To serve a provider and drive a Consumer (or any other work) in the
120//! same `main`, **spawn** the provider and keep the caller free:
121//!
122//! ```rust,ignore
123//! #[ice_rpc::main]
124//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
125//!     // `rt::spawn` works in every execution mode (rt-async / tokio / smol);
126//!     // under `#[ice_rpc::main(tokio)]`, `tokio::spawn` is the equivalent.
127//!     ice_rpc::rt::spawn(async {
128//!         if let Err(error) = ice_rpc::run_provider!(
129//!             CoreServiceProxy::provide(Core),
130//!         ).await {
131//!             log::error!("provider stopped: {error}");
132//!         }
133//!     });
134//!
135//!     // Consumer side, on the main task.
136//!     let print = ice_rpc::locator().get::<PrintServiceProxy>().await.unwrap();
137//!     print.print().await.first_value().await?;
138//!     Ok(())
139//! }
140//! ```
141//!
142//! A `rt::block_on(run_provider!(..))` does **not** start the provider in the
143//! background: `block_on` runs a future to completion on the calling thread, and
144//! this future completes only on shutdown — such a call blocks until Ctrl+C.
145//!
146//! ### 5. A blocking consumer, with no runtime at all
147//!
148//! A small consumer that only issues a call needs neither an executor nor an
149//! async `main`: `#[ice_rpc::main(rt-none)]` bootstraps ice-rpc around a plain
150//! **synchronous** `fn main` and shuts it down with `shutdown_blocking` on exit.
151//! The additive blocking surface — [`ServiceLocator::get_blocking`],
152//! [`Observable::first_value_blocking`] and the `{method}_blocking` twins a
153//! `#[service(..., blocking)]` generates — needs neither `.await` nor
154//! [`rt::block_on`]. The only auxiliary thread is the transport's own response
155//! dispatcher.
156//!
157//! ```rust,ignore
158//! #[ice_rpc::main(rt-none)] // init + shutdown_blocking around a sync main
159//! fn main() {
160//!     let proxy = ice_rpc::locator()
161//!         .get_blocking::<MyServiceProxy>()
162//!         .expect("the locator builds the proxy");
163//!
164//!     match proxy.hello_blocking("Alice".into()).first_value_blocking() {
165//!         Ok(value) => log::info!("Response: {value}"),
166//!         Err(e) => log::error!("call failed: {e}"),
167//!     }
168//! }
169//! ```
170//!
171//! A complete program lives in `examples/blocking-consumer-app.rs`.
172//!
173//! ### 6. Knowing whether a provider is connected
174//!
175//! `{Proxy}::is_provider_connected()` answers, **synchronously**, whether a
176//! provider is serving the service's channel right now. The probe is read-only —
177//! it opens the response direction of the channel without ever creating it — so
178//! asking the question cannot make a service appear on the bus, and an unknown
179//! channel answers `Ok(false)` instead of failing.
180//!
181//! ```rust,ignore
182//! // A readiness check, or the decision to take a degraded path, without
183//! // sending a request and waiting for the bounded provider wait.
184//! if GreeterServiceProxy::is_provider_connected()? {
185//!     // A provider is on the channel: this call will not wait for one.
186//!     let greeting = proxy.hello("Alice".into()).await.first_value().await?;
187//! } else {
188//!     log::warn!("GreeterService is not running");
189//! }
190//! ```
191//!
192//! The answer is per **channel** (the `group` of `#[service]`): every service
193//! that shares a group shares it, so it says whether *some* provider serves the
194//! channel, not which service of it is answering. A `true` is therefore a
195//! lower bound on availability, not a guarantee that this exact service is the
196//! one running.
197//!
198//! ### 7. Fire-and-forget methods
199//!
200//! A method declared **without a return type** is a notification: one sample
201//! published, no answer, no terminal event. The generated caller is synchronous
202//! and reports only what the emitter can know — whether a subscriber took the
203//! sample:
204//!
205//! ```rust,ignore
206//! #[service("LogSink", group = "logs")]
207//! pub trait LogSink: Send + Sync + 'static {
208//!     /// One-way: no return type, so nothing is answered.
209//!     async fn push(&self, batch: Vec<LogRecord>);
210//!     /// Request/response: a stream of values comes back.
211//!     async fn tail(&self, count: u32) -> Observable<Vec<LogRecord>, LogError>;
212//! }
213//!
214//! let sink = ice_rpc::locator().get_blocking::<LogSinkProxy>()?;
215//! match sink.push(batch) {      // no `.await`: there is nothing to wait for
216//!     Ok(true) => {}            // a subscriber took the sample
217//!     Ok(false) => drops += 1,  // nobody was there, or the buffer was full
218//!     Err(e) => errors += 1,    // the emission itself failed
219//! }
220//! ```
221//!
222//! The two vocabularies cannot be confused: a method meant to answer produces a
223//! value, so it cannot compile without its return type, and an explicit `-> ()`
224//! is refused with both alternatives named. `Ok(false)` is an ordinary outcome
225//! (best effort), `Err` is a real failure of the emission. On the provider side
226//! the handler still reads its [`CallContext`] — so it inherits the caller's
227//! trace — but it cannot be cancelled: there is no call left to cancel.
228//!
229//! Over the JSON transports a one-way method answers **`202 Accepted`**, with
230//! `delivered` reporting the same flag; no reply body is ever expected.
231//!
232//! # Architecture
233//!
234//! ## Workspace crates
235//!
236//! | Crate             | Role                                               |
237//! |-------------------|----------------------------------------------------|
238//! | `ice-rpc-rx`      | Reactive layer: `Observable`, operators, `Subject`, execution facade |
239//! | `ice-rpc`         | Core framework (protocol, transport, ServiceLocator) |
240//! | `ice-rpc-macros`  | Procedural macros (`#[service]`)                   |
241//! | `common`          | Example services (not shipped)                     |
242//! | `gateway_nodejs`  | Node.js bridge (N-API) for the services            |
243//!
244//! ## Key concepts
245//!
246//! - **Service** : Rust trait annotated with `#[service("Name")]` defining RPC methods
247//! - **Node** : process hosting one or more services, identified by its PID
248//! - **Observable** : the composable stream returned by services; emits
249//!   `Next` / `Complete` / `Error(ObservableError)` where the error is either
250//!   business (`E`) or technical (`RpcError`)
251//! - **ServiceLocator** : registry of the services the process provides, plus a
252//!   lazy cache of the consumer proxies
253//! - **transport** : iceoryx2 publish/subscribe, one channel per group of
254//!   services, correlated by an 8-byte request id (`ice_rpc::transport`)
255//! - **dispatch** : one thread per channel receives the requests and polls each
256//!   handler **once**, on that thread. A handler that answers without yielding
257//!   completes there, exactly as if the transport had called it inline; one that
258//!   `await`s is detached at its first `Pending` and runs as a task on the
259//!   execution facade, so a slow call never holds back the next request of the
260//!   same channel
261//! - **Proxy** : unified entry point supporting 3 modes (Provider / Consumer / ProviderJson)
262//!
263//! ## Main modules
264//!
265//! | Module | Role |
266//! |--------|------|
267//! | `rx` | The reactive layer, re-exported from `ice-rpc-rx`: operators, constructors and multicast primitives, all reachable from the `Observable` stream |
268//! | `rt` | Execution facade, re-exported from `ice-rpc-rx`: `spawn`, `Spawner`, `sleep`, `block_on`, cancellation |
269//! | `types` | Protocol types (`RpcHeader`, `EventKind`, `WireEvent`) and the reactive vocabulary re-exported from `ice-rpc-rx` |
270//! | `transport` | Publish/subscribe transport: one channel per service, correlation by id, streaming bridge |
271//! | `locator` | `ServiceLocator` : registration, lazy consumer proxies, lifecycle |
272//! | `codegen` | Internal contract for the generated code: wire types, provider primitives, constants, plumbing, dependency re-exports (doc-hidden) |
273
274#![cfg_attr(test, allow(clippy::unwrap_used))] // test code may panic
275pub use ice_rpc_macros::{main, payload, service};
276
277// The macro is re-exported so an implementation can write
278// `#[ice_rpc::async_trait]` without declaring the crate; `ice_rpc::codegen`
279// re-exports the crate instead, since generated code names it as a path segment.
280pub use async_trait::async_trait;
281
282// Dependency re-exports (`rkyv`, `serde_json`, `base64`, …) live in `ice_rpc::codegen`.
283
284mod config;
285mod global;
286mod hash;
287mod labels;
288mod locator;
289mod service_traits;
290mod shutdown;
291mod sync;
292mod types;
293
294use crate::global::Global;
295
296/// Internal facade for the code generated by `#[service]`.
297#[doc(hidden)]
298pub mod codegen;
299
300/// Propagation seam between a call collector and the wire.
301///
302/// A call emitted outside a provider handler takes its trace from the collector
303/// installed here ([`crate::trace::install`]), and a served call hands its
304/// incoming context to that collector before the span of the hop is created. The
305/// wire format does not change: the header still carries the same W3C fields.
306///
307/// Gated behind the `tracing` feature, because the hook exists for a
308/// `tracing`-based collector. Without it the transport keeps minting a root trace
309/// per call, which is the behaviour every build had before the hook existed.
310#[cfg(feature = "tracing")]
311pub mod trace;
312
313/// The JSON contract of a service, in both directions.
314///
315/// One [`JsonInvoker`](json::JsonInvoker) per service (the caller side, generated
316/// by `#[service]`) and one [`JsonDispatcher`](json::JsonDispatcher) per process
317/// (the host side, registered by the gateway).
318///
319/// Gated behind the `json` feature, which turns on the whole view at once: the
320/// [`JsonInvoker`](json::JsonInvoker) a JSON *transport* dispatches to (the HTTP
321/// gateway, the Node.js consumer), the rkyv ↔ `serde_json::Value` converters, and
322/// the `ProviderJson` mode a JSON host serves a non-Rust implementation with.
323///
324/// One switch, because the two halves are not two deployments: what decides
325/// whether a **binary** carries the host half is whether it ever builds a
326/// `ProviderJson` proxy (`Proxy::provide_json()`), and the link step answers that
327/// without help. A service crate has no way to know which process will call it, so
328/// asking it to choose per direction was the wrong place for the decision — and a
329/// Rust-to-Rust deployment still enables nothing, so the converters and their
330/// `serde` cost stay out of its build entirely.
331#[cfg(feature = "json")]
332pub mod json;
333
334/// Publish/subscribe transport (one channel per service, correlated by id).
335#[doc(hidden)]
336pub mod transport;
337
338#[cfg(any(
339    feature = "http-threads",
340    feature = "http-smol",
341    feature = "http-tokio"
342))]
343mod http_gateway;
344
345// ── Public API: service traits ─────────────────────────────────────
346// Only `ServiceInit` is implemented by the developer.
347pub use service_traits::ServiceInit;
348
349// ── Public API: the reactive vocabulary ─────────────────────────────
350// Defined by `ice-rpc-rx` and re-exported unchanged: one single stream type.
351pub use ice_rpc_rx::{
352    CancellationToken, Event, Observable, ObservableError, RpcError, defer, from, from_future, of,
353    throw_error,
354};
355#[cfg(feature = "operators")]
356pub use ice_rpc_rx::{RetryPolicy, Subject, Subscription, retry_with};
357
358// Wire-level items live in `ice_rpc::codegen`; the protocol types come from `types`.
359pub use types::{CallContext, TraceContext};
360
361/// Reactive layer, re-exported under its historical path.
362///
363/// The items live in [`ice_rpc_rx`]; this module keeps the paths a consumer of
364/// `ice-rpc` may already use (`ice_rpc::rx::from`, `ice_rpc::rx::Subject`, …).
365pub mod rx {
366    pub use ice_rpc_rx::*;
367}
368
369/// Execution facade, re-exported under its historical path.
370///
371/// `spawn`, `sleep`, `block_on` and the cancellation token live in
372/// [`ice_rpc_rx::rt`]; the transport and the examples keep using them here. The
373/// facade has one full mode per host runtime — `rt-async` (the default),
374/// `tokio`, `smol` — and the modes are exclusive.
375pub mod rt {
376    pub use ice_rpc_rx::rt::*;
377}
378
379// ── Public API: locator ─────────────────────────────────────────────
380pub use locator::ServiceLocator;
381
382// ── Public API: provider liveness ───────────────────────────────────
383// The probe behind `{Proxy}::is_provider_connected()`, exported for hosts that
384// only know the channel name (gateway, readiness endpoint, test).
385pub use transport::is_provider_connected;
386
387// ── Public API: out-of-band monitoring ──────────────────────────────
388pub mod monitor;
389
390/// Global cancellation token for the background IPC threads.
391///
392/// Triggered on shutdown (see [`ShutdownGuard`]) and by
393/// [`shutdown_and_release`].
394#[doc(hidden)]
395pub fn global_cancel_token() -> &'static CancellationToken {
396    static TOKEN: Global<CancellationToken> = Global::new();
397    TOKEN.get_or_init(CancellationToken::new)
398}
399
400/// Secondary cancellation token, kept distinct from [`global_cancel_token`].
401///
402/// Reserved for background helpers that must survive a global cancellation;
403/// both are cancelled by [`shutdown_and_release`] and by [`ShutdownGuard`].
404#[doc(hidden)]
405pub fn registry_cancel_token() -> &'static CancellationToken {
406    static TOKEN: Global<CancellationToken> = Global::new();
407    TOKEN.get_or_init(CancellationToken::new)
408}
409
410/// Cancels both tokens to propagate a termination signal to the IPC threads.
411///
412/// Called by the transport loops when iceoryx2 reports a termination through
413/// its `WaitSet`, or when they observe the termination flag while polling.
414pub(crate) fn request_shutdown() {
415    log::info!("Termination signal received, shutting down...");
416    global_cancel_token().cancel();
417    registry_cancel_token().cancel();
418}
419
420/// Cancels the IPC threads and waits for their termination in a single call.
421///
422/// # Example
423/// ```rust,ignore
424/// // Prefer the guard returned by `init()` (RAII):
425/// let guard = ice_rpc::codegen::init();
426/// // ... usage ...
427/// guard.shutdown().await; // clean shutdown waiting for the IPC threads
428/// ```
429#[doc(hidden)]
430pub async fn shutdown_and_release() {
431    global_cancel_token().cancel();
432    registry_cancel_token().cancel();
433    ServiceLocator::global().release_node().await;
434
435    // `release_node` joins the threads that own the ports, which is what lets
436    // iceoryx2 unlink its services; the `static` port cache is released after.
437    let released = crate::transport::release_process_ports();
438    if released > 0 {
439        log::info!("[ice-rpc] released {released} cached channel port(s)");
440    }
441
442    // Then the node: dropping it removes `nodes/<id>/` and its monitors, so it
443    // must come after the ports.
444    if crate::transport::release_shared_node() {
445        log::info!("[ice-rpc] released the iceoryx2 node");
446    }
447}
448
449/// RAII guard for the automatic shutdown of an ice-rpc process.
450///
451/// On `Drop` (process end or panic), cancels the cancellation tokens.
452/// For a clean shutdown (waiting for the IPC threads), call
453/// [`ShutdownGuard::shutdown`] before the end of `main`.
454///
455/// # Example
456/// ```rust,ignore
457/// #[tokio::main]
458/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
459///     let guard = ice_rpc::codegen::init(); // configures iceoryx2 + enables signal handling
460///     // ... use ice-rpc ...
461///     guard.shutdown().await;
462///     Ok(())
463/// }
464/// ```
465#[doc(hidden)]
466pub struct ShutdownGuard {
467    done: std::sync::atomic::AtomicBool,
468}
469
470impl ShutdownGuard {
471    /// Creates a new shutdown guard.
472    pub fn new() -> Self {
473        Self {
474            done: std::sync::atomic::AtomicBool::new(false),
475        }
476    }
477
478    /// Clean shutdown: cancels the tokens, waits for the IPC threads, releases the node.
479    ///
480    /// Idempotent. After the first call, the subsequent ones have no effect.
481    pub async fn shutdown(&self) {
482        if self.done.swap(true, std::sync::atomic::Ordering::Relaxed) {
483            return;
484        }
485        shutdown_and_release().await;
486    }
487
488    /// Clean shutdown, **blocking the current thread**.
489    ///
490    /// Synchronous twin of [`ShutdownGuard::shutdown`], for a `fn main` that runs
491    /// no async runtime: it drives the same idempotent shutdown without an
492    /// `.await`, so a blocking program keeps one single shape from the call to
493    /// the exit.
494    ///
495    /// # Example
496    /// ```rust,ignore
497    /// let guard = ice_rpc::codegen::init_without_ctrl_c();
498    /// // ... use ice-rpc ...
499    /// guard.shutdown_blocking();
500    /// ```
501    pub fn shutdown_blocking(&self) {
502        crate::rt::block_on(self.shutdown());
503    }
504}
505
506impl Default for ShutdownGuard {
507    fn default() -> Self {
508        Self::new()
509    }
510}
511
512impl Drop for ShutdownGuard {
513    fn drop(&mut self) {
514        if !self.done.load(std::sync::atomic::Ordering::Relaxed) {
515            // Fallback: cancel the tokens without waiting (the process is ending).
516            global_cancel_token().cancel();
517            registry_cancel_token().cancel();
518        }
519    }
520}
521
522/// The `ice-rpc` version this build was compiled from.
523///
524/// Sourced from the crate's own `CARGO_PKG_VERSION`, so a diagnostics surface
525/// can never drift from the manifest the way a hand-written literal does.
526/// `iceoryx2` exposes no equivalent symbol, which is why the gateway reports
527/// this version plus the protocol version instead of inventing a bus version.
528pub const VERSION: &str = env!("CARGO_PKG_VERSION");
529
530/// Returns the global [`ServiceLocator`].
531///
532/// Short alias of [`ServiceLocator::global()`] to reduce verbosity
533/// in applications.
534#[inline]
535pub fn locator() -> &'static ServiceLocator {
536    ServiceLocator::global()
537}
538
539/// Waits for the stop signal (SIGINT/SIGTERM or programmatic cancellation).
540///
541/// Syntactic sugar over `global_cancel_token().cancelled().await`.
542#[doc(hidden)]
543pub async fn wait_for_shutdown() {
544    global_cancel_token().cancelled().await;
545}
546
547// ────────────────────────────────────────────────────────────────────
548// Initialization functions
549// ────────────────────────────────────────────────────────────────────
550
551/// Whether the framework handles the process signals through iceoryx2.
552///
553/// Set by [`init`] (the default) and cleared by [`init_without_ctrl_c`].
554static SIGNAL_HANDLING_ENABLED: std::sync::atomic::AtomicBool =
555    std::sync::atomic::AtomicBool::new(true);
556
557/// Maps the signal-handling flag to the iceoryx2 `WaitSet` mode.
558fn resolve_signal_handling_mode(enabled: bool) -> iceoryx2::prelude::SignalHandlingMode {
559    if enabled {
560        iceoryx2::prelude::SignalHandlingMode::HandleTerminationRequests
561    } else {
562        iceoryx2::prelude::SignalHandlingMode::Disabled
563    }
564}
565
566/// Returns the signal-handling mode the transport must give to its `WaitSet`s.
567pub(crate) fn waitset_signal_handling_mode() -> iceoryx2::prelude::SignalHandlingMode {
568    resolve_signal_handling_mode(SIGNAL_HANDLING_ENABLED.load(std::sync::atomic::Ordering::Relaxed))
569}
570
571/// Initializes the framework and returns the RAII shutdown guard.
572///
573/// Configures iceoryx2 and enables the native signal handling of the `WaitSet`
574/// loops (SIGINT/SIGTERM). The returned guard **must be kept alive**: dropping
575/// it cancels the global tokens. Call [`ShutdownGuard::shutdown`] for a clean
576/// stop.
577///
578/// # Example
579/// ```rust,ignore
580/// let guard = ice_rpc::codegen::init();
581/// let proxy = ice_rpc::locator().get::<MyServiceProxy>().await.unwrap();
582/// // ... use ice-rpc ...
583/// guard.shutdown().await;
584/// ```
585#[doc(hidden)]
586#[must_use = "the guard cancels the ice-rpc tokens when dropped; bind it for the process lifetime"]
587pub fn init() -> ShutdownGuard {
588    SIGNAL_HANDLING_ENABLED.store(true, std::sync::atomic::Ordering::Relaxed);
589    ShutdownGuard::new()
590}
591
592/// Initializes the framework **without** signal handling and returns the RAII
593/// shutdown guard (Node.js gateway, tests…).
594///
595/// Variant of [`init`] for contexts that must manage shutdown manually. The
596/// returned guard should be **stored** for the host lifetime.
597///
598/// # Example
599/// ```rust,ignore
600/// let _guard = ice_rpc::codegen::init_without_ctrl_c();
601/// ```
602#[doc(hidden)]
603#[must_use = "the guard cancels the ice-rpc tokens when dropped; bind it for the host lifetime"]
604pub fn init_without_ctrl_c() -> ShutdownGuard {
605    SIGNAL_HANDLING_ENABLED.store(false, std::sync::atomic::Ordering::Relaxed);
606    ShutdownGuard::new()
607}
608
609/// Starts the HTTP REST gateway with the given service mapping.
610///
611/// Requires the `http` feature and one runtime adapter in `Cargo.toml`:
612/// ```toml
613/// ice-rpc = { features = ["http", "http-tokio"] }
614/// ```
615///
616/// Prefer the [`start_http_gateway!`] macro which builds the mapping
617/// automatically from the list of exposed proxies.
618#[cfg(any(
619    feature = "http-threads",
620    feature = "http-smol",
621    feature = "http-tokio"
622))]
623#[doc(hidden)]
624pub async fn start_http_server(
625    port: u16,
626    factories: std::collections::HashMap<
627        &'static str,
628        fn() -> std::sync::Arc<dyn json::JsonInvoker>,
629    >,
630) {
631    http_gateway::start_http_server(port, factories).await;
632}
633
634/// Starts the HTTP REST gateway exposing the listed services.
635///
636/// Builds locally the `name → factory` mapping from the provided proxy
637/// types, then starts the HTTP server. No build.rs nor global
638/// registry is needed: only the services exposed by this process
639/// are listed here.
640///
641/// # Example
642/// ```rust,ignore
643/// #[ice_rpc::main(tokio)]
644/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
645///     ice_rpc::start_http_gateway!(8080, DatabaseServiceProxy, ConfigServiceProxy).await;
646///     Ok(())
647/// }
648/// ```
649#[cfg(any(
650    feature = "http-threads",
651    feature = "http-smol",
652    feature = "http-tokio"
653))]
654#[macro_export]
655macro_rules! start_http_gateway {
656    ($port:expr, $($proxy:ty),+ $(,)?) => {{
657        let mut __map: std::collections::HashMap<
658            &'static str,
659            fn() -> std::sync::Arc<dyn ice_rpc::codegen::JsonInvoker>,
660        > = std::collections::HashMap::new();
661        $(
662            __map.insert(
663                <$proxy>::SERVICE_NAME,
664                || <$proxy>::consume() as std::sync::Arc<dyn ice_rpc::codegen::JsonInvoker>,
665            );
666        )+
667        ice_rpc::start_http_server($port, __map)
668    }};
669}
670
671/// Object trait allowing [`run_provider!`] to accept heterogeneous
672/// proxies in a `Vec` without knowing their concrete type.
673///
674/// Implemented automatically for any type satisfying the constraints
675/// of [`ServiceLocator::register`]. **Do not implement manually.**
676#[doc(hidden)]
677#[async_trait::async_trait]
678pub trait _ProviderService: Send + Sync + 'static {
679    async fn register_into(&self, locator: &'static ServiceLocator);
680}
681
682#[async_trait::async_trait]
683impl<T> _ProviderService for std::sync::Arc<T>
684where
685    T: crate::service_traits::ServiceLifecycle
686        + crate::service_traits::ServiceNamed
687        + crate::service_traits::ServiceInit
688        + std::any::Any
689        + Send
690        + Sync
691        + 'static,
692{
693    async fn register_into(&self, locator: &'static ServiceLocator) {
694        locator.register(self.clone()).await;
695    }
696}
697
698/// Registers and initializes a list of Provider services, then blocks until the
699/// process shutdown is requested (Ctrl+C).
700///
701/// Internal function called by the [`run_provider!`] macro.
702/// Prefer the macro for direct usage.
703///
704/// The process lifecycle (iceoryx2 bootstrap, signal handling, runtime and
705/// clean shutdown) is owned by `#[ice_rpc::main]`. This function only starts the
706/// services and keeps the process alive until cancellation, so it **must** be
707/// awaited from within an `#[ice_rpc::main]` body.
708///
709/// # This future does not complete before shutdown
710///
711/// It awaits [`wait_for_shutdown`], so it stays pending for the whole process
712/// lifetime and returns only once the process is asked to stop. Any work placed
713/// **after** its `.await` in the same task therefore runs at shutdown, not while
714/// the services are serving. To also drive a Consumer (or anything else) in the
715/// same process, **spawn** the provider instead of awaiting it on the caller's
716/// task — see the third example of [`run_provider!`].
717#[doc(hidden)]
718pub async fn run_provider_inner(
719    services: Vec<Box<dyn _ProviderService>>,
720) -> Result<(), Box<dyn std::error::Error>> {
721    // Idempotent: the `WaitSet`s below report signals even if the macro was
722    // bypassed (e.g. after `init_without_ctrl_c()`).
723    SIGNAL_HANDLING_ENABLED.store(true, std::sync::atomic::Ordering::Relaxed);
724
725    // Reap what killed providers left on the bus, before creating any service
726    // (see `transport::cleanup_dead_nodes`).
727    let reaped = crate::transport::cleanup_dead_nodes();
728    if reaped > 0 {
729        log::info!("[ice-rpc] reaped {reaped} dead node(s) left by previous runs");
730    }
731
732    crate::transport::sweep_orphan_shm_markers();
733
734    let loc = ServiceLocator::global();
735    for svc in services {
736        svc.register_into(loc).await;
737    }
738    loc.initialize_all().await?;
739    log::info!("All services are ready. Press Ctrl+C to stop.");
740    wait_for_shutdown().await;
741    log::info!("Stopping services...");
742    Ok(())
743}
744
745/// Starts the provider with the given services.
746///
747/// Registers each service, initializes everything in topological order, then
748/// blocks until the process shutdown is requested (Ctrl+C). The clean shutdown
749/// itself is owned by `#[ice_rpc::main]`: this macro only starts the services.
750///
751/// Returns a `Future` — must be `.await`ed from an `#[ice_rpc::main]` body.
752///
753/// # It does not return before shutdown
754///
755/// The returned future awaits [`wait_for_shutdown`] and stays pending for the
756/// whole process lifetime. Awaiting it **blocks the calling task** until Ctrl+C:
757/// any statement placed after the `.await` in that same task runs at shutdown,
758/// not while the services are serving. To run a provider *and* other work (a
759/// Consumer, for instance) in the same process, **spawn** it — see the third
760/// example.
761///
762/// # Dependencies are only ordered locally
763///
764/// `provide_with_init` declares [`ServiceInit::dependencies`],
765/// used **only** to order the services registered in this process. A dependency
766/// provided by another process is external and never blocks the startup — there
767/// is no discovery check.
768///
769/// # Example — Pure provider
770/// ```rust,ignore
771/// #[ice_rpc::main(tokio)]
772/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
773///     env_logger::init();
774///     // `#[ice_rpc::main]` owns init + shutdown; `run_provider!` starts them.
775///     ice_rpc::run_provider!(
776///         ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.json")),
777///         DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
778///     ).await
779/// }
780/// ```
781///
782/// # Example — Provider that consumes a service of its own process
783/// ```rust,ignore
784/// #[ice_rpc::main(tokio)]
785/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
786///     env_logger::init();
787///     // DatabaseServiceImpl calls ConfigService via locator().get(); both are
788///     // local, so the topological sort initializes ConfigService first.
789///     ice_rpc::run_provider!(
790///         ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.json")),
791///         DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
792///     ).await
793/// }
794/// ```
795///
796/// # Example — Provider *and* consumer in the same process
797/// ```rust,ignore
798/// #[ice_rpc::main]
799/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
800///     env_logger::init();
801///     // `run_provider!` never returns before shutdown, so it must be spawned,
802///     // not awaited here. `rt::spawn` works in every execution mode; under
803///     // `#[ice_rpc::main(tokio)]`, `tokio::spawn` is the equivalent.
804///     ice_rpc::rt::spawn(async {
805///         if let Err(error) = ice_rpc::run_provider!(
806///             CoreServiceProxy::provide(Core),
807///         ).await {
808///             log::error!("provider stopped: {error}");
809///         }
810///     });
811///
812///     // Consumer side, on the main task.
813///     let print = ice_rpc::locator().get::<PrintServiceProxy>().await.unwrap();
814///     print.print().await.first_value().await?;
815///     Ok(())
816/// }
817/// ```
818#[macro_export]
819macro_rules! run_provider {
820    ($($proxy:expr),+ $(,)?) => {{
821        ice_rpc::run_provider_inner(vec![
822            $(Box::new($proxy) as Box<dyn ice_rpc::_ProviderService>),+
823        ])
824    }};
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    // ── global_cancel_token / registry_cancel_token ──────────────────
832
833    #[test]
834    fn global_cancel_token_is_singleton() {
835        let t1 = global_cancel_token();
836        let t2 = global_cancel_token();
837        assert!(std::ptr::eq(t1, t2), "must return the same instance");
838    }
839
840    #[test]
841    fn registry_cancel_token_is_singleton() {
842        let t1 = registry_cancel_token();
843        let t2 = registry_cancel_token();
844        assert!(std::ptr::eq(t1, t2), "must return the same instance");
845    }
846
847    #[test]
848    fn cancel_tokens_are_distinct() {
849        let t1 = global_cancel_token();
850        let t2 = registry_cancel_token();
851        assert!(!std::ptr::eq(t1, t2), "must be different instances");
852    }
853
854    #[test]
855    fn shutdown_guard_drop_cancels_tokens() {
856        let t1 = global_cancel_token().clone();
857        let t2 = registry_cancel_token().clone();
858        {
859            let _guard = ShutdownGuard::new();
860            // `shutdown()` was not called: `Drop` cancels the tokens.
861        }
862        assert!(t1.is_cancelled());
863        assert!(t2.is_cancelled());
864    }
865
866    // ── locator ──────────────────────────────────────────────────────
867
868    #[test]
869    fn locator_returns_global_instance() {
870        let l1 = locator();
871        let l2 = ServiceLocator::global();
872        assert!(
873            std::ptr::eq(l1, l2),
874            "locator() must be the global instance"
875        );
876    }
877
878    // ── wait_for_shutdown / shutdown_and_release ─────────────────────
879
880    #[test]
881    fn wait_for_shutdown_returns_when_cancelled() {
882        let token = global_cancel_token().clone();
883        // Cancels in 10ms
884        std::thread::spawn(move || {
885            std::thread::sleep(std::time::Duration::from_millis(10));
886            token.cancel();
887        });
888        // Must not block indefinitely.
889        crate::rt::test_block_on(crate::rt::timeout(
890            std::time::Duration::from_secs(2),
891            wait_for_shutdown(),
892        ))
893        .expect("wait_for_shutdown did not return in time");
894    }
895
896    #[test]
897    fn shutdown_and_release_does_not_panic_when_no_node() {
898        // No node created: shutdown must still terminate cleanly.
899        crate::rt::test_block_on(shutdown_and_release());
900    }
901
902    // ── ShutdownGuard::shutdown ──────────────────────────────────────
903
904    #[test]
905    fn the_guard_shuts_down_once() {
906        let guard = ShutdownGuard::new();
907        // First call shuts down...
908        crate::rt::test_block_on(guard.shutdown());
909        // ...the second is a no-op, as is `Drop`: the node is released once.
910        crate::rt::test_block_on(guard.shutdown());
911        drop(guard);
912    }
913
914    /// The blocking twin drives the same idempotent shutdown, and needs no
915    /// runtime: it is the entry point a plain `fn main` uses.
916    #[test]
917    fn the_guard_shuts_down_once_blocking() {
918        let guard = ShutdownGuard::new();
919        guard.shutdown_blocking();
920        guard.shutdown_blocking();
921        drop(guard);
922    }
923
924    // ── signal handling ──────────────────────────────────────────────
925
926    #[test]
927    fn signal_handling_flag_selects_the_waitset_mode() {
928        use iceoryx2::prelude::SignalHandlingMode;
929
930        // Enabled: iceoryx2 captures SIGINT/SIGTERM.
931        assert_eq!(
932            resolve_signal_handling_mode(true),
933            SignalHandlingMode::HandleTerminationRequests
934        );
935        // Disabled: the host keeps the default disposition.
936        assert_eq!(
937            resolve_signal_handling_mode(false),
938            SignalHandlingMode::Disabled
939        );
940    }
941
942    /// Serialises the tests that read or write the process-wide signal flag.
943    fn signal_lock() -> &'static std::sync::Mutex<()> {
944        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
945        &LOCK
946    }
947
948    #[test]
949    fn the_process_handles_signals_by_default() {
950        use iceoryx2::prelude::SignalHandlingMode;
951
952        let _guard = signal_lock().lock().unwrap_or_else(|e| e.into_inner());
953        // Enabled unless `init_without_ctrl_c` was called.
954        assert_eq!(
955            waitset_signal_handling_mode(),
956            SignalHandlingMode::HandleTerminationRequests
957        );
958    }
959
960    #[test]
961    fn the_initializers_choose_who_handles_the_signals() {
962        use iceoryx2::prelude::SignalHandlingMode;
963        use std::sync::atomic::Ordering;
964
965        let _guard = signal_lock().lock().unwrap_or_else(|e| e.into_inner());
966
967        // `init` gives the signals back to iceoryx2, so running it twice is safe.
968        SIGNAL_HANDLING_ENABLED.store(false, Ordering::Relaxed);
969        let guard = init();
970        assert_eq!(
971            waitset_signal_handling_mode(),
972            SignalHandlingMode::HandleTerminationRequests
973        );
974        drop(guard);
975
976        // `init_without_ctrl_c` leaves the disposition to the host.
977        let guard = init_without_ctrl_c();
978        assert_eq!(waitset_signal_handling_mode(), SignalHandlingMode::Disabled);
979        drop(guard);
980
981        // Restore the state this process started with, for the other tests.
982        SIGNAL_HANDLING_ENABLED.store(true, Ordering::Relaxed);
983    }
984}