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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! This module consists of types and functions for creating configuration of [`super::CargoLib`].
//!
//! Configuration may be represented by a JSON like:
//! ```
//! # use wildland_cargo_lib::api::config::parse_config;
//! #
//! let config_json = r#"{
//!     "log_level": "trace",
//!     "log_use_ansi": false,
//!     "log_file_enabled": true,
//!     "log_file_path": "cargo_lib_log",
//!     "log_file_rotate_directory": ".",
//!     "evs_url": "some_url",
//!     "redis_connection_string": "redis://127.0.0.1/0",
//!     "gql_url": "http://localhost:8000/graphql/"
//! }"#;
//!
//! let _  = parse_config(config_json.as_bytes().to_vec()).unwrap();
//! ```
//!
//! It can be also provided via type implementing [`CargoCfgProvider`].

use std::path::PathBuf;
use std::str::FromStr;

use derivative::Derivative;
use serde::de::{Error, Unexpected};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use tracing::Level;
use url::Url;

const DEV_DEFAULT_EVS_URL: &str = "https://evs.cargo.wildland.dev/";

#[repr(C)]
pub enum FoundationCloudMode {
    Dev,
}

impl From<FoundationCloudMode> for FoundationStorageApiConfig {
    fn from(mode: FoundationCloudMode) -> Self {
        match mode {
            FoundationCloudMode::Dev => FoundationStorageApiConfig {
                evs_url: DEV_DEFAULT_EVS_URL.to_string(),
            },
        }
    }
}

pub trait CargoCfgProvider {
    fn get_use_logger(&self) -> bool;
    /// Must return one of (case-insensitive):
    /// - "error"
    /// - "warn"
    /// - "info"
    /// - "debug"
    /// - "trace"
    /// or number equivalent:
    /// - "1" - error
    /// - "2" - warn
    /// - "3" - info
    /// - "4" - debug
    /// - "5" - trace
    fn get_log_level(&self) -> String;
    fn get_log_use_ansi(&self) -> bool;
    fn get_log_file_enabled(&self) -> bool;
    fn get_log_file_path(&self) -> Option<String>;
    fn get_log_file_rotate_directory(&self) -> Option<String>;

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    fn get_oslog_category(&self) -> Option<String>;
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    fn get_oslog_subsystem(&self) -> Option<String>;

    fn get_foundation_cloud_env_mode(&self) -> FoundationCloudMode;

    fn get_catlib_gql_url(&self) -> String;

    /// Must return a valid Redis URI which is then used as a connection string
    /// for the redis Multi-device State backend.
    ///
    /// The URI must have the following format
    ///
    /// - w/o TLS
    ///
    /// ```none
    /// redis :// [[username :] password@] host [:port][/database]
    ///         [?[timeout=timeout[d|h|m|s|ms|us|ns]]
    /// ```
    ///
    /// - w/ TLS
    ///
    /// ```none
    /// rediss :// [[username :] password@] host [: port][/database]
    ///          [?[timeout=timeout[d|h|m|s|ms|us|ns]]
    /// ```
    ///
    /// Example:
    ///
    /// ```none
    /// redis://127.0.0.1:6379/0
    /// ```
    fn get_redis_url_for_multidevice_state(&self) -> String;
}

#[derive(PartialEq, Eq, Error, Debug, Clone)]
#[repr(C)]
pub enum ParseConfigError {
    #[error("invalid redis URI: {0}")]
    IncorrectRedisURL(String),
    #[error("Config parse error: {0}")]
    Error(String),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Derivative)]
#[derivative(Default(new = "true"))]
pub struct FoundationStorageApiConfig {
    #[serde(default = "default_evs_url")]
    #[derivative(Default(value = "default_evs_url()"))]
    pub evs_url: String,
}

fn default_evs_url() -> String {
    // TODO for now default is DEV
    // in the future we might distinguish debug and release builds in order to choose environment
    DEV_DEFAULT_EVS_URL.to_owned()
}

fn bool_default_as_true() -> bool {
    true
}

fn bool_default_as_false() -> bool {
    false
}

fn serde_logger_default_path() -> PathBuf {
    PathBuf::from("cargo_lib_log")
}

fn serde_logger_default_rot_dir() -> PathBuf {
    PathBuf::from(".")
}

/// Structure representing configuration of [`super::CargoLib`].
/// It is used to create [`super::CargoLib`] instance.
/// It is created from JSON or from type implementing [`CargoCfgProvider`].
/// This structure provides default values for all fields and can be constructed
/// by either LoggerConfig::new() or LoggerConfig::default(). Those two calls
/// are equivalent to each other.
/// ```
/// # use wildland_cargo_lib::api::config::parse_config;
/// #
/// let config_json = r#"
/// {
///     "log_level": "debug",
///     "log_use_ansi": true,
///     "log_file_path": "some_name",
///     "log_file_rotate_directory": ".",
///     "log_file_enabled": true,
///     "evs_url": "some_url",
///     "redis_connection_string": "redis://127.0.0.1/0",
///     "gql_url": "http://localhost:8000/graphql/"
/// }
/// "#;
/// let parsed_cfg = parse_config(config_json.as_bytes().to_vec()).unwrap();
///
///
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Derivative)]
#[derivative(Default(new = "true"))]
pub struct LoggerConfig {
    /// switch to disable the logger facility.
    /// If set to false, the logger will be disabled.
    /// usefull for cases where the client wants to use its own tracing
    /// subscriber object or want to enable it from the outside.
    /// Default: true
    ///
    /// Most users will want to leave it defaulted to true, especially users
    /// of the bindings, as they will not be able to create subscriber
    /// externally.
    ///
    /// In case its false, all the log configs are not used nor the subscriber
    /// is created.
    #[serde(default = "bool_default_as_true")]
    #[derivative(Default(value = "true"))]
    pub use_logger: bool,

    /// Minimum level of messages to get logged
    #[serde(deserialize_with = "log_level_deserialize")]
    #[serde(serialize_with = "log_level_serialize")]
    #[derivative(Default(value = "Level::INFO"))]
    pub log_level: Level,

    /// If Enabled, the logger will use ansi sequences to style text
    /// not all platforms and receivers do support this feature. False by default.
    #[serde(default = "bool_default_as_false")]
    #[derivative(Default(value = "false"))]
    pub log_use_ansi: bool,

    /// Enables or disables file logging.
    #[serde(default = "bool_default_as_false")]
    #[derivative(Default(value = "false"))]
    pub log_file_enabled: bool,

    /// File describing where log entries should be mirrored to. This part
    /// defines the file path of the currently active log file.
    /// defaults to `cargolib_log`
    #[serde(default = "serde_logger_default_path")]
    #[derivative(Default(value = "serde_logger_default_path()"))]
    pub log_file_path: PathBuf,

    /// File describing where log entries should be mirrored to. This part
    /// defines the file directory where the rotation will happen.
    /// defaults to the current working directory.
    #[serde(default = "serde_logger_default_rot_dir")]
    #[derivative(Default(value = "serde_logger_default_rot_dir()"))]
    pub log_file_rotate_directory: PathBuf,

    /// Name of the system.log category. If Some() provided together with
    /// oslog_subsystem category, enables the oslog facility. If OsLog is enabled,
    /// then all other facilities are not initialized.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    #[derivative(Default(value = "None"))]
    pub oslog_category: Option<String>,

    /// Name of the system.log subsystem. If Some() provided together with
    /// oslog_category, enables the oslog facility. If OsLog is enabled,
    /// then all other facilities are not initialized.

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    #[derivative(Default(value = "None"))]
    pub oslog_subsystem: Option<String>,
}

impl LoggerConfig {
    /// Helper function used to determine platform capabilities
    /// Whenever the os log facilities are available and properly configured,
    /// returns `true`. However if the configuration does not contain all the data
    /// necessary to start the logger or the platform does not support logging
    /// to the OsLog (i.e. linux,windows) then `false` is returned.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub fn is_oslog_eligible(&self) -> bool {
        if self.oslog_category.is_some() && self.oslog_subsystem.is_some() {
            return true;
        }
        false
    }

    /// Helper function used to determine platform capabilities
    /// Whenever the file log facilities are available and properly configured,
    /// returns `true`. However if the configuration uses paths that do not exist
    /// we will fail to initialize the logger and return `false`.
    pub fn is_file_eligible(&self) -> bool {
        if !self.log_file_enabled {
            return false;
        }

        let filepath = self.log_file_path.clone();
        let dirpath = self.log_file_rotate_directory.clone();

        // if filepaths are not existing, whetever provided or defaults, we are
        // not eligible to start file logging subscriber
        if !filepath.exists() || !dirpath.exists() {
            std::eprintln!("file log paths do not exist, we failed to create logging subscriber");
            return false;
        }

        true
    }
}

/// Structure used to define configuration parameters for the Catalog
/// backend.
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Derivative)]
#[derivative(Default(new = "true"))]
pub struct CatlibConfig {
    pub gql_url: String,
}

/// Redis backend configuration struct.
///
/// - `connection_string` parameter must be a valid redis URI, ie.
///
/// ### Redis w/o TLS
///
/// ```none
/// redis :// [[username :] password@] host [:port][/database]
///         [?[timeout=timeout[d|h|m|s|ms|us|ns]]
/// ```
///
/// ### Redis w/ TLS
///
/// ```none
/// rediss :// [[username :] password@] host [: port][/database]
///          [?[timeout=timeout[d|h|m|s|ms|us|ns]]
/// ```
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Derivative)]
#[derivative(Default(new = "true"))]
pub struct RedisConfig {
    #[serde(rename(deserialize = "redis_connection_string"))]
    #[serde(deserialize_with = "validate_redis_uri")]
    pub connection_string: String,
}

fn validate_redis_url(url: &Url) -> Result<(), ParseConfigError> {
    match url.scheme() {
        "redis" | "rediss" => Ok(()),
        _ => Err(ParseConfigError::IncorrectRedisURL(
            "Only redis and rediss schemes are supported".into(),
        )),
    }
}

fn validate_redis_uri<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let value = String::deserialize(deserializer)?;
    let redis_url = Url::parse(value.as_str()).map_err(|e| {
        Error::invalid_value(
            Unexpected::Str(&value),
            &format!("a valid redis URI. Encountered {e}").as_str(),
        )
    })?;
    validate_redis_url(&redis_url).map_err(|e| {
        Error::invalid_value(
            Unexpected::Str(&value),
            &format!("a valid redis URI. Encountered {e}").as_str(),
        )
    })?;

    Ok(value)
}

/// Helper function for handling deserializing `log_level` field
fn log_level_deserialize<'de, D>(deserializer: D) -> Result<Level, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Level::from_str(s.as_ref()).map_err(|_e| {
        Error::invalid_value(Unexpected::Str(&s), &"trace | debug | info | warn | error")
    })
}

/// Helper function for handling serializing `log_level` field
/// its not provieded by tracing for some reason
#[allow(dead_code)] // not really a dead code
fn log_level_serialize<S: Serializer>(
    level: &tracing::Level,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    // 3 is the number of fields in the struct.
    match *level {
        Level::TRACE => serializer.serialize_unit_variant("LevelInner", 0, "Trace"),
        Level::DEBUG => serializer.serialize_unit_variant("LevelInner", 1, "Debug"),
        Level::INFO => serializer.serialize_unit_variant("LevelInner", 2, "Info"),
        Level::WARN => serializer.serialize_unit_variant("LevelInner", 3, "Warn"),
        Level::ERROR => serializer.serialize_unit_variant("LevelInner", 4, "Error"),
    }
}

#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Derivative)]
pub struct UserConfig {
    #[serde(flatten)]
    pub redis_config: RedisConfig,
}

/// Structure representing configuration for [`super::CargoLib`] initialization.
///
/// It can be created outside of Rust in the following ways:
/// - by implementing [`CargoCfgProvider`] and calling [`collect_config`] function with that type as an argument
/// - calling [`parse_config`]
///
#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
pub struct CargoConfig {
    #[serde(flatten)]
    pub fsa_config: FoundationStorageApiConfig,
    #[serde(flatten)]
    pub logger_config: LoggerConfig,
    #[serde(flatten)]
    pub catlib_config: CatlibConfig,
    #[serde(flatten)]
    pub multidevice_state: UserConfig,
}

impl CargoConfig {
    pub fn override_evs_url(&mut self, new_evs_url: String) {
        self.fsa_config.evs_url = new_evs_url;
    }
}

impl TryFrom<Url> for RedisConfig {
    type Error = ParseConfigError;

    fn try_from(url: Url) -> Result<Self, Self::Error> {
        validate_redis_url(&url)?;

        Ok(RedisConfig {
            connection_string: url.to_string(),
        })
    }
}

/// Uses an implementation of [`CargoCfgProvider`] to collect a configuration storing structure ([`CargoConfig`])
/// which then can be passed to [`super::cargo_lib::create_cargo_lib`] in order to instantiate main API object ([`super::CargoLib`])
///
#[tracing::instrument(level = "debug", skip_all)]
pub fn collect_config(
    config_provider: Box<dyn CargoCfgProvider>,
) -> Result<CargoConfig, ParseConfigError> {
    let redis_url_multidevice = Url::parse(
        config_provider
            .get_redis_url_for_multidevice_state()
            .as_str(),
    )
    .map_err(|e| ParseConfigError::IncorrectRedisURL(e.to_string()))?;

    Ok(CargoConfig {
        logger_config: LoggerConfig {
            use_logger: config_provider.get_use_logger(),
            log_level: Level::from_str(config_provider.get_log_level().as_str())
                .map_err(|e| ParseConfigError::Error(e.to_string()))?,
            log_use_ansi: config_provider.get_log_use_ansi(),
            log_file_path: PathBuf::from(
                config_provider
                    .get_log_file_path()
                    .unwrap_or_else(|| serde_logger_default_path().to_string_lossy().to_string()),
            ),
            log_file_enabled: config_provider.get_log_file_enabled(),
            log_file_rotate_directory: PathBuf::from(
                config_provider
                    .get_log_file_rotate_directory()
                    .unwrap_or_else(|| {
                        serde_logger_default_rot_dir().to_string_lossy().to_string()
                    }),
            ),
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            oslog_category: config_provider.get_oslog_category(),

            #[cfg(any(target_os = "macos", target_os = "ios"))]
            oslog_subsystem: config_provider.get_oslog_subsystem(),
        },
        fsa_config: config_provider.get_foundation_cloud_env_mode().into(),
        catlib_config: CatlibConfig {
            gql_url: config_provider.get_catlib_gql_url(),
        },
        multidevice_state: UserConfig {
            redis_config: redis_url_multidevice.try_into()?,
        },
    })
}

/// Parses bytes representing JSON formatted configuration of [`super::CargoLib`]
/// into an instance of [`CargoConfig`]
/// The `settings` must be a string with JSON formatted configuration.
///
#[tracing::instrument(level = "debug", skip_all)]
pub fn parse_config(raw_content: Vec<u8>) -> Result<CargoConfig, ParseConfigError> {
    let parsed: CargoConfig =
        serde_json::from_slice(&raw_content).map_err(|e| ParseConfigError::Error(e.to_string()))?;
    Ok(parsed)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use tracing::Level;

    use super::{
        CargoConfig,
        CatlibConfig,
        FoundationStorageApiConfig,
        LoggerConfig,
        RedisConfig,
        UserConfig,
    };

    #[test]
    fn test_parsing_debug_config() {
        let config_str = r#"{
            "log_level": "trace",
            "log_use_ansi": false,
            "log_file_enabled": true,
            "log_file_path": "cargo_lib_log",
            "log_file_rotate_directory": ".",
            "evs_url": "some_url",
            "gql_url": "http://localhost:8000/graphql/",
            "redis_connection_string": "redis://127.0.0.1/0"
        }"#;

        let config: CargoConfig = serde_json::from_str(config_str).unwrap();

        assert_eq!(
            config,
            CargoConfig {
                fsa_config: FoundationStorageApiConfig {
                    evs_url: "some_url".to_owned(),
                },
                logger_config: LoggerConfig {
                    use_logger: true,
                    log_level: Level::TRACE,
                    log_use_ansi: false,
                    log_file_path: PathBuf::from("cargo_lib_log"),
                    log_file_rotate_directory: PathBuf::from("."),
                    log_file_enabled: true,
                    #[cfg(any(target_os = "macos", target_os = "ios"))]
                    oslog_category: None,
                    #[cfg(any(target_os = "macos", target_os = "ios"))]
                    oslog_subsystem: None,
                },
                catlib_config: CatlibConfig {
                    gql_url: "http://localhost:8000/graphql/".into(),
                },
                multidevice_state: UserConfig {
                    redis_config: RedisConfig {
                        connection_string: "redis://127.0.0.1/0".into()
                    }
                }
            }
        )
    }

    #[test]
    fn test_parsing_prod_config() {
        let config_str = r#"{
            "log_level": "trace",
            "log_use_ansi": true,
            "log_file_enabled": false,
            "gql_url": "http://localhost:8000/graphql/",
            "redis_connection_string": "redis://127.0.0.1/0"
        }"#;

        let config: CargoConfig = serde_json::from_str(config_str).unwrap();

        assert_eq!(
            config,
            CargoConfig {
                fsa_config: FoundationStorageApiConfig {
                    evs_url: "https://evs.cargo.wildland.dev/".to_owned(),
                },
                logger_config: LoggerConfig {
                    use_logger: true,
                    log_level: Level::TRACE,
                    log_use_ansi: true,
                    log_file_path: LoggerConfig::default().log_file_path,
                    log_file_rotate_directory: LoggerConfig::default().log_file_rotate_directory,
                    log_file_enabled: false,
                    #[cfg(any(target_os = "macos", target_os = "ios"))]
                    oslog_category: None,
                    #[cfg(any(target_os = "macos", target_os = "ios"))]
                    oslog_subsystem: None,
                },
                catlib_config: CatlibConfig {
                    gql_url: "http://localhost:8000/graphql/".into(),
                },
                multidevice_state: UserConfig {
                    redis_config: RedisConfig {
                        connection_string: "redis://127.0.0.1/0".into()
                    }
                }
            }
        )
    }

    #[test]
    fn test_invalid_redis_string() {
        let config_str = r#"{
            "redis_connection_string": "rediZZ://127.0.0.1/0"
        }"#;

        let err: Result<CargoConfig, _> = serde_json::from_str(config_str);
        err.unwrap_err();

        let config_str = r#"{
            "redis_connection_string": "redis://*/0"
        }"#;

        let err: Result<CargoConfig, _> = serde_json::from_str(config_str);
        err.unwrap_err();

        let config_str = r#"{
            "redis_connection_string": "redis://127.0.0.1:/"
        }"#;

        let err: Result<CargoConfig, _> = serde_json::from_str(config_str);
        err.unwrap_err();
    }
}