use crate::error::{Error, RpcError};
pub struct Request {
daiv: String,
doc: kaiv::Doc,
method: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationFailure {
pub kind: String,
pub line: usize,
pub detail: String,
}
impl ValidationFailure {
pub fn to_rpc(&self, code: i32) -> RpcError {
RpcError::new(code, self.kind.clone(), self.to_string())
}
}
impl std::fmt::Display for ValidationFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.line > 0 {
write!(f, "{} (line {})", self.detail, self.line)
} else {
f.write_str(&self.detail)
}
}
}
impl std::error::Error for ValidationFailure {}
impl Request {
pub fn parse(body: &[u8]) -> Result<Request, Error> {
let text = std::str::from_utf8(body)
.map_err(|_| Error::Parse("request body is not UTF-8".to_string()))?;
text.parse()
}
}
impl std::str::FromStr for Request {
type Err = Error;
fn from_str(text: &str) -> Result<Request, Error> {
let head = text.trim_start();
let daiv = if head.starts_with(".!daiv") {
text.to_string()
} else if head.starts_with(".!raiv") {
kaiv::denormalize(text).map_err(|e| Error::Parse(e.to_string()))?
} else {
let raiv = kaiv::compile(text.as_bytes()).map_err(|e| Error::Parse(e.to_string()))?;
kaiv::denormalize(&raiv).map_err(|e| Error::Parse(e.to_string()))?
};
let doc = kaiv::Doc::parse(&daiv).map_err(|e| Error::Parse(e.to_string()))?;
let method = doc
.root()
.value("::method")
.ok_or_else(|| Error::Envelope("method is required".to_string()))?
.to_string();
Ok(Request { daiv, doc, method })
}
}
impl Request {
pub fn validate(&self, schema: &kaiv::CompiledSchema) -> Result<(), ValidationFailure> {
kaiv::validate(&self.daiv, schema).map_err(|e| ValidationFailure {
kind: e.error.to_string(),
line: e.line,
detail: e.context,
})
}
pub fn validate_named(
&self,
resolver: &kaiv::Resolver,
schema_name: &str,
) -> Result<(), Error> {
let bytes = resolver
.csaiv_bytes(schema_name, &[])
.map_err(|e| Error::Envelope(format!("resolving {schema_name}: {e}")))?;
let text = String::from_utf8(bytes)
.map_err(|_| Error::Envelope(format!("{schema_name}.csaiv is not UTF-8")))?;
let schema = kaiv::parse_csaiv(&text).map_err(|e| Error::Envelope(e.to_string()))?;
self.validate(&schema)
.map_err(|f| Error::Invalid(Box::new(f)))
}
pub fn canonical(&self) -> &str {
&self.daiv
}
pub fn method(&self) -> &str {
&self.method
}
pub fn params<'de, T: serde::Deserialize<'de>>(&self) -> Result<T, Error> {
Ok(kaiv::serde::from_doc(&self.doc, "/params")?)
}
pub fn doc(&self) -> &kaiv::Doc {
&self.doc
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
use std::str::FromStr;
#[derive(Deserialize, Debug, PartialEq)]
struct Params {
ws: String,
#[serde(default)]
ids: Vec<String>,
#[serde(default)]
limit: i64,
}
#[test]
fn every_pipeline_stage_parses() {
let authored = ".!kaiv\nmethod=Post.MultiGet\n/params::ws=AGORA\n/params/@ids;=t3_a;t1_b\n";
let r = Request::from_str(authored).unwrap();
assert_eq!(r.method(), "Post.MultiGet");
let p: Params = r.params().unwrap();
assert_eq!(p.ws, "AGORA");
assert_eq!(p.ids, vec!["t3_a", "t1_b"]);
let canonical = concat!(
".!daiv\n",
"!str'::method=Post.MultiGet\n",
"!str'/params::ws=AGORA\n",
"!str'/params/@ids::0=t3_a\n",
"!str'/params/@ids::1=t1_b\n",
);
let r = Request::from_str(canonical).unwrap();
assert_eq!(r.method(), "Post.MultiGet");
assert_eq!(r.params::<Params>().unwrap().ids.len(), 2);
}
#[test]
fn untyped_scalars_decode_by_target_type() {
let r =
Request::from_str(".!kaiv\nmethod=X.Y\n/params::ws=A\n/params::limit=50\n").unwrap();
assert_eq!(r.params::<Params>().unwrap().limit, 50);
}
#[test]
fn a_document_without_a_method_is_refused() {
let e = match Request::from_str(".!kaiv\n/params::ws=A\n") {
Err(e) => e,
Ok(_) => panic!("a method-less document must be refused"),
};
assert!(matches!(e, Error::Envelope(_)), "{e}");
assert!(Request::from_str("this is not kaiv at all").is_err());
}
}