hotfix 0.12.0

Buy-side FIX engine written in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
mod active;
mod awaiting_logon;
mod awaiting_logout;
mod awaiting_resend;
mod disconnected;

pub(crate) use active::{ActiveState, calculate_peer_interval};
pub(crate) use awaiting_logon::AwaitingLogonState;
pub(crate) use awaiting_logout::AwaitingLogoutState;
pub(crate) use awaiting_resend::AwaitingResendState;
pub(crate) use disconnected::DisconnectedState;

use crate::Application;
use crate::message::OutboundMessage;
use crate::message::logon::Logon;
use crate::message::logout::Logout;
use crate::message::verification::VerificationFlags;
use crate::session::ctx::{PreProcessDecision, SessionCtx, TransitionResult, VerificationResult};
use crate::session::error::{
    InternalSendError, InternalSendResultExt, SessionOperationError, SetNextTargetSeqNumError,
};
use crate::session::event::ScheduleResponse;
use crate::session::info::Status as SessionInfoStatus;
use crate::transport::writer::WriterRef;
use hotfix_message::message::Message;
use hotfix_store::MessageStore;
use std::num::NonZeroU64;
use std::time::Duration;
use tokio::sync::oneshot;
use tokio::time::Instant;
use tracing::{debug, error, warn};

const TEST_REQUEST_THRESHOLD: f64 = 1.2;

pub(crate) type TestRequestId = String;

pub enum SessionState {
    /// We have established a connection, sent a logon message and await a response.
    AwaitingLogon(AwaitingLogonState),
    /// We are awaiting the target to resend the gap we have.
    AwaitingResend(AwaitingResendState),
    /// We are in the process of gracefully logging out
    AwaitingLogout(AwaitingLogoutState),
    /// The session is active, we have connected and mutually logged on.
    Active(ActiveState),
    /// The TCP connection has been dropped.
    ///
    /// This is also the state we're in if we purposefully disconnected due to the current
    /// time being out of session hours.
    Disconnected(DisconnectedState),
}

impl SessionState {
    pub fn new_disconnected(reconnect: bool, reason: &str) -> Self {
        Self::Disconnected(DisconnectedState::new(reconnect, reason))
    }

    pub fn new_active(writer: WriterRef, heartbeat_interval: u64) -> Self {
        let peer_interval = calculate_peer_interval(heartbeat_interval);

        Self::Active(ActiveState {
            writer,
            heartbeat_deadline: Instant::now() + Duration::from_secs(heartbeat_interval),
            peer_deadline: Instant::now() + Duration::from_secs(peer_interval),
            sent_test_request_id: None,
        })
    }

    /// Handles a Logon message from the peer. Only AwaitingLogon produces a
    /// transition — all other states log an error and stay.
    pub(crate) async fn on_peer_logon<A: Application, S: MessageStore>(
        &self,
        ctx: &mut SessionCtx<A, S>,
    ) -> Result<TransitionResult, SessionOperationError> {
        match self {
            Self::AwaitingLogon(state) => state.on_peer_logon(ctx).await,
            _ => {
                error!("received unexpected logon message");
                Ok(TransitionResult::Stay)
            }
        }
    }

    /// Returns the transition to apply when a Logout message is received from the peer.
    /// Each state determines its own reconnect policy and disconnect reason.
    pub(crate) fn on_peer_logout(&self) -> TransitionResult {
        match self {
            Self::AwaitingLogout(AwaitingLogoutState { reconnect, .. }) => {
                TransitionResult::TransitionTo(Self::new_disconnected(
                    *reconnect,
                    "logout completed",
                ))
            }
            Self::Disconnected(_) => TransitionResult::Stay,
            _ => TransitionResult::TransitionTo(Self::new_disconnected(
                true,
                "peer has logged us out",
            )),
        }
    }

    /// Returns the transition to apply when the transport layer reports a disconnect.
    /// Each state determines its own reconnect policy.
    pub(crate) fn on_disconnect(&self, reason: &str) -> TransitionResult {
        match self {
            Self::Active(_) | Self::AwaitingLogon(_) | Self::AwaitingResend(_) => {
                TransitionResult::TransitionTo(Self::new_disconnected(true, reason))
            }
            Self::AwaitingLogout(AwaitingLogoutState { reconnect, .. }) => {
                TransitionResult::TransitionTo(Self::new_disconnected(*reconnect, reason))
            }
            Self::Disconnected(_) => {
                warn!("disconnect message was received, but the session is already disconnected");
                TransitionResult::Stay
            }
        }
    }

    /// Let the current state decide whether an inbound message should be processed,
    /// queued for later, or rejected before verification and dispatch.
    pub(crate) fn pre_process_inbound(&mut self, message: Message) -> PreProcessDecision {
        match self {
            Self::AwaitingResend(state) => state.pre_process_inbound(message),
            Self::AwaitingLogon(state) => state.pre_process_inbound(message),
            _ => PreProcessDecision::Accept(message),
        }
    }

    pub fn should_reconnect(&self) -> bool {
        match self {
            SessionState::Disconnected(DisconnectedState { reconnect, .. }) => *reconnect,
            _ => true,
        }
    }

    pub async fn send_message<A, S>(
        &mut self,
        ctx: &mut SessionCtx<A, S>,
        message: impl OutboundMessage,
    ) -> Result<u64, InternalSendError>
    where
        A: Application,
        S: MessageStore,
    {
        let message_type = message.message_type().to_string();
        let prepared = ctx.prepare_message(message).await?;
        let raw = prepared.raw;

        match self {
            Self::Active(ActiveState { writer, .. })
            | Self::AwaitingResend(AwaitingResendState { writer, .. }) => {
                if message_type == Logon::MSG_TYPE {
                    error!("logon message is invalid for active sessions")
                } else {
                    writer.send_raw_message(raw).await
                }
            }
            Self::AwaitingLogon(AwaitingLogonState {
                writer, logon_sent, ..
            }) => match message_type.as_str() {
                Logon::MSG_TYPE => {
                    if *logon_sent {
                        error!("trying to send logon twice");
                    } else {
                        writer.send_raw_message(raw).await;
                        *logon_sent = true;
                    }
                }
                Logout::MSG_TYPE => {
                    writer.send_raw_message(raw).await;
                }
                _ => error!("invalid outgoing message for AwaitingLogon state"),
            },
            Self::AwaitingLogout(_) => {
                error!("trying to send message while awaiting logout");
            }
            _ => error!("trying to write without an established connection"),
        }

        self.reset_heartbeat_timer(ctx.config.heartbeat_interval);

        Ok(prepared.seq_num)
    }

    pub async fn disconnect_writer(&self) {
        match self {
            Self::Active(ActiveState { writer, .. })
            | Self::AwaitingLogon(AwaitingLogonState { writer, .. })
            | Self::AwaitingLogout(AwaitingLogoutState { writer, .. })
            | Self::AwaitingResend(AwaitingResendState { writer, .. }) => writer.disconnect().await,
            _ => debug!("disconnecting an already disconnected session"),
        }
    }

    pub(crate) fn get_writer(&self) -> Option<&WriterRef> {
        match self {
            Self::Active(ActiveState { writer, .. })
            | Self::AwaitingLogon(AwaitingLogonState { writer, .. })
            | Self::AwaitingLogout(AwaitingLogoutState { writer, .. })
            | Self::AwaitingResend(AwaitingResendState { writer, .. }) => Some(writer),
            _ => None,
        }
    }

    pub fn try_transition_to_awaiting_logout(
        &self,
        logout_timeout: Duration,
        reconnect: bool,
    ) -> TransitionResult {
        if matches!(self, SessionState::AwaitingLogout(_)) {
            debug!("already in awaiting logout state");
            return TransitionResult::Stay;
        }

        if let Some(writer) = self.get_writer() {
            TransitionResult::TransitionTo(SessionState::AwaitingLogout(AwaitingLogoutState {
                writer: writer.clone(),
                logout_timeout: Instant::now() + logout_timeout,
                reconnect,
            }))
        } else {
            error!("trying to transition to awaiting logout without an established connection");
            TransitionResult::Stay
        }
    }

    pub(crate) async fn handle_verification_issue<A: Application, S: MessageStore>(
        &mut self,
        ctx: &mut SessionCtx<A, S>,
        message: &Message,
        flags: VerificationFlags,
    ) -> Result<VerificationResult, SessionOperationError> {
        match self {
            SessionState::Active(state) => {
                state.handle_verification_issue(ctx, message, flags).await
            }
            SessionState::AwaitingResend(state) => {
                state.handle_verification_issue(ctx, message, flags).await
            }
            SessionState::AwaitingLogon(state) => {
                state.handle_verification_issue(ctx, message, flags).await
            }
            SessionState::AwaitingLogout(state) => {
                state.handle_verification_issue(ctx, message, flags).await
            }
            SessionState::Disconnected(_) => {
                error!("handle_verification_issue called while disconnected");
                Ok(VerificationResult::Passed)
            }
        }
    }

    /// Set the next expected target sequence number.
    pub(crate) async fn try_set_next_target_seq_num<A, S>(
        &self,
        ctx: &mut SessionCtx<A, S>,
        seq_num: NonZeroU64,
    ) -> Result<(), SetNextTargetSeqNumError>
    where
        A: Application,
        S: MessageStore,
    {
        // Only permitted while `Disconnected` — any other state returns `InvalidState`.
        match self {
            SessionState::Disconnected(_) => {
                // The store stores "last seen" (see `inbound::on_sequence_reset` passing `end - 1`),
                // so we subtract 1 to make `next_target_seq_number()` return `seq_num`.
                let target_seq_num = seq_num.get() - 1;

                ctx.store
                    .set_target_seq_number(target_seq_num)
                    .await
                    .map_err(SetNextTargetSeqNumError::from)
            }
            _ => Err(SetNextTargetSeqNumError::InvalidState {
                current: self.as_status(),
            }),
        }
    }

    /// Sends a logout message and puts the session state into an [`AwaitingLogout`] state.
    ///
    /// The session waits for a configurable timeout period for the counterparty to
    /// respond with a `Logout` message. If no response is received within the timeout
    /// period, it disconnects the counterparty.
    pub async fn initiate_graceful_logout<A, S>(
        &mut self,
        ctx: &mut SessionCtx<A, S>,
        reason: &str,
        reconnect: bool,
    ) -> Result<TransitionResult, SessionOperationError>
    where
        A: Application,
        S: MessageStore,
    {
        let result = self.try_transition_to_awaiting_logout(
            Duration::from_secs(ctx.config.logout_timeout),
            reconnect,
        );
        if matches!(result, TransitionResult::TransitionTo(_)) {
            self.send_logout(ctx, reason).await?;
        }

        Ok(result)
    }

    /// Sends a logout message and immediately disconnects the counterparty.
    ///
    /// This should be used sparingly in scenarios where there is a major issue
    /// requiring operational intervention, such as the sequence number being lower
    /// than expected, or some other key header field containing an invalid value.
    ///
    /// In other scenarios, [`initiate_graceful_logout`] should be preferred.
    pub async fn logout_and_terminate<A, S>(&mut self, ctx: &mut SessionCtx<A, S>, reason: &str)
    where
        A: Application,
        S: MessageStore,
    {
        if let Err(err) = self.send_logout(ctx, reason).await {
            warn!("failed to send logout during session termination: {}", err);
        }
        self.disconnect_writer().await;
    }

    pub async fn send_logout<A, S>(
        &mut self,
        ctx: &mut SessionCtx<A, S>,
        reason: &str,
    ) -> Result<(), SessionOperationError>
    where
        A: Application,
        S: MessageStore,
    {
        let logout = Logout::with_reason(reason.to_string());
        self.send_message(ctx, logout)
            .await
            .with_send_context("logout")?;
        Ok(())
    }

    pub fn register_schedule_awaiter(&mut self, responder: oneshot::Sender<ScheduleResponse>) {
        match self {
            SessionState::Disconnected(state) => {
                if state.has_schedule_awaiter() {
                    let reason = &state.reason;
                    error!(
                        "schedule awaiter already registered on state disconnected due to: {reason}"
                    );
                    if let Err(err) = responder.send(ScheduleResponse::Shutdown) {
                        error!("failed to send schedule awaiter response: {err:?}");
                    }
                } else {
                    state.set_schedule_awaiter(responder);
                    debug!("registered schedule awaiter");
                }
            }
            _ => {
                error!("schedule awaiter can only be registered on disconnected sessions");
                if let Err(err) = responder.send(ScheduleResponse::Shutdown) {
                    error!("failed to send schedule awaiter response: {err:?}");
                }
            }
        }
    }

    pub fn notify_schedule_awaiter(&mut self) {
        if let SessionState::Disconnected(state) = self
            && let Some(awaiter) = state.take_schedule_awaiter()
        {
            if let Err(err) = awaiter.send(ScheduleResponse::InSchedule) {
                error!("failed to send schedule awaiter response: {err:?}");
            } else {
                debug!("notified schedule awaiter");
            }
        }
    }

    pub fn heartbeat_deadline(&self) -> Option<&Instant> {
        match self {
            Self::Active(ActiveState {
                heartbeat_deadline, ..
            }) => Some(heartbeat_deadline),
            _ => None,
        }
    }

    pub fn reset_heartbeat_timer(&mut self, heartbeat_interval: u64) {
        if let Self::Active(ActiveState {
            heartbeat_deadline, ..
        }) = self
        {
            *heartbeat_deadline = Instant::now() + Duration::from_secs(heartbeat_interval);
        }
    }

    pub fn peer_deadline(&self) -> Option<&Instant> {
        match self {
            Self::Active(ActiveState { peer_deadline, .. }) => Some(peer_deadline),
            Self::AwaitingLogon(AwaitingLogonState { logon_timeout, .. }) => Some(logon_timeout),
            Self::AwaitingLogout(AwaitingLogoutState { logout_timeout, .. }) => {
                Some(logout_timeout)
            }
            _ => None,
        }
    }

    pub fn reset_peer_timer(
        &mut self,
        heartbeat_interval: u64,
        test_request_id: Option<TestRequestId>,
    ) {
        if let Self::Active(ActiveState {
            peer_deadline,
            sent_test_request_id,
            ..
        }) = self
        {
            let interval = calculate_peer_interval(heartbeat_interval);
            *peer_deadline = Instant::now() + Duration::from_secs(interval);
            *sent_test_request_id = test_request_id;
        }
    }

    pub fn expected_test_response_id(&self) -> Option<&TestRequestId> {
        match self {
            Self::Active(ActiveState {
                sent_test_request_id: expected_test_response_id,
                ..
            }) => expected_test_response_id.as_ref(),
            _ => None,
        }
    }

    pub fn is_connected(&self) -> bool {
        self.get_writer().is_some()
    }

    pub fn is_logged_on(&self) -> bool {
        matches!(self, SessionState::Active(_))
            || matches!(self, SessionState::AwaitingResend { .. })
    }

    pub fn is_expecting_test_response(&self) -> bool {
        self.expected_test_response_id().is_some()
    }

    pub fn is_awaiting_logon(&self) -> bool {
        matches!(self, SessionState::AwaitingLogon(_))
    }

    pub fn is_awaiting_logout(&self) -> bool {
        matches!(self, SessionState::AwaitingLogout(_))
    }

    pub fn as_status(&self) -> SessionInfoStatus {
        match self {
            SessionState::AwaitingLogon(_) => SessionInfoStatus::AwaitingLogon,
            SessionState::AwaitingResend(AwaitingResendState {
                begin_seq_number,
                end_seq_number,
                resend_attempts,
                ..
            }) => SessionInfoStatus::AwaitingResend {
                begin: *begin_seq_number,
                end: *end_seq_number,
                attempts: *resend_attempts,
            },
            SessionState::AwaitingLogout(_) => SessionInfoStatus::AwaitingLogout,
            SessionState::Active(_) => SessionInfoStatus::Active,
            SessionState::Disconnected(_) => SessionInfoStatus::Disconnected,
        }
    }
}