1use std::fmt;
10use std::path::PathBuf;
11use std::str::FromStr;
12use std::sync::Arc;
13use std::time::Duration;
14
15use url::Url;
16
17use crate::core::redact::redact_url;
18use crate::core::{
19 CommonConfig, CommonConfigBuilder, EnvReader, Error, Hooks, Result, RetryPolicy, Secret,
20 TlsConfig,
21};
22
23pub const DEFAULT_URL: &str = "";
27
28pub const VENDOR_URL_VARS: &[&str] = &["BETTERSTACK_INGESTING_URL", "BETTERSTACK_INGESTING_HOST"];
30pub const VENDOR_SOURCE_TOKEN_VARS: &[&str] = &["BETTERSTACK_SOURCE_TOKEN"];
32pub const VENDOR_QUERY_URL_VARS: &[&str] = &["BETTERSTACK_QUERY_URL", "BETTERSTACK_QUERY_HOST"];
34pub const VENDOR_QUERY_USERNAME_VARS: &[&str] = &["BETTERSTACK_QUERY_USERNAME"];
36pub const VENDOR_QUERY_PASSWORD_VARS: &[&str] = &["BETTERSTACK_QUERY_PASSWORD"];
38pub const VENDOR_SOURCE_TABLE_VARS: &[&str] = &["BETTERSTACK_SOURCE_TABLE"];
40
41pub fn is_valid_identifier(s: &str) -> bool {
44 let mut chars = s.chars();
45 match chars.next() {
46 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
47 _ => return false,
48 }
49 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
50}
51
52pub fn normalize_base_url(value: &str) -> Option<String> {
55 let trimmed = value.trim();
56 if trimmed.is_empty() {
57 return None;
58 }
59 let with_scheme = if trimmed.contains("://") {
60 trimmed.to_owned()
61 } else {
62 format!("https://{trimmed}")
63 };
64 Some(with_scheme.trim_end_matches('/').to_owned())
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
69pub enum Encoding {
70 #[default]
72 Json,
73 Ndjson,
75 Msgpack,
78}
79
80impl Encoding {
81 pub const ALL: [Encoding; 3] = [Encoding::Json, Encoding::Ndjson, Encoding::Msgpack];
83
84 pub fn as_str(self) -> &'static str {
86 match self {
87 Encoding::Json => "json",
88 Encoding::Ndjson => "ndjson",
89 Encoding::Msgpack => "msgpack",
90 }
91 }
92
93 pub fn content_type(self) -> &'static str {
95 match self {
96 Encoding::Json => "application/json",
97 Encoding::Ndjson => "application/x-ndjson",
98 Encoding::Msgpack => "application/msgpack",
99 }
100 }
101}
102
103impl fmt::Display for Encoding {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 f.write_str(self.as_str())
106 }
107}
108
109impl FromStr for Encoding {
110 type Err = Error;
111
112 fn from_str(s: &str) -> Result<Self> {
114 match s.trim().to_ascii_lowercase().as_str() {
115 "json" => Ok(Encoding::Json),
116 "ndjson" => Ok(Encoding::Ndjson),
117 "msgpack" | "messagepack" => Ok(Encoding::Msgpack),
118 _ => Err(Error::config("encoding must be json, ndjson or msgpack")),
119 }
120 }
121}
122
123#[derive(Clone)]
126pub struct BetterStackConfig {
127 common: CommonConfig,
128 ingest: Option<CommonConfig>,
129 query: Option<CommonConfig>,
130 source_token: Option<Secret>,
131 query_username: Option<String>,
132 query_password: Option<Secret>,
133 source_table: Option<String>,
134 encoding: Encoding,
135}
136
137impl fmt::Debug for BetterStackConfig {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.debug_struct("BetterStackConfig")
140 .field("url", &self.url().map(|u| redact_url(u.as_str())))
141 .field("source_token", &self.source_token)
142 .field(
143 "query_url",
144 &self.query_url().map(|u| redact_url(u.as_str())),
145 )
146 .field("query_username", &self.query_username)
147 .field("query_password", &self.query_password)
148 .field("source_table", &self.source_table)
149 .field("encoding", &self.encoding)
150 .field("common", &self.common)
151 .finish()
152 }
153}
154
155impl BetterStackConfig {
156 pub fn builder() -> BetterStackConfigBuilder {
158 BetterStackConfigBuilder::default()
159 }
160
161 pub fn from_env() -> Result<Self> {
164 Self::builder().build_from_env()
165 }
166
167 pub fn common(&self) -> &CommonConfig {
170 &self.common
171 }
172
173 pub fn ingest_common(&self) -> Option<&CommonConfig> {
175 self.ingest.as_ref()
176 }
177
178 pub fn query_common(&self) -> Option<&CommonConfig> {
180 self.query.as_ref()
181 }
182
183 pub fn url(&self) -> Option<&Url> {
185 self.ingest.as_ref().map(CommonConfig::url)
186 }
187
188 pub fn source_token(&self) -> Option<&Secret> {
190 self.source_token.as_ref()
191 }
192
193 pub fn query_url(&self) -> Option<&Url> {
195 self.query.as_ref().map(CommonConfig::url)
196 }
197
198 pub fn query_username(&self) -> Option<&str> {
200 self.query_username.as_deref()
201 }
202
203 pub fn query_password(&self) -> Option<&Secret> {
205 self.query_password.as_ref()
206 }
207
208 pub fn source_table(&self) -> Option<&str> {
210 self.source_table.as_deref()
211 }
212
213 pub fn encoding(&self) -> Encoding {
215 self.encoding
216 }
217
218 pub fn has_ingest(&self) -> bool {
220 self.ingest.is_some() && self.source_token.is_some()
221 }
222
223 pub fn has_query(&self) -> bool {
225 self.query.is_some() && self.query_username.is_some() && self.query_password.is_some()
226 }
227
228 pub fn basic_credentials(&self) -> Option<Secret> {
230 let (user, pass) = (self.query_username.as_ref()?, self.query_password.as_ref()?);
231 Some(Secret::new(crate::http::base64_encode(
232 format!("{user}:{}", pass.expose_secret()).as_bytes(),
233 false,
234 )))
235 }
236
237 pub fn known_secrets(&self) -> Vec<Secret> {
239 let mut out: Vec<Secret> = self
240 .source_token
241 .iter()
242 .chain(self.query_password.iter())
243 .cloned()
244 .collect();
245 out.extend(self.basic_credentials());
246 out
247 }
248
249 pub fn validate(&self) -> Result<()> {
252 let ingest_any = self.ingest.is_some() || self.source_token.is_some();
253 let query_any =
254 self.query.is_some() || self.query_username.is_some() || self.query_password.is_some();
255 if !ingest_any && !query_any {
256 return Err(Error::config(
257 "invalid configuration: set url + source_token (ingest) and/or query_url + query_username + query_password (SQL query)",
258 ));
259 }
260 let mut problems = Vec::new();
261 if ingest_any && self.ingest.is_none() {
262 problems.push("url (the source's ingesting host) is required with source_token");
263 }
264 if ingest_any && self.source_token.is_none() {
265 problems.push("source_token is required with url");
266 }
267 if query_any && !self.has_query() {
268 problems.push("query_url, query_username and query_password must be given together");
269 }
270 if self
271 .source_token
272 .as_ref()
273 .is_some_and(|t| t.expose_secret().trim().is_empty())
274 {
275 problems.push("source_token must not be blank");
276 }
277 if self.query_password.as_ref().is_some_and(Secret::is_empty) {
278 problems.push("query_password must not be blank");
279 }
280 if self
281 .source_table
282 .as_deref()
283 .is_some_and(|t| !is_valid_identifier(t))
284 {
285 problems.push("source_table must match ^[A-Za-z_][A-Za-z0-9_]*$");
286 }
287 if problems.is_empty() {
288 Ok(())
289 } else {
290 Err(Error::config(format!(
291 "invalid configuration: {}",
292 problems.join("; ")
293 )))
294 }
295 }
296}
297
298#[derive(Debug, Clone, Default)]
300pub struct BetterStackConfigBuilder {
301 common: CommonConfigBuilder,
302 url: Option<String>,
303 source_token: Option<Secret>,
304 query_url: Option<String>,
305 query_username: Option<String>,
306 query_password: Option<Secret>,
307 source_table: Option<String>,
308 encoding: Option<Encoding>,
309}
310
311impl BetterStackConfigBuilder {
312 pub fn url(mut self, url: impl Into<String>) -> Self {
315 self.url = Some(url.into());
316 self
317 }
318 pub fn source_token(mut self, token: impl Into<Secret>) -> Self {
320 self.source_token = Some(token.into());
321 self
322 }
323 pub fn query_url(mut self, url: impl Into<String>) -> Self {
325 self.query_url = Some(url.into());
326 self
327 }
328 pub fn query_username(mut self, username: impl Into<String>) -> Self {
330 self.query_username = Some(username.into());
331 self
332 }
333 pub fn query_password(mut self, password: impl Into<Secret>) -> Self {
335 self.query_password = Some(password.into());
336 self
337 }
338 pub fn source_table(mut self, table: impl Into<String>) -> Self {
340 self.source_table = Some(table.into());
341 self
342 }
343 pub fn encoding(mut self, encoding: Encoding) -> Self {
345 self.encoding = Some(encoding);
346 self
347 }
348 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
350 self.common = self.common.connect_timeout(timeout);
351 self
352 }
353 pub fn request_timeout(mut self, timeout: Duration) -> Self {
355 self.common = self.common.request_timeout(timeout);
356 self
357 }
358 pub fn total_timeout(mut self, timeout: Duration) -> Self {
360 self.common = self.common.total_timeout(timeout);
361 self
362 }
363 pub fn retry(mut self, retry: RetryPolicy) -> Self {
365 self.common = self.common.retry(retry);
366 self
367 }
368 pub fn max_retries(mut self, max_retries: u32) -> Self {
370 self.common = self.common.max_retries(max_retries);
371 self
372 }
373 pub fn tls(mut self, tls: TlsConfig) -> Self {
375 self.common = self.common.tls(tls);
376 self
377 }
378 pub fn ca_cert_path(mut self, path: impl Into<PathBuf>) -> Self {
380 self.common = self.common.ca_cert_path(path);
381 self
382 }
383 pub fn insecure_skip_verify(mut self, skip: bool) -> Self {
385 self.common = self.common.insecure_skip_verify(skip);
386 self
387 }
388 pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
390 self.common = self.common.proxy(proxy);
391 self
392 }
393 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
395 self.common = self.common.header(name, value);
396 self
397 }
398 pub fn user_agent_suffix(mut self, suffix: impl Into<String>) -> Self {
400 self.common = self.common.user_agent_suffix(suffix);
401 self
402 }
403 pub fn hooks(mut self, hooks: Arc<dyn Hooks>) -> Self {
405 self.common = self.common.hooks(hooks);
406 self
407 }
408 pub fn common(mut self, f: impl FnOnce(CommonConfigBuilder) -> CommonConfigBuilder) -> Self {
411 self.common = f(self.common);
412 self
413 }
414
415 pub fn build(self) -> Result<BetterStackConfig> {
417 let url = self.url.as_deref().and_then(normalize_base_url);
418 let query_url = self.query_url.as_deref().and_then(normalize_base_url);
419 let side = |url: &Option<String>, name: &str| -> Result<Option<CommonConfig>> {
420 match url {
421 None => Ok(None),
422 Some(u) => self
423 .common
424 .clone()
425 .url(u.clone())
426 .build(u)
427 .map(Some)
428 .map_err(|e| {
429 let msg = e.message().replacen("url", name, 1);
430 e.with_message(format!("invalid configuration: {msg}"))
431 }),
432 }
433 };
434 let ingest = side(&url, "url")?;
435 let query = side(&query_url, "query_url")?;
436 let common = match (&ingest, &query) {
437 (Some(c), _) | (None, Some(c)) => c.clone(),
438 (None, None) => {
439 self.common.clone().build("http://unset.invalid")?
441 }
442 };
443 let config = BetterStackConfig {
444 common,
445 ingest,
446 query,
447 source_token: self.source_token,
448 query_username: self.query_username.filter(|u| !u.trim().is_empty()),
449 query_password: self.query_password,
450 source_table: self.source_table.filter(|t| !t.is_empty()),
451 encoding: self.encoding.unwrap_or_default(),
452 };
453 config.validate()?;
454 Ok(config)
455 }
456
457 pub fn build_from_env(self) -> Result<BetterStackConfig> {
459 self.build_with_env(&EnvReader::new())
460 }
461
462 pub fn build_with_env(mut self, env: &EnvReader) -> Result<BetterStackConfig> {
464 self.common = self.common.apply_env(env, VENDOR_URL_VARS)?;
465 if self.url.is_none() {
466 self.url = env.string("URL", VENDOR_URL_VARS);
467 }
468 if self.source_token.is_none() {
469 self.source_token = env.secret("SOURCE_TOKEN", VENDOR_SOURCE_TOKEN_VARS);
470 }
471 if self.query_url.is_none() {
472 self.query_url = env.string("QUERY_URL", VENDOR_QUERY_URL_VARS);
473 }
474 if self.query_username.is_none() {
475 self.query_username = env
476 .string("QUERY_USERNAME", VENDOR_QUERY_USERNAME_VARS)
477 .map(|s| s.trim().to_owned());
478 }
479 if self.query_password.is_none() {
480 self.query_password = env.secret("QUERY_PASSWORD", VENDOR_QUERY_PASSWORD_VARS);
481 }
482 if self.source_table.is_none() {
483 self.source_table = env
484 .string("SOURCE_TABLE", VENDOR_SOURCE_TABLE_VARS)
485 .map(|s| s.trim().to_owned());
486 }
487 if self.encoding.is_none() {
488 if let Some((var, value)) = env.lookup("ENCODING", &[]) {
489 self.encoding = Some(value.parse().map_err(|_| {
490 Error::config(format!(
491 "environment variable {var} must be json, ndjson or msgpack"
492 ))
493 })?);
494 }
495 }
496 self.build()
497 }
498}