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::{log_build_info, BUILD_INFO},
19 logger::{self, LogLevel, LOG_LEVEL_DEFAULT},
20 service::utilities::net::{get_public_ipv4, get_public_ipv6},
21 utils::blake2b_hash::generate_uuid_string_from_data,
22};
23
24pub(crate) mod cardano_assets_cache;
25pub(crate) mod cassandra_db;
26pub(crate) mod chain_follower;
27pub(crate) mod event_db;
28pub(crate) mod rbac;
29pub(crate) mod signed_doc;
30mod str_env_var;
31
32const ADDRESS_DEFAULT: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 3030);
34
35const GITHUB_REPO_OWNER_DEFAULT: &str = "input-output-hk";
37
38const GITHUB_REPO_NAME_DEFAULT: &str = "catalyst-voices";
40
41const GITHUB_ISSUE_TEMPLATE_DEFAULT: &str = "bug_report.yml";
43
44const CLIENT_ID_KEY_DEFAULT: &str = "3db5301e-40f2-47ed-ab11-55b37674631a";
46
47const API_URL_PREFIX_DEFAULT: &str = "/api";
49
50const CHECK_CONFIG_TICK_DEFAULT: Duration = Duration::from_secs(5);
52
53const PURGE_BACKWARD_SLOT_BUFFER_DEFAULT: u64 = 100;
55
56const SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
59
60const SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT: u64 = 100;
63
64fn calculate_service_uuid() -> String {
67 let ip_addr: Vec<String> = vec![get_public_ipv4().to_string(), get_public_ipv6().to_string()];
68
69 generate_uuid_string_from_data("Catalyst-Gateway-Machine-UID", &ip_addr)
70}
71
72#[derive(Args, Clone)]
79#[clap(version = BUILD_INFO)]
80pub(crate) struct ServiceSettings {
81 #[clap(long, default_value = LOG_LEVEL_DEFAULT)]
83 pub(crate) log_level: LogLevel,
84}
85
86struct EnvVars {
88 github_repo_owner: StringEnvVar,
90
91 github_repo_name: StringEnvVar,
93
94 github_issue_template: StringEnvVar,
96
97 address: SocketAddr,
99
100 server_name: Option<StringEnvVar>,
102
103 service_id: StringEnvVar,
105
106 client_id_key: StringEnvVar,
108
109 api_host_names: Vec<String>,
111
112 api_url_prefix: StringEnvVar,
114
115 is_panic_endpoint_enabled: bool,
119
120 cassandra_persistent_db: cassandra_db::EnvVars,
122
123 cassandra_volatile_db: cassandra_db::EnvVars,
125
126 chain_follower: chain_follower::EnvVars,
128
129 event_db: event_db::EnvVars,
131
132 signed_doc: signed_doc::EnvVars,
134
135 rbac: rbac::EnvVars,
137
138 cardano_assets_cache: cardano_assets_cache::EnvVars,
140
141 internal_api_key: Option<StringEnvVar>,
143
144 #[allow(unused)]
146 check_config_tick: Duration,
147
148 purge_backward_slot_buffer: u64,
150
151 service_live_timeout_interval: Duration,
153
154 service_live_counter_threshold: u64,
156
157 log_not_found: Option<StringEnvVar>,
159}
160
161static ENV_VARS: LazyLock<EnvVars> = LazyLock::new(|| {
169 dotenv().ok();
171
172 let address = StringEnvVar::new("ADDRESS", ADDRESS_DEFAULT.to_string().into());
173 let address = SocketAddr::from_str(address.as_str())
174 .inspect_err(|err| {
175 error!(
176 error = ?err,
177 default_addr = ?ADDRESS_DEFAULT,
178 invalid_addr = ?address,
179 "Invalid binding address. Using default binding address value.",
180 );
181 })
182 .unwrap_or(ADDRESS_DEFAULT);
183
184 let purge_backward_slot_buffer = StringEnvVar::new_as_int(
185 "PURGE_BACKWARD_SLOT_BUFFER",
186 PURGE_BACKWARD_SLOT_BUFFER_DEFAULT,
187 0,
188 u64::MAX,
189 );
190
191 EnvVars {
192 github_repo_owner: StringEnvVar::new("GITHUB_REPO_OWNER", GITHUB_REPO_OWNER_DEFAULT.into()),
193 github_repo_name: StringEnvVar::new("GITHUB_REPO_NAME", GITHUB_REPO_NAME_DEFAULT.into()),
194 github_issue_template: StringEnvVar::new(
195 "GITHUB_ISSUE_TEMPLATE",
196 GITHUB_ISSUE_TEMPLATE_DEFAULT.into(),
197 ),
198 address,
199 server_name: StringEnvVar::new_optional("SERVER_NAME", false),
200 service_id: StringEnvVar::new("SERVICE_ID", calculate_service_uuid().into()),
201 client_id_key: StringEnvVar::new("CLIENT_ID_KEY", CLIENT_ID_KEY_DEFAULT.into()),
202 api_host_names: string_to_api_host_names(
203 &StringEnvVar::new_optional("c", false)
204 .map(|v| v.as_string())
205 .unwrap_or_default(),
206 ),
207 api_url_prefix: StringEnvVar::new("API_URL_PREFIX", API_URL_PREFIX_DEFAULT.into()),
208 is_panic_endpoint_enabled: StringEnvVar::new_optional("YES_I_REALLY_WANT_TO_PANIC", false)
209 .is_some_and(|v| v.as_str() == "panic attack"),
210
211 cassandra_persistent_db: cassandra_db::EnvVars::new(
212 cassandra_db::PERSISTENT_URL_DEFAULT,
213 cassandra_db::PERSISTENT_NAMESPACE_DEFAULT,
214 ),
215 cassandra_volatile_db: cassandra_db::EnvVars::new(
216 cassandra_db::VOLATILE_URL_DEFAULT,
217 cassandra_db::VOLATILE_NAMESPACE_DEFAULT,
218 ),
219 chain_follower: chain_follower::EnvVars::new(),
220 event_db: event_db::EnvVars::new(),
221 signed_doc: signed_doc::EnvVars::new(),
222 rbac: rbac::EnvVars::new(),
223 cardano_assets_cache: cardano_assets_cache::EnvVars::new(),
224 internal_api_key: StringEnvVar::new_optional("INTERNAL_API_KEY", true),
225 check_config_tick: StringEnvVar::new_as_duration(
226 "CHECK_CONFIG_TICK",
227 CHECK_CONFIG_TICK_DEFAULT,
228 ),
229 purge_backward_slot_buffer,
230 service_live_timeout_interval: StringEnvVar::new_as_duration(
231 "SERVICE_LIVE_TIMEOUT_INTERVAL",
232 SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT,
233 ),
234 service_live_counter_threshold: StringEnvVar::new_as_int(
235 "SERVICE_LIVE_COUNTER_THRESHOLD",
236 SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT,
237 0,
238 u64::MAX,
239 ),
240 log_not_found: StringEnvVar::new_optional("LOG_NOT_FOUND", false),
241 }
242});
243
244impl EnvVars {
245 pub(crate) fn validate() -> anyhow::Result<()> {
247 let mut status = Ok(());
248
249 let url = ENV_VARS.event_db.url();
250 if let Err(error) = tokio_postgres::config::Config::from_str(url) {
251 error!(error=%error, url=url, "Invalid Postgres DB URL.");
252 status = Err(anyhow!("Environment Variable Validation Error."));
253 }
254
255 status
256 }
257}
258
259static SERVICE_SETTINGS: OnceLock<ServiceSettings> = OnceLock::new();
261
262pub(crate) struct Settings();
264
265impl Settings {
266 pub(crate) fn init(settings: ServiceSettings) -> anyhow::Result<()> {
268 let log_level = settings.log_level;
269
270 if SERVICE_SETTINGS.set(settings).is_err() {
271 println!("Failed to initialize service settings. Called multiple times?");
273 }
274
275 logger::init(log_level);
277
278 log_build_info();
279
280 EnvVars::validate()
282 }
283
284 pub(crate) fn event_db_settings() -> &'static event_db::EnvVars {
286 &ENV_VARS.event_db
287 }
288
289 pub(crate) fn cassandra_db_cfg() -> (cassandra_db::EnvVars, cassandra_db::EnvVars) {
291 (
292 ENV_VARS.cassandra_persistent_db.clone(),
293 ENV_VARS.cassandra_volatile_db.clone(),
294 )
295 }
296
297 pub(crate) fn follower_cfg() -> chain_follower::EnvVars {
299 ENV_VARS.chain_follower.clone()
300 }
301
302 pub(crate) fn signed_doc_cfg() -> signed_doc::EnvVars {
304 ENV_VARS.signed_doc.clone()
305 }
306
307 pub fn rbac_cfg() -> &'static rbac::EnvVars {
309 &ENV_VARS.rbac
310 }
311
312 pub(crate) fn cardano_assets_cache() -> cardano_assets_cache::EnvVars {
314 ENV_VARS.cardano_assets_cache.clone()
315 }
316
317 pub(crate) fn cardano_network() -> Network {
320 ENV_VARS.chain_follower.chain
321 }
322
323 pub(crate) fn api_url_prefix() -> &'static str {
325 ENV_VARS.api_url_prefix.as_str()
326 }
327
328 pub(crate) fn client_id_key() -> &'static str {
330 ENV_VARS.client_id_key.as_str()
331 }
332
333 pub(crate) fn service_id() -> &'static str {
335 ENV_VARS.service_id.as_str()
336 }
337
338 pub(crate) fn api_host_names() -> &'static [String] {
347 &ENV_VARS.api_host_names
348 }
349
350 pub(crate) fn bound_address() -> SocketAddr {
352 ENV_VARS.address
353 }
354
355 pub(crate) fn server_name() -> Option<&'static str> {
357 ENV_VARS.server_name.as_ref().map(StringEnvVar::as_str)
358 }
359
360 pub(crate) fn is_panic_endpoint_enabled() -> bool {
362 ENV_VARS.is_panic_endpoint_enabled
363 }
364
365 pub(crate) fn generate_github_issue_url(title: &str) -> Option<Url> {
385 let path = format!(
386 "https://github.com/{}/{}/issues/new",
387 ENV_VARS.github_repo_owner.as_str(),
388 ENV_VARS.github_repo_name.as_str()
389 );
390
391 match Url::parse_with_params(&path, &[
392 ("template", ENV_VARS.github_issue_template.as_str()),
393 ("title", title),
394 ]) {
395 Ok(url) => Some(url),
396 Err(e) => {
397 error!("Failed to generate github issue url {:?}", e.to_string());
398 None
399 },
400 }
401 }
402
403 pub(crate) fn check_internal_api_key(value: &str) -> bool {
405 if let Some(required_key) = ENV_VARS.internal_api_key.as_ref().map(StringEnvVar::as_str) {
406 value == required_key
407 } else {
408 false
409 }
410 }
411
412 pub(crate) fn purge_backward_slot_buffer() -> Slot {
414 ENV_VARS.purge_backward_slot_buffer.into()
415 }
416
417 pub(crate) fn service_live_timeout_interval() -> Duration {
419 ENV_VARS.service_live_timeout_interval
420 }
421
422 pub(crate) fn service_live_counter_threshold() -> u64 {
424 ENV_VARS.service_live_counter_threshold
425 }
426
427 pub(crate) fn log_not_found() -> bool {
429 ENV_VARS.log_not_found.is_some()
430 }
431}
432
433fn string_to_api_host_names(hosts: &str) -> Vec<String> {
435 fn invalid_hostname(hostname: &str) -> String {
437 error!(hostname = hostname, "Invalid host name for API");
438 String::new()
439 }
440
441 let configured_hosts: Vec<String> = hosts
442 .split(',')
443 .filter(|s| !s.is_empty())
446 .map(|s| {
447 let url = Url::parse(s.trim());
448 match url {
449 Ok(url) => {
450 let scheme = url.scheme();
452
453 let port = url.port();
454
455 match url.host() {
457 Some(host) => {
458 let host = host.to_string();
459 if host.is_empty() {
460 invalid_hostname(s)
461 } else {
462 match port {
463 Some(port) => {
464 format! {"{scheme}://{host}:{port}"}
465 },
468 None => {
469 format! {"{scheme}://{host}"}
470 },
471 }
472 }
473 },
474 None => invalid_hostname(s),
475 }
476 },
477 Err(_) => invalid_hostname(s),
478 }
479 })
480 .filter(|s| !s.is_empty())
481 .collect();
482
483 configured_hosts
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489
490 #[test]
491 fn generate_github_issue_url_test() {
492 let title = "Hello, World! How are you?";
493 assert_eq!(
494 Settings::generate_github_issue_url(title).expect("Failed to generate url").as_str(),
495 "https://github.com/input-output-hk/catalyst-voices/issues/new?template=bug_report.yml&title=Hello%2C+World%21+How+are+you%3F"
496 );
497 }
498
499 #[test]
500 fn configured_hosts_default() {
501 let configured_hosts = Settings::api_host_names();
502 assert!(configured_hosts.is_empty());
503 }
504
505 #[test]
506 fn configured_hosts_set_multiple() {
507 let configured_hosts = string_to_api_host_names(
508 "http://api.prod.projectcatalyst.io , https://api.dev.projectcatalyst.io:1234",
509 );
510 assert_eq!(configured_hosts, vec![
511 "http://api.prod.projectcatalyst.io",
512 "https://api.dev.projectcatalyst.io:1234"
513 ]);
514 }
515
516 #[test]
517 fn configured_hosts_set_multiple_one_invalid() {
518 let configured_hosts =
519 string_to_api_host_names("not a hostname , https://api.dev.projectcatalyst.io:1234");
520 assert_eq!(configured_hosts, vec![
521 "https://api.dev.projectcatalyst.io:1234"
522 ]);
523 }
524
525 #[test]
526 fn configured_hosts_set_empty() {
527 let configured_hosts = string_to_api_host_names("");
528 assert!(configured_hosts.is_empty());
529 }
530
531 #[test]
532 fn configured_service_live_timeout_interval_default() {
533 let timeout_secs = Settings::service_live_timeout_interval();
534 assert_eq!(timeout_secs, SERVICE_LIVE_TIMEOUT_INTERVAL_DEFAULT);
535 }
536
537 #[test]
538 fn configured_service_live_counter_threshold_default() {
539 let threshold = Settings::service_live_counter_threshold();
540 assert_eq!(threshold, SERVICE_LIVE_COUNTER_THRESHOLD_DEFAULT);
541 }
542}