Files
rust-work/mongo-proxy/src/config.rs
T

140 lines
3.6 KiB
Rust

use anyhow::{Result, bail};
use serde::Deserialize;
use std::fs;
#[derive(Debug, Deserialize, Clone)]
pub struct ServerConfig {
pub port: u16,
#[serde(default = "default_host")]
pub host: String,
}
fn default_host() -> String {
"127.0.0.1".to_string()
}
#[derive(Debug, Deserialize, Clone)]
pub struct PoolConfig {
#[serde(default = "default_idle_timeout")]
pub idle_timeout_secs: u64,
#[serde(default = "default_check_interval")]
pub check_interval_secs: u64,
}
fn default_idle_timeout() -> u64 { 300 }
fn default_check_interval() -> u64 { 60 }
impl Default for PoolConfig {
fn default() -> Self {
Self {
idle_timeout_secs: default_idle_timeout(),
check_interval_secs: default_check_interval(),
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct ConnectionConfig {
pub name: String,
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
pub database: String,
#[serde(default)]
pub username: Option<String>,
#[serde(default)]
pub password: Option<String>,
#[serde(default)]
pub auth_source: Option<String>,
}
fn default_port() -> u16 { 27017 }
#[derive(Debug, Deserialize)]
pub struct Config {
#[serde(default = "default_server")]
pub server: ServerConfig,
#[serde(default)]
pub pool: PoolConfig,
pub connections: Vec<ConnectionConfig>,
}
fn default_server() -> ServerConfig {
ServerConfig {
port: 3309,
host: "127.0.0.1".to_string(),
}
}
impl Config {
pub fn from_file(path: &str) -> Result<Self> {
let content = fs::read_to_string(path)?;
let config: Config = toml::from_str(&content)?;
config.validate()?;
Ok(config)
}
#[allow(dead_code)]
pub fn load() -> Result<Self> {
let paths = [
"mongo-proxy.toml",
"./config/mongo-proxy.toml",
&format!("{}/.mongo-proxy.toml", std::env::var("HOME").unwrap_or_default()),
];
for path in &paths {
if std::path::Path::new(path).exists() {
return Self::from_file(path);
}
}
bail!("Config file not found. Create mongo-proxy.toml in current directory or use --config flag")
}
fn validate(&self) -> Result<()> {
let mut names = std::collections::HashSet::new();
for conn in &self.connections {
if conn.name.is_empty() {
bail!("Connection name cannot be empty");
}
if names.contains(&conn.name) {
bail!("Duplicate connection name: {}", conn.name);
}
names.insert(conn.name.clone());
}
Ok(())
}
}
impl ConnectionConfig {
pub fn build_uri(&self) -> String {
let cred = match (&self.username, &self.password) {
(Some(user), Some(pass)) => format!("{}:{}@", user, urlencoding(pass)),
_ => String::new(),
};
let auth = match &self.auth_source {
Some(src) => format!("?authSource={}", src),
None => String::new(),
};
format!(
"mongodb://{}{}:{}/{}{}",
cred, self.host, self.port, self.database, auth
)
}
}
fn urlencoding(s: &str) -> String {
let mut result = String::new();
for c in s.chars() {
match c {
'@' => result.push_str("%40"),
':' => result.push_str("%3A"),
'/' => result.push_str("%2F"),
'?' => result.push_str("%3F"),
'#' => result.push_str("%23"),
_ => result.push(c),
}
}
result
}