use std::fmt;
use std::io;
use std::path::PathBuf;
use serde::{Serialize, Serializer};
use serde_json::{Map, Value};
use crate::definition::{DefinitionFailure, Plan};
use crate::{FORMAT, Outcome, RequestError};
pub const MAX_DEFINITIONS: usize = 16;
pub const MAX_OPTIONS_BYTES: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Id {
Text(String),
Integer(i128),
}
impl Id {
#[must_use]
pub fn from_json(value: &Value) -> Option<Self> {
match value {
Value::String(text) => Some(Self::Text(text.clone())),
Value::Number(number) => number
.as_i64()
.map(i128::from)
.or_else(|| number.as_u64().map(i128::from))
.map(Self::Integer),
_ => None,
}
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Text(text) => f.write_str(&Value::String(text.clone()).to_string()),
Self::Integer(number) => write!(f, "{number}"),
}
}
}
impl Serialize for Id {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Text(text) => serializer.serialize_str(text),
Self::Integer(number) => serializer.serialize_i128(*number),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Path(PathBuf),
Text(String),
Bytes(Vec<u8>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Orientation {
#[default]
Ignore,
Apply,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub id: String,
pub plan: Result<Plan, DefinitionFailure>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Options {
pub definitions: Vec<Entry>,
pub orientation: Orientation,
}
impl Options {
pub fn from_json(value: &Value) -> Result<Self, String> {
let Value::Object(options) = value else {
return Err("`options` must be an object".to_owned());
};
if let Some(unknown) = options
.keys()
.find(|key| !matches!(key.as_str(), "format" | "definitions" | "orientation"))
{
return Err(format!(
"`options` has no key `{unknown}`; it takes `format`, `definitions` and `orientation`"
));
}
match options.get("format") {
Some(format) if format.as_u64() == Some(u64::from(FORMAT)) => {}
Some(format) => {
return Err(format!(
"this runner reads format `{FORMAT}`, not `{format}`; check `info` for the format it speaks"
));
}
None => return Err(format!("`options` needs `\"format\": {FORMAT}`")),
}
let orientation = match options.get("orientation").map(Value::as_str) {
None | Some(Some("ignore")) => Orientation::Ignore,
Some(Some("apply")) => Orientation::Apply,
Some(_) => return Err("`orientation` is `\"ignore\"` or `\"apply\"`".to_owned()),
};
let entries = match options.get("definitions") {
Some(Value::Array(entries)) if !entries.is_empty() => entries,
_ => return Err("`options` needs `definitions`, a list of one or more `{\"id\": ...}` objects".to_owned()),
};
if entries.len() > MAX_DEFINITIONS {
return Err(format!(
"`definitions` holds `{}` entries; a request asks for at most `{MAX_DEFINITIONS}`",
entries.len()
));
}
let definitions = entries
.iter()
.enumerate()
.map(|(index, entry)| match entry {
Value::Object(entry) => match entry.get("id") {
Some(Value::String(id)) => Ok(Entry {
id: id.clone(),
plan: Plan::from_entry(id, entry),
}),
_ => Err(format!("`definitions[{index}]` needs a string `id`")),
},
_ => Err(format!("`definitions[{index}]` must be an object with an `id`")),
})
.collect::<Result<Vec<Entry>, _>>()?;
for later in 1..definitions.len() {
let repeats = (0..later).find(|&earlier| {
entries[earlier] == entries[later]
|| matches!((&definitions[earlier].plan, &definitions[later].plan), (Ok(a), Ok(b)) if a == b)
});
if let Some(earlier) = repeats {
return Err(format!(
"`definitions[{later}]` repeats `definitions[{earlier}]`: the same definition with the same parameters"
));
}
}
Ok(Self {
definitions,
orientation,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub id: Id,
pub source: Source,
pub options: Options,
}
impl Request {
pub fn from_json(line: &[u8]) -> Result<Self, Box<Outcome>> {
let fail = |id: Option<&Id>, code, message: String| Box::new(Outcome::error(id.cloned(), code, message));
let request: Map<String, Value> = match serde_json::from_slice(line) {
Ok(Value::Object(request)) => request,
Ok(_) => {
return Err(fail(
None,
RequestError::InvalidRequest,
"a request must be a JSON object".to_owned(),
));
}
Err(error) => {
return Err(fail(
None,
RequestError::InvalidRequest,
format!("the line isn't JSON: {error}"),
));
}
};
let id = match request.get("id").map(Id::from_json) {
Some(Some(id)) => id,
Some(None) => {
return Err(fail(
None,
RequestError::InvalidRequest,
"`id` must be a string or an integer".to_owned(),
));
}
None => {
return Err(fail(
None,
RequestError::InvalidRequest,
"the request has no `id`".to_owned(),
));
}
};
if let Some(unknown) = request
.keys()
.find(|key| !matches!(key.as_str(), "id" | "path" | "text" | "base64" | "options"))
{
return Err(fail(
Some(&id),
RequestError::InvalidRequest,
format!("a request has no field `{unknown}`; it takes `id`, `path`, `text`, `base64` and `options`"),
));
}
let sources: Vec<(&str, &Value)> = ["path", "text", "base64"]
.into_iter()
.filter_map(|name| request.get(name).map(|value| (name, value)))
.collect();
let source = match sources.as_slice() {
[(name, value)] => source(name, value).map_err(|(code, message)| fail(Some(&id), code, message))?,
[] => {
return Err(fail(
Some(&id),
RequestError::NoSource,
"the request needs one source: `path`, `text` or `base64`".to_owned(),
));
}
_ => {
return Err(fail(
Some(&id),
RequestError::NoSource,
"the request gives more than one source; give exactly one of `path`, `text` and `base64`"
.to_owned(),
));
}
};
let options = match request.get("options") {
Some(options) if longer_than(options, MAX_OPTIONS_BYTES) => {
Err(format!("`options` is more than `{MAX_OPTIONS_BYTES}` bytes of JSON"))
}
Some(options) => Options::from_json(options),
None => Err("the request has no `options`".to_owned()),
}
.map_err(|message| fail(Some(&id), RequestError::InvalidOptions, message))?;
Ok(Self { id, source, options })
}
}
fn longer_than(value: &Value, most: usize) -> bool {
struct Count {
bytes: usize,
most: usize,
}
impl io::Write for Count {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
self.bytes += buffer.len();
if self.bytes > self.most {
return Err(io::Error::other("over the limit"));
}
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
serde_json::to_writer(&mut Count { bytes: 0, most }, value).is_err()
}
fn source(name: &str, value: &Value) -> Result<Source, (RequestError, String)> {
let Value::String(text) = value else {
return Err((RequestError::InvalidRequest, format!("`{name}` must be a string")));
};
match name {
"path" if text.is_empty() => Err((RequestError::InvalidRequest, "`path` is empty".to_owned())),
"path" => Ok(Source::Path(PathBuf::from(text))),
"text" => Ok(Source::Text(text.clone())),
_ => inline_bytes(name, text).map(Source::Bytes),
}
}
pub(crate) fn inline_bytes(name: &str, text: &str) -> Result<Vec<u8>, (RequestError, String)> {
let longest = legit_hashes::DECODE_MAX_INPUT;
if text.len() / 4 * 3 > longest {
return Err((
RequestError::TooLarge,
format!("the {name} holds more than `{longest}` bytes, the most the decoder reads"),
));
}
crate::base64::decode(text).map_err(|message| (RequestError::InvalidRequest, format!("`{name}` {message}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_print_as_json_so_equal_ids_compare_equal() {
assert_eq!(Id::Text("a\"b".to_owned()).to_string(), r#""a\"b""#);
assert_eq!(Id::Integer(-3).to_string(), "-3");
assert_eq!(
Id::from_json(&serde_json::json!(u64::MAX)),
Some(Id::Integer(i128::from(u64::MAX)))
);
assert_eq!(Id::from_json(&serde_json::json!(1.5)), None);
assert_eq!(Id::from_json(&serde_json::json!(null)), None);
}
#[test]
fn a_request_is_read_with_its_definitions() {
let request = Request::from_json(
br#"{"id":7,"text":"hello","options":{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"},{"id":"nope-v1"}]}}"#,
)
.expect("valid");
assert_eq!(request.id, Id::Integer(7));
assert_eq!(request.source, Source::Text("hello".to_owned()));
assert_eq!(request.options.definitions.len(), 2);
assert!(request.options.definitions[0].plan.is_ok());
assert!(request.options.definitions[1].plan.is_err());
}
#[test]
fn each_malformed_request_has_its_code() {
let cases: [(&str, RequestError, bool); 12] = [
("not json", RequestError::InvalidRequest, false),
("[1]", RequestError::InvalidRequest, false),
(r#"{"text":"x"}"#, RequestError::InvalidRequest, false),
(r#"{"id":true,"text":"x"}"#, RequestError::InvalidRequest, false),
(
r#"{"id":"a","text":"x","extra":1,"options":{}}"#,
RequestError::InvalidRequest,
true,
),
(r#"{"id":"a","options":{}}"#, RequestError::NoSource, true),
(
r#"{"id":"a","text":"x","path":"y","options":{}}"#,
RequestError::NoSource,
true,
),
(
r#"{"id":"a","base64":"!!!!","options":{}}"#,
RequestError::InvalidRequest,
true,
),
(r#"{"id":"a","text":"x"}"#, RequestError::InvalidOptions, true),
(
r#"{"id":"a","text":"x","options":{"definitions":[{"id":"pdq-v1"}]}}"#,
RequestError::InvalidOptions,
true,
),
(
r#"{"id":"a","text":"x","options":{"format":2,"definitions":[{"id":"pdq-v1"}]}}"#,
RequestError::InvalidOptions,
true,
),
(
r#"{"id":"a","text":"x","options":{"format":1,"definitions":["pdq-v1"]}}"#,
RequestError::InvalidOptions,
true,
),
];
for (line, code, has_id) in cases {
let outcome = Request::from_json(line.as_bytes()).expect_err(line);
assert_eq!(outcome.error_type, Some(code), "{line}");
assert_eq!(outcome.id.is_some(), has_id, "{line}");
}
}
}