configs/
config.rs

1use crate::tests_game_config::generate_game_config_for_tests;
2use anyhow::Context;
3use serde::{Deserialize, Serialize};
4use std::{cmp::Ordering, fmt, num::NonZeroU32, str::FromStr, sync::Arc};
5
6#[derive(
7    Debug, Clone, PartialEq, Eq, Deserialize, strum_macros::Display, strum_macros::EnumString,
8)]
9#[serde(rename_all = "lowercase")]
10#[strum(serialize_all = "lowercase")]
11pub enum Environment {
12    Test,
13    Dev,
14    Prestable,
15    Prod,
16}
17
18#[derive(Serialize, Deserialize, Debug, Clone)]
19pub struct WebsocketConfig {
20    #[serde(default = "WebsocketConfig::write_queue_size")]
21    pub write_queue_size: usize,
22    #[serde(default = "WebsocketConfig::max_request_per_sec")]
23    pub max_request_per_sec: NonZeroU32,
24}
25
26impl WebsocketConfig {
27    fn write_queue_size() -> usize {
28        100
29    }
30
31    fn max_request_per_sec() -> NonZeroU32 {
32        NonZeroU32::new(5u32).unwrap()
33    }
34}
35
36#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
37pub struct Version {
38    pub major: u8,
39    pub minor: u8,
40    pub patch: u8,
41}
42
43impl FromStr for Version {
44    type Err = String;
45
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        let parts: Vec<&str> = s.split('.').collect();
48        if parts.len() != 3 {
49            return Err(format!("Invalid version string: {}", s));
50        }
51        Ok(Version {
52            major: parts[0].parse().map_err(|_| "Bad major")?,
53            minor: parts[1].parse().map_err(|_| "Bad minor")?,
54            patch: parts[2].parse().map_err(|_| "Bad patch")?,
55        })
56    }
57}
58
59impl Ord for Version {
60    fn cmp(&self, other: &Self) -> Ordering {
61        (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch))
62    }
63}
64
65impl PartialOrd for Version {
66    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
67        Some(self.cmp(other))
68    }
69}
70
71impl fmt::Display for Version {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
74    }
75}
76
77impl Version {
78    pub fn is_compatible_with(&self, other: &Version) -> bool {
79        if self.major != other.major {
80            return false;
81        }
82
83        if self.minor != other.minor {
84            return false;
85        }
86
87        true
88    }
89}
90
91#[derive(Clone, Debug, Deserialize)]
92pub struct ModerationConfig {
93    pub language_service_enabled: bool,
94    pub min_confidence_to_block: f32,
95}
96
97#[derive(Clone, Debug, Deserialize)]
98pub struct InfraConfig {
99    #[serde(default = "InfraConfig::port_default")]
100    pub port: u16,
101    pub env: Environment,
102    pub ws_config: WebsocketConfig,
103    pub tg_bot_token: String,
104    pub db_pool_config: deadpool_postgres::Config,
105    pub db_use_tls: bool,
106    #[serde(default = "InfraConfig::txn_max_retries_default")]
107    pub txn_max_retries: u16,
108    #[serde(default = "InfraConfig::db_request_referrals_limit")]
109    pub db_request_referrals_limit: u16,
110    #[serde(default = "InfraConfig::db_request_abilities_limit")]
111    pub db_request_abilities_limit: u16,
112    pub hostname: String,
113    pub web_hostname: Option<String>,
114    pub db_sync_period: f64,
115    #[serde(default = "InfraConfig::state_updater_enabled_default")]
116    pub state_updater_enabled: bool,
117    #[serde(default = "InfraConfig::game_tick_enabled_default")]
118    pub game_tick_enabled: bool,
119    pub cron_trigger_period: f64,
120    pub webauthn_rp_id: String,
121    pub webauthn_rp_origin: String,
122    pub allowed_usernames: Vec<String>,
123    pub otlp_http_export_endpoint: String,
124    pub otlp_username: Option<String>,
125    pub otlp_password: Option<String>,
126    #[serde(default = "InfraConfig::otlp_sampling_rate_default")]
127    pub otlp_sampling_rate: f64,
128    pub show_metrics_logs: bool,
129    pub locale_folder_path: String,
130    pub default_locale: String,
131    pub analytics_gcs_logs_enabled: bool,
132    pub analytics_gcs_bucket: Option<String>,
133    pub analytics_gcs_folder: Option<String>,
134    pub analytics_gcs_upload_interval_secs: u64,
135    pub pyroscope_url: Option<String>,
136    pub firebase_project_id: String,
137    pub backend_version: Version,
138    #[serde(default = "InfraConfig::disconnect_log_events_count_default")]
139    pub disconnect_log_events_count: usize,
140    pub android_package_name: String,
141    #[serde(default = "InfraConfig::google_play_max_retries_default")]
142    pub google_play_max_retries: u16,
143    #[serde(default = "InfraConfig::google_play_retry_base_ms_default")]
144    pub google_play_retry_base_ms: u64,
145    pub moderation_config: ModerationConfig,
146    /// Shared admin secret. Used for two things:
147    ///   * `POST /api/admin/*` middleware (panel → monolith calls).
148    ///   * `X-Admin-API-Key` when calling realms-service `/ack_realm`.
149    /// Ops provision the same value into the realms-service secret under
150    /// `admin_api_key` so both services accept each other's requests.
151    #[serde(default)]
152    pub admin_api_key: Option<String>,
153    /// Realms-service entry point (e.g. `https://realms.overlord.lumex.team`).
154    /// Required on Prestable/Prod so the monolith can acknowledge that the
155    /// connecting user was actually routed here by `/pick_realm`.
156    #[serde(default)]
157    pub realms_service_url: Option<String>,
158    /// Slug that this monolith deploy uses to identify itself to realms-service
159    /// (matches `realms.name` in the realms-service DB, e.g. `r0`).
160    #[serde(default)]
161    pub realm_name: Option<String>,
162}
163
164impl InfraConfig {
165    pub const fn port_default() -> u16 {
166        3000
167    }
168
169    pub const fn txn_max_retries_default() -> u16 {
170        5
171    }
172
173    pub const fn db_request_referrals_limit() -> u16 {
174        10
175    }
176
177    pub const fn db_request_abilities_limit() -> u16 {
178        120
179    }
180
181    pub const fn google_play_max_retries_default() -> u16 {
182        3
183    }
184
185    pub const fn google_play_retry_base_ms_default() -> u64 {
186        500
187    }
188
189    pub const fn disconnect_log_events_count_default() -> usize {
190        20
191    }
192
193    pub fn otlp_sampling_rate_default() -> f64 {
194        1.0
195    }
196
197    pub const fn state_updater_enabled_default() -> bool {
198        true
199    }
200
201    pub const fn game_tick_enabled_default() -> bool {
202        true
203    }
204}
205
206#[derive(Clone, Debug, Deserialize)]
207pub struct Config {
208    pub infra_config: InfraConfig,
209    #[serde(deserialize_with = "deserialize_game_config_arc")]
210    pub game_config: Arc<crate::game_config::GameConfig>,
211    #[serde(skip)]
212    pub config_path: std::path::PathBuf,
213}
214
215fn deserialize_game_config_arc<'de, D>(
216    deserializer: D,
217) -> Result<Arc<crate::game_config::GameConfig>, D::Error>
218where
219    D: serde::Deserializer<'de>,
220{
221    let game_config = crate::game_config::GameConfig::deserialize(deserializer)?;
222    Ok(Arc::new(game_config))
223}
224
225impl Config {
226    pub fn load(
227        path: impl AsRef<std::path::Path> + Send + Sync + Clone + 'static,
228        port: Option<u16>,
229    ) -> anyhow::Result<Self> {
230        let config_path = path.as_ref().to_path_buf();
231        let mut config = config_parser::parse_from_file::<Self>(path)?;
232
233        config.game_config.validate();
234        config.config_path = config_path;
235
236        if let Some(port) = port {
237            config.infra_config.port = port;
238        }
239
240        if let Ok(v) = std::env::var("ENVIRONMENT") {
241            config.infra_config.env = v
242                .parse::<Environment>()
243                .map_err(|e| anyhow::anyhow!("Invalid ENVIRONMENT value `{v}`: {e}"))?;
244        }
245
246        if let Ok(v) = std::env::var("DB_HOST") {
247            config.infra_config.db_pool_config.host = Some(v);
248        }
249
250        if let Ok(v) = std::env::var("DB_PORT") {
251            let parsed = v
252                .parse::<u16>()
253                .with_context(|| format!("`{v}` is not a valid u16 for DB_PORT"))?;
254            config.infra_config.db_pool_config.port = Some(parsed);
255        }
256
257        if let Ok(v) = std::env::var("DB_NAME") {
258            config.infra_config.db_pool_config.dbname = Some(v);
259        }
260        if let Ok(v) = std::env::var("DB_USER") {
261            config.infra_config.db_pool_config.user = Some(v);
262        }
263        if let Ok(v) = std::env::var("DB_PASSWORD") {
264            config.infra_config.db_pool_config.password = Some(v);
265        }
266
267        if let Ok(v) = std::env::var("FIREBASEE_PROJECT_ID") {
268            config.infra_config.firebase_project_id = v;
269        }
270
271        if let Ok(v) = std::env::var("REALMS_SERVICE_URL") {
272            let trimmed = v.trim();
273            config.infra_config.realms_service_url = if trimmed.is_empty() {
274                None
275            } else {
276                Some(trimmed.to_string())
277            };
278        }
279        if let Ok(v) = std::env::var("REALM_NAME") {
280            let trimmed = v.trim();
281            config.infra_config.realm_name = if trimmed.is_empty() {
282                None
283            } else {
284                Some(trimmed.to_string())
285            };
286        }
287
288        if std::env::var_os("ALLOWED_PUBLIC").is_some() {
289            config.infra_config.allowed_usernames.clear();
290        }
291
292        if let Ok(v) = std::env::var("BACKEND_VERSION") {
293            let version: Version = v.parse().map_err(|e: String| {
294                anyhow::anyhow!("Invalid BACKEND_VERSION in ENV `{v}`: {e}")
295            })?;
296            config.infra_config.backend_version = version;
297        }
298
299        if let Ok(v) = std::env::var("GRAFANA_OTLP_ENDPOINT") {
300            config.infra_config.otlp_http_export_endpoint = v;
301        }
302
303        if let Ok(v) = std::env::var("GRAFANA_OTLP_USERNAME") {
304            config.infra_config.otlp_username = Some(v);
305        }
306
307        if let Ok(v) = std::env::var("GRAFANA_OTLP_PASSWORD") {
308            config.infra_config.otlp_password = Some(v);
309        }
310
311        if let Ok(v) = std::env::var("GRAFANA_OTLP_SAMPLING_RATE") {
312            config.infra_config.otlp_sampling_rate = v.parse::<f64>().with_context(|| {
313                format!("`{v}` is not a valid f64 for GRAFANA_OTLP_SAMPLING_RATE")
314            })?;
315        }
316
317        if let Ok(v) = std::env::var("GRAFANA_PYROSCOPE_URL") {
318            config.infra_config.pyroscope_url = Some(v);
319        }
320
321        if let Ok(v) = std::env::var("ANALYTICS_GCS_BUCKET") {
322            let bucket = v.trim();
323            config.infra_config.analytics_gcs_bucket = if bucket.is_empty() {
324                None
325            } else {
326                Some(bucket.to_string())
327            };
328        }
329
330        if let Ok(v) = std::env::var("ANALYTICS_GCS_FOLDER") {
331            let folder = v.trim().trim_matches('/');
332            config.infra_config.analytics_gcs_folder = if folder.is_empty() {
333                None
334            } else {
335                Some(folder.to_string())
336            };
337        }
338
339        if let Ok(v) = std::env::var("ANALYTICS_GCS_LOGS_ENABLED") {
340            config.infra_config.analytics_gcs_logs_enabled =
341                v.parse::<bool>().with_context(|| {
342                    format!("`{v}` is not a valid bool for ANALYTICS_GCS_LOGS_ENABLED")
343                })?;
344        }
345
346        if let Ok(v) = std::env::var("ANALYTICS_GCS_UPLOAD_INTERVAL_SECS") {
347            config.infra_config.analytics_gcs_upload_interval_secs =
348                v.parse::<u64>().with_context(|| {
349                    format!("`{v}` is not a valid u64 for ANALYTICS_GCS_UPLOAD_INTERVAL_SECS")
350                })?;
351        }
352
353        if let Ok(v) = std::env::var("ADMIN_API_KEY") {
354            config.infra_config.admin_api_key = Some(v);
355        }
356
357        Ok(config)
358    }
359
360    pub fn load_for_testing(
361        path: impl AsRef<std::path::Path> + Send + Sync + Clone + 'static,
362    ) -> anyhow::Result<Self> {
363        let config_path = path.as_ref().to_path_buf();
364        Ok(Config {
365            infra_config: config_parser::parse_from_file::<InfraConfig>(config_path.clone())?,
366            game_config: Arc::new(generate_game_config_for_tests()),
367            config_path,
368        })
369    }
370}