krishvishal commented on code in PR #2946: URL: https://github.com/apache/iggy/pull/2946#discussion_r2945747324
########## core/binary_protocol/src/consensus/message.rs: ########## @@ -0,0 +1,331 @@ +// 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}; +use bytes::Bytes; +use std::marker::PhantomData; + +/// 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: 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). + #[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) Review Comment: So basically alignment failure is the error here that can happen spuriously at runtime right? If the alignment of underlying buffer is ensured (16 bytes) then we can use unsafe pointer cast. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
