fixer 0.11.0

A full featured messaging engine for the FIX protocol implemented in 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
use crate::{
    application::Application,
    config,
    connection::{read_loop, write_loop},
    log::{LogEnum, LogFactoryEnum},
    message::Message,
    parser::Parser,
    registry::{lookup_session_registration_flexible, unregister_session},
    session::{
        AdminEnum, Connect, FixIn, Session, StopReq, factory::SessionFactory,
        session_id::SessionID, settings::SessionSettings,
    },
    settings::Settings,
    store::MessageStoreFactoryEnum,
    tag::{
        TAG_BEGIN_STRING, TAG_SENDER_COMP_ID, TAG_SENDER_LOCATION_ID, TAG_SENDER_SUB_ID,
        TAG_TARGET_COMP_ID, TAG_TARGET_LOCATION_ID, TAG_TARGET_SUB_ID,
    },
    tls,
};
use simple_error::SimpleResult;
use std::{
    net::SocketAddr,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};
use tokio::{
    io::BufReader,
    net::TcpListener,
    sync::{mpsc, mpsc::UnboundedSender, watch},
    task::JoinHandle,
};

/// `ConnectionValidator` is a trait allowing custom authentication logic for
/// incoming connections. For example, you may tie a `SenderCompID` to an IP range.
///
/// Validates incoming connections before they are associated with a session.
pub trait ConnectionValidator: Send + Sync + 'static {
    /// Validate the connection. Return `Ok(())` to accept, `Err` to reject.
    fn validate(&self, remote_addr: SocketAddr, session_id: &SessionID) -> SimpleResult<()>;
}

/// Callback that creates a `TcpListener` for a given address. This allows
/// callers to customize how the listener is created (e.g., set socket options,
/// use Unix sockets, etc.).
pub type NewListenerCallback =
    Box<dyn Fn(&str) -> std::pin::Pin<Box<dyn std::future::Future<Output = SimpleResult<TcpListener>> + Send>> + Send + Sync>;

// DynSessionCreator type-erases the Application generic so the Acceptor can
// create dynamic sessions without being generic itself.
trait DynSessionCreator: Send + Sync {
    fn create_session<'a>(
        &'a self,
        session_id: Arc<SessionID>,
        settings: &'a SessionSettings,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = SimpleResult<Session>> + Send + 'a>>;
}

struct SessionCreator {
    factory: SessionFactory,
    store_factory: MessageStoreFactoryEnum,
    log_factory: LogFactoryEnum,
    app: Arc<dyn Application>,
}

impl DynSessionCreator for SessionCreator {
    fn create_session<'a>(
        &'a self,
        session_id: Arc<SessionID>,
        settings: &'a SessionSettings,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = SimpleResult<Session>> + Send + 'a>>
    {
        Box::pin(async move {
            self.factory
                .create_session(
                    session_id,
                    self.store_factory.clone(),
                    settings,
                    self.log_factory.clone(),
                    self.app.clone(),
                )
                .await
        })
    }
}

struct SessionHandle {
    session: Option<Session>,
    admin_tx: UnboundedSender<AdminEnum>,
    session_id: Arc<SessionID>,
}

/// A FIX server that listens for inbound connections.
///
/// The `Acceptor` binds a TCP (or TLS) listener and waits for remote FIX
/// clients to connect. Each incoming connection is matched to a pre-configured
/// session by swapping the `SenderCompID` / `TargetCompID` from the first
/// message received on the wire.
///
/// # Lifecycle
///
/// ```text
/// Acceptor::new(app, store, settings, log)   // parse config, create sessions
///     .start()                                // bind listener, begin accepting
///     ...                                     // sessions exchange messages
///     .stop()                                 // graceful shutdown
/// ```
///
/// # Dynamic Sessions
///
/// When `DynamicSessions=Y` is set in the global config, connections from
/// unknown counterparties automatically create sessions on-the-fly using the
/// global settings. Set `DynamicQualifier=Y` to assign unique qualifiers so
/// multiple connections from the same `SenderCompID`/`TargetCompID` pair get
/// separate sessions.
///
/// # TLS
///
/// TLS is enabled by setting `SocketUseSSL=Y` along with
/// `SocketCertificateFile` and `SocketPrivateKeyFile` in the config, or by
/// calling [`set_tls_config`](Acceptor::set_tls_config) with a pre-built
/// [`TlsAcceptor`](tokio_rustls::TlsAcceptor) before `start()`.
///
/// # Example
///
/// ```rust,no_run
/// # use fixer::{
/// #     acceptor::Acceptor,
/// #     application::Application,
/// #     errors::MessageRejectErrorResult,
/// #     log::screen_log::ScreenLogFactory,
/// #     message::Message,
/// #     session::session_id::SessionID,
/// #     settings::Settings,
/// #     store::MemoryStoreFactory,
/// # };
/// # use simple_error::SimpleResult;
/// # use std::sync::Arc;
/// # use tokio::io::BufReader;
/// # struct MyApp;
/// # impl Application for MyApp {
/// #     fn on_create(&self, _: &Arc<SessionID>) {}
/// #     fn on_logon(&self, _: &Arc<SessionID>) {}
/// #     fn on_logout(&self, _: &Arc<SessionID>) {}
/// #     fn to_admin(&self, _: &mut Message, _: &Arc<SessionID>) {}
/// #     fn to_app(&self, _: &mut Message, _: &Arc<SessionID>) -> SimpleResult<()> { Ok(()) }
/// #     fn from_admin(&self, _: &Message, _: &Arc<SessionID>) -> MessageRejectErrorResult { Ok(()) }
/// #     fn from_app(&self, _: &Message, _: &Arc<SessionID>) -> MessageRejectErrorResult { Ok(()) }
/// # }
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let cfg = "\
/// [DEFAULT]
/// SocketAcceptPort=5001
/// SenderCompID=SERVER
/// TargetCompID=CLIENT
/// ResetOnLogon=Y
///
/// [SESSION]
/// BeginString=FIX.4.2
/// ";
/// let settings = Settings::parse(BufReader::new(cfg.as_bytes())).await?;
/// let app: Arc<dyn Application> = Arc::new(MyApp);
///
/// let mut acceptor = Acceptor::new(
///     app,
///     MemoryStoreFactory::new(),
///     settings,
///     ScreenLogFactory::new(),
/// ).await?;
///
/// acceptor.start().await?;
/// println!("Listening on {:?}", acceptor.local_address());
///
/// tokio::signal::ctrl_c().await?;
/// acceptor.stop().await;
/// # Ok(())
/// # }
/// ```
#[allow(clippy::struct_field_names)]
pub struct Acceptor {
    sessions: Vec<SessionHandle>,
    stop_tx: watch::Sender<bool>,
    stop_rx: watch::Receiver<bool>,
    task_handles: Vec<JoinHandle<()>>,
    listen_address: String,
    local_address: Option<SocketAddr>,
    connection_validator: Option<Arc<dyn ConnectionValidator>>,
    dynamic_sessions: bool,
    dynamic_qualifier: bool,
    dynamic_qualifier_count: Arc<AtomicUsize>,
    dynamic_session_tx: Option<mpsc::UnboundedSender<Session>>,
    session_creator: Arc<dyn DynSessionCreator>,
    global_settings: SessionSettings,
    tls_acceptor: Option<tokio_rustls::TlsAcceptor>,
    new_listener_callback: Option<Arc<NewListenerCallback>>,
}

impl Acceptor {
    /// Creates a new `Acceptor` from the given components.
    ///
    /// Parses `SocketAcceptPort` (required) and `SocketAcceptHost` (optional,
    /// defaults to `0.0.0.0`) from the global settings. Creates one session per
    /// `[SESSION]` block and registers them in the global session registry.
    ///
    /// Does **not** start listening — call [`start`](Acceptor::start) for that.
    pub async fn new(
        app: Arc<dyn Application>,
        store_factory: MessageStoreFactoryEnum,
        mut settings: Settings,
        log_factory: LogFactoryEnum,
    ) -> SimpleResult<Self> {
        let factory = SessionFactory {
            build_initiators: false,
        };

        // Determine listen address from global settings
        let global = settings
            .global_settings()
            .await
            .ok_or_else(|| simple_error!("no global settings"))?;
        let host = global
            .setting(config::SOCKET_ACCEPT_HOST)
            .unwrap_or_default();
        let port = global
            .setting(config::SOCKET_ACCEPT_PORT)
            .map_err(|e| simple_error!("SocketAcceptPort is required: {}", e))?;
        let listen_address = if host.is_empty() {
            format!("0.0.0.0:{port}")
        } else {
            format!("{host}:{port}")
        };

        // Load TLS config from global settings
        let tls_acceptor = tls::load_tls_acceptor(&global).await?;

        // Read dynamic sessions config
        let dynamic_sessions = if global.has_setting(config::DYNAMIC_SESSIONS) {
            global
                .bool_setting(config::DYNAMIC_SESSIONS)
                .unwrap_or(false)
        } else {
            false
        };
        let dynamic_qualifier = if global.has_setting(config::DYNAMIC_QUALIFIER) {
            global
                .bool_setting(config::DYNAMIC_QUALIFIER)
                .unwrap_or(false)
        } else {
            false
        };

        let global_settings = global;

        let mut sessions = Vec::new();
        let session_settings = settings.session_settings().await;

        for entry in &session_settings {
            let (session_id, ss) = entry.pair();
            let session = factory
                .create_session(
                    session_id.clone(),
                    store_factory.clone(),
                    ss,
                    log_factory.clone(),
                    app.clone(),
                )
                .await?;

            let admin_tx = session.admin.tx.clone();
            let sid = session.session_id.clone();

            sessions.push(SessionHandle {
                session: Some(session),
                admin_tx,
                session_id: sid,
            });
        }

        let (stop_tx, stop_rx) = watch::channel(false);

        let session_creator: Arc<dyn DynSessionCreator> = Arc::new(SessionCreator {
            factory,
            store_factory,
            log_factory,
            app,
        });

        Ok(Acceptor {
            sessions,
            stop_tx,
            stop_rx,
            task_handles: Vec::new(),
            listen_address,
            local_address: None,
            connection_validator: None,
            dynamic_sessions,
            dynamic_qualifier,
            dynamic_qualifier_count: Arc::new(AtomicUsize::new(0)),
            dynamic_session_tx: None,
            session_creator,
            global_settings,
            tls_acceptor,
            new_listener_callback: None,
        })
    }

    /// Binds the TCP listener and begins accepting connections.
    ///
    /// Each pre-configured session's `run()` loop is spawned as a background
    /// task. Incoming connections are matched to sessions by parsing the first
    /// FIX message. Must only be called once.
    pub async fn start(&mut self) -> SimpleResult<()> {
        // Start session.run() for all sessions — each task owns its Session
        for handle in &mut self.sessions {
            let mut session = handle
                .session
                .take()
                .expect("Acceptor::start() called more than once");
            let run_handle = tokio::spawn(async move {
                session.run().await;
            });
            self.task_handles.push(run_handle);
        }

        // Start dynamic sessions loop if enabled
        if self.dynamic_sessions {
            let (tx, rx) = mpsc::unbounded_channel::<Session>();
            self.dynamic_session_tx = Some(tx);

            let dynamic_handle = tokio::spawn(dynamic_sessions_loop(rx));
            self.task_handles.push(dynamic_handle);
        }

        // Bind TCP listener (use custom callback if set)
        let listener = if let Some(ref cb) = self.new_listener_callback {
            cb(&self.listen_address).await?
        } else {
            TcpListener::bind(&self.listen_address)
                .await
                .map_err(|e| simple_error!("failed to bind {}: {}", self.listen_address, e))?
        };

        self.local_address = listener.local_addr().ok();

        let mut stop_rx = self.stop_rx.clone();
        let validator = self.connection_validator.clone();
        let dynamic_ctx = if self.dynamic_sessions {
            Some(Arc::new(DynamicContext {
                session_creator: self.session_creator.clone(),
                global_settings: self.global_settings.clone(),
                dynamic_qualifier: self.dynamic_qualifier,
                qualifier_count: self.dynamic_qualifier_count.clone(),
                dynamic_session_tx: self.dynamic_session_tx.clone().unwrap(),
            }))
        } else {
            None
        };

        let tls_acceptor = self.tls_acceptor.clone();

        // Spawn accept loop
        let accept_handle = tokio::spawn(async move {
            loop {
                tokio::select! {
                    accept_result = listener.accept() => {
                        if let Ok((stream, remote_addr)) = accept_result {
                            let validator = validator.clone();
                            let dynamic_ctx = dynamic_ctx.clone();
                            let tls_acceptor = tls_acceptor.clone();
                            tokio::spawn(async move {
                                if let Some(tls_acceptor) = tls_acceptor {
                                    if let Ok(tls_stream) = tls_acceptor.accept(stream).await {
                                        let (read_half, write_half) = tokio::io::split(tls_stream);
                                        handle_connection(remote_addr, read_half, write_half, validator, dynamic_ctx).await;
                                    }
                                } else {
                                    let (read_half, write_half) = tokio::io::split(stream);
                                    handle_connection(remote_addr, read_half, write_half, validator, dynamic_ctx).await;
                                }
                            });
                        }
                    }
                    _ = stop_rx.changed() => {
                        break;
                    }
                }
            }
        });

        self.task_handles.push(accept_handle);
        Ok(())
    }

    /// Gracefully shuts down the acceptor.
    ///
    /// Stops the accept loop, sends a stop signal to every session, waits for
    /// all background tasks to complete, and unregisters sessions from the
    /// global registry so the acceptor can be recreated without duplicate
    /// session errors.
    pub async fn stop(&mut self) {
        // Signal accept loop to stop
        let _ = self.stop_tx.send(true);

        // Close dynamic session channel to signal the loop to shut down
        if self.dynamic_sessions {
            self.dynamic_session_tx.take();
        }

        // Stop all sessions
        for handle in &self.sessions {
            let _ = handle.admin_tx.send(AdminEnum::StopReq(StopReq));
        }

        // Wait for all tasks
        for task in self.task_handles.drain(..) {
            let _ = task.await;
        }

        // Unregister all sessions from the global registry so that
        // restarting does not cause duplicate session errors.
        for handle in &self.sessions {
            let _ = unregister_session(&handle.session_id);
        }
    }

    /// Sets an optional connection validator for custom authentication logic.
    /// To remove a previously set validator, pass `None`.
    pub fn set_connection_validator(&mut self, validator: Option<Arc<dyn ConnectionValidator>>) {
        self.connection_validator = validator;
    }

    /// Sets a custom TLS configuration for the acceptor. When set, this takes
    /// precedence over TLS settings from the config file (`SocketCertificateFile`,
    /// `SocketPrivateKeyFile`, etc.). Must be called before `start()`.
    pub fn set_tls_config(&mut self, tls_acceptor: tokio_rustls::TlsAcceptor) {
        self.tls_acceptor = Some(tls_acceptor);
    }

    /// Sets a custom listener callback that controls how the TCP listener is
    /// created. This allows callers to customize socket options, use Unix
    /// sockets, or apply other custom configurations. Must be called before
    /// `start()`.
    pub fn set_new_listener_callback(&mut self, cb: NewListenerCallback) {
        self.new_listener_callback = Some(Arc::new(cb));
    }

    /// Returns the actual bound address after [`start`](Acceptor::start).
    ///
    /// Useful when binding to port 0 to discover the OS-assigned port.
    /// Returns `None` before `start()` is called.
    pub fn local_address(&self) -> Option<SocketAddr> {
        self.local_address
    }
}

struct DynamicContext {
    session_creator: Arc<dyn DynSessionCreator>,
    global_settings: SessionSettings,
    dynamic_qualifier: bool,
    qualifier_count: Arc<AtomicUsize>,
    dynamic_session_tx: mpsc::UnboundedSender<Session>,
}

// handle_connection reads the first FIX message from an incoming connection
// (plain TCP or TLS), identifies the session (sender/target swapped), optionally
// validates via ConnectionValidator, wires up channels, and runs read_loop/write_loop
// until disconnect. If the session is not found and dynamic sessions are enabled,
// creates a new session on-the-fly.
//
// Generic over R/W so it works with both plain TCP and TLS streams.
async fn handle_connection<R, W>(
    remote_addr: SocketAddr,
    read_half: R,
    write_half: W,
    validator: Option<Arc<dyn ConnectionValidator>>,
    dynamic_ctx: Option<Arc<DynamicContext>>,
) where
    R: tokio::io::AsyncRead + Unpin + Send + 'static,
    W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    let buf_reader = BufReader::new(read_half);
    let mut parser = Parser::new(buf_reader);

    // Read the first message to identify the session
    let Ok(first_msg_bytes) = parser.read_message().await else {
        return;
    };

    // Parse to extract session identification fields
    let mut msg = Message::default();
    if let Err(_e) = msg.parse_message(&first_msg_bytes) {
        return;
    }

    // Extract fields from the incoming message header
    let Ok(begin_string) = msg.header.get_string(TAG_BEGIN_STRING) else {
        return;
    };
    let Ok(sender_comp_id) = msg.header.get_string(TAG_SENDER_COMP_ID) else {
        return;
    };
    let Ok(target_comp_id) = msg.header.get_string(TAG_TARGET_COMP_ID) else {
        return;
    };

    // Optional sub/location IDs
    let sender_sub_id = msg.header.get_string(TAG_SENDER_SUB_ID).unwrap_or_default();
    let sender_location_id = msg
        .header
        .get_string(TAG_SENDER_LOCATION_ID)
        .unwrap_or_default();
    let target_sub_id = msg.header.get_string(TAG_TARGET_SUB_ID).unwrap_or_default();
    let target_location_id = msg
        .header
        .get_string(TAG_TARGET_LOCATION_ID)
        .unwrap_or_default();

    // IMPORTANT: Swap sender/target for session lookup.
    // The incoming message's SenderCompID is the remote peer — our TargetCompID.
    // The incoming message's TargetCompID is us — our SenderCompID.
    let qualifier = if let Some(ref ctx) = dynamic_ctx {
        if ctx.dynamic_qualifier {
            let count = ctx.qualifier_count.fetch_add(1, Ordering::SeqCst) + 1;
            count.to_string()
        } else {
            String::new()
        }
    } else {
        String::new()
    };

    let session_id = Arc::new(SessionID {
        begin_string,
        sender_comp_id: target_comp_id,
        sender_sub_id: target_sub_id,
        sender_location_id: target_location_id,
        target_comp_id: sender_comp_id,
        target_sub_id: sender_sub_id,
        target_location_id: sender_location_id,
        qualifier,
    });

    // Validate the connection if a validator is configured.
    // This runs after session ID is determined but before session lookup,
    // matching the expected placement in the connection lifecycle.
    if let Some(ref validator) = validator
        && validator.validate(remote_addr, &session_id).is_err() {
            return;
        }

    // Look up the session's admin channel in the global registry, or create a dynamic session.
    // Use flexible lookup so that sessions with a SessionQualifier (e.g. FIXT.1.1 sessions)
    // can be found even though the incoming connection doesn't carry a qualifier.
    let is_dynamic;
    let (admin_tx, in_chan_capacity) =
        if let Some((_matched_id, reg)) = lookup_session_registration_flexible(&session_id) {
            is_dynamic = false;
            (reg.admin_tx, reg.in_chan_capacity)
        } else {
            // Session not found — try dynamic session creation
            let Some(ref ctx) = dynamic_ctx else {
                return;
            };
            let Ok(session) = ctx
                .session_creator
                .create_session(session_id.clone(), &ctx.global_settings)
                .await
            else {
                return;
            };
            // Clone admin_tx and read capacity before moving the owned session
            let tx = session.admin.tx.clone();
            let cap = session.session_settings.in_chan_capacity;
            let _ = ctx.dynamic_session_tx.send(session);
            is_dynamic = true;
            (tx, cap)
        };

    // Create channels for this connection
    let (msg_out_tx, msg_out_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(crate::session::DEFAULT_MSG_OUT_CAPACITY);
    let cap = if in_chan_capacity > 0 {
        in_chan_capacity
    } else {
        1 // tokio::mpsc::channel requires capacity >= 1
    };
    let (msg_in_tx, msg_in_rx) = tokio::sync::mpsc::channel::<FixIn>(cap);
    let (err_tx, mut err_rx) = tokio::sync::mpsc::unbounded_channel::<SimpleResult<()>>();

    // Send Connect to the session
    let _ = admin_tx.send(AdminEnum::Connect(Connect {
        message_out: msg_out_tx,
        message_in: msg_in_rx,
        err: err_tx,
    }));

    // Wait for connect acknowledgement
    if let Some(result) = err_rx.recv().await
        && result.is_err() {
            return;
        }

    // Re-inject the first message (the parser consumed it, but the session needs to process it)
    let _ = msg_in_tx
        .send(FixIn {
            bytes: first_msg_bytes,
            receive_time: jiff::Timestamp::now(),
        })
        .await;

    // Spawn read_loop and write_loop
    let read_task = tokio::spawn(async move { read_loop(parser, msg_in_tx).await });
    let write_task =
        tokio::spawn(async move { write_loop(write_half, msg_out_rx, LogEnum::default()).await });

    // Get abort handles before moving into select!
    let read_abort = read_task.abort_handle();
    let write_abort = write_task.abort_handle();

    // Wait for either loop to finish, then abort the other to close the TCP connection.
    // Both halves of the split TcpStream must be dropped to fully close the connection.
    tokio::select! {
        _ = read_task => {
            write_abort.abort();
        },
        _ = write_task => {
            read_abort.abort();
        },
    }

    // Stop dynamic sessions when the connection handler returns,
    // equivalent to Go's `defer session.stop()`.
    if is_dynamic {
        let _ = admin_tx.send(AdminEnum::StopReq(StopReq));
    }
}

// dynamic_sessions_loop manages the lifecycle of dynamically created sessions.
// It receives sessions via channel, spawns their run() loop, and unregisters
// them from the global registry when they complete. Equivalent to Go's
// Acceptor.dynamicSessionsLoop().
async fn dynamic_sessions_loop(mut rx: mpsc::UnboundedReceiver<Session>) {
    let mut run_handles: Vec<JoinHandle<()>> = Vec::new();

    // Receive dynamic sessions until the channel is closed (Acceptor::stop)
    while let Some(mut session) = rx.recv().await {
        let session_id = session.session_id.clone();
        let handle = tokio::spawn(async move {
            // Run the session — fully owned, no mutex
            session.run().await;

            // Unregister from the global registry after run() completes
            let _ = unregister_session(&session_id);
        });
        run_handles.push(handle);
    }

    // Channel closed — stop all remaining dynamic sessions and wait for completion
    // (The connection handler already sent StopReq via admin_tx, so run() will
    // eventually return. We just need to wait.)
    for handle in run_handles {
        let _ = handle.await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The address a test client connects to. The acceptor listens on the
    /// unspecified address (0.0.0.0 / ::), and connecting *to* that works on
    /// Linux but fails on Windows with WSAEADDRNOTAVAIL (10049) - so use
    /// loopback with the same port.
    fn connectable(addr: std::net::SocketAddr) -> std::net::SocketAddr {
        let mut addr = addr;
        if addr.ip().is_unspecified() {
            addr.set_ip(match addr.ip() {
                std::net::IpAddr::V4(_) => std::net::Ipv4Addr::LOCALHOST.into(),
                std::net::IpAddr::V6(_) => std::net::Ipv6Addr::LOCALHOST.into(),
            });
        }
        addr
    }
    use crate::application::NOPApp;
    use crate::log::LogFactoryEnum;
    use crate::registry::{SESSIONS, lookup_admin_tx, unregister_session};
    use crate::session::session_id::SessionID;
    use crate::store::MessageStoreFactoryEnum;
    use serial_test::serial;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tokio::io::BufReader;
    use tokio::net::TcpStream;

    fn clean_sessions() {
        let keys: Vec<_> = SESSIONS.iter().map(|e| e.key().clone()).collect();
        for key in keys {
            let _ = unregister_session(&key);
        }
    }

    /// Build a valid FIX logon message with current UTC timestamp and correct checksum.
    fn make_logon_msg(sender: &str, target: &str) -> Vec<u8> {
        let now = jiff::Timestamp::now();
        let ts = now.strftime("%Y%m%d-%H:%M:%S");
        // Build body (everything between BeginString and CheckSum)
        let body = format!(
            "35=A\x0149={sender}\x0156={target}\x0134=1\x0152={ts}\x0198=0\x01108=30\x01"
        );
        let body_len = body.len();
        // Partial message (before checksum)
        let partial = format!("8=FIX.4.2\x019={body_len}\x01{body}");
        // Compute checksum (sum of all bytes mod 256)
        let checksum: u32 = partial.bytes().map(u32::from).sum::<u32>() % 256;
        format!("{partial}10={checksum:03}\x01").into_bytes()
    }

    async fn make_acceptor_settings(port: &str) -> Settings {
        let cfg = format!(
            r"
[DEFAULT]
SocketAcceptPort={port}

[SESSION]
BeginString=FIX.4.2
SenderCompID=ACCEPTOR
TargetCompID=INITIATOR
"
        );
        Settings::parse(BufReader::new(cfg.as_bytes()))
            .await
            .unwrap()
    }

    // Verifies that Acceptor::start() binds a listener and Acceptor::stop() shuts down cleanly.
    #[tokio::test]
    #[serial]
    async fn test_acceptor_start() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .expect("Acceptor::new should succeed");

        assert_eq!(1, acceptor.sessions.len(), "should have 1 session");

        acceptor
            .start()
            .await
            .expect("Acceptor::start should succeed");

        let local_addr = acceptor.local_address();
        assert!(local_addr.is_some(), "should have a bound local address");
        assert_ne!(0, local_addr.unwrap().port(), "port should be assigned");

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that Acceptor::new() fails when SocketAcceptPort is missing.
    #[tokio::test]
    #[serial]
    async fn test_acceptor_new_requires_accept_port() {
        clean_sessions();

        let cfg = r"
[DEFAULT]

[SESSION]
BeginString=FIX.4.2
SenderCompID=ACCEPTOR
TargetCompID=INITIATOR
";
        let settings = Settings::parse(BufReader::new(cfg.as_bytes()))
            .await
            .unwrap();
        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();

        let result = Acceptor::new(app, store_factory, settings, log_factory).await;
        assert!(result.is_err(), "should fail without SocketAcceptPort");

        clean_sessions();
    }

    // Verifies that an incoming TCP connection with a valid FIX logon message
    // is matched to the correct session (sender/target swapped).
    #[tokio::test]
    #[serial]
    async fn test_acceptor_session_identification() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        acceptor.start().await.unwrap();

        let addr = connectable(acceptor.local_address().unwrap());

        // Connect as a client and send a FIX logon message.
        // The message's SenderCompID=INITIATOR (the remote peer)
        // and TargetCompID=ACCEPTOR (us).
        // The acceptor should swap these to look up session with
        // SenderCompID=ACCEPTOR, TargetCompID=INITIATOR.
        let logon_msg = make_logon_msg("INITIATOR", "ACCEPTOR");

        let mut stream = TcpStream::connect(addr).await.expect("should connect");
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .expect("should write logon");

        // Give the acceptor time to process the connection
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // Drop the client connection
        drop(stream);
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        acceptor.stop().await;
        clean_sessions();
    }

    // A validator that rejects all connections.
    struct RejectAllValidator {
        called: AtomicBool,
    }

    impl ConnectionValidator for RejectAllValidator {
        fn validate(&self, _remote_addr: SocketAddr, _session_id: &SessionID) -> SimpleResult<()> {
            self.called.store(true, Ordering::SeqCst);
            Err(simple_error!("connection rejected"))
        }
    }

    // A validator that accepts all connections.
    struct AcceptAllValidator {
        called: AtomicBool,
    }

    impl ConnectionValidator for AcceptAllValidator {
        fn validate(&self, _remote_addr: SocketAddr, _session_id: &SessionID) -> SimpleResult<()> {
            self.called.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    // Verifies that a ConnectionValidator that rejects causes the connection to be dropped.
    #[tokio::test]
    #[serial]
    async fn test_connection_validator_rejects() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        let validator = Arc::new(RejectAllValidator {
            called: AtomicBool::new(false),
        });
        acceptor.set_connection_validator(Some(validator.clone()));

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Send a valid FIX logon — the validator should reject it.
        let logon_msg = make_logon_msg("INITIATOR", "ACCEPTOR");
        let mut stream = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        assert!(
            validator.called.load(Ordering::SeqCst),
            "validator should have been called"
        );

        drop(stream);
        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that a ConnectionValidator that accepts allows the connection through.
    #[tokio::test]
    #[serial]
    async fn test_connection_validator_accepts() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        let validator = Arc::new(AcceptAllValidator {
            called: AtomicBool::new(false),
        });
        acceptor.set_connection_validator(Some(validator.clone()));

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        let logon_msg = make_logon_msg("INITIATOR", "ACCEPTOR");
        let mut stream = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        assert!(
            validator.called.load(Ordering::SeqCst),
            "validator should have been called"
        );

        drop(stream);
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies set_connection_validator with None removes the validator.
    #[tokio::test]
    #[serial]
    async fn test_set_connection_validator_none() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        // Set then remove validator
        let validator = Arc::new(RejectAllValidator {
            called: AtomicBool::new(false),
        });
        acceptor.set_connection_validator(Some(validator.clone()));
        acceptor.set_connection_validator(None);

        assert!(acceptor.connection_validator.is_none());

        acceptor.stop().await;
        clean_sessions();
    }

    async fn make_dynamic_acceptor_settings(port: &str, dynamic_qualifier: bool) -> Settings {
        let dq = if dynamic_qualifier {
            "DynamicQualifier=Y\n"
        } else {
            ""
        };
        let cfg = format!(
            r"
[DEFAULT]
SocketAcceptPort={port}
DynamicSessions=Y
{dq}
[SESSION]
BeginString=FIX.4.2
SenderCompID=ACCEPTOR
TargetCompID=INITIATOR
"
        );
        Settings::parse(BufReader::new(cfg.as_bytes()))
            .await
            .unwrap()
    }

    // Verifies that DynamicSessions=Y config is read correctly.
    #[tokio::test]
    #[serial]
    async fn test_dynamic_sessions_config() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_dynamic_acceptor_settings("0", false).await;

        let acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        assert!(acceptor.dynamic_sessions, "dynamic_sessions should be true");
        assert!(
            !acceptor.dynamic_qualifier,
            "dynamic_qualifier should be false"
        );

        clean_sessions();
    }

    // Verifies that a connection from an unknown session is accepted when
    // DynamicSessions=Y, creating a session on-the-fly.
    #[tokio::test]
    #[serial]
    async fn test_dynamic_session_creation() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_dynamic_acceptor_settings("0", false).await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Send a logon from an UNKNOWN session (SENDER2/TARGET2).
        // This session is not pre-configured, so it should be created dynamically.
        let logon_msg = make_logon_msg("SENDER2", "TARGET2");
        let mut stream = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        // The dynamic session should have been registered with swapped IDs:
        // SenderCompID=TARGET2 (us), TargetCompID=SENDER2 (them)
        let dynamic_id = Arc::new(SessionID {
            begin_string: "FIX.4.2".to_string(),
            sender_comp_id: "TARGET2".to_string(),
            sender_sub_id: String::new(),
            sender_location_id: String::new(),
            target_comp_id: "SENDER2".to_string(),
            target_sub_id: String::new(),
            target_location_id: String::new(),
            qualifier: String::new(),
        });
        assert!(
            lookup_admin_tx(&dynamic_id).is_some(),
            "dynamic session should be registered"
        );

        drop(stream);
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that DynamicQualifier=Y assigns unique qualifiers to dynamic sessions.
    #[tokio::test]
    #[serial]
    async fn test_dynamic_qualifier() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_dynamic_acceptor_settings("0", true).await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Two connections from the same unknown session — each should get a unique qualifier.
        let logon_msg = make_logon_msg("SENDER2", "TARGET2");

        let mut stream1 = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream1, &logon_msg)
            .await
            .unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        let mut stream2 = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream2, &logon_msg)
            .await
            .unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        // Both should be registered with different qualifiers
        let id1 = Arc::new(SessionID {
            begin_string: "FIX.4.2".to_string(),
            sender_comp_id: "TARGET2".to_string(),
            sender_sub_id: String::new(),
            sender_location_id: String::new(),
            target_comp_id: "SENDER2".to_string(),
            target_sub_id: String::new(),
            target_location_id: String::new(),
            qualifier: "1".to_string(),
        });
        let id2 = Arc::new(SessionID {
            begin_string: "FIX.4.2".to_string(),
            sender_comp_id: "TARGET2".to_string(),
            sender_sub_id: String::new(),
            sender_location_id: String::new(),
            target_comp_id: "SENDER2".to_string(),
            target_sub_id: String::new(),
            target_location_id: String::new(),
            qualifier: "2".to_string(),
        });

        assert!(
            lookup_admin_tx(&id1).is_some(),
            "first dynamic session (qualifier=1) should exist"
        );
        assert!(
            lookup_admin_tx(&id2).is_some(),
            "second dynamic session (qualifier=2) should exist"
        );

        drop(stream1);
        drop(stream2);
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that when DynamicSessions is not enabled, unknown sessions are rejected.
    #[tokio::test]
    #[serial]
    async fn test_no_dynamic_sessions_rejects_unknown() {
        clean_sessions();

        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        // Use standard settings (no DynamicSessions)
        let settings = make_acceptor_settings("0").await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        assert!(!acceptor.dynamic_sessions);

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Send a logon from an unknown session — should be silently rejected.
        let logon_msg = make_logon_msg("SENDER2", "TARGET2");
        let mut stream = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        let unknown_id = Arc::new(SessionID {
            begin_string: "FIX.4.2".to_string(),
            sender_comp_id: "TARGET2".to_string(),
            sender_sub_id: String::new(),
            sender_location_id: String::new(),
            target_comp_id: "SENDER2".to_string(),
            target_sub_id: String::new(),
            target_location_id: String::new(),
            qualifier: String::new(),
        });
        assert!(
            lookup_admin_tx(&unknown_id).is_none(),
            "unknown session should not be registered"
        );

        drop(stream);
        acceptor.stop().await;
        clean_sessions();
    }

    // --- TLS integration tests ---

    // Generate self-signed CA + server cert for testing using rcgen.
    fn generate_test_certs() -> (
        tempfile::NamedTempFile,
        tempfile::NamedTempFile,
        tempfile::NamedTempFile,
    ) {
        use rcgen::{CertificateParams, Issuer, KeyPair};
        use std::io::Write;

        let ca_key = KeyPair::generate().unwrap();
        let mut ca_params = CertificateParams::new(vec!["Test CA".to_string()]).unwrap();
        ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        let ca_cert = ca_params.self_signed(&ca_key).unwrap();

        let server_key = KeyPair::generate().unwrap();
        let server_params = CertificateParams::new(vec!["localhost".to_string()]).unwrap();
        let ca_issuer = Issuer::from_params(&ca_params, &ca_key);
        let server_cert = server_params.signed_by(&server_key, &ca_issuer).unwrap();

        let mut ca_file = tempfile::NamedTempFile::new().unwrap();
        ca_file.write_all(ca_cert.pem().as_bytes()).unwrap();

        let mut cert_file = tempfile::NamedTempFile::new().unwrap();
        cert_file.write_all(server_cert.pem().as_bytes()).unwrap();

        let mut key_file = tempfile::NamedTempFile::new().unwrap();
        key_file
            .write_all(server_key.serialize_pem().as_bytes())
            .unwrap();

        (ca_file, cert_file, key_file)
    }

    async fn make_tls_acceptor_settings(port: &str, cert_path: &str, key_path: &str) -> Settings {
        let cfg = format!(
            r"
[DEFAULT]
SocketAcceptPort={port}
SocketUseSSL=Y
SocketCertificateFile={cert_path}
SocketPrivateKeyFile={key_path}

[SESSION]
BeginString=FIX.4.2
SenderCompID=ACCEPTOR
TargetCompID=INITIATOR
"
        );
        Settings::parse(BufReader::new(cfg.as_bytes()))
            .await
            .unwrap()
    }

    // Verifies that an Acceptor with TLS enabled starts and stops cleanly.
    #[tokio::test]
    #[serial]
    async fn test_tls_acceptor_start_stop() {
        clean_sessions();

        let (_ca, cert, key) = generate_test_certs();
        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_tls_acceptor_settings(
            "0",
            cert.path().to_str().unwrap(),
            key.path().to_str().unwrap(),
        )
        .await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .expect("Acceptor::new with TLS should succeed");

        assert!(
            acceptor.tls_acceptor.is_some(),
            "TLS acceptor should be configured"
        );

        acceptor
            .start()
            .await
            .expect("Acceptor::start should succeed");
        let addr = connectable(acceptor.local_address().unwrap());
        assert_ne!(0, addr.port());

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that a TLS client can connect to a TLS-enabled Acceptor and
    // send a FIX logon message that gets matched to the correct session.
    #[tokio::test]
    #[serial]
    async fn test_tls_acceptor_session_identification() {
        clean_sessions();

        let (ca, cert, key) = generate_test_certs();
        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_tls_acceptor_settings(
            "0",
            cert.path().to_str().unwrap(),
            key.path().to_str().unwrap(),
        )
        .await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Build a TLS client using the CA cert to verify the server
        let ca_data = std::fs::read(ca.path()).unwrap();
        let ca_certs: Vec<_> =
            rustls_pemfile::certs(&mut std::io::BufReader::new(ca_data.as_slice()))
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
        let mut root_store = tokio_rustls::rustls::RootCertStore::empty();
        for c in ca_certs {
            root_store.add(c).unwrap();
        }
        let client_config = tokio_rustls::rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();
        let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(client_config));

        let tcp_stream = TcpStream::connect(addr).await.unwrap();
        let server_name =
            tokio_rustls::rustls::pki_types::ServerName::try_from("localhost").unwrap();
        let mut tls_stream = connector
            .connect(server_name, tcp_stream)
            .await
            .expect("TLS handshake should succeed");

        // Send a FIX logon over the TLS connection
        let logon_msg = make_logon_msg("INITIATOR", "ACCEPTOR");
        tokio::io::AsyncWriteExt::write_all(&mut tls_stream, &logon_msg)
            .await
            .expect("should write logon over TLS");

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        drop(tls_stream);
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        acceptor.stop().await;
        clean_sessions();
    }

    // Verifies that a plain TCP client is rejected by a TLS-enabled Acceptor
    // (TLS handshake fails, connection is dropped without crashing).
    #[tokio::test]
    #[serial]
    async fn test_tls_acceptor_rejects_plain_tcp() {
        clean_sessions();

        let (_ca, cert, key) = generate_test_certs();
        let app: Arc<dyn Application> = Arc::new(NOPApp::new());
        let store_factory = MessageStoreFactoryEnum::default();
        let log_factory = LogFactoryEnum::default();
        let settings = make_tls_acceptor_settings(
            "0",
            cert.path().to_str().unwrap(),
            key.path().to_str().unwrap(),
        )
        .await;

        let mut acceptor = Acceptor::new(app, store_factory, settings, log_factory)
            .await
            .unwrap();

        acceptor.start().await.unwrap();
        let addr = connectable(acceptor.local_address().unwrap());

        // Connect with plain TCP (no TLS) and send a FIX message.
        // The TLS handshake should fail, and the acceptor should handle it gracefully.
        let logon_msg = make_logon_msg("INITIATOR", "ACCEPTOR");
        let mut stream = TcpStream::connect(addr).await.unwrap();
        tokio::io::AsyncWriteExt::write_all(&mut stream, &logon_msg)
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // Acceptor should still be running fine
        drop(stream);
        acceptor.stop().await;
        clean_sessions();
    }
}