easyfix_core/message.rs
1//! The [`SessionMessage`] trait and related types.
2//!
3//! The session layer is generic over `M: SessionMessage`, so it never names a
4//! concrete message type. Implementations provide the bridge between session
5//! logic and concrete message definitions.
6
7use std::fmt::Debug;
8
9use crate::{
10 base_messages::{AdminBase, HeaderBase},
11 basic_types::{ApplVerId, Boolean, FixStr, FixString, MsgTypeField, SeqNum, UtcTimestamp},
12 deserializer::{DeserializeErrorKind, RawMessage, RawMessageError, raw_message},
13 serializer::SerializeError,
14 version::Version,
15};
16
17/// Deserialization failure returned by [`SessionMessage::from_raw_message`].
18///
19/// Aggregates the underlying [`DeserializeErrorKind`] with the header of the
20/// failed message when it is recoverable. The session layer uses the header
21/// to give header verdicts (sequence numbers first) precedence over the
22/// body-level error.
23#[derive(Debug, thiserror::Error)]
24#[error("{kind}")]
25pub struct DeserializeError {
26 /// The underlying deserialization failure.
27 #[source]
28 pub kind: DeserializeErrorKind,
29 /// Fully parsed header of the failed message. `Some` when header
30 /// parsing succeeded and the failure happened in the body or trailer;
31 /// `None` when the header itself failed to parse.
32 pub header: Option<Box<HeaderBase<'static>>>,
33}
34
35impl From<DeserializeErrorKind> for DeserializeError {
36 fn from(kind: DeserializeErrorKind) -> Self {
37 DeserializeError { kind, header: None }
38 }
39}
40
41impl From<RawMessageError> for DeserializeError {
42 fn from(error: RawMessageError) -> Self {
43 DeserializeErrorKind::from(error).into()
44 }
45}
46
47/// Admin vs App message category.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum MsgCat {
50 /// Administrative message
51 Admin,
52 /// Application message
53 App,
54}
55
56/// Core message trait that bridges session logic and concrete message types.
57///
58/// The session layer uses this trait to deserialize, inspect, construct, and
59/// serialize messages without knowing the concrete type.
60pub trait SessionMessage: Sized + Debug + HeaderAccess {
61 /// Deserialize from a structurally validated `RawMessage`.
62 ///
63 /// On failure the [`DeserializeError`] carries the parsed header whenever
64 /// header parsing succeeded before the failure.
65 //
66 // Boxed because concrete message types can be large (e.g. ExecutionReport).
67 fn from_raw_message(raw: RawMessage<'_>) -> Result<Box<Self>, DeserializeError>;
68
69 /// Deserialize from FIX tag-value wire bytes. Composes [`raw_message`]
70 /// framing with [`Self::from_raw_message`].
71 fn from_bytes(bytes: &[u8]) -> Result<Box<Self>, DeserializeError> {
72 let (_, raw) = raw_message(bytes)?;
73 Self::from_raw_message(raw)
74 }
75
76 /// Serialize to FIX tag-value wire format into the caller-provided buffer.
77 /// Returns the number of bytes written.
78 fn serialize(&self, buf: &mut [u8]) -> Result<usize, SerializeError>;
79
80 /// Extract header fields as a borrowed base. Zero-copy.
81 fn header(&self) -> HeaderBase<'_>;
82
83 /// If this is an admin message, return the borrowed base. Zero-copy.
84 fn try_as_admin(&self) -> Option<AdminBase<'_>>;
85
86 /// Compact message type identifier (e.g. `"A"` for Logon, `"D"` for
87 /// NewOrderSingle).
88 ///
89 /// Compare against [`MsgTypeBase`] variants for admin dispatch, or
90 /// `TryFrom` into a richer generated type for exhaustive matching -
91 /// fallible, since the field may hold a value that type does not define.
92 ///
93 /// [`MsgTypeBase`]: crate::base_messages::MsgTypeBase
94 fn msg_type(&self) -> MsgTypeField;
95
96 /// Whether this is an admin or application message.
97 fn msg_cat(&self) -> MsgCat;
98
99 /// Human-readable message name (e.g., `"Logon"`, `"NewOrderSingle"`).
100 fn name(&self) -> &'static str;
101
102 /// Build an outgoing admin message from owned base messages.
103 fn from_admin(header: HeaderBase<'static>, admin: AdminBase<'static>) -> Self;
104}
105
106/// Get/set access to the header fields the session layer reads and fills in.
107pub trait HeaderAccess {
108 /// BeginString (tag 8) - FIX protocol version.
109 ///
110 /// Constant per message type; it never varies between instances.
111 fn version(&self) -> Version;
112
113 /// SenderCompID (tag 49) - identifier of the message sender.
114 fn sender_comp_id(&self) -> &FixStr;
115
116 /// TargetCompID (tag 56) - identifier of the message recipient.
117 fn target_comp_id(&self) -> &FixStr;
118
119 /// MsgSeqNum (tag 34) - message sequence number within the session.
120 fn msg_seq_num(&self) -> SeqNum;
121
122 /// SendingTime (tag 52) - time the message was sent (UTC).
123 fn sending_time(&self) -> UtcTimestamp;
124
125 /// PossDupFlag (tag 43) - `true` if this is a possible duplicate (resend).
126 fn poss_dup_flag(&self) -> Option<Boolean>;
127
128 /// OrigSendingTime (tag 122) - original sending time for resent messages.
129 /// Returns `None` if the field is absent or the FIX version doesn't define it.
130 fn orig_sending_time(&self) -> Option<UtcTimestamp>;
131
132 /// ApplVerID (tag 1128) - application-level protocol version.
133 /// Only relevant for FIXT (FIX 5.0+); return `None` for FIX 4.x.
134 fn appl_ver_id(&self) -> Option<ApplVerId>;
135
136 /// Set SenderCompID (tag 49).
137 fn set_sender_comp_id(&mut self, value: FixString);
138
139 /// Set TargetCompID (tag 56).
140 fn set_target_comp_id(&mut self, value: FixString);
141
142 /// Set MsgSeqNum (tag 34).
143 fn set_msg_seq_num(&mut self, value: SeqNum);
144
145 /// Set SendingTime (tag 52).
146 fn set_sending_time(&mut self, value: UtcTimestamp);
147
148 /// Set PossDupFlag (tag 43). Pass `None` to clear.
149 fn set_poss_dup_flag(&mut self, value: Option<Boolean>);
150
151 /// Set OrigSendingTime (tag 122). Pass `None` to clear.
152 fn set_orig_sending_time(&mut self, value: Option<UtcTimestamp>);
153
154 /// Set ApplVerID (tag 1128). Pass `None` to clear.
155 /// No-op for FIX 4.x implementations.
156 fn set_appl_ver_id(&mut self, value: Option<ApplVerId>);
157}