quickwit_common/
lib.rs

1// Copyright (C) 2021 Quickwit, Inc.
2//
3// Quickwit is offered under the AGPL v3.0 and as commercial software.
4// For commercial licensing, contact us at hello@quickwit.io.
5//
6// AGPL:
7// This program is free software: you can redistribute it and/or modify
8// it under the terms of the GNU Affero General Public License as
9// published by the Free Software Foundation, either version 3 of the
10// License, or (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU Affero General Public License for more details.
16//
17// You should have received a copy of the GNU Affero General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20mod checklist;
21mod coolid;
22pub mod fs;
23pub mod metrics;
24pub mod net;
25pub mod rand;
26pub mod uri;
27
28use std::fmt::Debug;
29use std::ops::Range;
30use std::str::FromStr;
31
32pub use checklist::{print_checklist, run_checklist, BLUE_COLOR, GREEN_COLOR, RED_COLOR};
33pub use coolid::new_coolid;
34use tracing::{error, info};
35
36pub fn chunk_range(range: Range<usize>, chunk_size: usize) -> impl Iterator<Item = Range<usize>> {
37    range.clone().step_by(chunk_size).map(move |block_start| {
38        let block_end = (block_start + chunk_size).min(range.end);
39        block_start..block_end
40    })
41}
42
43pub fn into_u64_range(range: Range<usize>) -> Range<u64> {
44    range.start as u64..range.end as u64
45}
46
47pub fn setup_logging_for_tests() {
48    use std::sync::Once;
49    static INIT: Once = Once::new();
50    INIT.call_once(|| {
51        env_logger::builder().format_timestamp(None).init();
52    });
53}
54
55pub fn split_file(split_id: &str) -> String {
56    format!("{}.split", split_id)
57}
58
59pub fn get_from_env<T: FromStr + Debug>(key: &str, default_value: T) -> T {
60    if let Ok(value_str) = std::env::var(key) {
61        if let Ok(value) = T::from_str(&value_str) {
62            info!(value=?value, "Setting `{}` from environment", key);
63            return value;
64        } else {
65            error!(value_str=%value_str, "Failed to parse `{}` from environment", key);
66        }
67    }
68    info!(value=?default_value, "Setting `{}` from default", key);
69    default_value
70}
71
72#[cfg(test)]
73mod tests {
74    #[test]
75    fn test_get_from_env() {
76        const TEST_KEY: &str = "TEST_KEY";
77        assert_eq!(super::get_from_env(TEST_KEY, 10), 10);
78        std::env::set_var(TEST_KEY, "15");
79        assert_eq!(super::get_from_env(TEST_KEY, 10), 15);
80        std::env::set_var(TEST_KEY, "1invalidnumber");
81        assert_eq!(super::get_from_env(TEST_KEY, 10), 10);
82    }
83}