use std::cell::Cell;
use datafusion::common::{DataFusionError, Result, plan_err};
use prost::encoding::{DecodeContext, decode_key, skip_field};
use prost::{DecodeError, Message};
use super::payload;
pub(super) const PROST_RECURSION_LIMIT: usize = 100;
pub(super) const MAX_DETAIL_BYTES: usize = 16 * 1024 * 1024;
pub(super) const MAX_SOURCE_DEPTH: usize = 256;
pub(super) const MAX_SOURCE_FIELDS: usize = 16_384;
pub(super) const MAX_SOURCE_ELEMENTS: usize = MAX_SOURCE_FIELDS;
#[derive(Clone, Copy, Default)]
struct Budget {
depth: usize,
fields: usize,
elements: usize,
}
thread_local! {
static BUDGET: Cell<Option<Budget>> = const { Cell::new(None) };
}
pub(super) fn decode_detail(bytes: &[u8]) -> Result<payload::MatchRecognizeRel> {
if bytes.len() > MAX_DETAIL_BYTES {
return plan_err!("MATCH_RECOGNIZE detail exceeds {MAX_DETAIL_BYTES} bytes");
}
let _scope =
DetailScope(BUDGET.with(|budget| budget.replace(Some(Budget::default()))));
charge_wire_fields(bytes)
.map_err(|error| DataFusionError::Plan(error.to_string()))?;
payload::MatchRecognizeRel::decode(bytes)
.map_err(|error| DataFusionError::Plan(error.to_string()))
}
#[allow(deprecated)]
pub(super) fn charge_wire_fields(
mut bytes: &[u8],
) -> std::result::Result<(), DecodeError> {
let previous = BUDGET.with(Cell::get);
let mut budget = previous.unwrap_or_default();
while !bytes.is_empty() {
if budget.elements == MAX_SOURCE_ELEMENTS {
return Err(DecodeError::new(format!(
"MATCH_RECOGNIZE detail exceeds {MAX_SOURCE_ELEMENTS} wire fields"
)));
}
let (tag, wire_type) = decode_key(&mut bytes)?;
skip_field(wire_type, tag, &mut bytes, DecodeContext::default())?;
budget.elements += 1;
}
if previous.is_some() {
BUDGET.with(|state| state.set(Some(budget)));
}
Ok(())
}
struct DetailScope(Option<Budget>);
impl Drop for DetailScope {
fn drop(&mut self) {
BUDGET.with(|budget| budget.set(self.0));
}
}
pub(super) struct ExpressionScope {
owns_budget: bool,
}
impl ExpressionScope {
#[allow(deprecated)]
pub(super) fn enter() -> std::result::Result<Self, DecodeError> {
let previous = BUDGET.with(Cell::get);
let mut budget = previous.unwrap_or_default();
if budget.depth == MAX_SOURCE_DEPTH {
return Err(DecodeError::new(format!(
"MATCH_RECOGNIZE source expression exceeds depth {MAX_SOURCE_DEPTH}"
)));
}
if budget.fields == MAX_SOURCE_FIELDS {
return Err(DecodeError::new(format!(
"MATCH_RECOGNIZE source expressions exceed {MAX_SOURCE_FIELDS} kind fields"
)));
}
budget.depth += 1;
budget.fields += 1;
BUDGET.with(|state| state.set(Some(budget)));
Ok(Self {
owns_budget: previous.is_none(),
})
}
}
impl Drop for ExpressionScope {
fn drop(&mut self) {
BUDGET.with(|state| {
if self.owns_budget {
state.set(None);
} else {
let mut budget = state.get().expect("source decode budget is active");
budget.depth -= 1;
state.set(Some(budget));
}
});
}
}