kaivrpc 0.2.0

RPC over kaiv documents: the request/response envelope, typed params, and line-per-element streaming
Documentation
//! The request side: a document in, a method name and typed
//! params out.

use crate::error::{Error, RpcError};

/// A parsed kaivrpc request.
///
/// Accepts any pipeline stage, so a caller may send whichever form
/// it has: authored `.kaiv` (compiled and denormalized here),
/// relational `.raiv` (denormalized), or canonical `.daiv` (used
/// as is). Authored is the idiomatic form for a human-written or
/// client-generated request; canonical is what a machine already
/// holding a built document would send.
pub struct Request {
    daiv: String,
    doc: kaiv::Doc,
    method: String,
}

/// A request that did not satisfy its method's schema.
///
/// The parts are kept separate because the useful thing about a
/// kaiv refusal is WHERE it points: `line` indexes the caller's
/// own document, so the error a client receives names the line it
/// wrote. Application error codes are the application's
/// vocabulary, so pick one with [`to_rpc`](Self::to_rpc).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationFailure {
    /// The kaiv error name — `ConstraintViolationError`,
    /// `CardinalityViolationError`, `RequiredFieldSchemaError`, …
    pub kind: String,
    /// 1-based line in the request document; 0 when the failure is
    /// not tied to one line (a field missing at end of input).
    pub line: usize,
    /// The site description: the namepath, the value, and the
    /// constraint it violated.
    pub detail: String,
}

impl ValidationFailure {
    /// Render as an [`RpcError`] under an application error code
    /// of your choosing (the name stays the kaiv error kind).
    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 {
    /// Parse a request body.
    ///
    /// The document must carry a root `method` scalar (authored
    /// `method=Post.Get`, canonical `!str'::method=Post.Get`);
    /// arguments live under `/params`.
    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()
    }
}

/// [`Request::parse`] for a body already known to be text, so
/// `text.parse::<Request>()` works.
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 {
    /// Validate against the method's compiled request schema.
    ///
    /// This is the move JSON-RPC cannot make: the method's schema
    /// types the ENVELOPE and the arguments together, so one pass
    /// checks that the method is the one this schema pins, that
    /// every argument matches its domain type, and that
    /// collections are within their declared bounds — replacing
    /// the hand-written guard whose clauses would otherwise drift
    /// from the published contract.
    ///
    /// Pre-compile the schema once (`kaiv::parse_csaiv`) and keep
    /// it; validation itself is a parallel scan.
    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,
        })
    }

    /// [`validate`](Self::validate), resolving the schema by
    /// registry name through `resolver` (which caches, so the
    /// fetch happens once per name).
    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)))
    }

    /// The canonical form of the request — what validation reads,
    /// and what a server would log or replay.
    pub fn canonical(&self) -> &str {
        &self.daiv
    }

    /// The method name (`Family.Method`).
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Decode `/params` into a typed struct. Deserialization is
    /// driven by the TARGET type, so an authored request needs no
    /// annotation lines for its scalars — `limit=50` lands in an
    /// `i64` field. Give collection fields `#[serde(default)]`:
    /// an empty collection has no wire representation.
    pub fn params<'de, T: serde::Deserialize<'de>>(&self) -> Result<T, Error> {
        Ok(kaiv::serde::from_doc(&self.doc, "/params")?)
    }

    /// The parsed document, for callers that want to walk it by
    /// hand (`doc.root().view("/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"]);

        // Canonical form: same result.
        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() {
        // No `!int` annotation — the target type decides.
        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());
    }
}