zebra_node_services/scan_service/
request.rsuse std::collections::HashSet;
use crate::BoxError;
const MAX_REQUEST_KEYS: usize = 1000;
#[derive(Debug)]
pub enum Request {
Info,
RegisterKeys(Vec<(String, Option<u32>)>),
DeleteKeys(Vec<String>),
Results(Vec<String>),
SubscribeResults(HashSet<String>),
ClearResults(Vec<String>),
}
impl Request {
pub fn check(&self) -> Result<(), BoxError> {
self.check_num_keys()?;
Ok(())
}
fn check_num_keys(&self) -> Result<(), BoxError> {
match self {
Request::DeleteKeys(keys) | Request::ClearResults(keys)
if keys.is_empty() || keys.len() > MAX_REQUEST_KEYS =>
{
Err(format!("request must include between 1 and {MAX_REQUEST_KEYS} keys").into())
}
_ => Ok(()),
}
}
}
#[test]
fn test_check_num_keys() {
let fake_keys: Vec<_> = std::iter::repeat(String::new())
.take(MAX_REQUEST_KEYS + 1)
.collect();
let bad_requests = [
Request::DeleteKeys(vec![]),
Request::DeleteKeys(fake_keys.clone()),
Request::ClearResults(vec![]),
Request::ClearResults(fake_keys),
];
let valid_requests = [
Request::DeleteKeys(vec![String::new()]),
Request::ClearResults(vec![String::new()]),
];
for request in bad_requests {
let error = request.check().expect_err("check should return an error");
assert_eq!(
format!("request must include between 1 and {MAX_REQUEST_KEYS} keys"),
error.to_string(),
"check_num_keys should return an error because there are too many keys"
);
}
for request in valid_requests {
request.check().expect("check should return Ok(())");
}
}