easyfix-core 0.20.0

Easy FIX (Financial Information Exchange) toolset - core types.
Documentation
//! The [`SessionMessage`] trait and related types.
//!
//! The session layer is generic over `M: SessionMessage`, so it never names a
//! concrete message type. Implementations provide the bridge between session
//! logic and concrete message definitions.

use std::fmt::Debug;

use crate::{
    base_messages::{AdminBase, HeaderBase},
    basic_types::{ApplVerId, Boolean, FixStr, FixString, MsgTypeField, SeqNum, UtcTimestamp},
    deserializer::{DeserializeErrorKind, RawMessage, RawMessageError, raw_message},
    serializer::SerializeError,
    version::Version,
};

/// Deserialization failure returned by [`SessionMessage::from_raw_message`].
///
/// Aggregates the underlying [`DeserializeErrorKind`] with the header of the
/// failed message when it is recoverable. The session layer uses the header
/// to give header verdicts (sequence numbers first) precedence over the
/// body-level error.
#[derive(Debug, thiserror::Error)]
#[error("{kind}")]
pub struct DeserializeError {
    /// The underlying deserialization failure.
    #[source]
    pub kind: DeserializeErrorKind,
    /// Fully parsed header of the failed message. `Some` when header
    /// parsing succeeded and the failure happened in the body or trailer;
    /// `None` when the header itself failed to parse.
    pub header: Option<Box<HeaderBase<'static>>>,
}

impl From<DeserializeErrorKind> for DeserializeError {
    fn from(kind: DeserializeErrorKind) -> Self {
        DeserializeError { kind, header: None }
    }
}

impl From<RawMessageError> for DeserializeError {
    fn from(error: RawMessageError) -> Self {
        DeserializeErrorKind::from(error).into()
    }
}

/// Admin vs App message category.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MsgCat {
    /// Administrative message
    Admin,
    /// Application message
    App,
}

/// Core message trait that bridges session logic and concrete message types.
///
/// The session layer uses this trait to deserialize, inspect, construct, and
/// serialize messages without knowing the concrete type.
pub trait SessionMessage: Sized + Debug + HeaderAccess {
    /// Deserialize from a structurally validated `RawMessage`.
    ///
    /// On failure the [`DeserializeError`] carries the parsed header whenever
    /// header parsing succeeded before the failure.
    //
    // Boxed because concrete message types can be large (e.g. ExecutionReport).
    fn from_raw_message(raw: RawMessage<'_>) -> Result<Box<Self>, DeserializeError>;

    /// Deserialize from FIX tag-value wire bytes. Composes [`raw_message`]
    /// framing with [`Self::from_raw_message`].
    fn from_bytes(bytes: &[u8]) -> Result<Box<Self>, DeserializeError> {
        let (_, raw) = raw_message(bytes)?;
        Self::from_raw_message(raw)
    }

    /// Serialize to FIX tag-value wire format into the caller-provided buffer.
    /// Returns the number of bytes written.
    fn serialize(&self, buf: &mut [u8]) -> Result<usize, SerializeError>;

    /// Extract header fields as a borrowed base. Zero-copy.
    fn header(&self) -> HeaderBase<'_>;

    /// If this is an admin message, return the borrowed base. Zero-copy.
    fn try_as_admin(&self) -> Option<AdminBase<'_>>;

    /// Compact message type identifier (e.g. `"A"` for Logon, `"D"` for
    /// NewOrderSingle).
    ///
    /// Compare against [`MsgTypeBase`] variants for admin dispatch, or
    /// `TryFrom` into a richer generated type for exhaustive matching -
    /// fallible, since the field may hold a value that type does not define.
    ///
    /// [`MsgTypeBase`]: crate::base_messages::MsgTypeBase
    fn msg_type(&self) -> MsgTypeField;

    /// Whether this is an admin or application message.
    fn msg_cat(&self) -> MsgCat;

    /// Human-readable message name (e.g., `"Logon"`, `"NewOrderSingle"`).
    fn name(&self) -> &'static str;

    /// Build an outgoing admin message from owned base messages.
    fn from_admin(header: HeaderBase<'static>, admin: AdminBase<'static>) -> Self;
}

/// Get/set access to the header fields the session layer reads and fills in.
pub trait HeaderAccess {
    /// BeginString (tag 8) - FIX protocol version.
    ///
    /// Constant per message type; it never varies between instances.
    fn version(&self) -> Version;

    /// SenderCompID (tag 49) - identifier of the message sender.
    fn sender_comp_id(&self) -> &FixStr;

    /// TargetCompID (tag 56) - identifier of the message recipient.
    fn target_comp_id(&self) -> &FixStr;

    /// MsgSeqNum (tag 34) - message sequence number within the session.
    fn msg_seq_num(&self) -> SeqNum;

    /// SendingTime (tag 52) - time the message was sent (UTC).
    fn sending_time(&self) -> UtcTimestamp;

    /// PossDupFlag (tag 43) - `true` if this is a possible duplicate (resend).
    fn poss_dup_flag(&self) -> Option<Boolean>;

    /// OrigSendingTime (tag 122) - original sending time for resent messages.
    /// Returns `None` if the field is absent or the FIX version doesn't define it.
    fn orig_sending_time(&self) -> Option<UtcTimestamp>;

    /// ApplVerID (tag 1128) - application-level protocol version.
    /// Only relevant for FIXT (FIX 5.0+); return `None` for FIX 4.x.
    fn appl_ver_id(&self) -> Option<ApplVerId>;

    /// Set SenderCompID (tag 49).
    fn set_sender_comp_id(&mut self, value: FixString);

    /// Set TargetCompID (tag 56).
    fn set_target_comp_id(&mut self, value: FixString);

    /// Set MsgSeqNum (tag 34).
    fn set_msg_seq_num(&mut self, value: SeqNum);

    /// Set SendingTime (tag 52).
    fn set_sending_time(&mut self, value: UtcTimestamp);

    /// Set PossDupFlag (tag 43). Pass `None` to clear.
    fn set_poss_dup_flag(&mut self, value: Option<Boolean>);

    /// Set OrigSendingTime (tag 122). Pass `None` to clear.
    fn set_orig_sending_time(&mut self, value: Option<UtcTimestamp>);

    /// Set ApplVerID (tag 1128). Pass `None` to clear.
    /// No-op for FIX 4.x implementations.
    fn set_appl_ver_id(&mut self, value: Option<ApplVerId>);
}