iggy_binary_protocol 0.9.4-edge.1

Wire protocol types and codec for the Iggy binary protocol. Shared between server and SDK.
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Zero-copy consensus message wrapper.
//!
//! `Message<H>` wraps a `Bytes` buffer and provides typed access to the
//! header via `bytemuck` pointer cast (zero allocation, zero copy).

use crate::consensus::{
    Command2, ConsensusError, ConsensusHeader, GenericHeader, PrepareHeader, PrepareOkHeader,
    RequestHeader,
};
use bytes::Bytes;
use std::marker::PhantomData;

/// Trait for types that provide access to a consensus header.
pub trait ConsensusMessage<H: ConsensusHeader> {
    fn header(&self) -> &H;
}

impl<H: ConsensusHeader> ConsensusMessage<H> for Message<H> {
    fn header(&self) -> &H {
        let header_bytes = &self.buffer[..size_of::<H>()];
        bytemuck::checked::try_from_bytes(header_bytes)
            .expect("header validated at construction time")
    }
}

/// Zero-copy message wrapping a `Bytes` buffer with a typed header.
///
/// The header is accessed via `bytemuck::try_from_bytes` - a pointer cast,
/// not a deserialization step. The body is the slice after the header,
/// sized according to `header.size()`.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct Message<H: ConsensusHeader> {
    buffer: Bytes,
    _marker: PhantomData<H>,
}

impl<H: ConsensusHeader> Message<H> {
    /// Create a message from a buffer, validating the header.
    ///
    /// # Errors
    /// Returns `ConsensusError` if the buffer is too small or the header is invalid.
    pub fn from_bytes(buffer: Bytes) -> Result<Self, ConsensusError> {
        if buffer.len() < size_of::<H>() {
            return Err(ConsensusError::InvalidCommand {
                expected: H::COMMAND,
                found: Command2::Reserved,
            });
        }

        // TODO(hubcio): bytemuck::checked::try_from_bytes requires the buffer to be aligned
        // to the target type's alignment. Consensus headers contain u128 fields (16-byte
        // alignment), but Bytes from Vec<u8> only guarantees 8-byte alignment. The checked
        // variant returns Err on misalignment (no UB), but production code can fail on
        // misaligned buffers. The original iggy_common code has the same limitation.
        // Fix by either using pod_read_unaligned (copies header) or ensuring aligned
        // allocation at the network receive layer.
        let header_bytes = &buffer[..size_of::<H>()];
        let header = bytemuck::checked::try_from_bytes::<H>(header_bytes)
            .map_err(|_| ConsensusError::InvalidBitPattern)?;

        header.validate()?;

        let header_size = header.size() as usize;
        if buffer.len() < header_size {
            return Err(ConsensusError::InvalidCommand {
                expected: H::COMMAND,
                found: Command2::Reserved,
            });
        }

        Ok(Self {
            buffer,
            _marker: PhantomData,
        })
    }

    /// Create a zero-initialized message of the given size.
    /// The caller must initialize the header fields.
    ///
    /// # Panics
    /// Panics if `size` is smaller than the header size.
    #[must_use]
    pub fn new(size: usize) -> Self {
        assert!(
            size >= size_of::<H>(),
            "size must be at least header size ({})",
            size_of::<H>()
        );
        Self {
            buffer: Bytes::from(vec![0u8; size]),
            _marker: PhantomData,
        }
    }

    /// Access the typed header (zero-copy pointer cast).
    ///
    /// Re-validates the bit pattern on each call because headers contain
    /// `CheckedBitPattern` enums (`Command2`, `Operation`) which prevent
    /// using the unchecked `bytemuck::try_from_bytes` (requires `Pod`).
    /// The cost is a few enum discriminant range checks per access.
    /// The buffer is immutable (`Bytes`) so validation cannot fail after
    /// successful construction.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    #[inline]
    pub fn header(&self) -> &H {
        let header_bytes = &self.buffer[..size_of::<H>()];
        bytemuck::checked::try_from_bytes(header_bytes)
            .expect("header validated at construction time")
    }

    /// Message body (everything after the header).
    #[must_use]
    #[inline]
    pub fn body(&self) -> &[u8] {
        let header_size = size_of::<H>();
        let total_size = self.header().size() as usize;
        if total_size > header_size {
            &self.buffer[header_size..total_size]
        } else {
            &[]
        }
    }

    /// Message body as zero-copy [`Bytes`].
    #[must_use]
    #[inline]
    pub fn body_bytes(&self) -> Bytes {
        let header_size = size_of::<H>();
        let total_size = self.header().size() as usize;
        if total_size > header_size {
            self.buffer.slice(header_size..total_size)
        } else {
            Bytes::new()
        }
    }

    /// Complete message bytes (header + body).
    #[must_use]
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        let total_size = self.header().size() as usize;
        &self.buffer[..total_size]
    }

    /// Consume into the underlying buffer.
    #[must_use]
    #[inline]
    pub fn into_inner(self) -> Bytes {
        self.buffer
    }

    /// Convert to a generic message (type-erase the header).
    #[must_use]
    pub fn into_generic(self) -> Message<GenericHeader> {
        // SAFETY: Message<H> and Message<GenericHeader> have identical layout
        // (only PhantomData differs). GenericHeader accepts any command.
        unsafe { Message::from_buffer_unchecked(self.buffer) }
    }

    /// View as a generic message without consuming.
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn as_generic(&self) -> &Message<GenericHeader> {
        // SAFETY: #[repr(C)] guarantees field layout. Message<H> and
        // Message<GenericHeader> differ only in PhantomData (ZST).
        unsafe { &*std::ptr::from_ref(self).cast::<Message<GenericHeader>>() }
    }

    /// Try to reinterpret as a different header type.
    ///
    /// # Errors
    /// Returns `ConsensusError` if the header command doesn't match or validation fails.
    pub fn try_into_typed<T: ConsensusHeader>(self) -> Result<Message<T>, ConsensusError> {
        if self.buffer.len() < size_of::<T>() {
            return Err(ConsensusError::InvalidCommand {
                expected: T::COMMAND,
                found: Command2::Reserved,
            });
        }

        let generic = self.as_generic();
        if generic.header().command != T::COMMAND {
            return Err(ConsensusError::InvalidCommand {
                expected: T::COMMAND,
                found: generic.header().command,
            });
        }

        let header_bytes = &self.buffer[..size_of::<T>()];
        let header = bytemuck::checked::try_from_bytes::<T>(header_bytes)
            .map_err(|_| ConsensusError::InvalidBitPattern)?;
        header.validate()?;

        Ok(unsafe { Message::<T>::from_buffer_unchecked(self.buffer) })
    }

    /// Try to borrow as a different header type without consuming.
    ///
    /// # Errors
    /// Returns `ConsensusError` if the header command doesn't match or validation fails.
    pub fn try_as_typed<T: ConsensusHeader>(&self) -> Result<&Message<T>, ConsensusError> {
        if self.buffer.len() < size_of::<T>() {
            return Err(ConsensusError::InvalidCommand {
                expected: T::COMMAND,
                found: Command2::Reserved,
            });
        }

        let generic = self.as_generic();
        if generic.header().command != T::COMMAND {
            return Err(ConsensusError::InvalidCommand {
                expected: T::COMMAND,
                found: generic.header().command,
            });
        }

        let header_bytes = &self.buffer[..size_of::<T>()];
        bytemuck::checked::try_from_bytes::<T>(header_bytes)
            .map_err(|_| ConsensusError::InvalidBitPattern)?
            .validate()?;

        // SAFETY: Message<H> and Message<T> have identical layout (#[repr(C)],
        // differ only in PhantomData). Header validated above.
        Ok(unsafe { &*std::ptr::from_ref(self).cast::<Message<T>>() })
    }

    /// Transmute the header to a different type, preserving the buffer.
    ///
    /// The callback receives the old header (by value) and a mutable reference
    /// to the new (zeroed) header, allowing field-by-field initialization.
    ///
    /// # Panics
    /// Panics if `size_of::<H>() != size_of::<T>()`.
    #[must_use]
    pub fn transmute_header<T: ConsensusHeader>(self, f: impl FnOnce(H, &mut T)) -> Message<T> {
        assert_eq!(size_of::<H>(), size_of::<T>());
        let old_header = *self.header();
        let buffer = self.into_inner();
        // TODO: This mutates through Bytes via cast_mut(), which violates aliasing rules.
        // The original iggy_common code has the same pattern. Once iggy_common is migrated
        // to use iggy_binary_protocol types, fix both by using Bytes::try_into_mut() ->
        // mutate BytesMut -> freeze(). Tracked as part of the consensus migration.
        unsafe {
            let ptr = buffer.as_ptr().cast_mut();
            let slice = std::slice::from_raw_parts_mut(ptr, size_of::<T>());
            slice.fill(0);
            let new_header =
                bytemuck::checked::try_from_bytes_mut(slice).expect("zeroed bytes are valid");
            f(old_header, new_header);
        }
        Message {
            buffer,
            _marker: PhantomData,
        }
    }

    /// Create without validation. Private.
    ///
    /// # Safety
    /// Buffer must already be validated for the target header type.
    #[inline]
    const unsafe fn from_buffer_unchecked(buffer: Bytes) -> Self {
        Self {
            buffer,
            _marker: PhantomData,
        }
    }
}

/// Type-erased message bag for dispatching incoming consensus messages.
#[derive(Debug)]
pub enum MessageBag {
    Request(Message<RequestHeader>),
    Prepare(Message<PrepareHeader>),
    PrepareOk(Message<PrepareOkHeader>),
}

impl MessageBag {
    #[must_use]
    pub fn command(&self) -> Command2 {
        match self {
            Self::Request(m) => m.header().command,
            Self::Prepare(m) => m.header().command,
            Self::PrepareOk(m) => m.header().command,
        }
    }

    #[must_use]
    pub fn size(&self) -> u32 {
        match self {
            Self::Request(m) => m.header().size(),
            Self::Prepare(m) => m.header().size(),
            Self::PrepareOk(m) => m.header().size(),
        }
    }

    #[must_use]
    pub fn operation(&self) -> crate::consensus::Operation {
        match self {
            Self::Request(m) => m.header().operation,
            Self::Prepare(m) => m.header().operation,
            Self::PrepareOk(m) => m.header().operation,
        }
    }
}

impl<T: ConsensusHeader> TryFrom<Message<T>> for MessageBag {
    type Error = ConsensusError;

    fn try_from(value: Message<T>) -> Result<Self, Self::Error> {
        let command = value.as_generic().header().command;
        let buffer = value.into_inner();

        match command {
            Command2::Request => {
                let msg = unsafe { Message::<RequestHeader>::from_buffer_unchecked(buffer) };
                Ok(Self::Request(msg))
            }
            Command2::Prepare => {
                let msg = unsafe { Message::<PrepareHeader>::from_buffer_unchecked(buffer) };
                Ok(Self::Prepare(msg))
            }
            Command2::PrepareOk => {
                let msg = unsafe { Message::<PrepareOkHeader>::from_buffer_unchecked(buffer) };
                Ok(Self::PrepareOk(msg))
            }
            other => Err(ConsensusError::InvalidCommand {
                expected: Command2::Reserved,
                found: other,
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Message;
    use crate::consensus::{Command2, GenericHeader, RequestHeader};
    use bytes::{Bytes, BytesMut};

    #[test]
    fn generic_message_from_zeroed_buffer() {
        let mut buf = BytesMut::zeroed(384);
        let header =
            bytemuck::checked::try_from_bytes_mut::<GenericHeader>(&mut buf[..256]).unwrap();
        header.size = 384;
        header.cluster = 42;

        let msg = Message::<GenericHeader>::from_bytes(buf.freeze()).unwrap();
        assert_eq!(msg.header().cluster, 42);
        assert_eq!(msg.header().size, 384);
        assert_eq!(msg.body().len(), 128);
    }

    #[test]
    fn request_message_roundtrip() {
        let mut buf = BytesMut::zeroed(320);
        let header =
            bytemuck::checked::try_from_bytes_mut::<RequestHeader>(&mut buf[..256]).unwrap();
        header.size = 320;
        header.command = Command2::Request;
        header.client = 12345;
        header.operation = crate::consensus::Operation::CreateStream;

        let msg = Message::<RequestHeader>::from_bytes(buf.freeze()).unwrap();
        assert_eq!(msg.header().client, 12345);
        assert_eq!(
            msg.header().operation,
            crate::consensus::Operation::CreateStream
        );
        assert_eq!(msg.body().len(), 64);
    }

    #[test]
    fn too_small_buffer_rejected() {
        let buf = Bytes::from(vec![0u8; 100]); // < 256
        assert!(Message::<GenericHeader>::from_bytes(buf).is_err());
    }

    #[test]
    fn into_generic_and_back() {
        let mut buf = BytesMut::zeroed(256);
        let header =
            bytemuck::checked::try_from_bytes_mut::<RequestHeader>(&mut buf[..256]).unwrap();
        header.size = 256;
        header.command = Command2::Request;

        let msg = Message::<RequestHeader>::from_bytes(buf.freeze()).unwrap();
        let generic = msg.into_generic();
        assert_eq!(generic.header().command, Command2::Request);

        let back = generic.try_into_typed::<RequestHeader>().unwrap();
        assert_eq!(back.header().command, Command2::Request);
    }

    #[test]
    fn transmute_header_generic_to_request() {
        let mut buf = BytesMut::zeroed(320);
        let header =
            bytemuck::checked::try_from_bytes_mut::<GenericHeader>(&mut buf[..256]).unwrap();
        header.size = 320;
        header.cluster = 99;

        let generic = Message::<GenericHeader>::from_bytes(buf.freeze()).unwrap();
        let request = generic.transmute_header(|old, new: &mut RequestHeader| {
            new.size = old.size;
            new.command = Command2::Request;
            new.cluster = old.cluster;
            new.client = 42;
            new.operation = crate::consensus::Operation::CreateStream;
        });
        assert_eq!(request.header().command, Command2::Request);
        assert_eq!(request.header().client, 42);
        assert_eq!(request.header().cluster, 99);
        assert_eq!(request.header().size, 320);
        assert_eq!(request.body().len(), 64);
    }

    #[test]
    fn wrong_type_conversion_fails() {
        let mut buf = BytesMut::zeroed(256);
        let header =
            bytemuck::checked::try_from_bytes_mut::<GenericHeader>(&mut buf[..256]).unwrap();
        header.size = 256;
        header.command = Command2::Reserved; // not Request

        let msg = Message::<GenericHeader>::from_bytes(buf.freeze()).unwrap();
        assert!(msg.try_into_typed::<RequestHeader>().is_err());
    }
}