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
//! 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
//!
//! ### 1. Define a service
//!
//! ```rust,ignore
//! use ice_rpc::{service, Observable};
//! use rkyv::{Archive, Deserialize, Serialize};
//!
//! #[derive(Debug, Archive, Deserialize, Serialize)]
//! pub enum MyError {
//! NotFound,
//! }
//!
//! #[service("MyService")]
//! pub trait MyService: Send + Sync + 'static {
//! async fn hello(&self, name: String) -> Observable<String, MyError>;
//! }
//! ```
//!
//! The `#[service("MyService")]` macro automatically generates:
//! - `MyServiceRequest` — rkyv enum for serialization
//! - `MyServiceClient` — IPC client (publish/subscribe, one call per request id)
//! - `MyServiceServer` — IPC server exposing the method dispatcher
//! - `MyServiceProxy` — unified entry point (3 modes)
//!
//! ### 2. Start a Provider
//!
//! ```rust,ignore
//! struct MyServiceImpl;
//!
//! #[async_trait::async_trait]
//! impl MyService for MyServiceImpl {
//! async fn hello(&self, name: String) -> Observable<String, MyError> {
//! // One value, then completion. A handler streaming several values uses
//! // the wire-level `ice_rpc::gen::channel(capacity)`, which returns a
//! // `(Sender, Observable)` pair whose `send_complete_with` closes the
//! // stream with its last value.
//! Observable::from_events([
//! ice_rpc::Event::Next(format!("Hello {} !", name)),
//! ice_rpc::Event::Complete,
//! ]) // no Result: a service returns the observable itself
//! }
//! }
//!
//! #[ice_rpc::main(tokio)]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // `#[ice_rpc::main]` owns the bootstrap (init + runtime) and the clean
//! // shutdown; `run_provider!` only starts the services and waits for Ctrl+C.
//! ice_rpc::run_provider!(
//! MyServiceProxy::provide(MyServiceImpl),
//! ).await
//! }
//! ```
//!
//! If an implementation calls `locator().get()` (cross-service dependency):
//!
//! ```rust,ignore
//! #[ice_rpc::main(tokio)]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // This provider also consumes services via locator().get().
//! ice_rpc::run_provider!(
//! ServiceAProxy::provide_with_init(ServiceAImpl::new()),
//! ServiceBProxy::provide_with_init(ServiceBImpl::new()), // depends on ServiceA
//! ).await
//! }
//! ```
//!
//! ### 3. Call from a Consumer
//!
//! ```rust,ignore
//! #[ice_rpc::main(tokio)]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Proxy instantiated lazily, IPC connection on the first RPC call.
//! let proxy = ice_rpc::locator()
//! .get::<MyServiceProxy>().await
//! .expect("MyService unknown");
//!
//! let response = proxy.hello("Alice".into()).await.first_value().await?;
//! log::info!("Response: {}", response);
//!
//! Ok(()) // `#[ice_rpc::main]` shuts ice-rpc down on exit
//! }
//! ```
//!
//! # 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 / ProviderNodeJs)
//!
//! ## 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 |
//! | `node_liveness` | Crash detection through iceoryx2's native node monitoring |
//! | `gen` | Internal contract for the generated code: wire types, provider primitives, constants, plumbing, dependency re-exports (doc-hidden) |
// test code may panic
pub use ;
// Dependency re-exports (`rkyv`, `serde_json`, `base64`, …) live in `ice_rpc::gen`.
use crateGlobal;
/// Internal facade for the code generated by `#[service]`.
/// Node.js bridge: dynamic dispatch for the ProviderNodeJs mode.
/// Publish/subscribe transport (one channel per service, correlated by id).
// ── Public API: service traits ─────────────────────────────────────
// Only `ServiceInit` is implemented by the developer.
pub use 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 ;
// Wire-level items live in `ice_rpc::gen`; the protocol types come from `types`.
pub use ;
/// 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`, …).
/// 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-threads` (the default),
/// `tokio`, `smol` — and the modes are exclusive.
// ── Public API: locator ─────────────────────────────────────────────
pub use ServiceLocator;
// ── Public API: out-of-band monitoring ──────────────────────────────
/// Global cancellation token for the background IPC threads.
///
/// Triggered on shutdown (see [`ShutdownGuard`]) and by
/// [`shutdown_and_release`].
/// 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`].
/// 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
/// 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::gen::init();
/// // ... usage ...
/// guard.shutdown().await; // clean shutdown waiting for the IPC threads
/// ```
pub async
/// 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::gen::init(); // configures iceoryx2 + enables signal handling
/// // ... use ice-rpc ...
/// guard.shutdown().await;
/// Ok(())
/// }
/// ```
/// Returns the global [`ServiceLocator`].
///
/// Short alias of [`ServiceLocator::global()`] to reduce verbosity
/// in applications.
/// Waits for the stop signal (SIGINT/SIGTERM or programmatic cancellation).
///
/// Syntactic sugar over `global_cancel_token().cancelled().await`.
pub async
// ────────────────────────────────────────────────────────────────────
// 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: AtomicBool =
new;
/// Maps the signal-handling flag to the iceoryx2 `WaitSet` mode.
/// Returns the signal-handling mode the transport must give to its `WaitSet`s.
pub
/// Performs the one-time process bootstrap (iceoryx2 global configuration).
///
/// Idempotent: calling it several times has no effect after the first call.
/// 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::gen::init();
/// let proxy = ice_rpc::locator().get::<MyServiceProxy>().await.unwrap();
/// // ... use ice-rpc ...
/// guard.shutdown().await;
/// ```
/// 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::gen::init_without_ctrl_c();
/// ```
/// 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.
pub async
/// 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(())
/// }
/// ```
/// 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.**
/// 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.
pub async
/// 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.
///
/// # 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.toml")),
/// DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
/// ).await
/// }
/// ```
///
/// # Example — Provider that also consumes external services
/// ```rust,ignore
/// #[ice_rpc::main(tokio)]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// env_logger::init();
/// // DatabaseServiceImpl calls ConfigService via get()
/// ice_rpc::run_provider!(
/// ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.toml")),
/// DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
/// ).await
/// }
/// ```