1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

use clap::Parser;
use snafu::{ResultExt, Snafu};

#[derive(Clone, Debug, Parser)]
#[command(name = "sc_config")]
#[command(about = "Configuration for state-client-lib")]
pub struct SCEnvCLIConfig {
    /// URL of state-fold server grpc
    #[arg(long, env)]
    pub sc_grpc_endpoint: Option<String>,

    /// Default confirmations
    #[arg(long, env)]
    pub sc_default_confirmations: Option<usize>,

    /// Maximum size of a decoded message
    #[arg(long, env, default_value_t = 100 * 1024 * 1024)]
    pub ss_max_decoding_message_size: usize,
}

#[derive(Clone, Debug)]
pub struct SCConfig {
    pub grpc_endpoint: String,
    pub default_confirmations: usize,
    pub max_decoding_message_size: usize,
}

#[derive(Debug, Snafu)]
pub enum Error {
    #[snafu(display("Configuration missing server manager endpoint"))]
    MissingEndpoint {},
}

pub type Result<T> = std::result::Result<T, Error>;

const DEFAULT_DEFAULT_CONFIRMATIONS: usize = 7;

impl SCConfig {
    pub fn initialize_from_args() -> Result<Self> {
        let env_cli_config = SCEnvCLIConfig::parse();
        Self::initialize(env_cli_config)
    }

    pub fn initialize(env_cli_config: SCEnvCLIConfig) -> Result<Self> {
        let grpc_endpoint = env_cli_config
            .sc_grpc_endpoint
            .ok_or(snafu::NoneError)
            .context(MissingEndpointSnafu)?;

        let default_confirmations = env_cli_config
            .sc_default_confirmations
            .unwrap_or(DEFAULT_DEFAULT_CONFIRMATIONS);

        let max_decoding_message_size = env_cli_config.ss_max_decoding_message_size;

        Ok(SCConfig {
            grpc_endpoint,
            default_confirmations,
            max_decoding_message_size,
        })
    }
}