ice-rpc 0.3.2

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
//! Rendering of the observed payloads, and the registry of decoders.
//!
//! An observer linked against the service definitions can turn the rkyv payloads
//! back into text. The rendering is **optional by type**: each value is rendered
//! with its [`Display`](std::fmt::Display) implementation when it has one, with
//! its [`Debug`](std::fmt::Debug) implementation otherwise, so a service type
//! only has to be `Debug` to be observable.
//!
//! The inventory of the machine lives in [`super::inventory`]: this module never
//! looks at the iceoryx2 services themselves.

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

/// Value carrier of [`render_value!`].
///
/// Plumbing for the code generated by `#[service]` with the `monitoring`
/// feature; not meant to be named by hand.
#[doc(hidden)]
pub struct RenderValue<T>(pub T);

/// `Display` candidate of [`render_value!`].
///
/// Method resolution reaches this implementation **first**: it is selected as
/// soon as the wrapped type implements [`Display`](std::fmt::Display).
#[doc(hidden)]
pub trait RenderViaDisplay {
    /// Renders the wrapped value.
    fn render(&self) -> String;
}

impl<T: fmt::Display> RenderViaDisplay for RenderValue<T> {
    fn render(&self) -> String {
        self.0.to_string()
    }
}

/// `Debug` candidate of [`render_value!`].
///
/// Reached only when the wrapped type has no [`Display`](std::fmt::Display)
/// implementation: the fallback keeps a service free of any formatting
/// requirement beyond `Debug`.
#[doc(hidden)]
pub trait RenderViaDebug {
    /// Renders the wrapped value.
    fn render(&self) -> String;
}

impl<T: fmt::Debug> RenderViaDebug for &RenderValue<T> {
    fn render(&self) -> String {
        format!("{:?}", self.0)
    }
}

/// Renders a monitored value with its [`Display`](std::fmt::Display) form when
/// the type implements it, with its [`Debug`](std::fmt::Debug) form otherwise.
///
/// This is what the `#[service]`-generated decoders use, so a service type only
/// has to be `Debug` — which the generated request enum already requires — to be
/// rendered by an observer; a type that also implements `Display` keeps its
/// hand-written rendering.
///
/// The choice between the two implementations is made by **method resolution at
/// the call site**, hence a macro rather than a function: the generated code
/// expands it where the value's type is concrete, while a generic function would
/// resolve a single candidate — the `Debug` one — for every `T`.
#[doc(hidden)]
#[macro_export]
macro_rules! render_value {
    ($value:expr) => {{
        #[allow(unused_imports)]
        use $crate::monitor::{RenderViaDebug as _, RenderViaDisplay as _};
        (&$crate::monitor::RenderValue($value)).render()
    }};
}

/// Decodes a rkyv **request** payload into its rendered form.
///
/// `R` is the generated `{Trait}Request` enum, whose `Display` implementation —
/// always emitted by `#[service]` — renders each argument through
/// `render_value!`; an argument type therefore only has to be `Debug`.
///
/// Returns `None` when the bytes are not a valid encoding of `R` — typically
/// because the observer was not built with the service types.
///
/// [`Display`]: std::fmt::Display
pub fn decode_request<R>(payload: &[u8]) -> Option<String>
where
    R: rkyv::Archive + std::fmt::Display,
    <R as rkyv::Archive>::Archived:
        rkyv::Deserialize<R, rkyv::rancor::Strategy<rkyv::de::Pool, rkyv::rancor::Error>>,
    for<'a> <R as rkyv::Archive>::Archived:
        rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
    crate::transport::decode_aligned::<R>(payload)
        .ok()
        .map(|value| value.to_string())
}

/// Decodes a rkyv **response** payload into its rendered form.
///
/// A response is a [`WireEvent<T, E>`](crate::types::WireEvent): the human
/// rendering is that of the carried value, or the terminal kind name.
///
/// Decoding imposes **no** formatting bound on `T` and `E`: the caller passes
/// the renderers, expanded where the types are concrete (see `render_value!`),
/// so `Decoders` never forces `Display` — nor even `Debug` — on a service type.
pub fn decode_response<T, E>(
    payload: &[u8],
    render_ok: impl Fn(&T) -> String,
    render_err: impl Fn(&E) -> String,
) -> Option<String>
where
    crate::types::WireEvent<T, E>: rkyv::Archive,
    <crate::types::WireEvent<T, E> as rkyv::Archive>::Archived: rkyv::Deserialize<
        crate::types::WireEvent<T, E>,
        rkyv::rancor::Strategy<rkyv::de::Pool, rkyv::rancor::Error>,
    >,
    for<'a> <crate::types::WireEvent<T, E> as rkyv::Archive>::Archived:
        rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
    use crate::types::WireEvent;
    crate::transport::decode_aligned::<WireEvent<T, E>>(payload)
        .ok()
        .map(|event| match event {
            WireEvent::Next(value) | WireEvent::CompleteWith(value) => render_ok(&value),
            WireEvent::Complete => "complete".to_owned(),
            WireEvent::Error(error) => format!("error: {}", render_err(&error)),
            WireEvent::RpcError(error) => format!("rpc error: {error}"),
        })
}

/// Like [`decode_response`], for a service whose success type is `()`.
///
/// `()` carries nothing worth rendering, so the unit case — many health-check
/// methods return `Observable<(), E>` — only needs the error renderer.
pub fn decode_response_unit<E>(payload: &[u8], render_err: impl Fn(&E) -> String) -> Option<String>
where
    crate::types::WireEvent<(), E>: rkyv::Archive,
    <crate::types::WireEvent<(), E> as rkyv::Archive>::Archived: rkyv::Deserialize<
        crate::types::WireEvent<(), E>,
        rkyv::rancor::Strategy<rkyv::de::Pool, rkyv::rancor::Error>,
    >,
    for<'a> <crate::types::WireEvent<(), E> as rkyv::Archive>::Archived:
        rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
    use crate::types::WireEvent;
    crate::transport::decode_aligned::<WireEvent<(), E>>(payload)
        .ok()
        .map(|event| match event {
            WireEvent::Next(()) | WireEvent::CompleteWith(()) => "()".to_owned(),
            WireEvent::Complete => "complete".to_owned(),
            WireEvent::Error(error) => format!("error: {}", render_err(&error)),
            WireEvent::RpcError(error) => format!("rpc error: {error}"),
        })
}

/// Turns the raw rkyv payload of one service into human-readable text.
///
/// The two directions are separate because a request and a response carry
/// different types (`{Service}Request` and `WireEvent<T, E>`).
pub trait ServiceDecoder: Send + Sync {
    /// Renders a request payload, given the method name carried by the header.
    fn request(&self, method: &str, payload: &[u8]) -> Option<String>;

    /// Renders a response payload, given the method of the matched request.
    fn response(&self, method: &str, payload: &[u8]) -> Option<String>;
}

/// Boxed renderer used by [`ClosureDecoder`].
type Render = Box<dyn Fn(&str, &[u8]) -> Option<String> + Send + Sync>;

/// A [`ServiceDecoder`] assembled from two closures.
pub struct ClosureDecoder {
    request: Render,
    response: Render,
}

impl ClosureDecoder {
    /// Builds a decoder from a request renderer and a response renderer.
    pub fn new(
        request: impl Fn(&str, &[u8]) -> Option<String> + Send + Sync + 'static,
        response: impl Fn(&str, &[u8]) -> Option<String> + Send + Sync + 'static,
    ) -> Self {
        Self {
            request: Box::new(request),
            response: Box::new(response),
        }
    }
}

impl ServiceDecoder for ClosureDecoder {
    fn request(&self, method: &str, payload: &[u8]) -> Option<String> {
        (self.request)(method, payload)
    }

    fn response(&self, method: &str, payload: &[u8]) -> Option<String> {
        (self.response)(method, payload)
    }
}

/// Registry of the decoders known to an observer, keyed by service id.
///
/// The generated `{Trait}Decoder::register` populates it; an observer binary
/// builds one from the service definitions it links against.
#[derive(Default)]
pub struct Decoders {
    services: HashMap<u32, Arc<dyn ServiceDecoder>>,
}

impl Decoders {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers (or replaces) the decoder of `service_id`.
    pub fn register(&mut self, service_id: u32, decoder: Arc<dyn ServiceDecoder>) -> &mut Self {
        self.services.insert(service_id, decoder);
        self
    }

    /// Number of services with a registered decoder.
    pub fn len(&self) -> usize {
        self.services.len()
    }

    /// Returns `true` when no decoder is registered.
    pub fn is_empty(&self) -> bool {
        self.services.is_empty()
    }

    /// Renders a request payload; `None` without a decoder or on a decode failure.
    pub fn request(&self, service_id: u32, method: &str, payload: &[u8]) -> Option<String> {
        self.services.get(&service_id)?.request(method, payload)
    }

    /// Renders a response payload; `None` without a decoder or on a decode failure.
    pub fn response(&self, service_id: u32, method: &str, payload: &[u8]) -> Option<String> {
        self.services.get(&service_id)?.response(method, payload)
    }
}

impl fmt::Debug for Decoders {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Decoders")
            .field("services", &self.services.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rkyv::{Archive, Deserialize, Serialize};

    #[derive(Archive, Serialize, Deserialize, Debug, PartialEq)]
    struct Reply {
        value: i32,
    }

    impl fmt::Display for Reply {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "value={}", self.value)
        }
    }

    /// Type with no `Display`: its rendering falls back to `Debug`.
    #[derive(Archive, Serialize, Deserialize, Debug, PartialEq)]
    enum DebugOnly {
        Nok,
    }

    /// Stands for the request enum `#[service]` generates.
    #[derive(Archive, Serialize, Deserialize, Debug, PartialEq)]
    enum Request {
        Add { a: i32, b: i32 },
        Echo { text: String },
        Probe { status: DebugOnly },
    }

    /// Stands for the `Display` implementation `#[service]` generates: every
    /// argument is rendered through [`render_value!`].
    impl fmt::Display for Request {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Request::Add { a, b } => {
                    write!(f, "add(a={}, b={})", render_value!(a), render_value!(b))
                }
                Request::Echo { text } => write!(f, "echo(text={})", render_value!(text)),
                Request::Probe { status } => write!(f, "probe(status={})", render_value!(status)),
            }
        }
    }

    fn encode<T>(value: &T) -> Vec<u8>
    where
        T: for<'a> rkyv::Serialize<
            rkyv::rancor::Strategy<
                rkyv::ser::Serializer<
                    rkyv::util::AlignedVec,
                    rkyv::ser::allocator::ArenaHandle<'a>,
                    rkyv::ser::sharing::Share,
                >,
                rkyv::rancor::Error,
            >,
        >,
    {
        rkyv::to_bytes::<rkyv::rancor::Error>(value)
            .expect("encode")
            .to_vec()
    }

    #[test]
    fn requests_and_responses_decode_through_display() {
        let request = encode(&Request::Add { a: 1, b: 2 });
        assert_eq!(
            decode_request::<Request>(&request).as_deref(),
            Some("add(a=1, b=2)")
        );

        // A `Display` argument keeps its hand-written rendering: no quoting.
        let echo = encode(&Request::Echo {
            text: String::from("hi"),
        });
        assert_eq!(
            decode_request::<Request>(&echo).as_deref(),
            Some("echo(text=hi)")
        );

        // An argument without `Display` is rendered through its `Debug` form.
        let probe = encode(&Request::Probe {
            status: DebugOnly::Nok,
        });
        assert_eq!(
            decode_request::<Request>(&probe).as_deref(),
            Some("probe(status=Nok)")
        );

        let response = encode(&crate::types::WireEvent::<Reply, String>::Next(Reply {
            value: 7,
        }));
        assert_eq!(
            decode_response::<Reply, String>(
                &response,
                |value| render_value!(value),
                |error| render_value!(error)

            )
            .as_deref(),
            Some("value=7")
        );

        let unit = encode(&crate::types::WireEvent::<(), String>::Complete);
        assert_eq!(
            decode_response_unit::<String>(&unit, |error| render_value!(error)).as_deref(),
            Some("complete")
        );
    }

    #[test]
    fn rendering_falls_back_to_debug_without_display() {
        assert_eq!(render_value!(&DebugOnly::Nok), "Nok");
        // `Display` still wins whenever the type provides it, so a `String`
        // payload is not rendered with the `Debug` quoting.
        assert_eq!(render_value!(&Reply { value: 7 }), "value=7");
        assert_eq!(render_value!(&String::from("hi")), "hi");

        let next = encode(&crate::types::WireEvent::<DebugOnly, String>::Next(
            DebugOnly::Nok,
        ));
        assert_eq!(
            decode_response::<DebugOnly, String>(
                &next,
                |value| render_value!(value),
                |error| render_value!(error)

            )
            .as_deref(),
            Some("Nok")
        );

        let response = encode(&crate::types::WireEvent::<DebugOnly, String>::Error(
            String::from("boom"),
        ));
        assert_eq!(
            decode_response::<DebugOnly, String>(
                &response,
                |value| render_value!(value),
                |error| render_value!(error)

            )
            .as_deref(),
            // `Display` wins for the `String` error: no `Debug` quoting.
            Some("error: boom")
        );
    }

    #[test]
    fn garbage_does_not_decode() {
        assert_eq!(decode_request::<Request>(&[0xff, 0x00]), None);
        assert_eq!(
            decode_response::<Reply, String>(
                &[0xff, 0x00],
                |value| render_value!(value),
                |error| render_value!(error)

            ),
            None
        );
    }

    #[test]
    fn a_registered_decoder_renders_both_directions() {
        let mut decoders = Decoders::new();
        decoders.register(
            7,
            Arc::new(ClosureDecoder::new(
                |_method, payload| Some(String::from_utf8_lossy(payload).into_owned()),
                |_method, payload| Some(format!("{} bytes", payload.len())),
            )),
        );

        assert_eq!(decoders.request(7, "echo", b"hi").as_deref(), Some("hi"));
        assert_eq!(
            decoders.response(7, "echo", b"abcd").as_deref(),
            Some("4 bytes")
        );
        assert_eq!(decoders.request(9, "echo", b"hi"), None);
    }
}