use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock;
use std::time::Duration;
use regex::Regex;
#[derive(Debug, Clone, PartialEq)]
pub struct DynamicSource {
pub id: String,
pub source_type: SourceType,
pub refresh: RefreshPolicy,
pub timeout: Option<Duration>,
pub on_error: ErrorPolicy,
pub required: bool,
pub default: Option<yaml_serde::Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SourceType {
Http {
url: String,
method: Option<String>,
headers: HashMap<String, String>,
body: Option<String>,
format: DataFormat,
extract: Option<ExtractExpr>,
},
Command {
command: Vec<String>,
format: DataFormat,
extract: Option<ExtractExpr>,
},
File {
path: PathBuf,
format: DataFormat,
extract: Option<ExtractExpr>,
},
Nats {
url: String,
subject: String,
format: DataFormat,
extract: Option<ExtractExpr>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExtractExpr {
Jq(String),
JsonPath(String),
Cel(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum RefreshPolicy {
Once,
Interval(Duration),
Watch,
Push,
OnDemand,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorPolicy {
UseCached,
Fail,
UseDefault,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataFormat {
Json,
Yaml,
Lines,
Csv,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SourceRef {
pub source_id: String,
pub sub_path: Option<String>,
pub location: RefLocation,
pub raw_template: String,
}
pub fn is_valid_source_id(id: &str) -> bool {
!id.is_empty()
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceTemplate<'a> {
pub raw: &'a str,
pub start: usize,
pub source_id: &'a str,
pub sub_path: Option<&'a str>,
}
pub fn scan_source_templates(text: &str) -> impl Iterator<Item = SourceTemplate<'_>> {
static RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"\$\{source\.([A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_.]+))?\}")
.expect("source template regex is valid")
});
RE.captures_iter(text).map(|caps| {
let whole = caps.get(0).expect("group 0 always participates");
SourceTemplate {
raw: whole.as_str(),
start: whole.start(),
source_id: caps.get(1).expect("the id group is required").as_str(),
sub_path: caps.get(2).map(|m| m.as_str()),
}
})
}
#[derive(Debug, Clone, PartialEq)]
pub enum RefLocation {
Var { var_name: String },
TransformationField {
transform_index: usize,
field_name: String,
},
Include { transform_index: usize },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceStatus {
Pending,
Resolved,
Failed,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_source_ids() {
for id in ["ip_blocklist", "threat-intel", "1st_feed", "A9", "_", "-"] {
assert!(is_valid_source_id(id), "{id}");
}
for id in ["", "bad.id", "has space", "café", "a/b", "${x}"] {
assert!(!is_valid_source_id(id), "{id}");
}
}
#[test]
fn scan_finds_templates_with_offsets() {
let text = "a ${source.threat-intel.ips.0} b ${source.1st_feed} ${source.bad id}";
let found: Vec<_> = scan_source_templates(text).collect();
assert_eq!(
found,
[
SourceTemplate {
raw: "${source.threat-intel.ips.0}",
start: 2,
source_id: "threat-intel",
sub_path: Some("ips.0"),
},
SourceTemplate {
raw: "${source.1st_feed}",
start: 33,
source_id: "1st_feed",
sub_path: None,
},
]
);
for t in &found {
assert_eq!(&text[t.start..t.start + t.raw.len()], t.raw);
}
}
}