Skip to main content

easyfix_core/
base_messages.rs

1//! Base messages and base enumerations - the contract between the session
2//! layer and [`SessionMessage`] implementations.
3//!
4//! Types in this module are used by code that implements [`SessionMessage`]
5//! (typically the code generator, but also custom implementations). The session
6//! layer produces and consumes these types without knowing the concrete message
7//! representation.
8//!
9//! - **Base messages** (`HeaderBase`, `AdminBase`, `LogonBase`, etc.) - minimal
10//!   typed structures with only the fields the session needs. String fields use
11//!   `Cow` for zero-copy borrowing on incoming and owned construction on outgoing.
12//!
13//! - **Base enums** (`MsgTypeBase`, `SessionStatusBase`, `SessionRejectReasonBase`,
14//!   `EncryptMethodBase`) - typed constants for session-relevant FIX enumeration
15//!   values. [`SessionMessage`] implementations convert between these and the
16//!   concrete generated enums via `From` impls.
17//!
18//! [`SessionMessage`]: crate::message::SessionMessage
19
20use std::{borrow::Cow, mem::variant_count};
21
22use crate::basic_types::{
23    ApplVerId, Boolean, FixStr, Int, Length, MsgTypeField, MsgTypeValue, SeqNum,
24    SessionRejectReasonField, SessionRejectReasonValue, SessionStatusField, SessionStatusValue,
25    UtcTimestamp,
26};
27
28// ---------------------------------------------------------------------------
29// MsgTypeBase (tag 35)
30// ---------------------------------------------------------------------------
31
32/// MsgType (tag 35) base enum - typed constants for session-relevant
33/// admin message types.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum MsgTypeBase {
36    Heartbeat,     // "0"
37    TestRequest,   // "1"
38    ResendRequest, // "2"
39    Reject,        // "3"
40    SequenceReset, // "4"
41    Logout,        // "5"
42    Logon,         // "A"
43}
44
45impl MsgTypeBase {
46    /// All variants. The code generator validates that a generated `MsgType`
47    /// enum covers every variant listed here.
48    pub const ALL: &'static [MsgTypeBase] = &[
49        MsgTypeBase::Heartbeat,
50        MsgTypeBase::TestRequest,
51        MsgTypeBase::ResendRequest,
52        MsgTypeBase::Reject,
53        MsgTypeBase::SequenceReset,
54        MsgTypeBase::Logout,
55        MsgTypeBase::Logon,
56    ];
57
58    /// The compact MsgType field value for this administrative message type.
59    pub const fn raw_value(&self) -> MsgTypeField {
60        match self {
61            MsgTypeBase::Heartbeat => MsgTypeField::from_raw([b'0', 0]),
62            MsgTypeBase::TestRequest => MsgTypeField::from_raw([b'1', 0]),
63            MsgTypeBase::ResendRequest => MsgTypeField::from_raw([b'2', 0]),
64            MsgTypeBase::Reject => MsgTypeField::from_raw([b'3', 0]),
65            MsgTypeBase::SequenceReset => MsgTypeField::from_raw([b'4', 0]),
66            MsgTypeBase::Logout => MsgTypeField::from_raw([b'5', 0]),
67            MsgTypeBase::Logon => MsgTypeField::from_raw([b'A', 0]),
68        }
69    }
70}
71
72const _: () = assert!(
73    MsgTypeBase::ALL.len() == variant_count::<MsgTypeBase>(),
74    "MsgTypeBase::ALL is missing a variant"
75);
76
77impl MsgTypeValue for MsgTypeBase {
78    fn raw_value(&self) -> MsgTypeField {
79        MsgTypeBase::raw_value(self)
80    }
81}
82
83impl PartialEq<MsgTypeBase> for MsgTypeField {
84    fn eq(&self, other: &MsgTypeBase) -> bool {
85        *self == other.raw_value()
86    }
87}
88
89impl PartialEq<MsgTypeField> for MsgTypeBase {
90    fn eq(&self, other: &MsgTypeField) -> bool {
91        self.raw_value() == *other
92    }
93}
94
95// ---------------------------------------------------------------------------
96// SessionStatus (tag 1409)
97// ---------------------------------------------------------------------------
98
99/// SessionStatus (tag 1409), carried on FIXT Logon and Logout.
100#[derive(Clone, Copy, Debug, Eq, PartialEq)]
101pub enum SessionStatusBase {
102    SessionActive = 0,
103    SessionLogoutComplete = 4,
104    ReceivedMsgSeqNumTooLow = 9,
105    ReceivedNextExpectedMsgSeqNumTooHigh = 10,
106}
107
108impl SessionStatusBase {
109    /// All variants. The code generator validates that a generated
110    /// `SessionStatus` enum covers every variant listed here.
111    pub const ALL: &'static [SessionStatusBase] = &[
112        SessionStatusBase::SessionActive,
113        SessionStatusBase::SessionLogoutComplete,
114        SessionStatusBase::ReceivedMsgSeqNumTooLow,
115        SessionStatusBase::ReceivedNextExpectedMsgSeqNumTooHigh,
116    ];
117}
118
119const _: () = assert!(
120    SessionStatusBase::ALL.len() == variant_count::<SessionStatusBase>(),
121    "SessionStatusBase::ALL is missing a variant"
122);
123
124impl SessionStatusValue for SessionStatusBase {
125    fn raw_value(&self) -> Int {
126        *self as Int
127    }
128}
129
130// ---------------------------------------------------------------------------
131// SessionRejectReason (tag 373)
132// ---------------------------------------------------------------------------
133
134// FIX Session Layer (June 2020), Section 11.11, lists InvalidTagNumber (0)
135// and UndefinedTag (3) without explaining their distinction. FIX Session
136// Layer Test Cases (June 2020), Section 4.5.13, Scenario 14(a), requires
137// reason 0 for a tag not defined in the applicable specification unless
138// agreed as user-defined, even when the number is syntactically valid.
139// Scenario 14 assigns no separate validation case to code 3. Follow the
140// explicit test case rather than infer behavior from the variant names.
141// Neither document identifies code 3 as deprecated or replaced by code 0.
142// https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX_Session_Layer_June_2020.pdf
143// https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX_Session_Testcases_June_2020.pdf
144/// SessionRejectReason (tag 373), carried on Reject.
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum SessionRejectReasonBase {
147    InvalidTagNumber = 0,
148    RequiredTagMissing = 1,
149    TagNotDefinedForThisMessageType = 2,
150    UndefinedTag = 3,
151    TagSpecifiedWithoutAValue = 4,
152    ValueIsIncorrect = 5,
153    IncorrectDataFormatForValue = 6,
154    CompIdProblem = 9,
155    SendingTimeAccuracyProblem = 10,
156    InvalidMsgType = 11,
157    TagAppearsMoreThanOnce = 13,
158    TagSpecifiedOutOfRequiredOrder = 14,
159    RepeatingGroupFieldsOutOfOrder = 15,
160    IncorrectNumInGroupCountForRepeatingGroup = 16,
161}
162
163impl SessionRejectReasonBase {
164    /// All variants. The code generator validates that a generated
165    /// `SessionRejectReason` enum covers every variant listed here.
166    pub const ALL: &'static [SessionRejectReasonBase] = &[
167        SessionRejectReasonBase::InvalidTagNumber,
168        SessionRejectReasonBase::RequiredTagMissing,
169        SessionRejectReasonBase::TagNotDefinedForThisMessageType,
170        SessionRejectReasonBase::UndefinedTag,
171        SessionRejectReasonBase::TagSpecifiedWithoutAValue,
172        SessionRejectReasonBase::ValueIsIncorrect,
173        SessionRejectReasonBase::IncorrectDataFormatForValue,
174        SessionRejectReasonBase::CompIdProblem,
175        SessionRejectReasonBase::SendingTimeAccuracyProblem,
176        SessionRejectReasonBase::InvalidMsgType,
177        SessionRejectReasonBase::TagAppearsMoreThanOnce,
178        SessionRejectReasonBase::TagSpecifiedOutOfRequiredOrder,
179        SessionRejectReasonBase::RepeatingGroupFieldsOutOfOrder,
180        SessionRejectReasonBase::IncorrectNumInGroupCountForRepeatingGroup,
181    ];
182}
183
184const _: () = assert!(
185    SessionRejectReasonBase::ALL.len() == variant_count::<SessionRejectReasonBase>(),
186    "SessionRejectReasonBase::ALL is missing a variant"
187);
188
189impl SessionRejectReasonValue for SessionRejectReasonBase {
190    fn raw_value(&self) -> Int {
191        *self as Int
192    }
193
194    fn description(&self) -> &'static str {
195        match self {
196            Self::InvalidTagNumber => stringify!(InvalidTagNumber),
197            Self::RequiredTagMissing => stringify!(RequiredTagMissing),
198            Self::TagNotDefinedForThisMessageType => stringify!(TagNotDefinedForThisMessageType),
199            Self::UndefinedTag => stringify!(UndefinedTag),
200            Self::TagSpecifiedWithoutAValue => stringify!(TagSpecifiedWithoutAValue),
201            Self::ValueIsIncorrect => stringify!(ValueIsIncorrect),
202            Self::IncorrectDataFormatForValue => stringify!(IncorrectDataFormatForValue),
203            Self::CompIdProblem => stringify!(CompIdProblem),
204            Self::SendingTimeAccuracyProblem => stringify!(SendingTimeAccuracyProblem),
205            Self::InvalidMsgType => stringify!(InvalidMsgType),
206            Self::TagAppearsMoreThanOnce => stringify!(TagAppearsMoreThanOnce),
207            Self::TagSpecifiedOutOfRequiredOrder => stringify!(TagSpecifiedOutOfRequiredOrder),
208            Self::RepeatingGroupFieldsOutOfOrder => stringify!(RepeatingGroupFieldsOutOfOrder),
209            Self::IncorrectNumInGroupCountForRepeatingGroup => {
210                stringify!(IncorrectNumInGroupCountForRepeatingGroup)
211            }
212        }
213    }
214}
215
216impl PartialEq<SessionRejectReasonBase> for SessionRejectReasonField {
217    fn eq(&self, other: &SessionRejectReasonBase) -> bool {
218        self.into_inner() == other.raw_value()
219    }
220}
221
222// ---------------------------------------------------------------------------
223// EncryptMethod (tag 98)
224// ---------------------------------------------------------------------------
225
226/// EncryptMethod (tag 98). Only `None` (wire value `0`) is modelled here.
227#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
228pub enum EncryptMethodBase {
229    #[default]
230    None = 0,
231}
232
233impl EncryptMethodBase {
234    /// All variants. The code generator validates that a generated
235    /// `EncryptMethod` enum covers every variant listed here.
236    pub const ALL: &'static [EncryptMethodBase] = &[EncryptMethodBase::None];
237}
238
239const _: () = assert!(
240    EncryptMethodBase::ALL.len() == variant_count::<EncryptMethodBase>(),
241    "EncryptMethodBase::ALL is missing a variant"
242);
243
244/// Base header containing only the fields the session layer reads/writes.
245///
246/// - **Incoming**: returned by `SessionMessage::header` with `Cow::Borrowed` - zero allocations.
247/// - **Outgoing**: built by session with `Cow::Owned`, consumed via `From` conversion.
248#[derive(Clone, Debug, Default)]
249pub struct HeaderBase<'a> {
250    pub sender_comp_id: Cow<'a, FixStr>,
251    pub target_comp_id: Cow<'a, FixStr>,
252    pub msg_seq_num: SeqNum,
253    pub sending_time: UtcTimestamp,
254    pub poss_dup_flag: Option<Boolean>,
255    pub orig_sending_time: Option<UtcTimestamp>,
256    /// FIXT only. `None` for pre-FIXT versions.
257    pub appl_ver_id: Option<ApplVerId>,
258}
259
260impl HeaderBase<'_> {
261    /// Detach the header from the message bytes it borrows, converting
262    /// the `Cow` fields to owned values. Allocates only for borrowed
263    /// CompIDs; every other field is `Copy`.
264    pub fn into_owned(self) -> HeaderBase<'static> {
265        HeaderBase {
266            sender_comp_id: Cow::Owned(self.sender_comp_id.into_owned()),
267            target_comp_id: Cow::Owned(self.target_comp_id.into_owned()),
268            msg_seq_num: self.msg_seq_num,
269            sending_time: self.sending_time,
270            poss_dup_flag: self.poss_dup_flag,
271            orig_sending_time: self.orig_sending_time,
272            appl_ver_id: self.appl_ver_id,
273        }
274    }
275}
276
277/// Admin message base, obtained from `SessionMessage::try_as_admin`.
278#[derive(Clone, Debug)]
279pub enum AdminBase<'a> {
280    Logon(LogonBase),
281    Logout(LogoutBase<'a>),
282    Heartbeat(HeartbeatBase<'a>),
283    TestRequest(TestRequestBase<'a>),
284    ResendRequest(ResendRequestBase),
285    SequenceReset(SequenceResetBase),
286    Reject(RejectBase<'a>),
287}
288
289#[derive(Clone, Debug)]
290pub struct LogonBase {
291    /// Typed value for outgoing.
292    pub encrypt_method: EncryptMethodBase,
293    /// Raw value for incoming comparison/logging.
294    pub encrypt_method_raw: Int,
295    pub heart_bt_int: Int,
296    pub reset_seq_num_flag: Option<Boolean>,
297    /// Maximum number of octets the sender supports for messages it
298    /// receives (FIX Session Layer ยง4.3.6). `None` for FIX < 4.2, and
299    /// whenever the peer did not advertise a limit.
300    ///
301    /// Never `Some(0)` on the incoming path - a zero-valued Length field
302    /// is rejected while parsing.
303    pub max_message_size: Option<Length>,
304    /// `None` for FIX < 4.4.
305    pub next_expected_msg_seq_num: Option<SeqNum>,
306    /// `None` for pre-FIXT.
307    pub default_appl_ver_id: Option<ApplVerId>,
308    /// FIXT only.
309    pub session_status: Option<SessionStatusField>,
310}
311
312#[derive(Clone, Debug)]
313pub struct LogoutBase<'a> {
314    /// FIXT only.
315    pub session_status: Option<SessionStatusField>,
316    pub text: Option<Cow<'a, FixStr>>,
317}
318
319#[derive(Clone, Debug)]
320pub struct HeartbeatBase<'a> {
321    pub test_req_id: Option<Cow<'a, FixStr>>,
322}
323
324#[derive(Clone, Debug)]
325pub struct TestRequestBase<'a> {
326    pub test_req_id: Cow<'a, FixStr>,
327}
328
329#[derive(Clone, Copy, Debug)]
330pub struct ResendRequestBase {
331    pub begin_seq_no: SeqNum,
332    pub end_seq_no: SeqNum,
333}
334
335#[derive(Clone, Copy, Debug)]
336pub struct SequenceResetBase {
337    pub gap_fill_flag: Option<Boolean>,
338    pub new_seq_no: SeqNum,
339}
340
341#[derive(Clone, Debug)]
342pub struct RejectBase<'a> {
343    pub ref_seq_num: SeqNum,
344    pub ref_tag_id: Option<Int>,
345    pub ref_msg_type: Option<Cow<'a, FixStr>>,
346    pub session_reject_reason: Option<SessionRejectReasonField>,
347    pub text: Option<Cow<'a, FixStr>>,
348}