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
//! The JSON contract of a service, in both directions.
//!
//! A service exposed to a JSON transport is described by **one** view, and that
//! view has two halves: the caller side, implemented by the `#[service]` macro on
//! the proxy, and the host side, implemented by whatever answers the calls.
//!
//! | Half | Types | Implemented by |
//! |---|---|---|
//! | caller | [`JsonInvoker`], [`ReadMode`], [`JsonOutcome`], [`JsonCallError`] | `#[service]`, once per service |
//! | host | [`JsonDispatcher`], [`JsonCallStream`], [`JsonCallEvent`] | the JSON host, registered by [`set_json_dispatcher`] |
//!
//! [`read_json`] joins the two: it carries the reading policy (`First` / `All`)
//! and the mapping of a business error, so the generated dispatch table stays one
//! line per method.
//!
//! **Nothing here names a transport.** The same expansion serves the Node.js
//! gateway (`gateway_nodejs`), the HTTP gateway — which consumes the very same
//! [`JsonInvoker`] — a Rust test double, or a future WASM host: they all register
//! or consume the types below.

use crate::global::Global;
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;

// ── Caller side: what a JSON transport calls a service through ───────────────

/// How much of a call a JSON host reads.
///
/// This is a *reading policy*, not a difference of contract, which is why it is
/// an argument to [`JsonInvoker::invoke_json`] rather than a second generated
/// entry point.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReadMode {
    /// The first `Next` value, answering as soon as it is available — the only
    /// mode that can serve an endless stream.
    First,
    /// Every `Next` value, waiting for the terminal event.
    All,
}

/// What a JSON call produced.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonOutcome {
    /// One value (`ReadMode::First`), or a JSON array of every value
    /// (`ReadMode::All`).
    Value(serde_json::Value),
    /// The service completed **without emitting any value**. A legitimate result
    /// that a bare `null` could not be told apart from a real `null` payload —
    /// and the very difference the two JSON transports used to disagree on.
    Nothing,
}

/// Why a JSON-mediated call failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsonCallError {
    /// A parameter could not be decoded into the declared Rust type.
    InvalidArgs(String),
    /// The service answered with a business error.
    Business(String),
    /// The transport failed, or the host never answered.
    Transport(String),
}

/// What [`JsonInvoker::invoke_json`] returns.
pub type JsonResult = Result<JsonOutcome, JsonCallError>;

/// The JSON view of a service, from the caller's side.
///
/// Implemented automatically, **once**, by the `#[service]` macro, whatever the
/// JSON transport: the Node.js gateway and the HTTP gateway both consume this
/// trait, so neither adds generated code of its own. A Rust-to-Rust call does
/// not go through it at all — it calls the typed method.
///
/// # Example (generated by the macro)
///
/// ```rust,ignore
/// let invoker: Arc<dyn JsonInvoker> = ...;
/// match invoker.invoke_json("get_user_age", json!({"name": "Alice"}), ReadMode::First).await {
///     Some(Ok(JsonOutcome::Value(age))) => println!("{age}"),
///     Some(Ok(JsonOutcome::Nothing)) => println!("completed without a value"),
///     Some(Err(error)) => eprintln!("{error:?}"),
///     None => eprintln!("no such method"),
/// }
/// ```
#[async_trait::async_trait]
pub trait JsonInvoker: Send + Sync {
    /// Returns the logical name of the service.
    fn service_name(&self) -> &'static str;

    /// Invokes one method with JSON arguments.
    ///
    /// # Returns
    /// * `None` — the service has no such method, which lets a caller tell a
    ///   typo from a call that failed;
    /// * `Some(Ok(outcome))` — the call succeeded;
    /// * `Some(Err(error))` — the call failed, with the reason.
    async fn invoke_json(
        &self,
        method: &str,
        args: serde_json::Value,
        read: ReadMode,
    ) -> Option<Result<JsonOutcome, JsonCallError>>;
}
// ── Host side: what a JSON host implements to answer ─────────────────────────

/// How long the **first** event of a JSON call may take to arrive.
///
/// Guards the case that has no other bound: a host that never answers. Once
/// events flow, the call belongs to the service, which is why the deadline is
/// not re-armed per event — a long-lived stream is not a timeout.
pub const JSON_CALL_TIMEOUT: Duration = Duration::from_secs(30);

/// One step of a call to a JSON host, as read by the generated dispatcher.
#[derive(Debug)]
pub enum JsonCallEvent {
    /// An event pushed by the host.
    Event(Value),
    /// The host never answered. Reported on the bus as an internal error rather
    /// than silently ending the stream, which would look like a `Complete`.
    Failed(String),
}

/// The events of one call to a JSON host.
///
/// Built by the host ([`JsonCallStream::channel`]) and consumed by the generated
/// dispatcher, which emits one wire sample per event.
pub struct JsonCallStream {
    receiver: async_channel::Receiver<Value>,
    answered: bool,
}

impl JsonCallStream {
    /// Builds a stream together with the sender the host pushes events into.
    #[must_use]
    pub fn channel() -> (Self, async_channel::Sender<Value>) {
        let (sender, receiver) = async_channel::unbounded();
        (
            Self {
                receiver,
                answered: false,
            },
            sender,
        )
    }

    /// Returns the next event, or `None` once the host closed the call.
    pub async fn next(&mut self) -> Option<JsonCallEvent> {
        if self.answered {
            return self.receiver.recv().await.ok().map(JsonCallEvent::Event);
        }
        match crate::rt::timeout(JSON_CALL_TIMEOUT, self.receiver.recv()).await {
            Ok(Ok(value)) => {
                self.answered = true;
                Some(JsonCallEvent::Event(value))
            }
            // The sender was dropped without pushing anything: the call is over.
            Ok(Err(_)) => None,
            Err(_) => Some(JsonCallEvent::Failed(format!(
                "the JSON host did not answer within {}s",
                JSON_CALL_TIMEOUT.as_secs()
            ))),
        }
    }
}

/// The JSON view of a service, from the host's side.
///
/// Implemented by whatever hosts a JavaScript-like implementation of the
/// service; registered once, at startup, with [`set_json_dispatcher`].
#[async_trait::async_trait]
pub trait JsonDispatcher: Send + Sync + 'static {
    /// Hands one call to the host and returns the stream of its events.
    ///
    /// # Errors
    /// `Err` when the call could not even be started (no callback, host gone):
    /// the generated dispatcher reports it as an internal error.
    async fn dispatch_json(
        &self,
        cid: [u8; 16],
        service: &str,
        method: &str,
        args: Value,
    ) -> Result<JsonCallStream, String>;
}

static DISPATCHER: Global<Arc<dyn JsonDispatcher>> = Global::new();

/// Registers the JSON host. Called once, at startup.
///
/// Subsequent calls are ignored, so a second `init` cannot swap the host under
/// running calls.
pub fn set_json_dispatcher(dispatcher: Arc<dyn JsonDispatcher>) {
    DISPATCHER.get_or_init(|| dispatcher);
}

/// The registered host, if any.
pub fn json_dispatcher() -> Option<&'static Arc<dyn JsonDispatcher>> {
    DISPATCHER.get()
}

/// Hands a call to the registered host.
///
/// # Errors
/// Returns `Err` when no host was registered; the generated dispatcher logs and
/// reports it rather than dropping the call.
pub async fn dispatch_json(
    cid: [u8; 16],
    service: &str,
    method: &str,
    args: Value,
) -> Result<JsonCallStream, String> {
    match DISPATCHER.get() {
        Some(dispatcher) => dispatcher.dispatch_json(cid, service, method, args).await,
        None => Err("no JSON dispatcher registered — call \
                     ice_rpc::json::set_json_dispatcher() first"
            .to_string()),
    }
}

/// Reads a service call as JSON, whatever the transport asked for.
///
/// This helper is what keeps a generated match arm to a single line: the reading
/// policy and the mapping of a business error live here, once, instead of being
/// duplicated per method *and* per entry point — which is what the previous
/// `first_value` / `collect` pair of generated functions did.
///
/// # Bounds
/// `T: serde::Serialize` and `E: Display`: exactly the bounds the HTTP codegen
/// and the Node.js codegen already imposed on those very types, so unifying the
/// two surfaces adds none.
pub async fn read_json<T, E>(
    stream: crate::Observable<T, E>,
    read: ReadMode,
) -> Result<JsonOutcome, JsonCallError>
where
    T: serde::Serialize,
    E: std::fmt::Display,
{
    match read {
        ReadMode::First => match stream.first_value().await {
            Ok(value) => serde_json::to_value(&value)
                .map(JsonOutcome::Value)
                .map_err(|e| {
                    JsonCallError::Transport(format!("failed to serialize the response: {e}"))
                }),
            Err(crate::ObservableError::Business(e)) => Err(JsonCallError::Business(e.to_string())),
            Err(crate::ObservableError::Technical(e)) => {
                Err(JsonCallError::Transport(e.to_string()))
            }
            // A service may legitimately complete without emitting anything:
            // reported as such rather than as a failure.
            Err(crate::ObservableError::Empty) => Ok(JsonOutcome::Nothing),
        },
        ReadMode::All => match stream.collect().await {
            Ok(values) => values
                .iter()
                .map(serde_json::to_value)
                .collect::<Result<Vec<_>, _>>()
                .map(|values| JsonOutcome::Value(serde_json::Value::Array(values)))
                .map_err(|e| JsonCallError::Transport(format!("failed to serialize a value: {e}"))),
            Err(crate::ObservableError::Business(e)) => Err(JsonCallError::Business(e.to_string())),
            Err(crate::ObservableError::Technical(e)) => {
                Err(JsonCallError::Transport(e.to_string()))
            }
            // An empty stream is an empty array here; only `First` has to
            // distinguish "no value at all".
            Err(crate::ObservableError::Empty) => {
                Ok(JsonOutcome::Value(serde_json::Value::Array(Vec::new())))
            }
        },
    }
}

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

    /// A minimal host: echoes the arguments as one event.
    struct EchoHost;

    #[async_trait::async_trait]
    impl JsonDispatcher for EchoHost {
        async fn dispatch_json(
            &self,
            _cid: [u8; 16],
            service: &str,
            method: &str,
            args: Value,
        ) -> Result<JsonCallStream, String> {
            // Answered before returning: a host that spawned its answer would
            // need its executor to outlive the call, which is a property of that
            // host, not of the contract under test.
            let (stream, sender) = JsonCallStream::channel();
            let _ = sender.try_send(serde_json::json!({
                "service": service,
                "method": method,
                "args": args,
            }));
            // Dropping the sender is what closes the call.
            drop(sender);
            Ok(stream)
        }
    }

    #[test]
    fn a_registered_host_receives_the_call_and_its_events_are_read() {
        set_json_dispatcher(Arc::new(EchoHost));

        // `test_block_on`, not `block_on`: under the `tokio` facade the deadline
        // this stream arms needs an active runtime for the whole poll.
        let events = crate::rt::test_block_on(async {
            let mut stream = dispatch_json(
                [7u8; 16],
                "DatabaseService",
                "get_user_age",
                serde_json::json!({ "name": "Alice" }),
            )
            .await
            .expect("a registered host accepts the call");

            let mut collected = Vec::new();
            while let Some(event) = stream.next().await {
                match event {
                    JsonCallEvent::Event(value) => collected.push(value),
                    JsonCallEvent::Failed(message) => panic!("unexpected failure: {message}"),
                }
            }
            collected
        });

        assert_eq!(
            events,
            vec![serde_json::json!({
                "service": "DatabaseService",
                "method": "get_user_age",
                "args": { "name": "Alice" },
            })]
        );

        // The registry is a process-wide singleton, so every assertion about
        // *which* host it holds belongs to this test: a second `#[test]` reading
        // it would depend on when it happens to run.
        let registered = json_dispatcher().expect("a registered host stays reachable");
        assert_eq!(
            Arc::strong_count(registered),
            1,
            "the framework holds the single reference to the host"
        );

        // A second registration is ignored, so replaying `init` cannot swap the
        // host under the calls that are already running.
        set_json_dispatcher(Arc::new(EchoHost));
        assert_eq!(
            Arc::strong_count(json_dispatcher().expect("the first host is still there")),
            1,
            "the second host is dropped, the first one is kept"
        );
    }

    #[test]
    fn a_stream_whose_sender_is_dropped_ends_without_an_event() {
        let (mut stream, sender) = JsonCallStream::channel();
        drop(sender);
        assert!(
            crate::rt::test_block_on(stream.next()).is_none(),
            "a dropped sender ends the stream"
        );
    }

    /// A stream of `i32` values, ending as the given events say.
    fn values(
        events: impl IntoIterator<Item = crate::Event<i32, String>>,
    ) -> crate::Observable<i32, String> {
        crate::Observable::from_events(events)
    }

    #[test]
    fn first_mode_reads_only_the_first_value() {
        let stream = values([
            crate::Event::Next(1),
            crate::Event::Next(2),
            crate::Event::Complete,
        ]);
        let outcome = crate::rt::test_block_on(read_json(stream, ReadMode::First)).expect("ok");
        assert_eq!(outcome, JsonOutcome::Value(serde_json::json!(1)));
    }

    #[test]
    fn all_mode_collects_every_value_in_order() {
        let stream = values([
            crate::Event::Next(1),
            crate::Event::Next(2),
            crate::Event::Next(3),
            crate::Event::Complete,
        ]);
        let outcome = crate::rt::test_block_on(read_json(stream, ReadMode::All)).expect("ok");
        assert_eq!(outcome, JsonOutcome::Value(serde_json::json!([1, 2, 3])));
    }

    #[test]
    fn a_completion_without_any_value_is_not_a_failure() {
        // `First` has to tell "the service emitted nothing" from a `null` payload;
        // `All` simply produces the empty array.
        let nothing =
            crate::rt::test_block_on(read_json(values([crate::Event::Complete]), ReadMode::First))
                .expect("an empty completion is legitimate");
        assert_eq!(nothing, JsonOutcome::Nothing);

        let all =
            crate::rt::test_block_on(read_json(values([crate::Event::Complete]), ReadMode::All))
                .expect("an empty stream is legitimate");
        assert_eq!(all, JsonOutcome::Value(serde_json::json!([])));
    }

    #[test]
    fn a_business_error_maps_to_a_business_failure_in_both_modes() {
        // No `Next` before the error: in `First` mode a leading value would be
        // read and returned before the failure is ever seen.
        let error = |mode| {
            let stream = values([crate::Event::Error(crate::ObservableError::Business(
                String::from("denied"),
            ))]);
            crate::rt::test_block_on(read_json(stream, mode))
        };

        assert_eq!(
            error(ReadMode::First),
            Err(JsonCallError::Business(String::from("denied")))
        );
        assert_eq!(
            error(ReadMode::All),
            Err(JsonCallError::Business(String::from("denied")))
        );
    }

    #[test]
    fn a_technical_error_maps_to_a_transport_failure_in_both_modes() {
        let error = |mode| {
            let stream = values([crate::Event::Error(crate::ObservableError::Technical(
                crate::RpcError::TransportError(String::from("link down")),
            ))]);
            crate::rt::test_block_on(read_json(stream, mode))
        };

        for mode in [ReadMode::First, ReadMode::All] {
            match error(mode) {
                Err(JsonCallError::Transport(message)) => {
                    assert!(message.contains("link down"), "{message}");
                }
                other => panic!("expected a transport failure, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_value_json_cannot_represent_is_a_transport_failure() {
        use std::collections::HashMap;

        // JSON object keys are strings: a byte-string key cannot be represented,
        // so this value fails to serialize. The failure must surface as a call
        // error, not a panic.
        let failing = || {
            crate::Observable::<HashMap<Vec<u8>, i32>, String>::from_events([
                crate::Event::Next(HashMap::from([(vec![1, 2, 3], 2)])),
                crate::Event::Complete,
            ])
        };

        let first = crate::rt::test_block_on(read_json(failing(), ReadMode::First))
            .expect_err("the value cannot be serialized");
        assert!(
            matches!(&first, JsonCallError::Transport(message)
                if message.contains("failed to serialize the response")),
            "{first:?}"
        );

        let all = crate::rt::test_block_on(read_json(failing(), ReadMode::All))
            .expect_err("the value cannot be serialized");
        assert!(
            matches!(&all, JsonCallError::Transport(message)
                if message.contains("failed to serialize a value")),
            "{all:?}"
        );
    }
}