Skip to main content

useceleris_client/
client.rs

1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::channel::Channel;
6use crate::connection::{Dialer, web_socket_dialer};
7use crate::connection_url::validate_base_url;
8use crate::constants::{
9    DEFAULT_BASE_URL, DEFAULT_CONNECT_TIMEOUT, DEFAULT_DEDUPLICATION_WINDOW_SIZE,
10    DEFAULT_MAXIMUM_RECONNECT_ATTEMPTS, DEFAULT_PRESENCE_QUERY_TIMEOUT, MAXIMUM_PENDING_COMMANDS,
11    MAXIMUM_RECONNECT_ATTEMPTS_CEILING, MAXIMUM_TIMEOUT, MINIMUM_TIMEOUT,
12};
13use crate::credentials::CredentialProvider;
14use crate::errors::{CelerisError, configuration_error, failure};
15use crate::identifiers::channel_reference_rule;
16use crate::random::random_fraction;
17
18/// Configures a [`Client`]. Only the credential provider is required; `None`
19/// keeps an option's default (CONFIG-01).
20///
21/// ```
22/// use std::time::Duration;
23/// use useceleris_client::{ClientOptions, CredentialProvider, Credentials};
24///
25/// # let provider = CredentialProvider::new(|_| async { Ok(Credentials { payload: "p".into(), signature: "s".into() }) });
26/// let options = ClientOptions {
27///     connect_timeout: Some(Duration::from_secs(5)),
28///     ..ClientOptions::new(provider)
29/// };
30/// ```
31#[derive(Clone, Debug)]
32pub struct ClientOptions {
33    /// Fetches fresh credentials for every connection attempt.
34    pub credential_provider: CredentialProvider,
35
36    /// Defaults to the production endpoint. Set it only for local, CI or
37    /// self-hosted targets.
38    pub base_url: Option<String>,
39
40    /// Permits a `ws://` base URL for a loopback host.
41    pub allow_insecure_loopback: bool,
42
43    /// Covers credential acquisition and the handshake together: 1 ms to 15
44    /// minutes, 15 seconds by default.
45    pub connect_timeout: Option<Duration>,
46
47    /// The same deadline for each reconnect attempt: 1 ms to 15 minutes, the
48    /// connect timeout by default.
49    pub reconnect_timeout: Option<Duration>,
50
51    /// Bounds each presence query: 1 ms to 15 minutes, 10 seconds by default.
52    pub presence_query_timeout: Option<Duration>,
53
54    /// Caps the publishes that wait for room in the writer: at least 1, 64 by
55    /// default.
56    pub publish_queue_size: Option<usize>,
57
58    /// How many delivered message ids each channel remembers, to drop replayed
59    /// duplicates: at least 1, 1024 by default.
60    pub deduplication_window_size: Option<usize>,
61
62    /// How many failed reconnect attempts, in one retry budget, end recovery in
63    /// [`ChannelState::Failed`](crate::ChannelState::Failed): 1 to 100, 10 by
64    /// default.
65    pub maximum_reconnect_attempts: Option<u32>,
66} // end struct ClientOptions
67
68impl ClientOptions {
69    /// Options with every default and the given provider.
70    pub fn new(credential_provider: CredentialProvider) -> ClientOptions {
71        ClientOptions {
72            credential_provider,
73            base_url: None,
74            allow_insecure_loopback: false,
75            connect_timeout: None,
76            reconnect_timeout: None,
77            presence_query_timeout: None,
78            publish_queue_size: None,
79            deduplication_window_size: None,
80            maximum_reconnect_attempts: None,
81        }
82    } // end fn new
83} // end impl ClientOptions
84
85/// Creates channels. It holds configuration only and does no network work.
86/// It is cheap to clone.
87#[derive(Clone)]
88pub struct Client {
89    pub(crate) configuration: Arc<ClientConfiguration>,
90} // end struct Client
91
92impl fmt::Debug for Client {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        formatter
95            .debug_struct("Client")
96            .field("base_url", &self.configuration.base_url)
97            .finish_non_exhaustive()
98    } // end method fmt
99} // end impl Debug for Client
100
101/// A client's validated options, with every default applied.
102#[derive(Clone)]
103pub(crate) struct ClientConfiguration {
104    pub(crate) credential_provider: CredentialProvider,
105    pub(crate) base_url: String,
106    pub(crate) connect_timeout: Duration,
107    pub(crate) reconnect_timeout: Duration,
108    pub(crate) presence_query_timeout: Duration,
109    pub(crate) publish_queue_size: usize,
110    pub(crate) deduplication_window_size: usize,
111    pub(crate) maximum_reconnect_attempts: u32,
112
113    /// The seams: tests substitute an in-memory peer and fix the jitter.
114    pub(crate) dial: Dialer,
115    pub(crate) random: Arc<dyn Fn() -> f64 + Send + Sync>,
116} // end struct ClientConfiguration
117
118impl Client {
119    /// Validates `options` and returns a client. It fails with
120    /// [`CelerisError::Configuration`], which names every field that failed
121    /// and its rule: a timeout outside 1 ms to 15 minutes, a size of zero, a
122    /// maximum reconnect attempts outside 1 to 100, or a base URL that is not
123    /// `wss://`, or `ws://` for a loopback host when allowed.
124    pub fn new(options: ClientOptions) -> Result<Client, CelerisError> {
125        const TIMEOUT_RULE: &str = "Must be from 1 ms to 15 minutes";
126        const SIZE_RULE: &str = "Must be at least 1";
127
128        let mut failures = Vec::new();
129
130        let timeouts = [
131            ("connect_timeout", options.connect_timeout),
132            ("reconnect_timeout", options.reconnect_timeout),
133            ("presence_query_timeout", options.presence_query_timeout),
134        ];
135
136        for (field, timeout) in timeouts {
137            if timeout
138                .is_some_and(|timeout| !(MINIMUM_TIMEOUT..=MAXIMUM_TIMEOUT).contains(&timeout))
139            {
140                failures.push(failure(field, TIMEOUT_RULE));
141            }
142        }
143
144        let sizes = [
145            ("publish_queue_size", options.publish_queue_size),
146            (
147                "deduplication_window_size",
148                options.deduplication_window_size,
149            ),
150        ];
151
152        for (field, size) in sizes {
153            if size == Some(0) {
154                failures.push(failure(field, SIZE_RULE));
155            }
156        }
157
158        let attempts_valid =
159            |attempts| (1..=MAXIMUM_RECONNECT_ATTEMPTS_CEILING).contains(&attempts);
160
161        if options
162            .maximum_reconnect_attempts
163            .is_some_and(|attempts| !attempts_valid(attempts))
164        {
165            failures.push(failure(
166                "maximum_reconnect_attempts",
167                "Must be from 1 to 100",
168            ));
169        }
170
171        if !failures.is_empty() {
172            return Err(configuration_error("client options", &failures));
173        }
174
175        let base_url = validate_base_url(
176            options.base_url.as_deref().unwrap_or(DEFAULT_BASE_URL),
177            options.allow_insecure_loopback,
178        )?;
179
180        let connect_timeout = options.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT);
181
182        let configuration = ClientConfiguration {
183            credential_provider: options.credential_provider,
184            base_url,
185            connect_timeout,
186            reconnect_timeout: options.reconnect_timeout.unwrap_or(connect_timeout),
187            presence_query_timeout: options
188                .presence_query_timeout
189                .unwrap_or(DEFAULT_PRESENCE_QUERY_TIMEOUT),
190            publish_queue_size: options
191                .publish_queue_size
192                .unwrap_or(MAXIMUM_PENDING_COMMANDS),
193            deduplication_window_size: options
194                .deduplication_window_size
195                .unwrap_or(DEFAULT_DEDUPLICATION_WINDOW_SIZE),
196            maximum_reconnect_attempts: options
197                .maximum_reconnect_attempts
198                .unwrap_or(DEFAULT_MAXIMUM_RECONNECT_ATTEMPTS),
199            dial: web_socket_dialer(),
200            random: Arc::new(random_fraction),
201        };
202
203        Ok(Client {
204            configuration: Arc::new(configuration),
205        })
206    } // end fn new
207
208    /// A handle for the channel with the given reference. It does no network
209    /// work; each call returns a new channel with its own connection. It fails
210    /// with [`CelerisError::Configuration`] unless the reference is 1 to 255
211    /// ASCII letters, digits, hyphens or underscores.
212    pub fn channel(&self, reference: &str) -> Result<Channel, CelerisError> {
213        if let Some(rule) = channel_reference_rule(reference) {
214            return Err(configuration_error(
215                "channel reference",
216                &[failure("", rule)],
217            ));
218        }
219
220        Ok(Channel::new(Arc::clone(&self.configuration), reference))
221    } // end method channel
222} // end impl Client