easyfix-core 0.20.0

Easy FIX (Financial Information Exchange) toolset - core types.
Documentation
//! Base messages and base enumerations - the contract between the session
//! layer and [`SessionMessage`] implementations.
//!
//! Types in this module are used by code that implements [`SessionMessage`]
//! (typically the code generator, but also custom implementations). The session
//! layer produces and consumes these types without knowing the concrete message
//! representation.
//!
//! - **Base messages** (`HeaderBase`, `AdminBase`, `LogonBase`, etc.) - minimal
//!   typed structures with only the fields the session needs. String fields use
//!   `Cow` for zero-copy borrowing on incoming and owned construction on outgoing.
//!
//! - **Base enums** (`MsgTypeBase`, `SessionStatusBase`, `SessionRejectReasonBase`,
//!   `EncryptMethodBase`) - typed constants for session-relevant FIX enumeration
//!   values. [`SessionMessage`] implementations convert between these and the
//!   concrete generated enums via `From` impls.
//!
//! [`SessionMessage`]: crate::message::SessionMessage

use std::{borrow::Cow, mem::variant_count};

use crate::basic_types::{
    ApplVerId, Boolean, FixStr, Int, Length, MsgTypeField, MsgTypeValue, SeqNum,
    SessionRejectReasonField, SessionRejectReasonValue, SessionStatusField, SessionStatusValue,
    UtcTimestamp,
};

// ---------------------------------------------------------------------------
// MsgTypeBase (tag 35)
// ---------------------------------------------------------------------------

/// MsgType (tag 35) base enum - typed constants for session-relevant
/// admin message types.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MsgTypeBase {
    Heartbeat,     // "0"
    TestRequest,   // "1"
    ResendRequest, // "2"
    Reject,        // "3"
    SequenceReset, // "4"
    Logout,        // "5"
    Logon,         // "A"
}

impl MsgTypeBase {
    /// All variants. The code generator validates that a generated `MsgType`
    /// enum covers every variant listed here.
    pub const ALL: &'static [MsgTypeBase] = &[
        MsgTypeBase::Heartbeat,
        MsgTypeBase::TestRequest,
        MsgTypeBase::ResendRequest,
        MsgTypeBase::Reject,
        MsgTypeBase::SequenceReset,
        MsgTypeBase::Logout,
        MsgTypeBase::Logon,
    ];

    /// The compact MsgType field value for this administrative message type.
    pub const fn raw_value(&self) -> MsgTypeField {
        match self {
            MsgTypeBase::Heartbeat => MsgTypeField::from_raw([b'0', 0]),
            MsgTypeBase::TestRequest => MsgTypeField::from_raw([b'1', 0]),
            MsgTypeBase::ResendRequest => MsgTypeField::from_raw([b'2', 0]),
            MsgTypeBase::Reject => MsgTypeField::from_raw([b'3', 0]),
            MsgTypeBase::SequenceReset => MsgTypeField::from_raw([b'4', 0]),
            MsgTypeBase::Logout => MsgTypeField::from_raw([b'5', 0]),
            MsgTypeBase::Logon => MsgTypeField::from_raw([b'A', 0]),
        }
    }
}

const _: () = assert!(
    MsgTypeBase::ALL.len() == variant_count::<MsgTypeBase>(),
    "MsgTypeBase::ALL is missing a variant"
);

impl MsgTypeValue for MsgTypeBase {
    fn raw_value(&self) -> MsgTypeField {
        MsgTypeBase::raw_value(self)
    }
}

impl PartialEq<MsgTypeBase> for MsgTypeField {
    fn eq(&self, other: &MsgTypeBase) -> bool {
        *self == other.raw_value()
    }
}

impl PartialEq<MsgTypeField> for MsgTypeBase {
    fn eq(&self, other: &MsgTypeField) -> bool {
        self.raw_value() == *other
    }
}

// ---------------------------------------------------------------------------
// SessionStatus (tag 1409)
// ---------------------------------------------------------------------------

/// SessionStatus (tag 1409), carried on FIXT Logon and Logout.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionStatusBase {
    SessionActive = 0,
    SessionLogoutComplete = 4,
    ReceivedMsgSeqNumTooLow = 9,
    ReceivedNextExpectedMsgSeqNumTooHigh = 10,
}

impl SessionStatusBase {
    /// All variants. The code generator validates that a generated
    /// `SessionStatus` enum covers every variant listed here.
    pub const ALL: &'static [SessionStatusBase] = &[
        SessionStatusBase::SessionActive,
        SessionStatusBase::SessionLogoutComplete,
        SessionStatusBase::ReceivedMsgSeqNumTooLow,
        SessionStatusBase::ReceivedNextExpectedMsgSeqNumTooHigh,
    ];
}

const _: () = assert!(
    SessionStatusBase::ALL.len() == variant_count::<SessionStatusBase>(),
    "SessionStatusBase::ALL is missing a variant"
);

impl SessionStatusValue for SessionStatusBase {
    fn raw_value(&self) -> Int {
        *self as Int
    }
}

// ---------------------------------------------------------------------------
// SessionRejectReason (tag 373)
// ---------------------------------------------------------------------------

// FIX Session Layer (June 2020), Section 11.11, lists InvalidTagNumber (0)
// and UndefinedTag (3) without explaining their distinction. FIX Session
// Layer Test Cases (June 2020), Section 4.5.13, Scenario 14(a), requires
// reason 0 for a tag not defined in the applicable specification unless
// agreed as user-defined, even when the number is syntactically valid.
// Scenario 14 assigns no separate validation case to code 3. Follow the
// explicit test case rather than infer behavior from the variant names.
// Neither document identifies code 3 as deprecated or replaced by code 0.
// https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX_Session_Layer_June_2020.pdf
// https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX_Session_Testcases_June_2020.pdf
/// SessionRejectReason (tag 373), carried on Reject.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionRejectReasonBase {
    InvalidTagNumber = 0,
    RequiredTagMissing = 1,
    TagNotDefinedForThisMessageType = 2,
    UndefinedTag = 3,
    TagSpecifiedWithoutAValue = 4,
    ValueIsIncorrect = 5,
    IncorrectDataFormatForValue = 6,
    CompIdProblem = 9,
    SendingTimeAccuracyProblem = 10,
    InvalidMsgType = 11,
    TagAppearsMoreThanOnce = 13,
    TagSpecifiedOutOfRequiredOrder = 14,
    RepeatingGroupFieldsOutOfOrder = 15,
    IncorrectNumInGroupCountForRepeatingGroup = 16,
}

impl SessionRejectReasonBase {
    /// All variants. The code generator validates that a generated
    /// `SessionRejectReason` enum covers every variant listed here.
    pub const ALL: &'static [SessionRejectReasonBase] = &[
        SessionRejectReasonBase::InvalidTagNumber,
        SessionRejectReasonBase::RequiredTagMissing,
        SessionRejectReasonBase::TagNotDefinedForThisMessageType,
        SessionRejectReasonBase::UndefinedTag,
        SessionRejectReasonBase::TagSpecifiedWithoutAValue,
        SessionRejectReasonBase::ValueIsIncorrect,
        SessionRejectReasonBase::IncorrectDataFormatForValue,
        SessionRejectReasonBase::CompIdProblem,
        SessionRejectReasonBase::SendingTimeAccuracyProblem,
        SessionRejectReasonBase::InvalidMsgType,
        SessionRejectReasonBase::TagAppearsMoreThanOnce,
        SessionRejectReasonBase::TagSpecifiedOutOfRequiredOrder,
        SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
        SessionRejectReasonBase::IncorrectNumInGroupCountForRepeatingGroup,
    ];
}

const _: () = assert!(
    SessionRejectReasonBase::ALL.len() == variant_count::<SessionRejectReasonBase>(),
    "SessionRejectReasonBase::ALL is missing a variant"
);

impl SessionRejectReasonValue for SessionRejectReasonBase {
    fn raw_value(&self) -> Int {
        *self as Int
    }

    fn description(&self) -> &'static str {
        match self {
            Self::InvalidTagNumber => stringify!(InvalidTagNumber),
            Self::RequiredTagMissing => stringify!(RequiredTagMissing),
            Self::TagNotDefinedForThisMessageType => stringify!(TagNotDefinedForThisMessageType),
            Self::UndefinedTag => stringify!(UndefinedTag),
            Self::TagSpecifiedWithoutAValue => stringify!(TagSpecifiedWithoutAValue),
            Self::ValueIsIncorrect => stringify!(ValueIsIncorrect),
            Self::IncorrectDataFormatForValue => stringify!(IncorrectDataFormatForValue),
            Self::CompIdProblem => stringify!(CompIdProblem),
            Self::SendingTimeAccuracyProblem => stringify!(SendingTimeAccuracyProblem),
            Self::InvalidMsgType => stringify!(InvalidMsgType),
            Self::TagAppearsMoreThanOnce => stringify!(TagAppearsMoreThanOnce),
            Self::TagSpecifiedOutOfRequiredOrder => stringify!(TagSpecifiedOutOfRequiredOrder),
            Self::RepeatingGroupFieldsOutOfOrder => stringify!(RepeatingGroupFieldsOutOfOrder),
            Self::IncorrectNumInGroupCountForRepeatingGroup => {
                stringify!(IncorrectNumInGroupCountForRepeatingGroup)
            }
        }
    }
}

impl PartialEq<SessionRejectReasonBase> for SessionRejectReasonField {
    fn eq(&self, other: &SessionRejectReasonBase) -> bool {
        self.into_inner() == other.raw_value()
    }
}

// ---------------------------------------------------------------------------
// EncryptMethod (tag 98)
// ---------------------------------------------------------------------------

/// EncryptMethod (tag 98). Only `None` (wire value `0`) is modelled here.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum EncryptMethodBase {
    #[default]
    None = 0,
}

impl EncryptMethodBase {
    /// All variants. The code generator validates that a generated
    /// `EncryptMethod` enum covers every variant listed here.
    pub const ALL: &'static [EncryptMethodBase] = &[EncryptMethodBase::None];
}

const _: () = assert!(
    EncryptMethodBase::ALL.len() == variant_count::<EncryptMethodBase>(),
    "EncryptMethodBase::ALL is missing a variant"
);

/// Base header containing only the fields the session layer reads/writes.
///
/// - **Incoming**: returned by `SessionMessage::header` with `Cow::Borrowed` - zero allocations.
/// - **Outgoing**: built by session with `Cow::Owned`, consumed via `From` conversion.
#[derive(Clone, Debug, Default)]
pub struct HeaderBase<'a> {
    pub sender_comp_id: Cow<'a, FixStr>,
    pub target_comp_id: Cow<'a, FixStr>,
    pub msg_seq_num: SeqNum,
    pub sending_time: UtcTimestamp,
    pub poss_dup_flag: Option<Boolean>,
    pub orig_sending_time: Option<UtcTimestamp>,
    /// FIXT only. `None` for pre-FIXT versions.
    pub appl_ver_id: Option<ApplVerId>,
}

impl HeaderBase<'_> {
    /// Detach the header from the message bytes it borrows, converting
    /// the `Cow` fields to owned values. Allocates only for borrowed
    /// CompIDs; every other field is `Copy`.
    pub fn into_owned(self) -> HeaderBase<'static> {
        HeaderBase {
            sender_comp_id: Cow::Owned(self.sender_comp_id.into_owned()),
            target_comp_id: Cow::Owned(self.target_comp_id.into_owned()),
            msg_seq_num: self.msg_seq_num,
            sending_time: self.sending_time,
            poss_dup_flag: self.poss_dup_flag,
            orig_sending_time: self.orig_sending_time,
            appl_ver_id: self.appl_ver_id,
        }
    }
}

/// Admin message base, obtained from `SessionMessage::try_as_admin`.
#[derive(Clone, Debug)]
pub enum AdminBase<'a> {
    Logon(LogonBase),
    Logout(LogoutBase<'a>),
    Heartbeat(HeartbeatBase<'a>),
    TestRequest(TestRequestBase<'a>),
    ResendRequest(ResendRequestBase),
    SequenceReset(SequenceResetBase),
    Reject(RejectBase<'a>),
}

#[derive(Clone, Debug)]
pub struct LogonBase {
    /// Typed value for outgoing.
    pub encrypt_method: EncryptMethodBase,
    /// Raw value for incoming comparison/logging.
    pub encrypt_method_raw: Int,
    pub heart_bt_int: Int,
    pub reset_seq_num_flag: Option<Boolean>,
    /// Maximum number of octets the sender supports for messages it
    /// receives (FIX Session Layer ยง4.3.6). `None` for FIX < 4.2, and
    /// whenever the peer did not advertise a limit.
    ///
    /// Never `Some(0)` on the incoming path - a zero-valued Length field
    /// is rejected while parsing.
    pub max_message_size: Option<Length>,
    /// `None` for FIX < 4.4.
    pub next_expected_msg_seq_num: Option<SeqNum>,
    /// `None` for pre-FIXT.
    pub default_appl_ver_id: Option<ApplVerId>,
    /// FIXT only.
    pub session_status: Option<SessionStatusField>,
}

#[derive(Clone, Debug)]
pub struct LogoutBase<'a> {
    /// FIXT only.
    pub session_status: Option<SessionStatusField>,
    pub text: Option<Cow<'a, FixStr>>,
}

#[derive(Clone, Debug)]
pub struct HeartbeatBase<'a> {
    pub test_req_id: Option<Cow<'a, FixStr>>,
}

#[derive(Clone, Debug)]
pub struct TestRequestBase<'a> {
    pub test_req_id: Cow<'a, FixStr>,
}

#[derive(Clone, Copy, Debug)]
pub struct ResendRequestBase {
    pub begin_seq_no: SeqNum,
    pub end_seq_no: SeqNum,
}

#[derive(Clone, Copy, Debug)]
pub struct SequenceResetBase {
    pub gap_fill_flag: Option<Boolean>,
    pub new_seq_no: SeqNum,
}

#[derive(Clone, Debug)]
pub struct RejectBase<'a> {
    pub ref_seq_num: SeqNum,
    pub ref_tag_id: Option<Int>,
    pub ref_msg_type: Option<Cow<'a, FixStr>>,
    pub session_reject_reason: Option<SessionRejectReasonField>,
    pub text: Option<Cow<'a, FixStr>>,
}