Skip to main content

ctrader_connector/common/
config.rs

1//! Connection configuration and its builders.
2//!
3//! A configuration targets the demo environment unless the live one is requested:
4//!
5//! ```
6//! use ctrader_connector::common::config::{ConfigurationOpenApi, Environment};
7//!
8//! let configuration = ConfigurationOpenApi::builder()
9//!     .client_id("id")
10//!     .client_secret("secret")
11//!     .access_token("token")
12//!     .build()?;
13//! assert_eq!(configuration.environment(), Environment::Demo);
14//! # Ok::<(), ctrader_connector::common::errors::ConfigError>(())
15//! ```
16
17use std::fmt;
18use std::str::FromStr;
19use std::time::Duration;
20
21use crate::common::errors::ConfigError;
22
23/// Host of the demo environment.
24pub const DEMO_HOST: &str = "demo.ctraderapi.com";
25/// Host of the live environment.
26pub const LIVE_HOST: &str = "live.ctraderapi.com";
27/// Port accepting Protobuf messages over TLS.
28pub const DEFAULT_PORT: u16 = 5035;
29/// Endpoint that exchanges a refresh token for a new access token.
30pub const DEFAULT_TOKEN_URL: &str = "https://connect.spotware.com/apps/token";
31/// Default time allowed for a single request.
32pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
33/// Default number of times a failed request is retried.
34pub const DEFAULT_RETRIES: u32 = 3;
35/// Default pause before a retry.
36pub const DEFAULT_BACKOFF: Duration = Duration::from_secs(1);
37/// Default pause before a dropped connection is opened again.
38pub const DEFAULT_RECONNECT_DELAY: Duration = Duration::from_secs(5);
39
40/// Environment variable holding the application client id.
41pub const ENV_CLIENT_ID: &str = "BROKER_CLIENT_ID";
42/// Environment variable holding the application client secret.
43pub const ENV_CLIENT_SECRET: &str = "BROKER_CLIENT_SECRET";
44/// Environment variable holding the access token.
45pub const ENV_ACCESS_TOKEN: &str = "BROKER_ACCESS_TOKEN";
46/// Environment variable holding the refresh token.
47pub const ENV_REFRESH_TOKEN: &str = "BROKER_REFRESH_TOKEN";
48/// Environment variable overriding the host of the demo environment.
49pub const ENV_DEMO_HOST: &str = "BROKER_DEMO_HOST";
50/// Environment variable overriding the token URL.
51pub const ENV_TOKEN_URL: &str = "BROKER_TOKEN_URL";
52/// Environment variable selecting the environment, `demo` or `live`.
53pub const ENV_ENVIRONMENT: &str = "BROKER_ENVIRONMENT";
54
55const CLIENT_ID: &str = "client_id";
56const CLIENT_SECRET: &str = "client_secret";
57const ACCESS_TOKEN: &str = "access_token";
58const REFRESH_TOKEN: &str = "refresh_token";
59const FIX_PASSWORD: &str = "fix_password";
60const TIMEOUT: &str = "timeout";
61const BACKOFF: &str = "backoff";
62const RECONNECT_DELAY: &str = "reconnect_delay";
63
64/// Trading environment a connection targets.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
66pub enum Environment {
67    /// Demo accounts; the default.
68    #[default]
69    Demo,
70    /// Live accounts.
71    Live,
72}
73
74impl Environment {
75    /// Returns the default host of the environment.
76    #[must_use]
77    pub const fn host(self) -> &'static str {
78        match self {
79            Self::Demo => DEMO_HOST,
80            Self::Live => LIVE_HOST,
81        }
82    }
83
84    /// Returns the lower-case name of the environment.
85    #[must_use]
86    pub const fn as_str(self) -> &'static str {
87        match self {
88            Self::Demo => "demo",
89            Self::Live => "live",
90        }
91    }
92}
93
94impl fmt::Display for Environment {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(self.as_str())
97    }
98}
99
100impl FromStr for Environment {
101    type Err = ConfigError;
102
103    fn from_str(text: &str) -> Result<Self, Self::Err> {
104        match text {
105            "demo" => Ok(Self::Demo),
106            "live" => Ok(Self::Live),
107            other => Err(ConfigError::InvalidEnvironment(other.to_owned())),
108        }
109    }
110}
111
112/// Identifier of the application registered with the broker.
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
114pub struct ClientId(String);
115
116impl ClientId {
117    /// Wraps a client id.
118    ///
119    /// # Errors
120    ///
121    /// Returns [`ConfigError::Missing`] when the value is empty.
122    pub fn new(value: impl Into<String>) -> Result<Self, ConfigError> {
123        filled(value.into(), CLIENT_ID).map(Self)
124    }
125
126    /// Returns the client id.
127    #[must_use]
128    pub fn as_str(&self) -> &str {
129        &self.0
130    }
131}
132
133macro_rules! secret {
134    ($(#[$doc:meta])* $name:ident, $option:expr) => {
135        $(#[$doc])*
136        ///
137        /// The value never appears in `Debug` output.
138        #[derive(Clone, PartialEq, Eq)]
139        pub struct $name(String);
140
141        impl $name {
142            /// Wraps a secret value.
143            ///
144            /// # Errors
145            ///
146            /// Returns [`ConfigError::Missing`] when the value is empty.
147            pub fn new(value: impl Into<String>) -> Result<Self, ConfigError> {
148                filled(value.into(), $option).map(Self)
149            }
150
151            /// Returns the secret value; the caller must keep it out of logs.
152            #[must_use]
153            pub fn expose(&self) -> &str {
154                &self.0
155            }
156        }
157
158        impl fmt::Debug for $name {
159            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160                f.write_str(concat!(stringify!($name), "(***)"))
161            }
162        }
163    };
164}
165
166secret!(
167    /// Secret of the application registered with the broker.
168    ClientSecret,
169    CLIENT_SECRET
170);
171secret!(
172    /// Token authorising access to trading accounts.
173    AccessToken,
174    ACCESS_TOKEN
175);
176secret!(
177    /// Token exchanged for a new access token.
178    RefreshToken,
179    REFRESH_TOKEN
180);
181secret!(
182    /// Password of the FIX sessions of a trading account.
183    FixPassword,
184    FIX_PASSWORD
185);
186
187fn filled(value: String, option: &'static str) -> Result<String, ConfigError> {
188    if value.trim().is_empty() {
189        Err(ConfigError::Missing(option))
190    } else {
191        Ok(value)
192    }
193}
194
195fn host_name(value: String) -> Result<String, ConfigError> {
196    let bare = !value.is_empty()
197        && value
198            .chars()
199            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-');
200    if bare {
201        Ok(value)
202    } else {
203        Err(ConfigError::InvalidHost(value))
204    }
205}
206
207fn https_url(value: String) -> Result<String, ConfigError> {
208    let valid = value.strip_prefix("https://").is_some_and(|rest| {
209        !rest.is_empty() && !rest.starts_with('/') && !rest.contains(char::is_whitespace)
210    });
211    if valid {
212        Ok(value)
213    } else {
214        Err(ConfigError::InvalidTokenUrl(value))
215    }
216}
217
218fn positive(value: Duration, option: &'static str) -> Result<Duration, ConfigError> {
219    if value.is_zero() {
220        Err(ConfigError::ZeroDuration(option))
221    } else {
222        Ok(value)
223    }
224}
225
226/// Validated configuration of an Open API connection.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct ConfigurationOpenApi {
229    environment: Environment,
230    host: String,
231    port: u16,
232    client_id: ClientId,
233    client_secret: ClientSecret,
234    access_token: AccessToken,
235    refresh_token: Option<RefreshToken>,
236    token_url: String,
237    timeout: Duration,
238    retries: u32,
239    backoff: Duration,
240    reconnect_delay: Duration,
241}
242
243impl ConfigurationOpenApi {
244    /// Starts a configuration for the demo environment.
245    pub fn builder() -> ConfigurationOpenApiBuilder {
246        Self::demo()
247    }
248
249    /// Starts a configuration for the demo environment.
250    pub fn demo() -> ConfigurationOpenApiBuilder {
251        ConfigurationOpenApiBuilder::new(Environment::Demo)
252    }
253
254    /// Starts a configuration for the live environment.
255    pub fn live() -> ConfigurationOpenApiBuilder {
256        ConfigurationOpenApiBuilder::new(Environment::Live)
257    }
258
259    /// Builds a configuration from the process environment.
260    ///
261    /// See [`ConfigurationOpenApi::from_lookup`] for the variables read.
262    ///
263    /// # Errors
264    ///
265    /// Returns a [`ConfigError`] when a required variable is absent or a value is rejected.
266    pub fn from_env() -> Result<Self, ConfigError> {
267        Self::from_lookup(|key| std::env::var(key).ok())
268    }
269
270    /// Builds a configuration from variables resolved by `lookup`.
271    ///
272    /// [`ENV_CLIENT_ID`], [`ENV_CLIENT_SECRET`] and [`ENV_ACCESS_TOKEN`] are required.
273    /// [`ENV_REFRESH_TOKEN`], [`ENV_TOKEN_URL`] and [`ENV_ENVIRONMENT`] are optional, and
274    /// [`ENV_DEMO_HOST`] replaces the host only when the environment is demo. An empty value
275    /// counts as absent.
276    ///
277    /// # Errors
278    ///
279    /// Returns a [`ConfigError`] when a required variable is absent or a value is rejected.
280    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
281        let optional = |key: &str| lookup(key).filter(|value| !value.trim().is_empty());
282        let required = |key: &'static str| optional(key).ok_or(ConfigError::Missing(key));
283        let environment = match optional(ENV_ENVIRONMENT) {
284            Some(name) => name.parse()?,
285            None => Environment::Demo,
286        };
287        let mut builder = ConfigurationOpenApiBuilder::new(environment)
288            .client_id(required(ENV_CLIENT_ID)?)
289            .client_secret(required(ENV_CLIENT_SECRET)?)
290            .access_token(required(ENV_ACCESS_TOKEN)?);
291        if let Some(token) = optional(ENV_REFRESH_TOKEN) {
292            builder = builder.refresh_token(token);
293        }
294        if let Some(url) = optional(ENV_TOKEN_URL) {
295            builder = builder.token_url(url);
296        }
297        if environment == Environment::Demo {
298            if let Some(host) = optional(ENV_DEMO_HOST) {
299                builder = builder.host(host);
300            }
301        }
302        builder.build()
303    }
304
305    /// Returns the environment the connection targets.
306    #[must_use]
307    pub const fn environment(&self) -> Environment {
308        self.environment
309    }
310
311    /// Returns the host to connect to.
312    #[must_use]
313    pub fn host(&self) -> &str {
314        &self.host
315    }
316
317    /// Returns the port to connect to.
318    #[must_use]
319    pub const fn port(&self) -> u16 {
320        self.port
321    }
322
323    /// Returns the application client id.
324    #[must_use]
325    pub const fn client_id(&self) -> &ClientId {
326        &self.client_id
327    }
328
329    /// Returns the application client secret.
330    #[must_use]
331    pub const fn client_secret(&self) -> &ClientSecret {
332        &self.client_secret
333    }
334
335    /// Returns the access token.
336    #[must_use]
337    pub const fn access_token(&self) -> &AccessToken {
338        &self.access_token
339    }
340
341    /// Returns the refresh token, when one was given.
342    #[must_use]
343    pub const fn refresh_token(&self) -> Option<&RefreshToken> {
344        self.refresh_token.as_ref()
345    }
346
347    /// Returns the endpoint that refreshes the access token.
348    #[must_use]
349    pub fn token_url(&self) -> &str {
350        &self.token_url
351    }
352
353    /// Returns the time allowed for a single request.
354    #[must_use]
355    pub const fn timeout(&self) -> Duration {
356        self.timeout
357    }
358
359    /// Returns the number of times a failed request is retried.
360    #[must_use]
361    pub const fn retries(&self) -> u32 {
362        self.retries
363    }
364
365    /// Returns the pause before a retry.
366    #[must_use]
367    pub const fn backoff(&self) -> Duration {
368        self.backoff
369    }
370
371    /// Returns the pause before a dropped connection is opened again.
372    #[must_use]
373    pub const fn reconnect_delay(&self) -> Duration {
374        self.reconnect_delay
375    }
376}
377
378/// Builder of a [`ConfigurationOpenApi`].
379///
380/// Values are checked by [`ConfigurationOpenApiBuilder::build`], not by the setters.
381#[derive(Debug, Clone)]
382#[must_use]
383pub struct ConfigurationOpenApiBuilder {
384    environment: Environment,
385    host: Option<String>,
386    port: u16,
387    client_id: Option<String>,
388    client_secret: Option<String>,
389    access_token: Option<String>,
390    refresh_token: Option<String>,
391    token_url: String,
392    timeout: Duration,
393    retries: u32,
394    backoff: Duration,
395    reconnect_delay: Duration,
396}
397
398impl ConfigurationOpenApiBuilder {
399    fn new(environment: Environment) -> Self {
400        Self {
401            environment,
402            host: None,
403            port: DEFAULT_PORT,
404            client_id: None,
405            client_secret: None,
406            access_token: None,
407            refresh_token: None,
408            token_url: DEFAULT_TOKEN_URL.to_owned(),
409            timeout: DEFAULT_TIMEOUT,
410            retries: DEFAULT_RETRIES,
411            backoff: DEFAULT_BACKOFF,
412            reconnect_delay: DEFAULT_RECONNECT_DELAY,
413        }
414    }
415
416    /// Sets the host, replacing the default of the environment.
417    pub fn host(mut self, host: impl Into<String>) -> Self {
418        self.host = Some(host.into());
419        self
420    }
421
422    /// Sets the port.
423    pub fn port(mut self, port: u16) -> Self {
424        self.port = port;
425        self
426    }
427
428    /// Sets the application client id.
429    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
430        self.client_id = Some(client_id.into());
431        self
432    }
433
434    /// Sets the application client secret.
435    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
436        self.client_secret = Some(client_secret.into());
437        self
438    }
439
440    /// Sets the access token.
441    pub fn access_token(mut self, access_token: impl Into<String>) -> Self {
442        self.access_token = Some(access_token.into());
443        self
444    }
445
446    /// Sets the refresh token.
447    pub fn refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
448        self.refresh_token = Some(refresh_token.into());
449        self
450    }
451
452    /// Sets the endpoint that refreshes the access token.
453    pub fn token_url(mut self, token_url: impl Into<String>) -> Self {
454        self.token_url = token_url.into();
455        self
456    }
457
458    /// Sets the time allowed for a single request.
459    pub fn timeout(mut self, timeout: Duration) -> Self {
460        self.timeout = timeout;
461        self
462    }
463
464    /// Sets the number of times a failed request is retried; zero disables retries.
465    pub fn retries(mut self, retries: u32) -> Self {
466        self.retries = retries;
467        self
468    }
469
470    /// Sets the pause before a retry.
471    pub fn backoff(mut self, backoff: Duration) -> Self {
472        self.backoff = backoff;
473        self
474    }
475
476    /// Sets the pause before a dropped connection is opened again.
477    pub fn reconnect_delay(mut self, reconnect_delay: Duration) -> Self {
478        self.reconnect_delay = reconnect_delay;
479        self
480    }
481
482    /// Checks every value and returns the configuration.
483    ///
484    /// # Errors
485    ///
486    /// Returns a [`ConfigError`] when the client id, client secret or access token is absent
487    /// or empty, the refresh token is empty, the host is not a bare host name, the port is
488    /// zero, the token URL is not an `https` URL, or a duration is zero.
489    pub fn build(self) -> Result<ConfigurationOpenApi, ConfigError> {
490        let host = self
491            .host
492            .unwrap_or_else(|| self.environment.host().to_owned());
493        Ok(ConfigurationOpenApi {
494            environment: self.environment,
495            host: host_name(host)?,
496            port: if self.port == 0 {
497                return Err(ConfigError::InvalidPort);
498            } else {
499                self.port
500            },
501            client_id: ClientId::new(self.client_id.unwrap_or_default())?,
502            client_secret: ClientSecret::new(self.client_secret.unwrap_or_default())?,
503            access_token: AccessToken::new(self.access_token.unwrap_or_default())?,
504            refresh_token: self.refresh_token.map(RefreshToken::new).transpose()?,
505            token_url: https_url(self.token_url)?,
506            timeout: positive(self.timeout, TIMEOUT)?,
507            retries: self.retries,
508            backoff: positive(self.backoff, BACKOFF)?,
509            reconnect_delay: positive(self.reconnect_delay, RECONNECT_DELAY)?,
510        })
511    }
512}
513
514/// Host of the FIX sessions; every broker has its own.
515pub const ENV_FIX_HOST: &str = "BROKER_FIX_HOST";
516/// Port of the price session over TLS.
517pub const ENV_FIX_QUOTE_PORT: &str = "BROKER_FIX_QUOTE_PORT";
518/// Port of the trade session over TLS.
519pub const ENV_FIX_TRADE_PORT: &str = "BROKER_FIX_TRADE_PORT";
520/// Identifier the client sends as its sender (49).
521pub const ENV_FIX_SENDER_COMP_ID: &str = "BROKER_FIX_SENDER_COMP_ID";
522/// Identifier of the server (56).
523pub const ENV_FIX_TARGET_COMP_ID: &str = "BROKER_FIX_TARGET_COMP_ID";
524/// Login of the trading account (553).
525pub const ENV_FIX_USERNAME: &str = "BROKER_FIX_USERNAME";
526/// Password of the FIX sessions of the account (554).
527pub const ENV_FIX_PASSWORD: &str = "BROKER_FIX_PASSWORD";
528
529/// Default port of the price session over TLS.
530pub const DEFAULT_FIX_QUOTE_PORT: u16 = 5211;
531/// Default port of the trade session over TLS.
532pub const DEFAULT_FIX_TRADE_PORT: u16 = 5212;
533/// Default port of the price session without encryption.
534pub const DEFAULT_FIX_QUOTE_PLAIN_PORT: u16 = 5201;
535/// Default port of the trade session without encryption.
536pub const DEFAULT_FIX_TRADE_PLAIN_PORT: u16 = 5202;
537/// Identifier of the server the specification names.
538pub const DEFAULT_FIX_TARGET_COMP_ID: &str = "CSERVER";
539/// Default interval between heartbeats.
540pub const DEFAULT_FIX_HEARTBEAT: Duration = Duration::from_secs(30);
541/// Longest interval between heartbeats a configuration accepts.
542///
543/// The logon carries the interval as a whole number of seconds (108) and the session watches
544/// the server on multiples of it, so an interval without an end would leave a dead connection
545/// unnoticed.
546pub const MAX_FIX_HEARTBEAT: Duration = Duration::from_secs(3_600);
547/// Longest reconnect delay a configuration holds: the pause before the first attempt to
548/// open a lost session again.
549///
550/// A configuration takes a longer delay as this one. The constant bounds the delay, not
551/// every pause: a session makes five attempts at most and pauses before the n-th one for n
552/// times the delay, so the longest pause, the one before the fifth attempt, is five hours.
553/// The bound keeps a session that lost its connection from waiting without an end before it
554/// logs on again.
555pub const MAX_FIX_RECONNECT_DELAY: Duration = Duration::from_secs(3_600);
556
557const FIX_HOST: &str = "host";
558const FIX_SENDER_COMP_ID: &str = "sender_comp_id";
559const FIX_TARGET_COMP_ID: &str = "target_comp_id";
560const FIX_USERNAME: &str = "username";
561const HEARTBEAT: &str = "heartbeat";
562
563fn port_number(text: &str) -> Result<u16, ConfigError> {
564    match text.trim().parse::<u16>() {
565        Ok(port) if port > 0 => Ok(port),
566        _ => Err(ConfigError::InvalidPort),
567    }
568}
569
570fn nonzero_port(port: u16) -> Result<u16, ConfigError> {
571    if port == 0 {
572        Err(ConfigError::InvalidPort)
573    } else {
574        Ok(port)
575    }
576}
577
578/// Validated configuration of the FIX sessions of one trading account.
579///
580/// The password never appears in `Debug` output.
581#[derive(Debug, Clone, PartialEq, Eq)]
582pub struct ConfigurationFix {
583    host: String,
584    quote_port: u16,
585    trade_port: u16,
586    encrypted: bool,
587    sender_comp_id: String,
588    target_comp_id: String,
589    username: String,
590    password: FixPassword,
591    heartbeat: Duration,
592    timeout: Duration,
593    reconnect_delay: Duration,
594}
595
596impl ConfigurationFix {
597    /// Starts a configuration; the sessions run over TLS unless
598    /// [`ConfigurationFixBuilder::unencrypted`] is called.
599    pub fn builder() -> ConfigurationFixBuilder {
600        ConfigurationFixBuilder::new()
601    }
602
603    /// Builds a configuration from the process environment.
604    ///
605    /// See [`ConfigurationFix::from_lookup`] for the variables read.
606    ///
607    /// # Errors
608    ///
609    /// Returns a [`ConfigError`] when a required variable is absent or a value is rejected.
610    pub fn from_env() -> Result<Self, ConfigError> {
611        Self::from_lookup(|key| std::env::var(key).ok())
612    }
613
614    /// Builds a configuration from variables resolved by `lookup`.
615    ///
616    /// [`ENV_FIX_HOST`], [`ENV_FIX_SENDER_COMP_ID`], [`ENV_FIX_USERNAME`] and
617    /// [`ENV_FIX_PASSWORD`] are required. [`ENV_FIX_QUOTE_PORT`] and [`ENV_FIX_TRADE_PORT`]
618    /// replace the default TLS ports. [`ENV_FIX_TARGET_COMP_ID`] replaces
619    /// [`DEFAULT_FIX_TARGET_COMP_ID`] and is sent as given; the server reads it without regard
620    /// to case. An empty value counts as absent. The sessions run over TLS.
621    ///
622    /// # Errors
623    ///
624    /// Returns a [`ConfigError`] when a required variable is absent or a value is rejected.
625    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
626        let optional = |key: &str| lookup(key).filter(|value| !value.trim().is_empty());
627        let required = |key: &'static str| optional(key).ok_or(ConfigError::Missing(key));
628        let mut builder = Self::builder()
629            .host(required(ENV_FIX_HOST)?)
630            .sender_comp_id(required(ENV_FIX_SENDER_COMP_ID)?)
631            .username(required(ENV_FIX_USERNAME)?)
632            .password(required(ENV_FIX_PASSWORD)?);
633        if let Some(port) = optional(ENV_FIX_QUOTE_PORT) {
634            builder = builder.quote_port(port_number(&port)?);
635        }
636        if let Some(port) = optional(ENV_FIX_TRADE_PORT) {
637            builder = builder.trade_port(port_number(&port)?);
638        }
639        if let Some(target) = optional(ENV_FIX_TARGET_COMP_ID) {
640            builder = builder.target_comp_id(target);
641        }
642        builder.build()
643    }
644
645    /// Returns the host.
646    #[must_use]
647    pub fn host(&self) -> &str {
648        &self.host
649    }
650
651    /// Returns the port of the price session.
652    #[must_use]
653    pub const fn quote_port(&self) -> u16 {
654        self.quote_port
655    }
656
657    /// Returns the port of the trade session.
658    #[must_use]
659    pub const fn trade_port(&self) -> u16 {
660        self.trade_port
661    }
662
663    /// Tells whether the sessions run over TLS.
664    #[must_use]
665    pub const fn encrypted(&self) -> bool {
666        self.encrypted
667    }
668
669    /// Returns the identifier the client sends as its sender (49).
670    #[must_use]
671    pub fn sender_comp_id(&self) -> &str {
672        &self.sender_comp_id
673    }
674
675    /// Returns the identifier of the server (56).
676    #[must_use]
677    pub fn target_comp_id(&self) -> &str {
678        &self.target_comp_id
679    }
680
681    /// Returns the login of the trading account (553).
682    #[must_use]
683    pub fn username(&self) -> &str {
684        &self.username
685    }
686
687    /// Returns the password of the sessions (554).
688    #[must_use]
689    pub const fn password(&self) -> &FixPassword {
690        &self.password
691    }
692
693    /// Returns the interval between heartbeats.
694    #[must_use]
695    pub const fn heartbeat(&self) -> Duration {
696        self.heartbeat
697    }
698
699    /// Returns the time allowed for an answer of the server and for a write.
700    #[must_use]
701    pub const fn timeout(&self) -> Duration {
702        self.timeout
703    }
704
705    /// Returns the reconnect delay: the pause before the first attempt to open a lost session
706    /// again. The pause before the n-th attempt is n times as long.
707    #[must_use]
708    pub const fn reconnect_delay(&self) -> Duration {
709        self.reconnect_delay
710    }
711}
712
713/// Builder of a [`ConfigurationFix`].
714///
715/// Values are checked by [`ConfigurationFixBuilder::build`], not by the setters.
716#[derive(Debug, Clone)]
717#[must_use]
718pub struct ConfigurationFixBuilder {
719    host: Option<String>,
720    quote_port: Option<u16>,
721    trade_port: Option<u16>,
722    encrypted: bool,
723    sender_comp_id: Option<String>,
724    target_comp_id: String,
725    username: Option<String>,
726    password: Option<FixPassword>,
727    heartbeat: Duration,
728    timeout: Duration,
729    reconnect_delay: Duration,
730}
731
732impl ConfigurationFixBuilder {
733    fn new() -> Self {
734        Self {
735            host: None,
736            quote_port: None,
737            trade_port: None,
738            encrypted: true,
739            sender_comp_id: None,
740            target_comp_id: DEFAULT_FIX_TARGET_COMP_ID.to_owned(),
741            username: None,
742            password: None,
743            heartbeat: DEFAULT_FIX_HEARTBEAT,
744            timeout: DEFAULT_TIMEOUT,
745            reconnect_delay: DEFAULT_RECONNECT_DELAY,
746        }
747    }
748
749    /// Sets the host.
750    pub fn host(mut self, host: impl Into<String>) -> Self {
751        self.host = Some(host.into());
752        self
753    }
754
755    /// Sets the port of the price session, replacing the default of the transport.
756    pub const fn quote_port(mut self, port: u16) -> Self {
757        self.quote_port = Some(port);
758        self
759    }
760
761    /// Sets the port of the trade session, replacing the default of the transport.
762    pub const fn trade_port(mut self, port: u16) -> Self {
763        self.trade_port = Some(port);
764        self
765    }
766
767    /// Runs the sessions without encryption: the password and every order cross the network
768    /// in the clear. TLS is the default; this is an explicit choice for networks that are
769    /// trusted, and it moves the default ports to the unencrypted ones.
770    pub const fn unencrypted(mut self) -> Self {
771        self.encrypted = false;
772        self
773    }
774
775    /// Sets the identifier the client sends as its sender (49).
776    pub fn sender_comp_id(mut self, sender_comp_id: impl Into<String>) -> Self {
777        self.sender_comp_id = Some(sender_comp_id.into());
778        self
779    }
780
781    /// Sets the identifier of the server (56), replacing [`DEFAULT_FIX_TARGET_COMP_ID`].
782    pub fn target_comp_id(mut self, target_comp_id: impl Into<String>) -> Self {
783        self.target_comp_id = target_comp_id.into();
784        self
785    }
786
787    /// Sets the login of the trading account (553).
788    pub fn username(mut self, username: impl Into<String>) -> Self {
789        self.username = Some(username.into());
790        self
791    }
792
793    /// Sets the password of the sessions (554).
794    pub fn password(mut self, password: impl Into<String>) -> Self {
795        self.password = FixPassword::new(password).ok();
796        self
797    }
798
799    /// Sets the interval between heartbeats.
800    ///
801    /// The logon carries it as a whole number of seconds (108), so a fraction of a second is
802    /// dropped. [`ConfigurationFixBuilder::build`] refuses an interval below one second: zero
803    /// seconds would ask the server for a session without heartbeats, and this library always
804    /// keeps a session alive and watches the server by them. It also refuses an interval above
805    /// [`MAX_FIX_HEARTBEAT`].
806    pub const fn heartbeat(mut self, heartbeat: Duration) -> Self {
807        self.heartbeat = heartbeat;
808        self
809    }
810
811    /// Sets the time allowed for an answer of the server and for a write.
812    pub const fn timeout(mut self, timeout: Duration) -> Self {
813        self.timeout = timeout;
814        self
815    }
816
817    /// Sets the reconnect delay: the pause before the first attempt to open a lost session
818    /// again. The pause before the n-th attempt is n times as long.
819    ///
820    /// [`ConfigurationFixBuilder::build`] takes a delay above [`MAX_FIX_RECONNECT_DELAY`] as
821    /// that maximum.
822    pub const fn reconnect_delay(mut self, reconnect_delay: Duration) -> Self {
823        self.reconnect_delay = reconnect_delay;
824        self
825    }
826
827    /// Checks every value and returns the configuration.
828    ///
829    /// # Errors
830    ///
831    /// Returns a [`ConfigError`] when the host, the sender, the target, the login or the
832    /// password is absent or empty, the host is not a bare host name, a port is zero, the
833    /// heartbeat is shorter than one second or longer than [`MAX_FIX_HEARTBEAT`], or another
834    /// duration is zero. A reconnect delay above [`MAX_FIX_RECONNECT_DELAY`] is no error: it
835    /// is shortened to that maximum.
836    pub fn build(self) -> Result<ConfigurationFix, ConfigError> {
837        let (quote, trade) = if self.encrypted {
838            (DEFAULT_FIX_QUOTE_PORT, DEFAULT_FIX_TRADE_PORT)
839        } else {
840            (DEFAULT_FIX_QUOTE_PLAIN_PORT, DEFAULT_FIX_TRADE_PLAIN_PORT)
841        };
842        if self.heartbeat.as_secs() == 0 {
843            return Err(ConfigError::ZeroDuration(HEARTBEAT));
844        }
845        if self.heartbeat > MAX_FIX_HEARTBEAT {
846            return Err(ConfigError::TooLong {
847                option: HEARTBEAT,
848                limit: MAX_FIX_HEARTBEAT,
849            });
850        }
851        Ok(ConfigurationFix {
852            host: host_name(filled(self.host.unwrap_or_default(), FIX_HOST)?)?,
853            quote_port: nonzero_port(self.quote_port.unwrap_or(quote))?,
854            trade_port: nonzero_port(self.trade_port.unwrap_or(trade))?,
855            encrypted: self.encrypted,
856            sender_comp_id: filled(self.sender_comp_id.unwrap_or_default(), FIX_SENDER_COMP_ID)?,
857            target_comp_id: filled(self.target_comp_id, FIX_TARGET_COMP_ID)?,
858            username: filled(self.username.unwrap_or_default(), FIX_USERNAME)?,
859            password: self.password.ok_or(ConfigError::Missing(FIX_PASSWORD))?,
860            heartbeat: Duration::from_secs(self.heartbeat.as_secs()),
861            timeout: positive(self.timeout, TIMEOUT)?,
862            reconnect_delay: positive(self.reconnect_delay, RECONNECT_DELAY)?
863                .min(MAX_FIX_RECONNECT_DELAY),
864        })
865    }
866}
867
868#[cfg(test)]
869mod tests {
870    use std::collections::HashMap;
871    use std::time::Duration;
872
873    use super::{
874        AccessToken, ClientId, ClientSecret, ConfigurationOpenApi, ConfigurationOpenApiBuilder,
875        DEFAULT_BACKOFF, DEFAULT_PORT, DEFAULT_RECONNECT_DELAY, DEFAULT_RETRIES, DEFAULT_TIMEOUT,
876        DEFAULT_TOKEN_URL, DEMO_HOST, ENV_ACCESS_TOKEN, ENV_CLIENT_ID, ENV_CLIENT_SECRET,
877        ENV_DEMO_HOST, ENV_ENVIRONMENT, ENV_REFRESH_TOKEN, ENV_TOKEN_URL, Environment, LIVE_HOST,
878        RefreshToken,
879    };
880    use super::{
881        ConfigurationFix, ConfigurationFixBuilder, DEFAULT_FIX_HEARTBEAT,
882        DEFAULT_FIX_QUOTE_PLAIN_PORT, DEFAULT_FIX_QUOTE_PORT, DEFAULT_FIX_TARGET_COMP_ID,
883        DEFAULT_FIX_TRADE_PLAIN_PORT, DEFAULT_FIX_TRADE_PORT, ENV_FIX_HOST, ENV_FIX_PASSWORD,
884        ENV_FIX_QUOTE_PORT, ENV_FIX_SENDER_COMP_ID, ENV_FIX_TARGET_COMP_ID, ENV_FIX_TRADE_PORT,
885        ENV_FIX_USERNAME, MAX_FIX_HEARTBEAT, MAX_FIX_RECONNECT_DELAY,
886    };
887    use crate::common::errors::ConfigError;
888
889    fn filled(builder: ConfigurationOpenApiBuilder) -> ConfigurationOpenApiBuilder {
890        builder
891            .client_id("id")
892            .client_secret("secret")
893            .access_token("access")
894    }
895
896    fn lookup(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
897        let map: HashMap<String, String> = pairs
898            .iter()
899            .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
900            .collect();
901        move |key| map.get(key).cloned()
902    }
903
904    const REQUIRED: [(&str, &str); 3] = [
905        (ENV_CLIENT_ID, "id"),
906        (ENV_CLIENT_SECRET, "secret"),
907        (ENV_ACCESS_TOKEN, "access"),
908    ];
909
910    fn with(extra: &[(&'static str, &'static str)]) -> Vec<(&'static str, &'static str)> {
911        REQUIRED.iter().chain(extra).copied().collect()
912    }
913
914    #[test]
915    fn builder_defaults_to_demo() -> Result<(), ConfigError> {
916        let configuration = filled(ConfigurationOpenApi::builder()).build()?;
917        assert_eq!(configuration.environment(), Environment::Demo);
918        assert_eq!(configuration.host(), DEMO_HOST);
919        assert_eq!(configuration.host(), "demo.ctraderapi.com");
920        assert_eq!(configuration.port(), DEFAULT_PORT);
921        assert_eq!(configuration.port(), 5035);
922        assert_eq!(configuration.client_id().as_str(), "id");
923        assert_eq!(configuration.client_secret().expose(), "secret");
924        assert_eq!(configuration.access_token().expose(), "access");
925        assert_eq!(configuration.refresh_token(), None);
926        assert_eq!(configuration.token_url(), DEFAULT_TOKEN_URL);
927        assert_eq!(configuration.timeout(), DEFAULT_TIMEOUT);
928        assert_eq!(configuration.retries(), DEFAULT_RETRIES);
929        assert_eq!(configuration.backoff(), DEFAULT_BACKOFF);
930        assert_eq!(configuration.reconnect_delay(), DEFAULT_RECONNECT_DELAY);
931        Ok(())
932    }
933
934    #[test]
935    fn demo_constructor_equals_the_default_builder() -> Result<(), ConfigError> {
936        let demo = filled(ConfigurationOpenApi::demo()).build()?;
937        let default = filled(ConfigurationOpenApi::builder()).build()?;
938        assert_eq!(demo, default);
939        Ok(())
940    }
941
942    #[test]
943    fn live_constructor_targets_the_live_host() -> Result<(), ConfigError> {
944        let configuration = filled(ConfigurationOpenApi::live()).build()?;
945        assert_eq!(configuration.environment(), Environment::Live);
946        assert_eq!(configuration.host(), LIVE_HOST);
947        assert_eq!(configuration.host(), "live.ctraderapi.com");
948        assert_eq!(configuration.port(), 5035);
949        Ok(())
950    }
951
952    #[test]
953    fn overrides_replace_every_default() -> Result<(), ConfigError> {
954        let configuration = filled(ConfigurationOpenApi::builder())
955            .host("proxy.example.test")
956            .port(6000)
957            .refresh_token("refresh")
958            .token_url("https://auth.example.test/token")
959            .timeout(Duration::from_millis(250))
960            .retries(0)
961            .backoff(Duration::from_millis(40))
962            .reconnect_delay(Duration::from_secs(9))
963            .build()?;
964        assert_eq!(configuration.host(), "proxy.example.test");
965        assert_eq!(configuration.port(), 6000);
966        assert_eq!(
967            configuration.refresh_token().map(RefreshToken::expose),
968            Some("refresh")
969        );
970        assert_eq!(configuration.token_url(), "https://auth.example.test/token");
971        assert_eq!(configuration.timeout(), Duration::from_millis(250));
972        assert_eq!(configuration.retries(), 0);
973        assert_eq!(configuration.backoff(), Duration::from_millis(40));
974        assert_eq!(configuration.reconnect_delay(), Duration::from_secs(9));
975        Ok(())
976    }
977
978    #[test]
979    fn missing_credentials_are_rejected() {
980        let no_id = ConfigurationOpenApi::builder()
981            .client_secret("secret")
982            .access_token("access")
983            .build();
984        assert_eq!(no_id, Err(ConfigError::Missing("client_id")));
985        let no_secret = ConfigurationOpenApi::builder()
986            .client_id("id")
987            .access_token("access")
988            .build();
989        assert_eq!(no_secret, Err(ConfigError::Missing("client_secret")));
990        let no_token = ConfigurationOpenApi::builder()
991            .client_id("id")
992            .client_secret("secret")
993            .build();
994        assert_eq!(no_token, Err(ConfigError::Missing("access_token")));
995    }
996
997    #[test]
998    fn blank_credentials_are_rejected() {
999        let builder = || filled(ConfigurationOpenApi::builder());
1000        assert_eq!(
1001            builder().client_id(" ").build(),
1002            Err(ConfigError::Missing("client_id"))
1003        );
1004        assert_eq!(
1005            builder().client_secret("").build(),
1006            Err(ConfigError::Missing("client_secret"))
1007        );
1008        assert_eq!(
1009            builder().access_token("").build(),
1010            Err(ConfigError::Missing("access_token"))
1011        );
1012        assert_eq!(
1013            builder().refresh_token("").build(),
1014            Err(ConfigError::Missing("refresh_token"))
1015        );
1016    }
1017
1018    #[test]
1019    fn bad_hosts_and_ports_are_rejected() {
1020        let builder = || filled(ConfigurationOpenApi::builder());
1021        for host in ["", "host name", "https://host", "host:5035", "host/path"] {
1022            assert_eq!(
1023                builder().host(host).build(),
1024                Err(ConfigError::InvalidHost(host.to_owned()))
1025            );
1026        }
1027        assert_eq!(builder().port(0).build(), Err(ConfigError::InvalidPort));
1028    }
1029
1030    #[test]
1031    fn bad_token_urls_are_rejected() {
1032        let builder = || filled(ConfigurationOpenApi::builder());
1033        for url in [
1034            "",
1035            "http://auth.example.test/token",
1036            "https://",
1037            "https:///token",
1038            "https://a b",
1039        ] {
1040            assert_eq!(
1041                builder().token_url(url).build(),
1042                Err(ConfigError::InvalidTokenUrl(url.to_owned()))
1043            );
1044        }
1045    }
1046
1047    #[test]
1048    fn zero_durations_are_rejected() {
1049        let builder = || filled(ConfigurationOpenApi::builder());
1050        assert_eq!(
1051            builder().timeout(Duration::ZERO).build(),
1052            Err(ConfigError::ZeroDuration("timeout"))
1053        );
1054        assert_eq!(
1055            builder().backoff(Duration::ZERO).build(),
1056            Err(ConfigError::ZeroDuration("backoff"))
1057        );
1058        assert_eq!(
1059            builder().reconnect_delay(Duration::ZERO).build(),
1060            Err(ConfigError::ZeroDuration("reconnect_delay"))
1061        );
1062    }
1063
1064    #[test]
1065    fn secrets_are_redacted_in_debug_output() -> Result<(), ConfigError> {
1066        let configuration = filled(ConfigurationOpenApi::builder())
1067            .client_secret("s3cr3t-value")
1068            .access_token("acc3ss-value")
1069            .refresh_token("r3fr3sh-value")
1070            .build()?;
1071        let printed = format!("{configuration:?}");
1072        assert!(!printed.contains("s3cr3t-value"));
1073        assert!(!printed.contains("acc3ss-value"));
1074        assert!(!printed.contains("r3fr3sh-value"));
1075        assert!(printed.contains("ClientSecret(***)"));
1076        assert!(printed.contains("AccessToken(***)"));
1077        assert!(printed.contains("RefreshToken(***)"));
1078        assert_eq!(
1079            format!("{:?}", ClientSecret::new("x")?),
1080            "ClientSecret(***)"
1081        );
1082        assert_eq!(format!("{:?}", AccessToken::new("x")?), "AccessToken(***)");
1083        assert_eq!(format!("{:?}", ClientId::new("x")?), "ClientId(\"x\")");
1084        Ok(())
1085    }
1086
1087    #[test]
1088    fn environment_parses_and_prints() {
1089        assert_eq!("demo".parse(), Ok(Environment::Demo));
1090        assert_eq!("live".parse(), Ok(Environment::Live));
1091        assert_eq!(
1092            "paper".parse::<Environment>(),
1093            Err(ConfigError::InvalidEnvironment("paper".to_owned()))
1094        );
1095        assert_eq!(Environment::Demo.to_string(), "demo");
1096        assert_eq!(Environment::Live.to_string(), "live");
1097        assert_eq!(Environment::default(), Environment::Demo);
1098    }
1099
1100    #[test]
1101    fn lookup_with_required_values_gives_demo_defaults() -> Result<(), ConfigError> {
1102        let configuration = ConfigurationOpenApi::from_lookup(lookup(&REQUIRED))?;
1103        let expected = filled(ConfigurationOpenApi::builder()).build()?;
1104        assert_eq!(configuration, expected);
1105        Ok(())
1106    }
1107
1108    #[test]
1109    fn lookup_applies_optional_values() -> Result<(), ConfigError> {
1110        let configuration = ConfigurationOpenApi::from_lookup(lookup(&with(&[
1111            (ENV_REFRESH_TOKEN, "refresh"),
1112            (ENV_DEMO_HOST, "demo.example.test"),
1113            (ENV_TOKEN_URL, "https://auth.example.test/token"),
1114            (ENV_ENVIRONMENT, "demo"),
1115        ])))?;
1116        assert_eq!(configuration.environment(), Environment::Demo);
1117        assert_eq!(configuration.host(), "demo.example.test");
1118        assert_eq!(configuration.token_url(), "https://auth.example.test/token");
1119        assert_eq!(
1120            configuration.refresh_token().map(RefreshToken::expose),
1121            Some("refresh")
1122        );
1123        Ok(())
1124    }
1125
1126    #[test]
1127    fn lookup_ignores_the_demo_host_when_live() -> Result<(), ConfigError> {
1128        let configuration = ConfigurationOpenApi::from_lookup(lookup(&with(&[
1129            (ENV_DEMO_HOST, "demo.example.test"),
1130            (ENV_ENVIRONMENT, "live"),
1131        ])))?;
1132        assert_eq!(configuration.environment(), Environment::Live);
1133        assert_eq!(configuration.host(), LIVE_HOST);
1134        Ok(())
1135    }
1136
1137    #[test]
1138    fn lookup_treats_empty_values_as_absent() -> Result<(), ConfigError> {
1139        let configuration = ConfigurationOpenApi::from_lookup(lookup(&with(&[
1140            (ENV_REFRESH_TOKEN, ""),
1141            (ENV_DEMO_HOST, ""),
1142            (ENV_TOKEN_URL, ""),
1143            (ENV_ENVIRONMENT, ""),
1144        ])))?;
1145        let expected = filled(ConfigurationOpenApi::builder()).build()?;
1146        assert_eq!(configuration, expected);
1147        Ok(())
1148    }
1149
1150    #[test]
1151    fn lookup_names_the_missing_variable() {
1152        for missing in [ENV_CLIENT_ID, ENV_CLIENT_SECRET, ENV_ACCESS_TOKEN] {
1153            let pairs: Vec<_> = REQUIRED
1154                .iter()
1155                .filter(|(key, _)| *key != missing)
1156                .copied()
1157                .collect();
1158            assert_eq!(
1159                ConfigurationOpenApi::from_lookup(lookup(&pairs)),
1160                Err(ConfigError::Missing(missing))
1161            );
1162        }
1163    }
1164
1165    #[test]
1166    fn lookup_rejects_bad_values() {
1167        assert_eq!(
1168            ConfigurationOpenApi::from_lookup(lookup(&with(&[(ENV_ENVIRONMENT, "paper")]))),
1169            Err(ConfigError::InvalidEnvironment("paper".to_owned()))
1170        );
1171        assert_eq!(
1172            ConfigurationOpenApi::from_lookup(lookup(&with(&[(ENV_DEMO_HOST, "a b")]))),
1173            Err(ConfigError::InvalidHost("a b".to_owned()))
1174        );
1175        assert_eq!(
1176            ConfigurationOpenApi::from_lookup(lookup(&with(&[(ENV_TOKEN_URL, "ftp://x")]))),
1177            Err(ConfigError::InvalidTokenUrl("ftp://x".to_owned()))
1178        );
1179    }
1180
1181    #[test]
1182    fn process_environment_is_read_through_the_same_lookup() {
1183        let direct = ConfigurationOpenApi::from_lookup(|key| std::env::var(key).ok());
1184        assert_eq!(ConfigurationOpenApi::from_env(), direct);
1185    }
1186
1187    #[test]
1188    fn errors_describe_the_rejected_value() {
1189        assert_eq!(
1190            ConfigError::Missing("client_id").to_string(),
1191            "client_id is not set"
1192        );
1193        assert_eq!(
1194            ConfigError::InvalidEnvironment("paper".to_owned()).to_string(),
1195            "environment must be demo or live, got paper"
1196        );
1197        assert_eq!(
1198            ConfigError::InvalidHost("a b".to_owned()).to_string(),
1199            "host is not a bare host name: a b"
1200        );
1201        assert_eq!(
1202            ConfigError::InvalidPort.to_string(),
1203            "port must not be zero"
1204        );
1205        assert_eq!(
1206            ConfigError::InvalidTokenUrl("x".to_owned()).to_string(),
1207            "token URL must be an https URL: x"
1208        );
1209        assert_eq!(
1210            ConfigError::ZeroDuration("timeout").to_string(),
1211            "timeout must be longer than zero"
1212        );
1213        assert_eq!(
1214            ConfigError::TooLong {
1215                option: "heartbeat",
1216                limit: MAX_FIX_HEARTBEAT,
1217            }
1218            .to_string(),
1219            "heartbeat must not be longer than 3600 s"
1220        );
1221    }
1222
1223    fn fix() -> ConfigurationFixBuilder {
1224        ConfigurationFix::builder()
1225            .host("fix.example.com")
1226            .sender_comp_id("demo.broker.4242")
1227            .username("4242")
1228            .password("open-sesame")
1229    }
1230
1231    const FIX_REQUIRED: [(&str, &str); 4] = [
1232        (ENV_FIX_HOST, "fix.example.com"),
1233        (ENV_FIX_SENDER_COMP_ID, "demo.broker.4242"),
1234        (ENV_FIX_USERNAME, "4242"),
1235        (ENV_FIX_PASSWORD, "open-sesame"),
1236    ];
1237
1238    fn fix_with(extra: &[(&'static str, &'static str)]) -> Vec<(&'static str, &'static str)> {
1239        FIX_REQUIRED.iter().chain(extra).copied().collect()
1240    }
1241
1242    #[test]
1243    fn fix_builder_defaults_to_tls_and_the_documented_ports() -> Result<(), ConfigError> {
1244        let configuration = fix().build()?;
1245        assert_eq!(configuration.host(), "fix.example.com");
1246        assert!(configuration.encrypted());
1247        assert_eq!(configuration.quote_port(), DEFAULT_FIX_QUOTE_PORT);
1248        assert_eq!(configuration.trade_port(), DEFAULT_FIX_TRADE_PORT);
1249        assert_eq!(configuration.sender_comp_id(), "demo.broker.4242");
1250        assert_eq!(configuration.target_comp_id(), DEFAULT_FIX_TARGET_COMP_ID);
1251        assert_eq!(configuration.username(), "4242");
1252        assert_eq!(configuration.password().expose(), "open-sesame");
1253        assert_eq!(configuration.heartbeat(), DEFAULT_FIX_HEARTBEAT);
1254        assert_eq!(configuration.timeout(), DEFAULT_TIMEOUT);
1255        assert_eq!(configuration.reconnect_delay(), DEFAULT_RECONNECT_DELAY);
1256        Ok(())
1257    }
1258
1259    #[test]
1260    fn fix_sessions_run_unencrypted_only_on_request() -> Result<(), ConfigError> {
1261        let plain = fix().unencrypted().build()?;
1262        assert!(!plain.encrypted());
1263        assert_eq!(plain.quote_port(), DEFAULT_FIX_QUOTE_PLAIN_PORT);
1264        assert_eq!(plain.trade_port(), DEFAULT_FIX_TRADE_PLAIN_PORT);
1265        let chosen = fix().unencrypted().quote_port(1).trade_port(2).build()?;
1266        assert_eq!((chosen.quote_port(), chosen.trade_port()), (1, 2));
1267        Ok(())
1268    }
1269
1270    #[test]
1271    fn fix_builder_takes_every_setting() -> Result<(), ConfigError> {
1272        let configuration = fix()
1273            .target_comp_id("cServer")
1274            .heartbeat(Duration::from_millis(5_900))
1275            .timeout(Duration::from_secs(3))
1276            .reconnect_delay(Duration::from_secs(4))
1277            .build()?;
1278        assert_eq!(configuration.target_comp_id(), "cServer");
1279        assert_eq!(configuration.heartbeat(), Duration::from_secs(5));
1280        assert_eq!(configuration.timeout(), Duration::from_secs(3));
1281        assert_eq!(configuration.reconnect_delay(), Duration::from_secs(4));
1282        let slowest = fix().heartbeat(MAX_FIX_HEARTBEAT).build()?;
1283        assert_eq!(slowest.heartbeat(), MAX_FIX_HEARTBEAT);
1284        Ok(())
1285    }
1286
1287    #[test]
1288    fn fix_reconnect_delay_is_bounded_at_one_hour() {
1289        assert_eq!(MAX_FIX_RECONNECT_DELAY, Duration::from_secs(3_600));
1290    }
1291
1292    #[test]
1293    fn fix_builder_shortens_a_reconnect_delay_above_the_maximum() -> Result<(), ConfigError> {
1294        let longest = fix().reconnect_delay(MAX_FIX_RECONNECT_DELAY).build()?;
1295        assert_eq!(longest.reconnect_delay(), MAX_FIX_RECONNECT_DELAY);
1296        let above = MAX_FIX_RECONNECT_DELAY + Duration::from_nanos(1);
1297        for delay in [above, Duration::MAX] {
1298            let configuration = fix().reconnect_delay(delay).build()?;
1299            assert_eq!(configuration.reconnect_delay(), MAX_FIX_RECONNECT_DELAY);
1300        }
1301        let below = MAX_FIX_RECONNECT_DELAY - Duration::from_nanos(1);
1302        assert_eq!(
1303            fix().reconnect_delay(below).build()?.reconnect_delay(),
1304            below
1305        );
1306        Ok(())
1307    }
1308
1309    #[test]
1310    fn fix_builder_rejects_absent_and_invalid_values() {
1311        let cases = [
1312            (
1313                ConfigurationFix::builder().build(),
1314                ConfigError::Missing("host"),
1315            ),
1316            (
1317                fix().host("a host").build(),
1318                ConfigError::InvalidHost("a host".to_owned()),
1319            ),
1320            (
1321                fix().sender_comp_id(" ").build(),
1322                ConfigError::Missing("sender_comp_id"),
1323            ),
1324            (
1325                fix().target_comp_id("").build(),
1326                ConfigError::Missing("target_comp_id"),
1327            ),
1328            (fix().username("").build(), ConfigError::Missing("username")),
1329            (
1330                fix().password("").build(),
1331                ConfigError::Missing("fix_password"),
1332            ),
1333            (fix().quote_port(0).build(), ConfigError::InvalidPort),
1334            (fix().trade_port(0).build(), ConfigError::InvalidPort),
1335            (
1336                fix().heartbeat(Duration::from_millis(999)).build(),
1337                ConfigError::ZeroDuration("heartbeat"),
1338            ),
1339            (
1340                fix()
1341                    .heartbeat(MAX_FIX_HEARTBEAT + Duration::from_secs(1))
1342                    .build(),
1343                ConfigError::TooLong {
1344                    option: "heartbeat",
1345                    limit: MAX_FIX_HEARTBEAT,
1346                },
1347            ),
1348            (
1349                fix().heartbeat(Duration::MAX).build(),
1350                ConfigError::TooLong {
1351                    option: "heartbeat",
1352                    limit: MAX_FIX_HEARTBEAT,
1353                },
1354            ),
1355            (
1356                fix().timeout(Duration::ZERO).build(),
1357                ConfigError::ZeroDuration("timeout"),
1358            ),
1359            (
1360                fix().reconnect_delay(Duration::ZERO).build(),
1361                ConfigError::ZeroDuration("reconnect_delay"),
1362            ),
1363        ];
1364        for (built, expected) in cases {
1365            assert_eq!(built, Err(expected));
1366        }
1367    }
1368
1369    #[test]
1370    fn fix_configuration_is_read_from_variables() -> Result<(), ConfigError> {
1371        let plain = ConfigurationFix::from_lookup(lookup(&FIX_REQUIRED))?;
1372        assert_eq!(plain, fix().build()?);
1373        let full = ConfigurationFix::from_lookup(lookup(&fix_with(&[
1374            (ENV_FIX_QUOTE_PORT, " 6001 "),
1375            (ENV_FIX_TRADE_PORT, "6002"),
1376            (ENV_FIX_TARGET_COMP_ID, "cServer"),
1377        ])))?;
1378        assert_eq!((full.quote_port(), full.trade_port()), (6001, 6002));
1379        assert_eq!(full.target_comp_id(), "cServer");
1380        let blank = ConfigurationFix::from_lookup(lookup(&fix_with(&[
1381            (ENV_FIX_QUOTE_PORT, " "),
1382            (ENV_FIX_TARGET_COMP_ID, ""),
1383        ])))?;
1384        assert_eq!(blank, plain);
1385        Ok(())
1386    }
1387
1388    #[test]
1389    fn fix_variables_that_are_absent_or_invalid_are_rejected() {
1390        for (index, (key, _)) in FIX_REQUIRED.iter().enumerate() {
1391            let rest: Vec<_> = FIX_REQUIRED
1392                .iter()
1393                .enumerate()
1394                .filter(|(other, _)| *other != index)
1395                .map(|(_, pair)| *pair)
1396                .collect();
1397            assert_eq!(
1398                ConfigurationFix::from_lookup(lookup(&rest)),
1399                Err(ConfigError::Missing(key))
1400            );
1401        }
1402        for (key, value) in [
1403            (ENV_FIX_QUOTE_PORT, "0"),
1404            (ENV_FIX_QUOTE_PORT, "70000"),
1405            (ENV_FIX_TRADE_PORT, "port"),
1406        ] {
1407            assert_eq!(
1408                ConfigurationFix::from_lookup(lookup(&fix_with(&[(key, value)]))),
1409                Err(ConfigError::InvalidPort)
1410            );
1411        }
1412    }
1413
1414    #[test]
1415    fn fix_password_never_appears_in_debug_output() -> Result<(), ConfigError> {
1416        let shown = format!("{:?} {:?}", fix(), fix().build()?);
1417        assert!(!shown.contains("open-sesame"), "{shown}");
1418        assert!(shown.contains("FixPassword(***)"), "{shown}");
1419        Ok(())
1420    }
1421}