easyfix-session 0.11.5

Easy FIX (Financial Information Exchange) toolset - session.
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
use std::{
    cell::{Cell, RefCell},
    collections::HashMap,
    future::Future,
    io,
    net::SocketAddr,
    pin::Pin,
    rc::Rc,
    task::{Context, Poll},
};

use easyfix_messages::fields::{FixString, SeqNum, SessionStatus};
use futures::{self, Stream};
use pin_project::pin_project;
use tokio::{
    io::{AsyncRead, AsyncWrite},
    net::TcpListener,
    task::JoinHandle,
};
use tracing::{Instrument, error, info, info_span, instrument, warn};

use crate::{
    DisconnectReason, Settings,
    application::{AsEvent, Emitter, EventStream, events_channel},
    io::acceptor_connection,
    messages_storage::MessagesStorage,
    session::Session,
    session_id::SessionId,
    session_state::State as SessionState,
    settings::SessionSettings,
};

#[derive(Debug, thiserror::Error)]
pub enum AcceptorError {
    #[error("Unknown session")]
    UnknownSession,
    #[error("Session active")]
    SessionActive,
}

#[allow(async_fn_in_trait)]
pub trait Connection {
    async fn accept(
        &mut self,
    ) -> Result<
        (
            impl AsyncRead + Unpin + 'static,
            impl AsyncWrite + Unpin + 'static,
            SocketAddr,
        ),
        io::Error,
    >;
}

pub struct TcpConnection {
    listener: TcpListener,
}

impl TcpConnection {
    pub async fn new(socket_addr: impl Into<SocketAddr>) -> Result<TcpConnection, io::Error> {
        let socket_addr = socket_addr.into();
        let listener = TcpListener::bind(&socket_addr).await?;
        Ok(TcpConnection { listener })
    }
}

impl Connection for TcpConnection {
    async fn accept(
        &mut self,
    ) -> Result<
        (
            impl AsyncRead + Unpin + 'static,
            impl AsyncWrite + Unpin + 'static,
            SocketAddr,
        ),
        io::Error,
    > {
        let (tcp_stream, peer_addr) = self.listener.accept().await?;
        tcp_stream.set_nodelay(true)?;
        let (reader, writer) = tcp_stream.into_split();
        Ok((reader, writer, peer_addr))
    }
}

type SessionMapInternal<S> = HashMap<SessionId, (SessionSettings, Rc<RefCell<SessionState<S>>>)>;

pub struct SessionsMap<S> {
    map: SessionMapInternal<S>,
    message_storage_builder: Box<dyn Fn(&SessionId) -> S>,
}

impl<S: MessagesStorage> SessionsMap<S> {
    fn new(message_storage_builder: Box<dyn Fn(&SessionId) -> S>) -> SessionsMap<S> {
        SessionsMap {
            map: HashMap::new(),
            message_storage_builder,
        }
    }

    pub fn register_session(&mut self, session_id: SessionId, session_settings: SessionSettings) {
        let storage = (self.message_storage_builder)(&session_id);
        self.map.insert(
            session_id.clone(),
            (
                session_settings,
                Rc::new(RefCell::new(SessionState::new(storage))),
            ),
        );
    }

    pub(crate) fn get_session(
        &self,
        session_id: &SessionId,
    ) -> Option<(SessionSettings, Rc<RefCell<SessionState<S>>>)> {
        self.map.get(session_id).cloned()
    }

    fn contains(&self, session_id: &SessionId) -> bool {
        self.map.contains_key(session_id)
    }
}

pub struct SessionTask<S> {
    settings: Settings,
    sessions: Rc<RefCell<SessionsMap<S>>>,
    active_sessions: Rc<RefCell<ActiveSessionsMap<S>>>,
    emitter: Emitter,
    enabled: Rc<Cell<bool>>,
}

impl<S> Clone for SessionTask<S> {
    fn clone(&self) -> Self {
        Self {
            settings: self.settings.clone(),
            sessions: self.sessions.clone(),
            active_sessions: self.active_sessions.clone(),
            emitter: self.emitter.clone(),
            enabled: self.enabled.clone(),
        }
    }
}

impl<S: MessagesStorage + 'static> SessionTask<S> {
    fn new(
        settings: Settings,
        sessions: Rc<RefCell<SessionsMap<S>>>,
        active_sessions: Rc<RefCell<ActiveSessionsMap<S>>>,
        emitter: Emitter,
        enabled: Rc<Cell<bool>>,
    ) -> SessionTask<S> {
        SessionTask {
            settings,
            sessions,
            active_sessions,
            emitter,
            enabled,
        }
    }

    pub async fn run(
        self,
        peer_addr: SocketAddr,
        reader: impl AsyncRead + Unpin + 'static,
        writer: impl AsyncWrite + Unpin + 'static,
    ) {
        let span = info_span!("connection", %peer_addr);

        span.in_scope(|| {
            info!("New connection");
        });

        if self.enabled.get() {
            acceptor_connection(
                reader,
                writer,
                self.settings,
                self.sessions,
                self.active_sessions,
                self.emitter,
                self.enabled,
            )
            .instrument(span.clone())
            .await;
        } else {
            span.in_scope(|| warn!("Acceptor is disabled"))
        }

        span.in_scope(|| {
            info!("Connection closed");
        });
    }
}

pub(crate) type ActiveSessionsMap<S> = HashMap<SessionId, Rc<Session<S>>>;

#[pin_project]
pub struct Acceptor<S> {
    sessions: Rc<RefCell<SessionsMap<S>>>,
    active_sessions: Rc<RefCell<ActiveSessionsMap<S>>>,
    session_task: SessionTask<S>,
    #[pin]
    event_stream: EventStream,
    enabled: Rc<Cell<bool>>,
}

impl<S: MessagesStorage + 'static> Acceptor<S> {
    pub fn new(
        settings: Settings,
        message_storage_builder: Box<dyn Fn(&SessionId) -> S>,
    ) -> Acceptor<S> {
        let (emitter, event_stream) = events_channel();
        let sessions = Rc::new(RefCell::new(SessionsMap::new(message_storage_builder)));
        let active_sessions = Rc::new(RefCell::new(HashMap::new()));
        let enabled = Rc::new(Cell::new(true));
        let session_task = SessionTask::new(
            settings,
            sessions.clone(),
            active_sessions.clone(),
            emitter,
            enabled.clone(),
        );

        Acceptor {
            sessions,
            active_sessions,
            session_task,
            event_stream,
            enabled,
        }
    }

    pub fn enable(&self) {
        info!("acceptor enabled");
        self.enabled.set(true);
    }

    pub fn disable(&self) {
        info!("acceptor disabled");
        self.enabled.set(false);
        for (_, session) in self.active_sessions.borrow_mut().drain() {
            session.disconnect(
                &mut session.state().borrow_mut(),
                DisconnectReason::ApplicationForcedDisconnect,
            );
        }
    }

    pub fn disable_with_logout(
        &self,
        session_status: Option<SessionStatus>,
        reason: Option<FixString>,
    ) {
        info!("acceptor disabled with logout");
        self.enabled.set(false);
        for (_, session) in self.active_sessions.borrow_mut().drain() {
            let mut state = session.state().borrow_mut();
            session.send_logout(&mut state, session_status, reason.clone());
            session.disconnect(&mut state, DisconnectReason::ApplicationForcedDisconnect);
        }
    }

    pub fn register_session(&mut self, session_id: SessionId, session_settings: SessionSettings) {
        self.sessions
            .borrow_mut()
            .register_session(session_id, session_settings);
    }

    pub fn sessions_map(&self) -> Rc<RefCell<SessionsMap<S>>> {
        self.sessions.clone()
    }

    pub fn start(&self, connection: impl Connection + 'static) -> JoinHandle<()> {
        tokio::task::spawn_local(Self::server_task(connection, self.session_task.clone()))
    }

    pub fn is_session_active(&self, session_id: &SessionId) -> Result<bool, AcceptorError> {
        if self.active_sessions.borrow().contains_key(session_id) {
            Ok(true)
        } else if self.sessions.borrow().contains(session_id) {
            Ok(false)
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    pub fn logout(
        &self,
        session_id: &SessionId,
        session_status: Option<SessionStatus>,
        reason: Option<FixString>,
    ) -> Result<(), AcceptorError> {
        if let Some(session) = self.active_sessions.borrow().get(session_id) {
            session.send_logout(&mut session.state().borrow_mut(), session_status, reason);
            Ok(())
        } else if self.sessions.borrow().contains(session_id) {
            // Already logged out
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    pub fn disconnect(&self, session_id: &SessionId) -> Result<(), AcceptorError> {
        if let Some(session) = self.active_sessions.borrow_mut().remove(session_id) {
            session.disconnect(
                &mut session.state().borrow_mut(),
                DisconnectReason::ApplicationForcedDisconnect,
            );
            Ok(())
        } else if self.sessions.borrow().contains(session_id) {
            // Already disconnected
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    pub fn disconnect_with_logout(
        &self,
        session_id: &SessionId,
        session_status: Option<SessionStatus>,
        reason: Option<FixString>,
    ) -> Result<(), AcceptorError> {
        if let Some(session) = self.active_sessions.borrow().get(session_id) {
            session.send_logout(&mut session.state().borrow_mut(), session_status, reason);
            session.disconnect(
                &mut session.state().borrow_mut(),
                DisconnectReason::ApplicationForcedDisconnect,
            );
            Ok(())
        } else if self.sessions.borrow().contains(session_id) {
            // Already logged out
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    /// Force reset of the session
    ///
    /// Functionally equivalent to `reset_on_logon/logout/disconnect` settings,
    /// but triggered manually.
    ///
    /// Returns [`AcceptorError::SessionActive`] if the session is still active.
    /// In that case, call [Self::disconnect] or [Self::logout] first and wait
    /// for the session to fully terminate before retrying.
    #[instrument(skip_all, fields(session_id=%session_id) ret)]
    pub fn reset(&self, session_id: &SessionId) -> Result<(), AcceptorError> {
        if self.active_sessions.borrow().contains_key(session_id) {
            Err(AcceptorError::SessionActive)
        } else if let Some((_, session_state)) = self.sessions.borrow().get_session(session_id) {
            session_state.borrow_mut().reset();
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    // TODO: temporary solution, remove when diconnect will be synchronized
    #[instrument(skip_all, fields(session_id=%session_id) ret)]
    pub fn force_reset(&self, session_id: &SessionId) -> Result<(), AcceptorError> {
        if let Some(session) = self.active_sessions.borrow().get(session_id) {
            session.state().borrow_mut().reset();
            Ok(())
        } else if let Some((_, session_state)) = self.sessions.borrow().get_session(session_id) {
            session_state.borrow_mut().reset();
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    /// Sender seq_num getter
    #[instrument(skip_all, fields(session_id=%session_id) ret)]
    pub fn next_sender_msg_seq_num(&self, session_id: &SessionId) -> Result<SeqNum, AcceptorError> {
        if let Some(session) = self.active_sessions.borrow().get(session_id) {
            Ok(session.state().borrow().next_sender_msg_seq_num())
        } else if let Some((_, session_state)) = self.sessions.borrow().get_session(session_id) {
            Ok(session_state.borrow().next_sender_msg_seq_num())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    /// Override sender's next seq_num
    #[instrument(skip_all, fields(session_id=%session_id, seq_num) ret)]
    pub fn set_next_sender_msg_seq_num(
        &self,
        session_id: &SessionId,
        seq_num: SeqNum,
    ) -> Result<(), AcceptorError> {
        if let Some(session) = self.active_sessions.borrow().get(session_id) {
            session
                .state()
                .borrow_mut()
                .set_next_sender_msg_seq_num(seq_num);
            Ok(())
        } else if let Some((_, session_state)) = self.sessions.borrow().get_session(session_id) {
            session_state
                .borrow_mut()
                .set_next_sender_msg_seq_num(seq_num);
            Ok(())
        } else {
            Err(AcceptorError::UnknownSession)
        }
    }

    async fn server_task(mut connection: impl Connection, session_task: SessionTask<S>) {
        info!("Acceptor started");
        loop {
            match connection.accept().await {
                Ok((reader, writer, peer_addr)) => {
                    tokio::task::spawn_local(session_task.clone().run(peer_addr, reader, writer));
                }
                Err(err) => error!("server task failed to accept incoming connection: {err}"),
            }
        }
    }

    pub fn session_task(&self) -> SessionTask<S> {
        self.session_task.clone()
    }

    pub fn run_session_task(
        &self,
        peer_addr: SocketAddr,
        reader: impl AsyncRead + Unpin + 'static,
        writer: impl AsyncWrite + Unpin + 'static,
    ) -> impl Future<Output = ()> {
        self.session_task.clone().run(peer_addr, reader, writer)
    }
}

impl<S: MessagesStorage> Stream for Acceptor<S> {
    type Item = impl AsEvent;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.event_stream).poll_next(cx)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.event_stream.size_hint()
    }
}