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
//! Support for loading configs from multiple formats.
#![deny(missing_docs, missing_debug_implementations)]
use std::fmt;
use std::path::Path;
use std::str::FromStr;
use serde::de;
/// A type alias to better capture the semantics.
pub type FormatHint = Option<Format>;
/// The format used to represent the configuration data.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Format {
/// TOML format is used.
#[default]
Toml,
/// JSON format is used.
Json,
/// YAML format is used.
Yaml,
}
impl FromStr for Format {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"toml" => Ok(Format::Toml),
"yaml" => Ok(Format::Yaml),
"json" => Ok(Format::Json),
_ => Err(format!("Invalid format: {}", s)),
}
}
}
impl fmt::Display for Format {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let format = match self {
Format::Toml => "toml",
Format::Json => "json",
Format::Yaml => "yaml",
};
write!(f, "{}", format)
}
}
impl Format {
/// Obtain the format from the file path using extension as a hint.
pub fn from_path<T: AsRef<Path>>(path: T) -> Result<Self, T> {
match path.as_ref().extension().and_then(|ext| ext.to_str()) {
Some("toml") => Ok(Format::Toml),
Some("yaml") | Some("yml") => Ok(Format::Yaml),
Some("json") => Ok(Format::Json),
_ => Err(path),
}
}
}
/// Parse the string represented in the specified format.
pub fn deserialize<T>(content: &str, format: Format) -> Result<T, Vec<String>>
where
T: de::DeserializeOwned,
{
match format {
Format::Toml => toml::from_str(content).map_err(|e| vec![e.to_string()]),
Format::Yaml => serde_yaml::from_str::<serde_yaml::Value>(content)
.and_then(|mut v| {
v.apply_merge()?;
serde_yaml::from_value(v)
})
.map_err(|e| vec![e.to_string()]),
Format::Json => serde_json::from_str(content).map_err(|e| vec![e.to_string()]),
}
}
/// Serialize the specified `value` into a string.
pub fn serialize<T>(value: &T, format: Format) -> Result<String, String>
where
T: serde::ser::Serialize,
{
match format {
Format::Toml => toml::to_string(value).map_err(|e| e.to_string()),
Format::Yaml => serde_yaml::to_string(value).map_err(|e| e.to_string()),
Format::Json => serde_json::to_string_pretty(value).map_err(|e| e.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// This test ensures the logic to guess file format from the file path
/// works correctly.
/// Like all other tests, it also demonstrates various cases and how our
/// code behaves when it encounters them.
#[test]
fn test_from_path() {
let cases = vec![
// Unknown - odd variants.
("", None),
(".", None),
// Unknown - no ext.
("myfile", None),
("mydir/myfile", None),
("/mydir/myfile", None),
// Unknown - some unknown ext.
("myfile.myext", None),
("mydir/myfile.myext", None),
("/mydir/myfile.myext", None),
// Unknown - some unknown ext after known ext.
("myfile.toml.myext", None),
("myfile.yaml.myext", None),
("myfile.yml.myext", None),
("myfile.json.myext", None),
// Unknown - invalid case.
("myfile.TOML", None),
("myfile.YAML", None),
("myfile.YML", None),
("myfile.JSON", None),
// Unknown - nothing but extension.
(".toml", None),
(".yaml", None),
(".yml", None),
(".json", None),
// TOML
("config.toml", Some(Format::Toml)),
("/config.toml", Some(Format::Toml)),
("/dir/config.toml", Some(Format::Toml)),
("config.qq.toml", Some(Format::Toml)),
// YAML
("config.yaml", Some(Format::Yaml)),
("/config.yaml", Some(Format::Yaml)),
("/dir/config.yaml", Some(Format::Yaml)),
("config.qq.yaml", Some(Format::Yaml)),
("config.yml", Some(Format::Yaml)),
("/config.yml", Some(Format::Yaml)),
("/dir/config.yml", Some(Format::Yaml)),
("config.qq.yml", Some(Format::Yaml)),
// JSON
("config.json", Some(Format::Json)),
("/config.json", Some(Format::Json)),
("/dir/config.json", Some(Format::Json)),
("config.qq.json", Some(Format::Json)),
];
for (input, expected) in cases {
let output = Format::from_path(std::path::PathBuf::from(input));
assert_eq!(expected, output.ok(), "{}", input)
}
}
// Here we test that the deserializations from various formats match
// the TOML format.
#[cfg(all(
feature = "sources-socket",
feature = "transforms-sample",
feature = "sinks-socket"
))]
#[test]
fn test_deserialize_matches_toml() {
use crate::config::ConfigBuilder;
macro_rules! concat_with_newlines {
($($e:expr,)*) => { concat!( $($e, "\n"),+ ) };
}
const SAMPLE_TOML: &str = r#"
[enrichment_tables.csv]
type = "file"
file.path = "/tmp/file.csv"
file.encoding.type = "csv"
[sources.in]
type = "socket"
mode = "tcp"
address = "127.0.0.1:1235"
[sources.in2]
type = "socket"
mode = "tcp"
address = "127.0.0.1:1234"
[transforms.sample]
type = "sample"
inputs = ["in"]
rate = 10
[sinks.out]
type = "socket"
mode = "tcp"
inputs = ["sample"]
encoding.codec = "text"
address = "127.0.0.1:9999"
"#;
let cases = vec![
// Valid empty inputs should resolve to an empty, default value.
("", Format::Toml, Ok("")),
("{}", Format::Yaml, Ok("")),
("{}", Format::Json, Ok("")),
("", Format::Yaml, Ok("")),
// Invalid "empty" inputs should resolve to an error.
(
"",
Format::Json,
Err(vec!["EOF while parsing a value at line 1 column 0"]),
),
// Sample config.
(SAMPLE_TOML, Format::Toml, Ok(SAMPLE_TOML)),
(
// YAML is sensitive to leading whitespace and linebreaks.
concat_with_newlines!(
r#"enrichment_tables:"#,
r#" csv:"#,
r#" type: "file""#,
r#" file:"#,
r#" path: "/tmp/file.csv""#,
r#" encoding:"#,
r#" type: "csv""#,
r#"sources:"#,
r#" in: &a"#,
r#" type: "socket""#,
r#" mode: &b "tcp""#,
r#" address: "127.0.0.1:1235""#,
r#" in2:"#,
r#" <<: *a"#,
r#" address: "127.0.0.1:1234""#,
r#"transforms:"#,
r#" sample:"#,
r#" type: "sample""#,
r#" inputs: ["in"]"#,
r#" rate: 10"#,
r#"sinks:"#,
r#" out:"#,
r#" type: "socket""#,
r#" mode: *b"#,
r#" inputs: ["sample"]"#,
r#" encoding:"#,
r#" codec: "text""#,
r#" address: "127.0.0.1:9999""#,
),
Format::Yaml,
Ok(SAMPLE_TOML),
),
(
r#"
{
"enrichment_tables": {
"csv": {
"type": "file",
"file": {
"path": "/tmp/file.csv",
"encoding": {
"type": "csv"
}
}
}
},
"sources": {
"in": {
"type": "socket",
"mode": "tcp",
"address": "127.0.0.1:1235"
},
"in2": {
"type": "socket",
"mode": "tcp",
"address": "127.0.0.1:1234"
}
},
"transforms": {
"sample": {
"type": "sample",
"inputs": ["in"],
"rate": 10
}
},
"sinks": {
"out": {
"type": "socket",
"mode": "tcp",
"inputs": ["sample"],
"encoding": {
"codec": "text"
},
"address": "127.0.0.1:9999"
}
}
}
"#,
Format::Json,
Ok(SAMPLE_TOML),
),
];
for (input, format, expected) in cases {
// Here we use the same trick as at ConfigBuilder::clone impl to
// compare the results.
let output = deserialize(input, format);
match expected {
Ok(expected) => {
#[allow(clippy::expect_fun_call)] // false positive
let output: ConfigBuilder = output.expect(&format!(
"expected Ok, got Err with format {:?} and input {:?}",
format, input
));
let output_json = serde_json::to_value(output).unwrap();
let expected_output: ConfigBuilder = deserialize(expected, Format::Toml)
.expect("Invalid TOML passed as an expectation");
let expected_json = serde_json::to_value(expected_output).unwrap();
assert_eq!(expected_json, output_json, "{}", input)
}
Err(expected) => assert_eq!(
expected,
output.expect_err(&format!(
"expected Err, got Ok with format {:?} and input {:?}",
format, input
)),
"{}",
input
),
}
}
}
}