Skip to main content

ctrader_connector/common/
errors.rs

1//! Error types shared by every protocol.
2
3use 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/// Reasons a configuration is rejected before any connection is attempted.
13#[derive(Debug, Clone, PartialEq, Eq, Error)]
14#[non_exhaustive]
15pub enum ConfigError {
16    /// A required option or environment variable is absent or empty.
17    #[error("{0} is not set")]
18    Missing(&'static str),
19    /// The environment name is neither `demo` nor `live`.
20    #[error("environment must be demo or live, got {0}")]
21    InvalidEnvironment(String),
22    /// The host is empty or is not a bare host name.
23    #[error("host is not a bare host name: {0}")]
24    InvalidHost(String),
25    /// The port is zero.
26    #[error("port must not be zero")]
27    InvalidPort,
28    /// The token URL is not an `https` URL with a host.
29    #[error("token URL must be an https URL: {0}")]
30    InvalidTokenUrl(String),
31    /// A duration option is zero.
32    #[error("{0} must be longer than zero")]
33    ZeroDuration(&'static str),
34    /// A duration option is longer than the longest value it accepts.
35    #[error("{option} must not be longer than {} s", limit.as_secs())]
36    TooLong {
37        /// Name of the option.
38        option: &'static str,
39        /// Longest value the option accepts.
40        limit: Duration,
41    },
42}
43
44macro_rules! error_codes {
45    ($($(#[$doc:meta])* $variant:ident => $wire:literal,)*) => {
46        /// Error code reported by the server.
47        ///
48        /// The server sends the code as text. Every code named in the proto files has a variant;
49        /// any other text is kept in [`ErrorCode::Unknown`] exactly as received.
50        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
51        #[non_exhaustive]
52        pub enum ErrorCode {
53            $($(#[$doc])* $variant,)*
54            /// A code this version of the library does not name, kept as received.
55            Unknown(String),
56        }
57
58        impl ErrorCode {
59            /// Maps the text sent by the server to a code.
60            #[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            /// Returns the text the server uses for the code.
69            #[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    /// The server failed for a reason it does not disclose.
82    UnknownError => "UNKNOWN_ERROR",
83    /// The message type is not supported.
84    UnsupportedMessage => "UNSUPPORTED_MESSAGE",
85    /// The request is malformed or carries invalid values.
86    InvalidRequest => "INVALID_REQUEST",
87    /// The server did not process the request in time.
88    TimeoutError => "TIMEOUT_ERROR",
89    /// The entity named by the request does not exist.
90    EntityNotFound => "ENTITY_NOT_FOUND",
91    /// The server could not route the request.
92    CantRouteRequest => "CANT_ROUTE_REQUEST",
93    /// The frame exceeds the size limit.
94    FrameTooLong => "FRAME_TOO_LONG",
95    /// The market is closed.
96    MarketClosed => "MARKET_CLOSED",
97    /// The entity was changed by another request at the same time.
98    ConcurrentModification => "CONCURRENT_MODIFICATION",
99    /// The payload type is blocked.
100    BlockedPayloadType => "BLOCKED_PAYLOAD_TYPE",
101    /// The access token has expired.
102    OaAuthTokenExpired => "OA_AUTH_TOKEN_EXPIRED",
103    /// The account is not authorised on this connection.
104    AccountNotAuthorized => "ACCOUNT_NOT_AUTHORIZED",
105    /// No account has this login.
106    RetNoSuchLogin => "RET_NO_SUCH_LOGIN",
107    /// The account is already authorised on this connection.
108    AlreadyLoggedIn => "ALREADY_LOGGED_IN",
109    /// The account is disabled.
110    RetAccountDisabled => "RET_ACCOUNT_DISABLED",
111    /// The application credentials were refused.
112    ChClientAuthFailure => "CH_CLIENT_AUTH_FAILURE",
113    /// The application is not authorised on this connection.
114    ChClientNotAuthenticated => "CH_CLIENT_NOT_AUTHENTICATED",
115    /// The application is already authorised on this connection.
116    ChClientAlreadyAuthenticated => "CH_CLIENT_ALREADY_AUTHENTICATED",
117    /// The access token is invalid.
118    ChAccessTokenInvalid => "CH_ACCESS_TOKEN_INVALID",
119    /// The trading server is not reachable.
120    ChServerNotReachable => "CH_SERVER_NOT_REACHABLE",
121    /// The trading account was not found.
122    ChCtidTraderAccountNotFound => "CH_CTID_TRADER_ACCOUNT_NOT_FOUND",
123    /// The application was not found.
124    ChOaClientNotFound => "CH_OA_CLIENT_NOT_FOUND",
125    /// Requests are sent more often than the limit allows.
126    RequestFrequencyExceeded => "REQUEST_FREQUENCY_EXCEEDED",
127    /// The server is under maintenance.
128    ServerIsUnderMaintenance => "SERVER_IS_UNDER_MAINTENANCE",
129    /// The channel is blocked.
130    ChannelIsBlocked => "CHANNEL_IS_BLOCKED",
131    /// The limit of open connections is reached.
132    ConnectionsLimitExceeded => "CONNECTIONS_LIMIT_EXCEEDED",
133    /// A guaranteed stop loss may not be moved to a worse level.
134    WorseGslNotAllowed => "WORSE_GSL_NOT_ALLOWED",
135    /// Trading is suspended because the symbol has a holiday.
136    SymbolHasHoliday => "SYMBOL_HAS_HOLIDAY",
137    /// The connection is not subscribed to spot prices of the symbol.
138    NotSubscribedToSpots => "NOT_SUBSCRIBED_TO_SPOTS",
139    /// The subscription already exists.
140    AlreadySubscribed => "ALREADY_SUBSCRIBED",
141    /// The symbol was not found.
142    SymbolNotFound => "SYMBOL_NOT_FOUND",
143    /// The symbol is not known to the server.
144    UnknownSymbol => "UNKNOWN_SYMBOL",
145    /// The requested time range is not valid.
146    IncorrectBoundaries => "INCORRECT_BOUNDARIES",
147    /// There are no quotes to trade on.
148    NoQuotes => "NO_QUOTES",
149    /// The account lacks the funds for the trade.
150    NotEnoughMoney => "NOT_ENOUGH_MONEY",
151    /// The exposure limit is reached.
152    MaxExposureReached => "MAX_EXPOSURE_REACHED",
153    /// The position was not found.
154    PositionNotFound => "POSITION_NOT_FOUND",
155    /// The order was not found.
156    OrderNotFound => "ORDER_NOT_FOUND",
157    /// The position is not open.
158    PositionNotOpen => "POSITION_NOT_OPEN",
159    /// The position is locked.
160    PositionLocked => "POSITION_LOCKED",
161    /// The limit of open positions is reached.
162    TooManyPositions => "TOO_MANY_POSITIONS",
163    /// The volume is not valid.
164    TradingBadVolume => "TRADING_BAD_VOLUME",
165    /// The stop levels are not valid.
166    TradingBadStops => "TRADING_BAD_STOPS",
167    /// The prices are not valid.
168    TradingBadPrices => "TRADING_BAD_PRICES",
169    /// The stake is not valid.
170    TradingBadStake => "TRADING_BAD_STAKE",
171    /// The protection level is too close to the market price.
172    ProtectionIsTooCloseToMarket => "PROTECTION_IS_TOO_CLOSE_TO_MARKET",
173    /// The expiration date is not valid.
174    TradingBadExpirationDate => "TRADING_BAD_EXPIRATION_DATE",
175    /// The position has an execution pending.
176    PendingExecution => "PENDING_EXECUTION",
177    /// Trading is disabled for the symbol.
178    TradingDisabled => "TRADING_DISABLED",
179    /// The account may not trade.
180    TradingNotAllowed => "TRADING_NOT_ALLOWED",
181    /// The order cannot be cancelled.
182    UnableToCancelOrder => "UNABLE_TO_CANCEL_ORDER",
183    /// The order cannot be amended.
184    UnableToAmendOrder => "UNABLE_TO_AMEND_ORDER",
185    /// Short selling is not allowed.
186    ShortSellingNotAllowed => "SHORT_SELLING_NOT_ALLOWED",
187}
188
189impl ErrorCode {
190    /// Tells whether the code is one the proto files name.
191    #[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/// Error reported by the server in reply to a request.
210///
211/// The `Debug` output masks the account: it prints `<masked>` in place of the identifier, so
212/// an error printed to a log or to the output of a test names no account. The `Display`
213/// output carries the code and the explanation only. The [`account_id`](Self::account_id)
214/// field itself stays readable.
215#[derive(Clone, PartialEq, Eq, Error)]
216#[error("server error {code}{}", detail(.description.as_deref()))]
217#[non_exhaustive]
218pub struct ServerError {
219    /// Code of the error, preserved as sent.
220    pub code: ErrorCode,
221    /// Explanation given by the server, when there is one.
222    pub description: Option<String>,
223    /// Account the error concerns, when the server names one.
224    pub account_id: Option<AccountId>,
225    /// End of the maintenance window in milliseconds since the Unix epoch, when announced.
226    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    /// Describes an error with the given code and no further detail.
250    #[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    /// Adds the explanation given by the server.
261    #[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    /// Adds the account the error concerns.
268    #[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    /// Adds the end of the maintenance window, in milliseconds since the Unix epoch.
275    #[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/// Reasons an identifier, a price, a volume or a moment in time is rejected.
287#[derive(Debug, Clone, PartialEq, Eq, Error)]
288#[non_exhaustive]
289pub enum ValueError {
290    /// The identifier is not a positive integer.
291    #[error("{kind} must be a positive integer, got {value}")]
292    InvalidId {
293        /// Kind of the identifier.
294        kind: &'static str,
295        /// The rejected value as given.
296        value: String,
297    },
298    /// The text is not a decimal number.
299    #[error("{kind} is not a decimal number: {text}")]
300    InvalidDecimal {
301        /// Kind of the value.
302        kind: &'static str,
303        /// The rejected text.
304        text: String,
305    },
306    /// The value is below zero.
307    #[error("{kind} must not be negative, got {value}")]
308    Negative {
309        /// Kind of the value.
310        kind: &'static str,
311        /// The rejected value.
312        value: Decimal,
313    },
314    /// The symbol has more digits than a wire price carries.
315    #[error("symbol digits must be at most 5, got {digits}")]
316    TooManyDigits {
317        /// The rejected number of digits.
318        digits: u32,
319    },
320    /// The value is finer than the wire step or too large for the wire integer.
321    #[error("{kind} cannot be carried on the wire: {value}")]
322    Unrepresentable {
323        /// Kind of the value.
324        kind: &'static str,
325        /// The rejected value.
326        value: Decimal,
327    },
328    /// The wire integer does not fit a decimal.
329    #[error("{kind} is out of range")]
330    OutOfRange {
331        /// Kind of the value.
332        kind: &'static str,
333    },
334    /// A message of the server lacks a field the value is built from.
335    #[error("{kind} is missing")]
336    Missing {
337        /// Kind of the value.
338        kind: &'static str,
339    },
340    /// A range of time ends before it starts.
341    #[error("range from {from} ends before it starts, at {to}")]
342    InvertedRange {
343        /// Start of the range, in milliseconds since the Unix epoch.
344        from: i64,
345        /// End of the range, in milliseconds since the Unix epoch.
346        to: i64,
347    },
348    /// The text has more characters than the server keeps.
349    #[error("{kind} has {length} characters, more than the {limit} allowed")]
350    TooLong {
351        /// Kind of the text.
352        kind: &'static str,
353        /// Number of characters of the rejected text.
354        length: usize,
355        /// Largest number of characters allowed.
356        limit: usize,
357    },
358    /// The value is smaller than the symbol allows.
359    #[error("{kind} must be at least {minimum}, got {value}")]
360    BelowMinimum {
361        /// Kind of the value.
362        kind: &'static str,
363        /// The rejected value.
364        value: Decimal,
365        /// Smallest value allowed.
366        minimum: Decimal,
367    },
368    /// The value is larger than the symbol allows.
369    #[error("{kind} must be at most {maximum}, got {value}")]
370    AboveMaximum {
371        /// Kind of the value.
372        kind: &'static str,
373        /// The rejected value.
374        value: Decimal,
375        /// Largest value allowed.
376        maximum: Decimal,
377    },
378    /// The value is not a multiple of the step of the symbol.
379    #[error("{kind} must be a multiple of {step}, got {value}")]
380    OffStep {
381        /// Kind of the value.
382        kind: &'static str,
383        /// The rejected value.
384        value: Decimal,
385        /// Step the value has to be a multiple of.
386        step: Decimal,
387    },
388    /// The value has more decimal places than the symbol has digits.
389    #[error("{kind} must have at most {digits} decimal places, got {value}")]
390    TooFine {
391        /// Kind of the value.
392        kind: &'static str,
393        /// The rejected value.
394        value: Decimal,
395        /// Digits of the symbol.
396        digits: u32,
397    },
398    /// Two values that have to agree do not.
399    #[error("{kind} does not match")]
400    Mismatch {
401        /// Kind of the value.
402        kind: &'static str,
403    },
404    /// The value cannot be given for this kind of request.
405    #[error("{kind} is not supported here")]
406    Unsupported {
407        /// Kind of the value.
408        kind: &'static str,
409    },
410}
411
412/// Reasons a connection fails below the level of protocol messages.
413///
414/// The variants carry text instead of the underlying error values so the type stays comparable
415/// and cloneable.
416#[derive(Debug, Clone, PartialEq, Eq, Error)]
417#[non_exhaustive]
418pub enum TransportError {
419    /// Reading from or writing to the socket failed.
420    #[error("input or output failed ({kind:?}): {message}")]
421    Io {
422        /// Kind of the failure.
423        kind: std::io::ErrorKind,
424        /// Explanation given by the operating system or the runtime.
425        message: String,
426    },
427    /// The TLS layer refused the configuration or the handshake.
428    #[error("TLS failed: {0}")]
429    Tls(String),
430    /// The host is not a name a certificate can be checked against.
431    #[error("host is not a valid server name: {0}")]
432    InvalidHost(String),
433    /// The connection was not established in time.
434    #[error("connecting timed out after {0:?}")]
435    ConnectTimeout(Duration),
436    /// A write to the socket did not complete in time.
437    #[error("writing timed out after {0:?}")]
438    WriteTimeout(Duration),
439    /// The peer sent nothing, not even a heartbeat, for the time allowed.
440    #[error("nothing was received for {0:?}")]
441    Idle(Duration),
442    /// A frame is longer than the limit.
443    #[error("frame of {length} bytes exceeds the limit of {limit} bytes")]
444    FrameTooLong {
445        /// Length announced by the frame.
446        length: usize,
447        /// Longest frame accepted.
448        limit: usize,
449    },
450    /// A frame does not hold a valid message.
451    #[error("frame cannot be decoded: {0}")]
452    Decode(String),
453    /// The peer closed the connection.
454    #[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/// Reasons a token refresh fails.
468///
469/// The variants never carry a token or the reply of the token endpoint.
470#[derive(Debug, Clone, PartialEq, Eq, Error)]
471#[non_exhaustive]
472pub enum TokenError {
473    /// The configuration holds no refresh token.
474    #[error("no refresh token is configured")]
475    NoRefreshToken,
476    /// The token endpoint refused the refresh.
477    #[error("token refresh refused: {code}{}", detail(Some(.description.as_str()).filter(|text| !text.is_empty())))]
478    Refused {
479        /// Code of the refusal as sent.
480        code: String,
481        /// Explanation given by the endpoint; empty when there is none.
482        description: String,
483    },
484    /// The reply lacks the named part or the part is not valid.
485    #[error("token response is malformed: {0}")]
486    Malformed(&'static str),
487    /// The token endpoint answered with an HTTP status that signals a failure.
488    #[error("token endpoint answered with status {0}")]
489    Status(u16),
490}
491
492/// What kept the answer to a request that was sent from arriving.
493#[derive(Debug, Clone, PartialEq, Eq, Error)]
494#[non_exhaustive]
495pub enum Interruption {
496    /// The server did not answer in time.
497    #[error("no response within {0:?}")]
498    Timeout(Duration),
499    /// The connection failed while the answer was awaited.
500    #[error("transport failed: {0}")]
501    Transport(TransportError),
502    /// The server asked for the request again and was told to skip it, because no request
503    /// is sent twice.
504    #[error("the server asked for the request again and it was not repeated")]
505    Skipped,
506}
507
508/// What ended the authorisation of a session.
509#[derive(Debug, Clone, PartialEq, Eq, Error)]
510#[non_exhaustive]
511pub enum SessionEndCause {
512    /// The server announced that the access token of the account is no longer valid, as
513    /// happens once the token pair was refreshed elsewhere or the access was revoked.
514    #[error("the access token was invalidated{}", detail(.reason.as_deref()))]
515    TokenInvalidated {
516        /// Explanation given by the server, when it gave one.
517        reason: Option<String>,
518    },
519    /// The server announced that it dropped the session of the account.
520    #[error("the server dropped the session of the account")]
521    AccountDisconnected,
522    /// The server announced that it ends the session of the application.
523    #[error("the server ended the session of the application{}", detail(.reason.as_deref()))]
524    ClientDisconnected {
525        /// Explanation given by the server, when it gave one.
526        reason: Option<String>,
527    },
528    /// The server refused the access token when the account was authorised again after a
529    /// reconnection.
530    #[error("the access token was refused after a reconnection: {0}")]
531    TokenRefused(ErrorCode),
532}
533
534/// A session that is no longer authorised on its connection.
535///
536/// Requests on the session fail with this error, without being sent, from the moment the
537/// server ends the authorisation until the session is authorised again.
538#[derive(Debug, Clone, PartialEq, Eq, Error)]
539#[error("{} is no longer authorised: {cause}", subject(.account.as_ref()))]
540#[non_exhaustive]
541pub struct SessionEnded {
542    /// Account whose session ended; `None` when the session of the application ended, which
543    /// ends the sessions of all its accounts.
544    pub account: Option<AccountId>,
545    /// What ended the authorisation.
546    pub cause: SessionEndCause,
547}
548
549impl SessionEnded {
550    /// Describes the end of the session of `account`, or of the application for `None`.
551    #[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/// Reasons a FIX message is rejected by this library.
565///
566/// No variant holds the value of a field, so no credential of a logon can reach a log through
567/// an error.
568#[derive(Debug, Clone, PartialEq, Eq, Error)]
569#[non_exhaustive]
570pub enum FixError {
571    /// The bytes are not a FIX message.
572    #[error("the bytes are not a FIX message: {0}")]
573    Garbled(&'static str),
574    /// The checksum of a message does not match its bytes.
575    #[error("checksum is {found}, the bytes sum to {computed}")]
576    Checksum {
577        /// Checksum computed over the bytes received.
578        computed: u8,
579        /// Checksum the message carries.
580        found: u8,
581    },
582    /// The body of a message is longer than the limit.
583    #[error("body of {length} bytes exceeds the limit of {limit} bytes")]
584    TooLong {
585        /// Length of the body in bytes.
586        length: usize,
587        /// Largest length accepted.
588        limit: usize,
589    },
590    /// A required field is absent.
591    #[error("message {msg_type} lacks the required tag {tag}")]
592    MissingField {
593        /// Type of the message.
594        msg_type: String,
595        /// Tag that is absent.
596        tag: u32,
597    },
598    /// A field holds a value of the wrong form.
599    #[error("message {msg_type} holds an invalid value under tag {tag}")]
600    InvalidField {
601        /// Type of the message.
602        msg_type: String,
603        /// Tag whose value is invalid.
604        tag: u32,
605    },
606    /// The type of the message is not known to this library.
607    #[error("message type {0} is not supported")]
608    UnsupportedMessage(String),
609    /// The message is of a type this library never sends, because the server refuses it.
610    #[error("message type {0} is never sent")]
611    Unsendable(String),
612    /// The server answered the logon with a logout.
613    #[error("the server refused the logon: {}", explained(text.as_deref()))]
614    LogonRefused {
615        /// Explanation the server gave.
616        text: Option<String>,
617    },
618    /// A message of this type arrived where another was due.
619    #[error("message of type {0} arrived where another was due")]
620    UnexpectedMessage(String),
621    /// The server rejected a message at the session level.
622    #[error("the server rejected message {ref_seq_num}: {}", explained(text.as_deref()))]
623    Rejected {
624        /// Sequence number of the message rejected.
625        ref_seq_num: u64,
626        /// Tag the server objects to.
627        tag: Option<u32>,
628        /// Reason code of the server.
629        reason: Option<u32>,
630        /// Explanation the server gave.
631        text: Option<String>,
632    },
633    /// The server refused a request at the application level.
634    #[error("the server refused the request: {}", explained(text.as_deref()))]
635    BusinessRejected {
636        /// Identifier of the request refused.
637        ref_id: Option<String>,
638        /// Reason code of the server.
639        reason: Option<u32>,
640        /// Explanation the server gave.
641        text: Option<String>,
642    },
643    /// The server refused a subscription to prices.
644    #[error("the server refused the market data request: {}", explained(text.as_deref()))]
645    MarketDataRejected {
646        /// Reason code of the server.
647        reason: Option<u32>,
648        /// Explanation the server gave.
649        text: Option<String>,
650    },
651    /// The server took an order and then refused, cancelled or expired it.
652    #[error("the server refused the order: {}", explained(text.as_deref()))]
653    OrderRejected {
654        /// Identifier the client gave the order.
655        cl_ord_id: Option<String>,
656        /// Reason code of the server.
657        reason: Option<u32>,
658        /// Explanation the server gave.
659        text: Option<String>,
660    },
661    /// The server refused to cancel or to replace an order, which stays as it was.
662    #[error("the server refused to change the order: {}", explained(text.as_deref()))]
663    CancelRejected {
664        /// Identifier the client gave the refused request.
665        cl_ord_id: String,
666        /// Identifier of the order the request named.
667        orig_cl_ord_id: Option<String>,
668        /// Whether a cancellation or a replacement was refused.
669        change: RefusedChange,
670        /// Explanation the server gave.
671        text: Option<String>,
672    },
673}
674
675/// Change of an order the server refused.
676#[derive(Debug, Clone, Copy, PartialEq, Eq)]
677pub enum RefusedChange {
678    /// A cancellation.
679    Cancel,
680    /// A replacement of the terms.
681    Replace,
682}
683
684fn explained(text: Option<&str>) -> &str {
685    text.unwrap_or("no explanation given")
686}
687
688/// Any failure reported by this library.
689#[derive(Debug, Clone, PartialEq, Eq, Error)]
690#[non_exhaustive]
691pub enum ConnectorError {
692    /// The configuration was rejected.
693    #[error("configuration rejected: {0}")]
694    Config(#[from] ConfigError),
695    /// The server refused a request.
696    #[error(transparent)]
697    Server(#[from] ServerError),
698    /// An identifier, a price or a volume was rejected.
699    #[error("value rejected: {0}")]
700    Value(#[from] ValueError),
701    /// The connection failed below the level of protocol messages.
702    #[error("transport failed: {0}")]
703    Transport(#[from] TransportError),
704    /// A token refresh failed.
705    #[error(transparent)]
706    Token(#[from] TokenError),
707    /// A FIX message was rejected, by this library or by the server.
708    #[error("FIX failure: {0}")]
709    Fix(#[from] FixError),
710    /// The server did not answer a request in time.
711    #[error("no response within {0:?}")]
712    Timeout(Duration),
713    /// A request that must not be sent twice was sent, and the connection failed or the time
714    /// allowed ran out before the server answered: the server may or may not have acted on it.
715    #[error("the request was sent and its outcome is unknown: {0}")]
716    OutcomeUnknown(Interruption),
717    /// The server ended the authorisation of the session the request belongs to.
718    #[error(transparent)]
719    SessionEnded(#[from] SessionEnded),
720    /// The connection is shut down and accepts no further requests.
721    #[error("connection is shut down")]
722    Closed,
723    /// A reader of the events of the connection fell behind and events were dropped unread.
724    #[error("{skipped} events were dropped because their reader fell behind")]
725    Lagged {
726        /// Number of events dropped unread.
727        skipped: u64,
728    },
729    /// The server announced more historical data than it sent and the rest cannot be asked for,
730    /// so data between the two moments, both included, is missing.
731    #[error("the server announced more data between {from} and {to} than it sent")]
732    Incomplete {
733        /// Start of the part that is missing.
734        from: Timestamp,
735        /// End of the part that is missing.
736        to: Timestamp,
737    },
738    /// The server answered with a message of another type than the request calls for.
739    #[error("expected payload type {expected}, received {received}")]
740    UnexpectedResponse {
741        /// Payload type of the response the request calls for.
742        expected: u32,
743        /// Payload type the server sent.
744        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}