kaivrpc 0.2.0

RPC over kaiv documents: the request/response envelope, typed params, and line-per-element streaming
Documentation
//! Optional axum glue (`--features axum`).
//!
//! The core crate is framework-free on purpose; this module is
//! the twenty lines every axum consumer would otherwise write —
//! notably turning a chunk vector into a genuinely chunked body,
//! which is what makes the streaming half of the protocol visible
//! on the wire.

use axum::body::Body;
use axum::http::{header, StatusCode};
use axum::response::Response as AxumResponse;

/// The canonical media type a kaivrpc response is served as.
pub const CONTENT_TYPE: &str = "application/daiv";
/// The media type a client sends a request under.
pub const REQUEST_CONTENT_TYPE: &str = "application/kaiv";

/// Serve a complete document as one buffered body.
pub fn buffered(doc: String) -> AxumResponse {
    AxumResponse::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, CONTENT_TYPE)
        .body(Body::from(doc))
        .expect("static response builds")
}

/// Serve chunks as a STREAMED body — one HTTP chunk per element
/// run, the cadence
/// [`Response::stream_chunks`](crate::Response::stream_chunks)
/// produces. A client reading incrementally sees each element as
/// its chunk lands; a client that just collects the body gets
/// bytes identical to [`buffered`].
pub fn streamed(chunks: Vec<String>) -> AxumResponse {
    let stream = tokio_stream::iter(
        chunks
            .into_iter()
            .map(Ok::<String, std::convert::Infallible>),
    );
    AxumResponse::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, CONTENT_TYPE)
        .body(Body::from_stream(stream))
        .expect("static response builds")
}

/// Serve an error document. The HTTP status stays 200 by default
/// — the envelope carries the verdict, exactly as a JSON-RPC
/// error does — but a transport-level failure (an unparseable
/// body) may prefer a 4xx, so the status is the caller's.
pub fn error(doc: String, status: StatusCode) -> AxumResponse {
    AxumResponse::builder()
        .status(status)
        .header(header::CONTENT_TYPE, CONTENT_TYPE)
        .body(Body::from(doc))
        .expect("static response builds")
}