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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! ice-rpc — High-performance RPC framework over iceoryx2 shared memory.
//!
//! # Overview
//!
//! ice-rpc is a client/server RPC framework using iceoryx2 shared memory
//! as transport. From a simple Rust trait annotated with `#[service]`,
//! the procedural macro automatically generates the entire IPC code:
//! client, server, proxy and lifecycle.
//!
//! ## Quick start
//!
//! A complete, runnable example lives in `examples/quickstart.rs`: one file
//! holding the service, its provider and its consumer — the two roles picked by
//! a command-line argument. The steps below are that file.
//!
//! ### 1. Define a service
//!
//! ```rust,ignore
//! use ice_rpc::{Observable, service};
//!
//! /// The business error of the service.
//! ///
//! /// `#[ice_rpc::payload]` supplies the rkyv derives (and `Debug`) — no `rkyv`
//! /// dependency of your own. The `serde` derives are the ones the optional `json`
//! /// and `http` features require on every service type.
//! #[ice_rpc::payload]
//! #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
//! pub enum GreeterError {
//!     /// The name was empty.
//!     EmptyName,
//! }
//!
//! #[service("GreeterService")]
//! pub trait GreeterService {
//!     /// Returns a greeting for `name`.
//!     async fn hello(&self, name: String) -> Observable<String, GreeterError>;
//! }
//! ```
//!
//! The `#[service("GreeterService")]` macro automatically generates:
//! - `GreeterServiceRequest` — rkyv enum for serialization
//! - `GreeterServiceClient` — IPC client (publish/subscribe, one call per request id)
//! - `GreeterServiceServer` — IPC server exposing the method dispatcher
//! - `GreeterServiceProxy` — unified entry point (3 modes)
//!
//! ### 2. Start a Provider
//!
//! ```rust,ignore
//! struct Greeter;
//!
//! #[ice_rpc::async_trait]
//! impl GreeterService for Greeter {
//!     async fn hello(&self, name: String) -> Observable<String, GreeterError> {
//!         if name.is_empty() {
//!             // A business error is an observable too: it travels inside the flux.
//!             return ice_rpc::throw_error(GreeterError::EmptyName);
//!         }
//!         // One value, then completion. A handler streaming several values uses
//!         // the wire-level `ice_rpc::codegen::channel(capacity)`, which returns a
//!         // `(Sender, Observable)` pair whose `send_complete_with` closes the
//!         // stream with its last value.
//!         ice_rpc::of(format!("Hello {name}!"))
//!     }
//! }
//!
//! #[ice_rpc::main(tokio)]
//! async fn main() {
//!     // `#[ice_rpc::main]` owns the bootstrap (init + runtime) and the clean
//!     // shutdown; `run_provider!` starts the services and waits for Ctrl+C.
//!     if let Err(error) = ice_rpc::run_provider!(GreeterServiceProxy::provide(Greeter)).await {
//!         log::error!("provider stopped: {error}");
//!     }
//! }
//! ```
//!
//! If an implementation calls `locator().get()` on a service of the **same**
//! process, declare it in `dependencies()`: the topological sort then initializes
//! the dependency first.
//!
//! ```rust,ignore
//! #[ice_rpc::main(tokio)]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // ServiceBImpl calls ServiceA via locator().get(); both are local, so
//!     // `ServiceBImpl::dependencies()` lists "ServiceA" and the sort runs
//!     // ServiceA first.
//!     ice_rpc::run_provider!(
//!         ServiceAProxy::provide_with_init(ServiceAImpl::new()),
//!         ServiceBProxy::provide_with_init(ServiceBImpl::new()),
//!     ).await
//! }
//! ```
//!
//! A dependency provided by **another process** is external and never blocks the
//! startup: no discovery, no connection, no wait — see
//! [`ServiceInit::dependencies`].
//!
//! ### 3. Call from a Consumer
//!
//! ```rust,ignore
//! #[ice_rpc::main(tokio)]
//! async fn main() {
//!     // Proxy instantiated lazily, IPC connection on the first RPC call.
//!     let proxy = ice_rpc::locator()
//!         .get::<GreeterServiceProxy>().await
//!         .expect("GreeterService unknown");
//!
//!     match proxy.hello("Alice".into()).await.first_value().await {
//!         Ok(greeting) => log::info!("{greeting}"),
//!         Err(error) => log::error!("call failed: {error}"),
//!     }
//! }
//! ```
//!
//! ### 4. Provider *and* consumer in the same process
//!
//! `run_provider!` **never returns before shutdown**: it awaits
//! `wait_for_shutdown()` and therefore blocks the task that calls it. Code
//! written *after* its `.await`, in the same task, runs only once the process is
//! stopping. To serve a provider and drive a Consumer (or any other work) in the
//! same `main`, **spawn** the provider and keep the caller free:
//!
//! ```rust,ignore
//! #[ice_rpc::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // `rt::spawn` works in every execution mode (rt-async / tokio / smol);
//!     // under `#[ice_rpc::main(tokio)]`, `tokio::spawn` is the equivalent.
//!     ice_rpc::rt::spawn(async {
//!         if let Err(error) = ice_rpc::run_provider!(
//!             CoreServiceProxy::provide(Core),
//!         ).await {
//!             log::error!("provider stopped: {error}");
//!         }
//!     });
//!
//!     // Consumer side, on the main task.
//!     let print = ice_rpc::locator().get::<PrintServiceProxy>().await.unwrap();
//!     print.print().await.first_value().await?;
//!     Ok(())
//! }
//! ```
//!
//! A `rt::block_on(run_provider!(..))` does **not** start the provider in the
//! background: `block_on` runs a future to completion on the calling thread, and
//! this future completes only on shutdown — such a call blocks until Ctrl+C.
//!
//! ### 5. A blocking consumer, with no runtime at all
//!
//! A small consumer that only issues a call needs neither an executor nor an
//! async `main`: `#[ice_rpc::main(rt-none)]` bootstraps ice-rpc around a plain
//! **synchronous** `fn main` and shuts it down with `shutdown_blocking` on exit.
//! The additive blocking surface — [`ServiceLocator::get_blocking`],
//! [`Observable::first_value_blocking`] and the `{method}_blocking` twins a
//! `#[service(..., blocking)]` generates — needs neither `.await` nor
//! [`rt::block_on`]. The only auxiliary thread is the transport's own response
//! dispatcher.
//!
//! ```rust,ignore
//! #[ice_rpc::main(rt-none)] // init + shutdown_blocking around a sync main
//! fn main() {
//!     let proxy = ice_rpc::locator()
//!         .get_blocking::<MyServiceProxy>()
//!         .expect("the locator builds the proxy");
//!
//!     match proxy.hello_blocking("Alice".into()).first_value_blocking() {
//!         Ok(value) => log::info!("Response: {value}"),
//!         Err(e) => log::error!("call failed: {e}"),
//!     }
//! }
//! ```
//!
//! A complete program lives in `examples/blocking-consumer-app.rs`.
//!
//! # Architecture
//!
//! ## Workspace crates
//!
//! | Crate             | Role                                               |
//! |-------------------|----------------------------------------------------|
//! | `ice-rpc-rx`      | Reactive layer: `Observable`, operators, `Subject`, execution facade |
//! | `ice-rpc`         | Core framework (protocol, transport, ServiceLocator) |
//! | `ice-rpc-macros`  | Procedural macros (`#[service]`)                   |
//! | `common`          | Example services (not shipped)                     |
//! | `gateway_nodejs`  | Node.js bridge (N-API) for the services            |
//!
//! ## Key concepts
//!
//! - **Service** : Rust trait annotated with `#[service("Name")]` defining RPC methods
//! - **Node** : process hosting one or more services, identified by its PID
//! - **Observable** : the composable stream returned by services; emits
//!   `Next` / `Complete` / `Error(ObservableError)` where the error is either
//!   business (`E`) or technical (`RpcError`)
//! - **ServiceLocator** : registry of the services the process provides, plus a
//!   lazy cache of the consumer proxies
//! - **transport** : iceoryx2 publish/subscribe, one channel per group of
//!   services, correlated by a 16-byte request id (`ice_rpc::transport`)
//! - **dispatch** : one thread per channel receives the requests and polls each
//!   handler **once**, on that thread. A handler that answers without yielding
//!   completes there, exactly as if the transport had called it inline; one that
//!   `await`s is detached at its first `Pending` and runs as a task on the
//!   execution facade, so a slow call never holds back the next request of the
//!   same channel
//! - **Proxy** : unified entry point supporting 3 modes (Provider / Consumer / ProviderJson)
//!
//! ## Main modules
//!
//! | Module | Role |
//! |--------|------|
//! | `rx` | The reactive layer, re-exported from `ice-rpc-rx`: operators, constructors and multicast primitives, all reachable from the `Observable` stream |
//! | `rt` | Execution facade, re-exported from `ice-rpc-rx`: `spawn`, `Spawner`, `sleep`, `block_on`, cancellation |
//! | `types` | Protocol types (`RpcHeader`, `EventKind`, `WireEvent`) and the reactive vocabulary re-exported from `ice-rpc-rx` |
//! | `transport` | Publish/subscribe transport: one channel per service, correlation by id, streaming bridge |
//! | `locator` | `ServiceLocator` : registration, lazy consumer proxies, lifecycle |
//! | `codegen` | Internal contract for the generated code: wire types, provider primitives, constants, plumbing, dependency re-exports (doc-hidden) |

#![cfg_attr(test, allow(clippy::unwrap_used))] // test code may panic
pub use ice_rpc_macros::{main, payload, service};

// The *macro* is re-exported, not the crate, so a service implementation can
// annotate its `impl` block with the short `#[ice_rpc::async_trait]` — without
// declaring the `async-trait` crate. The attribute expands to `::core::…` paths
// only; the explicit `#[async_trait::async_trait]` keeps working for a crate
// that already has the dependency.
// (`ice_rpc::codegen` re-exports the *crate* instead, because the generated `impl`
// blocks name it as a path segment: `ice_rpc::codegen::async_trait::async_trait`.)
pub use async_trait::async_trait;

// Dependency re-exports (`rkyv`, `serde_json`, `base64`, …) live in `ice_rpc::codegen`.

mod config;
mod global;
mod hash;
mod labels;
mod locator;
mod service_traits;
mod shutdown;
mod sync;
mod types;

use crate::global::Global;

/// Internal facade for the code generated by `#[service]`.
#[doc(hidden)]
pub mod codegen;

/// The JSON contract of a service, in both directions.
///
/// One [`JsonInvoker`](json::JsonInvoker) per service (the caller side, generated
/// by `#[service]`) and one [`JsonDispatcher`](json::JsonDispatcher) per process
/// (the host side, registered by the gateway).
///
/// Gated behind `json`: a Rust-to-Rust deployment never speaks JSON, so the
/// converters and their `serde` cost stay out of the build. The HTTP gateway
/// needs it, so `http` enables `json`.
#[cfg(feature = "json")]
pub mod json;

/// Publish/subscribe transport (one channel per service, correlated by id).
#[doc(hidden)]
pub mod transport;

#[cfg(feature = "http")]
mod http_gateway;

// ── Public API: service traits ─────────────────────────────────────
// Only `ServiceInit` is implemented by the developer.
pub use service_traits::ServiceInit;

// ── Public API: the reactive vocabulary ─────────────────────────────
// Defined by `ice-rpc-rx` and re-exported unchanged: the crate keeps one single
// stream type, and a consumer never has to name the stream crate.
pub use ice_rpc_rx::{
    CancellationToken, Event, Observable, ObservableError, RpcError, defer, from, from_future, of,
    throw_error,
};
#[cfg(feature = "operators")]
pub use ice_rpc_rx::{RetryPolicy, Subject, Subscription, retry_with};

// Wire-level items live in `ice_rpc::codegen`; the protocol types come from `types`.
pub use types::{CallContext, TraceContext};

/// Reactive layer, re-exported under its historical path.
///
/// The items live in [`ice_rpc_rx`]; this module keeps the paths a consumer of
/// `ice-rpc` may already use (`ice_rpc::rx::from`, `ice_rpc::rx::Subject`, …).
pub mod rx {
    pub use ice_rpc_rx::*;
}

/// Execution facade, re-exported under its historical path.
///
/// `spawn`, `sleep`, `block_on` and the cancellation token live in
/// [`ice_rpc_rx::rt`]; the transport and the examples keep using them here. The
/// facade has one full mode per host runtime — `rt-async` (the default),
/// `tokio`, `smol` — and the modes are exclusive.
pub mod rt {
    pub use ice_rpc_rx::rt::*;
}

// ── Public API: locator ─────────────────────────────────────────────
pub use locator::ServiceLocator;

// ── Public API: out-of-band monitoring ──────────────────────────────
pub mod monitor;

/// Global cancellation token for the background IPC threads.
///
/// Triggered on shutdown (see [`ShutdownGuard`]) and by
/// [`shutdown_and_release`].
#[doc(hidden)]
pub fn global_cancel_token() -> &'static CancellationToken {
    static TOKEN: Global<CancellationToken> = Global::new();
    TOKEN.get_or_init(CancellationToken::new)
}

/// Secondary cancellation token, kept distinct from [`global_cancel_token`].
///
/// Reserved for background helpers that must survive a global cancellation;
/// both are cancelled by [`shutdown_and_release`] and by [`ShutdownGuard`].
#[doc(hidden)]
pub fn registry_cancel_token() -> &'static CancellationToken {
    static TOKEN: Global<CancellationToken> = Global::new();
    TOKEN.get_or_init(CancellationToken::new)
}

/// Cancels both tokens to propagate a termination signal to the IPC threads.
///
/// Called by the transport loops when iceoryx2 reports a termination through
/// its `WaitSet`, or when they observe the termination flag while polling.
pub(crate) fn request_shutdown() {
    log::info!("Termination signal received, shutting down...");
    global_cancel_token().cancel();
    registry_cancel_token().cancel();
}

/// Cancels the IPC threads and waits for their termination in a single call.
///
/// # Example
/// ```rust,ignore
/// // Prefer the guard returned by `init()` (RAII):
/// let guard = ice_rpc::codegen::init();
/// // ... usage ...
/// guard.shutdown().await; // clean shutdown waiting for the IPC threads
/// ```
#[doc(hidden)]
pub async fn shutdown_and_release() {
    global_cancel_token().cancel();
    registry_cancel_token().cancel();
    ServiceLocator::global().release_node().await;

    // `release_node` joins the dispatch threads, and a thread owns its ports:
    // joining it is what makes iceoryx2 unlink the services it created. What
    // survives is the cache of consumed channels, which lives in a `static` —
    // Rust never drops a `static`, so it is released here explicitly.
    let released = crate::transport::release_process_ports();
    if released > 0 {
        log::info!("[ice-rpc] released {released} cached channel port(s)");
    }

    // Last, and only now: the node itself. iceoryx2 removes the node's own state
    // — `nodes/<id>/` and its `node_monitor*` files — when the node is dropped,
    // so releasing it is what a clean exit needs to leave nothing behind. It has
    // to come after the ports, which is why it is not part of their release.
    if crate::transport::release_shared_node() {
        log::info!("[ice-rpc] released the iceoryx2 node");
    }
}

/// RAII guard for the automatic shutdown of an ice-rpc process.
///
/// On `Drop` (process end or panic), cancels the cancellation tokens.
/// For a clean shutdown (waiting for the IPC threads), call
/// [`ShutdownGuard::shutdown`] before the end of `main`.
///
/// # Example
/// ```rust,ignore
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let guard = ice_rpc::codegen::init(); // configures iceoryx2 + enables signal handling
///     // ... use ice-rpc ...
///     guard.shutdown().await;
///     Ok(())
/// }
/// ```
#[doc(hidden)]
pub struct ShutdownGuard {
    done: std::sync::atomic::AtomicBool,
}

impl ShutdownGuard {
    /// Creates a new shutdown guard.
    pub fn new() -> Self {
        Self {
            done: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// Clean shutdown: cancels the tokens, waits for the IPC threads, releases the node.
    ///
    /// Idempotent. After the first call, the subsequent ones have no effect.
    pub async fn shutdown(&self) {
        if self.done.swap(true, std::sync::atomic::Ordering::Relaxed) {
            return;
        }
        shutdown_and_release().await;
    }

    /// Clean shutdown, **blocking the current thread**.
    ///
    /// Synchronous twin of [`ShutdownGuard::shutdown`], for a `fn main` that runs
    /// no async runtime: it drives the same idempotent shutdown without an
    /// `.await`, so a blocking program keeps one single shape from the call to
    /// the exit.
    ///
    /// # Example
    /// ```rust,ignore
    /// let guard = ice_rpc::codegen::init_without_ctrl_c();
    /// // ... use ice-rpc ...
    /// guard.shutdown_blocking();
    /// ```
    pub fn shutdown_blocking(&self) {
        crate::rt::block_on(self.shutdown());
    }
}

impl Default for ShutdownGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ShutdownGuard {
    fn drop(&mut self) {
        if !self.done.load(std::sync::atomic::Ordering::Relaxed) {
            // Fallback: cancel the tokens without waiting (the process is ending).
            global_cancel_token().cancel();
            registry_cancel_token().cancel();
        }
    }
}

/// The `ice-rpc` version this build was compiled from.
///
/// Sourced from the crate's own `CARGO_PKG_VERSION`, so a diagnostics surface
/// can never drift from the manifest the way a hand-written literal does.
/// `iceoryx2` exposes no equivalent symbol, which is why the gateway reports
/// this version plus the protocol version instead of inventing a bus version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Returns the global [`ServiceLocator`].
///
/// Short alias of [`ServiceLocator::global()`] to reduce verbosity
/// in applications.
#[inline]
pub fn locator() -> &'static ServiceLocator {
    ServiceLocator::global()
}

/// Waits for the stop signal (SIGINT/SIGTERM or programmatic cancellation).
///
/// Syntactic sugar over `global_cancel_token().cancelled().await`.
#[doc(hidden)]
pub async fn wait_for_shutdown() {
    global_cancel_token().cancelled().await;
}

// ────────────────────────────────────────────────────────────────────
// Initialization functions
// ────────────────────────────────────────────────────────────────────

/// Whether the framework handles the process signals through iceoryx2.
///
/// Set by [`init`] (the default) and cleared by [`init_without_ctrl_c`].
static SIGNAL_HANDLING_ENABLED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(true);

/// Maps the signal-handling flag to the iceoryx2 `WaitSet` mode.
fn resolve_signal_handling_mode(enabled: bool) -> iceoryx2::prelude::SignalHandlingMode {
    if enabled {
        iceoryx2::prelude::SignalHandlingMode::HandleTerminationRequests
    } else {
        iceoryx2::prelude::SignalHandlingMode::Disabled
    }
}

/// Returns the signal-handling mode the transport must give to its `WaitSet`s.
pub(crate) fn waitset_signal_handling_mode() -> iceoryx2::prelude::SignalHandlingMode {
    resolve_signal_handling_mode(SIGNAL_HANDLING_ENABLED.load(std::sync::atomic::Ordering::Relaxed))
}

/// Initializes the framework and returns the RAII shutdown guard.
///
/// Configures iceoryx2 and enables the native signal handling of the `WaitSet`
/// loops (SIGINT/SIGTERM). The returned guard **must be kept alive**: dropping
/// it cancels the global tokens. Call [`ShutdownGuard::shutdown`] for a clean
/// stop.
///
/// # Example
/// ```rust,ignore
/// let guard = ice_rpc::codegen::init();
/// let proxy = ice_rpc::locator().get::<MyServiceProxy>().await.unwrap();
/// // ... use ice-rpc ...
/// guard.shutdown().await;
/// ```
#[doc(hidden)]
#[must_use = "the guard cancels the ice-rpc tokens when dropped; bind it for the process lifetime"]
pub fn init() -> ShutdownGuard {
    SIGNAL_HANDLING_ENABLED.store(true, std::sync::atomic::Ordering::Relaxed);
    ShutdownGuard::new()
}

/// Initializes the framework **without** signal handling and returns the RAII
/// shutdown guard (Node.js gateway, tests…).
///
/// Variant of [`init`] for contexts that must manage shutdown manually. The
/// returned guard should be **stored** for the host lifetime.
///
/// # Example
/// ```rust,ignore
/// let _guard = ice_rpc::codegen::init_without_ctrl_c();
/// ```
#[doc(hidden)]
#[must_use = "the guard cancels the ice-rpc tokens when dropped; bind it for the host lifetime"]
pub fn init_without_ctrl_c() -> ShutdownGuard {
    SIGNAL_HANDLING_ENABLED.store(false, std::sync::atomic::Ordering::Relaxed);
    ShutdownGuard::new()
}

/// Starts the HTTP REST gateway with the given service mapping.
///
/// Requires the `http` feature and one runtime adapter in `Cargo.toml`:
/// ```toml
/// ice-rpc = { features = ["http", "http-tokio"] }
/// ```
///
/// Prefer the [`start_http_gateway!`] macro which builds the mapping
/// automatically from the list of exposed proxies.
#[cfg(feature = "http")]
#[doc(hidden)]
pub async fn start_http_server(
    port: u16,
    factories: std::collections::HashMap<
        &'static str,
        fn() -> std::sync::Arc<dyn json::JsonInvoker>,
    >,
) {
    http_gateway::start_http_server(port, factories).await;
}

/// Starts the HTTP REST gateway exposing the listed services.
///
/// Builds locally the `name → factory` mapping from the provided proxy
/// types, then starts the HTTP server. No build.rs nor global
/// registry is needed: only the services exposed by this process
/// are listed here.
///
/// # Example
/// ```rust,ignore
/// #[ice_rpc::main(tokio)]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     ice_rpc::start_http_gateway!(8080, DatabaseServiceProxy, ConfigServiceProxy).await;
///     Ok(())
/// }
/// ```
#[cfg(feature = "http")]
#[macro_export]
macro_rules! start_http_gateway {
    ($port:expr, $($proxy:ty),+ $(,)?) => {{
        let mut __map: std::collections::HashMap<
            &'static str,
            fn() -> std::sync::Arc<dyn ice_rpc::codegen::JsonInvoker>,
        > = std::collections::HashMap::new();
        $(
            __map.insert(
                <$proxy>::SERVICE_NAME,
                || <$proxy>::consume() as std::sync::Arc<dyn ice_rpc::codegen::JsonInvoker>,
            );
        )+
        ice_rpc::start_http_server($port, __map)
    }};
}

/// Object trait allowing [`run_provider!`] to accept heterogeneous
/// proxies in a `Vec` without knowing their concrete type.
///
/// Implemented automatically for any type satisfying the constraints
/// of [`ServiceLocator::register`]. **Do not implement manually.**
#[doc(hidden)]
#[async_trait::async_trait]
pub trait _ProviderService: Send + Sync + 'static {
    async fn register_into(&self, locator: &'static ServiceLocator);
}

#[async_trait::async_trait]
impl<T> _ProviderService for std::sync::Arc<T>
where
    T: crate::service_traits::ServiceLifecycle
        + crate::service_traits::ServiceNamed
        + crate::service_traits::ServiceInit
        + std::any::Any
        + Send
        + Sync
        + 'static,
{
    async fn register_into(&self, locator: &'static ServiceLocator) {
        locator.register(self.clone()).await;
    }
}

/// Registers and initializes a list of Provider services, then blocks until the
/// process shutdown is requested (Ctrl+C).
///
/// Internal function called by the [`run_provider!`] macro.
/// Prefer the macro for direct usage.
///
/// The process lifecycle (iceoryx2 bootstrap, signal handling, runtime and
/// clean shutdown) is owned by `#[ice_rpc::main]`. This function only starts the
/// services and keeps the process alive until cancellation, so it **must** be
/// awaited from within an `#[ice_rpc::main]` body.
///
/// # This future does not complete before shutdown
///
/// It awaits [`wait_for_shutdown`], so it stays pending for the whole process
/// lifetime and returns only once the process is asked to stop. Any work placed
/// **after** its `.await` in the same task therefore runs at shutdown, not while
/// the services are serving. To also drive a Consumer (or anything else) in the
/// same process, **spawn** the provider instead of awaiting it on the caller's
/// task — see the third example of [`run_provider!`].
#[doc(hidden)]
pub async fn run_provider_inner(
    services: Vec<Box<dyn _ProviderService>>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Defensive and idempotent: enabling signal handling here guarantees the
    // `WaitSet`s created below report SIGINT/SIGTERM even if the macro was
    // bypassed (e.g. after `init_without_ctrl_c()`).
    SIGNAL_HANDLING_ENABLED.store(true, std::sync::atomic::Ordering::Relaxed);

    // Reap what previous runs left behind, before creating any service: a provider
    // that was killed is still on the bus, and nothing else removes it — see
    // `transport::cleanup_dead_nodes`. This is what makes a machine self-healing
    // in production, where nobody runs a purge script.
    let reaped = crate::transport::cleanup_dead_nodes();
    if reaped > 0 {
        log::info!("[ice-rpc] reaped {reaped} dead node(s) left by previous runs");
    }

    crate::transport::sweep_orphan_shm_markers();

    let loc = ServiceLocator::global();
    for svc in services {
        svc.register_into(loc).await;
    }
    loc.initialize_all().await?;
    log::info!("All services are ready. Press Ctrl+C to stop.");
    wait_for_shutdown().await;
    log::info!("Stopping services...");
    Ok(())
}

/// Starts the provider with the given services.
///
/// Registers each service, initializes everything in topological order, then
/// blocks until the process shutdown is requested (Ctrl+C). The clean shutdown
/// itself is owned by `#[ice_rpc::main]`: this macro only starts the services.
///
/// Returns a `Future` — must be `.await`ed from an `#[ice_rpc::main]` body.
///
/// # It does not return before shutdown
///
/// The returned future awaits [`wait_for_shutdown`] and stays pending for the
/// whole process lifetime. Awaiting it **blocks the calling task** until Ctrl+C:
/// any statement placed after the `.await` in that same task runs at shutdown,
/// not while the services are serving. To run a provider *and* other work (a
/// Consumer, for instance) in the same process, **spawn** it — see the third
/// example.
///
/// # Dependencies are only ordered locally
///
/// `provide_with_init` declares [`ServiceInit::dependencies`],
/// used **only** to order the services registered in this process. A dependency
/// provided by another process is external and never blocks the startup — there
/// is no discovery check.
///
/// # Example — Pure provider
/// ```rust,ignore
/// #[ice_rpc::main(tokio)]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     env_logger::init();
///     // `#[ice_rpc::main]` owns init + shutdown; `run_provider!` starts them.
///     ice_rpc::run_provider!(
///         ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.json")),
///         DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
///     ).await
/// }
/// ```
///
/// # Example — Provider that consumes a service of its own process
/// ```rust,ignore
/// #[ice_rpc::main(tokio)]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     env_logger::init();
///     // DatabaseServiceImpl calls ConfigService via locator().get(); both are
///     // local, so the topological sort initializes ConfigService first.
///     ice_rpc::run_provider!(
///         ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.json")),
///         DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
///     ).await
/// }
/// ```
///
/// # Example — Provider *and* consumer in the same process
/// ```rust,ignore
/// #[ice_rpc::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     env_logger::init();
///     // `run_provider!` never returns before shutdown, so it must be spawned,
///     // not awaited here. `rt::spawn` works in every execution mode; under
///     // `#[ice_rpc::main(tokio)]`, `tokio::spawn` is the equivalent.
///     ice_rpc::rt::spawn(async {
///         if let Err(error) = ice_rpc::run_provider!(
///             CoreServiceProxy::provide(Core),
///         ).await {
///             log::error!("provider stopped: {error}");
///         }
///     });
///
///     // Consumer side, on the main task.
///     let print = ice_rpc::locator().get::<PrintServiceProxy>().await.unwrap();
///     print.print().await.first_value().await?;
///     Ok(())
/// }
/// ```
#[macro_export]
macro_rules! run_provider {
    ($($proxy:expr),+ $(,)?) => {{
        ice_rpc::run_provider_inner(vec![
            $(Box::new($proxy) as Box<dyn ice_rpc::_ProviderService>),+
        ])
    }};
}

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

    // ── global_cancel_token / registry_cancel_token ──────────────────

    #[test]
    fn global_cancel_token_is_singleton() {
        let t1 = global_cancel_token();
        let t2 = global_cancel_token();
        assert!(std::ptr::eq(t1, t2), "must return the same instance");
    }

    #[test]
    fn registry_cancel_token_is_singleton() {
        let t1 = registry_cancel_token();
        let t2 = registry_cancel_token();
        assert!(std::ptr::eq(t1, t2), "must return the same instance");
    }

    #[test]
    fn cancel_tokens_are_distinct() {
        let t1 = global_cancel_token();
        let t2 = registry_cancel_token();
        assert!(!std::ptr::eq(t1, t2), "must be different instances");
    }

    #[test]
    fn shutdown_guard_drop_cancels_tokens() {
        let t1 = global_cancel_token().clone();
        let t2 = registry_cancel_token().clone();
        {
            let _guard = ShutdownGuard::new();
            // The guard has not called shutdown() yet → Drop cancels the tokens.
        }
        assert!(t1.is_cancelled());
        assert!(t2.is_cancelled());
    }

    // ── locator ──────────────────────────────────────────────────────

    #[test]
    fn locator_returns_global_instance() {
        let l1 = locator();
        let l2 = ServiceLocator::global();
        assert!(
            std::ptr::eq(l1, l2),
            "locator() must be the global instance"
        );
    }

    // ── wait_for_shutdown / shutdown_and_release ─────────────────────

    #[test]
    fn wait_for_shutdown_returns_when_cancelled() {
        let token = global_cancel_token().clone();
        // Cancels in 10ms
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(10));
            token.cancel();
        });
        // Must not block indefinitely.
        crate::rt::test_block_on(crate::rt::timeout(
            std::time::Duration::from_secs(2),
            wait_for_shutdown(),
        ))
        .expect("wait_for_shutdown did not return in time");
    }

    #[test]
    fn shutdown_and_release_does_not_panic_when_no_node() {
        // Without a created iceoryx2 Node, shutdown_and_release must terminate
        // cleanly.
        crate::rt::test_block_on(shutdown_and_release());
    }

    // ── ShutdownGuard::shutdown ──────────────────────────────────────

    #[test]
    fn the_guard_shuts_down_once() {
        let guard = ShutdownGuard::new();
        // The first call performs the shutdown...
        crate::rt::test_block_on(guard.shutdown());
        // ...the second is a no-op, and `Drop` then does nothing either (the flag
        // is already set), so the node is never released twice.
        crate::rt::test_block_on(guard.shutdown());
        drop(guard);
    }

    /// The blocking twin drives the same idempotent shutdown, and needs no
    /// runtime: it is the entry point a plain `fn main` uses.
    #[test]
    fn the_guard_shuts_down_once_blocking() {
        let guard = ShutdownGuard::new();
        guard.shutdown_blocking();
        guard.shutdown_blocking();
        drop(guard);
    }

    // ── signal handling ──────────────────────────────────────────────

    #[test]
    fn signal_handling_flag_selects_the_waitset_mode() {
        use iceoryx2::prelude::SignalHandlingMode;

        // Enabled: iceoryx2 captures SIGINT/SIGTERM.
        assert_eq!(
            resolve_signal_handling_mode(true),
            SignalHandlingMode::HandleTerminationRequests
        );
        // Disabled: the host keeps the default disposition.
        assert_eq!(
            resolve_signal_handling_mode(false),
            SignalHandlingMode::Disabled
        );
    }

    /// Serialises the tests that read or write the process-wide signal flag.
    fn signal_lock() -> &'static std::sync::Mutex<()> {
        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        &LOCK
    }

    #[test]
    fn the_process_handles_signals_by_default() {
        use iceoryx2::prelude::SignalHandlingMode;

        let _guard = signal_lock().lock().unwrap_or_else(|e| e.into_inner());
        // The flag is enabled unless `init_without_ctrl_c` was called: a plain
        // `init` must let iceoryx2 report SIGINT/SIGTERM to the WaitSet loops.
        assert_eq!(
            waitset_signal_handling_mode(),
            SignalHandlingMode::HandleTerminationRequests
        );
    }

    #[test]
    fn the_initializers_choose_who_handles_the_signals() {
        use iceoryx2::prelude::SignalHandlingMode;
        use std::sync::atomic::Ordering;

        let _guard = signal_lock().lock().unwrap_or_else(|e| e.into_inner());

        // `init` gives the signals back to iceoryx2, even after a host had taken
        // them — which is what makes running it twice harmless.
        SIGNAL_HANDLING_ENABLED.store(false, Ordering::Relaxed);
        let guard = init();
        assert_eq!(
            waitset_signal_handling_mode(),
            SignalHandlingMode::HandleTerminationRequests
        );
        drop(guard);

        // `init_without_ctrl_c` leaves the disposition to the host (the Node.js
        // gateway installs its own handler).
        let guard = init_without_ctrl_c();
        assert_eq!(waitset_signal_handling_mode(), SignalHandlingMode::Disabled);
        drop(guard);

        // Restore the state this process started with, for the other tests.
        SIGNAL_HANDLING_ENABLED.store(true, Ordering::Relaxed);
    }
}