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
//! 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 with automatic reconnection
//! - `MyServiceServer` — IPC server with dispatch loop
//! - `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> {
//! let (tx, rx) = ice_rpc::channel::<String, MyError>(2);
//! ice_rpc::rt::spawn(async move {
//! let _ = tx.send(ice_rpc::Event::Next(format!("Hello {} !", name))).await;
//! let _ = tx.send(ice_rpc::Event::Complete).await;
//! });
//! Ok(rx)
//! }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Pure provider: no implementation calls locator().get().
//! ice_rpc::init();
//!
//! ice_rpc::run_provider!(
//! MyServiceProxy::provide(MyServiceImpl),
//! ).await
//! }
//! ```
//!
//! If an implementation calls `locator().get()` (cross-service dependency):
//!
//! ```rust,ignore
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // This provider also consumes services via locator().get().
//! ice_rpc::init();
//!
//! 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
//! use ice_rpc::take_one;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // This process consumes services via locator().get().
//! ice_rpc::init();
//!
//! // RAII guard: cancels the tokens on Drop, even on panic.
//! let guard = ice_rpc::ShutdownGuard::new();
//!
//! // Proxy instantiated lazily, IPC connection on the first RPC call.
//! let proxy = ice_rpc::locator()
//! .get::<MyServiceProxy>().await
//! .expect("MyService unknown");
//!
//! let response: String = take_one!(proxy.hello("Alice".into()))?;
//! log::info!("Response: {}", response);
//!
//! // Clean shutdown: wait for IPC threads, release the iceoryx2 node.
//! guard.shutdown().await;
//! Ok(())
//! }
//! ```
//!
//! # Architecture
//!
//! ## Workspace crates
//!
//! | Crate | Role |
//! |-------------------|----------------------------------------------------|
//! | `ice-rpc` | Core framework (types, discovery, hub) |
//! | `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** : RPC event stream (`Next` / `Complete` / `Error`)
//! - **NodeHub** : central communication hub managing the IPC publishers/subscribers
//! - **ServiceLocator** : service registry with dependency resolution and topological sort
//! - **NodeDiscovery** : local service→NodeId cache, initial discovery + Event-based updates
//! - **Proxy** : unified entry point supporting 3 modes (Provider / Consumer / ProviderNodeJs)
//!
//! ## Main modules
//!
//! | Module | Role |
//! |--------|------|
//! | `types` | Fundamental types: `NodeId`, `RpcHeader`, `Event`, `Observable`, `RpcError`, `ServiceInfo` |
//! | `hub` | `NodeHub` : centralized dispatch loop, publishers, response handlers |
//! | `locator` | `ServiceLocator` : registration, lifecycle, Kahn topological sort |
//! | `node_discovery` | `NodeDiscovery` : local cache, service→NodeId resolution |
//! | `blackboard` | Discovery registry: 1 Blackboard per node (`ice_rpc_node_{pid}`), key = service name |
//! | `registry_notify` | Event notifications: carries the NodeId via `EventId` |
//! | `registry_listener` | WaitSet loop: receives the Events, updates the cache, cleans dead nodes |
//! | `node_supervisor` | Node supervisor: broadcasts node death to subscribed clients |
//! | `node_lock` | Cross-platform kernel named lock (Windows Mutex / Unix flock) |
//! | `client_core` | Shared consumer state: ConnectionState machine, `resolve_target`, reconnection callback, client bootstrap |
//! | `gen` | Internal facade for the code generated by `#[service]` (doc-hidden) |
//! | `macros` | `take_one!`, `take_one_or_cancel!`, `try_or_log!` utilities |
//! | `cache` | `RpcCache` consumer-side TTL cache (`hash_bytes`, `hash_key`) — requires the `cache` feature |
pub use base64;
pub use ;
pub use cache;
pub use iceoryx2;
pub use log;
pub use rkyv;
pub use serde_json;
// Runtime-agnostic building blocks re-exported for the generated code.
pub use async_channel;
pub use async_lock;
pub use futures;
pub use futures_lite;
/// Internal facade for the code generated by `#[service]`.
/// Node.js bridge: dynamic dispatch for the ProviderNodeJs mode.
pub use ;
// ── Public API: service traits ─────────────────────────────────────
pub use ;
// ── Public API: cache ───────────────────────────────────────────────
pub use ;
// ── Public API: fundamental types ──────────────────────────────────
pub use ;
// ── Public API: configuration ───────────────────────────────────────
pub use setup_iceoryx2_global_config;
// ── Public API: locator ─────────────────────────────────────────────
pub use ServiceLocator;
use OnceLock;
pub use crateCancellationToken;
/// Global cancellation token for the WaitSet loops (dispatch loop).
///
/// Triggered by Ctrl+C or by the dispatch loop on fatal error.
/// Cancellation token for the NODE_REGISTRY listener.
///
/// Is NOT triggered by the dispatch loop (TerminationRequest), only
/// by Ctrl+C. This allows the listener to survive the provider death
/// and to receive the restart announcements.
/// Cancels the IPC threads and waits for their termination in a single call.
///
/// # Example
/// ```rust,ignore
/// // Prefer ShutdownGuard (RAII):
/// let guard = ice_rpc::ShutdownGuard::new();
/// // ... 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::ShutdownGuard::new();
/// // ... 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 (Ctrl+C or programmatic cancellation).
///
/// Syntactic sugar over `global_cancel_token().cancelled().await`.
/// Used at the end of `main` to block until shutdown.
pub async
// ────────────────────────────────────────────────────────────────────
// Initialization functions
// ────────────────────────────────────────────────────────────────────
/// Initializes the framework: configures iceoryx2 and installs the Ctrl+C
/// handler.
///
/// Suitable for consumers, providers and provider+consumer processes alike:
/// no service registry is needed, proxies are instantiated on demand from
/// their type.
///
/// # Example
/// ```rust,ignore
/// ice_rpc::init();
/// let proxy = ice_rpc::locator().get::<MyServiceProxy>().await.unwrap();
/// ```
/// Initializes the framework **without** a Ctrl+C handler (Node.js gateway, tests…).
///
/// Variant of [`init`] for contexts that must manage shutdown
/// manually (N-API thread, tests, embedded executors).
///
/// # Example
/// ```rust,ignore
/// ice_rpc::init_without_ctrl_c();
/// ```
/// Installs the Ctrl+C handler that triggers [`global_cancel_token`].
///
/// Available separately if needed (already called by [`init`]).
/// The handler is installed through the [`ctrlc`] crate, so it works from any
/// context, without an async runtime.
/// Starts the HTTP REST gateway with the given service mapping.
///
/// Requires the `http` feature in `Cargo.toml`:
/// ```toml
/// ice-rpc = { features = ["http"] }
/// ```
///
/// 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::init();
/// ice_rpc::start_http_gateway!(8080, DatabaseServiceProxy, ConfigServiceProxy).await;
/// ```
/// 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, waits for Ctrl+C,
/// then performs the clean shutdown.
///
/// Internal function called by the [`run_provider!`] macro.
/// Prefer the macro for direct usage.
pub async
/// Starts the provider with the given services.
///
/// Registers each service, initializes everything in topological order,
/// blocks until Ctrl+C, then performs a clean shutdown.
///
/// Returns a `Future` — must be `.await`ed in an async context.
///
/// # Example — Pure provider
/// ```rust,ignore
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// env_logger::init();
/// ice_rpc::init();
/// 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
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// env_logger::init();
/// // DatabaseServiceImpl calls ConfigService via get()
/// ice_rpc::init();
/// ice_rpc::run_provider!(
/// ConfigServiceProxy::provide_with_init(ConfigServiceImpl::new("config.toml")),
/// DatabaseServiceProxy::provide_with_init(DatabaseServiceImpl::new()),
/// ).await
/// }
/// ```