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
use crate::auth::oidc::OidcAuthCfg;
use crate::cli::GlobalArgs;
use crate::service::ServiceConfig;
use actix_web::HttpRequest;
use clap::{ArgMatches, FromArgMatches};
use core::fmt::Display;
use figment::providers::{Env, Format, Toml};
use figment::Figment;
use log::info;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use std::env;
use std::path::PathBuf;

/// Application configuration singleton
pub fn app_config() -> &'static Figment {
    static CONFIG: OnceCell<Figment> = OnceCell::new();
    CONFIG.get_or_init(|| {
        let config = Figment::new()
            .merge(Toml::file(
                env::var("BBOX_CONFIG").unwrap_or("bbox.toml".to_string()),
            ))
            .merge(Env::prefixed("BBOX_").split("__"));
        if let Some(source) = config_source(&config) {
            // Logger is not initialized yet
            println!("Reading configuration from `{source}`");
            info!("Reading configuration from `{source}`");
        }
        config
    })
}

fn config_source(config: &Figment) -> &Option<figment::Source> {
    if let Some(meta) = config.metadata().next() {
        &meta.source
    } else {
        &None
    }
}

/// Base directory for files referenced in configuration
pub fn base_dir() -> PathBuf {
    let config = app_config();
    if let Some(source) = config_source(config)
        .as_ref()
        .and_then(|source| source.file_path())
    {
        source
            .parent()
            .expect("absolute config file path")
            .canonicalize()
            .expect("absolute config file path")
    } else {
        env::current_dir().expect("current working dir")
    }
}

/// Full path relative to application base directory
pub fn app_dir(path: impl Into<PathBuf>) -> PathBuf {
    let path = path.into();
    if path.is_relative() {
        base_dir().join(path)
    } else {
        path
    }
}

#[derive(thiserror::Error, Debug)]
pub enum ConfigError {
    #[error("Configuration error")]
    ConfigurationError,
}

pub fn from_config_or_exit<'a, T: Default + Deserialize<'a>>(tag: &str) -> T {
    let config = app_config();
    match config.extract_inner(tag) {
        Ok(config) => config,
        Err(err) => {
            config_error_exit(err);
            Default::default()
        }
    }
}

pub fn from_config_root_or_exit<'a, T: Default + Deserialize<'a>>() -> T {
    let config = app_config();
    match config.extract() {
        Ok(config) => config,
        Err(err) => {
            config_error_exit(err);
            Default::default()
        }
    }
}

pub fn from_config_opt_or_exit<'a, T: Deserialize<'a>>(tag: &str) -> Option<T> {
    let config = app_config();
    config
        .find_value(tag)
        .map(|_| config.extract_inner(tag).unwrap_or_else(error_exit))
        .ok()
}

pub fn config_error_exit<T: Display>(err: T) {
    eprintln!("Error during initialization: {err}");
    std::process::exit(1);
}

pub fn error_exit<T: Display, R>(err: T) -> R {
    eprintln!("Error during initialization: {err}");
    std::process::exit(1);
}

// -- Common configuration --

#[derive(Deserialize, Default)]
pub struct CoreServiceCfg {
    pub webserver: Option<WebserverCfg>,
    pub metrics: Option<MetricsCfg>,
    #[serde(default)]
    pub datasource: Vec<NamedDatasourceCfg>,
    pub auth: Option<AuthCfg>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(default, deny_unknown_fields)]
pub struct WebserverCfg {
    /// IP address of interface and port to bind web server (e.g. 0.0.0.0:8080 for all)
    pub server_addr: String,
    /// Number of parallel web server threads. Defaults to number of available logical CPUs
    worker_threads: Option<usize>,
    public_server_url: Option<String>,
    /// Log level (Default: info)
    pub loglevel: Option<Loglevel>,
    pub tls_cert: Option<String>,
    pub tls_key: Option<String>,
    pub cors: Option<CorsCfg>,
}

#[derive(clap::ValueEnum, Deserialize, Serialize, Clone, Debug)]
pub enum Loglevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct CorsCfg {
    pub allow_all_origins: bool,
    // #[serde(rename = "allowed_origin")]
    // pub allowed_origins: Vec<String>,
}

impl ServiceConfig for CoreServiceCfg {
    fn initialize(args: &ArgMatches) -> Result<Self, ConfigError> {
        let mut cfg: CoreServiceCfg = from_config_root_or_exit();
        if let Ok(args) = GlobalArgs::from_arg_matches(args) {
            if let Some(loglevel) = args.loglevel {
                let mut webserver = cfg.webserver.unwrap_or_default();
                webserver.loglevel = Some(loglevel);
                cfg.webserver = Some(webserver);
            }
        };
        Ok(cfg)
    }
}

impl CoreServiceCfg {
    pub fn loglevel(&self) -> Option<Loglevel> {
        self.webserver.as_ref().and_then(|cfg| cfg.loglevel.clone())
    }
}

impl Default for WebserverCfg {
    fn default() -> Self {
        let cors = if cfg!(debug_assertions) {
            // Enable CORS for debug build
            Some(CorsCfg {
                allow_all_origins: true,
            })
        } else {
            None
        };
        WebserverCfg {
            server_addr: "127.0.0.1:8080".to_string(),
            worker_threads: None,
            public_server_url: None,
            loglevel: None,
            tls_cert: None,
            tls_key: None,
            cors,
        }
    }
}

impl WebserverCfg {
    pub fn worker_threads(&self) -> usize {
        self.worker_threads.unwrap_or(num_cpus::get())
    }
    pub fn public_server_url(&self, req: HttpRequest) -> String {
        if let Some(url) = &self.public_server_url {
            url.clone()
        } else {
            let conninfo = req.connection_info();
            format!("{}://{}", conninfo.scheme(), conninfo.host(),)
        }
    }
}

#[derive(Deserialize, Serialize, Default, Clone, Debug)]
#[serde(default, deny_unknown_fields)]
pub struct AuthCfg {
    pub oidc: Option<OidcAuthCfg>,
}

// -- Metrics --

#[derive(Deserialize, Serialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub struct MetricsCfg {
    pub prometheus: Option<PrometheusCfg>,
    pub jaeger: Option<JaegerCfg>,
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct PrometheusCfg {
    pub path: String,
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct JaegerCfg {
    pub agent_endpoint: String,
}

impl MetricsCfg {
    pub fn from_config() -> Option<Self> {
        from_config_opt_or_exit("metrics")
    }
}

// -- Datasources --

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct NamedDatasourceCfg {
    pub name: String,
    #[serde(flatten)]
    pub datasource: DatasourceCfg,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub enum DatasourceCfg {
    // -- vector sources --
    #[serde(rename = "postgis")]
    Postgis(DsPostgisCfg),
    #[serde(rename = "gpkg")]
    Gpkg(DsGpkgCfg),
    // GdalData(GdalSource),
    // -- raster sources --
    WmsFcgi,
    #[serde(rename = "wms_proxy")]
    WmsHttp(WmsHttpSourceProviderCfg),
    // GdalData(GdalSource),
    // RasterData(GeorasterSource),
    // -- direct tile sources --
    #[serde(rename = "mbtiles")]
    Mbtiles,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct DsPostgisCfg {
    pub url: String,
    // pub pool: Option<u16>,
    // pub connection_timeout: Option<u64>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct DsGpkgCfg {
    pub path: PathBuf,
    // pub pool_min_connections(0)
    // pub pool_max_connections(8)
}

impl DsGpkgCfg {
    pub fn abs_path(&self) -> PathBuf {
        app_dir(&self.path)
    }
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct WmsHttpSourceProviderCfg {
    pub baseurl: String,
    pub format: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use figment::providers::Env;
    use serde::Deserialize;

    #[derive(Deserialize, Serialize, Debug)]
    struct Package {
        name: String,
    }

    #[test]
    fn toml_config() {
        let config = Figment::new()
            .merge(Toml::file("Cargo.toml"))
            .merge(Env::prefixed("CARGO_"));
        let package: Package = config.extract_inner("package").unwrap();
        assert_eq!(package.name, "bbox-core");
    }
}