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
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Zero-copy RPC header carried in iceoryx2's `user_header`.
//!
//! The header is `ZeroCopySend` and lives *next to* the payload in the shared
//! memory sample, not inside it: reading the correlation id, the method name or
//! the protocol version never deserializes the payload.
//!
//! The layout is `#[repr(C)]` and part of the wire contract shared by every
//! process on the machine: it must not drift silently.

use std::time::{SystemTime, UNIX_EPOCH};

use iceoryx2::prelude::ZeroCopySend;

use super::context::TraceContext;
use crate::labels::impl_labels;
use crate::types::consts::PROTOCOL_VERSION;

/// Correlation id prefixing every request/response pair.
pub const CORRELATION_ID_LEN: usize = 16;

/// Returns the current wall-clock time as nanoseconds since the Unix epoch.
///
/// Every process on the same host shares this clock, so two timestamps taken by
/// different processes are comparable. This is what lets an out-of-band observer
/// compute an exact latency from the `timestamp_ns` fields of a request and of
/// its response.
///
/// A clock adjustment (NTP step or slew) can make a difference between two
/// readings negative: callers must subtract with saturation and count the
/// occurrences separately.
#[inline]
pub fn now_ns() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0)
}

/// Kind of the sample carried by a [`RpcHeader`].
///
/// Stored as a `u8` in the header so the zero-copy layout stays plain data; the
/// values are part of the wire contract.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EventKind {
    /// Request emitted by a client (non-terminal).
    #[default]
    Request = 0,
    /// Intermediate event carrying a business value (non-terminal).
    Next = 1,
    /// Normal end of the stream (terminal).
    Complete = 2,
    /// Terminal business error, whose payload is the service's `WireEvent<T, E>`.
    Error = 3,
    /// Terminal **transport-level** technical error, whose payload is a bare
    /// [`RpcError`](crate::types::RpcError).
    ///
    /// Distinct from [`EventKind::Error`] on purpose: a rejection (unknown
    /// method, unknown service, protocol or interface version mismatch) says
    /// nothing about the service types, and the provider cannot name them at all
    /// for a method it does not have. Framing it as a bare `RpcError` is what
    /// lets any request be answered instead of silently timing out.
    RpcError = 4,
    /// Client to provider signal asking the provider to abandon the call named by
    /// the correlation id it carries (non-terminal).
    ///
    /// Published on the **request** channel, because that is the direction the
    /// caller already publishes on: no extra service, no extra port, and the
    /// correlation id travels in the zero-copy header like every other sample.
    ///
    /// It is not an answer: a provider that does not know the id ignores it, and
    /// an older build decodes it as [`EventKind::Error`] through the fail-closed
    /// [`EventKind::from_u8`], so mixed builds degrade instead of breaking.
    /// Being non-terminal matters to the out-of-band observer too: a Cancel ends a
    /// call's tail, it does not close the call as answered.
    Cancel = 5,
}

impl EventKind {
    /// Returns `true` if this kind terminates the stream.
    #[inline]
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            EventKind::Complete | EventKind::Error | EventKind::RpcError
        )
    }

    /// Returns the wire value of this kind.
    #[inline]
    pub const fn as_u8(self) -> u8 {
        self as u8
    }

    /// Decodes a wire value; unknown values map to [`EventKind::Error`].
    ///
    /// Deliberately fail-closed: an unknown value must never read as a
    /// successful completion. `Complete` is terminal, so a corrupt kind decoded
    /// that way would close a call as if it had succeeded — inflating the
    /// completion counters and hiding the very corruption it should report.
    #[inline]
    pub const fn from_u8(value: u8) -> Self {
        match value {
            0 => EventKind::Request,
            1 => EventKind::Next,
            2 => EventKind::Complete,
            3 => EventKind::Error,
            4 => EventKind::RpcError,
            5 => EventKind::Cancel,
            _ => EventKind::Error,
        }
    }
}

// The labels an observer reads back from a sample (`kind="complete"`), declared
// next to the kind they describe.
impl_labels!(EventKind {
    EventKind::Request => "request",
    EventKind::Next => "next",
    EventKind::Complete => "complete",
    EventKind::Error => "error",
    EventKind::RpcError => "rpc-error",
    EventKind::Cancel => "cancel",
});

/// Zero-copy RPC header attached to every request and response sample.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, ZeroCopySend)]
pub struct RpcHeader {
    /// Request↔response correlation id (16 bytes).
    pub correlation_id: [u8; CORRELATION_ID_LEN],
    /// Emission timestamp, in nanoseconds since the Unix epoch.
    ///
    /// Stamped by the emitter (consumer for a request, provider for a response),
    /// so an observer computes an exact latency with
    /// `response.timestamp_ns - request.timestamp_ns`.
    ///
    /// Declared early so the two 8-byte monitoring fields pack tightly: the
    /// struct must stay within the 128-byte wire budget.
    pub timestamp_ns: u64,
    /// Per-publisher, per-channel monotonic sample counter.
    ///
    /// A publisher is single-threaded for a given channel, so a gap in the
    /// observed sequence proves that samples were lost. Set by the emitter at
    /// publication time.
    pub seq: u64,
    /// W3C trace id of the call, shared by every hop of its call tree.
    ///
    /// Zero when the caller propagated no trace — that is the "absent" value,
    /// not a valid id — which is why [`TraceContext::is_present`] exists.
    pub trace_id: [u8; 16],
    /// Span of the caller, onto which the receiver parents its own span.
    ///
    /// This is the W3C `parent-id` of the `traceparent`: the id of the span
    /// that emitted the call. Zero only on a sample that opens a trace.
    pub parent_span_id: u64,
    /// W3C span id of the hop that **emitted** this sample.
    ///
    /// Distinct from [`parent_span_id`](Self::parent_span_id): this is the
    /// emitter's own span, unique per call and non-zero. It lets an out-of-band
    /// observer reconstruct the trace tree — matching a child's `parent_span_id`
    /// to the parent's `span_id` — and lets an exporter build a `traceparent`.
    pub span_id: u64,
    /// Identifier of the target service inside the channel it is published on.
    ///
    /// Several services can share one channel (their *group*); this id —
    /// [`service_id_of`] of the service name — selects the provider dispatcher.
    ///
    /// The **emitter** identity is deliberately absent: the native iceoryx2
    /// sample header already carries the source `node_id` (hence the PID) and the
    /// `publisher_id`, so duplicating it here would only risk a divergence. An
    /// observer reads it from [`Sample::header()`], and the `publisher_id` is what
    /// scopes [`seq`](Self::seq).
    ///
    /// [`Sample::header()`]: iceoryx2::sample::Sample::header
    pub service_id: u32,
    /// Method invoked by the request (zero on a response or a Cancel).
    ///
    /// [`method_id_of`] of the method name, exactly as [`service_id`](Self::service_id)
    /// is the hash of the service name. The method is routed before the payload
    /// is decoded, so an unknown method is rejected without ever decoding.
    pub method_id: u32,
    /// W3C `traceparent` version byte (always `0` today).
    ///
    /// Stored so the header is a literal `traceparent` prefix and so a future
    /// version can be negotiated without adding another field.
    pub traceparent_version: u8,
    /// Kind of the sample (request / next / complete / error), as a wire value.
    pub event_kind: u8,
    /// ice-rpc wire protocol version of the emitter.
    pub protocol_version: u16,
    /// Service interface version of the emitter.
    pub service_version: u16,
    /// W3C trace flags (bit 0: sampled), propagated with the trace.
    pub flags: u8,
}

impl RpcHeader {
    /// Creates a **request** header with a fresh correlation id.
    ///
    /// `method_id` is [`method_id_of`] of the method name, computed by the
    /// generated caller as a constant.
    #[inline]
    pub fn request(method_id: impl MethodId, service_id: u32, service_version: u16) -> Self {
        Self {
            correlation_id: next_correlation_id(),
            service_id,
            method_id: method_id.method_id(),
            traceparent_version: 0,
            event_kind: EventKind::Request.as_u8(),
            protocol_version: PROTOCOL_VERSION,
            service_version,
            // No trace until the caller attaches one with `with_trace`.
            trace_id: [0u8; 16],
            parent_span_id: 0,
            span_id: 0,
            flags: 0,
            // Stamped by the caller with the per-channel sequence.
            seq: 0,
            timestamp_ns: now_ns(),
        }
    }

    /// Attaches the trace context propagated with this sample (builder style).
    ///
    /// A caller that is itself serving a traced call passes the context it
    /// received, so the chain survives the hop; a caller with no ambient trace
    /// leaves the three fields zeroed, which is the "absent" value.
    #[inline]
    pub fn with_trace(mut self, trace: TraceContext) -> Self {
        self.trace_id = trace.trace_id;
        self.parent_span_id = trace.parent_span_id;
        self.flags = trace.flags;
        self
    }

    /// Sets the W3C span id of the emitting hop (builder style).
    ///
    /// Distinct from the trace context: `with_trace` carries the **caller's**
    /// span (the W3C `parent-id`), while this is the emitter's own span.
    #[inline]
    pub fn with_span_id(mut self, span_id: u64) -> Self {
        self.span_id = span_id;
        self
    }

    /// Trace context carried by this sample.
    #[inline]
    pub fn trace(&self) -> TraceContext {
        TraceContext {
            trace_id: self.trace_id,
            parent_span_id: self.parent_span_id,
            flags: self.flags,
        }
    }

    /// Sets the per-publisher sample sequence (builder style).
    ///
    /// The counter is owned by the publisher (one per channel), not by this
    /// header constructor, so the emitter stamps it just before publication.
    #[inline]
    pub fn with_seq(mut self, seq: u64) -> Self {
        self.seq = seq;
        self
    }

    /// Builds the response header of `request`.
    #[inline]
    pub fn response_from(request: &RpcHeader, event_kind: EventKind, service_version: u16) -> Self {
        Self {
            correlation_id: request.correlation_id,
            service_id: request.service_id,
            method_id: 0,
            traceparent_version: request.traceparent_version,
            event_kind: event_kind.as_u8(),
            protocol_version: PROTOCOL_VERSION,
            service_version,
            // A response echoes the trace of the request it answers.
            trace_id: request.trace_id,
            parent_span_id: request.parent_span_id,
            // The emitter's own span is not known here; an observer joins the
            // response to its request through the correlation id.
            span_id: 0,
            flags: request.flags,
            // Stamped by the caller with the per-channel sequence.
            seq: 0,
            timestamp_ns: now_ns(),
        }
    }

    /// Builds the header of the Cancel that abandons `request`.
    ///
    /// Mirrors [`response_from`](Self::response_from): same correlation id, same
    /// service identity and same trace, so the provider finds the call it must
    /// stop and an out-of-band observer joins the Cancel to its request. The
    /// method name is left empty on purpose — the correlation id names the call
    /// on its own, and a provider routes a Cancel without looking up a service,
    /// which is exactly what lets it be answered for a call it never dispatched.
    #[inline]
    pub fn cancel_from(request: &RpcHeader) -> Self {
        Self {
            correlation_id: request.correlation_id,
            service_id: request.service_id,
            method_id: 0,
            traceparent_version: request.traceparent_version,
            event_kind: EventKind::Cancel.as_u8(),
            protocol_version: PROTOCOL_VERSION,
            service_version: request.service_version,
            // A Cancel stays in the trace of the call it abandons.
            trace_id: request.trace_id,
            parent_span_id: request.parent_span_id,
            span_id: 0,
            flags: request.flags,
            // Stamped by the emitter with the per-channel sequence, like every
            // other sample: a gap in `seq` is how the observer detects a loss.
            seq: 0,
            timestamp_ns: now_ns(),
        }
    }

    /// Returns the method id carried by the header (zero on a response).
    #[inline]
    pub fn method_id(&self) -> u32 {
        self.method_id
    }

    /// Returns the kind of the sample.
    #[inline]
    pub fn event_kind(&self) -> EventKind {
        EventKind::from_u8(self.event_kind)
    }
}

/// FNV-1a hash of `bytes`: the shared identity primitive of the wire contract.
///
/// `const` so every name hash is computed at compile time, and deterministic so
/// every process derives the same value without discovery.
#[inline]
const fn fnv1a_u32(bytes: &[u8]) -> u32 {
    const OFFSET_BASIS: u32 = 0x811c_9dc5;
    const PRIME: u32 = 0x0100_0193;

    let mut hash = OFFSET_BASIS;
    let mut i = 0;
    while i < bytes.len() {
        hash ^= bytes[i] as u32;
        hash = hash.wrapping_mul(PRIME);
        i += 1;
    }
    hash
}

/// Computes the stable identifier of a service inside its channel (FNV-1a).
///
/// A `const fn`, so the generated code can use the result as a constant, and
/// every process derives the same value from the same name without discovery.
/// A collision between two co-located services is detected at channel
/// registration.
#[inline]
pub const fn service_id_of(name: &str) -> u32 {
    fnv1a_u32(name.as_bytes())
}

/// Computes the stable identifier of a method inside its service (FNV-1a).
///
/// The method counterpart of [`service_id_of`]: the wire carries this 4-byte id
/// instead of the method name, which frees the header and lets the provider
/// route — and reject an unknown method — before decoding the payload. The name
/// itself stays compile-time knowledge of the generated code (logs, spans, the
/// observer's registry), never a wire field.
#[inline]
pub const fn method_id_of(name: &str) -> u32 {
    fnv1a_u32(name.as_bytes())
}

/// A method identifier accepted by the call APIs.
///
/// The wire carries only a `u32` ([`method_id_of`]). The generated code passes
/// that constant id, but hand-written callers and tests may pass the method name
/// directly and pay one hash — which keeps the call sites readable without ever
/// putting the name on the wire.
pub trait MethodId {
    /// Returns the wire id of the method.
    fn method_id(self) -> u32;
}

impl MethodId for u32 {
    #[inline]
    fn method_id(self) -> u32 {
        self
    }
}

impl MethodId for &str {
    #[inline]
    fn method_id(self) -> u32 {
        method_id_of(self)
    }
}

/// Identity of a service contract: its id inside the channel and its interface
/// version.
///
/// The two always travel together and are generated **once** per service, so an
/// id can never be paired with a foreign version. Threading this single value
/// through the transport is what makes dropping the version a compile error
/// rather than a silent `1`.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ServiceRef {
    /// Identifier of the service inside its channel ([`service_id_of`]).
    pub id: u32,
    /// Service interface version declared by `#[service(..., version = N)]`.
    pub version: u16,
}

impl ServiceRef {
    /// Builds a service identity; usable in a `const` item.
    #[inline]
    pub const fn new(id: u32, version: u16) -> Self {
        Self { id, version }
    }
}

/// Allocates a process-unique correlation id: `pid ++ counter`.
#[inline]
pub fn next_correlation_id() -> [u8; CORRELATION_ID_LEN] {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(1);
    let pid = u64::from(super::node::cached_pid());
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    let mut out = [0u8; CORRELATION_ID_LEN];
    out[..8].copy_from_slice(&pid.to_be_bytes());
    out[8..].copy_from_slice(&counter.to_be_bytes());
    out
}

/// Formats a correlation id as a UUID-like hexadecimal string.
pub fn fmt_correlation_id(cid: &[u8; CORRELATION_ID_LEN]) -> String {
    let [
        b0,
        b1,
        b2,
        b3,
        b4,
        b5,
        b6,
        b7,
        b8,
        b9,
        b10,
        b11,
        b12,
        b13,
        b14,
        b15,
    ] = cid;
    format!(
        "{b0:02x}{b1:02x}{b2:02x}{b3:02x}-{b4:02x}{b5:02x}-{b6:02x}{b7:02x}-\
         {b8:02x}{b9:02x}-{b10:02x}{b11:02x}{b12:02x}{b13:02x}{b14:02x}{b15:02x}"
    )
}
/// Parses a UUID-like hexadecimal correlation id.
///
/// Accepts both forms a JavaScript caller may hold: the 36-character dashed
/// form produced by [`fmt_correlation_id`] and the 32-character undashed one.
/// Performs a single pass and allocates nothing, so it is usable on the hot
/// path of the Node.js bridge. Returns `None` on any other length, on a
/// misplaced dash and on a non-hexadecimal digit -- a partially parsed id is
/// never returned.
pub fn parse_correlation_id(text: &str) -> Option<[u8; CORRELATION_ID_LEN]> {
    let bytes = text.as_bytes();
    let undashed_len = CORRELATION_ID_LEN * 2;
    let dashed = if bytes.len() == undashed_len {
        false
    } else if bytes.len() == undashed_len + 4 {
        true
    } else {
        return None;
    };

    let mut out = [0u8; CORRELATION_ID_LEN];
    let mut nibbles = 0usize;
    for (index, byte) in bytes.iter().enumerate() {
        if dashed && matches!(index, 8 | 13 | 18 | 23) {
            if *byte != b'-' {
                return None;
            }
            continue;
        }
        let digit = match byte {
            b'0'..=b'9' => byte - b'0',
            b'a'..=b'f' => byte - b'a' + 10,
            b'A'..=b'F' => byte - b'A' + 10,
            _ => return None,
        };
        if nibbles.is_multiple_of(2) {
            out[nibbles / 2] = digit << 4;
        } else {
            out[nibbles / 2] |= digit;
        }
        nibbles += 1;
    }

    (nibbles == CORRELATION_ID_LEN * 2).then_some(out)
}

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

    #[test]
    fn request_header_carries_the_method_and_a_fresh_id() {
        let id = service_id_of("DatabaseService");
        let method = method_id_of("get_user_age");
        let a = RpcHeader::request(method, id, 2);
        let b = RpcHeader::request(method, id, 2);
        assert_eq!(a.method_id(), method);
        assert_eq!(a.event_kind(), EventKind::Request);
        assert_eq!(a.service_id, id);
        assert_eq!(a.service_version, 2);
        assert_ne!(a.correlation_id, b.correlation_id);
    }

    #[test]
    fn response_header_reuses_the_request_id_and_service() {
        let id = service_id_of("GetPerson");
        let request = RpcHeader::request(method_id_of("ping"), id, 1);
        let response = RpcHeader::response_from(&request, EventKind::Complete, 1);
        assert_eq!(response.correlation_id, request.correlation_id);
        assert_eq!(response.service_id, id);
        assert_eq!(response.event_kind(), EventKind::Complete);
        assert_eq!(response.method_id(), 0, "a response names no method");
    }

    #[test]
    fn service_id_is_stable_and_distinguishes_names() {
        // Offset basis of FNV-1a: pins the algorithm.
        assert_eq!(service_id_of(""), 0x811c_9dc5);

        // Usable in a constant expression, which is how the macro passes it.
        const ID: u32 = service_id_of("DatabaseService");
        assert_eq!(ID, service_id_of("DatabaseService"));
        assert_ne!(
            service_id_of("DatabaseService"),
            service_id_of("ConfigService")
        );
    }

    #[test]
    fn method_id_is_stable_and_distinguishes_names() {
        // Same primitive as `service_id_of`: the offset basis is pinned.
        assert_eq!(method_id_of(""), 0x811c_9dc5);

        const ID: u32 = method_id_of("get_user_age");
        assert_eq!(ID, method_id_of("get_user_age"));
        assert_ne!(method_id_of("get_user_age"), method_id_of("get_user_name"));
    }

    #[test]
    fn the_header_layout_stays_bounded_and_aligned() {
        // Part of the wire contract: the header is copied per sample and its size
        // is validated by iceoryx2 when a service is opened, so every process on
        // the machine must agree on it. Pinning the exact size makes any layout
        // drift a deliberate, reviewed change.
        assert_eq!(std::mem::align_of::<RpcHeader>(), 8);
        assert_eq!(std::mem::size_of::<RpcHeader>(), 80);

        assert_eq!(std::mem::offset_of!(RpcHeader, correlation_id), 0);
        assert_eq!(std::mem::offset_of!(RpcHeader, timestamp_ns), 16);
        assert_eq!(std::mem::offset_of!(RpcHeader, seq), 24);
        assert_eq!(std::mem::offset_of!(RpcHeader, trace_id), 32);
        assert_eq!(std::mem::offset_of!(RpcHeader, parent_span_id), 48);
        assert_eq!(std::mem::offset_of!(RpcHeader, span_id), 56);
        assert_eq!(std::mem::offset_of!(RpcHeader, service_id), 64);
        assert_eq!(std::mem::offset_of!(RpcHeader, method_id), 68);
        assert_eq!(std::mem::offset_of!(RpcHeader, traceparent_version), 72);
        assert_eq!(std::mem::offset_of!(RpcHeader, event_kind), 73);
        assert_eq!(std::mem::offset_of!(RpcHeader, protocol_version), 74);
        assert_eq!(std::mem::offset_of!(RpcHeader, service_version), 76);
        assert_eq!(std::mem::offset_of!(RpcHeader, flags), 78);
    }

    /// The trace context survives a header round-trip, and the response echoes
    /// the request's.
    #[test]
    fn the_trace_context_travels_with_the_header() {
        let trace = TraceContext {
            trace_id: [7u8; 16],
            parent_span_id: 42,
            flags: 1,
        };

        let request =
            RpcHeader::request(method_id_of("ping"), service_id_of("Ping"), 1).with_trace(trace);
        assert_eq!(request.trace(), trace);
        assert!(request.trace().is_present());
        assert!(request.trace().is_sampled());

        let response = RpcHeader::response_from(&request, EventKind::Complete, 1);
        assert_eq!(response.trace(), trace, "the response echoes the trace");
    }

    /// With no trace attached, the three fields stay at their "absent" value.
    #[test]
    fn a_request_without_trace_carries_zeros() {
        let request = RpcHeader::request(method_id_of("ping"), service_id_of("Ping"), 1);
        assert!(!request.trace().is_present());
        assert_eq!(request.trace().parent_span_id, 0);
    }

    #[test]
    fn request_stamps_a_timestamp() {
        let id = service_id_of("Ping");
        let before = now_ns();
        let header = RpcHeader::request(method_id_of("ping"), id, 1);
        let after = now_ns();

        assert!(header.timestamp_ns >= before);
        assert!(header.timestamp_ns <= after);
        // `seq` is owned by the publisher, not by the constructor.
        assert_eq!(header.seq, 0);
        assert_eq!(header.with_seq(7).seq, 7);
    }

    #[test]
    fn response_stamps_its_own_emission_time() {
        let request = RpcHeader::request(method_id_of("ping"), service_id_of("Ping"), 1);
        let response = RpcHeader::response_from(&request, EventKind::Complete, 1);

        assert_eq!(response.correlation_id, request.correlation_id);
        // The response carries its own emission time, distinct from the request's.
        assert!(response.timestamp_ns >= request.timestamp_ns);
        assert_eq!(response.with_seq(3).seq, 3);
    }

    #[test]
    fn fmt_correlation_id_is_uuid_shaped() {
        let cid = [
            0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
            0x66, 0x77,
        ];
        assert_eq!(
            fmt_correlation_id(&cid),
            "deadbeef-cafe-babe-0011-223344556677"
        );
    }

    /// An unknown kind must decode to `Error`, never to the terminal `Complete`.
    #[test]
    fn an_unknown_event_kind_decodes_as_error_not_complete() {
        for value in 6u8..=u8::MAX {
            assert_eq!(
                EventKind::from_u8(value),
                EventKind::Error,
                "the unknown kind {value} must not read as a successful completion"
            );
        }

        // Every declared value round-trips, `Complete` included.
        for kind in [
            EventKind::Request,
            EventKind::Next,
            EventKind::Complete,
            EventKind::Error,
            EventKind::RpcError,
            EventKind::Cancel,
        ] {
            assert_eq!(EventKind::from_u8(kind.as_u8()), kind);
        }
    }

    /// A Cancel abandons a call, it does not answer it: reading it as terminal
    /// would let an observer close a call the provider never finished.
    #[test]
    fn a_cancel_is_not_terminal_and_has_its_own_label() {
        assert!(!EventKind::Cancel.is_terminal());
        assert_eq!(EventKind::Cancel.label(), "cancel");
        assert_eq!(EventKind::from_u8(5), EventKind::Cancel);
    }

    /// The Cancel names the call and nothing else: same identity as the request,
    /// no method, and its own emission time.
    #[test]
    fn cancel_header_reuses_the_request_identity_without_a_method() {
        let id = service_id_of("GetPerson");
        let request = RpcHeader::request(method_id_of("get_person"), id, 3)
            .with_trace(TraceContext::new_root());
        let cancel = RpcHeader::cancel_from(&request);

        assert_eq!(cancel.correlation_id, request.correlation_id);
        assert_eq!(cancel.service_id, id);
        assert_eq!(cancel.service_version, 3);
        assert_eq!(cancel.event_kind(), EventKind::Cancel);
        assert_eq!(cancel.method_id(), 0, "a Cancel names no method");
        assert_eq!(cancel.trace(), request.trace(), "the Cancel stays traced");
        // `seq` belongs to the emitter, exactly like a response's.
        assert_eq!(cancel.seq, 0);
        assert_eq!(cancel.with_seq(9).seq, 9);
        assert!(cancel.timestamp_ns >= request.timestamp_ns);
    }
}

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

    #[test]
    fn roundtrips_the_formatted_form() {
        let cid = next_correlation_id();
        let text = fmt_correlation_id(&cid);
        assert_eq!(text.len(), 36);
        assert_eq!(parse_correlation_id(&text), Some(cid));
    }

    #[test]
    fn accepts_the_undashed_form() {
        let cid = [
            0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x00, 0x11,
            0x22, 0x33,
        ];
        assert_eq!(
            parse_correlation_id("deadbeef0123456789abcdef00112233"),
            Some(cid)
        );
    }

    #[test]
    fn accepts_uppercase_hex() {
        let lower = parse_correlation_id("deadbeef-cafe-babe-0011-223344556677");
        let upper = parse_correlation_id("DEADBEEF-CAFE-BABE-0011-223344556677");
        assert!(lower.is_some());
        assert_eq!(lower, upper);
    }

    #[test]
    fn rejects_bad_lengths_digits_and_dash_positions() {
        assert!(parse_correlation_id("").is_none());
        assert!(parse_correlation_id("deadbeef").is_none());
        assert!(parse_correlation_id("deadbeef-cafe-babe-0011-22334455667").is_none());
        assert!(parse_correlation_id("gggggggg-gggg-gggg-gggg-gggggggggggg").is_none());
        // 36 bytes, but the dashes do not sit at 8/13/18/23.
        assert!(parse_correlation_id("deadbeef-cafe-bab-e0011-223344556677").is_none());
    }
}