kaivrpc 0.2.0

RPC over kaiv documents: the request/response envelope, typed params, and line-per-element streaming
Documentation

kaivrpc

RPC over kaiv documents — the Rust server side. The browser and Node client is kaivrpc-client; the two are tested against each other's output.

A request is a document; a response is a document. Both are ordinary kaiv, so a request can be saved, diffed, and replayed with curl --data-binary @req.kaiv, and a response can be validated against its schema, grepped, or consumed line by line as it streams.

.!kaiv                        →   .!daiv
method=Post.MultiGet              .!schema:kaivrpc/response-head
/params::ws=AGORA                 .!schema:acme/resp/list
/params/@ids;=t3_9fq2k            .!schema:kaivrpc/response-tail
                                  !str'::status=ok
                                  !str'/data/@rows/0::id=t3_9fq2k
                                  …
                                  !null'::error=
                                  !int'::n=1

Why bother

One schema sees the whole request. JSON-RPC's envelope cannot type params — the spec says "a Structured value", so every argument constraint lives in prose and hand-written guard code, maintained twice. Here the method's request schema types the envelope and the arguments, and the refusal names the line in the caller's own document.

Truncation detection falls out of the contract. The response composes three schemas: a head (status — the verdict before any data), the method's data schema, and a tail (error? and a required n). Composition order is composed field order, so the ordered scan enforces the layout — and because n is required and last, a response cut short fails validation. No sentinel frame, no length prefix, no protocol machinery.

Streaming reaches the browser. gRPC's streaming does not (no HTTP/2 trailers in JS); JSON cannot be parsed before its last byte. Every canonical kaiv line is a self-contained (type, namepath, value) fact, so a server flushes as it goes and a client acts on each element as it lands — over plain fetch.

Use

use kaivrpc::{Envelope, Head, Heads, Request, Response, RpcError};

// Requests: any pipeline stage in, typed params out.
let req = Request::parse(body)?;
match req.method() {
    "Post.MultiGet" => {
        let params: MultiGetParams = req.params()?;   // serde
        let rows = fetch(&params).await?;

        // Per-field wire types serde cannot see: unions are
        // NOMINAL, so a union-typed field needs its alternative
        // named.
        const HEADS: Heads<'static> =
            &[("body", Head::Text { embed: "html" })];
        let resp = Response::new(
            Envelope::kaivrpc(), Some("acme/resp/list"), HEADS);

        // One body...
        let doc = resp.buffered(&Data { rows }, n)?;
        // ...or one chunk per element run, which concatenates to
        // exactly the same bytes.
        let chunks = resp.stream_chunks("/data/@rows", &rows)?;
    }
    other => return Ok(resp.error(&RpcError::new(
        601, "MethodNotFound", format!("no such method: {other}")))?),
}

Flush per element run, not per line. Measured on a real 100-row payload with a shared brotli context: one-shot 10.2 KB, per-element-run 13.3 KB, per-LINE 37.9 KB. Element-run cadence keeps lines arriving as lines at ~30% ratio cost; per-line forfeits compression almost entirely.

Validate the request, delete the guard

The method's schema types the ENVELOPE and the arguments together, so one pass replaces the hand-written guard whose clauses would otherwise drift from the published contract — and the refusal points at the line the caller wrote:

let schema = kaiv::parse_csaiv(&csaiv)?;   // compile once, keep
if let Err(f) = req.validate(&schema) {
    // f.kind  = "CardinalityViolationError"
    // f.line  = 4  (in the CALLER's document)
    // f.detail= "/params/@ids has 0 elements, schema requires min=1 max=100"
    return Ok(resp.error(&f.to_rpc(602))?);
}

Error codes stay your vocabulary — to_rpc takes the code you report.

axum

--features axum (off by default) adds the small glue: a buffered body, an error body, and streamed(chunks), which turns the chunk vector into a genuinely chunked HTTP body — the thing that makes the streaming half visible on the wire.

use kaivrpc::axum_support::{buffered, streamed};
streamed(resp.stream_chunks("/data/@rows", &rows)?)

What this crate is not

Transport-agnostic by construction — no HTTP framework, no async runtime, no dispatch. You get Strings and Vec<String>s and wire them into whatever server you have; authentication, authorization, and routing stay yours.

The envelope schemas

schemas/ ships the three microschemas as authored .saiv source, re-exported as string constants and compiled in the test suite. Publish them under the names in kaivrpc::schemas so clients can resolve what a response declares, or name your own namespaced copies via Envelope::with_schemas.

License

MIT OR Apache-2.0.