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
//! 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>;

    /// Resolves the human-readable name of `method_id`, when this decoder knows
    /// it.
    ///
    /// The wire carries only [`method_id_of`](crate::types::method_id_of): an
    /// observer that did not link the service definitions cannot name a method,
    /// exactly as it cannot name a service. The default returns `None`, so the
    /// observer falls back to the hexadecimal id.
    fn method_name(&self, _method_id: u32) -> Option<&'static str> {
        None
    }
}

/// 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,
    /// Method names this decoder can resolve from their wire id.
    names: Vec<(u32, &'static str)>,
}

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),
            names: Vec::new(),
        }
    }

    /// Declares one method name this decoder can resolve from its wire id.
    ///
    /// A hand-built observer must name the methods it wants rendered; the
    /// generated decoders declare theirs automatically.
    #[must_use]
    pub fn with_method(mut self, name: &'static str) -> Self {
        self.names.push((crate::types::method_id_of(name), name));
        self
    }
}

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)
    }

    fn method_name(&self, method_id: u32) -> Option<&'static str> {
        self.names
            .iter()
            .find(|(id, _)| *id == method_id)
            .map(|(_, name)| *name)
    }
}

/// 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()
    }

    /// Builds the registry from **every** decoder linked into this binary.
    ///
    /// This is the registry an observer wants, and the one no hand-written list
    /// can keep honest: a service declared with `#[service]` in a linked crate is
    /// in it, and a service that is not linked is not part of the binary at all.
    ///
    /// # The one caveat
    /// A crate whose items are never referenced can be dropped by the linker,
    /// registrations included, and the registry would then be *silently* empty.
    /// An observer that only watches another crate's services therefore has to
    /// reference it once — `use common as _;`, or the accessor that crate
    /// documents — which is also what keeps the link honest.
    #[cfg(feature = "monitoring")]
    pub fn linked() -> Self {
        let mut decoders = Self::new();
        for registration in DECODERS {
            decoders.register(
                crate::types::service_id_of(registration.service_name),
                (registration.build)(),
            );
        }
        decoders
    }

    /// 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)
    }

    /// Resolves the human-readable name of a method from its wire id.
    ///
    /// `None` without a decoder for the service, or when the decoder was not
    /// told that method's name: the observer then falls back to the hexadecimal
    /// id, exactly as it does for an unlinked service.
    pub fn method_name(&self, service_id: u32, method_id: u32) -> Option<&'static str> {
        self.services.get(&service_id)?.method_name(method_id)
    }
}

impl fmt::Debug for Decoders {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Decoders")
            .field("services", &self.services.len())
            .finish()
    }
}
/// One decoder a `#[service]` expansion submits **at link time**.
///
/// The macro fills one of these per service, and the linker collects them into a
/// section read back by [`Decoders::linked`]. That is what removes the list an
/// observer used to maintain: the services it can render are exactly the ones
/// whose crates are linked into its binary.
#[cfg(feature = "monitoring")]
pub struct DecoderRegistration {
    /// Logical name of the service, as declared to `#[service]`.
    pub service_name: &'static str,
    /// Builds the decoder. A `fn` pointer, so the submitted value is a constant.
    pub build: fn() -> Arc<dyn ServiceDecoder>,
}

#[cfg(feature = "monitoring")]
impl DecoderRegistration {
    /// Builds one registration, in the `const` expression `linkme` requires.
    pub const fn new(service_name: &'static str, build: fn() -> Arc<dyn ServiceDecoder>) -> Self {
        Self {
            service_name,
            build,
        }
    }
}

/// Every decoder linked into this binary.
///
/// `#[service]` appends one entry per service when the `monitoring` feature is
/// on, and the linker assembles the slice. The order across crates is **not**
/// specified, so a consumer that needs a stable order sorts on
/// [`DecoderRegistration::service_name`].
#[cfg(feature = "monitoring")]
#[linkme::distributed_slice]
pub static DECODERS: [DecoderRegistration] = [..];

#[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);
    }

    #[test]
    fn every_response_kind_decodes_to_its_own_text() {
        use crate::types::{RpcError, WireEvent};

        let render = |payload: &[u8]| {
            decode_response::<Reply, String>(payload, |v| render_value!(v), |e| render_value!(e))
        };

        // `Complete` carries no value: the terminal kind names itself.
        let complete = encode(&WireEvent::<Reply, String>::Complete);
        assert_eq!(render(&complete).as_deref(), Some("complete"));

        // `CompleteWith` is the last value of a stream, rendered like a `Next`.
        let complete_with = encode(&WireEvent::<Reply, String>::CompleteWith(Reply {
            value: 3,
        }));
        assert_eq!(render(&complete_with).as_deref(), Some("value=3"));

        let error = encode(&WireEvent::<Reply, String>::Error(String::from("nope")));
        assert_eq!(render(&error).as_deref(), Some("error: nope"));

        // A transport-level rejection is rendered without the service types.
        let rpc_error = encode(&WireEvent::<Reply, String>::RpcError(
            RpcError::TransportError(String::from("boom")),
        ));
        let rendered = render(&rpc_error).expect("an RpcError decodes");
        assert!(rendered.starts_with("rpc error: "), "{rendered}");
    }

    #[test]
    fn the_unit_response_decodes_every_kind() {
        use crate::types::{RpcError, WireEvent};

        let render = |payload: &[u8]| decode_response_unit::<String>(payload, |e| render_value!(e));

        // `()` carries nothing worth rendering, so both value kinds print `()`.
        let next = encode(&WireEvent::<(), String>::Next(()));
        assert_eq!(render(&next).as_deref(), Some("()"));

        let complete_with = encode(&WireEvent::<(), String>::CompleteWith(()));
        assert_eq!(render(&complete_with).as_deref(), Some("()"));

        let complete = encode(&WireEvent::<(), String>::Complete);
        assert_eq!(render(&complete).as_deref(), Some("complete"));

        let error = encode(&WireEvent::<(), String>::Error(String::from("bad")));
        assert_eq!(render(&error).as_deref(), Some("error: bad"));

        let rpc_error = encode(&WireEvent::<(), String>::RpcError(
            RpcError::TransportError(String::from("x")),
        ));
        let rendered = render(&rpc_error).expect("an RpcError decodes");
        assert!(rendered.starts_with("rpc error: "), "{rendered}");
    }

    #[test]
    fn the_registry_reports_its_size_and_resolves_method_names() {
        let mut decoders = Decoders::new();
        assert!(decoders.is_empty());
        assert_eq!(decoders.len(), 0);
        // An unknown service has no decoder: neither direction decodes, and no
        // method name can be resolved.
        assert_eq!(decoders.request(1, "m", b""), None);
        assert_eq!(decoders.response(1, "m", b""), None);
        assert_eq!(decoders.method_name(1, 0), None);

        decoders.register(
            7,
            Arc::new(ClosureDecoder::new(|_, _| None, |_, _| None).with_method("echo")),
        );
        assert_eq!(decoders.len(), 1);
        assert!(!decoders.is_empty());
        // The name is resolvable from the id the wire actually carries.
        assert_eq!(
            decoders.method_name(7, crate::types::method_id_of("echo")),
            Some("echo")
        );
        // An id the decoder was never told about stays unknown.
        assert_eq!(decoders.method_name(7, 0xDEAD_BEEF), None);

        // A decoder that declares no name keeps the default `None`.
        decoders.register(8, Arc::new(ClosureDecoder::new(|_, _| None, |_, _| None)));
        assert_eq!(decoders.method_name(8, 0), None);

        // Re-registering a service replaces its decoder instead of adding one.
        decoders.register(7, Arc::new(ClosureDecoder::new(|_, _| None, |_, _| None)));
        assert_eq!(decoders.len(), 2, "a service id maps to a single decoder");

        let debug = format!("{decoders:?}");
        assert!(debug.starts_with("Decoders"), "{debug}");
        assert!(debug.contains("services"), "{debug}");
    }
}