#[cfg(feature = "yaml")]
use std::fmt;
#[cfg(feature = "yaml")]
use std::path::Path;
use std::sync::{PoisonError, RwLock};
#[cfg(feature = "yaml")]
use std::{fs, io};
use serde::Deserialize;
#[cfg(feature = "yaml")]
use serde_saphyr::Budget;
#[cfg(feature = "yaml")]
use serde_saphyr::options::AliasLimits;
#[cfg(feature = "yaml")]
use super::format::Raise;
#[cfg(feature = "yaml")]
use super::{Input, InputError};
#[cfg(feature = "yaml")]
pub const REPO_FILE: &str = ".ctl/input.yaml";
macro_rules! limits {
(
shared { $( $(#[$sdoc:meta])* $sfield:ident = $sdefault:ident, )* }
yaml { $( $(#[$ydoc:meta])* $yfield:ident: $yty:ty, )* }
replay { $( $(#[$rdoc:meta])* $rfield:ident, )* }
) => {
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct Limits {
$( $(#[$sdoc])* pub $sfield: Option<usize>, )*
$( $(#[$ydoc])* #[cfg(feature = "yaml")] pub $yfield: Option<$yty>, )*
$( $(#[$rdoc])* #[cfg(feature = "yaml")] pub $rfield: Option<usize>, )*
}
impl Limits {
pub const NONE: Self = Self {
$( $sfield: None, )*
$( #[cfg(feature = "yaml")] $yfield: None, )*
$( #[cfg(feature = "yaml")] $rfield: None, )*
};
#[must_use]
pub fn or(self, lower: &Self) -> Self {
Self {
$( $sfield: self.$sfield.or(lower.$sfield), )*
$( #[cfg(feature = "yaml")] $yfield: self.$yfield.or(lower.$yfield), )*
$( #[cfg(feature = "yaml")] $rfield: self.$rfield.or(lower.$rfield), )*
}
}
#[cfg(feature = "yaml")]
pub(super) fn budget(&self) -> Budget {
let bounds = self.bounds();
let mut budget = Budget::default();
budget.max_reader_input_bytes = Some(bounds.input_bytes);
budget.max_depth = bounds.depth;
budget.max_nodes = bounds.nodes;
$( if let Some(value) = self.$yfield {
budget.$yfield = value;
} )*
budget
}
#[cfg(feature = "yaml")]
pub(super) fn alias_limits(&self) -> AliasLimits {
let mut limits = AliasLimits::default();
$( if let Some(value) = self.$rfield {
limits.$rfield = value;
} )*
limits
}
#[cfg(feature = "yaml")]
fn loosened(&self) -> Vec<Loosened> {
let mut loosened = Vec::new();
$( if let Some(value) = self.$sfield
&& value > Self::$sdefault
{
loosened.push(Loosened {
field: stringify!($sfield),
value: value.to_string(),
default: Self::$sdefault.to_string(),
});
} )*
let default = Budget::default();
$( if let Some(value) = self.$yfield
&& value > default.$yfield
{
loosened.push(Loosened {
field: stringify!($yfield),
value: value.to_string(),
default: default.$yfield.to_string(),
});
} )*
let default = AliasLimits::default();
$( if let Some(value) = self.$rfield
&& value > default.$rfield
{
loosened.push(Loosened {
field: stringify!($rfield),
value: value.to_string(),
default: default.$rfield.to_string(),
});
} )*
loosened
}
}
};
}
limits! {
shared {
max_reader_input_bytes = DEFAULT_MAX_READER_INPUT_BYTES,
max_depth = DEFAULT_MAX_DEPTH,
max_nodes = DEFAULT_MAX_NODES,
}
yaml {
max_buffered_comment_events: usize,
simple_key_max_lookahead: usize,
flow_nesting_limit: usize,
max_events: usize,
max_aliases: usize,
max_anchors: usize,
max_recorded_anchor_events: usize,
max_recorded_anchor_bytes: usize,
max_property_expansion_depth: usize,
max_total_property_interpolation_work: usize,
max_inclusion_depth: u32,
max_documents: usize,
max_total_scalar_bytes: usize,
max_total_comment_bytes: usize,
max_merge_keys: usize,
alias_anchor_min_aliases: usize,
alias_anchor_ratio_multiplier: usize,
}
replay {
max_total_replayed_events,
max_replay_stack_depth,
max_alias_expansions_per_anchor,
}
}
impl Limits {
pub const DEFAULT_MAX_READER_INPUT_BYTES: usize = 256 * 1024 * 1024;
pub const DEFAULT_MAX_DEPTH: usize = 64;
pub const DEFAULT_MAX_NODES: usize = 250_000;
pub(super) fn bounds(&self) -> Bounds {
Bounds {
input_bytes: self
.max_reader_input_bytes
.unwrap_or(Self::DEFAULT_MAX_READER_INPUT_BYTES),
depth: self.max_depth.unwrap_or(Self::DEFAULT_MAX_DEPTH),
nodes: self.max_nodes.unwrap_or(Self::DEFAULT_MAX_NODES),
}
}
}
#[derive(Clone, Copy)]
pub(super) struct Bounds {
pub(super) input_bytes: usize,
pub(super) depth: usize,
pub(super) nodes: usize,
}
static PROCESS: RwLock<Limits> = RwLock::new(Limits::NONE);
#[cfg(feature = "yaml")]
static REPOSITORY: RwLock<Limits> = RwLock::new(Limits::NONE);
pub fn set_default_limits(limits: Limits) {
*PROCESS.write().unwrap_or_else(PoisonError::into_inner) = limits;
}
#[cfg(feature = "yaml")]
pub fn use_repo_limits(root: &Path) -> Result<Vec<Loosened>, InputError> {
let path = root.join(REPO_FILE);
let limits = match fs::read_to_string(&path) {
Ok(text) => {
let process = PROCESS
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone();
Input::new(path.display().to_string(), text)
.parse_within::<RepoFile>(&process, Raise::InProcess)?
.limits
}
Err(error) if error.kind() == io::ErrorKind::NotFound => Limits::NONE,
Err(error) => {
return Err(InputError::unread(path.display().to_string(), &error));
}
};
let loosened = limits.loosened();
*REPOSITORY.write().unwrap_or_else(PoisonError::into_inner) = limits;
Ok(loosened)
}
#[cfg(feature = "yaml")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Loosened {
pub field: &'static str,
pub value: String,
pub default: String,
}
#[cfg(feature = "yaml")]
impl fmt::Display for Loosened {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{REPO_FILE} raises {} to {}, above the default {}",
self.field, self.value, self.default
)
}
}
#[cfg(feature = "yaml")]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RepoFile {
#[serde(default)]
limits: Limits,
}
pub(super) fn effective(call: &Limits) -> Limits {
let process = PROCESS.read().unwrap_or_else(PoisonError::into_inner);
#[cfg(feature = "yaml")]
let call = call
.clone()
.or(&REPOSITORY.read().unwrap_or_else(PoisonError::into_inner));
#[cfg(not(feature = "yaml"))]
let call = call.clone();
call.or(&process)
}
#[cfg(all(test, feature = "yaml"))]
mod tests {
use serde_saphyr::Budget;
use super::Limits;
#[test]
fn the_shared_defaults_match_serde_saphyr() {
let budget = Budget::default();
assert_eq!(
budget.max_reader_input_bytes,
Some(Limits::DEFAULT_MAX_READER_INPUT_BYTES)
);
assert_eq!(budget.max_depth, Limits::DEFAULT_MAX_DEPTH);
assert_eq!(budget.max_nodes, Limits::DEFAULT_MAX_NODES);
}
}