use std::collections::HashSet;
use std::fmt;
use serde::de::{self, DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde_json::{Map, Value as Json};
use super::FORMAT;
use super::error::{ErrorType, ServiceError};
use super::limits::{Lane, Limits};
use super::log::ChangeName;
use crate::value::Value;
const SEARCH_KEYS: [&str; 8] = [
"format",
"index",
"width",
"radius",
"values",
"subset",
"limit",
"exclude_zero",
];
const STATS_KEYS: [&str; 3] = ["format", "index", "subset"];
const CHANGE_KEYS: [&str; 5] = ["format", "index", "width", "records", "subset"];
const REMOVE_KEYS: [&str; 5] = ["format", "index", "width", "ids", "subset"];
const QUOTED: usize = 64;
#[must_use]
pub fn is_valid_name(name: &str) -> bool {
(1..=32).contains(&name.len())
&& name
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-'))
}
#[must_use]
pub fn shorten(text: &str, chars: usize) -> &str {
text.char_indices().nth(chars).map_or(text, |(end, _)| &text[..end])
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Values {
W64(Vec<u64>),
W256(Vec<[u64; 4]>),
}
impl Values {
pub(crate) fn len(&self) -> usize {
match self {
Self::W64(values) => values.len(),
Self::W256(values) => values.len(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SearchRequest {
pub(crate) index: String,
pub(crate) subset: Option<String>,
pub(crate) width: u32,
pub(crate) radius: u32,
pub(crate) values: Values,
pub(crate) limit: Option<usize>,
pub(crate) exclude_zero: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StatsRequest {
pub(crate) index: String,
pub(crate) subset: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ChangeRecords {
W64(Vec<(u64, u64)>),
W256(Vec<(u64, [u64; 4])>),
Remove(Vec<u64>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChangeRequest {
pub(crate) index: String,
pub(crate) width: u32,
pub(crate) name: ChangeName,
pub(crate) records: ChangeRecords,
}
pub(crate) fn change(text: &str, limits: &Limits, name: ChangeName) -> Result<ChangeRequest, ServiceError> {
let keys: &[&str] = if name == ChangeName::Remove {
&REMOVE_KEYS
} else {
&CHANGE_KEYS
};
let (key, most, what) = match name {
ChangeName::Remove => ("ids", limits.max_remove_ids, "a list of ids"),
_ => ("records", limits.max_change_records, "a list of `[id, hex]` pairs"),
};
let (object, listed) = object(text, limits, keys, Some((key, most)))?;
let (index, subset) = names(&object)?;
if subset.is_some() {
return Err(ServiceError::invalid(
"a change can't name a `subset`: subsets are snapshots only, replaced by the next export",
));
}
let width = match object.get("width") {
Some(Json::Number(number)) if number.as_u64() == Some(64) => 64,
Some(Json::Number(number)) if number.as_u64() == Some(256) => 256,
Some(_) => return Err(ServiceError::invalid("`width` is 64 or 256")),
None => return Err(ServiceError::invalid("`options` needs `width`, 64 or 256")),
};
let list = match object.get(key) {
Some(Json::Array(list)) if !list.is_empty() => list,
Some(Json::Array(_)) => return Err(ServiceError::invalid(format!("`{key}` is empty; give at least one"))),
Some(_) => return Err(ServiceError::invalid(format!("`{key}` is {what}"))),
None => return Err(ServiceError::invalid(format!("`options` needs `{key}`, {what}"))),
};
let count = listed.unwrap_or(list.len());
if count > most {
return Err(ServiceError::new(
ErrorType::TooManyValues,
format!(
"the task holds {count} {key}; {} `{}` task takes at most {most}",
if name.as_str().starts_with(['a', 'e', 'i', 'o', 'u']) {
"an"
} else {
"a"
},
name.as_str()
),
));
}
let records = match (name, width) {
(ChangeName::Remove, _) => {
let ids = list
.iter()
.enumerate()
.map(|(position, id)| {
id.as_u64().ok_or_else(|| {
ServiceError::invalid(format!(
"id {position} (from 0) isn't a whole number from 0 to 2^64 - 1"
))
})
})
.collect::<Result<Vec<u64>, _>>()?;
rising(ids.iter().copied())?;
ChangeRecords::Remove(ids)
}
(_, 64) => ChangeRecords::W64(pairs(list)?),
_ => ChangeRecords::W256(pairs(list)?),
};
Ok(ChangeRequest {
index,
width,
name,
records,
})
}
fn pairs<V: Value>(list: &[Json]) -> Result<Vec<(u64, V)>, ServiceError> {
let records = list
.iter()
.enumerate()
.map(|(position, record)| match record.as_array().map(Vec::as_slice) {
Some([id, Json::String(hex)]) => {
let id = id.as_u64().ok_or_else(|| {
ServiceError::invalid(format!(
"record {position} (from 0): its id isn't a whole number from 0 to 2^64 - 1"
))
})?;
let value = V::from_hex(hex).map_err(|_| {
ServiceError::invalid(format!(
"record {position} (from 0): its value isn't {} hex digits",
V::WORDS * 16
))
})?;
Ok((id, value))
}
_ => Err(ServiceError::invalid(format!(
"record {position} (from 0) isn't an `[id, hex]` pair"
))),
})
.collect::<Result<Vec<_>, _>>()?;
rising(records.iter().map(|&(id, _)| id))?;
Ok(records)
}
fn rising(ids: impl Iterator<Item = u64>) -> Result<(), ServiceError> {
let mut previous = None;
for (position, id) in ids.enumerate() {
if previous.is_some_and(|previous| id <= previous) {
return Err(ServiceError::invalid(format!(
"id {position} (from 0) isn't above the id before it; a task's ids rise"
)));
}
previous = Some(id);
}
Ok(())
}
pub(crate) fn search(text: &str, limits: &Limits, lane: Lane) -> Result<SearchRequest, ServiceError> {
let most = limits.max_values(lane);
let (object, listed) = object(text, limits, &SEARCH_KEYS, Some(("values", most)))?;
let (index, subset) = names(&object)?;
let width = match object.get("width") {
Some(Json::Number(number)) if number.as_u64() == Some(64) => 64,
Some(Json::Number(number)) if number.as_u64() == Some(256) => 256,
Some(_) => return Err(ServiceError::invalid("`width` is 64 or 256")),
None => return Err(ServiceError::invalid("`options` needs `width`, 64 or 256")),
};
let radius = match object.get("radius") {
Some(Json::Number(number)) => number
.as_u64()
.ok_or_else(|| ServiceError::invalid("`radius` is a whole number of at least 0"))?,
Some(_) => return Err(ServiceError::invalid("`radius` is a whole number of at least 0")),
None => return Err(ServiceError::invalid("`options` needs `radius`")),
};
let limit = match object.get("limit") {
None | Some(Json::Null) => None,
Some(Json::Number(number)) => match number.as_u64() {
Some(limit) if limit > 0 => Some(usize::try_from(limit).unwrap_or(usize::MAX)),
_ => return Err(ServiceError::invalid("`limit` is a whole number of at least 1")),
},
Some(_) => return Err(ServiceError::invalid("`limit` is a whole number of at least 1")),
};
let exclude_zero = match object.get("exclude_zero") {
None | Some(Json::Null) => false,
Some(Json::Bool(exclude)) => *exclude,
Some(_) => return Err(ServiceError::invalid("`exclude_zero` is true or false")),
};
let values = match object.get("values") {
Some(Json::Array(values)) if !values.is_empty() => values,
Some(Json::Array(_)) => return Err(ServiceError::invalid("`values` holds no value; give at least one")),
Some(_) => return Err(ServiceError::invalid("`values` is a list of hex strings")),
None => return Err(ServiceError::invalid("`options` needs `values`, a list of hex strings")),
};
let count = listed.unwrap_or(values.len());
if count > most {
return Err(ServiceError::new(
ErrorType::TooManyValues,
format!(
"the request holds {count} values; the {} lane takes at most {most}",
lane.name()
),
));
}
let max_radius = limits.max_radius(width).unwrap_or(0);
if radius > u64::from(max_radius) {
let mut error = ServiceError::new(
ErrorType::RadiusTooLarge,
format!("radius {radius} is above {max_radius}, the largest this service searches at {width} bits"),
);
error.max_radius = Some(max_radius);
return Err(error);
}
let values = if width == 64 {
Values::W64(parse_values(values)?)
} else {
Values::W256(parse_values(values)?)
};
Ok(SearchRequest {
index,
subset,
width,
radius: u32::try_from(radius).unwrap_or(u32::MAX),
values,
limit,
exclude_zero,
})
}
pub(crate) fn stats(text: &str, limits: &Limits) -> Result<StatsRequest, ServiceError> {
let (object, _) = object(text, limits, &STATS_KEYS, None)?;
let (index, subset) = names(&object)?;
Ok(StatsRequest { index, subset })
}
fn object(
text: &str,
limits: &Limits,
allowed: &[&str],
list: Option<(&str, usize)>,
) -> Result<(Map<String, Json>, Option<usize>), ServiceError> {
if text.len() > limits.max_options_bytes {
return Err(ServiceError::invalid(format!(
"`options` is {} bytes of JSON; it may be at most {}",
text.len(),
limits.max_options_bytes
)));
}
if text.trim().is_empty() {
return Err(ServiceError::invalid("the request has no `options`"));
}
let mut json = serde_json::Deserializer::from_str(text);
let seed = OptionsSeed { allowed, list };
let read = match seed.deserialize(&mut json).and_then(|read| json.end().map(|()| read)) {
Ok(read) => read,
Err(error) => return Err(ServiceError::invalid(format!("`options` isn't JSON: {error}"))),
};
let Some(read) = read else {
return Err(ServiceError::invalid("`options` is a JSON object"));
};
if let Some(key) = read.twice {
return Err(ServiceError::invalid(format!(
"`options` gives the key `{}` twice; each key is given once",
shorten(&key, QUOTED)
)));
}
if let Some(key) = read.unknown {
return Err(ServiceError::invalid(format!(
"`options` has a key `{}` this request doesn't take; it takes `{}`",
shorten(&key, QUOTED),
allowed.join("`, `")
)));
}
let object = read.object;
let listed = read.listed;
match object.get("format") {
Some(Json::Number(number)) if number.as_u64() == Some(u64::from(FORMAT)) => Ok((object, listed)),
Some(_) => Err(ServiceError::invalid(format!(
"`format` is {FORMAT}, the only version of the options this service reads"
))),
None => Err(ServiceError::invalid(format!("`options` needs `format`: {FORMAT}"))),
}
}
fn names(object: &Map<String, Json>) -> Result<(String, Option<String>), ServiceError> {
let index = match object.get("index") {
Some(Json::String(index)) => index.clone(),
Some(_) => return Err(ServiceError::invalid("`index` is a name")),
None => return Err(ServiceError::invalid("`options` needs `index`, the index to search")),
};
let subset = match object.get("subset") {
None | Some(Json::Null) => None,
Some(Json::String(subset)) => Some(subset.clone()),
Some(_) => return Err(ServiceError::invalid("`subset` is a name")),
};
Ok((index, subset))
}
fn parse_values<V: Value>(values: &[Json]) -> Result<Vec<V>, ServiceError> {
values
.iter()
.enumerate()
.map(|(position, value)| {
let digits = V::WORDS * 16;
let wrong = match value {
Json::String(hex) => match V::from_hex(hex) {
Ok(value) => return Ok(value),
Err(_) if hex.chars().count() != digits => format!("is {} characters long", hex.chars().count()),
Err(_) => "holds a character that isn't a hex digit".to_owned(),
},
_ => "isn't a string".to_owned(),
};
Err(ServiceError::invalid(format!(
"`values[{position}]` {wrong}; a value at this width is {digits} hex digits"
)))
})
.collect()
}
struct Read {
object: Map<String, Json>,
twice: Option<String>,
unknown: Option<String>,
listed: Option<usize>,
}
const ELEMENT_KEEP: usize = 3;
struct OptionsSeed<'a> {
allowed: &'a [&'a str],
list: Option<(&'a str, usize)>,
}
impl<'de> DeserializeSeed<'de> for OptionsSeed<'_> {
type Value = Option<Read>;
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for OptionsSeed<'_> {
type Value = Option<Read>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut read = Read {
object: Map::new(),
twice: None,
unknown: None,
listed: None,
};
let mut seen: HashSet<String> = HashSet::new();
while let Some(key) = map.next_key::<String>()? {
if !self.allowed.contains(&key.as_str()) {
read.unknown.get_or_insert(key);
map.next_value::<IgnoredAny>()?;
} else if seen.contains(&key) {
read.twice.get_or_insert(key);
map.next_value::<IgnoredAny>()?;
} else {
let shape = match self.list {
Some((list, bound)) if list == key => Shallow { levels: 2, keep: bound },
_ => Shallow { levels: 0, keep: 0 },
};
let (value, count) = map.next_value_seed(shape)?;
if self.list.is_some_and(|(list, _)| list == key) {
read.listed = count;
}
seen.insert(key.clone());
read.object.insert(key, value);
}
}
Ok(Some(read))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(None)
}
fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
}
#[derive(Clone, Copy)]
struct Shallow {
levels: u8,
keep: usize,
}
impl<'de> DeserializeSeed<'de> for Shallow {
type Value = (Json, Option<usize>);
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for Shallow {
type Value = (Json, Option<usize>);
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON value")
}
fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
Ok((Json::Bool(value), None))
}
fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
Ok((Json::from(value), None))
}
fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
Ok((Json::from(value), None))
}
fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
Ok((Json::from(value), None))
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
Ok((Json::String(value.to_owned()), None))
}
fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
Ok((Json::String(value), None))
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok((Json::Null, None))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut held = Vec::new();
let mut count = 0usize;
loop {
if self.levels > 0 && count < self.keep {
let element = Self {
levels: self.levels - 1,
keep: ELEMENT_KEEP,
};
match seq.next_element_seed(element)? {
Some((value, _)) => held.push(value),
None => break,
}
} else if seq.next_element::<IgnoredAny>()?.is_none() {
break;
}
count = count.saturating_add(1);
}
Ok((Json::Array(held), Some(count)))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
Ok((Json::Object(Map::new()), None))
}
}
pub(crate) fn unknown(error_type: ErrorType, what: &str, name: &str) -> ServiceError {
ServiceError::new(
error_type,
format!("this service serves no {what} `{}`", shorten(name, QUOTED)),
)
}
#[cfg(test)]
mod tests {
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use super::*;
struct Counting;
thread_local! {
static ALLOCATED: Cell<usize> = const { Cell::new(0) };
}
#[expect(
unsafe_code,
reason = "a global allocator, which passes each call on to the system's"
)]
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCATED.with(|allocated| allocated.set(allocated.get().saturating_add(layout.size())));
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
unsafe { System.dealloc(pointer, layout) }
}
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
ALLOCATED.with(|allocated| allocated.set(allocated.get().saturating_add(size)));
unsafe { System.realloc(pointer, layout, size) }
}
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
fn allocated(work: impl FnOnce()) -> usize {
let before = ALLOCATED.with(Cell::get);
work();
ALLOCATED.with(Cell::get) - before
}
#[test]
fn a_task_of_a_million_values_is_refused_without_holding_them() {
let limits = Limits::new();
let values = vec!["0"; (limits.max_options_bytes - 100) / 2].join(",");
let text = format!(r#"{{"format":1,"index":"images","width":64,"radius":2,"values":[{values}]}}"#);
assert!(text.len() <= limits.max_options_bytes);
let mut refused = None;
let bytes = allocated(|| refused = Some(search(&text, &limits, Lane::Fast)));
let error = refused.expect("ran").expect_err("refused");
assert_eq!(error.error_type, ErrorType::TooManyValues);
assert!(
error
.message
.contains(&format!("{}", (limits.max_options_bytes - 100) / 2))
);
let tree = allocated(|| drop(serde_json::from_str::<Json>(&text)));
assert!(bytes < 64 << 10, "{bytes} bytes held to refuse it; a tree takes {tree}");
assert!(tree > 100 * bytes);
let records = vec![r#"[1,"0000000000000000"]"#; 40_000].join(",");
let text = format!(r#"{{"format":1,"index":"images","width":64,"records":[{records}]}}"#);
let bytes = allocated(|| {
let error = change(&text, &limits, ChangeName::Append).expect_err("refused");
assert_eq!(error.error_type, ErrorType::TooManyValues);
});
let tree = allocated(|| drop(serde_json::from_str::<Json>(&text)));
assert!(
bytes < 512 << 10 && tree > 20 * bytes,
"{bytes} bytes held to refuse it; a tree takes {tree}"
);
let text = format!(r#"{{"format":1,"index":"images","width":64,"radius":2,"values":[],"other":[{values}]}}"#);
let bytes = allocated(|| {
let error = search(&text, &limits, Lane::Bulk).expect_err("refused");
assert!(error.message.contains("`other`"));
});
assert!(bytes < 64 << 10, "{bytes} bytes held to refuse it");
}
#[test]
fn a_value_out_of_its_place_is_read_as_the_wrong_type_it_is() {
let limits = Limits::new();
let cases = [
(r#""width":[64]"#, "`width` is 64 or 256"),
(r#""width":{"a":64}"#, "`width` is 64 or 256"),
(r#""radius":[1]"#, "`radius` is a whole number"),
(r#""limit":[[2]]"#, "`limit` is a whole number"),
(r#""limit":1.5"#, "`limit` is a whole number"),
(r#""exclude_zero":[]"#, "`exclude_zero` is true or false"),
(r#""subset":["a"]"#, "`subset` is a name"),
];
for (field, message) in cases {
let mut object: Map<String, Json> =
serde_json::from_str(r#"{"format":1,"index":"images","width":64,"radius":2,"values":["0"]}"#)
.expect("JSON");
let (key, value) = field.split_once(':').expect("a field");
object.insert(
serde_json::from_str(key).expect("a key"),
serde_json::from_str(value).expect("a value"),
);
let text = Json::Object(object).to_string();
let error = search(&text, &limits, Lane::Bulk).expect_err("refused");
assert!(error.message.contains(message), "{field}: {}", error.message);
}
for records in [
r#"[[1,"0000000000000000",3]]"#,
r#"[[1,["0000000000000000"]]]"#,
r#"[{"id":1}]"#,
] {
let text = format!(r#"{{"format":1,"index":"images","width":64,"records":{records}}}"#);
let error = change(&text, &limits, ChangeName::Replace).expect_err("refused");
assert!(
error.message.contains("isn't an `[id, hex]` pair"),
"{records}: {}",
error.message
);
}
let error = change(
r#"{"format":1,"index":"images","width":64,"ids":[[1]]}"#,
&limits,
ChangeName::Remove,
)
.expect_err("refused");
assert!(error.message.contains("isn't a whole number"), "{}", error.message);
}
}