1use std::fmt;
4use std::time::Duration;
5
6use rust_decimal::Decimal;
7use thiserror::Error;
8
9use crate::common::ids::AccountId;
10use crate::common::time::Timestamp;
11
12#[derive(Debug, Clone, PartialEq, Eq, Error)]
14#[non_exhaustive]
15pub enum ConfigError {
16 #[error("{0} is not set")]
18 Missing(&'static str),
19 #[error("environment must be demo or live, got {0}")]
21 InvalidEnvironment(String),
22 #[error("host is not a bare host name: {0}")]
24 InvalidHost(String),
25 #[error("port must not be zero")]
27 InvalidPort,
28 #[error("token URL must be an https URL: {0}")]
30 InvalidTokenUrl(String),
31 #[error("{0} must be longer than zero")]
33 ZeroDuration(&'static str),
34 #[error("{option} must not be longer than {} s", limit.as_secs())]
36 TooLong {
37 option: &'static str,
39 limit: Duration,
41 },
42}
43
44macro_rules! error_codes {
45 ($($(#[$doc:meta])* $variant:ident => $wire:literal,)*) => {
46 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
51 #[non_exhaustive]
52 pub enum ErrorCode {
53 $($(#[$doc])* $variant,)*
54 Unknown(String),
56 }
57
58 impl ErrorCode {
59 #[must_use]
61 pub fn from_wire(text: &str) -> Self {
62 match text {
63 $($wire => Self::$variant,)*
64 other => Self::Unknown(other.to_owned()),
65 }
66 }
67
68 #[must_use]
70 pub fn as_str(&self) -> &str {
71 match self {
72 $(Self::$variant => $wire,)*
73 Self::Unknown(text) => text,
74 }
75 }
76 }
77 };
78}
79
80error_codes! {
81 UnknownError => "UNKNOWN_ERROR",
83 UnsupportedMessage => "UNSUPPORTED_MESSAGE",
85 InvalidRequest => "INVALID_REQUEST",
87 TimeoutError => "TIMEOUT_ERROR",
89 EntityNotFound => "ENTITY_NOT_FOUND",
91 CantRouteRequest => "CANT_ROUTE_REQUEST",
93 FrameTooLong => "FRAME_TOO_LONG",
95 MarketClosed => "MARKET_CLOSED",
97 ConcurrentModification => "CONCURRENT_MODIFICATION",
99 BlockedPayloadType => "BLOCKED_PAYLOAD_TYPE",
101 OaAuthTokenExpired => "OA_AUTH_TOKEN_EXPIRED",
103 AccountNotAuthorized => "ACCOUNT_NOT_AUTHORIZED",
105 RetNoSuchLogin => "RET_NO_SUCH_LOGIN",
107 AlreadyLoggedIn => "ALREADY_LOGGED_IN",
109 RetAccountDisabled => "RET_ACCOUNT_DISABLED",
111 ChClientAuthFailure => "CH_CLIENT_AUTH_FAILURE",
113 ChClientNotAuthenticated => "CH_CLIENT_NOT_AUTHENTICATED",
115 ChClientAlreadyAuthenticated => "CH_CLIENT_ALREADY_AUTHENTICATED",
117 ChAccessTokenInvalid => "CH_ACCESS_TOKEN_INVALID",
119 ChServerNotReachable => "CH_SERVER_NOT_REACHABLE",
121 ChCtidTraderAccountNotFound => "CH_CTID_TRADER_ACCOUNT_NOT_FOUND",
123 ChOaClientNotFound => "CH_OA_CLIENT_NOT_FOUND",
125 RequestFrequencyExceeded => "REQUEST_FREQUENCY_EXCEEDED",
127 ServerIsUnderMaintenance => "SERVER_IS_UNDER_MAINTENANCE",
129 ChannelIsBlocked => "CHANNEL_IS_BLOCKED",
131 ConnectionsLimitExceeded => "CONNECTIONS_LIMIT_EXCEEDED",
133 WorseGslNotAllowed => "WORSE_GSL_NOT_ALLOWED",
135 SymbolHasHoliday => "SYMBOL_HAS_HOLIDAY",
137 NotSubscribedToSpots => "NOT_SUBSCRIBED_TO_SPOTS",
139 AlreadySubscribed => "ALREADY_SUBSCRIBED",
141 SymbolNotFound => "SYMBOL_NOT_FOUND",
143 UnknownSymbol => "UNKNOWN_SYMBOL",
145 IncorrectBoundaries => "INCORRECT_BOUNDARIES",
147 NoQuotes => "NO_QUOTES",
149 NotEnoughMoney => "NOT_ENOUGH_MONEY",
151 MaxExposureReached => "MAX_EXPOSURE_REACHED",
153 PositionNotFound => "POSITION_NOT_FOUND",
155 OrderNotFound => "ORDER_NOT_FOUND",
157 PositionNotOpen => "POSITION_NOT_OPEN",
159 PositionLocked => "POSITION_LOCKED",
161 TooManyPositions => "TOO_MANY_POSITIONS",
163 TradingBadVolume => "TRADING_BAD_VOLUME",
165 TradingBadStops => "TRADING_BAD_STOPS",
167 TradingBadPrices => "TRADING_BAD_PRICES",
169 TradingBadStake => "TRADING_BAD_STAKE",
171 ProtectionIsTooCloseToMarket => "PROTECTION_IS_TOO_CLOSE_TO_MARKET",
173 TradingBadExpirationDate => "TRADING_BAD_EXPIRATION_DATE",
175 PendingExecution => "PENDING_EXECUTION",
177 TradingDisabled => "TRADING_DISABLED",
179 TradingNotAllowed => "TRADING_NOT_ALLOWED",
181 UnableToCancelOrder => "UNABLE_TO_CANCEL_ORDER",
183 UnableToAmendOrder => "UNABLE_TO_AMEND_ORDER",
185 ShortSellingNotAllowed => "SHORT_SELLING_NOT_ALLOWED",
187}
188
189impl ErrorCode {
190 #[must_use]
192 pub const fn is_known(&self) -> bool {
193 !matches!(self, Self::Unknown(_))
194 }
195}
196
197impl fmt::Display for ErrorCode {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 f.write_str(self.as_str())
200 }
201}
202
203impl From<&str> for ErrorCode {
204 fn from(text: &str) -> Self {
205 Self::from_wire(text)
206 }
207}
208
209#[derive(Clone, PartialEq, Eq, Error)]
216#[error("server error {code}{}", detail(.description.as_deref()))]
217#[non_exhaustive]
218pub struct ServerError {
219 pub code: ErrorCode,
221 pub description: Option<String>,
223 pub account_id: Option<AccountId>,
225 pub maintenance_end_timestamp: Option<i64>,
227}
228
229struct Masked;
230
231impl fmt::Debug for Masked {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 f.write_str("<masked>")
234 }
235}
236
237impl fmt::Debug for ServerError {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 f.debug_struct("ServerError")
240 .field("code", &self.code)
241 .field("description", &self.description)
242 .field("account_id", &self.account_id.map(|_| Masked))
243 .field("maintenance_end_timestamp", &self.maintenance_end_timestamp)
244 .finish()
245 }
246}
247
248impl ServerError {
249 #[must_use]
251 pub const fn new(code: ErrorCode) -> Self {
252 Self {
253 code,
254 description: None,
255 account_id: None,
256 maintenance_end_timestamp: None,
257 }
258 }
259
260 #[must_use]
262 pub fn with_description(mut self, description: impl Into<String>) -> Self {
263 self.description = Some(description.into());
264 self
265 }
266
267 #[must_use]
269 pub const fn with_account_id(mut self, account_id: AccountId) -> Self {
270 self.account_id = Some(account_id);
271 self
272 }
273
274 #[must_use]
276 pub const fn with_maintenance_end_timestamp(mut self, timestamp: i64) -> Self {
277 self.maintenance_end_timestamp = Some(timestamp);
278 self
279 }
280}
281
282fn detail(description: Option<&str>) -> String {
283 description.map_or_else(String::new, |text| format!(": {text}"))
284}
285
286#[derive(Debug, Clone, PartialEq, Eq, Error)]
288#[non_exhaustive]
289pub enum ValueError {
290 #[error("{kind} must be a positive integer, got {value}")]
292 InvalidId {
293 kind: &'static str,
295 value: String,
297 },
298 #[error("{kind} is not a decimal number: {text}")]
300 InvalidDecimal {
301 kind: &'static str,
303 text: String,
305 },
306 #[error("{kind} must not be negative, got {value}")]
308 Negative {
309 kind: &'static str,
311 value: Decimal,
313 },
314 #[error("symbol digits must be at most 5, got {digits}")]
316 TooManyDigits {
317 digits: u32,
319 },
320 #[error("{kind} cannot be carried on the wire: {value}")]
322 Unrepresentable {
323 kind: &'static str,
325 value: Decimal,
327 },
328 #[error("{kind} is out of range")]
330 OutOfRange {
331 kind: &'static str,
333 },
334 #[error("{kind} is missing")]
336 Missing {
337 kind: &'static str,
339 },
340 #[error("range from {from} ends before it starts, at {to}")]
342 InvertedRange {
343 from: i64,
345 to: i64,
347 },
348 #[error("{kind} has {length} characters, more than the {limit} allowed")]
350 TooLong {
351 kind: &'static str,
353 length: usize,
355 limit: usize,
357 },
358 #[error("{kind} must be at least {minimum}, got {value}")]
360 BelowMinimum {
361 kind: &'static str,
363 value: Decimal,
365 minimum: Decimal,
367 },
368 #[error("{kind} must be at most {maximum}, got {value}")]
370 AboveMaximum {
371 kind: &'static str,
373 value: Decimal,
375 maximum: Decimal,
377 },
378 #[error("{kind} must be a multiple of {step}, got {value}")]
380 OffStep {
381 kind: &'static str,
383 value: Decimal,
385 step: Decimal,
387 },
388 #[error("{kind} must have at most {digits} decimal places, got {value}")]
390 TooFine {
391 kind: &'static str,
393 value: Decimal,
395 digits: u32,
397 },
398 #[error("{kind} does not match")]
400 Mismatch {
401 kind: &'static str,
403 },
404 #[error("{kind} is not supported here")]
406 Unsupported {
407 kind: &'static str,
409 },
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Error)]
417#[non_exhaustive]
418pub enum TransportError {
419 #[error("input or output failed ({kind:?}): {message}")]
421 Io {
422 kind: std::io::ErrorKind,
424 message: String,
426 },
427 #[error("TLS failed: {0}")]
429 Tls(String),
430 #[error("host is not a valid server name: {0}")]
432 InvalidHost(String),
433 #[error("connecting timed out after {0:?}")]
435 ConnectTimeout(Duration),
436 #[error("writing timed out after {0:?}")]
438 WriteTimeout(Duration),
439 #[error("nothing was received for {0:?}")]
441 Idle(Duration),
442 #[error("frame of {length} bytes exceeds the limit of {limit} bytes")]
444 FrameTooLong {
445 length: usize,
447 limit: usize,
449 },
450 #[error("frame cannot be decoded: {0}")]
452 Decode(String),
453 #[error("connection closed by the peer")]
455 Closed,
456}
457
458impl From<std::io::Error> for TransportError {
459 fn from(error: std::io::Error) -> Self {
460 Self::Io {
461 kind: error.kind(),
462 message: error.to_string(),
463 }
464 }
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Error)]
471#[non_exhaustive]
472pub enum TokenError {
473 #[error("no refresh token is configured")]
475 NoRefreshToken,
476 #[error("token refresh refused: {code}{}", detail(Some(.description.as_str()).filter(|text| !text.is_empty())))]
478 Refused {
479 code: String,
481 description: String,
483 },
484 #[error("token response is malformed: {0}")]
486 Malformed(&'static str),
487 #[error("token endpoint answered with status {0}")]
489 Status(u16),
490}
491
492#[derive(Debug, Clone, PartialEq, Eq, Error)]
494#[non_exhaustive]
495pub enum Interruption {
496 #[error("no response within {0:?}")]
498 Timeout(Duration),
499 #[error("transport failed: {0}")]
501 Transport(TransportError),
502 #[error("the server asked for the request again and it was not repeated")]
505 Skipped,
506}
507
508#[derive(Debug, Clone, PartialEq, Eq, Error)]
510#[non_exhaustive]
511pub enum SessionEndCause {
512 #[error("the access token was invalidated{}", detail(.reason.as_deref()))]
515 TokenInvalidated {
516 reason: Option<String>,
518 },
519 #[error("the server dropped the session of the account")]
521 AccountDisconnected,
522 #[error("the server ended the session of the application{}", detail(.reason.as_deref()))]
524 ClientDisconnected {
525 reason: Option<String>,
527 },
528 #[error("the access token was refused after a reconnection: {0}")]
531 TokenRefused(ErrorCode),
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Error)]
539#[error("{} is no longer authorised: {cause}", subject(.account.as_ref()))]
540#[non_exhaustive]
541pub struct SessionEnded {
542 pub account: Option<AccountId>,
545 pub cause: SessionEndCause,
547}
548
549impl SessionEnded {
550 #[must_use]
552 pub const fn new(account: Option<AccountId>, cause: SessionEndCause) -> Self {
553 Self { account, cause }
554 }
555}
556
557fn subject(account: Option<&AccountId>) -> String {
558 account.map_or_else(
559 || "the session of the application".to_owned(),
560 |account| format!("the session of account {account}"),
561 )
562}
563
564#[derive(Debug, Clone, PartialEq, Eq, Error)]
569#[non_exhaustive]
570pub enum FixError {
571 #[error("the bytes are not a FIX message: {0}")]
573 Garbled(&'static str),
574 #[error("checksum is {found}, the bytes sum to {computed}")]
576 Checksum {
577 computed: u8,
579 found: u8,
581 },
582 #[error("body of {length} bytes exceeds the limit of {limit} bytes")]
584 TooLong {
585 length: usize,
587 limit: usize,
589 },
590 #[error("message {msg_type} lacks the required tag {tag}")]
592 MissingField {
593 msg_type: String,
595 tag: u32,
597 },
598 #[error("message {msg_type} holds an invalid value under tag {tag}")]
600 InvalidField {
601 msg_type: String,
603 tag: u32,
605 },
606 #[error("message type {0} is not supported")]
608 UnsupportedMessage(String),
609 #[error("message type {0} is never sent")]
611 Unsendable(String),
612 #[error("the server refused the logon: {}", explained(text.as_deref()))]
614 LogonRefused {
615 text: Option<String>,
617 },
618 #[error("message of type {0} arrived where another was due")]
620 UnexpectedMessage(String),
621 #[error("the server rejected message {ref_seq_num}: {}", explained(text.as_deref()))]
623 Rejected {
624 ref_seq_num: u64,
626 tag: Option<u32>,
628 reason: Option<u32>,
630 text: Option<String>,
632 },
633 #[error("the server refused the request: {}", explained(text.as_deref()))]
635 BusinessRejected {
636 ref_id: Option<String>,
638 reason: Option<u32>,
640 text: Option<String>,
642 },
643 #[error("the server refused the market data request: {}", explained(text.as_deref()))]
645 MarketDataRejected {
646 reason: Option<u32>,
648 text: Option<String>,
650 },
651 #[error("the server refused the order: {}", explained(text.as_deref()))]
653 OrderRejected {
654 cl_ord_id: Option<String>,
656 reason: Option<u32>,
658 text: Option<String>,
660 },
661 #[error("the server refused to change the order: {}", explained(text.as_deref()))]
663 CancelRejected {
664 cl_ord_id: String,
666 orig_cl_ord_id: Option<String>,
668 change: RefusedChange,
670 text: Option<String>,
672 },
673}
674
675#[derive(Debug, Clone, Copy, PartialEq, Eq)]
677pub enum RefusedChange {
678 Cancel,
680 Replace,
682}
683
684fn explained(text: Option<&str>) -> &str {
685 text.unwrap_or("no explanation given")
686}
687
688#[derive(Debug, Clone, PartialEq, Eq, Error)]
690#[non_exhaustive]
691pub enum ConnectorError {
692 #[error("configuration rejected: {0}")]
694 Config(#[from] ConfigError),
695 #[error(transparent)]
697 Server(#[from] ServerError),
698 #[error("value rejected: {0}")]
700 Value(#[from] ValueError),
701 #[error("transport failed: {0}")]
703 Transport(#[from] TransportError),
704 #[error(transparent)]
706 Token(#[from] TokenError),
707 #[error("FIX failure: {0}")]
709 Fix(#[from] FixError),
710 #[error("no response within {0:?}")]
712 Timeout(Duration),
713 #[error("the request was sent and its outcome is unknown: {0}")]
716 OutcomeUnknown(Interruption),
717 #[error(transparent)]
719 SessionEnded(#[from] SessionEnded),
720 #[error("connection is shut down")]
722 Closed,
723 #[error("{skipped} events were dropped because their reader fell behind")]
725 Lagged {
726 skipped: u64,
728 },
729 #[error("the server announced more data between {from} and {to} than it sent")]
732 Incomplete {
733 from: Timestamp,
735 to: Timestamp,
737 },
738 #[error("expected payload type {expected}, received {received}")]
740 UnexpectedResponse {
741 expected: u32,
743 received: u32,
745 },
746}
747
748#[cfg(test)]
749mod tests {
750 use std::collections::HashSet;
751 use std::error::Error;
752
753 use std::time::Duration;
754
755 use super::{
756 ConfigError, ConnectorError, ErrorCode, FixError, Interruption, ServerError,
757 SessionEndCause, SessionEnded, TransportError, ValueError,
758 };
759 use crate::common::ids::AccountId;
760 use crate::common::time::Timestamp;
761 use crate::proto_text;
762
763 fn proto_codes(name: &str) -> Vec<String> {
764 proto_text::enums()
765 .remove(name)
766 .expect("enum is present in the proto files")
767 .into_iter()
768 .map(|(text, _)| text)
769 .collect()
770 }
771
772 #[test]
773 fn every_code_in_the_proto_files_has_a_variant() {
774 let common = proto_codes("protoerrorcode");
775 let open_api = proto_codes("protooaerrorcode");
776 assert_eq!(common.len(), 10);
777 assert_eq!(open_api.len(), 43);
778 let mut seen = HashSet::new();
779 for text in common.iter().chain(&open_api) {
780 let code = ErrorCode::from_wire(text);
781 assert!(code.is_known(), "{text} has no variant");
782 assert_eq!(code.as_str(), text);
783 assert_eq!(code.to_string(), *text);
784 assert_eq!(ErrorCode::from(text.as_str()), code);
785 assert!(seen.insert(code), "{text} shares a variant");
786 }
787 assert_eq!(seen.len(), 53);
788 }
789
790 #[test]
791 fn selected_codes_map_to_their_variants() {
792 assert_eq!(
793 ErrorCode::from_wire("MARKET_CLOSED"),
794 ErrorCode::MarketClosed
795 );
796 assert_eq!(
797 ErrorCode::from_wire("OA_AUTH_TOKEN_EXPIRED"),
798 ErrorCode::OaAuthTokenExpired
799 );
800 assert_eq!(
801 ErrorCode::from_wire("CH_ACCESS_TOKEN_INVALID"),
802 ErrorCode::ChAccessTokenInvalid
803 );
804 assert_eq!(
805 ErrorCode::from_wire("NOT_ENOUGH_MONEY"),
806 ErrorCode::NotEnoughMoney
807 );
808 assert_eq!(
809 ErrorCode::from_wire("SHORT_SELLING_NOT_ALLOWED"),
810 ErrorCode::ShortSellingNotAllowed
811 );
812 }
813
814 #[test]
815 fn unknown_codes_are_preserved_as_text() {
816 for text in ["BRAND_NEW_CODE", "market_closed", "", "104"] {
817 let code = ErrorCode::from_wire(text);
818 assert_eq!(code, ErrorCode::Unknown(text.to_owned()));
819 assert!(!code.is_known());
820 assert_eq!(code.as_str(), text);
821 assert_eq!(code.to_string(), text);
822 }
823 }
824
825 #[test]
826 fn server_error_prints_code_and_description() {
827 let bare = ServerError::new(ErrorCode::MarketClosed);
828 assert_eq!(bare.to_string(), "server error MARKET_CLOSED");
829 assert_eq!(bare.description, None);
830 assert_eq!(bare.maintenance_end_timestamp, None);
831 let detailed = ServerError::new(ErrorCode::from_wire("BRAND_NEW_CODE"))
832 .with_description("try later")
833 .with_maintenance_end_timestamp(1_700_000_000_000);
834 assert_eq!(
835 detailed.to_string(),
836 "server error BRAND_NEW_CODE: try later"
837 );
838 assert_eq!(detailed.maintenance_end_timestamp, Some(1_700_000_000_000));
839 assert_eq!(detailed.account_id, None);
840 let account = AccountId::new(7).expect("positive id");
841 assert_eq!(detailed.with_account_id(account).account_id, Some(account));
842 }
843
844 #[test]
845 fn server_error_debug_masks_the_account_and_keeps_the_field() {
846 let account = AccountId::new(987_654_321).expect("positive id");
847 let error = ServerError::new(ErrorCode::MarketClosed)
848 .with_description("closed")
849 .with_account_id(account);
850 let printed = format!("{error:?} {error:#?} {error}");
851 assert!(!printed.contains("987654321"), "{printed}");
852 assert!(printed.contains("account_id: Some(<masked>)"), "{printed}");
853 assert!(printed.contains("MarketClosed"), "{printed}");
854 assert!(printed.contains("closed"), "{printed}");
855 assert_eq!(error.account_id, Some(account));
856 let wrapped = format!("{:?}", ConnectorError::from(error));
857 assert!(!wrapped.contains("987654321"), "{wrapped}");
858 let bare = format!("{:?}", ServerError::new(ErrorCode::MarketClosed));
859 assert!(bare.contains("account_id: None"), "{bare}");
860 }
861
862 #[test]
863 fn session_end_names_the_session_and_the_cause() {
864 let account = AccountId::new(7).expect("positive id");
865 let invalidated = SessionEnded::new(
866 Some(account),
867 SessionEndCause::TokenInvalidated {
868 reason: Some("refreshed".to_owned()),
869 },
870 );
871 assert_eq!(
872 invalidated.to_string(),
873 "the session of account 7 is no longer authorised: the access token was invalidated: refreshed"
874 );
875 assert_eq!(
876 ConnectorError::from(invalidated.clone()),
877 ConnectorError::SessionEnded(invalidated.clone())
878 );
879 assert_eq!(
880 ConnectorError::from(invalidated.clone()).to_string(),
881 invalidated.to_string()
882 );
883 assert_eq!(
884 SessionEnded::new(Some(account), SessionEndCause::AccountDisconnected).to_string(),
885 "the session of account 7 is no longer authorised: the server dropped the session of the account"
886 );
887 assert_eq!(
888 SessionEnded::new(None, SessionEndCause::ClientDisconnected { reason: None })
889 .to_string(),
890 "the session of the application is no longer authorised: the server ended the session of the application"
891 );
892 assert_eq!(
893 SessionEnded::new(
894 Some(account),
895 SessionEndCause::TokenRefused(ErrorCode::ChAccessTokenInvalid)
896 )
897 .to_string(),
898 "the session of account 7 is no longer authorised: the access token was refused after a reconnection: CH_ACCESS_TOKEN_INVALID"
899 );
900 }
901
902 #[test]
903 fn connector_error_wraps_its_sources() {
904 let server = ServerError::new(ErrorCode::TradingBadVolume).with_description("too small");
905 let error = ConnectorError::from(server.clone());
906 assert_eq!(error, ConnectorError::Server(server));
907 assert_eq!(
908 error.to_string(),
909 "server error TRADING_BAD_VOLUME: too small"
910 );
911 let config = ConnectorError::from(ConfigError::InvalidPort);
912 assert_eq!(
913 config.to_string(),
914 "configuration rejected: port must not be zero"
915 );
916 let value = ConnectorError::from(ValueError::TooManyDigits { digits: 9 });
917 assert_eq!(
918 value.to_string(),
919 "value rejected: symbol digits must be at most 5, got 9"
920 );
921 assert_eq!(
922 config.source().map(ToString::to_string),
923 Some("port must not be zero".to_owned())
924 );
925 }
926
927 #[test]
928 fn transport_error_keeps_the_kind_of_an_io_failure() {
929 let source = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "reset by peer");
930 let error = TransportError::from(source);
931 assert_eq!(
932 error,
933 TransportError::Io {
934 kind: std::io::ErrorKind::ConnectionReset,
935 message: "reset by peer".to_owned(),
936 }
937 );
938 assert_eq!(
939 ConnectorError::from(error).to_string(),
940 "transport failed: input or output failed (ConnectionReset): reset by peer"
941 );
942 assert_eq!(
943 TransportError::FrameTooLong {
944 length: 9,
945 limit: 8
946 }
947 .to_string(),
948 "frame of 9 bytes exceeds the limit of 8 bytes"
949 );
950 assert_eq!(
951 TransportError::ConnectTimeout(Duration::from_secs(15)).to_string(),
952 "connecting timed out after 15s"
953 );
954 assert_eq!(
955 TransportError::Closed.to_string(),
956 "connection closed by the peer"
957 );
958 assert_eq!(
959 TransportError::WriteTimeout(Duration::from_secs(10)).to_string(),
960 "writing timed out after 10s"
961 );
962 assert_eq!(
963 TransportError::Idle(Duration::from_secs(40)).to_string(),
964 "nothing was received for 40s"
965 );
966 let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
967 assert_eq!(
968 ConnectorError::Incomplete {
969 from: at(5),
970 to: at(9)
971 }
972 .to_string(),
973 "the server announced more data between 5 and 9 than it sent"
974 );
975 assert_eq!(
976 ConnectorError::OutcomeUnknown(Interruption::Timeout(Duration::from_secs(2)))
977 .to_string(),
978 "the request was sent and its outcome is unknown: no response within 2s"
979 );
980 assert_eq!(
981 ConnectorError::OutcomeUnknown(Interruption::Transport(TransportError::Closed))
982 .to_string(),
983 "the request was sent and its outcome is unknown: transport failed: connection closed by the peer"
984 );
985 assert_eq!(
986 ConnectorError::Lagged { skipped: 3 }.to_string(),
987 "3 events were dropped because their reader fell behind"
988 );
989 }
990
991 #[test]
992 fn fix_refusals_carry_the_explanation_of_the_server_or_say_that_none_came() {
993 assert_eq!(
994 FixError::LogonRefused {
995 text: Some("RET_INVALID_DATA".to_owned())
996 }
997 .to_string(),
998 "the server refused the logon: RET_INVALID_DATA"
999 );
1000 assert_eq!(
1001 FixError::LogonRefused { text: None }.to_string(),
1002 "the server refused the logon: no explanation given"
1003 );
1004 assert_eq!(
1005 FixError::Unsendable("j".to_owned()).to_string(),
1006 "message type j is never sent"
1007 );
1008 assert_eq!(
1009 FixError::UnexpectedMessage("0".to_owned()).to_string(),
1010 "message of type 0 arrived where another was due"
1011 );
1012 assert_eq!(
1013 FixError::Rejected {
1014 ref_seq_num: 7,
1015 tag: Some(55),
1016 reason: Some(5),
1017 text: Some("Value is incorrect".to_owned())
1018 }
1019 .to_string(),
1020 "the server rejected message 7: Value is incorrect"
1021 );
1022 assert_eq!(
1023 FixError::BusinessRejected {
1024 ref_id: Some("a".to_owned()),
1025 reason: None,
1026 text: None
1027 }
1028 .to_string(),
1029 "the server refused the request: no explanation given"
1030 );
1031 }
1032
1033 #[test]
1034 fn fix_errors_name_the_message_and_the_tag_and_never_a_value() {
1035 let missing = FixError::MissingField {
1036 msg_type: "A".to_owned(),
1037 tag: 108,
1038 };
1039 assert_eq!(missing.to_string(), "message A lacks the required tag 108");
1040 assert_eq!(
1041 ConnectorError::from(missing).to_string(),
1042 "FIX failure: message A lacks the required tag 108"
1043 );
1044 assert_eq!(
1045 FixError::InvalidField {
1046 msg_type: "A".to_owned(),
1047 tag: 554
1048 }
1049 .to_string(),
1050 "message A holds an invalid value under tag 554"
1051 );
1052 assert_eq!(
1053 FixError::Checksum {
1054 computed: 7,
1055 found: 8
1056 }
1057 .to_string(),
1058 "checksum is 8, the bytes sum to 7"
1059 );
1060 assert_eq!(
1061 FixError::TooLong {
1062 length: 9,
1063 limit: 8
1064 }
1065 .to_string(),
1066 "body of 9 bytes exceeds the limit of 8 bytes"
1067 );
1068 assert_eq!(
1069 FixError::Garbled("no opening").to_string(),
1070 "the bytes are not a FIX message: no opening"
1071 );
1072 assert_eq!(
1073 FixError::UnsupportedMessage("ZZ".to_owned()).to_string(),
1074 "message type ZZ is not supported"
1075 );
1076 }
1077}