ironfix-engine 0.4.1

High-level FIX engine facade for IronFix
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
/******************************************************************************
   Author: Joaquín Béjar García
   Email: jb@taunais.com
   Date: 14/7/26
******************************************************************************/

//! Internal helpers for building and parsing FIX frames.
//!
//! Admin messages (Logon, Heartbeat, TestRequest, Logout, ResendRequest,
//! SequenceReset, Reject) are built here as [`PendingMessage`]s — a MsgType
//! plus body fields, with no header and no sequence number yet — exactly the
//! form an application message arrives in. [`MessageFactory::encode`] stamps
//! the standard header and trailer around either.
//!
//! The split is what makes `to_admin` / `to_app` mean something: the callback
//! mutates the [`OutboundMessage`] inside a [`PendingMessage`], and that is the
//! value the encoder then reads. It is also what lets the caller encode
//! **before** spending a sequence number, so a body with no legal wire form
//! costs nothing.
//!
//! One [`Encoder`] lives for the life of the factory and is rewound with
//! [`Encoder::clear`] between messages, so its buffer is allocated once and
//! [`MessageFactory::encode`] hands back a slice of it rather than a fresh
//! owned frame.
//!
//! A resend of a **stored** message takes a different path: [`resend_frame`]
//! rebuilds a verbatim frame the store handed back, keeping its original
//! `MsgSeqNum` and stamping `PossDupFlag` (43) / `OrigSendingTime` (122). That
//! is a replay of real traffic, not a freshly numbered message, so it does not
//! go through the factory's sequence-numbering `encode`.

use crate::application::{RejectReason, SessionId};
use crate::outbound::{OutboundField, OutboundMessage};
use bytes::BytesMut;
use ironfix_core::error::{DecodeError, EncodeError};
use ironfix_core::field::FieldRef;
use ironfix_core::message::{MsgType, RawMessage};
use ironfix_core::types::Timestamp;
use ironfix_core::version::FixVersion;
use ironfix_session::SessionConfig;
use ironfix_tagvalue::{Decoder, Encoder};
use std::time::Duration;

/// Derives the [`SessionId`] from a session configuration.
///
/// The identity is taken sender-first from the configuration, so both the
/// [`Initiator`](crate::Initiator) and the [`Acceptor`](crate::Acceptor) name a
/// session the same way: `begin_string:sender_comp_id->target_comp_id`, with
/// the optional sub IDs attached when configured.
pub(crate) fn session_id_from_config(config: &SessionConfig) -> SessionId {
    let mut session_id = SessionId::new(
        config.begin_string.clone(),
        config.sender_comp_id.as_str(),
        config.target_comp_id.as_str(),
    );
    if let Some(sub) = &config.sender_sub_id {
        session_id = session_id.with_sender_sub_id(sub.clone());
    }
    if let Some(sub) = &config.target_sub_id {
        session_id = session_id.with_target_sub_id(sub.clone());
    }
    session_id
}

/// A configured `BeginString` the engine cannot frame conformantly.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unsupported FIX version {version}: {detail}")]
pub(crate) struct UnsupportedVersion {
    /// The configured version string.
    pub(crate) version: String,
    /// Why it cannot be framed.
    pub(crate) detail: String,
}

/// Resolves the configured version string to the [`FixVersion`] whose wire
/// representation the header stamper uses.
///
/// The version-to-wire mapping — `BeginString` (8), and the application
/// version for `DefaultApplVerID` (1137) and `ApplVerID` (1128) — belongs to
/// [`FixVersion`] in `ironfix-core`, which is the workspace's single copy of
/// it. This function only decides whether a configured string names a version
/// the engine can frame; it does not restate the table.
///
/// Two strings are refused:
///
/// - one that names no version at all, which has no `BeginString` to stamp;
/// - bare `FIXT.1.1`, which names the transport version only. A FIXT Logon
///   must carry `DefaultApplVerID` (1137), which is **required**, and the
///   application version is exactly what this string failed to state.
///   Defaulting it would put a guessed version on the wire, so the session is
///   refused instead — configure `FIX.5.0`, `FIX.5.0SP1` or `FIX.5.0SP2`.
///
/// # Errors
/// Returns [`UnsupportedVersion`] in either of those cases.
pub(crate) fn wire_version(value: &str) -> Result<FixVersion, UnsupportedVersion> {
    let version: FixVersion = value.parse().map_err(|_| UnsupportedVersion {
        version: value.to_owned(),
        detail: format!(
            "not a FIX version this engine can frame; supported values are {}",
            framable_versions()
        ),
    })?;

    if version.uses_fixt() && version.appl_ver_id().is_none() {
        return Err(UnsupportedVersion {
            version: value.to_owned(),
            detail: format!(
                "{version} names only the transport version and carries no application version \
                 for DefaultApplVerID (1137), which a FIXT Logon requires; supported values are {}",
                framable_versions()
            ),
        });
    }

    Ok(version)
}

/// Lists the versions [`wire_version`] accepts, derived from [`FixVersion`] so
/// the message cannot go stale when a version is added.
fn framable_versions() -> String {
    FixVersion::ALL
        .into_iter()
        .filter(|version| !(version.uses_fixt() && version.appl_ver_id().is_none()))
        .map(FixVersion::as_str)
        .collect::<Vec<_>>()
        .join(", ")
}

/// A mismatch between an inbound message's identity fields and the
/// configured counterparty.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct IdentityMismatch {
    /// The offending tag (49, 56, 50 or 57).
    pub(crate) tag: u32,
    /// The value the configuration requires.
    pub(crate) expected: String,
    /// The value the counterparty sent, empty when the tag was absent.
    pub(crate) received: String,
    /// True when the tag carried the right value but was found outside the
    /// standard header, where it does not identify the counterparty.
    pub(crate) misplaced: bool,
}

impl std::fmt::Display for IdentityMismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.misplaced {
            return write!(
                f,
                "CompID problem: tag {} appears outside the standard header",
                self.tag
            );
        }
        write!(
            f,
            "CompID problem: tag {} expected '{}', received '{}'",
            self.tag, self.expected, self.received
        )
    }
}

/// Whether `tag` belongs to the FIX standard header.
///
/// The set is the standard header of FIX 4.0 through 5.0 SP2 taken together:
/// the framing fields, the routing and CompID fields, `MsgSeqNum` (34), the
/// PossDup/PossResend pair, `SendingTime` (52) and `OrigSendingTime` (122),
/// the `NoHops` group (627 and its 628/629/630 entries), and the FIXT.1.1
/// application-version fields (1128, 1129, 1156). A tag outside this set is
/// the first field of the message body.
const fn is_standard_header_tag(tag: u32) -> bool {
    matches!(
        tag,
        8 | 9
            | 34
            | 35
            | 43
            | 49
            | 50
            | 52
            | 56
            | 57
            | 90
            | 91
            | 97
            | 115
            | 116
            | 122
            | 128
            | 129
            | 142
            | 143
            | 144
            | 145
            | 212
            | 213
            | 347
            | 369
            | 627
            | 628
            | 629
            | 630
            | 1128
            | 1129
            | 1156
    )
}

/// Whether `tag` occurs in the standard header of `raw`.
///
/// The header is the leading run of standard-header tags, so the scan stops at
/// the first body field. Decoded fields keep their wire order, which is what
/// makes the distinction available here at all — nothing else in a decoded
/// message says where the header ended.
fn in_standard_header(raw: &RawMessage<'_>, tag: u32) -> bool {
    for field in raw.fields() {
        if field.tag == tag {
            return true;
        }
        if !is_standard_header_tag(field.tag) {
            return false;
        }
    }
    false
}

/// Reads `MsgSeqNum` (34) from the standard header of `raw`.
///
/// A tag 34 that appears only in the message body is treated as **absent**: it
/// is not the standard-header field the session sequences against, and the same
/// positional contract the identity check enforces on 49/56 applies here.
/// Accepting a body-only 34 would let a peer smuggle a sequence number past a
/// Logon that is, in fact, missing its header `MsgSeqNum`.
///
/// Returns `None` when 34 is absent from the header or is not a valid `u64`.
pub(crate) fn header_seq_num(raw: &RawMessage<'_>) -> Option<u64> {
    if !in_standard_header(raw, 34) {
        return None;
    }
    raw.get_field_str(34)
        .and_then(|value| value.parse::<u64>().ok())
}

/// Upper bound, in seconds, on a `HeartBtInt` (108) accepted from a
/// counterparty.
///
/// One day. FIX types `HeartBtInt` as an unbounded non-negative int, and
/// `108 = 0` is legal ("do not send heartbeats"), so the *lower* end is left
/// open. The upper end is not: a [`Duration`] built from a
/// counterparty-controlled value must stay finite, because the heartbeat clock
/// adds a grace period to it (`interval + grace`), and
/// `Duration::from_secs(u64::MAX) + _` overflows and panics — which, under the
/// release profile's `panic = "abort"`, takes the whole process down. A single
/// crafted Logon carrying `108 = u64::MAX` would otherwise be a remote abort. A
/// day is orders of magnitude beyond any real interval while leaving enormous
/// headroom below that overflow.
pub(crate) const MAX_HEARTBEAT_INTERVAL_SECS: u64 = 86_400;

/// Longest `HeartBtInt` (108) value echoed back in a log line or a Logout
/// `Text` (58). The field is counterparty-controlled, so it is bounded.
const MAX_ECHOED_HEARTBEAT: usize = 32;

/// Why an inbound `HeartBtInt` (108) was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum HeartBtIntProblem {
    /// The field is absent. FIX requires it on every Logon.
    Missing,
    /// The field is present but is not a non-negative integer.
    Malformed {
        /// The offending value, truncated for the log and the Logout text.
        value: String,
    },
    /// The field parses but exceeds [`MAX_HEARTBEAT_INTERVAL_SECS`].
    OutOfRange {
        /// The requested interval, in seconds.
        secs: u64,
    },
}

impl std::fmt::Display for HeartBtIntProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Missing => write!(f, "HeartBtInt (108) is missing"),
            Self::Malformed { value } => {
                write!(
                    f,
                    "HeartBtInt (108) '{value}' is not a non-negative integer"
                )
            }
            Self::OutOfRange { secs } => write!(
                f,
                "HeartBtInt (108) {secs}s exceeds the {MAX_HEARTBEAT_INTERVAL_SECS}s maximum"
            ),
        }
    }
}

/// Parses and bounds the `HeartBtInt` (108) of an inbound Logon.
///
/// The value is adopted by the acceptor and drives a
/// [`HeartbeatManager`](ironfix_session::HeartbeatManager), so it is validated
/// at the handshake rather than trusted onto the heartbeat clock. `108 = 0` is
/// accepted (it is legal FIX and is not specially handled today); anything above
/// [`MAX_HEARTBEAT_INTERVAL_SECS`] is refused so a crafted value can never
/// overflow the clock's `interval + grace` arithmetic.
///
/// # Errors
/// Returns [`HeartBtIntProblem::Missing`] when tag 108 is absent,
/// [`HeartBtIntProblem::Malformed`] when it is not a non-negative integer, and
/// [`HeartBtIntProblem::OutOfRange`] when it exceeds the maximum.
pub(crate) fn parse_heartbeat_interval(raw: &RawMessage<'_>) -> Result<u64, HeartBtIntProblem> {
    let Some(value) = raw.get_field_str(108) else {
        return Err(HeartBtIntProblem::Missing);
    };
    let Ok(secs) = value.parse::<u64>() else {
        return Err(HeartBtIntProblem::Malformed {
            value: value.chars().take(MAX_ECHOED_HEARTBEAT).collect(),
        });
    };
    if secs > MAX_HEARTBEAT_INTERVAL_SECS {
        return Err(HeartBtIntProblem::OutOfRange { secs });
    }
    Ok(secs)
}

/// The identity every inbound message must carry, derived from the session
/// configuration with sender and target reversed.
///
/// A cross-wired connection that is never checked advances sequence state
/// against the wrong counterparty and delivers another session's traffic to
/// the application, so this is validated before anything else touches
/// session state. A mismatch is `SessionRejectReason` 9, "CompID problem"
/// (`doc/fix_operations.md`, "Session Reject Reasons").
#[derive(Debug, Clone)]
pub(crate) struct PeerIdentity {
    /// Required inbound `SenderCompID` (49) — our configured target.
    sender_comp_id: String,
    /// Required inbound `TargetCompID` (56) — our configured sender.
    target_comp_id: String,
    /// Required inbound `SenderSubID` (50), when configured.
    sender_sub_id: Option<String>,
    /// Required inbound `TargetSubID` (57), when configured.
    target_sub_id: Option<String>,
}

impl PeerIdentity {
    /// Builds the expected inbound identity from the session configuration.
    #[must_use]
    pub(crate) fn new(config: &SessionConfig) -> Self {
        Self {
            sender_comp_id: config.target_comp_id.as_str().to_string(),
            target_comp_id: config.sender_comp_id.as_str().to_string(),
            sender_sub_id: config.target_sub_id.clone(),
            target_sub_id: config.sender_sub_id.clone(),
        }
    }

    /// Checks an inbound message's identity fields.
    ///
    /// Sub IDs are only checked when configured; an unconfigured sub ID
    /// places no requirement on the counterparty.
    ///
    /// Each field must both carry the expected value **and** occur in the
    /// standard header. A CompID that appears only after the message body
    /// identifies nothing: the standard header is where the counterparty is
    /// named, and a message that omits it from there is missing a required
    /// header field however many copies it carries elsewhere. Both failures
    /// are `SessionRejectReason` 9.
    pub(crate) fn validate(&self, raw: &RawMessage<'_>) -> Result<(), IdentityMismatch> {
        check_field(raw, 49, &self.sender_comp_id)?;
        check_field(raw, 56, &self.target_comp_id)?;
        if let Some(expected) = &self.sender_sub_id {
            check_field(raw, 50, expected)?;
        }
        if let Some(expected) = &self.target_sub_id {
            check_field(raw, 57, expected)?;
        }
        Ok(())
    }
}

/// Compares one inbound identity field against its required value, and
/// requires it to sit in the standard header.
///
/// The value is compared first so a cross-wired CompID keeps reporting the
/// value it sent rather than its position.
fn check_field(raw: &RawMessage<'_>, tag: u32, expected: &str) -> Result<(), IdentityMismatch> {
    let received = raw.get_field_str(tag).unwrap_or_default();
    if received != expected {
        return Err(IdentityMismatch {
            tag,
            expected: expected.to_string(),
            received: received.to_string(),
            misplaced: false,
        });
    }
    if !in_standard_header(raw, tag) {
        return Err(IdentityMismatch {
            tag,
            expected: expected.to_string(),
            received: received.to_string(),
            misplaced: true,
        });
    }
    Ok(())
}

/// Why an inbound `SendingTime` (52) failed validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SendingTimeProblem {
    /// The field is absent. It is required in every standard header.
    Missing,
    /// The field is present but is not a FIX `UTCTimestamp`.
    Malformed {
        /// The offending value, truncated for the log and the Reject text.
        value: String,
    },
    /// The field parses but lies outside the configured tolerance.
    Skewed {
        /// Absolute difference from the local clock, in milliseconds.
        skew_millis: u64,
        /// The configured tolerance, in milliseconds.
        tolerance_millis: u64,
    },
}

impl SendingTimeProblem {
    /// The session-level Reject this problem produces.
    ///
    /// Reason 10 is "SendingTime accuracy problem"; a missing required field
    /// is reason 1 and an unparseable one is reason 6, "incorrect data
    /// format" (`doc/fix_operations.md`, "Session Reject Reasons").
    #[must_use]
    pub(crate) fn reject_reason(&self) -> RejectReason {
        let code = match self {
            Self::Missing => 1,
            Self::Malformed { .. } => 6,
            Self::Skewed { .. } => 10,
        };
        RejectReason::new(code, self.to_string()).with_ref_tag(52)
    }
}

impl std::fmt::Display for SendingTimeProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Missing => write!(f, "SendingTime (52) is missing"),
            Self::Malformed { value } => {
                write!(f, "SendingTime (52) '{value}' is not a UTC timestamp")
            }
            Self::Skewed {
                skew_millis,
                tolerance_millis,
            } => write!(
                f,
                "SendingTime (52) differs from the local clock by {skew_millis}ms, \
                 outside the {tolerance_millis}ms tolerance"
            ),
        }
    }
}

/// Longest `SendingTime` value echoed back in a Reject or a log line.
///
/// The value is counterparty-controlled and lands in `Text` (58) on the wire,
/// so it is bounded. A legal `UTCTimestamp` is at most 27 characters.
const MAX_ECHOED_SENDING_TIME: usize = 32;

/// Checks inbound `SendingTime` (52) against the local clock.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SendingTimeGuard {
    /// Configured tolerance. `Duration::ZERO` — and only that — disables the
    /// check; any nonzero value, including a sub-millisecond one, leaves it on.
    tolerance: Duration,
}

impl SendingTimeGuard {
    /// Builds the guard from the session configuration.
    #[must_use]
    pub(crate) const fn new(config: &SessionConfig) -> Self {
        Self {
            tolerance: config.sending_time_tolerance,
        }
    }

    /// Whether the check is switched off.
    ///
    /// Only an exactly-zero tolerance disables it. The duration is compared as
    /// a duration rather than flattened to whole milliseconds first, so a
    /// sub-millisecond tolerance — which floors to zero milliseconds — cannot
    /// masquerade as "disabled" and silently switch the whole check off, the
    /// opposite of what the operator asked for.
    #[must_use]
    pub(crate) const fn is_disabled(&self) -> bool {
        self.tolerance.is_zero()
    }

    /// Validates the `SendingTime` (52) of an inbound message.
    ///
    /// A zero tolerance disables the check entirely, including the presence
    /// and format checks: the knob governs `SendingTime` validation as a
    /// whole, so an operator who has switched it off for a peer with a known
    /// clock problem does not get half of it back.
    ///
    /// Tag 52 must sit in the standard header: a copy appearing only after the
    /// body opens names no sending time, exactly as a misplaced CompID names no
    /// counterparty, so it is treated as absent. The binding spec assigns no
    /// positional reject reason for 52 (reason 9 is CompID-only), so this is
    /// inbound-acceptance hardening rather than a spec-mandated reject.
    ///
    /// # Errors
    /// Returns [`SendingTimeProblem::Missing`] when tag 52 is absent from the
    /// standard header, [`SendingTimeProblem::Malformed`] when it is present but
    /// is not a UTF-8 `UTCTimestamp`, and [`SendingTimeProblem::Skewed`] when it
    /// parses but lies further from the local clock than the configured
    /// tolerance, in either direction.
    pub(crate) fn validate(&self, raw: &RawMessage<'_>) -> Result<(), SendingTimeProblem> {
        if self.is_disabled() {
            return Ok(());
        }
        // Present AND in the standard header, in that order: the header copy is
        // the one that counts, so a body-only 52 is as good as missing.
        let Some(field) = raw.get_field(52).filter(|_| in_standard_header(raw, 52)) else {
            return Err(SendingTimeProblem::Missing);
        };
        // A present-but-unreadable value is malformed (reason 6), not missing
        // (reason 1). Invalid UTF-8 fails `as_str`, so it is folded into the
        // same malformed path instead of being misreported as absent, per
        // `doc/fix_operations.md`, "Session Reject Reasons".
        let Ok(value) = field.as_str() else {
            return Err(SendingTimeProblem::Malformed {
                value: String::from_utf8_lossy(field.value)
                    .chars()
                    .take(MAX_ECHOED_SENDING_TIME)
                    .collect(),
            });
        };
        let Some(sent_millis) = parse_utc_timestamp_millis(value) else {
            return Err(SendingTimeProblem::Malformed {
                value: value.chars().take(MAX_ECHOED_SENDING_TIME).collect(),
            });
        };

        let skew_millis = Timestamp::now().as_millis().abs_diff(sent_millis);
        // Compared as a duration so the tolerance is never truncated to whole
        // milliseconds: a sub-millisecond tolerance stays meaningful.
        if Duration::from_millis(skew_millis) > self.tolerance {
            return Err(SendingTimeProblem::Skewed {
                skew_millis,
                tolerance_millis: u64::try_from(self.tolerance.as_millis()).unwrap_or(u64::MAX),
            });
        }
        Ok(())
    }
}

/// Parses a FIX `UTCTimestamp` into milliseconds since the Unix epoch.
///
/// Accepts `YYYYMMDD-HH:MM:SS` with an optional fractional part of one to nine
/// digits, which covers every precision FIX 4.0 through 5.0 SP2 puts on the
/// wire. Digits below the millisecond are truncated; the tolerance this feeds
/// is measured in seconds.
///
/// Returns `None` for anything else, including a well-shaped string naming a
/// date that does not exist and any year before 1970. There is no
/// representable instant for those, and inventing one would let a malformed
/// value pass the accuracy check.
fn parse_utc_timestamp_millis(value: &str) -> Option<u64> {
    let bytes = value.as_bytes();
    // "YYYYMMDD-HH:MM:SS" — the fractional part is optional.
    if bytes.len() < 17 || bytes.get(8) != Some(&b'-') {
        return None;
    }
    if bytes.get(11) != Some(&b':') || bytes.get(14) != Some(&b':') {
        return None;
    }

    let year = parse_digits(bytes.get(0..4)?)?;
    let month = parse_digits(bytes.get(4..6)?)?;
    let day = parse_digits(bytes.get(6..8)?)?;
    let hour = parse_digits(bytes.get(9..11)?)?;
    let minute = parse_digits(bytes.get(12..14)?)?;
    // 60 is a leap second, which FIX permits.
    let second = parse_digits(bytes.get(15..17)?)?;

    let fraction_millis = match bytes.get(17) {
        None => 0,
        Some(&b'.') => parse_fraction_millis(bytes.get(18..)?)?,
        Some(_) => return None,
    };

    if !(1970..=9999).contains(&year)
        || !(1..=12).contains(&month)
        || day < 1
        || day > days_in_month(year, month)?
        || hour > 23
        || minute > 59
        || second > 60
    {
        return None;
    }

    let days = days_from_civil(year, month, day)?;
    let seconds = days
        .checked_mul(86_400)?
        .checked_add(hour.checked_mul(3_600)?)?
        .checked_add(minute.checked_mul(60)?)?
        .checked_add(second)?;
    seconds.checked_mul(1_000)?.checked_add(fraction_millis)
}

/// Parses a run of ASCII digits into an integer.
fn parse_digits(bytes: &[u8]) -> Option<u64> {
    if bytes.is_empty() || !bytes.iter().all(u8::is_ascii_digit) {
        return None;
    }
    let mut value: u64 = 0;
    for byte in bytes {
        value = value.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
    }
    Some(value)
}

/// Parses the fractional-second digits of a `UTCTimestamp` into milliseconds,
/// truncating anything below a millisecond.
fn parse_fraction_millis(bytes: &[u8]) -> Option<u64> {
    if bytes.is_empty() || bytes.len() > 9 || !bytes.iter().all(u8::is_ascii_digit) {
        return None;
    }
    let mut millis: u64 = 0;
    for index in 0..3 {
        let digit = bytes.get(index).map_or(0, |byte| u64::from(byte - b'0'));
        millis = millis * 10 + digit;
    }
    Some(millis)
}

/// Days in `month` of `year`, Gregorian.
fn days_in_month(year: u64, month: u64) -> Option<u64> {
    const LENGTHS: [u64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let leap = year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
    if month == 2 && leap {
        return Some(29);
    }
    let index = usize::try_from(month.checked_sub(1)?).ok()?;
    LENGTHS.get(index).copied()
}

/// Days from `1970-01-01` to the given Gregorian date.
///
/// Hinnant's `days_from_civil`, restricted to dates at or after the epoch so
/// every intermediate stays non-negative. The caller has already range-checked
/// the components.
fn days_from_civil(year: u64, month: u64, day: u64) -> Option<u64> {
    let shifted = if month <= 2 {
        year.checked_sub(1)?
    } else {
        year
    };
    let era = shifted / 400;
    let year_of_era = shifted - era * 400;
    let shifted_month = if month > 2 { month - 3 } else { month + 9 };
    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    (era * 146_097 + day_of_era).checked_sub(719_468)
}

/// Decodes a framed FIX message.
///
/// Checksum validation is skipped: the transport codec has already
/// validated the frame when configured to do so.
pub(crate) fn decode_frame(frame: &[u8]) -> Result<RawMessage<'_>, DecodeError> {
    let mut decoder = Decoder::new(frame).with_checksum_validation(false);
    decoder.decode()
}

/// Why a stored message could not be rebuilt as a resend.
///
/// Every variant means the same thing to the reactor — this particular message
/// cannot be replayed and its sequence number must be gap-filled instead — but
/// they are kept apart so the log line says which defect was hit.
#[derive(Debug, thiserror::Error)]
pub(crate) enum ResendError {
    /// The stored frame does not decode.
    #[error("stored frame does not decode: {0}")]
    Decode(#[from] DecodeError),

    /// The rebuilt frame has no legal wire form.
    #[error("resend frame cannot be encoded: {0}")]
    Encode(#[from] EncodeError),

    /// The stored frame carries no `SendingTime` (52).
    ///
    /// FIX requires `OrigSendingTime` (122) on a message carrying
    /// `PossDupFlag` (43) = Y. On the first resend that original time is the
    /// frame's own 52 (a resend-of-a-resend keeps it in its own 122 instead —
    /// see [`resend_frame`]). With no 52 recorded there is no header position to
    /// re-stamp and nothing truthful to put in 122, and inventing one would
    /// misreport when the message was first sent.
    #[error("stored frame carries no SendingTime (52) to copy into OrigSendingTime (122)")]
    MissingSendingTime,
}

/// Rebuilds a stored frame as a resend of itself.
///
/// The message keeps its original `MsgSeqNum` (34) — a resend re-occupies the
/// number it was first sent under and allocates nothing — and gains
/// `PossDupFlag` (43) = Y with `OrigSendingTime` (122) set to when the message
/// was *first* sent, while 52 is restamped with the time of *this* transmission
/// (`doc/fix_operations.md`, "Resend Request", items 2 and 4). Both are written
/// in their standard-header positions: 43 immediately before 52, 122 immediately
/// after it.
///
/// On a plain resend the first-sent time is the frame's own `SendingTime` (52).
/// On a **resend of a resend** the frame already carries that original in its
/// own 122 — its 52 by then is only the prior transmission's time — so an
/// existing 122 is preferred and copied through unchanged. Overwriting it with
/// 52 would silently move `OrigSendingTime` forward to the last replay.
///
/// Every other field is copied through verbatim in its original order, so the
/// business content of the replayed message is byte-identical to what was
/// sent. `BodyLength` (9) and `CheckSum` (10) are restamped by the encoder,
/// because both change with the two inserted fields.
///
/// # Errors
/// Returns [`ResendError`] if the stored frame does not decode, carries no
/// `SendingTime` (52), or cannot be re-encoded. The caller must gap-fill the
/// sequence number instead of skipping it.
pub(crate) fn resend_frame(stored: &[u8]) -> Result<BytesMut, ResendError> {
    let raw = decode_frame(stored)?;
    let begin_string = raw.begin_string()?;
    // 52 is both the emission trigger below and the fallback source for 122, so
    // its absence is the terminal error: our own stored frames always carry it.
    let sending_time_52 = raw
        .get_field_str(52)
        .ok_or(ResendError::MissingSendingTime)?;
    // Prefer an existing OrigSendingTime (122): on a resend-of-a-resend it holds
    // the *first* transmission's time, whereas 52 by then is the prior replay's.
    // Falling back to 52 covers the first resend, where no 122 is present yet.
    let orig_sending_time = raw.get_field_str(122).unwrap_or(sending_time_52);
    let sending_time = Timestamp::now().format_millis();

    // The rebuilt frame is the original plus 43 and 122; the extra headroom
    // keeps the encoder from reallocating while it copies the body across.
    let mut encoder = Encoder::with_capacity(begin_string, stored.len() + RESEND_HEADROOM);

    // Collected so a LENGTH field can look ahead to its DATA field. This is
    // the resend path, not the hot path: one allocation per replayed message
    // is the right trade for handling every spec-defined field shape.
    let fields: Vec<&FieldRef<'_>> = raw.fields().collect();
    let mut index = 0;
    while let Some(field) = fields.get(index) {
        index += 1;
        match field.tag {
            // BeginString and BodyLength are stamped by `finish`.
            8 | 9 => {}
            // Re-emitted below, in their standard-header positions. A frame
            // already carrying them is being replayed a second time.
            43 | 122 => {}
            52 => {
                encoder.try_put_raw(43, b"Y")?;
                encoder.try_put_raw(52, sending_time.as_str().as_bytes())?;
                encoder.try_put_raw(122, orig_sending_time.as_bytes())?;
            }
            tag => {
                if let Err(err) = encoder.try_put_raw(tag, field.value) {
                    // The encoder refuses a LENGTH or DATA tag on its own,
                    // because it derives the declared count from the payload
                    // so the two cannot disagree. Pair it with the field that
                    // follows and write both together.
                    let paired = fields.get(index).is_some_and(|data| {
                        encoder.try_put_data(tag, data.tag, data.value).is_ok()
                    });
                    if !paired {
                        return Err(err.into());
                    }
                    index += 1;
                }
            }
        }
    }

    Ok(into_frame(&mut encoder)?)
}

/// Extra bytes reserved for the `PossDupFlag` (43) and `OrigSendingTime` (122)
/// a resend inserts, plus the framing fields the encoder restamps.
const RESEND_HEADROOM: usize = 64;

/// Stamps the frame and moves it into a buffer the transport owns.
///
/// Used by [`resend_frame`], which builds a fresh encoder per replayed message
/// rather than sharing the factory's reused one.
///
/// # Errors
/// Returns the [`EncodeError`] the encoder recorded — a field value that
/// cannot be represented on the wire, such as a `Text` (58) carrying the SOH
/// delimiter. A frame is never produced from a rejected value.
fn into_frame(encoder: &mut Encoder) -> Result<BytesMut, EncodeError> {
    let mut frame = BytesMut::new();
    encoder.finish_into(&mut frame)?;
    Ok(frame)
}

/// A message built but not yet framed: body fields, plus the one header
/// property that is not derivable from the MsgType.
///
/// This is what the `to_admin` / `to_app` callbacks mutate and what
/// [`MessageFactory::encode`] reads, so the two cannot disagree about what
/// goes on the wire.
#[derive(Debug, Clone)]
pub(crate) struct PendingMessage {
    /// MsgType and body fields.
    message: OutboundMessage,
    /// Whether the header carries `PossDupFlag` (43) and `OrigSendingTime`
    /// (122). Only a SequenceReset-GapFill answering a ResendRequest sets it.
    poss_dup: bool,
}

impl PendingMessage {
    /// Wraps a message that is not a possible duplicate.
    #[must_use]
    fn plain(message: OutboundMessage) -> Self {
        Self {
            message,
            poss_dup: false,
        }
    }

    /// Wraps an application message handed in by a consumer.
    #[must_use]
    pub(crate) fn application(message: OutboundMessage) -> Self {
        Self::plain(message)
    }

    /// Returns the message type.
    #[must_use]
    pub(crate) fn msg_type(&self) -> &MsgType {
        self.message.msg_type()
    }

    /// Returns the message body.
    #[must_use]
    pub(crate) fn message(&self) -> &OutboundMessage {
        &self.message
    }

    /// Returns the message body for the `to_admin` / `to_app` callbacks.
    #[must_use]
    pub(crate) fn message_mut(&mut self) -> &mut OutboundMessage {
        &mut self.message
    }
}

/// Builds outbound messages and frames them with the session header stamped.
#[derive(Debug)]
pub(crate) struct MessageFactory {
    version: FixVersion,
    sender_comp_id: String,
    target_comp_id: String,
    sender_sub_id: Option<String>,
    target_sub_id: Option<String>,
    sender_location_id: Option<String>,
    target_location_id: Option<String>,
    /// Reused across every message: [`Encoder::clear`] rewinds it while
    /// retaining its buffer, so framing does not allocate per message.
    encoder: Encoder,
}

impl MessageFactory {
    /// Creates a factory from the session configuration.
    #[must_use]
    pub(crate) fn new(config: &SessionConfig, version: FixVersion) -> Self {
        Self {
            version,
            sender_comp_id: config.sender_comp_id.as_str().to_string(),
            target_comp_id: config.target_comp_id.as_str().to_string(),
            sender_sub_id: config.sender_sub_id.clone(),
            target_sub_id: config.target_sub_id.clone(),
            sender_location_id: config.sender_location_id.clone(),
            target_location_id: config.target_location_id.clone(),
            encoder: Encoder::new(version.begin_string()),
        }
    }

    /// Frames `pending` under `seq` and returns the finished frame, which
    /// borrows the factory's own buffer until the next call.
    ///
    /// The standard header is stamped first —
    /// 35, \[1128\], 49, 56, \[50\], \[142\], \[57\], \[143\], 34, \[43\], 52, \[122\] —
    /// then the body fields in insertion order.
    ///
    /// `SenderLocationID` (142) follows `SenderSubID` (50) and
    /// `TargetLocationID` (143) follows `TargetSubID` (57), the standard-header
    /// pairing of the routing fields. Both are stamped only when configured; an
    /// unset LocationID places nothing on the wire.
    ///
    /// `PossDupFlag` (43) is always accompanied by `OrigSendingTime` (122):
    /// FIX requires 122 on every message carrying 43=Y. Its only user here is a
    /// SequenceReset-GapFill, whose "original" messages are administrative
    /// filler that was never sent, so there is no recorded sending time to copy
    /// and 122 takes the same value as `SendingTime` (52) — the FIX handling
    /// for an unavailable OrigSendingTime. A genuine replay of a stored message
    /// goes through [`resend_frame`], which copies the real original 52 into
    /// 122.
    ///
    /// `ApplVerID` (1128) is stamped immediately after MsgType, its position in
    /// the FIXT.1.1 standard header, and only for application messages;
    /// session-level messages are versioned by the FIXT.1.1 BeginString itself.
    ///
    /// # Errors
    /// Returns the [`EncodeError`] the encoder recorded — a field value with no
    /// on-the-wire form, such as a `Text` (58) carrying the SOH delimiter or an
    /// empty `TestReqID` (112) echoed back from a peer. A frame is never
    /// produced from a rejected value, and the caller has not yet spent a
    /// sequence number on it.
    pub(crate) fn encode(
        &mut self,
        seq: u64,
        pending: &PendingMessage,
    ) -> Result<&[u8], EncodeError> {
        let poss_dup = pending.poss_dup;
        let message = &pending.message;
        // Session-level messages are versioned by the BeginString; only
        // application messages carry ApplVerID.
        let appl_ver_id = if message.msg_type().is_admin() {
            None
        } else {
            self.version.appl_ver_id()
        };

        self.encoder.clear();
        self.encoder.put_str(35, message.msg_type().as_str());
        if let Some(appl_ver_id) = appl_ver_id {
            self.encoder.put_str(1128, appl_ver_id);
        }
        self.encoder.put_str(49, &self.sender_comp_id);
        self.encoder.put_str(56, &self.target_comp_id);
        if let Some(sub) = &self.sender_sub_id {
            self.encoder.put_str(50, sub);
        }
        if let Some(location) = &self.sender_location_id {
            self.encoder.put_str(142, location);
        }
        if let Some(sub) = &self.target_sub_id {
            self.encoder.put_str(57, sub);
        }
        if let Some(location) = &self.target_location_id {
            self.encoder.put_str(143, location);
        }
        self.encoder.put_uint(34, seq);
        if poss_dup {
            self.encoder.put_bool(43, true);
        }
        let sending_time = Timestamp::now().format_millis();
        self.encoder.put_str(52, sending_time.as_str());
        if poss_dup {
            self.encoder.put_str(122, sending_time.as_str());
        }

        for field in message.fields() {
            match field {
                OutboundField::Raw { tag, value } => self.encoder.put_raw(*tag, value),
                OutboundField::Data {
                    length_tag,
                    data_tag,
                    value,
                } => self.encoder.put_data(*length_tag, *data_tag, value),
            }
        }
        self.encoder.finish()
    }

    /// Builds a Logon (35=A) with EncryptMethod=0, HeartBtInt and, for a
    /// FIXT.1.1 session, DefaultApplVerID (1137).
    #[must_use]
    pub(crate) fn logon(&self, heartbeat_secs: u64, reset_seq: bool) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::Logon);
        message.push_uint(98, 0).push_uint(108, heartbeat_secs);
        if reset_seq {
            message.push_bool(141, true);
        }
        if let Some(appl_ver_id) = self.version.appl_ver_id() {
            message.push_str(1137, appl_ver_id);
        }
        PendingMessage::plain(message)
    }

    /// Builds a Heartbeat (35=0), echoing TestReqID (112) when replying to
    /// a TestRequest.
    #[must_use]
    pub(crate) fn heartbeat(&self, test_req_id: Option<&str>) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::Heartbeat);
        if let Some(id) = test_req_id {
            message.push_str(112, id);
        }
        PendingMessage::plain(message)
    }

    /// Builds a TestRequest (35=1) with TestReqID (112).
    #[must_use]
    pub(crate) fn test_request(&self, test_req_id: &str) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::TestRequest);
        message.push_str(112, test_req_id);
        PendingMessage::plain(message)
    }

    /// Builds a Logout (35=5) with optional Text (58).
    ///
    /// An empty text is dropped rather than written: `58=` has no legal wire
    /// form, and losing the reason is better than losing the Logout.
    #[must_use]
    pub(crate) fn logout(&self, text: Option<&str>) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::Logout);
        if let Some(text) = text.filter(|text| !text.is_empty()) {
            message.push_str(58, text);
        }
        PendingMessage::plain(message)
    }

    /// Builds a ResendRequest (35=2) for `begin_seq..end_seq`
    /// (`end_seq` = 0 means "up to infinity").
    #[must_use]
    pub(crate) fn resend_request(&self, begin_seq: u64, end_seq: u64) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::ResendRequest);
        message.push_uint(7, begin_seq).push_uint(16, end_seq);
        PendingMessage::plain(message)
    }

    /// Builds a SequenceReset-GapFill (35=4, 123=Y) that answers a
    /// ResendRequest by jumping the counterparty's expectation to `new_seq`.
    /// Carries PossDupFlag (43=Y) and OrigSendingTime (122); the caller
    /// encodes it under the gap's begin sequence.
    #[must_use]
    pub(crate) fn sequence_reset_gap_fill(&self, new_seq: u64) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::SequenceReset);
        message.push_bool(123, true).push_uint(36, new_seq);
        PendingMessage {
            message,
            poss_dup: true,
        }
    }

    /// Builds a session-level Reject (35=3).
    #[must_use]
    pub(crate) fn session_reject(
        &self,
        ref_seq: u64,
        ref_msg_type: &str,
        reason: &RejectReason,
    ) -> PendingMessage {
        let mut message = OutboundMessage::new(MsgType::Reject);
        message.push_uint(45, ref_seq);
        if let Some(ref_tag) = reason.ref_tag {
            message.push_uint(371, u64::from(ref_tag));
        }
        message
            .push_str(372, ref_msg_type)
            .push_uint(373, u64::from(reason.code));
        if !reason.text.is_empty() {
            message.push_str(58, &reason.text);
        }
        PendingMessage::plain(message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ironfix_core::message::MsgType;
    use ironfix_core::types::CompId;
    use std::time::Duration;

    fn config_for(begin_string: &str) -> SessionConfig {
        let Ok(sender) = CompId::new("CLIENT") else {
            unreachable!("CLIENT is a valid CompId")
        };
        let Ok(target) = CompId::new("VENUE") else {
            unreachable!("VENUE is a valid CompId")
        };
        SessionConfig::new(sender, target, begin_string)
    }

    fn factory_for(begin_string: &str) -> MessageFactory {
        let config = config_for(begin_string);
        match wire_version(&config.begin_string) {
            Ok(version) => MessageFactory::new(&config, version),
            Err(err) => panic!("test fixture uses an unsupported version: {err}"),
        }
    }

    fn factory() -> MessageFactory {
        factory_for("FIX.4.4")
    }

    fn decode(frame: &[u8]) -> RawMessage<'_> {
        match decode_frame(frame) {
            Ok(raw) => raw,
            Err(err) => unreachable!("factory frame must decode: {err}"),
        }
    }

    /// Frames `pending` under `seq`, failing the test with the encoder's
    /// rejection.
    #[track_caller]
    fn framed(factory: &mut MessageFactory, seq: u64, pending: &PendingMessage) -> Vec<u8> {
        match factory.encode(seq, pending) {
            Ok(frame) => frame.to_vec(),
            Err(err) => panic!("factory frame must encode: {err}"),
        }
    }

    /// Unwraps a hand-built frame, failing the test with the encoder's
    /// rejection.
    #[track_caller]
    fn built(frame: Result<BytesMut, EncodeError>) -> BytesMut {
        match frame {
            Ok(frame) => frame,
            Err(err) => panic!("fixture frame must encode: {err}"),
        }
    }

    /// Fails the test with context instead of `.unwrap()` / `.expect()`.
    #[track_caller]
    fn some<T>(value: Option<T>, what: &str) -> T {
        match value {
            Some(value) => value,
            None => panic!("{what}"),
        }
    }

    /// Reads a field out of a finished frame as an owned `String`.
    fn field_of(frame: &[u8], tag: u32) -> Option<String> {
        decode_frame(frame)
            .ok()
            .and_then(|raw| raw.get_field_str(tag).map(str::to_string))
    }

    #[test]
    fn test_logon_frame_roundtrip() {
        let mut factory = factory();
        let logon = factory.logon(30, true);
        let frame = framed(&mut factory, 1, &logon);
        let raw = decode(&frame);
        assert_eq!(raw.msg_type(), &MsgType::Logon);
        assert_eq!(raw.get_field_str(49), Some("CLIENT"));
        assert_eq!(raw.get_field_str(56), Some("VENUE"));
        assert_eq!(raw.get_field_str(34), Some("1"));
        assert_eq!(raw.get_field_str(98), Some("0"));
        assert_eq!(raw.get_field_str(108), Some("30"));
        assert_eq!(raw.get_field_str(141), Some("Y"));
        // Pre-5.0 session: no application version fields.
        assert_eq!(raw.get_field_str(1137), None);
    }

    #[test]
    fn test_gap_fill_frame_carries_orig_sending_time() {
        let mut factory = factory();
        let gap_fill = factory.sequence_reset_gap_fill(10);
        let frame = framed(&mut factory, 3, &gap_fill);
        let raw = decode(&frame);
        assert_eq!(raw.msg_type(), &MsgType::SequenceReset);
        assert_eq!(raw.get_field_str(34), Some("3"));
        assert_eq!(raw.get_field_str(43), Some("Y"));
        assert_eq!(raw.get_field_str(123), Some("Y"));
        assert_eq!(raw.get_field_str(36), Some("10"));
        // Every frame carrying PossDupFlag must carry OrigSendingTime, and
        // absent a store it equals SendingTime.
        assert_eq!(raw.get_field_str(122), raw.get_field_str(52));
        assert!(raw.get_field_str(122).is_some());
    }

    #[test]
    fn test_non_poss_dup_frame_omits_orig_sending_time() {
        let mut factory = factory();
        let heartbeat = factory.heartbeat(None);
        let frame = framed(&mut factory, 4, &heartbeat);
        let raw = decode(&frame);
        assert_eq!(raw.get_field_str(43), None);
        assert_eq!(raw.get_field_str(122), None);
    }

    #[test]
    fn test_encoder_reuse_produces_independent_frames() {
        // One encoder is reused for the life of the session; a message must
        // never carry residue of the one before it.
        let mut factory = factory();
        let logon = factory.logon(30, false);
        let first = framed(&mut factory, 1, &logon);
        let heartbeat = factory.heartbeat(Some("TEST-1"));
        let second = framed(&mut factory, 2, &heartbeat);

        assert_eq!(decode(&first).msg_type(), &MsgType::Logon);
        assert_eq!(decode(&first).get_field_str(108), Some("30"));
        let raw = decode(&second);
        assert_eq!(raw.msg_type(), &MsgType::Heartbeat);
        assert_eq!(raw.get_field_str(34), Some("2"));
        assert_eq!(raw.get_field_str(112), Some("TEST-1"));
        assert_eq!(raw.get_field_str(108), None);
    }

    #[test]
    fn test_encode_rejects_an_unframeable_body_without_a_frame() {
        // A value with no legal wire form is refused here, before the caller
        // spends a sequence number on it.
        let mut factory = factory();
        let mut logout = factory.logout(None);
        logout.message_mut().push_str(58, "bye\x0149=EVIL");
        match factory.encode(9, &logout) {
            Err(EncodeError::InvalidFieldValue { tag: 58, .. }) => {}
            other => panic!("an embedded SOH must be refused, got {other:?}"),
        }

        // And the factory still frames the next message.
        let heartbeat = factory.heartbeat(None);
        let frame = framed(&mut factory, 9, &heartbeat);
        assert_eq!(decode(&frame).msg_type(), &MsgType::Heartbeat);
    }

    #[test]
    fn test_logout_drops_an_empty_text() {
        let mut factory = factory();
        let logout = factory.logout(Some(""));
        let frame = framed(&mut factory, 1, &logout);
        let raw = decode(&frame);
        assert_eq!(raw.msg_type(), &MsgType::Logout);
        assert_eq!(raw.get_field_str(58), None);
    }

    #[test]
    fn test_application_message_frame() {
        let mut message = OutboundMessage::new(MsgType::NewOrderSingle);
        message.push_str(11, "ORDER-1").push_char(54, '1');

        let mut factory = factory();
        let pending = PendingMessage::application(message);
        let frame = framed(&mut factory, 7, &pending);
        let raw = decode(&frame);
        assert_eq!(raw.msg_type(), &MsgType::NewOrderSingle);
        assert_eq!(raw.get_field_str(34), Some("7"));
        assert_eq!(raw.get_field_str(11), Some("ORDER-1"));
        assert_eq!(raw.get_field_str(54), Some("1"));
        assert_eq!(raw.get_field_str(1128), None);
    }

    #[test]
    fn test_application_message_encodes_raw_data_as_a_counted_pair() {
        // A RawData payload carrying SOH is routed through the encoder's
        // LENGTH/DATA path, not put_raw, so the frame encodes and the payload
        // survives byte-exact instead of the message being refused.
        let payload: &[u8] = b"a\x01b=c";
        let mut message = OutboundMessage::new(MsgType::NewOrderSingle);
        message
            .push_str(11, "ORDER-1")
            .push_data(95, 96, payload.to_vec());

        let mut factory = factory();
        let pending = PendingMessage::application(message);
        let frame = framed(&mut factory, 7, &pending);
        let raw = decode(&frame);
        assert_eq!(raw.get_field_str(11), Some("ORDER-1"));
        assert_eq!(raw.get_field(95).map(|f| f.value), Some(b"5".as_slice()));
        assert_eq!(raw.get_field(96).map(|f| f.value), Some(payload));
    }

    #[test]
    fn test_header_stamps_configured_location_ids() {
        let mut config = config_for("FIX.4.4");
        config.sender_location_id = Some("LON".to_string());
        config.target_location_id = Some("NYC".to_string());
        let version = match wire_version(&config.begin_string) {
            Ok(version) => version,
            Err(err) => panic!("test fixture uses an unsupported version: {err}"),
        };
        let mut factory = MessageFactory::new(&config, version);

        let logon = factory.logon(30, false);
        let frame = framed(&mut factory, 1, &logon);
        let raw = decode(&frame);
        // SenderLocationID (142) and TargetLocationID (143) are routing fields
        // of the standard header, so a configured value is stamped onto every
        // outbound message.
        assert_eq!(raw.get_field_str(142), Some("LON"));
        assert_eq!(raw.get_field_str(143), Some("NYC"));
    }

    #[test]
    fn test_header_omits_unset_location_ids() {
        let mut factory = factory();
        let logon = factory.logon(30, false);
        let frame = framed(&mut factory, 1, &logon);
        let raw = decode(&frame);
        assert_eq!(raw.get_field_str(142), None);
        assert_eq!(raw.get_field_str(143), None);
    }

    #[test]
    fn test_wire_version_pre_fixt_passthrough() {
        assert_eq!(wire_version("FIX.4.4"), Ok(FixVersion::Fix44));
    }

    /// The mapping now lives once, in `ironfix_core::FixVersion`. This walks
    /// every version from that single list and asserts the engine frames each
    /// one exactly as the core table says — the cross-check that was
    /// impossible while the engine kept its own copy, since asserting against
    /// `ironfix-dictionary` would have taken a forbidden dependency.
    #[test]
    fn test_wire_version_matches_core_table_for_every_version() {
        for version in FixVersion::ALL {
            let resolved = wire_version(version.as_str());

            // Only a FIXT session with no application version is refused; it
            // cannot supply the required DefaultApplVerID (1137).
            if version.uses_fixt() && version.appl_ver_id().is_none() {
                match resolved {
                    Err(err) => assert_eq!(err.version, version.as_str()),
                    Ok(framable) => {
                        unreachable!("{version} must be refused, got {framable:?}")
                    }
                }
                continue;
            }

            assert_eq!(resolved, Ok(version));

            let mut factory = factory_for(version.as_str());
            let logon = factory.logon(30, false);
            let frame = framed(&mut factory, 1, &logon);
            let raw = decode(&frame);
            assert_eq!(
                raw.begin_string(),
                Ok(version.begin_string()),
                "{version} framed the wrong BeginString"
            );
            assert_eq!(
                raw.get_field_str(1137),
                version.appl_ver_id(),
                "{version} framed the wrong DefaultApplVerID"
            );
        }
    }

    #[test]
    fn test_wire_version_unknown_is_typed_error() {
        // An unsupported version must degrade to an explicit typed error, never
        // travel onto the wire as a fabricated BeginString.
        match wire_version("FIX.9.9") {
            Err(err) => assert_eq!(err.version, "FIX.9.9"),
            Ok(version) => panic!("FIX.9.9 must not be framed, got {version:?}"),
        }
    }

    #[test]
    fn test_wire_version_bare_fixt_is_rejected_for_missing_appl_ver_id() {
        // FIXT.1.1 names only the transport version. Its Logon requires
        // DefaultApplVerID (1137) and nothing here can supply it, so the
        // session is refused rather than sent without a required field.
        match wire_version("FIXT.1.1") {
            Err(err) => {
                assert_eq!(err.version, "FIXT.1.1");
                assert!(
                    err.detail.contains("1137"),
                    "the reason should name the missing field, got {}",
                    err.detail
                );
            }
            Ok(version) => panic!("bare FIXT.1.1 must be refused, got {version:?}"),
        }
    }

    #[test]
    fn test_wire_version_fix50_maps_to_fixt() {
        for (configured, appl_ver_id) in
            [("FIX.5.0", "7"), ("FIX.5.0SP1", "8"), ("FIX.5.0SP2", "9")]
        {
            match wire_version(configured) {
                Ok(version) => {
                    assert_eq!(version.begin_string(), "FIXT.1.1");
                    assert_eq!(version.appl_ver_id(), Some(appl_ver_id));
                }
                Err(err) => unreachable!("{configured} must be framable: {err}"),
            }
        }
    }

    #[test]
    fn test_fix50sp2_logon_carries_fixt_begin_string_and_default_appl_ver_id() {
        let mut factory = factory_for("FIX.5.0SP2");
        let logon = factory.logon(30, false);
        let frame = framed(&mut factory, 1, &logon);
        let raw = decode(&frame);
        assert_eq!(raw.begin_string(), Ok("FIXT.1.1"));
        assert_eq!(raw.get_field_str(1137), Some("9"));
    }

    #[test]
    fn test_fix50sp2_application_message_carries_appl_ver_id() {
        let mut message = OutboundMessage::new(MsgType::NewOrderSingle);
        message.push_str(11, "ORDER-1");

        let mut factory = factory_for("FIX.5.0SP2");
        let pending = PendingMessage::application(message);
        let frame = framed(&mut factory, 2, &pending);
        let raw = decode(&frame);
        assert_eq!(raw.begin_string(), Ok("FIXT.1.1"));
        assert_eq!(raw.get_field_str(1128), Some("9"));
    }

    #[test]
    fn test_resend_frame_preserves_body_and_stamps_poss_dup() {
        let mut message = OutboundMessage::new(MsgType::NewOrderSingle);
        message.push_str(11, "ORDER-1").push_char(54, '1');
        let mut factory = factory();
        let pending = PendingMessage::application(message);
        let original = framed(&mut factory, 7, &pending);
        let original_sending_time = some(
            field_of(&original, 52),
            "the original must carry SendingTime",
        );

        let resent = match resend_frame(&original) {
            Ok(frame) => frame,
            Err(err) => panic!("a factory frame must rebuild as a resend: {err}"),
        };
        let raw = decode(&resent);

        // Same message, same number: a resend re-occupies the sequence number
        // it was first sent under.
        assert_eq!(raw.msg_type(), &MsgType::NewOrderSingle);
        assert_eq!(raw.get_field_str(34), Some("7"));
        assert_eq!(raw.get_field_str(11), Some("ORDER-1"));
        assert_eq!(raw.get_field_str(54), Some("1"));
        assert_eq!(raw.get_field_str(49), Some("CLIENT"));
        assert_eq!(raw.get_field_str(56), Some("VENUE"));

        // The whole point: 122 is the *original* sending time, not a fresh one.
        assert_eq!(raw.get_field_str(43), Some("Y"));
        assert_eq!(raw.get_field_str(122), Some(original_sending_time.as_str()));
    }

    #[test]
    fn test_resend_frame_of_a_resend_preserves_the_first_sending_time() {
        // The intermediate frame is built by hand so its SendingTime (52, the
        // *prior* replay) and OrigSendingTime (122, the *first* transmission)
        // are deterministically different. Chaining two `resend_frame` calls
        // would let both land in the same millisecond — SendingTime is
        // millisecond-resolution — and hide a 122 overwritten with 52.
        const FIRST_SENT: &str = "20260721-10:00:00.000";
        const PRIOR_REPLAY: &str = "20260721-11:30:45.500";

        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "D");
        encoder.put_str(49, "CLIENT");
        encoder.put_str(56, "VENUE");
        encoder.put_uint(34, 3);
        encoder.put_bool(43, true);
        encoder.put_str(52, PRIOR_REPLAY);
        encoder.put_str(122, FIRST_SENT);
        encoder.put_str(11, "ORDER-1");
        let once = built(into_frame(&mut encoder));

        let twice = match resend_frame(&once) {
            Ok(frame) => frame,
            Err(err) => panic!("second resend must build: {err}"),
        };
        let raw = decode(&twice);

        // The prior 43/122 are re-emitted once in their header positions, never
        // duplicated.
        assert_eq!(raw.fields().filter(|field| field.tag == 43).count(), 1);
        assert_eq!(raw.fields().filter(|field| field.tag == 122).count(), 1);
        // The whole point: 122 still names the *first* transmission, not the
        // prior replay's SendingTime.
        assert_eq!(raw.get_field_str(122), Some(FIRST_SENT));
        assert_ne!(raw.get_field_str(122), Some(PRIOR_REPLAY));
        // 52 is this transmission's time, distinct from both, and the body and
        // number survive.
        assert_eq!(raw.get_field_str(34), Some("3"));
        assert_eq!(raw.get_field_str(11), Some("ORDER-1"));
        assert_eq!(raw.get_field_str(43), Some("Y"));
    }

    #[test]
    fn test_resend_frame_without_sending_time_is_a_typed_error() {
        // Built by hand: the factory always stamps 52.
        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "D");
        encoder.put_str(49, "CLIENT");
        encoder.put_str(56, "VENUE");
        encoder.put_uint(34, 4);
        let frame = built(into_frame(&mut encoder));

        match resend_frame(&frame) {
            Err(ResendError::MissingSendingTime) => {}
            Err(err) => panic!("expected MissingSendingTime, got {err}"),
            Ok(_) => panic!("a frame with no SendingTime must not be replayed"),
        }
    }

    #[test]
    fn test_resend_frame_of_undecodable_bytes_is_a_typed_error() {
        match resend_frame(b"not a fix message") {
            Err(ResendError::Decode(_)) => {}
            Err(err) => panic!("expected a decode error, got {err}"),
            Ok(_) => panic!("garbage must not rebuild into a frame"),
        }
    }

    #[test]
    fn test_resend_frame_preserves_a_length_data_pair() {
        // RawData (96) is framed by the count in RawDataLength (95), so the two
        // have to be rebuilt together or the frame is corrupt. The payload
        // carries SOH deliberately: that is what the pair exists for.
        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "D");
        encoder.put_str(49, "CLIENT");
        encoder.put_str(56, "VENUE");
        encoder.put_uint(34, 9);
        encoder.put_str(52, "20260721-10:00:00.000");
        encoder.put_data(95, 96, b"opaque\x01payload");
        let original = built(into_frame(&mut encoder));

        let resent = match resend_frame(&original) {
            Ok(frame) => frame,
            Err(err) => panic!("a frame with a LENGTH/DATA pair must rebuild: {err}"),
        };
        let raw = decode(&resent);

        assert_eq!(raw.get_field_str(95), Some("14"));
        assert_eq!(
            some(raw.get_field(96), "RawData must survive the rebuild").value,
            b"opaque\x01payload"
        );
        assert_eq!(raw.get_field_str(43), Some("Y"));
        assert_eq!(raw.get_field_str(122), Some("20260721-10:00:00.000"));
    }

    #[test]
    fn test_peer_identity_accepts_reversed_comp_ids() {
        let identity = PeerIdentity::new(&config_for("FIX.4.4"));
        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "0");
        encoder.put_str(49, "VENUE");
        encoder.put_str(56, "CLIENT");
        encoder.put_uint(34, 1);
        let frame = match encoder.finish() {
            Ok(frame) => frame.to_vec(),
            Err(err) => panic!("fixture frame must encode: {err}"),
        };

        assert_eq!(identity.validate(&decode(&frame)), Ok(()));
    }

    #[test]
    fn test_peer_identity_rejects_wrong_sender_comp_id() {
        let identity = PeerIdentity::new(&config_for("FIX.4.4"));
        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "0");
        encoder.put_str(49, "OTHER");
        encoder.put_str(56, "CLIENT");
        encoder.put_uint(34, 1);
        let frame = match encoder.finish() {
            Ok(frame) => frame.to_vec(),
            Err(err) => panic!("fixture frame must encode: {err}"),
        };

        assert_eq!(
            identity.validate(&decode(&frame)),
            Err(IdentityMismatch {
                tag: 49,
                expected: "VENUE".to_string(),
                received: "OTHER".to_string(),
                misplaced: false,
            })
        );
    }

    #[test]
    fn test_peer_identity_rejects_missing_sub_id_when_configured() {
        let config = config_for("FIX.4.4").with_sender_sub_id("DESK");
        let identity = PeerIdentity::new(&config);
        let mut encoder = Encoder::new("FIX.4.4");
        encoder.put_str(35, "0");
        encoder.put_str(49, "VENUE");
        encoder.put_str(56, "CLIENT");
        encoder.put_uint(34, 1);
        let frame = match encoder.finish() {
            Ok(frame) => frame.to_vec(),
            Err(err) => panic!("fixture frame must encode: {err}"),
        };

        // Our SenderSubID is the peer's TargetSubID (57).
        assert_eq!(
            identity.validate(&decode(&frame)),
            Err(IdentityMismatch {
                tag: 57,
                expected: "DESK".to_string(),
                received: String::new(),
                misplaced: false,
            })
        );
    }

    /// Builds a frame with an explicit field order, bypassing the encoder's
    /// header conformance so the body can carry the CompIDs.
    fn frame_with_fields(fields: &[(u32, &str)]) -> Vec<u8> {
        let fields: Vec<(u32, &[u8])> = fields
            .iter()
            .map(|(tag, value)| (*tag, value.as_bytes()))
            .collect();
        frame_with_raw_fields(&fields)
    }

    /// Builds a framed message from raw field bytes, so a value can carry a
    /// sequence that is not valid UTF-8.
    fn frame_with_raw_fields(fields: &[(u32, &[u8])]) -> Vec<u8> {
        let mut body = Vec::new();
        for (tag, value) in fields {
            body.extend_from_slice(format!("{tag}=").as_bytes());
            body.extend_from_slice(value);
            body.push(0x01);
        }
        let mut frame = Vec::new();
        frame.extend_from_slice(b"8=FIX.4.4\x01");
        frame.extend_from_slice(format!("9={}\x01", body.len()).as_bytes());
        frame.extend_from_slice(&body);
        let sum: u64 = frame.iter().map(|&byte| u64::from(byte)).sum();
        frame.extend_from_slice(format!("10={:03}\x01", sum % 256).as_bytes());
        frame
    }

    #[test]
    fn test_peer_identity_rejects_comp_ids_outside_the_standard_header() {
        let identity = PeerIdentity::new(&config_for("FIX.4.4"));
        // 11 (ClOrdID) opens the body; the CompIDs that follow it are not in
        // the standard header and identify nothing.
        let frame = frame_with_fields(&[
            (35, "D"),
            (34, "2"),
            (52, "20260721-10:00:00.000"),
            (11, "ORDER-1"),
            (49, "VENUE"),
            (56, "CLIENT"),
        ]);

        assert_eq!(
            identity.validate(&decode(&frame)),
            Err(IdentityMismatch {
                tag: 49,
                expected: "VENUE".to_string(),
                received: "VENUE".to_string(),
                misplaced: true,
            })
        );
    }

    #[test]
    fn test_peer_identity_accepts_comp_ids_across_the_whole_standard_header() {
        // 50/57/122 sit after MsgSeqNum in the standard header, so the run the
        // scan walks must not stop before them.
        let config = config_for("FIX.4.4")
            .with_sender_sub_id("DESK")
            .with_target_sub_id("MM");
        let identity = PeerIdentity::new(&config);
        let frame = frame_with_fields(&[
            (35, "D"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "2"),
            (50, "MM"),
            (57, "DESK"),
            (43, "Y"),
            (52, "20260721-10:00:00.000"),
            (122, "20260721-10:00:00.000"),
            (11, "ORDER-1"),
        ]);

        assert_eq!(identity.validate(&decode(&frame)), Ok(()));
    }

    #[test]
    fn test_parse_utc_timestamp_accepts_every_fix_precision() {
        // 1970-01-01T00:00:00Z is 0; the fractional part only adds millis.
        assert_eq!(parse_utc_timestamp_millis("19700101-00:00:00"), Some(0));
        assert_eq!(parse_utc_timestamp_millis("19700101-00:00:00.000"), Some(0));
        assert_eq!(
            parse_utc_timestamp_millis("19700101-00:00:00.123456"),
            Some(123)
        );
        assert_eq!(
            parse_utc_timestamp_millis("19700101-00:00:00.123456789"),
            Some(123)
        );
        assert_eq!(
            parse_utc_timestamp_millis("19700102-00:00:01.500"),
            Some(86_401_500)
        );
    }

    /// The parser must agree with the formatter it validates against, for
    /// dates on both sides of a leap day.
    #[test]
    fn test_parse_utc_timestamp_roundtrips_the_formatter() {
        for millis in [
            0,
            951_782_400_000,   // 2000-02-29, a leap day in a leap century
            1_078_012_800_000, // 2004-02-29
            1_769_000_000_123,
            4_102_444_800_999, // 2100-01-01, a common year divisible by 100
        ] {
            let Ok(timestamp) = Timestamp::from_millis(millis) else {
                unreachable!("{millis} is representable")
            };
            assert_eq!(
                parse_utc_timestamp_millis(timestamp.format_millis().as_str()),
                Some(millis),
                "{} did not round-trip",
                timestamp.format_millis()
            );
        }
    }

    #[test]
    fn test_parse_utc_timestamp_rejects_malformed_values() {
        for value in [
            "",
            "not-a-timestamp",
            "20260721",
            "20260721-10:00",
            "20260721 10:00:00",
            "20260721-10-00-00",
            "2026072a-10:00:00",
            "20260721-10:00:00.",
            "20260721-10:00:00.1234567890", // more than nanosecond precision
            "20260721-10:00:00x000",
            "20260231-10:00:00.000", // February has no 31st
            "20260732-10:00:00.000",
            "20261301-10:00:00.000",
            "20260721-24:00:00.000",
            "20260721-10:60:00.000",
            "20260721-10:00:61.000",
            "19690721-10:00:00.000", // before the epoch
        ] {
            assert_eq!(
                parse_utc_timestamp_millis(value),
                None,
                "{value} must not parse"
            );
        }
    }

    /// A leap second is a legal UTCTimestamp and must not be refused.
    #[test]
    fn test_parse_utc_timestamp_accepts_leap_second() {
        assert!(parse_utc_timestamp_millis("20261231-23:59:60.000").is_some());
    }

    fn guard_with(tolerance: Duration) -> SendingTimeGuard {
        SendingTimeGuard::new(&config_for("FIX.4.4").with_sending_time_tolerance(tolerance))
    }

    fn frame_sent_at(sending_time: &str) -> Vec<u8> {
        frame_with_fields(&[
            (35, "0"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "2"),
            (52, sending_time),
        ])
    }

    #[test]
    fn test_sending_time_guard_accepts_the_current_clock() {
        let frame = frame_sent_at(Timestamp::now().format_millis().as_str());

        assert_eq!(
            guard_with(Duration::from_secs(120)).validate(&decode(&frame)),
            Ok(())
        );
    }

    #[test]
    fn test_sending_time_guard_rejects_a_stale_timestamp_with_reason_10() {
        let frame = frame_sent_at("20200101-00:00:00.000");

        let problem = match guard_with(Duration::from_secs(120)).validate(&decode(&frame)) {
            Err(problem) => problem,
            Ok(()) => panic!("a five-year-old SendingTime must not pass"),
        };
        assert!(matches!(problem, SendingTimeProblem::Skewed { .. }));
        assert_eq!(problem.reject_reason().code, 10);
        assert_eq!(problem.reject_reason().ref_tag, Some(52));
    }

    /// The window is symmetric: a peer whose clock runs fast is as broken as
    /// one that runs slow.
    #[test]
    fn test_sending_time_guard_rejects_a_future_timestamp() {
        let frame = frame_sent_at("21000101-00:00:00.000");

        assert!(matches!(
            guard_with(Duration::from_secs(120)).validate(&decode(&frame)),
            Err(SendingTimeProblem::Skewed { .. })
        ));
    }

    #[test]
    fn test_sending_time_guard_accepts_skew_inside_the_window() {
        let Some(millis) = Timestamp::now().as_millis().checked_sub(60_000) else {
            unreachable!("the system clock is at least a minute past the epoch")
        };
        let Ok(stale) = Timestamp::from_millis(millis) else {
            unreachable!("a minute before now is representable")
        };
        let frame = frame_sent_at(stale.format_millis().as_str());

        // A minute of skew inside a two-minute window is tolerated: the check
        // is a broken-clock detector, not a latency budget.
        assert_eq!(
            guard_with(Duration::from_secs(120)).validate(&decode(&frame)),
            Ok(())
        );
    }

    #[test]
    fn test_sending_time_guard_reports_missing_and_malformed_fields() {
        let missing = frame_with_fields(&[(35, "0"), (49, "VENUE"), (56, "CLIENT"), (34, "2")]);
        let guard = guard_with(Duration::from_secs(120));
        assert_eq!(
            guard.validate(&decode(&missing)),
            Err(SendingTimeProblem::Missing)
        );
        assert_eq!(
            SendingTimeProblem::Missing.reject_reason().code,
            1,
            "a missing required header field is reason 1"
        );

        let malformed = frame_sent_at("yesterday");
        assert_eq!(
            guard.validate(&decode(&malformed)),
            Err(SendingTimeProblem::Malformed {
                value: "yesterday".to_string(),
            })
        );
        assert_eq!(
            SendingTimeProblem::Malformed {
                value: "yesterday".to_string()
            }
            .reject_reason()
            .code,
            6,
            "an unparseable timestamp is reason 6"
        );
    }

    #[test]
    fn test_sending_time_guard_zero_tolerance_disables_every_check() {
        let guard = guard_with(Duration::ZERO);
        assert!(guard.is_disabled());

        // Neither a wildly skewed value nor an absent one is reported once the
        // operator has switched the check off.
        let stale = frame_sent_at("20200101-00:00:00.000");
        assert_eq!(guard.validate(&decode(&stale)), Ok(()));
        let missing = frame_with_fields(&[(35, "0"), (49, "VENUE"), (56, "CLIENT"), (34, "2")]);
        assert_eq!(guard.validate(&decode(&missing)), Ok(()));
    }

    #[test]
    fn test_sending_time_guard_echoes_a_bounded_value() {
        let long = "9".repeat(200);
        let frame = frame_sent_at(&long);

        match guard_with(Duration::from_secs(120)).validate(&decode(&frame)) {
            Err(SendingTimeProblem::Malformed { value }) => {
                assert_eq!(value.chars().count(), MAX_ECHOED_SENDING_TIME);
            }
            other => panic!("a 200-character SendingTime must be malformed: {other:?}"),
        }
    }

    /// A tag 52 that appears only after the body opens is not in the standard
    /// header and names no sending time: it is treated as missing, mirroring the
    /// positional guard the CompID check already applies.
    #[test]
    fn test_sending_time_guard_treats_a_body_only_sending_time_as_missing() {
        // 11 (ClOrdID) opens the body; the 52 that follows it is not a header
        // field however well-formed its value is.
        let frame = frame_with_fields(&[
            (35, "D"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "2"),
            (11, "ORDER-1"),
            (52, "20260721-10:00:00.000"),
        ]);

        assert_eq!(
            guard_with(Duration::from_secs(120)).validate(&decode(&frame)),
            Err(SendingTimeProblem::Missing)
        );
    }

    /// A present tag 52 whose bytes are not valid UTF-8 is malformed (reason 6),
    /// not missing (reason 1): the field is there, it is just unreadable.
    #[test]
    fn test_sending_time_guard_reports_invalid_utf8_as_malformed() {
        let frame = frame_with_raw_fields(&[
            (35, b"0"),
            (49, b"VENUE"),
            (56, b"CLIENT"),
            (34, b"2"),
            (52, &[0xFF, 0xFE, 0xFD]),
        ]);

        let problem = match guard_with(Duration::from_secs(120)).validate(&decode(&frame)) {
            Err(problem) => problem,
            Ok(()) => panic!("a non-UTF-8 SendingTime must not pass"),
        };
        assert!(matches!(problem, SendingTimeProblem::Malformed { .. }));
        assert_eq!(
            problem.reject_reason().code,
            6,
            "a present but unreadable timestamp is reason 6, not the reason 1 of an absent one"
        );
    }

    /// A sub-millisecond tolerance floors to zero milliseconds, but the check
    /// stays enabled: it must still validate rather than treating the truncated
    /// value as the disabled sentinel.
    #[test]
    fn test_sending_time_guard_sub_millisecond_tolerance_stays_enabled() {
        let guard = guard_with(Duration::from_micros(500));
        assert!(!guard.is_disabled(), "a 500us tolerance is not disabled");

        // A wildly stale timestamp is still rejected under the tiny tolerance.
        let stale = frame_sent_at("20200101-00:00:00.000");
        assert!(matches!(
            guard.validate(&decode(&stale)),
            Err(SendingTimeProblem::Skewed { .. })
        ));

        // And an absent field is still reported, proving the presence check was
        // not switched off along with the skew check.
        let missing = frame_with_fields(&[(35, "0"), (49, "VENUE"), (56, "CLIENT"), (34, "2")]);
        assert_eq!(
            guard.validate(&decode(&missing)),
            Err(SendingTimeProblem::Missing)
        );
    }

    #[test]
    fn test_header_seq_num_reads_the_header_field() {
        let frame = frame_with_fields(&[
            (35, "A"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "7"),
            (52, "20260721-10:00:00.000"),
        ]);
        assert_eq!(header_seq_num(&decode(&frame)), Some(7));
    }

    #[test]
    fn test_header_seq_num_ignores_a_body_only_seq_num() {
        // 11 (ClOrdID) opens the body; the 34 that follows it is not the
        // standard-header MsgSeqNum and must read as absent.
        let frame = frame_with_fields(&[
            (35, "A"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (52, "20260721-10:00:00.000"),
            (11, "ORDER-1"),
            (34, "7"),
        ]);
        assert_eq!(header_seq_num(&decode(&frame)), None);
    }

    #[test]
    fn test_header_seq_num_rejects_a_non_numeric_value() {
        let frame = frame_with_fields(&[
            (35, "A"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "not-a-number"),
        ]);
        assert_eq!(header_seq_num(&decode(&frame)), None);
    }

    /// Reads a `HeartBtInt` (108) into a Logon fixture.
    fn logon_with_heartbeat(heartbeat: &str) -> Vec<u8> {
        frame_with_fields(&[
            (35, "A"),
            (49, "VENUE"),
            (56, "CLIENT"),
            (34, "1"),
            (52, "20260721-10:00:00.000"),
            (98, "0"),
            (108, heartbeat),
        ])
    }

    #[test]
    fn test_parse_heartbeat_interval_accepts_a_sane_value() {
        assert_eq!(
            parse_heartbeat_interval(&decode(&logon_with_heartbeat("30"))),
            Ok(30)
        );
    }

    #[test]
    fn test_parse_heartbeat_interval_accepts_zero() {
        // 108=0 is legal FIX ("do not send heartbeats") and is not specially
        // handled today; the bound only refuses values that would overflow.
        assert_eq!(
            parse_heartbeat_interval(&decode(&logon_with_heartbeat("0"))),
            Ok(0)
        );
    }

    #[test]
    fn test_parse_heartbeat_interval_rejects_u64_max() {
        // The remote-abort case: Duration::from_secs(u64::MAX) overflows the
        // heartbeat clock's interval + grace, which aborts under panic=abort.
        match parse_heartbeat_interval(&decode(&logon_with_heartbeat(&u64::MAX.to_string()))) {
            Err(HeartBtIntProblem::OutOfRange { secs }) => assert_eq!(secs, u64::MAX),
            other => panic!("u64::MAX HeartBtInt must be out of range, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_heartbeat_interval_rejects_over_one_day() {
        let over = MAX_HEARTBEAT_INTERVAL_SECS + 1;
        match parse_heartbeat_interval(&decode(&logon_with_heartbeat(&over.to_string()))) {
            Err(HeartBtIntProblem::OutOfRange { secs }) => assert_eq!(secs, over),
            other => panic!("an over-a-day HeartBtInt must be out of range, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_heartbeat_interval_rejects_missing_and_malformed() {
        let missing = frame_with_fields(&[(35, "A"), (49, "VENUE"), (56, "CLIENT"), (34, "1")]);
        assert_eq!(
            parse_heartbeat_interval(&decode(&missing)),
            Err(HeartBtIntProblem::Missing)
        );

        match parse_heartbeat_interval(&decode(&logon_with_heartbeat("thirty"))) {
            Err(HeartBtIntProblem::Malformed { value }) => assert_eq!(value, "thirty"),
            other => panic!("a non-numeric HeartBtInt must be malformed, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_heartbeat_interval_echoes_a_bounded_value() {
        let long = "9".repeat(200);
        match parse_heartbeat_interval(&decode(&logon_with_heartbeat(&long))) {
            // 200 nines parse as u64 overflow -> Malformed, echoed bounded.
            Err(HeartBtIntProblem::Malformed { value }) => {
                assert_eq!(value.chars().count(), MAX_ECHOED_HEARTBEAT);
            }
            other => panic!("a 200-digit HeartBtInt must be malformed, got {other:?}"),
        }
    }
}