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
use clap::Error;
use clap::Parser;
use compact_str::format_compact;
use compact_str::CompactString;
use influxdb::Client;

#[derive(Debug, Parser)]
pub struct InfluxDbConfig {
	#[clap(long, env = "INFLUXDB_HOST")]
	pub influxdb_host: CompactString,

	#[clap(long, env = "INFLUXDB_PORT", default_value_t = 8086)]
	pub influxdb_port: u16,

	#[clap(long, env = "INFLUXDB_USE_TLS", default_value_t = false)]
	pub influxdb_tls: bool,

	#[clap(long, env = "INFLUXDB_USERNAME")]
	pub influxdb_username: Option<CompactString>,

	#[clap(long, env = "INFLUXDB_PASSWORD", default_value = "")]
	pub influxdb_password: CompactString,

	#[clap(long, env = "INFLUXDB_DATABASE", default_value = "example")]
	pub influxdb_database: CompactString,
}

impl InfluxDbConfig {
	// Consumes self, but doesn't strictly _need_ to.  Can switch it to borrow
	//    self.database, self.username, and self.password if there's a use
	//    case that that would satisfy.
	#[inline]
	pub fn into_client(self) -> Client {
		let client = Client::new(self.get_url(), self.influxdb_database);
		match self.influxdb_username {
			None => client,
			Some(v) => client.with_auth(v, self.influxdb_password)
		}
	}

	#[inline]
	pub fn client(&self) -> Client {
		let client = Client::new(self.get_url(), self.influxdb_database.clone());
		match self.influxdb_username.as_ref() {
			None => client,
			Some(v) => client.with_auth(v.clone(), self.influxdb_password.clone())
		}
	}

	#[inline]
	fn get_url(&self) -> CompactString {
		match self.influxdb_tls {
			true => format_compact!("https://{}:{}", self.influxdb_host, self.influxdb_port),
			false => format_compact!("http://{}:{}", self.influxdb_host, self.influxdb_port)
		}
	}
}

#[inline]
pub fn from_env() -> Result<InfluxDbConfig, Error> {
	InfluxDbConfig::try_parse()
}

#[inline]
pub fn client_from_env() -> Result<Client, Error> {
	Ok(from_env()?.into_client())
}