This repository was archived by the owner on Mar 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.rs
More file actions
413 lines (359 loc) · 10.6 KB
/
settings.rs
File metadata and controls
413 lines (359 loc) · 10.6 KB
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
// Copyright 2023 joshyrobot, ThatsNoMoon
// Licensed under the Open Software License version 3.0
//! Handling of bot configuration for hosters.
#[cfg(feature = "sqlite")]
use std::path::PathBuf;
#[cfg(feature = "bot")]
use std::time::Duration;
use std::{
collections::HashMap,
env::{self, VarError},
fs::read_to_string,
io::ErrorKind,
};
use anyhow::{bail, Result};
use config::{
builder::DefaultState, ConfigBuilder, ConfigError, Environment, File,
FileFormat,
};
use once_cell::sync::OnceCell;
use serde::Deserialize;
#[cfg(feature = "bot")]
use serenity::model::id::GuildId;
use tracing::metadata::LevelFilter;
use url::Url;
#[cfg(feature = "bot")]
mod duration_de {
use std::{fmt, time::Duration};
use serde::{de, Deserializer};
/// Visitor to deserialize a `Duration` from a number of seconds.
struct DurationVisitor;
impl<'de> de::Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a std::time::Duration in seconds")
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Duration::from_secs(v))
}
}
pub(super) fn deserialize_duration<'de, D>(
d: D,
) -> Result<Option<Duration>, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_u64(DurationVisitor).map(Some)
}
}
#[cfg(feature = "bot")]
use duration_de::deserialize_duration;
#[cfg(feature = "monitoring")]
mod user_address {
use std::{
fmt,
net::{SocketAddr, ToSocketAddrs},
};
use serde::{de, Deserialize, Deserializer};
#[derive(Debug, Clone, Copy)]
pub(crate) struct UserAddress {
pub(crate) socket_addr: SocketAddr,
}
impl<'de> Deserialize<'de> for UserAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(UserAddressVisitor)
}
}
/// Visitor to deserialize a `SocketAddr` using ToSocketAddrs.
struct UserAddressVisitor;
impl<'de> de::Visitor<'de> for UserAddressVisitor {
type Value = UserAddress;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a socket address in the form `host:port`")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
let socket_addr =
v.to_socket_addrs().map_err(E::custom)?.next().ok_or_else(
|| E::custom("provided host did not resolve to an address"),
)?;
Ok(UserAddress { socket_addr })
}
}
}
mod level {
use std::{collections::HashMap, fmt};
use serde::{de, Deserialize, Deserializer};
use tracing::metadata::LevelFilter;
struct LevelFilterWrapper(LevelFilter);
/// Visitor to deserialize a `LevelFilter` from a string.
struct LevelFilterVisitor;
impl<'de> de::Visitor<'de> for LevelFilterVisitor {
type Value = LevelFilterWrapper;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"a logging level (trace, debug, info, warn, error, off)"
)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match v {
"off" | "OFF" => Ok(LevelFilter::OFF),
"trace" | "TRACE" => Ok(LevelFilter::TRACE),
"debug" | "DEBUG" => Ok(LevelFilter::DEBUG),
"info" | "INFO" => Ok(LevelFilter::INFO),
"warn" | "WARN" => Ok(LevelFilter::WARN),
"error" | "ERROR" => Ok(LevelFilter::ERROR),
_ => Err(E::invalid_value(de::Unexpected::Str(v), &self)),
}
.map(LevelFilterWrapper)
}
}
impl<'de> Deserialize<'de> for LevelFilterWrapper {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_str(LevelFilterVisitor)
}
}
pub(super) fn deserialize_level_filter<'de, D>(
d: D,
) -> Result<LevelFilter, D::Error>
where
D: Deserializer<'de>,
{
LevelFilterWrapper::deserialize(d).map(|LevelFilterWrapper(f)| f)
}
/// Visitor to deserialize a `LevelFilter` from a string.
struct LevelFiltersVisitor;
impl<'de> de::Visitor<'de> for LevelFiltersVisitor {
type Value = HashMap<String, LevelFilter>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a table of modules to logging levels")
}
fn visit_map<A>(self, mut filters: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
let mut map = HashMap::new();
while let Some((module, LevelFilterWrapper(filter))) =
filters.next_entry::<String, LevelFilterWrapper>()?
{
map.insert(module, filter);
}
Ok(map)
}
}
pub(super) fn deserialize_level_filters<'de, D>(
d: D,
) -> Result<HashMap<String, LevelFilter>, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_map(LevelFiltersVisitor)
}
}
use level::{deserialize_level_filter, deserialize_level_filters};
mod log_format {
use std::fmt;
use serde::{de, Deserialize, Deserializer};
#[derive(Debug)]
pub(crate) enum LogFormat {
Compact,
Pretty,
Json,
}
/// Visitor to deserialize a `LevelFilter` from a string.
struct LogFormatVisitor;
impl<'de> de::Visitor<'de> for LogFormatVisitor {
type Value = LogFormat;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a log format (compact, pretty, json)")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match v {
"compact" | "COMPACT" => Ok(LogFormat::Compact),
"pretty" | "PRETTY" => Ok(LogFormat::Pretty),
"json" | "JSON" => Ok(LogFormat::Json),
_ => Err(E::invalid_value(de::Unexpected::Str(v), &self)),
}
}
}
impl<'de> Deserialize<'de> for LogFormat {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_str(LogFormatVisitor)
}
}
}
pub(crate) use log_format::LogFormat;
#[cfg(feature = "monitoring")]
pub(crate) use user_address::UserAddress;
/// Settings for the highlighting behavior of the bot.
#[cfg(feature = "bot")]
#[derive(Debug, Deserialize)]
pub(crate) struct BehaviorSettings {
/// Maximum number of keywords allowed for one user.
#[serde(alias = "maxkeywords")]
pub(crate) max_keywords: u32,
/// Duration to wait for activity before sending a notification.
#[serde(with = "humantime_serde")]
#[cfg(feature = "bot")]
pub(crate) patience: Duration,
/// Duration to wait before deleting notifications.
#[serde(
alias = "notificationlifetime",
with = "humantime_serde::option",
default
)]
#[cfg(feature = "bot")]
pub(crate) notification_lifetime: Option<Duration>,
/// Deprecated method to specify patience.
#[serde(
deserialize_with = "deserialize_duration",
alias = "patienceseconds",
default
)]
#[cfg(feature = "bot")]
pub(crate) patience_seconds: Option<Duration>,
}
/// Settings for the account of the bot.
#[cfg(feature = "bot")]
#[derive(Debug, Deserialize)]
pub(crate) struct BotSettings {
/// Bot token to log into Discord with.
pub(crate) token: String,
/// ID of the bot's application.
#[serde(alias = "applicationid")]
pub(crate) application_id: u64,
/// Whether this bot is private or not.
///
/// Controls whether the `about` command outputs an invite link.
pub(crate) private: bool,
#[serde(alias = "testguild")]
pub(crate) test_guild: Option<GuildId>,
}
/// Settings for various logging facilities.
#[derive(Debug, Deserialize)]
pub(crate) struct LoggingSettings {
/// Webhook URL to send error/panic messages to.
#[cfg(feature = "reporting")]
pub(crate) webhook: Option<Url>,
/// Address to find Jaeger agent to send traces to.
#[cfg(feature = "monitoring")]
pub(crate) jaeger: Option<UserAddress>,
/// Percentage of traces to sample.
///
/// See [`TraceIdRatioBased`](opentelemetry::sdk::trace::Sampler::TraceIdRatioBased).
#[cfg(feature = "monitoring")]
#[serde(alias = "sampleratio")]
pub(crate) sample_ratio: f64,
/// Global level that log messages should be filtered to.
#[serde(deserialize_with = "deserialize_level_filter")]
pub(crate) level: LevelFilter,
/// Per-module log level filters.
#[serde(deserialize_with = "deserialize_level_filters")]
pub(crate) filters: HashMap<String, LevelFilter>,
/// Whether or not to use ANSI color codes.
pub(crate) color: bool,
/// Standard output logging format.
pub(crate) format: LogFormat,
}
/// Settings for the database.
#[derive(Debug, Deserialize)]
pub(crate) struct DatabaseSettings {
/// Path to the directory that should hold the SQLite database.
#[cfg(feature = "sqlite")]
pub(crate) path: Option<PathBuf>,
/// Database connection URL.
#[cfg(feature = "sqlite")]
pub(crate) url: Option<Url>,
/// Database connection URL.
#[cfg(not(feature = "sqlite"))]
pub(crate) url: Url,
/// Whether or not to run automatic daily backups.
#[cfg(feature = "backup")]
pub(crate) backup: Option<bool>,
}
/// Collection of settings.
#[derive(Debug, Deserialize)]
pub(crate) struct Settings {
#[cfg(feature = "bot")]
pub(crate) behavior: BehaviorSettings,
#[cfg(feature = "bot")]
pub(crate) bot: BotSettings,
pub(crate) logging: LoggingSettings,
pub(crate) database: DatabaseSettings,
}
impl Settings {
/// Builds settings from environment variables and the configuration file.
pub(crate) fn new() -> Result<Self, ConfigError> {
let b = ConfigBuilder::<DefaultState>::default();
#[cfg(feature = "bot")]
let b = b.set_default("behavior.max_keywords", 100i64)?
.set_default("behavior.patience", "2m")?
.set_default("bot.private", false)?;
#[cfg(feature = "monitoring")]
let b = b.set_default("logging.sample_ratio", 1.0f64)?;
let mut b = b
.set_default("logging.level", "WARN")?
.set_default("logging.filters.highlights", "INFO")?
.set_default("logging.color", "true")?
.set_default("logging.format", "compact")?;
let filename = env::var("HIGHLIGHTS_CONFIG").or_else(|e| match e {
VarError::NotPresent => Ok("./config.toml".to_owned()),
e => Err(ConfigError::Foreign(Box::new(e))),
})?;
match read_to_string(filename) {
Ok(conf) => {
b = b.add_source(File::from_str(&conf, FileFormat::Toml));
}
Err(e) if e.kind() == ErrorKind::NotFound => (),
Err(e) => return Err(ConfigError::Foreign(Box::new(e))),
}
b.add_source(Environment::with_prefix("HIGHLIGHTS").separator("_"))
.build()?
.try_deserialize()
.map(|mut settings: Settings| {
if let Some(old) = settings.behavior.patience_seconds {
settings.behavior.patience = old;
}
settings
})
}
}
/// Settings configured by the hoster.
static SETTINGS: OnceCell<Settings> = OnceCell::new();
/// Gets the settings configured by the hoster.
pub(crate) fn settings() -> &'static Settings {
SETTINGS.get().expect("Settings were not initialized")
}
/// Initialize the bot's [`Settings`].
pub(crate) fn init() -> Result<()> {
match Settings::new() {
Ok(settings) => {
let _ = SETTINGS.set(settings);
Ok(())
}
Err(e) => {
bail!("Failed to parse settings: {}", e);
}
}
}