Skip to main content

oxtel_config/
lib.rs

1//! OpenTelemetry declarative configuration for
2//! [oxtel](https://github.com/agentstatelabs/oxtel): the YAML file
3//! `OTEL_CONFIG_FILE` names, read into a typed [`Config`].
4//!
5//! - Environment variables are substituted in values (`${NAME}`,
6//!   `${env:NAME}`, `${NAME:-default}`, `$$` for a literal `$`). Unquoted
7//!   values are then typed as YAML scalars, so `${OTEL_SDK_DISABLED:-false}`
8//!   is a boolean, while quoted values stay strings. A substituted value is
9//!   never read as YAML structure.
10//! - `file_format` must be `1.x`.
11//! - Values of the wrong type are errors, naming the field's path.
12//! - Keys and components oxtel doesn't support, such as views or the gRPC
13//!   exporter, are reported in [`Parsed::warnings`] and otherwise ignored.
14//!
15//! The `oxtel` crate builds its pipelines from the result when
16//! `OTEL_CONFIG_FILE` is set.
17//!
18//! ```
19//! let parsed = oxtel_config::parse_with(
20//!     "file_format: \"1.2\"\ndisabled: ${DISABLED:-false}\n",
21//!     &|_| None,
22//! )
23//! .unwrap();
24//! assert!(!parsed.config.disabled);
25//! ```
26
27mod model;
28mod yaml;
29
30use std::fmt;
31use std::path::Path;
32
33pub use model::{
34    AttributeValue, Config, ExporterConfig, Limits, LoggerProviderConfig, MeterProviderConfig,
35    OtlpHttpConfig, ProcessorConfig, ReaderConfig, ResourceConfig, SamplerConfig,
36    TracerProviderConfig,
37};
38
39/// A configuration and what in it was ignored.
40#[derive(Clone, Debug, PartialEq)]
41pub struct Parsed {
42    /// The configuration.
43    pub config: Config,
44    /// Keys and components oxtel doesn't support, one message each.
45    pub warnings: Vec<String>,
46}
47
48/// Why a configuration couldn't be read.
49#[derive(Clone, Debug, PartialEq)]
50#[non_exhaustive]
51pub enum Error {
52    /// The file couldn't be read.
53    Io(String),
54    /// The YAML is malformed, or a substitution is invalid.
55    Parse {
56        /// The line, from 1.
57        line: usize,
58        /// The column, from 1.
59        column: usize,
60        /// What's wrong.
61        message: String,
62    },
63    /// `file_format` is missing, or isn't a version oxtel reads.
64    FileFormat(Option<String>),
65    /// A value has the wrong type.
66    Invalid {
67        /// Where, such as `tracer_provider.processors[0].batch.max_queue_size`.
68        path: String,
69        /// What it should be.
70        expected: String,
71    },
72}
73
74impl fmt::Display for Error {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match self {
77            Error::Io(e) => write!(f, "couldn't read the configuration file: {e}"),
78            Error::Parse {
79                line,
80                column,
81                message,
82            } => write!(
83                f,
84                "configuration file, line {line}, column {column}: {message}"
85            ),
86            Error::FileFormat(None) => write!(f, "the configuration file has no `file_format`"),
87            Error::FileFormat(Some(v)) => {
88                write!(f, "`file_format: {v}` isn't supported; oxtel reads 1.x")
89            }
90            Error::Invalid { path, expected } => {
91                write!(f, "`{path}` in the configuration file should be {expected}")
92            }
93        }
94    }
95}
96
97impl std::error::Error for Error {}
98
99/// Read the configuration in `text`, substituting the process's
100/// environment variables.
101pub fn parse(text: &str) -> Result<Parsed, Error> {
102    parse_with(text, &|name| std::env::var(name).ok())
103}
104
105/// Read the configuration in `text`, substituting variables from `lookup`.
106pub fn parse_with(text: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Result<Parsed, Error> {
107    let root = yaml::parse(text, lookup)?;
108    let mut warnings = Vec::new();
109    let config = model::config(&root, &mut warnings)?;
110    Ok(Parsed { config, warnings })
111}
112
113/// Read the configuration file at `path`.
114pub fn from_file(path: impl AsRef<Path>) -> Result<Parsed, Error> {
115    let text = std::fs::read_to_string(path.as_ref())
116        .map_err(|e| Error::Io(format!("{}: {e}", path.as_ref().display())))?;
117    parse(&text)
118}