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    /// GCP project ID that hosts the Pub/Sub topic Play Console publishes
142    /// Real-time Developer Notifications (RTDN) to. The monolith pulls voided
143    /// purchase events from a subscription on that topic to mark refunds and
144    /// ban abusive accounts from further purchases.
145    pub pubsub_project_id: String,
146    /// Pull subscription name on the RTDN topic. Combined with
147    /// `pubsub_project_id` into `projects/<id>/subscriptions/<name>` for the
148    /// Pub/Sub Subscriber API. Empty string keeps the puller disabled at
149    /// startup — useful before the GCP setup is finalized.
150    pub pubsub_rtdn_subscription: String,
151    #[serde(default = "InfraConfig::google_play_max_retries_default")]
152    pub google_play_max_retries: u16,
153    #[serde(default = "InfraConfig::google_play_retry_base_ms_default")]
154    pub google_play_retry_base_ms: u64,
155    pub moderation_config: ModerationConfig,
156    /// Shared admin secret. Used for two things:
157    ///   * `POST /api/admin/*` middleware (panel → monolith calls).
158    ///   * `X-Admin-API-Key` when calling realms-service `/ack_realm`.
159    ///
160    /// Ops provision the same value into the realms-service secret under
161    /// `admin_api_key` so both services accept each other's requests.
162    #[serde(default)]
163    pub admin_api_key: Option<String>,
164    /// Realms-service entry point (e.g. `https://realms.overlord.lumex.team`).
165    /// Required on Prestable/Prod so the monolith can acknowledge that the
166    /// connecting user was actually routed here by `/pick_realm`.
167    #[serde(default)]
168    pub realms_service_url: Option<String>,
169    /// Slug that this monolith deploy uses to identify itself to realms-service
170    /// (matches `realms.name` in the realms-service DB, e.g. `r0`).
171    #[serde(default)]
172    pub realm_name: Option<String>,
173}
174
175impl InfraConfig {
176    pub const fn port_default() -> u16 {
177        3000
178    }
179
180    pub const fn txn_max_retries_default() -> u16 {
181        5
182    }
183
184    pub const fn db_request_referrals_limit() -> u16 {
185        10
186    }
187
188    pub const fn db_request_abilities_limit() -> u16 {
189        120
190    }
191
192    pub const fn google_play_max_retries_default() -> u16 {
193        3
194    }
195
196    pub const fn google_play_retry_base_ms_default() -> u64 {
197        500
198    }
199
200    pub const fn disconnect_log_events_count_default() -> usize {
201        20
202    }
203
204    pub fn otlp_sampling_rate_default() -> f64 {
205        1.0
206    }
207
208    pub const fn state_updater_enabled_default() -> bool {
209        true
210    }
211
212    pub const fn game_tick_enabled_default() -> bool {
213        true
214    }
215}
216
217#[derive(Clone, Debug, Deserialize)]
218pub struct Config {
219    pub infra_config: InfraConfig,
220    #[serde(deserialize_with = "deserialize_game_config_arc")]
221    pub game_config: Arc<crate::game_config::GameConfig>,
222    #[serde(skip)]
223    pub config_path: std::path::PathBuf,
224}
225
226fn deserialize_game_config_arc<'de, D>(
227    deserializer: D,
228) -> Result<Arc<crate::game_config::GameConfig>, D::Error>
229where
230    D: serde::Deserializer<'de>,
231{
232    let game_config = crate::game_config::GameConfig::deserialize(deserializer)?;
233    Ok(Arc::new(game_config))
234}
235
236impl Config {
237    pub fn load(
238        path: impl AsRef<std::path::Path> + Send + Sync + Clone + 'static,
239        port: Option<u16>,
240    ) -> anyhow::Result<Self> {
241        let config_path = path.as_ref().to_path_buf();
242        let mut config = config_parser::parse_from_file::<Self>(path)?;
243
244        config.game_config.validate();
245        config.config_path = config_path;
246
247        if let Some(port) = port {
248            config.infra_config.port = port;
249        }
250
251        if let Ok(v) = std::env::var("ENVIRONMENT") {
252            config.infra_config.env = v
253                .parse::<Environment>()
254                .map_err(|e| anyhow::anyhow!("Invalid ENVIRONMENT value `{v}`: {e}"))?;
255        }
256
257        if let Ok(v) = std::env::var("DB_HOST") {
258            config.infra_config.db_pool_config.host = Some(v);
259        }
260
261        if let Ok(v) = std::env::var("DB_PORT") {
262            let parsed = v
263                .parse::<u16>()
264                .with_context(|| format!("`{v}` is not a valid u16 for DB_PORT"))?;
265            config.infra_config.db_pool_config.port = Some(parsed);
266        }
267
268        if let Ok(v) = std::env::var("DB_NAME") {
269            config.infra_config.db_pool_config.dbname = Some(v);
270        }
271        if let Ok(v) = std::env::var("DB_USER") {
272            config.infra_config.db_pool_config.user = Some(v);
273        }
274        if let Ok(v) = std::env::var("DB_PASSWORD") {
275            config.infra_config.db_pool_config.password = Some(v);
276        }
277
278        if let Ok(v) = std::env::var("FIREBASEE_PROJECT_ID") {
279            config.infra_config.firebase_project_id = v;
280        }
281
282        if let Ok(v) = std::env::var("PUBSUB_PROJECT_ID") {
283            config.infra_config.pubsub_project_id = v;
284        }
285        if let Ok(v) = std::env::var("PUBSUB_RTDN_SUBSCRIPTION") {
286            config.infra_config.pubsub_rtdn_subscription = v;
287        }
288
289        if let Ok(v) = std::env::var("REALMS_SERVICE_URL") {
290            let trimmed = v.trim();
291            config.infra_config.realms_service_url = if trimmed.is_empty() {
292                None
293            } else {
294                Some(trimmed.to_string())
295            };
296        }
297        if let Ok(v) = std::env::var("REALM_NAME") {
298            let trimmed = v.trim();
299            config.infra_config.realm_name = if trimmed.is_empty() {
300                None
301            } else {
302                Some(trimmed.to_string())
303            };
304        }
305
306        if std::env::var_os("ALLOWED_PUBLIC").is_some() {
307            config.infra_config.allowed_usernames.clear();
308        }
309
310        if let Ok(v) = std::env::var("BACKEND_VERSION") {
311            let version: Version = v.parse().map_err(|e: String| {
312                anyhow::anyhow!("Invalid BACKEND_VERSION in ENV `{v}`: {e}")
313            })?;
314            config.infra_config.backend_version = version;
315        }
316
317        if let Ok(v) = std::env::var("GRAFANA_OTLP_ENDPOINT") {
318            config.infra_config.otlp_http_export_endpoint = v;
319        }
320
321        if let Ok(v) = std::env::var("GRAFANA_OTLP_USERNAME") {
322            config.infra_config.otlp_username = Some(v);
323        }
324
325        if let Ok(v) = std::env::var("GRAFANA_OTLP_PASSWORD") {
326            config.infra_config.otlp_password = Some(v);
327        }
328
329        if let Ok(v) = std::env::var("GRAFANA_OTLP_SAMPLING_RATE") {
330            config.infra_config.otlp_sampling_rate = v.parse::<f64>().with_context(|| {
331                format!("`{v}` is not a valid f64 for GRAFANA_OTLP_SAMPLING_RATE")
332            })?;
333        }
334
335        if let Ok(v) = std::env::var("GRAFANA_PYROSCOPE_URL") {
336            config.infra_config.pyroscope_url = Some(v);
337        }
338
339        if let Ok(v) = std::env::var("ANALYTICS_GCS_BUCKET") {
340            let bucket = v.trim();
341            config.infra_config.analytics_gcs_bucket = if bucket.is_empty() {
342                None
343            } else {
344                Some(bucket.to_string())
345            };
346        }
347
348        if let Ok(v) = std::env::var("ANALYTICS_GCS_FOLDER") {
349            let folder = v.trim().trim_matches('/');
350            config.infra_config.analytics_gcs_folder = if folder.is_empty() {
351                None
352            } else {
353                Some(folder.to_string())
354            };
355        }
356
357        if let Ok(v) = std::env::var("ANALYTICS_GCS_LOGS_ENABLED") {
358            config.infra_config.analytics_gcs_logs_enabled =
359                v.parse::<bool>().with_context(|| {
360                    format!("`{v}` is not a valid bool for ANALYTICS_GCS_LOGS_ENABLED")
361                })?;
362        }
363
364        if let Ok(v) = std::env::var("ANALYTICS_GCS_UPLOAD_INTERVAL_SECS") {
365            config.infra_config.analytics_gcs_upload_interval_secs =
366                v.parse::<u64>().with_context(|| {
367                    format!("`{v}` is not a valid u64 for ANALYTICS_GCS_UPLOAD_INTERVAL_SECS")
368                })?;
369        }
370
371        if let Ok(v) = std::env::var("ADMIN_API_KEY") {
372            config.infra_config.admin_api_key = Some(v);
373        }
374
375        Ok(config)
376    }
377
378    pub fn load_for_testing(
379        path: impl AsRef<std::path::Path> + Send + Sync + Clone + 'static,
380    ) -> anyhow::Result<Self> {
381        let config_path = path.as_ref().to_path_buf();
382        Ok(Config {
383            infra_config: config_parser::parse_from_file::<InfraConfig>(config_path.clone())?,
384            game_config: Arc::new(generate_game_config_for_tests()),
385            config_path,
386        })
387    }
388}