ctrader-connector 0.3.10

Client library for the cTrader Open API and the cTrader FIX 4.4 API
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
//! Connection task and the handle callers talk to it through.
//!
//! One task owns the socket. Callers hold a cloneable [`Connection`]; a request travels over a
//! bounded command channel, is framed with a fresh `clientMsgId` and resolves when the response
//! carrying the same id arrives. Every id comes from one counter that requests and replayed
//! requests share and that only ever grows, so no id is used twice on a connection and a late
//! answer to a request given up is never taken for the answer to another one. Messages the
//! server pushes on its own are fanned out as [`Event`]s. The task sends a heartbeat whenever
//! nothing was written for the heartbeat interval, which keeps the server from closing an idle
//! connection.
//!
//! Deadlines: nothing the task waits for on the socket is open-ended. A write that does not
//! complete within the time allowed for a response fails with
//! [`TransportError::WriteTimeout`], and a server that sends nothing at all, not even a
//! heartbeat, for the period set with [`ConnectionOptions::inbound_timeout`] fails the
//! connection with [`TransportError::Idle`]. Both count as a loss of the connection.
//! Every duration an option carries is added to the clock without overflow. A heartbeat
//! interval, a silence allowed or a time allowed for a response of more than thirty years is
//! never due, so [`Duration::MAX`] stands for never and turns the wait it is given to off. A
//! pause before a request is sent again ends thirty years ahead at the latest.
//!
//! Backpressure: the command channel is bounded, so callers wait while the task is busy, and the
//! event stream is a bounded broadcast, so a subscriber that falls behind skips the oldest
//! events instead of stalling the task.
//!
//! Limits: the server accepts a number of requests per second on one connection, fewer for
//! historical data. The task holds requests back so that neither limit is exceeded, and when
//! the server still answers that a limit was exceeded it pauses and sends the request again, up
//! to the configured number of retries.
//!
//! Reconnection: when the socket is lost the task fails the requests in flight, reports
//! [`Event::Disconnected`] and connects again, waiting twice as long before every further
//! attempt. Once connected it sends the registered requests again in the order of their
//! [`ReplayStage`] (application, accounts, subscriptions) and then reports
//! [`Event::Reconnected`]. The registered requests are read one at a time, each just before it
//! is sent, so a registration removed meanwhile is not replayed and one added meanwhile is.
//! Requests made while the connection is down fail at once with the reason of the loss.
//!
//! End of an authorisation: the server can end the authorisation of an account, or of the
//! application, while the connection stays up: it announces that an access token is no longer
//! valid, that it dropped the session of an account, or that it ends the session of the
//! application. The same holds when it refuses the access token while an account is authorised
//! again after a reconnection. The task then reports [`Event::SessionEnded`], forgets the
//! registered requests of the session, so that nothing is replayed with a dead token, and
//! answers every later request of the session with [`ConnectorError::SessionEnded`] without
//! sending it. The session is usable again once it is authorised anew on this connection: an
//! account with a valid access token, the application with its credentials followed by its
//! accounts.
//!
//! Requests that must not arrive twice: a request made with [`Connection::request_once`], an
//! order for one, is written at most once. It is neither sent again after a limit error nor
//! replayed, and when the connection fails or the time allowed runs out after it was written
//! the caller is told that its outcome is unknown, with [`ConnectorError::OutcomeUnknown`].

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::future::pending;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::{Instant, sleep, sleep_until, timeout};

use crate::common::config::{
    ConfigurationOpenApi, DEFAULT_BACKOFF, DEFAULT_RECONNECT_DELAY, DEFAULT_RETRIES,
    DEFAULT_TIMEOUT,
};
use crate::common::errors::{
    ConnectorError, ErrorCode, Interruption, ServerError, SessionEndCause, SessionEnded,
    TransportError,
};
use crate::common::ids::AccountId;
use crate::open_api::messages::{
    ProtoErrorRes, ProtoHeartbeatEvent, ProtoMessage, ProtoOaAccountAuthReq, ProtoOaAccountAuthRes,
    ProtoOaApplicationAuthReq, ProtoOaApplicationAuthRes, ProtoOaErrorRes,
};
use crate::open_api::payload::{Payload, Request, account_of, is_historical, sessions_ended_by};
use crate::open_api::transport::{Connect, Framed};

/// Pause after the last write before a heartbeat is sent.
pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);

/// Number of requests that may wait in the command channel.
pub const DEFAULT_COMMAND_CAPACITY: usize = 64;

/// Number of events kept for a subscriber that falls behind.
pub const DEFAULT_EVENT_CAPACITY: usize = 1024;

/// Largest number of requests that may wait in the command channel; a larger number asked for
/// is lowered to it.
pub const MAX_COMMAND_CAPACITY: usize = 65_536;

/// Largest number of events kept for a subscriber that falls behind; a larger number asked for
/// is lowered to it, because the room for the events is set aside when the connection opens.
pub const MAX_EVENT_CAPACITY: usize = 65_536;

/// Requests the server accepts per second on one connection, historical data excluded.
pub const REQUEST_LIMIT: u32 = 50;

/// Requests for historical data the server accepts per second on one connection.
pub const HISTORICAL_LIMIT: u32 = 5;

/// Longest pause after the server answered that a limit was exceeded.
pub const BACKOFF_LIMIT: Duration = Duration::from_secs(30);

const LIMIT_WINDOW: Duration = Duration::from_millis(1100);

/// Longest pause between two reconnection attempts.
pub const RECONNECT_DELAY_LIMIT: Duration = Duration::from_secs(60);

const SHORTEST_INTERVAL: Duration = Duration::from_millis(1);

/// Pause between two heartbeats the server sends on a connection that is otherwise quiet.
pub const SERVER_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);

/// Silence of the server after which the connection counts as lost unless another period is
/// set: two and a half times [`SERVER_HEARTBEAT_INTERVAL`], so one heartbeat of the server may
/// go missing, and the next one be late by half an interval, before a connection is given up.
pub const DEFAULT_INBOUND_TIMEOUT: Duration = Duration::from_secs(75);

const LONGEST_WAIT: Duration = Duration::from_secs(30 * 365 * 86_400);

macro_rules! log_debug {
    ($($argument:tt)*) => {{
        #[cfg(feature = "logging")]
        tracing::debug!($($argument)*);
    }};
}

/// Tunable behaviour of a [`Connection`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct ConnectionOptions {
    timeout: Duration,
    heartbeat_interval: Duration,
    command_capacity: usize,
    event_capacity: usize,
    reconnect_delay: Duration,
    reconnect_attempts: Option<u32>,
    request_limit: u32,
    historical_limit: u32,
    retries: u32,
    backoff: Duration,
    inbound_timeout: Option<Duration>,
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_TIMEOUT,
            heartbeat_interval: HEARTBEAT_INTERVAL,
            command_capacity: DEFAULT_COMMAND_CAPACITY,
            event_capacity: DEFAULT_EVENT_CAPACITY,
            reconnect_delay: DEFAULT_RECONNECT_DELAY,
            reconnect_attempts: None,
            request_limit: REQUEST_LIMIT,
            historical_limit: HISTORICAL_LIMIT,
            retries: DEFAULT_RETRIES,
            backoff: DEFAULT_BACKOFF,
            inbound_timeout: None,
        }
    }
}

impl From<&ConfigurationOpenApi> for ConnectionOptions {
    fn from(configuration: &ConfigurationOpenApi) -> Self {
        Self::default()
            .timeout(configuration.timeout())
            .reconnect_delay(configuration.reconnect_delay())
            .retries(configuration.retries())
            .backoff(configuration.backoff())
    }
}

impl ConnectionOptions {
    /// Starts from the default options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the time allowed between sending a request and receiving its response.
    ///
    /// A duration below one millisecond is raised to one millisecond.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout.max(SHORTEST_INTERVAL);
        self
    }

    /// Sets the pause after the last write before a heartbeat is sent.
    ///
    /// A duration below one millisecond is raised to one millisecond.
    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
        self.heartbeat_interval = interval.max(SHORTEST_INTERVAL);
        self
    }

    /// Sets the number of requests that may wait in the command channel.
    ///
    /// Zero is raised to one and a number above [`MAX_COMMAND_CAPACITY`] is lowered to it.
    pub fn command_capacity(mut self, capacity: usize) -> Self {
        self.command_capacity = capacity.clamp(1, MAX_COMMAND_CAPACITY);
        self
    }

    /// Sets the number of events kept for a subscriber that falls behind.
    ///
    /// Zero is raised to one and a number above [`MAX_EVENT_CAPACITY`] is lowered to it.
    pub fn event_capacity(mut self, capacity: usize) -> Self {
        self.event_capacity = capacity.clamp(1, MAX_EVENT_CAPACITY);
        self
    }

    /// Sets the pause before the first reconnection attempt; it doubles before every further
    /// attempt up to [`RECONNECT_DELAY_LIMIT`].
    ///
    /// A duration below one millisecond is raised to one millisecond.
    pub fn reconnect_delay(mut self, delay: Duration) -> Self {
        self.reconnect_delay = delay.max(SHORTEST_INTERVAL);
        self
    }

    /// Sets how many times in a row the task tries to connect again before it gives up.
    ///
    /// `None` keeps trying, which is the default; `Some(0)` turns reconnection off.
    pub const fn reconnect_attempts(mut self, attempts: Option<u32>) -> Self {
        self.reconnect_attempts = attempts;
        self
    }

    /// Sets the number of requests sent per second, historical data excluded; at least one.
    pub fn request_limit(mut self, limit: u32) -> Self {
        self.request_limit = limit.max(1);
        self
    }

    /// Sets the number of requests for historical data sent per second; at least one.
    pub fn historical_limit(mut self, limit: u32) -> Self {
        self.historical_limit = limit.max(1);
        self
    }

    /// Sets how often a request is sent again after the server answered that a limit was
    /// exceeded; zero hands the error to the caller at once.
    pub const fn retries(mut self, retries: u32) -> Self {
        self.retries = retries;
        self
    }

    /// Sets the pause after the server answered that a limit was exceeded; it doubles with
    /// every retry of the same request up to [`BACKOFF_LIMIT`].
    ///
    /// A duration below one millisecond is raised to one millisecond.
    pub fn backoff(mut self, backoff: Duration) -> Self {
        self.backoff = backoff.max(SHORTEST_INTERVAL);
        self
    }

    /// Sets how long the server may stay silent before the connection counts as lost.
    ///
    /// Every frame the server sends, heartbeats included, starts the period anew. When it runs
    /// out the task reports [`Event::Disconnected`] with [`TransportError::Idle`] and connects
    /// again. Left unset, the period is [`DEFAULT_INBOUND_TIMEOUT`]. It follows from the pace of
    /// the server alone, which sends a heartbeat of its own every
    /// [`SERVER_HEARTBEAT_INTERVAL`] on a connection that is otherwise quiet, and from nothing
    /// the client is set to do: neither the heartbeat interval nor the time allowed for a
    /// response changes it. A period shorter than the pace of the server gives up connections
    /// that are in order.
    ///
    /// A duration below one millisecond is raised to one millisecond. [`Duration::MAX`] turns
    /// the watch off: the server may then stay silent for as long as it likes.
    pub fn inbound_timeout(mut self, period: Duration) -> Self {
        self.inbound_timeout = Some(period.max(SHORTEST_INTERVAL));
        self
    }

    fn silence(&self) -> Duration {
        self.inbound_timeout.unwrap_or(DEFAULT_INBOUND_TIMEOUT)
    }
}

/// Something that happened on the connection without a request asking for it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
    /// The server sent a message that answers no pending request.
    Message(ProtoMessage),
    /// The connection was lost for the given reason; reconnection follows.
    Disconnected(TransportError),
    /// An attempt to connect again failed; another one follows unless the limit is reached.
    ReconnectFailed {
        /// Number of the attempt since the loss, starting at one.
        attempt: u32,
        /// Reason the attempt failed.
        reason: TransportError,
    },
    /// The connection is established again and the registered requests were replayed.
    Reconnected {
        /// Number of the attempt that succeeded, starting at one.
        attempt: u32,
    },
    /// A registered request was refused or left unanswered while it was replayed.
    ReplayFailed {
        /// Key the request was registered under.
        key: ReplayKey,
        /// Failure of the replayed request.
        error: ConnectorError,
    },
    /// The server ended the authorisation of a session; its requests fail with
    /// [`ConnectorError::SessionEnded`] until it is authorised again.
    SessionEnded(SessionEnded),
}

impl Event {
    /// Returns the pushed message when the event carries one of type `M`.
    #[must_use]
    pub fn decode<M: Payload>(&self) -> Option<M> {
        match self {
            Self::Message(message) => M::from_message(message).ok(),
            _ => None,
        }
    }
}

/// Counters of a connection since it was opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Stats {
    /// Requests written to the socket.
    pub requests_sent: u64,
    /// Heartbeats written to the socket.
    pub heartbeats_sent: u64,
    /// Heartbeats received from the server.
    pub heartbeats_received: u64,
    /// Times the connection was established again after a loss.
    pub reconnects: u64,
    /// Requests sent again after the server answered that a limit was exceeded.
    pub throttle_retries: u64,
}

#[derive(Debug, Default)]
struct Counters {
    requests_sent: AtomicU64,
    heartbeats_sent: AtomicU64,
    heartbeats_received: AtomicU64,
    reconnects: AtomicU64,
    throttle_retries: AtomicU64,
}

fn bump(counter: &AtomicU64) {
    counter.fetch_add(1, Ordering::Relaxed);
}

/// Phase of the restoration a replayed request belongs to; earlier phases are replayed first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ReplayStage {
    /// Authorisation of the application.
    Application,
    /// Authorisation of a trading account.
    Account,
    /// Subscription to a stream of events.
    Subscription,
}

/// Name a request is registered under for replay after a reconnection.
///
/// Registering another request under the same key replaces the earlier one.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReplayKey {
    stage: ReplayStage,
    id: String,
}

impl ReplayKey {
    /// Builds a key from the phase and a name unique within it.
    #[must_use]
    pub fn new(stage: ReplayStage, id: impl Into<String>) -> Self {
        Self {
            stage,
            id: id.into(),
        }
    }

    /// Returns the phase the request is replayed in.
    #[must_use]
    pub const fn stage(&self) -> ReplayStage {
        self.stage
    }

    /// Returns the name of the request within its phase.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }
}

#[derive(Clone, PartialEq, Eq)]
struct Stored {
    payload_type: u32,
    payload: Vec<u8>,
}

type Replays = BTreeMap<ReplayKey, Stored>;

type Reply = oneshot::Sender<Result<ProtoMessage, ConnectorError>>;

struct Outbound {
    payload_type: u32,
    payload: Vec<u8>,
    historical: bool,
    once: bool,
    attempts: u32,
    reply: Reply,
}

impl Outbound {
    fn interrupted(&self, by: Interruption) -> ConnectorError {
        if self.once {
            ConnectorError::OutcomeUnknown(by)
        } else {
            match by {
                Interruption::Timeout(limit) => ConnectorError::Timeout(limit),
                Interruption::Transport(reason) => ConnectorError::Transport(reason),
                Interruption::Skipped => ConnectorError::OutcomeUnknown(by),
            }
        }
    }
}

#[derive(Default)]
struct Ended {
    application: Option<SessionEndCause>,
    accounts: BTreeMap<AccountId, SessionEndCause>,
}

impl Ended {
    fn refusal(&self, payload_type: u32, payload: &[u8]) -> Option<SessionEnded> {
        if payload_type == ProtoOaApplicationAuthReq::PAYLOAD_TYPE {
            return None;
        }
        if let Some(cause) = &self.application {
            return Some(SessionEnded::new(None, cause.clone()));
        }
        if payload_type == ProtoOaAccountAuthReq::PAYLOAD_TYPE {
            return None;
        }
        let account = account_of(payload_type, payload)?;
        let cause = self.accounts.get(&account)?;
        Some(SessionEnded::new(Some(account), cause.clone()))
    }

    fn granted(&mut self, answer: &ProtoMessage) {
        if answer.payload_type == ProtoOaApplicationAuthRes::PAYLOAD_TYPE {
            self.application = None;
        } else if answer.payload_type == ProtoOaAccountAuthRes::PAYLOAD_TYPE {
            let payload = answer.payload.as_deref().unwrap_or_default();
            if let Some(account) = account_of(answer.payload_type, payload) {
                self.accounts.remove(&account);
            }
        }
    }
}

fn token_refused(key: &ReplayKey, stored: &Stored, error: &ConnectorError) -> Option<SessionEnded> {
    let ConnectorError::Server(error) = error else {
        return None;
    };
    let dead = matches!(
        error.code,
        ErrorCode::ChAccessTokenInvalid | ErrorCode::OaAuthTokenExpired
    );
    if !dead || key.stage() != ReplayStage::Account {
        return None;
    }
    let account = account_of(stored.payload_type, &stored.payload)?;
    Some(SessionEnded::new(
        Some(account),
        SessionEndCause::TokenRefused(error.code.clone()),
    ))
}

enum Command {
    Request(Outbound),
    Replay(ReplayKey, Option<Stored>),
    Reconnect,
    Shutdown,
}

/// Cloneable handle of a connection task.
///
/// The task ends when [`Connection::shutdown`] is called or the last handle is dropped.
#[derive(Debug, Clone)]
pub struct Connection {
    commands: mpsc::Sender<Command>,
    events: broadcast::Sender<Event>,
    counters: Arc<Counters>,
    task: Arc<Mutex<Option<JoinHandle<()>>>>,
}

impl Connection {
    /// Connects to `host` on `port` and starts the connection task.
    ///
    /// Must be called from within a Tokio runtime.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Transport`] when the connection cannot be established.
    pub async fn open<C: Connect>(
        connector: C,
        host: &str,
        port: u16,
        options: ConnectionOptions,
    ) -> Result<Self, ConnectorError> {
        let stream = connector.connect(host, port).await?;
        log_debug!(host, port, "connected");
        let (commands, receiver) = mpsc::channel(options.command_capacity);
        let (events, _) = broadcast::channel(options.event_capacity);
        let counters = Arc::new(Counters::default());
        let actor = Actor {
            connector,
            host: host.to_owned(),
            port,
            heartbeat_at: within(Instant::now(), options.heartbeat_interval),
            silent_at: within(Instant::now(), options.silence()),
            options,
            commands: receiver,
            events: events.clone(),
            counters: Arc::clone(&counters),
            queue: VecDeque::new(),
            pending: HashMap::new(),
            deadlines: VecDeque::new(),
            replays: Replays::new(),
            ended: Ended::default(),
            throttles: [Throttle::default(), Throttle::default()],
            paused_until: None,
            send_at: None,
            next_id: 0,
        };
        let task = tokio::spawn(actor.run(Framed::new(stream)));
        Ok(Self {
            commands,
            events,
            counters,
            task: Arc::new(Mutex::new(Some(task))),
        })
    }

    /// Sends a request and waits for its response.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Server`] when the server answers with an error,
    /// [`ConnectorError::Timeout`] when it does not answer in time,
    /// [`ConnectorError::Transport`] when the connection fails while the request is pending,
    /// [`ConnectorError::UnexpectedResponse`] when the answer has another type, and
    /// [`ConnectorError::Closed`] when the connection is shut down.
    pub async fn request<R: Request>(&self, request: &R) -> Result<R::Response, ConnectorError> {
        let message = self
            .send(
                R::PAYLOAD_TYPE,
                request.encode_to_vec(),
                R::HISTORICAL,
                false,
            )
            .await?;
        R::Response::from_message(&message)
    }

    /// Sends an already encoded request and waits for the envelope of its response.
    ///
    /// # Errors
    ///
    /// Fails like [`Connection::request`], except that the type of the answer is not checked.
    pub async fn request_message(
        &self,
        payload_type: u32,
        payload: Vec<u8>,
    ) -> Result<ProtoMessage, ConnectorError> {
        self.send(payload_type, payload, is_historical(payload_type), false)
            .await
    }

    /// Sends an already encoded request that the server must not receive twice, such as an
    /// order, and waits for the envelope of the first message that answers it.
    ///
    /// The request is written to the socket at most once. It is not sent again when the server
    /// answers that a limit was exceeded, which is handed to the caller as the refusal it is,
    /// and it is never replayed after a reconnection. The answer is also reported to the
    /// subscribers of [`Connection::events`] as an [`Event::Message`], ahead of the messages
    /// the server sends after it, so that a reader of the events sees all the server said about
    /// the request in the order it was said.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::OutcomeUnknown`] when the request was written and the
    /// connection failed or the time allowed ran out before an answer arrived, in which case
    /// the server may or may not have acted on it. [`ConnectorError::Transport`] means the
    /// request was not written: the connection was down when it was made or was lost while it
    /// waited its turn. [`ConnectorError::Closed`] is returned when the connection is shut down
    /// from this side, also while the answer is awaited. Fails like
    /// [`Connection::request_message`] otherwise.
    pub async fn request_once(
        &self,
        payload_type: u32,
        payload: Vec<u8>,
    ) -> Result<ProtoMessage, ConnectorError> {
        self.send(payload_type, payload, is_historical(payload_type), true)
            .await
    }

    async fn send(
        &self,
        payload_type: u32,
        payload: Vec<u8>,
        historical: bool,
        once: bool,
    ) -> Result<ProtoMessage, ConnectorError> {
        let (reply, response) = oneshot::channel();
        let outbound = Outbound {
            payload_type,
            payload,
            reply,
            historical,
            once,
            attempts: 0,
        };
        self.commands
            .send(Command::Request(outbound))
            .await
            .map_err(|_| ConnectorError::Closed)?;
        response.await.map_err(|_| ConnectorError::Closed)?
    }

    /// Registers a request to be sent again, under `key`, after every reconnection.
    ///
    /// The request is not sent now. Requests are replayed in the order of their keys. A request
    /// registered or replaced while the connection is being restored is replayed before
    /// [`Event::Reconnected`] is reported.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Closed`] when the connection is shut down.
    pub async fn register_replay<R: Request>(
        &self,
        key: ReplayKey,
        request: &R,
    ) -> Result<(), ConnectorError> {
        let stored = Stored {
            payload_type: R::PAYLOAD_TYPE,
            payload: request.encode_to_vec(),
        };
        self.command(Command::Replay(key, Some(stored))).await
    }

    /// Forgets the request registered under `key`.
    ///
    /// While the connection is being restored the registered requests are looked up one at a
    /// time, each just before it is sent, so a request removed before its turn is not replayed.
    /// A request that was replayed already stays in force on the server: the task knows no
    /// request that would withdraw it, which is left to the caller once
    /// [`Event::Reconnected`] is reported.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Closed`] when the connection is shut down.
    pub async fn remove_replay(&self, key: ReplayKey) -> Result<(), ConnectorError> {
        self.command(Command::Replay(key, None)).await
    }

    /// Drops the socket on this side, which starts a reconnection as a loss would.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Closed`] when the connection is shut down.
    pub async fn force_reconnect(&self) -> Result<(), ConnectorError> {
        self.command(Command::Reconnect).await
    }

    async fn command(&self, command: Command) -> Result<(), ConnectorError> {
        self.commands
            .send(command)
            .await
            .map_err(|_| ConnectorError::Closed)
    }

    /// Subscribes to the events of the connection, starting with the next one.
    ///
    /// A subscriber that falls more than the event capacity behind skips the oldest events and
    /// is told how many were skipped.
    #[must_use]
    pub fn events(&self) -> broadcast::Receiver<Event> {
        self.events.subscribe()
    }

    /// Waits until the connection task has ended, after which every request fails with
    /// [`ConnectorError::Closed`].
    pub async fn closed(&self) {
        self.commands.closed().await;
    }

    /// Returns the counters of the connection.
    #[must_use]
    pub fn stats(&self) -> Stats {
        Stats {
            requests_sent: self.counters.requests_sent.load(Ordering::Relaxed),
            heartbeats_sent: self.counters.heartbeats_sent.load(Ordering::Relaxed),
            heartbeats_received: self.counters.heartbeats_received.load(Ordering::Relaxed),
            reconnects: self.counters.reconnects.load(Ordering::Relaxed),
            throttle_retries: self.counters.throttle_retries.load(Ordering::Relaxed),
        }
    }

    /// Stops the connection task and waits until the socket is closed.
    ///
    /// Requests still pending fail with [`ConnectorError::Closed`]. Calling it again is
    /// harmless.
    pub async fn shutdown(&self) {
        let _ = self.commands.send(Command::Shutdown).await;
        let task = self
            .task
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(task) = task {
            let _ = task.await;
        }
    }
}

#[derive(Debug)]
enum Exit {
    Shutdown,
    Lost(TransportError),
}

struct Actor<C: Connect> {
    connector: C,
    host: String,
    port: u16,
    options: ConnectionOptions,
    commands: mpsc::Receiver<Command>,
    events: broadcast::Sender<Event>,
    counters: Arc<Counters>,
    queue: VecDeque<Outbound>,
    pending: HashMap<String, Outbound>,
    deadlines: VecDeque<(Option<Instant>, String)>,
    replays: Replays,
    ended: Ended,
    throttles: [Throttle; 2],
    paused_until: Option<Instant>,
    send_at: Option<Instant>,
    next_id: u64,
    heartbeat_at: Option<Instant>,
    silent_at: Option<Instant>,
}

impl<C: Connect> Actor<C> {
    async fn run(mut self, mut framed: Framed<C::Stream>) {
        let error = loop {
            match self.serve(&mut framed).await {
                Exit::Shutdown => break ConnectorError::Closed,
                Exit::Lost(reason) => {
                    log_debug!(%reason, "connection lost");
                    close(&mut framed, self.options.timeout).await;
                    self.fail_in_flight(&reason);
                    let _ = self.events.send(Event::Disconnected(reason.clone()));
                    match self.reconnect(reason).await {
                        Ok(fresh) => framed = fresh,
                        Err(error) => break error,
                    }
                }
            }
        };
        self.fail_all(&error);
        close(&mut framed, self.options.timeout).await;
    }

    async fn reconnect(
        &mut self,
        reason: TransportError,
    ) -> Result<Framed<C::Stream>, ConnectorError> {
        let mut last = reason;
        let mut delay = self.options.reconnect_delay;
        let longest = RECONNECT_DELAY_LIMIT.max(delay);
        let mut attempt = 0_u32;
        loop {
            if self
                .options
                .reconnect_attempts
                .is_some_and(|limit| attempt >= limit)
            {
                return Err(ConnectorError::Transport(last));
            }
            attempt = attempt.saturating_add(1);
            hold(&mut self.commands, &mut self.replays, &last, sleep(delay)).await?;
            delay = delay.saturating_mul(2).min(longest);
            match self.restore(&last).await? {
                Ok((framed, replays_sent)) => {
                    log_debug!(attempt, "reconnected");
                    bump(&self.counters.reconnects);
                    let seeded = replays_sent
                        .min(usize::try_from(self.options.request_limit).unwrap_or(usize::MAX));
                    if let Some(throttle) = self.throttles.first_mut() {
                        throttle
                            .sent
                            .extend(std::iter::repeat_n(Instant::now(), seeded));
                    }
                    self.heartbeat_at = within(Instant::now(), self.options.heartbeat_interval);
                    self.silent_at = within(Instant::now(), self.options.silence());
                    let _ = self.events.send(Event::Reconnected { attempt });
                    return Ok(framed);
                }
                Err(reason) => {
                    log_debug!(attempt, %reason, "reconnection failed");
                    let _ = self.events.send(Event::ReconnectFailed {
                        attempt,
                        reason: reason.clone(),
                    });
                    last = reason;
                }
            }
        }
    }

    async fn restore(
        &mut self,
        reason: &TransportError,
    ) -> Result<Result<(Framed<C::Stream>, usize), TransportError>, ConnectorError> {
        let limit = self.options.timeout;
        let spacing = LIMIT_WINDOW / self.options.request_limit;
        let connect = self.connector.connect(&self.host, self.port);
        let mut framed = match hold(&mut self.commands, &mut self.replays, reason, connect).await? {
            Ok(stream) => Framed::new(stream),
            Err(reason) => return Ok(Err(reason)),
        };
        let mut sent = Replays::new();
        loop {
            let next = self
                .replays
                .iter()
                .find(|(key, stored)| sent.get(*key) != Some(*stored))
                .map(|(key, stored)| (key.clone(), stored.clone()));
            let Some((key, stored)) = next else {
                return Ok(Ok((framed, sent.len())));
            };
            sent.insert(key.clone(), stored.clone());
            let id = self.fresh_id();
            let mut pushed = Vec::new();
            let step = Box::pin(replay(
                &mut framed,
                id,
                stored.clone(),
                limit,
                &self.events,
                &mut pushed,
            ));
            let answer = match hold(&mut self.commands, &mut self.replays, reason, step).await? {
                Ok(answer) => answer,
                Err(reason) => return Ok(Err(reason)),
            };
            for session in pushed {
                self.end(session);
            }
            match answer {
                Ok(answer) => self.ended.granted(&answer),
                Err(error) => {
                    log_debug!(%error, "replayed request failed");
                    let refused = token_refused(&key, &stored, &error);
                    let _ = self.events.send(Event::ReplayFailed { key, error });
                    if let Some(session) = refused {
                        self.end(session);
                    }
                }
            }
            hold(
                &mut self.commands,
                &mut self.replays,
                reason,
                sleep(spacing),
            )
            .await?;
        }
    }

    async fn serve(&mut self, framed: &mut Framed<C::Stream>) -> Exit {
        loop {
            if let Err(reason) = self.flush(framed).await {
                return Exit::Lost(reason);
            }
            let wake = self.next_wake();
            let capacity = self.options.command_capacity;
            tokio::select! {
                incoming = framed.receive() => match incoming {
                    Ok(message) => self.heard(message),
                    Err(reason) => return Exit::Lost(reason),
                },
                command = self.commands.recv(), if self.queue.len() < capacity => match command {
                    Some(Command::Request(outbound)) => self.queue.push_back(outbound),
                    Some(Command::Replay(key, stored)) => store(&mut self.replays, key, stored),
                    Some(Command::Reconnect) => return Exit::Lost(TransportError::Closed),
                    Some(Command::Shutdown) | None => return Exit::Shutdown,
                },
                () = reached(wake) => {
                    if let Err(reason) = self.tick(framed).await {
                        return Exit::Lost(reason);
                    }
                }
            }
        }
    }

    fn end(&mut self, session: SessionEnded) {
        log_debug!(%session, "authorisation ended");
        if let Some(account) = session.account {
            self.replays.retain(|_, stored| {
                account_of(stored.payload_type, &stored.payload) != Some(account)
            });
            self.ended.accounts.insert(account, session.cause.clone());
        } else {
            for stored in self.replays.values() {
                if let Some(account) = account_of(stored.payload_type, &stored.payload) {
                    self.ended.accounts.insert(account, session.cause.clone());
                }
            }
            self.replays.clear();
            self.ended.application = Some(session.cause.clone());
        }
        let _ = self.events.send(Event::SessionEnded(session));
    }

    fn fresh_id(&mut self) -> String {
        self.next_id = self.next_id.saturating_add(1);
        self.next_id.to_string()
    }

    fn heard(&mut self, message: ProtoMessage) {
        self.silent_at = within(Instant::now(), self.options.silence());
        self.dispatch(message);
    }

    fn next_wake(&self) -> Option<Instant> {
        let deadline = self.deadlines.front().and_then(|(deadline, _)| *deadline);
        [self.heartbeat_at, self.silent_at, deadline, self.send_at]
            .into_iter()
            .flatten()
            .min()
    }

    fn next_ready(&mut self, now: Instant) -> Option<usize> {
        self.send_at = None;
        if let Some(until) = self.paused_until {
            if until > now {
                if !self.queue.is_empty() {
                    self.send_at = Some(until);
                }
                return None;
            }
            self.paused_until = None;
        }
        let limits = [self.options.request_limit, self.options.historical_limit];
        let mut ready = [None, None];
        for ((throttle, limit), ready) in self.throttles.iter_mut().zip(limits).zip(&mut ready) {
            *ready = throttle.ready_at(now, limit);
        }
        for (index, outbound) in self.queue.iter().enumerate() {
            match ready
                .get(usize::from(outbound.historical))
                .copied()
                .flatten()
            {
                None => return Some(index),
                Some(at) => self.send_at = Some(self.send_at.map_or(at, |known| known.min(at))),
            }
        }
        None
    }

    async fn flush(&mut self, framed: &mut Framed<C::Stream>) -> Result<(), TransportError> {
        loop {
            let now = Instant::now();
            let Some(outbound) = self
                .next_ready(now)
                .and_then(|index| self.queue.remove(index))
            else {
                return Ok(());
            };
            if outbound.reply.is_closed() {
                continue;
            }
            if let Some(ended) = self.ended.refusal(outbound.payload_type, &outbound.payload) {
                let _ = outbound.reply.send(Err(ended.into()));
                continue;
            }
            let id = self.fresh_id();
            let message = ProtoMessage {
                payload_type: outbound.payload_type,
                payload: Some(outbound.payload.clone()),
                client_msg_id: Some(id.clone()),
            };
            match write(framed, &message, self.options.timeout).await {
                Ok(()) => {
                    bump(&self.counters.requests_sent);
                    if let Some(throttle) = self.throttles.get_mut(usize::from(outbound.historical))
                    {
                        throttle.sent.push_back(now);
                    }
                    self.heartbeat_at = within(now, self.options.heartbeat_interval);
                    self.deadlines
                        .push_back((within(now, self.options.timeout), id.clone()));
                    self.pending.insert(id, outbound);
                }
                Err(error @ TransportError::FrameTooLong { .. }) => {
                    let _ = outbound.reply.send(Err(error.into()));
                }
                Err(reason) => {
                    let error = outbound.interrupted(Interruption::Transport(reason.clone()));
                    let _ = outbound.reply.send(Err(error));
                    return Err(reason);
                }
            }
        }
    }

    async fn tick(&mut self, framed: &mut Framed<C::Stream>) -> Result<(), TransportError> {
        let now = Instant::now();
        while let Some((deadline, id)) = self.deadlines.pop_front() {
            if deadline.is_none_or(|deadline| deadline > now) {
                self.deadlines.push_front((deadline, id));
                break;
            }
            if let Some(outbound) = self.pending.remove(&id) {
                let error = outbound.interrupted(Interruption::Timeout(self.options.timeout));
                let _ = outbound.reply.send(Err(error));
            }
        }
        if self.silent_at.is_some_and(|silent_at| now >= silent_at) {
            let silence = self.options.silence();
            let late = timeout(Duration::ZERO, framed.receive())
                .await
                .unwrap_or(Err(TransportError::Idle(silence)));
            self.heard(late?);
        }
        if self
            .heartbeat_at
            .is_some_and(|heartbeat_at| now >= heartbeat_at)
        {
            let beat = ProtoHeartbeatEvent::default().to_message(None);
            write(framed, &beat, self.options.timeout).await?;
            bump(&self.counters.heartbeats_sent);
            self.heartbeat_at = within(Instant::now(), self.options.heartbeat_interval);
        }
        Ok(())
    }

    fn dispatch(&mut self, message: ProtoMessage) {
        if message.payload_type == ProtoHeartbeatEvent::PAYLOAD_TYPE {
            bump(&self.counters.heartbeats_received);
            return;
        }
        let waiting = message
            .client_msg_id
            .as_ref()
            .and_then(|id| self.pending.remove(id));
        let Some(mut outbound) = waiting else {
            let sessions = sessions_ended_by(&message);
            let _ = self.events.send(Event::Message(message));
            for session in sessions {
                self.end(session);
            }
            return;
        };
        self.ended.granted(&message);
        if outbound.once {
            let _ = self.events.send(Event::Message(message.clone()));
        }
        let result = outcome(message);
        if !outbound.once && over_limit(&result) && outbound.attempts < self.options.retries {
            let pause = self
                .options
                .backoff
                .saturating_mul(1 << outbound.attempts.min(16))
                .min(BACKOFF_LIMIT.max(self.options.backoff));
            let until = after(Instant::now(), pause);
            log_debug!(
                payload_type = outbound.payload_type,
                ?pause,
                "limit exceeded"
            );
            self.paused_until = Some(self.paused_until.map_or(until, |known| known.max(until)));
            outbound.attempts += 1;
            bump(&self.counters.throttle_retries);
            self.queue.push_front(outbound);
        } else {
            let _ = outbound.reply.send(result);
        }
    }

    fn fail_in_flight(&mut self, reason: &TransportError) {
        self.deadlines.clear();
        for (_, outbound) in self.pending.drain() {
            let error = outbound.interrupted(Interruption::Transport(reason.clone()));
            let _ = outbound.reply.send(Err(error));
        }
        for outbound in self.queue.drain(..) {
            let _ = outbound.reply.send(Err(reason.clone().into()));
        }
        self.reset_pacing();
    }

    fn close_in_flight(&mut self, error: &ConnectorError) {
        self.deadlines.clear();
        for (_, outbound) in self.pending.drain() {
            let _ = outbound.reply.send(Err(error.clone()));
        }
        for outbound in self.queue.drain(..) {
            let _ = outbound.reply.send(Err(error.clone()));
        }
        self.reset_pacing();
    }

    fn reset_pacing(&mut self) {
        self.paused_until = None;
        self.send_at = None;
        for throttle in &mut self.throttles {
            throttle.sent.clear();
        }
    }

    fn fail_all(&mut self, error: &ConnectorError) {
        self.close_in_flight(error);
        self.commands.close();
        while let Ok(command) = self.commands.try_recv() {
            if let Command::Request(outbound) = command {
                let _ = outbound.reply.send(Err(error.clone()));
            }
        }
    }
}

#[derive(Default)]
struct Throttle {
    sent: VecDeque<Instant>,
}

impl Throttle {
    fn ready_at(&mut self, now: Instant, limit: u32) -> Option<Instant> {
        while self
            .sent
            .front()
            .is_some_and(|sent| now.duration_since(*sent) >= LIMIT_WINDOW)
        {
            self.sent.pop_front();
        }
        let limit = usize::try_from(limit).unwrap_or(usize::MAX);
        let excess = (self.sent.len() + 1).checked_sub(limit)?;
        let blocking = excess.checked_sub(1)?;
        self.sent
            .get(blocking)
            .map(|sent| after(*sent, LIMIT_WINDOW))
    }
}

fn after(start: Instant, period: Duration) -> Instant {
    start.checked_add(period.min(LONGEST_WAIT)).unwrap_or(start)
}

fn within(start: Instant, period: Duration) -> Option<Instant> {
    if period > LONGEST_WAIT {
        return None;
    }
    start.checked_add(period)
}

async fn reached(wake: Option<Instant>) {
    match wake {
        Some(wake) => sleep_until(wake).await,
        None => pending().await,
    }
}

fn over_limit(result: &Result<ProtoMessage, ConnectorError>) -> bool {
    matches!(
        result,
        Err(ConnectorError::Server(error)) if matches!(
            error.code,
            ErrorCode::RequestFrequencyExceeded | ErrorCode::BlockedPayloadType
        )
    )
}

fn store(replays: &mut Replays, key: ReplayKey, stored: Option<Stored>) {
    match stored {
        Some(stored) => {
            replays.insert(key, stored);
        }
        None => {
            replays.remove(&key);
        }
    }
}

async fn write<S: AsyncRead + AsyncWrite + Unpin>(
    framed: &mut Framed<S>,
    message: &ProtoMessage,
    limit: Duration,
) -> Result<(), TransportError> {
    timeout(limit, framed.send(message))
        .await
        .unwrap_or(Err(TransportError::WriteTimeout(limit)))
}

async fn close<S: AsyncRead + AsyncWrite + Unpin>(framed: &mut Framed<S>, limit: Duration) {
    let _ = timeout(limit, framed.close()).await;
}

async fn hold<F: Future>(
    commands: &mut mpsc::Receiver<Command>,
    replays: &mut Replays,
    reason: &TransportError,
    work: F,
) -> Result<F::Output, ConnectorError> {
    tokio::pin!(work);
    loop {
        tokio::select! {
            output = &mut work => return Ok(output),
            command = commands.recv() => match command {
                Some(Command::Request(outbound)) => {
                    let _ = outbound.reply.send(Err(reason.clone().into()));
                }
                Some(Command::Replay(key, stored)) => store(replays, key, stored),
                Some(Command::Reconnect) => {}
                Some(Command::Shutdown) | None => return Err(ConnectorError::Closed),
            },
        }
    }
}

async fn replay<S: AsyncRead + AsyncWrite + Unpin>(
    framed: &mut Framed<S>,
    id: String,
    stored: Stored,
    limit: Duration,
    events: &broadcast::Sender<Event>,
    pushed: &mut Vec<SessionEnded>,
) -> Result<Result<ProtoMessage, ConnectorError>, TransportError> {
    let message = ProtoMessage {
        payload_type: stored.payload_type,
        payload: Some(stored.payload),
        client_msg_id: Some(id.clone()),
    };
    write(framed, &message, limit).await?;
    Ok(
        match timeout(limit, answer_to(framed, &id, events, pushed)).await {
            Ok(answer) => outcome(answer?),
            Err(_) => Err(ConnectorError::Timeout(limit)),
        },
    )
}

async fn answer_to<S: AsyncRead + AsyncWrite + Unpin>(
    framed: &mut Framed<S>,
    id: &str,
    events: &broadcast::Sender<Event>,
    pushed: &mut Vec<SessionEnded>,
) -> Result<ProtoMessage, TransportError> {
    loop {
        let message = framed.receive().await?;
        if message.client_msg_id.as_deref() == Some(id) {
            return Ok(message);
        }
        if message.payload_type != ProtoHeartbeatEvent::PAYLOAD_TYPE {
            pushed.extend(sessions_ended_by(&message));
            let _ = events.send(Event::Message(message));
        }
    }
}

fn outcome(message: ProtoMessage) -> Result<ProtoMessage, ConnectorError> {
    if message.payload_type == ProtoOaErrorRes::PAYLOAD_TYPE {
        Err(ProtoOaErrorRes::from_message(&message)
            .map_or_else(|error| error, |response| ServerError::from(response).into()))
    } else if message.payload_type == ProtoErrorRes::PAYLOAD_TYPE {
        Err(ProtoErrorRes::from_message(&message)
            .map_or_else(|error| error, |response| ServerError::from(response).into()))
    } else {
        Ok(message)
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{
        ConnectionOptions, DEFAULT_INBOUND_TIMEOUT, Event, LIMIT_WINDOW, LONGEST_WAIT,
        MAX_COMMAND_CAPACITY, MAX_EVENT_CAPACITY, ReplayKey, ReplayStage,
        SERVER_HEARTBEAT_INTERVAL, Throttle, after, outcome, over_limit, within,
    };
    use crate::common::config::ConfigurationOpenApi;
    use crate::common::errors::{ConnectorError, ErrorCode, TransportError};
    use crate::open_api::messages::{
        ProtoErrorRes, ProtoMessage, ProtoOaErrorRes, ProtoOaSpotEvent, ProtoOaVersionRes,
    };
    use crate::open_api::payload::Payload;
    use tokio::time::Instant;

    #[test]
    fn options_take_timing_and_retries_of_the_configuration() {
        let configuration = ConfigurationOpenApi::builder()
            .client_id("id")
            .client_secret("secret")
            .access_token("token")
            .timeout(Duration::from_secs(3))
            .reconnect_delay(Duration::from_secs(2))
            .retries(7)
            .backoff(Duration::from_millis(250))
            .build()
            .expect("configuration");
        let options = ConnectionOptions::from(&configuration);
        assert_eq!(
            options,
            ConnectionOptions::new()
                .timeout(Duration::from_secs(3))
                .reconnect_delay(Duration::from_secs(2))
                .retries(7)
                .backoff(Duration::from_millis(250))
        );
    }

    #[test]
    fn silence_allowed_follows_the_pace_of_the_server_unless_it_is_set() {
        assert_eq!(DEFAULT_INBOUND_TIMEOUT, Duration::from_secs(75));
        assert!(DEFAULT_INBOUND_TIMEOUT >= SERVER_HEARTBEAT_INTERVAL * 2);
        assert_eq!(ConnectionOptions::new().silence(), DEFAULT_INBOUND_TIMEOUT);
        let quick = ConnectionOptions::new()
            .heartbeat_interval(Duration::from_secs(2))
            .timeout(Duration::from_secs(1));
        assert_eq!(quick.silence(), DEFAULT_INBOUND_TIMEOUT);
        assert_eq!(
            quick.clone().inbound_timeout(Duration::ZERO).silence(),
            Duration::from_millis(1)
        );
        assert_eq!(
            quick.inbound_timeout(Duration::from_secs(90)).silence(),
            Duration::from_secs(90)
        );
    }

    #[test]
    fn options_raise_degenerate_values() {
        let options = ConnectionOptions::new()
            .timeout(Duration::ZERO)
            .heartbeat_interval(Duration::ZERO)
            .command_capacity(0)
            .event_capacity(0)
            .reconnect_delay(Duration::ZERO)
            .reconnect_attempts(Some(4))
            .request_limit(0)
            .historical_limit(0)
            .retries(0)
            .backoff(Duration::ZERO);
        assert_eq!(options.timeout, Duration::from_millis(1));
        assert_eq!(options.heartbeat_interval, Duration::from_millis(1));
        assert_eq!(options.command_capacity, 1);
        assert_eq!(options.event_capacity, 1);
        let largest = ConnectionOptions::new()
            .command_capacity(usize::MAX)
            .event_capacity(usize::MAX);
        assert_eq!(largest.command_capacity, MAX_COMMAND_CAPACITY);
        assert_eq!(largest.event_capacity, MAX_EVENT_CAPACITY);
        assert_eq!(options.reconnect_delay, Duration::from_millis(1));
        assert_eq!(options.reconnect_attempts, Some(4));
        assert_eq!(options.request_limit, 1);
        assert_eq!(options.historical_limit, 1);
        assert_eq!(options.retries, 0);
        assert_eq!(options.backoff, Duration::from_millis(1));
        assert_eq!(ConnectionOptions::new().reconnect_attempts, None);
    }

    #[test]
    fn error_responses_become_server_errors() {
        let open_api = ProtoOaErrorRes {
            error_code: "CH_CLIENT_AUTH_FAILURE".to_owned(),
            ..ProtoOaErrorRes::default()
        };
        assert!(matches!(
            outcome(open_api.to_message(None)),
            Err(ConnectorError::Server(error)) if error.code == ErrorCode::ChClientAuthFailure
        ));
        let common = ProtoErrorRes {
            error_code: "UNSUPPORTED_MESSAGE".to_owned(),
            ..ProtoErrorRes::default()
        };
        assert!(matches!(
            outcome(common.to_message(None)),
            Err(ConnectorError::Server(error)) if error.code == ErrorCode::UnsupportedMessage
        ));
        for payload_type in [50, 2142] {
            let malformed = ProtoMessage {
                payload_type,
                payload: Some(vec![0xff]),
                client_msg_id: None,
            };
            assert!(matches!(
                outcome(malformed),
                Err(ConnectorError::Transport(TransportError::Decode(_)))
            ));
        }
        let fine = ProtoOaVersionRes::default().to_message(None);
        assert_eq!(outcome(fine.clone()), Ok(fine));
    }

    #[test]
    fn event_decodes_only_the_message_it_carries() {
        let spot = ProtoOaSpotEvent {
            ctid_trader_account_id: 1,
            symbol_id: 2,
            ..ProtoOaSpotEvent::default()
        };
        let event = Event::Message(spot.to_message(None));
        assert_eq!(event.decode::<ProtoOaSpotEvent>(), Some(spot));
        assert_eq!(event.decode::<ProtoOaVersionRes>(), None);
        let lost = Event::Disconnected(TransportError::Closed);
        assert_eq!(lost.decode::<ProtoOaSpotEvent>(), None);
        let again = Event::Reconnected { attempt: 1 };
        assert_eq!(again.decode::<ProtoOaSpotEvent>(), None);
    }

    #[test]
    fn replay_keys_order_by_stage_then_name() {
        let mut keys = [
            ReplayKey::new(ReplayStage::Subscription, "a"),
            ReplayKey::new(ReplayStage::Account, "2"),
            ReplayKey::new(ReplayStage::Application, "z"),
            ReplayKey::new(ReplayStage::Account, "1"),
        ];
        keys.sort();
        let order: Vec<(ReplayStage, &str)> =
            keys.iter().map(|key| (key.stage(), key.id())).collect();
        assert_eq!(
            order,
            vec![
                (ReplayStage::Application, "z"),
                (ReplayStage::Account, "1"),
                (ReplayStage::Account, "2"),
                (ReplayStage::Subscription, "a"),
            ]
        );
    }

    #[test]
    fn throttle_names_the_moment_the_next_request_may_go() {
        let start = Instant::now();
        let mut throttle = Throttle::default();
        assert_eq!(throttle.ready_at(start, 2), None);
        throttle.sent.push_back(start);
        assert_eq!(throttle.ready_at(start, 2), None);
        throttle.sent.push_back(start + Duration::from_millis(10));
        assert_eq!(throttle.ready_at(start, 2), Some(start + LIMIT_WINDOW));
        throttle.sent.push_back(start + Duration::from_millis(20));
        assert_eq!(
            throttle.ready_at(start, 2),
            Some(start + Duration::from_millis(10) + LIMIT_WINDOW)
        );
        let later = start + LIMIT_WINDOW + Duration::from_millis(10);
        assert_eq!(throttle.ready_at(later, 2), None);
        assert_eq!(throttle.sent.len(), 1);
    }

    #[test]
    fn waits_too_long_for_the_clock_end_at_the_longest_wait() {
        let start = Instant::now();
        let brief = Duration::from_secs(90);
        assert_eq!(after(start, brief), start + brief);
        assert_eq!(after(start, LONGEST_WAIT), start + LONGEST_WAIT);
        assert_eq!(after(start, Duration::MAX), start + LONGEST_WAIT);
        let far = after(start, Duration::MAX);
        assert_eq!(after(far, Duration::MAX), far + LONGEST_WAIT);
        assert_eq!(within(start, brief), Some(start + brief));
        assert_eq!(within(start, LONGEST_WAIT), Some(start + LONGEST_WAIT));
        assert_eq!(within(start, LONGEST_WAIT + Duration::from_nanos(1)), None);
        assert_eq!(within(start, Duration::MAX), None);
        let options = ConnectionOptions::new()
            .timeout(Duration::MAX)
            .heartbeat_interval(Duration::MAX);
        assert_eq!(options.silence(), DEFAULT_INBOUND_TIMEOUT);
        assert_eq!(
            options.inbound_timeout(Duration::MAX).silence(),
            Duration::MAX
        );
        let mut throttle = Throttle::default();
        throttle.sent.push_back(far);
        assert_eq!(throttle.ready_at(far, 1), Some(far + LIMIT_WINDOW));
    }

    #[test]
    fn only_limit_errors_are_retried() {
        let refusal = |code: &str| {
            outcome(
                ProtoOaErrorRes {
                    error_code: code.to_owned(),
                    ..ProtoOaErrorRes::default()
                }
                .to_message(None),
            )
        };
        assert!(over_limit(&refusal("REQUEST_FREQUENCY_EXCEEDED")));
        assert!(over_limit(&refusal("BLOCKED_PAYLOAD_TYPE")));
        assert!(!over_limit(&refusal("INVALID_REQUEST")));
        assert!(!over_limit(&Ok(
            ProtoOaVersionRes::default().to_message(None)
        )));
        assert!(!over_limit(&Err(ConnectorError::Closed)));
    }
}