mod capture;
mod chain;
mod config;
mod driver;
mod frame;
mod number;
mod sink;
mod trace;
#[cfg(feature = "both-paths")]
pub mod both_paths;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
use thiserror::Error;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
pub use chain::ChainError;
pub use config::{Chain, FallbackConfig, FormatChoice, HopConfig, ParseConfig, Settings};
#[cfg(test)]
#[allow(
unused_imports,
reason = "its test sits behind the stock parser features"
)]
pub(crate) use driver::gate_pays;
pub use driver::{Batch, CompileError, Outcome, ParsePlan, ParserCounts, SourceState, Status};
#[cfg(feature = "parse-grok")]
pub(crate) use driver::{Counter, counter};
#[cfg(feature = "framing")]
pub use frame::{
ContainerConfig, ContainerFormat, JsonPointer, JsonPointerConfig, PointerError, StreamConfig,
StreamSplit,
};
pub use frame::{Frame, FrameState, FramingConfig, MultiLineConfig};
pub use number::Number;
pub use sink::{FieldSink, Fields, PrefixStack, SinkMark};
pub use trace::{Event, Failure, Input, Step, Trace};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Hint {
Text,
Int,
Float,
Bool,
Ip,
Timestamp,
Json,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldValue<'a> {
pub bytes: Cow<'a, [u8]>,
pub hint: Hint,
}
impl<'a> FieldValue<'a> {
#[must_use]
pub const fn borrowed(bytes: &'a [u8], hint: Hint) -> Self {
Self {
bytes: Cow::Borrowed(bytes),
hint,
}
}
#[must_use]
pub const fn owned(bytes: Vec<u8>, hint: Hint) -> Self {
Self {
bytes: Cow::Owned(bytes),
hint,
}
}
#[must_use]
pub fn into_owned(self) -> FieldValue<'static> {
FieldValue {
bytes: Cow::Owned(self.bytes.into_owned()),
hint: self.hint,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Parsed {
NoMatch,
Done,
Body {
span: Range<usize>,
hint: Option<&'static str>,
},
}
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ParseError {
#[error("malformed at byte {offset}: {reason}")]
Malformed {
offset: usize,
reason: &'static str,
},
#[error("limit reached: {what}")]
Limit {
what: &'static str,
},
#[error("a frame of {len} bytes is over max_bytes {max}")]
FrameTooLong {
len: u64,
max: usize,
},
#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync>),
}
pub trait Parser: Send + Sync {
fn name(&self) -> &str;
fn tier(&self) -> MatcherTier;
fn signature(&self) -> &Signature;
fn cost(&self) -> Option<crate::cost::Cost> {
crate::cost::of(&format!("parser.{}", self.name()))
}
fn parse_counted<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
counts: &mut ParserCounts,
) -> Result<Parsed, ParseError> {
let _ = counts;
self.parse(input, out)
}
fn detectable(&self) -> bool {
!self.signature().is_literal_free()
}
fn escape_value(
&self,
input: &[u8],
field: usize,
at: Range<usize>,
value: &[u8],
out: &mut Vec<u8>,
) -> Option<Range<usize>> {
let _ = (input, field);
out.extend_from_slice(value);
Some(at)
}
fn parse<'a>(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>)
-> Result<Parsed, ParseError>;
}
#[cfg(any(feature = "parse-kv", feature = "parse-csv", feature = "parse-gelf"))]
pub(crate) fn quoted_span(
input: &[u8],
at: &Range<usize>,
quote: impl Fn(u8) -> bool,
) -> Option<Range<usize>> {
let open = *input.get(at.start.checked_sub(1)?)?;
(quote(open) && input.get(at.end) == Some(&open)).then(|| at.start - 1..at.end + 1)
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ResolveError {
#[error("no parser named {0:?}")]
Unknown(String),
#[error("parser name {0:?} is not `format` or `format:instance` in lower case")]
BadName(String),
#[error("parser {name:?}: {reason}")]
Settings {
name: String,
reason: String,
},
}
pub trait Resolve {
fn resolve(
&self,
name: &str,
settings: Option<&serde_json::Value>,
) -> Result<Arc<dyn Parser>, ResolveError>;
fn candidates(&self) -> Vec<Arc<dyn Parser>>;
}
#[derive(Default, Clone)]
pub struct Parsers {
by_name: HashMap<String, Arc<dyn Parser>>,
order: Vec<Arc<dyn Parser>>,
}
impl std::fmt::Debug for Parsers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.order.iter().map(|p| p.name()))
.finish()
}
}
impl Parsers {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, parser: Arc<dyn Parser>) -> Result<(), ResolveError> {
let name = parser.name().to_owned();
if !valid_parser_name(&name) {
return Err(ResolveError::BadName(name));
}
if let Some(old) = self.by_name.insert(name, Arc::clone(&parser)) {
self.order.retain(|p| !Arc::ptr_eq(p, &old));
}
self.order.push(parser);
Ok(())
}
}
#[must_use]
pub fn valid_parser_name(name: &str) -> bool {
let (format, instance) = match name.split_once(':') {
Some((f, i)) => (f, Some(i)),
None => (name, None),
};
let mut fb = format.bytes();
let format_ok = fb.next().is_some_and(|b| b.is_ascii_lowercase())
&& fb.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
&& !chain::RESERVED.contains(&format);
let instance_ok = instance.is_none_or(|i| {
!i.is_empty()
&& i.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
})
});
format_ok && instance_ok
}
impl Resolve for Parsers {
fn resolve(
&self,
name: &str,
settings: Option<&serde_json::Value>,
) -> Result<Arc<dyn Parser>, ResolveError> {
let parser = self
.by_name
.get(name)
.ok_or_else(|| ResolveError::Unknown(name.to_owned()))?;
if settings.is_some() {
return Err(ResolveError::Settings {
name: name.to_owned(),
reason: "this parser takes no settings".to_owned(),
});
}
Ok(Arc::clone(parser))
}
fn candidates(&self) -> Vec<Arc<dyn Parser>> {
self.order.clone()
}
}
#[cfg(test)]
mod tests;