Skip to main content

autoconnect_settings/
lib.rs

1mod app_state;
2
3extern crate slog;
4#[macro_use]
5extern crate slog_scope;
6extern crate serde_derive;
7
8// Specify "unused_imports" to satisfy clippy.
9#[allow(unused_imports)]
10use std::env;
11use std::{io, net::ToSocketAddrs, time::Duration};
12
13use config::{Config, ConfigError, Environment, File};
14use fernet::Fernet;
15use lazy_static::lazy_static;
16use serde::{Deserialize, Deserializer};
17
18use autopush_common::util::deserialize_u32_to_duration;
19// Specify "unused_imports" to satisfy clippy.
20#[allow(unused_imports)]
21use serde_json::json;
22
23pub use app_state::AppState;
24
25pub const ENV_PREFIX: &str = "autoconnect";
26
27lazy_static! {
28    static ref HOSTNAME: String = mozsvc_common::get_hostname()
29        .expect("Couldn't get_hostname")
30        .into_string()
31        .expect("Couldn't convert get_hostname");
32    static ref RESOLVED_HOSTNAME: String = resolve_ip(&HOSTNAME)
33        .unwrap_or_else(|_| panic!("Failed to resolve hostname: {}", *HOSTNAME));
34}
35
36/// Resolve a hostname to its IP if possible
37fn resolve_ip(hostname: &str) -> io::Result<String> {
38    Ok((hostname, 0)
39        .to_socket_addrs()?
40        .next()
41        .map_or_else(|| hostname.to_owned(), |addr| addr.ip().to_string()))
42}
43
44/// Indicate whether the port should be included for the given scheme
45fn include_port(scheme: &str, port: u16) -> bool {
46    !((scheme == "http" && port == 80) || (scheme == "https" && port == 443))
47}
48
49/// The Applications settings, read from CLI, Environment or settings file, for the
50/// autoconnect application. These are later converted to
51/// [autoconnect::autoconnect-settings::AppState].
52#[derive(Clone, Debug, Deserialize)]
53#[serde(default)]
54pub struct Settings {
55    /// The application port to listen on
56    pub port: u16,
57    /// The DNS specified name of the application host to used for internal routing
58    pub hostname: Option<String>,
59    /// The override hostname to use for internal routing (NOTE: requires `hostname` to be set)
60    pub resolve_hostname: bool,
61    /// The internal webpush routing port
62    pub router_port: u16,
63    /// The DNS name to use for internal routing
64    pub router_hostname: Option<String>,
65    /// The server based ping interval (also used for Broadcast sends)
66    #[serde(deserialize_with = "deserialize_f64_to_duration")]
67    pub auto_ping_interval: Duration,
68    /// How long to wait for a response Pong before being timed out and connection drop
69    #[serde(deserialize_with = "deserialize_f64_to_duration")]
70    pub auto_ping_timeout: Duration,
71    /// How long to wait for the initial connection handshake.
72    #[serde(deserialize_with = "deserialize_u32_to_duration")]
73    pub open_handshake_timeout: Duration,
74    /// The URL scheme (http/https) for the endpoint URL
75    pub endpoint_scheme: String,
76    /// The host url for the endpoint URL (differs from `hostname` and `resolve_hostname`)
77    pub endpoint_hostname: String,
78    /// The optional port override for the endpoint URL
79    pub endpoint_port: u16,
80    /// The seed key to use for endpoint encryption
81    pub crypto_key: String,
82    /// The host name to send recorded metrics
83    pub statsd_host: Option<String>,
84    /// The port number to send recorded metrics
85    pub statsd_port: u16,
86    /// The root label to apply to metrics.
87    pub statsd_label: String,
88    /// Whether to disable Sentry error reporting
89    pub disable_sentry: bool,
90    /// The DSN to connect to the storage engine (Used to select between storage systems)
91    pub db_dsn: Option<String>,
92    /// JSON set of specific database settings (See data storage engines)
93    pub db_settings: String,
94    /// Server endpoint to pull Broadcast ID change values (Sent in Pings)
95    pub megaphone_api_url: Option<String>,
96    /// Broadcast token for authentication (deprecated, no longer used)
97    pub megaphone_api_token: Option<String>,
98    /// How often to poll the server for new data
99    #[serde(deserialize_with = "deserialize_u32_to_duration")]
100    pub megaphone_poll_interval: Duration,
101    /// Use human readable (simplified, non-JSON)
102    pub human_logs: bool,
103    /// Number of log records to buffer before dropping them. Records are dropped
104    /// when the buffer is full, and each drop emits an ERROR level overflow
105    /// report, so this should comfortably exceed the peak logging rate. 0 uses
106    /// the default.
107    pub log_chan_size: usize,
108    /// Maximum allowed number of backlogged messages. Exceeding this number will
109    /// trigger a user reset because the user may have been offline way too long.
110    pub msg_limit: u32,
111    /// Maximum number of buffered notifications per client before backpressure
112    /// is applied on the notification channel.
113    pub client_channel_capacity: usize,
114    /// Sets the maximum number of concurrent connections per actix-web worker.
115    ///
116    /// All socket listeners will stop accepting connections when this limit is
117    /// reached for each worker.
118    pub actix_max_connections: Option<usize>,
119    /// Sets number of actix-web workers to start (per bind address).
120    ///
121    /// By default, the number of available physical CPUs is used as the worker count.
122    pub actix_workers: Option<usize>,
123    /// Maximum idle connections per host in the HTTP connection pool.
124    pub pool_max_idle_per_host: usize,
125    /// Idle connection timeout in seconds.
126    pub pool_idle_timeout_secs: u64,
127    #[cfg(feature = "reliable_report")]
128    /// The DNS for the reliability data store. This is normally a Redis compatible
129    /// storage system. See [Connection Parameters](https://docs.rs/redis/latest/redis/#connection-parameters)
130    /// for details.
131    pub reliability_dsn: Option<String>,
132    #[cfg(feature = "reliable_report")]
133    /// Max number of retries for retries for Redis transactions
134    pub reliability_retry_count: usize,
135}
136// Did you update the documentation in `docs/src/config_options.md`?
137
138impl Default for Settings {
139    fn default() -> Self {
140        Self {
141            port: 8080,
142            hostname: None,
143            resolve_hostname: false,
144            router_port: 8081,
145            router_hostname: None,
146            auto_ping_interval: Duration::from_secs(300),
147            auto_ping_timeout: Duration::from_secs(4),
148            open_handshake_timeout: Duration::from_secs(5),
149            endpoint_scheme: "http".to_owned(),
150            endpoint_hostname: "localhost".to_owned(),
151            endpoint_port: 8082,
152            crypto_key: format!("[{}]", Fernet::generate_key()),
153            statsd_host: Some("localhost".to_owned()),
154            // Matches the legacy value
155            statsd_label: "autoconnect".to_owned(),
156            statsd_port: 8125,
157            disable_sentry: false,
158            db_dsn: None,
159            db_settings: "".to_owned(),
160            megaphone_api_url: None,
161            megaphone_api_token: None,
162            megaphone_poll_interval: Duration::from_secs(30),
163            human_logs: false,
164            log_chan_size: autopush_common::logging::DEFAULT_LOG_CHAN_SIZE,
165            msg_limit: 150,
166            client_channel_capacity: 128,
167            actix_max_connections: None,
168            actix_workers: None,
169            pool_max_idle_per_host: 10,
170            pool_idle_timeout_secs: 30,
171            #[cfg(feature = "reliable_report")]
172            reliability_dsn: None,
173            #[cfg(feature = "reliable_report")]
174            reliability_retry_count: autopush_common::redis_util::MAX_TRANSACTION_LOOP,
175        }
176    }
177}
178
179impl Settings {
180    /// Load the settings from the config files in order first then the environment.
181    pub fn with_env_and_config_files(filenames: &[String]) -> Result<Self, ConfigError> {
182        let mut s = Config::builder();
183
184        // Merge the configs from the files
185        for filename in filenames {
186            s = s.add_source(File::with_name(filename));
187        }
188
189        // Merge the environment overrides
190        s = s.add_source(Environment::with_prefix(&ENV_PREFIX.to_uppercase()).separator("__"));
191
192        let built = s.build()?;
193        let s = built.try_deserialize::<Settings>()?;
194        s.validate()?;
195        Ok(s)
196    }
197
198    pub fn router_url(&self) -> String {
199        let router_scheme = "http";
200        let url = format!(
201            "{}://{}",
202            router_scheme,
203            self.router_hostname
204                .as_ref()
205                .map_or_else(|| self.get_hostname(), String::clone),
206        );
207        if include_port(router_scheme, self.router_port) {
208            format!("{}:{}", url, self.router_port)
209        } else {
210            url
211        }
212    }
213
214    pub fn endpoint_url(&self) -> String {
215        let url = format!("{}://{}", self.endpoint_scheme, self.endpoint_hostname,);
216        if include_port(&self.endpoint_scheme, self.endpoint_port) {
217            format!("{}:{}", url, self.endpoint_port)
218        } else {
219            url
220        }
221    }
222
223    fn get_hostname(&self) -> String {
224        if let Some(ref hostname) = self.hostname {
225            if self.resolve_hostname {
226                resolve_ip(hostname)
227                    .unwrap_or_else(|_| panic!("Failed to resolve provided hostname: {hostname}"))
228            } else {
229                hostname.clone()
230            }
231        } else if self.resolve_hostname {
232            RESOLVED_HOSTNAME.clone()
233        } else {
234            HOSTNAME.clone()
235        }
236    }
237
238    pub fn validate(&self) -> Result<(), ConfigError> {
239        let non_zero = |val: Duration, name| {
240            if val.is_zero() {
241                return Err(ConfigError::Message(format!(
242                    "Invalid {ENV_PREFIX}_{name}: cannot be 0"
243                )));
244            }
245            Ok(())
246        };
247        non_zero(self.megaphone_poll_interval, "MEGAPHONE_POLL_INTERVAL")?;
248        non_zero(self.auto_ping_interval, "AUTO_PING_INTERVAL")?;
249        non_zero(self.auto_ping_timeout, "AUTO_PING_TIMEOUT")?;
250        Ok(())
251    }
252
253    pub fn test_settings() -> Self {
254        // Provide test settings based on enabled features.
255        // semi-hack to satisfy clippy --all --all-features
256        if cfg!(feature = "bigtable") {
257            let host = env::var("BIGTABLE_EMULATOR_HOST").unwrap_or("localhost:8086".to_owned());
258            let db_dsn = Some(format!("grpc://{}", host));
259            // BigTable DB_SETTINGS.
260            let db_settings = json!({
261                "table_name":"projects/test/instances/test/tables/autopush",
262                "message_family":"message",
263                "router_family":"router",
264                "message_topic_family":"message_topic",
265            })
266            .to_string();
267            return Self {
268                db_dsn,
269                db_settings,
270                ..Default::default()
271            };
272        }
273        if cfg!(feature = "redis") {
274            let host = env::var("REDIS_HOST").unwrap_or("localhost:6379".to_owned());
275            let db_dsn = Some(format!("redis://{}", host));
276            let db_settings = "".to_string();
277            return Self {
278                db_dsn,
279                db_settings,
280                ..Default::default()
281            };
282        }
283        if cfg!(feature = "postgres") {
284            let host = env::var("POSTGRES_HOST").unwrap_or("localhost:5432".to_owned());
285            let db_dsn = Some(format!("postgres://{}", host));
286            let db_settings = "".to_string();
287            return Self {
288                db_dsn,
289                db_settings,
290                ..Default::default()
291            };
292        }
293        Self::default()
294    }
295}
296
297fn deserialize_f64_to_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
298where
299    D: Deserializer<'de>,
300{
301    let seconds: f64 = Deserialize::deserialize(deserializer)?;
302    Ok(Duration::new(
303        seconds as u64,
304        (seconds.fract() * 1_000_000_000.0) as u32,
305    ))
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    #[cfg(feature = "unsafe")]
312    use slog_scope::trace;
313
314    #[test]
315    fn test_router_url() {
316        let mut settings = Settings {
317            router_hostname: Some("testname".to_string()),
318            router_port: 80,
319            ..Default::default()
320        };
321        let url = settings.router_url();
322        assert_eq!("http://testname", url);
323
324        settings.router_port = 8080;
325        let url = settings.router_url();
326        assert_eq!("http://testname:8080", url);
327    }
328
329    #[test]
330    fn test_endpoint_url() {
331        let mut settings = Settings {
332            endpoint_hostname: "testname".to_string(),
333            endpoint_port: 80,
334            endpoint_scheme: "http".to_string(),
335            ..Default::default()
336        };
337        let url = settings.endpoint_url();
338        assert_eq!("http://testname", url);
339
340        settings.endpoint_port = 8080;
341        let url = settings.endpoint_url();
342        assert_eq!("http://testname:8080", url);
343
344        settings.endpoint_port = 443;
345        settings.endpoint_scheme = "https".to_string();
346        let url = settings.endpoint_url();
347        assert_eq!("https://testname", url);
348
349        settings.endpoint_port = 8080;
350        let url = settings.endpoint_url();
351        assert_eq!("https://testname:8080", url);
352    }
353
354    // The following test is commented out due to the recent change in rust that makes `env::set_var` unsafe
355    #[cfg(all(test, feature = "unsafe"))]
356    #[test]
357    fn test_default_settings() {
358        // Test that the Config works the way we expect it to.
359        use std::env;
360        let port = format!("{ENV_PREFIX}__PORT").to_uppercase();
361        let msg_limit = format!("{ENV_PREFIX}__MSG_LIMIT").to_uppercase();
362        let fernet = format!("{ENV_PREFIX}__CRYPTO_KEY").to_uppercase();
363
364        let v1 = env::var(&port);
365        let v2 = env::var(&msg_limit);
366        unsafe {
367            env::set_var(&port, "9123");
368            env::set_var(&msg_limit, "123");
369            env::set_var(&fernet, "[mqCGb8D-N7mqx6iWJov9wm70Us6kA9veeXdb8QUuzLQ=]");
370        }
371        let settings = Settings::with_env_and_config_files(&Vec::new()).unwrap();
372        assert_eq!(settings.endpoint_hostname, "localhost".to_owned());
373        assert_eq!(&settings.port, &9123);
374        assert_eq!(&settings.msg_limit, &123);
375        assert_eq!(
376            &settings.crypto_key,
377            "[mqCGb8D-N7mqx6iWJov9wm70Us6kA9veeXdb8QUuzLQ=]"
378        );
379        assert_eq!(settings.open_handshake_timeout, Duration::from_secs(5));
380
381        // reset (just in case)
382        if let Ok(p) = v1 {
383            trace!("Resetting {}", &port);
384            // TODO: Audit that the environment access only happens in single-threaded code.
385            unsafe { env::set_var(&port, p) };
386        } else {
387            // TODO: Audit that the environment access only happens in single-threaded code.
388            unsafe { env::remove_var(&port) };
389        }
390        if let Ok(p) = v2 {
391            trace!("Resetting {}", msg_limit);
392            // TODO: Audit that the environment access only happens in single-threaded code.
393            unsafe { env::set_var(&msg_limit, p) };
394        } else {
395            // TODO: Audit that the environment access only happens in single-threaded code.
396            unsafe { env::remove_var(&msg_limit) };
397        }
398        // TODO: Audit that the environment access only happens in single-threaded code.
399        unsafe { env::remove_var(&fernet) };
400    }
401}