use super::{BulkLintReport, GenerationError, SchemaRegistry};
use alloc::{collections::BTreeMap, string::String};
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum BulkAdvisory {
OpaqueBytes,
PackedList,
BooleanList,
WideIntegerList,
ZeroByteList,
}
impl BulkAdvisory {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::OpaqueBytes => "opaque-bytes",
Self::PackedList => "packed-list",
Self::BooleanList => "boolean-list",
Self::WideIntegerList => "wide-integer-list",
Self::ZeroByteList => "zero-byte-list",
}
}
}
impl core::str::FromStr for BulkAdvisory {
type Err = GenerationError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
[
Self::OpaqueBytes,
Self::PackedList,
Self::BooleanList,
Self::WideIntegerList,
Self::ZeroByteList,
]
.into_iter()
.find(|id| id.as_str() == value)
.ok_or(GenerationError::Schema)
}
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum BulkSite {
ListElement(String),
Field(String, String),
}
impl BulkSite {
#[must_use]
pub fn list_element<T: ?Sized>() -> Self {
Self::ListElement(SchemaRegistry::type_label::<T>())
}
#[must_use]
pub fn field<T: ?Sized>(name: &str) -> Self {
Self::Field(SchemaRegistry::type_label::<T>(), name.into())
}
}
#[derive(Default)]
pub struct BulkPolicy {
rules: BTreeMap<BulkSite, BTreeMap<BulkAdvisory, Decision>>,
}
struct Decision {
reason: String,
matched: bool,
}
impl BulkPolicy {
pub fn acknowledge(
&mut self,
site: BulkSite,
advisory: BulkAdvisory,
reason: &str,
) -> Result<(), GenerationError> {
if reason.trim().is_empty()
|| match &site {
BulkSite::ListElement(name) => name.is_empty(),
BulkSite::Field(record, field) => record.is_empty() || field.is_empty(),
}
{
return Err(GenerationError::Schema);
}
let rules = self.rules.entry(site).or_default();
let alloc::collections::btree_map::Entry::Vacant(entry) = rules.entry(advisory) else {
return Err(GenerationError::Schema);
};
entry.insert(Decision {
reason: reason.into(),
matched: false,
});
Ok(())
}
pub fn apply(&mut self, report: &mut BulkLintReport) {
report.warnings.retain(|warning| {
let mut keep = true;
for site in &warning.sites {
if let Some(rule) = self
.rules
.get_mut(site)
.and_then(|rules| rules.get_mut(&warning.advisory))
{
rule.matched = true;
keep = false;
}
}
keep
});
}
pub fn stale(&self) -> impl Iterator<Item = (&BulkSite, BulkAdvisory, &str)> {
self.rules.iter().flat_map(|(site, rules)| {
rules
.iter()
.filter(|(_, rule)| !rule.matched)
.map(move |(id, rule)| (site, *id, rule.reason.as_str()))
})
}
}