• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

getdozer / dozer / 5954012408

23 Aug 2023 04:32PM UTC coverage: 75.86% (-0.2%) from 76.088%
5954012408

push

github

web-flow
chore: Move ContractService implementation to Contract (#1899)

* chore: Split `build.rs` to several files

* chore: Remove `serde` from `dozer-cli/Cargo.toml`

* chore: Move `ContractService` implementation to `Contract`

461 of 461 new or added lines in 8 files covered. (100.0%)

46996 of 61951 relevant lines covered (75.86%)

73804.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

25.37
/dozer-cli/src/cli/helper.rs
1
use crate::config_helper::combine_config;
2
use crate::errors::CliError;
3
use crate::errors::CliError::{ConfigurationFilePathNotProvided, FailedToFindConfigurationFiles};
4
use crate::errors::ConfigCombineError::CannotReadConfig;
5
use crate::errors::OrchestrationError;
6
use crate::simple::SimpleOrchestrator as Dozer;
7
use atty::Stream;
8
use dozer_types::models::config::default_cache_max_map_size;
9
use dozer_types::prettytable::{row, Table};
10
use dozer_types::serde_json;
11
use dozer_types::{models::config::Config, serde_yaml};
12
use handlebars::Handlebars;
13
use std::collections::BTreeMap;
14
use std::io::{self, Read};
15
use std::path::PathBuf;
16
use std::sync::Arc;
17
use tokio::runtime::Runtime;
18

×
19
pub async fn init_dozer(
×
20
    runtime: Arc<Runtime>,
×
21
    config_paths: Vec<String>,
×
22
    config_token: Option<String>,
×
23
    config_overrides: Vec<(String, serde_json::Value)>,
×
24
    ignore_pipe: bool,
×
25
    enable_progress: bool,
×
26
) -> Result<Dozer, CliError> {
×
27
    let mut config = load_config(config_paths, config_token, ignore_pipe).await?;
×
28

×
29
    config = apply_overrides(&config, config_overrides)?;
×
30

×
31
    let cache_max_map_size = config
×
32
        .cache_max_map_size
×
33
        .unwrap_or_else(default_cache_max_map_size);
×
34
    let page_size = page_size::get() as u64;
×
35
    config.cache_max_map_size = Some(cache_max_map_size / page_size * page_size);
×
36

×
37
    Ok(Dozer::new(config, runtime, enable_progress))
×
38
}
×
39

×
40
pub async fn list_sources(
×
41
    runtime: Arc<Runtime>,
×
42
    config_paths: Vec<String>,
×
43
    config_token: Option<String>,
×
44
    config_overrides: Vec<(String, serde_json::Value)>,
×
45
    ignore_pipe: bool,
×
46
    filter: Option<String>,
×
47
) -> Result<(), OrchestrationError> {
×
48
    let dozer = init_dozer(
×
49
        runtime,
×
50
        config_paths,
×
51
        config_token,
×
52
        config_overrides,
×
53
        ignore_pipe,
×
54
        false,
×
55
    )
×
56
    .await?;
×
57
    let connection_map = dozer.list_connectors()?;
×
58
    let mut table_parent = Table::new();
×
59
    for (connection_name, (tables, schemas)) in connection_map {
×
60
        let mut first_table_found = false;
×
61

×
62
        for (table, schema) in tables.into_iter().zip(schemas) {
×
63
            let name = table.schema.map_or(table.name.clone(), |schema_name| {
×
64
                format!("{schema_name}.{}", table.name)
×
65
            });
×
66

×
67
            if filter
×
68
                .as_ref()
×
69
                .map_or(true, |name_part| name.contains(name_part))
×
70
            {
×
71
                if !first_table_found {
×
72
                    table_parent.add_row(row!["Connection", "Table", "Columns"]);
×
73
                    first_table_found = true;
×
74
                }
×
75
                let schema_table = schema.schema.print();
×
76

×
77
                table_parent.add_row(row![connection_name, name, schema_table]);
×
78
            }
×
79
        }
80

×
81
        if first_table_found {
×
82
            table_parent.add_empty_row();
×
83
        }
×
84
    }
×
85
    table_parent.printstd();
×
86
    Ok(())
×
87
}
×
88

×
89
async fn load_config(
×
90
    config_url_or_paths: Vec<String>,
×
91
    config_token: Option<String>,
×
92
    ignore_pipe: bool,
×
93
) -> Result<Config, CliError> {
×
94
    let read_stdin = atty::isnt(Stream::Stdin) && !ignore_pipe;
×
95
    let first_config_path = config_url_or_paths.get(0);
×
96
    match first_config_path {
×
97
        None => Err(ConfigurationFilePathNotProvided),
×
98
        Some(path) => {
×
99
            if path.starts_with("https://") || path.starts_with("http://") {
×
100
                load_config_from_http_url(path, config_token).await
×
101
            } else {
×
102
                load_config_from_file(config_url_or_paths, read_stdin)
×
103
            }
104
        }
105
    }
×
106
}
×
107

×
108
async fn load_config_from_http_url(
×
109
    config_url: &str,
×
110
    config_token: Option<String>,
×
111
) -> Result<Config, CliError> {
×
112
    let client = reqwest::Client::new();
×
113
    let mut get_request = client.get(config_url);
×
114
    if let Some(token) = config_token {
×
115
        get_request = get_request.bearer_auth(token);
×
116
    }
×
117
    let response: reqwest::Response = get_request.send().await?.error_for_status()?;
×
118
    let contents = response.text().await?;
×
119
    parse_config(&contents)
×
120
}
×
121

×
122
pub fn load_config_from_file(
×
123
    config_path: Vec<String>,
×
124
    read_stdin: bool,
×
125
) -> Result<Config, CliError> {
×
126
    let stdin_path = PathBuf::from("<stdin>");
×
127
    let input = if read_stdin {
×
128
        let mut input = String::new();
×
129
        io::stdin()
×
130
            .read_to_string(&mut input)
×
131
            .map_err(|e| CannotReadConfig(stdin_path, e))?;
×
132
        Some(input)
×
133
    } else {
×
134
        None
×
135
    };
136

×
137
    let config_template = combine_config(config_path.clone(), input)?;
×
138
    match config_template {
×
139
        Some(template) => parse_config(&template),
×
140
        None => Err(FailedToFindConfigurationFiles(config_path.join(", "))),
×
141
    }
×
142
}
×
143

×
144
fn parse_config(config_template: &str) -> Result<Config, CliError> {
×
145
    let mut handlebars = Handlebars::new();
×
146
    handlebars
×
147
        .register_template_string("config", config_template)
×
148
        .map_err(|e| CliError::FailedToParseYaml(Box::new(e)))?;
×
149

×
150
    let mut data = BTreeMap::new();
×
151

×
152
    for (key, value) in std::env::vars() {
×
153
        data.insert(key, value);
×
154
    }
×
155

×
156
    let config_str = handlebars
×
157
        .render("config", &data)
×
158
        .map_err(|e| CliError::FailedToParseYaml(Box::new(e)))?;
×
159

×
160
    let config: Config = serde_yaml::from_str(&config_str)
×
161
        .map_err(|e: serde_yaml::Error| CliError::FailedToParseYaml(Box::new(e)))?;
×
162

×
163
    Ok(config)
×
164
}
×
165

166
/// Convert `config` to JSON, apply JSON pointer overrides, then convert back to `Config`.
×
167
fn apply_overrides(
2✔
168
    config: &Config,
2✔
169
    config_overrides: Vec<(String, serde_json::Value)>,
2✔
170
) -> Result<Config, CliError> {
2✔
171
    let mut config_json = serde_json::to_value(config).map_err(CliError::SerializeConfigToJson)?;
2✔
172

×
173
    for (pointer, value) in config_overrides {
4✔
174
        if let Some(pointee) = config_json.pointer_mut(&pointer) {
2✔
175
            *pointee = value;
2✔
176
        } else {
2✔
177
            return Err(CliError::MissingConfigOverride(pointer));
×
178
        }
179
    }
180

181
    // Directly convert `config_json` to `Config` fails, not sure why.
×
182
    let config_json_string =
2✔
183
        serde_json::to_string(&config_json).map_err(CliError::SerializeConfigToJson)?;
2✔
184
    let config: Config =
2✔
185
        serde_json::from_str(&config_json_string).map_err(CliError::DeserializeConfigFromJson)?;
2✔
186

×
187
    Ok(config)
2✔
188
}
2✔
189

190
pub const LOGO: &str = r"
191
.____   ___ __________ ____
192
|  _ \ / _ \__  / ____|  _ \
193
| | | | | | |/ /|  _| | |_) |
194
| |_| | |_| / /_| |___|  _ <
195
|____/ \___/____|_____|_| \_\
196
";
197

198
pub const DESCRIPTION: &str = r#"Open-source platform to build, publish and manage blazing-fast real-time data APIs in minutes. 
199

200
 If no sub commands are passed, dozer will bring up both app and api services.
201
"#;
202

203
#[cfg(test)]
204
mod tests {
205
    use dozer_types::models::{api_config::ApiConfig, api_security::ApiSecurity};
206

207
    use super::*;
208

×
209
    #[test]
1✔
210
    fn test_override_top_level() {
1✔
211
        let mut config = Config {
1✔
212
            app_name: "test_override_top_level".to_string(),
1✔
213
            ..Default::default()
1✔
214
        };
1✔
215
        config.sql = Some("sql1".to_string());
1✔
216
        let sql = "sql2".to_string();
1✔
217
        let config = apply_overrides(
1✔
218
            &config,
1✔
219
            vec![("/sql".to_string(), serde_json::to_value(&sql).unwrap())],
1✔
220
        )
1✔
221
        .unwrap();
1✔
222
        assert_eq!(config.sql.unwrap(), sql);
1✔
223
    }
1✔
224

×
225
    #[test]
1✔
226
    fn test_override_nested() {
1✔
227
        let mut config = Config {
1✔
228
            app_name: "test_override_nested".to_string(),
1✔
229
            ..Default::default()
1✔
230
        };
1✔
231
        config.api = Some(ApiConfig {
1✔
232
            api_security: Some(ApiSecurity::Jwt("secret1".to_string())),
1✔
233
            ..Default::default()
1✔
234
        });
1✔
235
        let api_security = ApiSecurity::Jwt("secret2".to_string());
1✔
236
        let config = apply_overrides(
1✔
237
            &config,
1✔
238
            vec![(
1✔
239
                "/api/api_security".to_string(),
1✔
240
                serde_json::to_value(&api_security).unwrap(),
1✔
241
            )],
1✔
242
        )
1✔
243
        .unwrap();
1✔
244
        assert_eq!(config.api.unwrap().api_security.unwrap(), api_security);
1✔
245
    }
1✔
246
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc