hibana 0.8.0

Const-projected Affine Multiparty Session Types for choreography-first Rust protocols
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
//! Transport codec helpers.
//!
//! `WireEncode` is the send-side contract. `WirePayload` is the receive-side
//! contract. `Payload` is the borrowed byte view passed from transport into a
//! decoder.
//!
//! Decoding is exact for built-in fixed-size payloads: trailing bytes are
//! rejected. Borrowed payload types may return views tied to the endpoint borrow.
//! Protocol-specific transports map descriptor decisions onto their native frame
//! formats; Hibana metadata is not placed on the application wire by this layer.

use core::{fmt, ops};

const ERR_PAYLOAD_LEN: &str = "payload length";
const ERR_SYNTHETIC_PAYLOAD: &str = "synthetic payload";
const ERR_BOOLEAN_PAYLOAD: &str = "boolean payload";

/// Errors surfaced by wire encode/decode helpers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodecError {
    Truncated,
    Invalid(&'static str),
}

#[inline]
pub(crate) fn require_exact_len(
    actual: usize,
    expected: usize,
    context: &'static str,
) -> Result<(), CodecError> {
    if actual < expected {
        Err(CodecError::Truncated)
    } else if actual == expected {
        Ok(())
    } else {
        Err(CodecError::Invalid(context))
    }
}

/// Send-side payload encoding contract.
pub trait WireEncode {
    /// Optional hint describing the encoded length if it is statically known.
    fn encoded_len(&self) -> Option<usize>;

    /// Encode into `out`, returning the number of bytes written.
    fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError>;
}

pub(crate) type ErasedEncoder = unsafe fn(*const (), &mut [u8]) -> Result<usize, CodecError>;

#[inline(always)]
pub(crate) const fn erased_encoder<P: WireEncode>() -> ErasedEncoder {
    encode_erased::<P>
}

#[inline(always)]
unsafe fn encode_erased<P: WireEncode>(
    ptr: *const (),
    scratch: &mut [u8],
) -> Result<usize, CodecError> {
    // SAFETY: callers pair an erased pointer produced from `&P` with this
    // exact encoder. The future or kernel owner keeps the source borrow live.
    let payload = unsafe { &*ptr.cast::<P>() };
    payload.encode_into(scratch)
}

/// Receive-side payload decoding contract.
///
/// `Payload` remains the send-side owner that `flow().send()` accepts by
/// reference. `Decoded<'a>` describes what `recv()` / `decode()` yield when the
/// wire bytes are borrowed for the duration of the endpoint borrow.
pub trait WirePayload: WireEncode {
    /// Static fact used by the descriptor kernel when a transport returns an
    /// empty payload without binding evidence.
    const ACCEPTS_EMPTY_PAYLOAD: bool = false;

    type Decoded<'a>;

    /// Validate payload-local bytes before endpoint progress can commit.
    ///
    /// Checks that require choreography descriptor context, endpoint role,
    /// session/lane identity, or control epoch are owned by the endpoint
    /// kernel. Those contextual checks run after payload-local validation and
    /// before receive/decode progress commits.
    fn validate_payload(input: Payload<'_>) -> Result<(), CodecError>;

    /// Decode bytes already accepted by payload-local validation and any
    /// endpoint-context validation owned by the calling kernel path.
    ///
    /// Endpoint receive/decode progress is committed before this adapter runs,
    /// so this operation has no error channel.
    fn decode_validated_payload<'a>(input: Payload<'a>) -> Self::Decoded<'a>;

    /// Validate and decode bytes for non-endpoint callers.
    #[inline]
    fn decode_payload<'a>(input: Payload<'a>) -> Result<Self::Decoded<'a>, CodecError> {
        Self::validate_payload(input)?;
        Ok(Self::decode_validated_payload(input))
    }

    /// Provide the canonical zero payload used for non-wire local route
    /// materialization. Types that cannot represent such a payload keep the
    /// default fail-closed implementation.
    fn synthetic_payload<'a>(_scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
        Err(CodecError::Invalid(ERR_SYNTHETIC_PAYLOAD))
    }
}

impl WireEncode for () {
    fn encoded_len(&self) -> Option<usize> {
        Some(0)
    }

    fn encode_into(&self, _out: &mut [u8]) -> Result<usize, CodecError> {
        Ok(0)
    }
}

impl WirePayload for () {
    const ACCEPTS_EMPTY_PAYLOAD: bool = true;

    type Decoded<'a> = Self;

    fn validate_payload(input: Payload<'_>) -> Result<(), CodecError> {
        require_exact_len(input.as_bytes().len(), 0, ERR_PAYLOAD_LEN)
    }

    fn decode_validated_payload<'a>(_input: Payload<'a>) -> Self::Decoded<'a> {
        ()
    }

    fn synthetic_payload<'a>(_scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
        Ok(Payload::new(&[]))
    }
}

impl WireEncode for bool {
    fn encoded_len(&self) -> Option<usize> {
        Some(1)
    }

    fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError> {
        if out.is_empty() {
            return Err(CodecError::Truncated);
        }
        out[0] = if *self { 1 } else { 0 };
        Ok(1)
    }
}

impl WirePayload for bool {
    type Decoded<'a> = Self;

    fn validate_payload(input: Payload<'_>) -> Result<(), CodecError> {
        let bytes = input.as_bytes();
        require_exact_len(bytes.len(), 1, ERR_PAYLOAD_LEN)?;
        match bytes[0] {
            0 | 1 => Ok(()),
            _ => Err(CodecError::Invalid(ERR_BOOLEAN_PAYLOAD)),
        }
    }

    fn decode_validated_payload<'a>(input: Payload<'a>) -> Self::Decoded<'a> {
        input.as_bytes()[0] != 0
    }

    fn synthetic_payload<'a>(scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
        if scratch.is_empty() {
            return Err(CodecError::Truncated);
        }
        scratch[0] = 0;
        Ok(Payload::new(&scratch[..1]))
    }
}

macro_rules! impl_wire_for_int {
    ($ty:ty, $len:expr) => {
        impl WireEncode for $ty {
            fn encoded_len(&self) -> Option<usize> {
                Some($len)
            }

            fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError> {
                if out.len() < $len {
                    return Err(CodecError::Truncated);
                }
                out[..$len].copy_from_slice(&self.to_be_bytes());
                Ok($len)
            }
        }

        impl WirePayload for $ty {
            type Decoded<'a> = Self;

            fn validate_payload(input: Payload<'_>) -> Result<(), CodecError> {
                require_exact_len(input.as_bytes().len(), $len, ERR_PAYLOAD_LEN)
            }

            fn decode_validated_payload<'a>(input: Payload<'a>) -> Self::Decoded<'a> {
                let bytes = input.as_bytes();
                let mut buf = [0u8; $len];
                buf.copy_from_slice(&bytes[..$len]);
                <$ty>::from_be_bytes(buf)
            }

            fn synthetic_payload<'a>(scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
                if scratch.len() < $len {
                    return Err(CodecError::Truncated);
                }
                scratch[..$len].fill(0);
                Ok(Payload::new(&scratch[..$len]))
            }
        }
    };
}

impl_wire_for_int!(u8, 1);
impl_wire_for_int!(i8, 1);
impl_wire_for_int!(u16, 2);
impl_wire_for_int!(i16, 2);
impl_wire_for_int!(u32, 4);
impl_wire_for_int!(i32, 4);
impl_wire_for_int!(u64, 8);
impl_wire_for_int!(i64, 8);
impl_wire_for_int!(u128, 16);
impl_wire_for_int!(i128, 16);

impl WireEncode for &[u8] {
    fn encoded_len(&self) -> Option<usize> {
        Some(self.len())
    }

    fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError> {
        if out.len() < self.len() {
            return Err(CodecError::Truncated);
        }
        out[..self.len()].copy_from_slice(self);
        Ok(self.len())
    }
}

impl WirePayload for &[u8] {
    const ACCEPTS_EMPTY_PAYLOAD: bool = true;

    type Decoded<'a> = &'a [u8];

    fn validate_payload(_input: Payload<'_>) -> Result<(), CodecError> {
        Ok(())
    }

    fn decode_validated_payload<'a>(input: Payload<'a>) -> Self::Decoded<'a> {
        input.as_bytes()
    }

    fn synthetic_payload<'a>(_scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
        Ok(Payload::new(&[]))
    }
}

impl<const N: usize> WireEncode for [u8; N] {
    fn encoded_len(&self) -> Option<usize> {
        Some(N)
    }

    fn encode_into(&self, out: &mut [u8]) -> Result<usize, CodecError> {
        if out.len() < N {
            return Err(CodecError::Truncated);
        }
        out[..N].copy_from_slice(self);
        Ok(N)
    }
}

impl<const N: usize> WirePayload for [u8; N] {
    const ACCEPTS_EMPTY_PAYLOAD: bool = N == 0;

    type Decoded<'a> = Self;

    fn validate_payload(input: Payload<'_>) -> Result<(), CodecError> {
        require_exact_len(input.as_bytes().len(), N, ERR_PAYLOAD_LEN)
    }

    fn decode_validated_payload<'a>(input: Payload<'a>) -> Self::Decoded<'a> {
        let bytes = input.as_bytes();
        let mut buf = [0u8; N];
        buf.copy_from_slice(&bytes[..N]);
        buf
    }

    fn synthetic_payload<'a>(scratch: &'a mut [u8]) -> Result<Payload<'a>, CodecError> {
        if scratch.len() < N {
            return Err(CodecError::Truncated);
        }
        scratch[..N].fill(0);
        Ok(Payload::new(&scratch[..N]))
    }
}

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

    #[test]
    fn fixed_payload_decoders_reject_trailing_bytes() {
        assert_eq!(
            <() as WirePayload>::decode_payload(Payload::new(&[])),
            Ok(())
        );
        assert_eq!(
            <() as WirePayload>::decode_payload(Payload::new(&[1])),
            Err(CodecError::Invalid(ERR_PAYLOAD_LEN))
        );

        assert_eq!(
            <bool as WirePayload>::decode_payload(Payload::new(&[1])),
            Ok(true)
        );
        assert_eq!(
            <bool as WirePayload>::decode_payload(Payload::new(&[1, 0])),
            Err(CodecError::Invalid(ERR_PAYLOAD_LEN))
        );

        assert_eq!(
            <u16 as WirePayload>::decode_payload(Payload::new(&[0x12, 0x34])),
            Ok(0x1234)
        );
        assert_eq!(
            <u16 as WirePayload>::decode_payload(Payload::new(&[0x12, 0x34, 0x56])),
            Err(CodecError::Invalid(ERR_PAYLOAD_LEN))
        );

        assert_eq!(
            <[u8; 2] as WirePayload>::decode_payload(Payload::new(&[7, 9])),
            Ok([7, 9])
        );
        assert_eq!(
            <[u8; 2] as WirePayload>::decode_payload(Payload::new(&[7, 9, 11])),
            Err(CodecError::Invalid(ERR_PAYLOAD_LEN))
        );
    }

    #[test]
    fn borrowed_byte_slice_remains_variable_length() {
        let bytes = [1, 2, 3];
        assert_eq!(
            <&[u8] as WirePayload>::decode_payload(Payload::new(&bytes)),
            Ok(&bytes[..])
        );
    }

    #[test]
    fn synthetic_payloads_are_canonical_for_builtin_fixed_types() {
        let mut scratch = [0xFF; 8];

        assert_eq!(
            <() as WirePayload>::synthetic_payload(&mut scratch)
                .expect("unit synthetic payload")
                .as_bytes(),
            &[] as &[u8]
        );
        assert_eq!(
            <u32 as WirePayload>::synthetic_payload(&mut scratch)
                .expect("u32 synthetic payload")
                .as_bytes(),
            &[0, 0, 0, 0]
        );
        assert_eq!(
            <[u8; 3] as WirePayload>::synthetic_payload(&mut scratch)
                .expect("array synthetic payload")
                .as_bytes(),
            &[0, 0, 0]
        );
        assert_eq!(
            <bool as WirePayload>::synthetic_payload(&mut scratch)
                .expect("bool synthetic payload")
                .as_bytes(),
            &[0]
        );
    }
}

/// Wire-level flags for frames (no external crates).
///
/// Only transport fragmentation metadata remains here; control-plane signalling
/// stays on typed control messages so that the data plane observes a uniform
/// message model.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Default)]
#[repr(transparent)]
pub(crate) struct FrameFlags(u8);

impl FrameFlags {
    /// Mask of supported bits. Unknown bits are dropped when decoding.
    pub(crate) const ALLOWED: u8 = 0x10 /*FRAG*/ | 0x20 /*IDX*/ | 0x40 /*TOT*/;

    pub(crate) const EMPTY: Self = Self(0x00);
    pub(crate) const FRAG: Self = Self(0x10);
    pub(crate) const IDX: Self = Self(0x20);
    pub(crate) const TOT: Self = Self(0x40);

    #[inline]
    pub(crate) const fn empty() -> Self {
        Self::EMPTY
    }

    #[inline]
    pub(crate) const fn bits(self) -> u8 {
        self.0
    }

    /// True if *all* bits in `other` are set in `self`.
    #[inline]
    pub(crate) const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

// ---- bit-ops (mask within ALLOWED) ----
impl ops::BitOr for FrameFlags {
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self::Output {
        Self((self.0 | rhs.0) & Self::ALLOWED)
    }
}

impl ops::BitOrAssign for FrameFlags {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 = (self.0 | rhs.0) & Self::ALLOWED;
    }
}

impl ops::BitAnd for FrameFlags {
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0)
    }
}

impl ops::BitAndAssign for FrameFlags {
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0;
    }
}

impl ops::BitXor for FrameFlags {
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: Self) -> Self::Output {
        Self((self.0 ^ rhs.0) & Self::ALLOWED)
    }
}

impl ops::BitXorAssign for FrameFlags {
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        self.0 = (self.0 ^ rhs.0) & Self::ALLOWED;
    }
}

impl ops::Not for FrameFlags {
    type Output = Self;

    #[inline]
    fn not(self) -> Self::Output {
        Self(Self::ALLOWED & !self.0)
    }
}

impl fmt::Debug for FrameFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        write!(f, "FrameFlags{{")?;
        macro_rules! push {
            ($flag:ident) => {
                if self.contains(FrameFlags::$flag) {
                    if !first {
                        write!(f, "|")?;
                    }
                    first = false;
                    write!(f, stringify!($flag))?;
                }
            };
        }
        push!(FRAG);
        push!(IDX);
        push!(TOT);
        if first {
            write!(f, "EMPTY")?;
        }
        write!(f, "}}")
    }
}

/// Zero-copy view over an encoded payload slice (application data remains
/// opaque to Hibana; transports simply forward the bytes handed to them).
#[derive(Clone, Copy)]
pub struct Payload<'a> {
    data: &'a [u8],
}
impl<'a> Payload<'a> {
    #[inline]
    pub const fn new(data: &'a [u8]) -> Self {
        Self { data }
    }

    #[inline]
    pub fn as_bytes(&self) -> &'a [u8] {
        self.data
    }
}

impl<'a> fmt::Debug for Payload<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = self.as_bytes();
        let preview_len = bytes.len().min(32);
        f.debug_struct("Payload")
            .field("len", &bytes.len())
            .field("preview", &&bytes[..preview_len])
            .finish()
    }
}