easyfix_session/
io.rs

1use std::{
2    cell::{Cell, RefCell},
3    collections::{HashMap, hash_map::Entry},
4    rc::Rc,
5    sync::Mutex,
6    time::Duration,
7};
8
9use easyfix_messages::{
10    fields::{FixString, SessionStatus},
11    messages::{FixtMessage, Message},
12};
13use futures_util::{Stream, pin_mut};
14use tokio::{
15    self,
16    io::{AsyncRead, AsyncWrite, AsyncWriteExt},
17    net::TcpStream,
18    sync::mpsc,
19};
20use tokio_stream::StreamExt;
21use tracing::{Instrument, Span, debug, error, info, info_span, warn};
22
23use crate::{
24    DisconnectReason, Error, NO_INBOUND_TIMEOUT_PADDING, Sender, SessionError,
25    TEST_REQUEST_THRESHOLD,
26    acceptor::{ActiveSessionsMap, SessionsMap},
27    application::{Emitter, FixEventInternal},
28    messages_storage::MessagesStorage,
29    session::Session,
30    session_id::SessionId,
31    session_state::State,
32    settings::{SessionSettings, Settings},
33};
34
35mod input_stream;
36pub use input_stream::{InputEvent, InputStream, input_stream};
37
38mod output_stream;
39use output_stream::{OutputEvent, output_stream};
40
41pub mod time;
42use time::{timeout, timeout_at, timeout_stream};
43
44static SENDERS: Mutex<Option<HashMap<SessionId, Sender>>> = Mutex::new(None);
45
46pub fn register_sender(session_id: SessionId, sender: Sender) {
47    if let Entry::Vacant(entry) = SENDERS
48        .lock()
49        .unwrap()
50        .get_or_insert_with(HashMap::new)
51        .entry(session_id)
52    {
53        entry.insert(sender);
54    }
55}
56
57pub fn unregister_sender(session_id: &SessionId) {
58    if SENDERS
59        .lock()
60        .unwrap()
61        .get_or_insert_with(HashMap::new)
62        .remove(session_id)
63        .is_none()
64    {
65        // TODO: ERROR?
66    }
67}
68
69pub fn sender(session_id: &SessionId) -> Option<Sender> {
70    SENDERS
71        .lock()
72        .unwrap()
73        .get_or_insert_with(HashMap::new)
74        .get(session_id)
75        .cloned()
76}
77
78// TODO: Remove?
79pub fn send(session_id: &SessionId, msg: Box<Message>) -> Result<(), Box<Message>> {
80    if let Some(sender) = sender(session_id) {
81        sender.send(msg).map_err(|msg| msg.body)
82    } else {
83        Err(msg)
84    }
85}
86
87pub fn send_raw(msg: Box<FixtMessage>) -> Result<(), Box<FixtMessage>> {
88    if let Some(sender) = sender(&SessionId::from_input_msg(&msg)) {
89        sender.send_raw(msg)
90    } else {
91        Err(msg)
92    }
93}
94
95async fn first_msg(
96    stream: &mut (impl Stream<Item = InputEvent> + Unpin),
97    logon_timeout: Duration,
98) -> Result<Box<FixtMessage>, Error> {
99    match timeout(logon_timeout, stream.next()).await {
100        Ok(Some(InputEvent::Message(msg))) => Ok(msg),
101        Ok(Some(InputEvent::IoError(error))) => Err(error.into()),
102        Ok(Some(InputEvent::DeserializeError(error))) => {
103            error!("failed to deserialize first message: {error}");
104            Err(Error::SessionError(SessionError::LogonNeverReceived))
105        }
106        _ => Err(Error::SessionError(SessionError::LogonNeverReceived)),
107    }
108}
109
110#[derive(Debug)]
111struct Connection<S> {
112    session: Rc<Session<S>>,
113}
114
115pub(crate) async fn acceptor_connection<S>(
116    reader: impl AsyncRead + Unpin,
117    writer: impl AsyncWrite + Unpin,
118    settings: Settings,
119    sessions: Rc<RefCell<SessionsMap<S>>>,
120    active_sessions: Rc<RefCell<ActiveSessionsMap<S>>>,
121    emitter: Emitter,
122    enabled: Rc<Cell<bool>>,
123) where
124    S: MessagesStorage,
125{
126    let stream = input_stream(reader);
127    let logon_timeout =
128        settings.auto_disconnect_after_no_logon_received + NO_INBOUND_TIMEOUT_PADDING;
129    pin_mut!(stream);
130    let msg = match first_msg(&mut stream, logon_timeout).await {
131        Ok(msg) => msg,
132        Err(err) => {
133            error!(%err, "failed to establish new session");
134            return;
135        }
136    };
137
138    let session_id = SessionId::from_input_msg(&msg);
139    debug!(first_msg = ?msg);
140
141    // XXX: there should be no await point between active_sessions.insert below
142    if !enabled.get() {
143        warn!("Acceptor is disabled, drop connection");
144        return;
145    }
146
147    let (sender, receiver) = mpsc::unbounded_channel();
148    let sender = Sender::new(sender);
149
150    let Some((session_settings, session_state)) = sessions.borrow().get_session(&session_id) else {
151        error!(%session_id, "failed to establish new session: unknown session id");
152        return;
153    };
154    if !session_state.borrow_mut().disconnected()
155        || active_sessions.borrow().contains_key(&session_id)
156    {
157        error!(%session_id, "Session already active");
158        return;
159    }
160    session_state.borrow_mut().set_disconnected(false);
161    register_sender(session_id.clone(), sender.clone());
162    let session = Rc::new(Session::new(
163        settings,
164        session_settings,
165        session_state,
166        sender,
167        emitter.clone(),
168    ));
169
170    active_sessions
171        .borrow_mut()
172        .insert(session_id.clone(), session.clone());
173
174    let session_span = info_span!(
175        parent: None,
176        "session",
177        id = %session_id
178    );
179    session_span.follows_from(Span::current());
180
181    let input_loop_span = info_span!(parent: &session_span, "in");
182    let output_loop_span = info_span!(parent: &session_span, "out");
183
184    let force_disconnection_with_reason = session
185        .on_message_in(msg)
186        .instrument(input_loop_span.clone())
187        .await;
188
189    // TODO: Not here!, send this event when SessionState is created!
190    emitter
191        .send(FixEventInternal::Created(session_id.clone()))
192        .await;
193
194    let input_timeout_duration = session.heartbeat_interval().mul_f32(TEST_REQUEST_THRESHOLD);
195    let input_stream = timeout_stream(input_timeout_duration, stream)
196        .map(|res| res.unwrap_or(InputEvent::Timeout));
197    pin_mut!(input_stream);
198
199    let output_stream = output_stream(session.clone(), session.heartbeat_interval(), receiver);
200    pin_mut!(output_stream);
201
202    let connection = Connection::new(session);
203    let (input_closed_tx, input_closed_rx) = tokio::sync::oneshot::channel();
204
205    tokio::join!(
206        connection
207            .input_loop(
208                input_stream,
209                input_closed_tx,
210                force_disconnection_with_reason
211            )
212            .instrument(input_loop_span),
213        connection
214            .output_loop(writer, output_stream, input_closed_rx)
215            .instrument(output_loop_span),
216    );
217    session_span.in_scope(|| {
218        info!("connection closed");
219    });
220    unregister_sender(&session_id);
221    active_sessions.borrow_mut().remove(&session_id);
222}
223
224pub(crate) async fn initiator_connection<S>(
225    tcp_stream: TcpStream,
226    settings: Settings,
227    session_settings: SessionSettings,
228    state: Rc<RefCell<State<S>>>,
229    active_sessions: Rc<RefCell<ActiveSessionsMap<S>>>,
230    emitter: Emitter,
231) where
232    S: MessagesStorage,
233{
234    let (source, sink) = tcp_stream.into_split();
235    state.borrow_mut().set_disconnected(false);
236    let session_id = session_settings.session_id.clone();
237
238    let (sender, receiver) = mpsc::unbounded_channel();
239    let sender = Sender::new(sender);
240
241    register_sender(session_id.clone(), sender.clone());
242    let session = Rc::new(Session::new(
243        settings,
244        session_settings,
245        state,
246        sender,
247        emitter.clone(),
248    ));
249    active_sessions
250        .borrow_mut()
251        .insert(session_id.clone(), session.clone());
252
253    let session_span = info_span!(
254        "session",
255        id = %session_id
256    );
257
258    let input_loop_span = info_span!(parent: &session_span, "in");
259    let output_loop_span = info_span!(parent: &session_span, "out");
260
261    // TODO: Not here!, send this event when SessionState is created!
262    emitter
263        .send(FixEventInternal::Created(session_id.clone()))
264        .await;
265
266    let input_timeout_duration = session.heartbeat_interval().mul_f32(TEST_REQUEST_THRESHOLD);
267    let input_stream = timeout_stream(input_timeout_duration, input_stream(source))
268        .map(|res| res.unwrap_or(InputEvent::Timeout));
269    pin_mut!(input_stream);
270
271    let output_stream = output_stream(session.clone(), session.heartbeat_interval(), receiver);
272    pin_mut!(output_stream);
273
274    // TODO: It's not so simple, add check if session time is within range,
275    //       if not schedule timer to send logon at proper time
276    session.send_logon_request(&mut session.state().borrow_mut());
277
278    let connection = Connection::new(session);
279    let (input_closed_tx, input_closed_rx) = tokio::sync::oneshot::channel();
280
281    tokio::join!(
282        connection
283            .input_loop(input_stream, input_closed_tx, None)
284            .instrument(input_loop_span),
285        connection
286            .output_loop(sink, output_stream, input_closed_rx)
287            .instrument(output_loop_span),
288    );
289    info!("connection closed");
290    unregister_sender(&session_id);
291    active_sessions.borrow_mut().remove(&session_id);
292}
293
294impl<S: MessagesStorage> Connection<S> {
295    fn new(session: Rc<Session<S>>) -> Connection<S> {
296        Connection { session }
297    }
298
299    async fn input_loop(
300        &self,
301        mut input_stream: impl Stream<Item = InputEvent> + Unpin,
302        input_closed_tx: tokio::sync::oneshot::Sender<()>,
303        force_disconnection_with_reason: Option<DisconnectReason>,
304    ) {
305        if let Some(disconnect_reason) = force_disconnection_with_reason {
306            self.session
307                .disconnect(&mut self.session.state().borrow_mut(), disconnect_reason);
308
309            // Notify output loop that all input is processed so output queue can
310            // be safely closed.
311            // See `fn send()` and `fn send_raw()` from session.rs.
312            input_closed_tx
313                .send(())
314                .expect("Failed to notify about closed inpuot");
315
316            return;
317        }
318
319        let mut disconnect_reason = DisconnectReason::Disconnected;
320        let mut logout_deadline = None;
321
322        let mut next_item = async || {
323            if logout_deadline.is_none() {
324                logout_deadline = self.session.logout_deadline();
325            }
326            if let Some(logout_deadline) = logout_deadline {
327                timeout_at(logout_deadline, input_stream.next())
328                    .await
329                    .unwrap_or(Some(InputEvent::LogoutTimeout))
330            } else {
331                input_stream.next().await
332            }
333        };
334
335        while let Some(event) = next_item().await {
336            // Don't accept new messages if session is disconnected.
337            if self.session.state().borrow().disconnected() {
338                info!("session disconnected, exit input processing");
339                // Notify output loop that all input is processed so output queue can
340                // be safely closed.
341                // See `fn send()` and `fn send_raw()` from session.rs.
342                input_closed_tx
343                    .send(())
344                    .expect("Failed to notify about closed inpout");
345                return;
346            }
347            match event {
348                InputEvent::Message(msg) => {
349                    if let Some(reason) = self.session.on_message_in(msg).await {
350                        info!(?reason, "disconnect, exit input processing");
351                        disconnect_reason = reason;
352                        break;
353                    }
354                }
355                InputEvent::DeserializeError(error) => {
356                    if let Some(reason) = self.session.on_deserialize_error(error).await {
357                        info!(?reason, "disconnect, exit input processing");
358                        disconnect_reason = reason;
359                        break;
360                    }
361                }
362                InputEvent::IoError(error) => {
363                    error!(%error, "Input error");
364                    disconnect_reason = DisconnectReason::IoError;
365                    break;
366                }
367                InputEvent::Timeout => {
368                    if self.session.on_in_timeout().await {
369                        self.session.send_logout(
370                            &mut self.session.state().borrow_mut(),
371                            Some(SessionStatus::SessionLogoutComplete),
372                            Some(FixString::from_ascii_lossy(
373                                b"Grace period is over".to_vec(),
374                            )),
375                        );
376                        break;
377                    }
378                }
379                InputEvent::LogoutTimeout => {
380                    info!("Logout timeout");
381                    disconnect_reason = DisconnectReason::LogoutTimeout;
382                    break;
383                }
384            }
385        }
386        self.session
387            .disconnect(&mut self.session.state().borrow_mut(), disconnect_reason);
388
389        // Notify output loop that all input is processed so output queue can
390        // be safely closed.
391        // See `fn send()` and `fn send_raw()` from session.rs.
392        input_closed_tx
393            .send(())
394            .expect("Failed to notify about closed inpout");
395    }
396
397    async fn output_loop(
398        &self,
399        mut sink: impl AsyncWrite + Unpin,
400        mut output_stream: impl Stream<Item = OutputEvent> + Unpin,
401        input_closed_rx: tokio::sync::oneshot::Receiver<()>,
402    ) {
403        let mut sink_closed = false;
404        let mut disconnect_reason = DisconnectReason::Disconnected;
405        while let Some(event) = output_stream.next().await {
406            match event {
407                OutputEvent::Message(msg) => {
408                    if sink_closed {
409                        // Sink is closed - ignore message, but do not break
410                        // the loop. Output stream has to process all enqueued
411                        // messages to made them available
412                        // for ResendRequest<2>.
413                        info!("Client disconnected, message will be stored for further resend");
414                    } else if let Err(error) = sink.write_all(&msg).await {
415                        sink_closed = true;
416                        error!(%error, "Output write error");
417                        // XXX: Don't disconnect now. If IO error happened
418                        //      here, it will aslo happen in input loop
419                        //      and input loop will trigger disconnection.
420                        //      Disonnection from here would lead to message
421                        //      loss when output queue would be closed
422                        //      and input handler would try to send something.
423                        //
424                        // self.session.disconnect(
425                        //     &mut self.session.state().borrow_mut(),
426                        //     DisconnectReason::IoError,
427                        // );
428                    }
429                }
430                OutputEvent::Timeout => self.session.on_out_timeout().await,
431                OutputEvent::Disconnect(reason) => {
432                    // Internal channel is closed in output stream
433                    // inplementation, at this point no new messages
434                    // can be send.
435                    info!("Client disconnected");
436                    if !sink_closed && let Err(error) = sink.flush().await {
437                        error!(%error, "final flush failed");
438                    }
439                    disconnect_reason = reason;
440                }
441            }
442        }
443        // XXX: Emit logout here instead of Session::disconnect, so `Logout`
444        //      event will be delivered after Logout message instead of
445        //      randomly before or after.
446        self.session.emit_logout(disconnect_reason).await;
447
448        // Don't wait for any specific value it's just notification that
449        // input_loop finished, so no more messages can be added to output
450        // queue.
451        let _ = input_closed_rx.await;
452        if let Err(error) = sink.shutdown().await {
453            error!(%error, "connection shutdown failed")
454        }
455        info!("disconnect, exit output processing");
456    }
457}