1use std::{
3 net::{IpAddr, Ipv4Addr, SocketAddr},
4 str::FromStr,
5 sync::{LazyLock, OnceLock},
6 time::Duration,
7};
8
9use anyhow::anyhow;
10use cardano_chain_follower::{Network, Slot};
11use clap::Args;
12use dotenvy::dotenv;
13use str_env_var::StringEnvVar;
14use tracing::error;
15use url::Url;
16
17use crate::{
18 build_info::{BUILD_INFO, log_build_info},
19 logger::{self, LOG_LEVEL_DEFAULT, LogLevel},
20 service::utilities::net::{get_public_ipv4, get_public_ipv6},
21 utils::blake2b_hash::generate_uuid_string_from_data,
22};
23
24pub(crate) mod admin;
25pub(crate) mod cardano_assets_cache;
26pub(crate) mod cassandra_db;
27pub(crate) mod chain_follower;
28pub(crate) mod event_db;
29pub(crate) mod rbac;
30pub(crate) mod signed_doc;
31mod str_env_var;
32
33const ADDRESS_DEFAULT: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 3030);
35
36const GITHUB_REPO_OWNER_DEFAULT: &str = "input-output-hk";
38
39const GITHUB_REPO_NAME_DEFAULT: &str = "catalyst-voices";
41
42const GITHUB_ISSUE_TEMPLATE_DEFAULT: &str = "bug_report.yml";
44
45const CLIENT_ID_KEY_DEFAULT: &str = "3db5301e-40f2-47ed-ab11-55b37674631a";
47
48const API_URL_PREFIX_DEFAULT: &str = "/api";
50
51const CHECK_CONFIG_TICK_DEFAULT: Duration = Duration::from_secs(5);
53
54const PURGE_BACKWARD_SLOT_BUFFER_DEFAULT: u64 = 100;
56
57const SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
60
61const SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT: u64 = 100;
64
65fn calculate_service_uuid() -> String {
68 let ip_addr: Vec<String> = vec![get_public_ipv4().to_string(), get_public_ipv6().to_string()];
69
70 generate_uuid_string_from_data("Catalyst-Gateway-Machine-UID", &ip_addr)
71}
72
73#[derive(Args, Clone)]
80#[clap(version = BUILD_INFO)]
81pub(crate) struct ServiceSettings {
82 #[clap(long, default_value = LOG_LEVEL_DEFAULT)]
84 pub(crate) log_level: LogLevel,
85}
86
87struct EnvVars {
89 github_repo_owner: StringEnvVar,
91
92 github_repo_name: StringEnvVar,
94
95 github_issue_template: StringEnvVar,
97
98 address: SocketAddr,
100
101 server_name: Option<StringEnvVar>,
103
104 service_id: StringEnvVar,
106
107 client_id_key: StringEnvVar,
109
110 api_host_names: Vec<String>,
112
113 api_url_prefix: StringEnvVar,
115
116 is_panic_endpoint_enabled: bool,
120
121 cassandra_persistent_db: cassandra_db::EnvVars,
123
124 cassandra_volatile_db: cassandra_db::EnvVars,
126
127 chain_follower: chain_follower::EnvVars,
129
130 event_db: event_db::EnvVars,
132
133 signed_doc: signed_doc::EnvVars,
135
136 rbac: rbac::EnvVars,
138
139 cardano_assets_cache: cardano_assets_cache::EnvVars,
141
142 internal_api_key: Option<StringEnvVar>,
144
145 #[allow(unused)]
147 check_config_tick: Duration,
148
149 purge_backward_slot_buffer: u64,
151
152 service_live_timeout_interval: Duration,
154
155 service_live_counter_threshold: u64,
157
158 log_not_found: Option<StringEnvVar>,
160}
161
162static ENV_VARS: LazyLock<EnvVars> = LazyLock::new(|| {
170 dotenv().ok();
172
173 let address = StringEnvVar::new("ADDRESS", ADDRESS_DEFAULT.to_string().into());
174 let address = SocketAddr::from_str(address.as_str())
175 .inspect_err(|err| {
176 error!(
177 error = ?err,
178 default_addr = ?ADDRESS_DEFAULT,
179 invalid_addr = ?address,
180 "Invalid binding address. Using default binding address value.",
181 );
182 })
183 .unwrap_or(ADDRESS_DEFAULT);
184
185 let purge_backward_slot_buffer = StringEnvVar::new_as_int(
186 "PURGE_BACKWARD_SLOT_BUFFER",
187 PURGE_BACKWARD_SLOT_BUFFER_DEFAULT,
188 0,
189 u64::MAX,
190 );
191
192 EnvVars {
193 github_repo_owner: StringEnvVar::new("GITHUB_REPO_OWNER", GITHUB_REPO_OWNER_DEFAULT.into()),
194 github_repo_name: StringEnvVar::new("GITHUB_REPO_NAME", GITHUB_REPO_NAME_DEFAULT.into()),
195 github_issue_template: StringEnvVar::new(
196 "GITHUB_ISSUE_TEMPLATE",
197 GITHUB_ISSUE_TEMPLATE_DEFAULT.into(),
198 ),
199 address,
200 server_name: StringEnvVar::new_optional("SERVER_NAME", false),
201 service_id: StringEnvVar::new("SERVICE_ID", calculate_service_uuid().into()),
202 client_id_key: StringEnvVar::new("CLIENT_ID_KEY", CLIENT_ID_KEY_DEFAULT.into()),
203 api_host_names: string_to_api_host_names(
204 &StringEnvVar::new_optional("API_HOST_NAMES", false)
205 .map(|v| v.as_string())
206 .unwrap_or_default(),
207 ),
208 api_url_prefix: StringEnvVar::new("API_URL_PREFIX", API_URL_PREFIX_DEFAULT.into()),
209 is_panic_endpoint_enabled: StringEnvVar::new_optional("YES_I_REALLY_WANT_TO_PANIC", false)
210 .is_some_and(|v| v.as_str() == "panic attack"),
211
212 cassandra_persistent_db: cassandra_db::EnvVars::new(
213 cassandra_db::PERSISTENT_URL_DEFAULT,
214 cassandra_db::PERSISTENT_NAMESPACE_DEFAULT,
215 ),
216 cassandra_volatile_db: cassandra_db::EnvVars::new(
217 cassandra_db::VOLATILE_URL_DEFAULT,
218 cassandra_db::VOLATILE_NAMESPACE_DEFAULT,
219 ),
220 chain_follower: chain_follower::EnvVars::new(),
221 event_db: event_db::EnvVars::new(),
222 signed_doc: signed_doc::EnvVars::new(),
223 rbac: rbac::EnvVars::new(),
224 cardano_assets_cache: cardano_assets_cache::EnvVars::new(),
225 internal_api_key: StringEnvVar::new_optional("INTERNAL_API_KEY", true),
226 check_config_tick: StringEnvVar::new_as_duration(
227 "CHECK_CONFIG_TICK",
228 CHECK_CONFIG_TICK_DEFAULT,
229 ),
230 purge_backward_slot_buffer,
231 service_live_timeout_interval: StringEnvVar::new_as_duration(
232 "SERVICE_LIVE_TIMEOUT_INTERVAL",
233 SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT,
234 ),
235 service_live_counter_threshold: StringEnvVar::new_as_int(
236 "SERVICE_LIVE_COUNTER_THRESHOLD",
237 SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT,
238 0,
239 u64::MAX,
240 ),
241 log_not_found: StringEnvVar::new_optional("LOG_NOT_FOUND", false),
242 }
243});
244
245impl EnvVars {
246 pub(crate) fn validate() -> anyhow::Result<()> {
248 let mut status = Ok(());
249
250 let url = ENV_VARS.event_db.url();
251 if let Err(error) = tokio_postgres::config::Config::from_str(url) {
252 error!(error=%error, url=url, "Invalid Postgres DB URL.");
253 status = Err(anyhow!("Environment Variable Validation Error."));
254 }
255
256 status
257 }
258}
259
260static SERVICE_SETTINGS: OnceLock<ServiceSettings> = OnceLock::new();
262
263pub(crate) struct Settings();
265
266impl Settings {
267 pub(crate) fn init(settings: ServiceSettings) -> anyhow::Result<()> {
269 let log_level = settings.log_level;
270
271 if SERVICE_SETTINGS.set(settings).is_err() {
272 println!("Failed to initialize service settings. Called multiple times?");
274 }
275
276 logger::init(log_level);
278
279 log_build_info();
280
281 EnvVars::validate()
283 }
284
285 pub(crate) fn event_db_settings() -> &'static event_db::EnvVars {
287 &ENV_VARS.event_db
288 }
289
290 pub(crate) fn cassandra_db_cfg() -> (cassandra_db::EnvVars, cassandra_db::EnvVars) {
292 (
293 ENV_VARS.cassandra_persistent_db.clone(),
294 ENV_VARS.cassandra_volatile_db.clone(),
295 )
296 }
297
298 pub(crate) fn follower_cfg() -> chain_follower::EnvVars {
300 ENV_VARS.chain_follower.clone()
301 }
302
303 pub(crate) fn signed_doc_cfg() -> signed_doc::EnvVars {
305 ENV_VARS.signed_doc.clone()
306 }
307
308 pub fn rbac_cfg() -> &'static rbac::EnvVars {
310 &ENV_VARS.rbac
311 }
312
313 pub(crate) fn cardano_assets_cache() -> cardano_assets_cache::EnvVars {
315 ENV_VARS.cardano_assets_cache.clone()
316 }
317
318 pub(crate) fn cardano_network() -> &'static Network {
321 &ENV_VARS.chain_follower.chain
322 }
323
324 pub(crate) fn api_url_prefix() -> &'static str {
326 ENV_VARS.api_url_prefix.as_str()
327 }
328
329 pub(crate) fn client_id_key() -> &'static str {
331 ENV_VARS.client_id_key.as_str()
332 }
333
334 pub(crate) fn service_id() -> &'static str {
336 ENV_VARS.service_id.as_str()
337 }
338
339 pub(crate) fn api_host_names() -> &'static [String] {
348 &ENV_VARS.api_host_names
349 }
350
351 pub(crate) fn bound_address() -> SocketAddr {
353 ENV_VARS.address
354 }
355
356 pub(crate) fn server_name() -> Option<&'static str> {
358 ENV_VARS.server_name.as_ref().map(StringEnvVar::as_str)
359 }
360
361 pub(crate) fn is_panic_endpoint_enabled() -> bool {
363 ENV_VARS.is_panic_endpoint_enabled
364 }
365
366 pub(crate) fn generate_github_issue_url(title: &str) -> Option<Url> {
386 let path = format!(
387 "https://github.com/{}/{}/issues/new",
388 ENV_VARS.github_repo_owner.as_str(),
389 ENV_VARS.github_repo_name.as_str()
390 );
391
392 match Url::parse_with_params(&path, &[
393 ("template", ENV_VARS.github_issue_template.as_str()),
394 ("title", title),
395 ]) {
396 Ok(url) => Some(url),
397 Err(e) => {
398 error!("Failed to generate github issue url {:?}", e.to_string());
399 None
400 },
401 }
402 }
403
404 pub(crate) fn check_internal_api_key(value: &str) -> bool {
406 if let Some(required_key) = ENV_VARS.internal_api_key.as_ref().map(StringEnvVar::as_str) {
407 value == required_key
408 } else {
409 false
410 }
411 }
412
413 pub(crate) fn purge_backward_slot_buffer() -> Slot {
415 ENV_VARS.purge_backward_slot_buffer.into()
416 }
417
418 pub(crate) fn service_live_timeout_interval() -> Duration {
420 ENV_VARS.service_live_timeout_interval
421 }
422
423 pub(crate) fn service_live_counter_threshold() -> u64 {
425 ENV_VARS.service_live_counter_threshold
426 }
427
428 pub(crate) fn log_not_found() -> bool {
430 ENV_VARS.log_not_found.is_some()
431 }
432}
433
434fn string_to_api_host_names(hosts: &str) -> Vec<String> {
436 fn invalid_hostname(hostname: &str) -> String {
438 error!(hostname = hostname, "Invalid host name for API");
439 String::new()
440 }
441
442 let configured_hosts: Vec<String> = hosts
443 .split(',')
444 .filter(|s| !s.is_empty())
447 .map(|s| {
448 let url = Url::parse(s.trim());
449 match url {
450 Ok(url) => {
451 let scheme = url.scheme();
453
454 let port = url.port();
455
456 match url.host() {
458 Some(host) => {
459 let host = host.to_string();
460 if host.is_empty() {
461 invalid_hostname(s)
462 } else {
463 match port {
464 Some(port) => {
465 format! {"{scheme}://{host}:{port}"}
466 },
469 None => {
470 format! {"{scheme}://{host}"}
471 },
472 }
473 }
474 },
475 None => invalid_hostname(s),
476 }
477 },
478 Err(_) => invalid_hostname(s),
479 }
480 })
481 .filter(|s| !s.is_empty())
482 .collect();
483
484 configured_hosts
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490
491 #[test]
492 fn generate_github_issue_url_test() {
493 let title = "Hello, World! How are you?";
494 assert_eq!(
495 Settings::generate_github_issue_url(title)
496 .expect("Failed to generate url")
497 .as_str(),
498 "https://github.com/input-output-hk/catalyst-voices/issues/new?template=bug_report.yml&title=Hello%2C+World%21+How+are+you%3F"
499 );
500 }
501
502 #[test]
503 fn configured_hosts_default() {
504 let configured_hosts = Settings::api_host_names();
505 assert!(configured_hosts.is_empty());
506 }
507
508 #[test]
509 fn configured_hosts_set_multiple() {
510 let configured_hosts = string_to_api_host_names(
511 "http://api.prod.projectcatalyst.io , https://api.dev.projectcatalyst.io:1234",
512 );
513 assert_eq!(configured_hosts, vec![
514 "http://api.prod.projectcatalyst.io",
515 "https://api.dev.projectcatalyst.io:1234"
516 ]);
517 }
518
519 #[test]
520 fn configured_hosts_set_multiple_one_invalid() {
521 let configured_hosts =
522 string_to_api_host_names("not a hostname , https://api.dev.projectcatalyst.io:1234");
523 assert_eq!(configured_hosts, vec![
524 "https://api.dev.projectcatalyst.io:1234"
525 ]);
526 }
527
528 #[test]
529 fn configured_hosts_set_empty() {
530 let configured_hosts = string_to_api_host_names("");
531 assert!(configured_hosts.is_empty());
532 }
533
534 #[test]
535 fn configured_service_live_timeout_interval_default() {
536 let timeout_secs = Settings::service_live_timeout_interval();
537 assert_eq!(timeout_secs, SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT);
538 }
539
540 #[test]
541 fn configured_service_live_counter_threshold_default() {
542 let threshold = Settings::service_live_counter_threshold();
543 assert_eq!(threshold, SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT);
544 }
545}