taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

lib.rs (3581B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2024-2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use std::{path::PathBuf, time::Duration};
     18 
     19 use config::{Config, parser::ConfigSource};
     20 use mimalloc::MiMalloc;
     21 use tracing::error;
     22 use tracing_subscriber::util::SubscriberInitExt;
     23 
     24 use crate::log::taler_logger;
     25 
     26 pub mod api;
     27 pub mod bench;
     28 pub mod cli;
     29 pub mod config;
     30 pub mod db;
     31 pub mod encoding;
     32 pub mod error;
     33 pub mod error_code;
     34 pub mod json_file;
     35 pub mod log;
     36 pub mod signature;
     37 pub mod types;
     38 
     39 #[global_allocator]
     40 static GLOBAL: MiMalloc = MiMalloc;
     41 
     42 #[derive(clap::Parser, Debug, Clone)]
     43 pub struct CommonArgs {
     44     /// Specifies the configuration file
     45     #[arg(short, long, global = true)]
     46     config: Option<PathBuf>,
     47 
     48     /// Configure logging to use LOGLEVEL
     49     #[arg(short('L'), long, global = true)]
     50     log: Option<tracing::Level>,
     51 
     52     /// Show logs from all sources
     53     #[arg(short, long, global = true, hide = true)]
     54     verbose: bool,
     55 }
     56 
     57 /// DD102: will fail with exit code 9 and will not be restarted by systemd
     58 #[derive(Debug, thiserror::Error)]
     59 #[error("{0}")]
     60 pub struct PermanentErr(String);
     61 
     62 pub fn taler_main(
     63     src: ConfigSource,
     64     args: CommonArgs,
     65     app: impl AsyncFnOnce(&Config) -> Result<(), anyhow::Error>,
     66 ) {
     67     taler_logger(args.log, args.verbose).init();
     68     let cfg = match Config::load(src, args.config) {
     69         Ok(cfg) => cfg,
     70         Err(err) => {
     71             error!(target: "config", "{}", err);
     72             std::process::exit(6);
     73         }
     74     };
     75 
     76     // Setup async runtime
     77     let runtime = tokio::runtime::Builder::new_multi_thread()
     78         .enable_all()
     79         .build()
     80         .unwrap();
     81 
     82     // Run app
     83     let result = runtime.block_on(app(&cfg));
     84     if let Err(err) = result {
     85         error!(target: "cli", "{}", err);
     86         // DD102: only diagnosed configuration errors suppress service recovery
     87         std::process::exit(if err.chain().any(|cause| cause.is::<config::CfgErr>()) {
     88             6
     89         } else if err.chain().any(|cause| cause.is::<PermanentErr>()) {
     90             9
     91         } else {
     92             1
     93         })
     94     }
     95 }
     96 
     97 /// Infinite exponential backoff with decorrelated jitter
     98 pub struct ExpoBackoffDecorr {
     99     base: u32,
    100     max: u32,
    101     factor: f32,
    102     sleep: u32,
    103 }
    104 
    105 impl ExpoBackoffDecorr {
    106     pub fn new(base: Duration, max: Duration, factor: f32) -> Self {
    107         Self {
    108             base: base.as_millis() as u32,
    109             max: max.as_millis() as u32,
    110             factor,
    111             sleep: base.as_millis() as u32,
    112         }
    113     }
    114 
    115     pub fn backoff(&mut self) -> Duration {
    116         self.sleep =
    117             rand::random_range(self.base..(self.sleep as f32 * self.factor) as u32).min(self.max);
    118         Duration::from_millis(self.sleep as u64)
    119     }
    120 
    121     pub fn reset(&mut self) {
    122         self.sleep = self.base
    123     }
    124 }
    125 
    126 impl Default for ExpoBackoffDecorr {
    127     fn default() -> Self {
    128         Self::new(Duration::from_millis(400), Duration::from_secs(30), 2.5)
    129     }
    130 }