use std::collections::BTreeMap;
use std::fmt;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use super::chain::{self, ChainError};
pub type Settings = BTreeMap<String, serde_json::Value>;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(into = "FormatRepr")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(with = "FormatRepr"))]
#[non_exhaustive]
pub enum FormatChoice {
Auto,
AutoStar,
Named(Vec<String>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
enum FormatRepr {
One(String),
List(Vec<String>),
}
impl From<String> for FormatChoice {
fn from(name: String) -> Self {
match name.as_str() {
"auto" => Self::Auto,
"auto*" => Self::AutoStar,
_ => Self::Named(vec![name]),
}
}
}
impl From<FormatChoice> for FormatRepr {
fn from(choice: FormatChoice) -> Self {
match choice {
FormatChoice::Auto => Self::One("auto".to_owned()),
FormatChoice::AutoStar => Self::One("auto*".to_owned()),
FormatChoice::Named(mut names) if names.len() == 1 => {
Self::One(names.pop().unwrap_or_default())
}
FormatChoice::Named(names) => Self::List(names),
}
}
}
impl<'de> Deserialize<'de> for FormatChoice {
fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
struct Choice;
impl<'de> Visitor<'de> for Choice {
type Value = FormatChoice;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("auto, auto*, a parser name or a list of parser names")
}
fn visit_str<E: de::Error>(self, name: &str) -> Result<FormatChoice, E> {
Ok(name.to_owned().into())
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<FormatChoice, A::Error> {
let mut names = Vec::new();
while let Some(name) = seq.next_element::<String>()? {
names.push(name);
}
Ok(FormatChoice::Named(names))
}
}
de.deserialize_any(Choice)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(with = "String"))]
#[non_exhaustive]
pub enum FallbackConfig {
#[default]
Raw,
Reject,
Format(String),
}
impl From<String> for FallbackConfig {
fn from(s: String) -> Self {
match s.as_str() {
"raw" => Self::Raw,
"reject" => Self::Reject,
_ => Self::Format(s),
}
}
}
impl From<FallbackConfig> for String {
fn from(f: FallbackConfig) -> Self {
match f {
FallbackConfig::Raw => "raw".to_owned(),
FallbackConfig::Reject => "reject".to_owned(),
FallbackConfig::Format(name) => name,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct HopConfig {
pub format: FormatChoice,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub each: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prefix: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fallback: Option<FallbackConfig>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub settings: Settings,
}
impl HopConfig {
#[must_use]
pub const fn new(format: FormatChoice) -> Self {
Self {
format,
field: None,
each: false,
prefix: None,
fallback: None,
settings: BTreeMap::new(),
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HopTable {
format: FormatChoice,
#[serde(default)]
field: Option<String>,
#[serde(default)]
each: bool,
#[serde(default)]
prefix: Option<String>,
#[serde(default)]
fallback: Option<FallbackConfig>,
#[serde(default)]
settings: Settings,
}
impl<'de> Deserialize<'de> for HopConfig {
fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
struct Hop;
impl<'de> Visitor<'de> for Hop {
type Value = HopConfig;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a hop such as `cef` or `field(\"msg\"):xml`, or a table with `format`")
}
fn visit_str<E: de::Error>(self, text: &str) -> Result<HopConfig, E> {
chain::hop(text).map_err(E::custom)
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<HopConfig, A::Error> {
let t = HopTable::deserialize(de::value::MapAccessDeserializer::new(map))?;
Ok(HopConfig {
format: t.format,
field: t.field,
each: t.each,
prefix: t.prefix,
fallback: t.fallback,
settings: t.settings,
})
}
}
de.deserialize_any(Hop)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Chain(pub Vec<HopConfig>);
impl std::str::FromStr for Chain {
type Err = ChainError;
fn from_str(text: &str) -> Result<Self, ChainError> {
chain::chain(text).map(Self)
}
}
impl<'de> Deserialize<'de> for Chain {
fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
struct Hops;
impl<'de> Visitor<'de> for Hops {
type Value = Chain;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a chain such as `syslog > cef`, or a list of hops")
}
fn visit_str<E: de::Error>(self, text: &str) -> Result<Chain, E> {
text.parse().map_err(E::custom)
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Chain, A::Error> {
let mut hops = Vec::new();
while let Some(hop) = seq.next_element::<HopConfig>()? {
hops.push(hop);
}
Ok(Chain(hops))
}
}
de.deserialize_any(Hops)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct ParseConfig {
pub chain: Chain,
#[serde(default)]
pub fallback: FallbackConfig,
#[serde(default = "default_max_depth")]
pub max_depth: usize,
#[serde(default = "default_max_invocations")]
pub max_invocations: usize,
#[serde(default)]
pub framing: super::FramingConfig,
#[serde(default)]
pub settings: Settings,
}
const fn default_max_depth() -> usize {
4
}
const fn default_max_invocations() -> usize {
256
}
impl ParseConfig {
#[must_use]
pub const fn new(chain: Chain) -> Self {
Self {
chain,
fallback: FallbackConfig::Raw,
max_depth: default_max_depth(),
max_invocations: default_max_invocations(),
framing: super::FramingConfig::None,
settings: BTreeMap::new(),
}
}
pub fn chain(text: &str) -> Result<Self, ChainError> {
text.parse().map(Self::new)
}
}