reports-web 1.0.0

Reports.Web for Rust: build PREPEJ print data from .prepdj report definitions and render PDF with the Reports.Web engine (C++ WebAssembly). Japanese business forms: invoices, estimates, labels. Trial build.
Documentation
//! Client for the Reports.Web engine (`ghcr.io/reportsweb/engine`): POST PREPEJ JSON to `/render/pdf`.
use crate::printdata::PrintData;
use serde_json::Value;
use std::{fmt, time::Duration};

/// Largest print data and PDF accepted, in bytes (32 MiB).
pub const MAX_BYTES: usize = 32 * 1024 * 1024;

/// Error from the Reports.Web engine. `status` is the HTTP status, or `None` for transport errors.
#[derive(Debug, Clone)]
pub struct EngineError {
    pub status: Option<u16>,
    pub message: String,
}

impl fmt::Display for EngineError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for EngineError {}

impl EngineError {
    fn new(status: Option<u16>, message: impl Into<String>) -> Self {
        Self { status, message: message.into() }
    }
}

/// Async client for the Reports.Web engine.
///
/// ```no_run
/// # async fn run(print_data: reports_web::PrintData) -> Result<(), Box<dyn std::error::Error>> {
/// let engine = reports_web::ReportsWebEngine::new("http://127.0.0.1:3107")?;
/// let pdf: Vec<u8> = engine.render_pdf(&print_data).await?;
/// # Ok(()) }
/// ```
#[derive(Clone)]
pub struct ReportsWebEngine {
    url: String,
    client: reqwest::Client,
    max_bytes: usize,
}

impl ReportsWebEngine {
    /// Client for `url` with a 90 second timeout.
    pub fn new(url: &str) -> Result<Self, EngineError> {
        Self::with_timeout(url, Duration::from_secs(90))
    }

    /// Client for `REPORTS_ENGINE_URL`, or `http://127.0.0.1:3107` when unset.
    pub fn from_env() -> Result<Self, EngineError> {
        Self::new(&std::env::var("REPORTS_ENGINE_URL").unwrap_or_else(|_| "http://127.0.0.1:3107".into()))
    }

    /// Client for `url` with the given request timeout.
    pub fn with_timeout(url: &str, timeout: Duration) -> Result<Self, EngineError> {
        let client = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(10))
            .timeout(timeout)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| EngineError::new(None, format!("Cannot create the HTTP client: {e}")))?;
        Ok(Self { url: url.trim_end_matches('/').to_owned(), client, max_bytes: MAX_BYTES })
    }

    /// Engine base URL.
    pub fn url(&self) -> &str {
        &self.url
    }

    /// `GET /health`, e.g. `{"status":"ok","engine":"C++ WebAssembly"}`.
    pub async fn health(&self) -> Result<Value, EngineError> {
        let response = self.client.get(format!("{}/health", self.url)).send().await.map_err(|e| self.unreachable(e))?;
        let status = response.status();
        if !status.is_success() {
            return Err(EngineError::new(Some(status.as_u16()), format!("Engine health check failed (HTTP {status}).")));
        }
        response.json().await.map_err(|e| EngineError::new(Some(status.as_u16()), format!("Invalid health response: {e}")))
    }

    /// Render a [`PrintData`] to PDF.
    pub async fn render_pdf(&self, print_data: &PrintData) -> Result<Vec<u8>, EngineError> {
        let json = print_data.to_json(false).map_err(|e| EngineError::new(None, e.to_string()))?;
        self.render_pdf_json(json.into_bytes()).await
    }

    /// Render PREPEJ JSON (bytes or text) to PDF.
    pub async fn render_pdf_json(&self, json: impl Into<Vec<u8>>) -> Result<Vec<u8>, EngineError> {
        let payload = json.into();
        if payload.len() > MAX_BYTES {
            return Err(EngineError::new(None, "Print data exceeds 32 MiB."));
        }
        let response = self
            .client
            .post(format!("{}/render/pdf", self.url))
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(payload)
            .send()
            .await
            .map_err(|e| self.unreachable(e))?;
        let status = response.status();
        if !status.is_success() {
            let text = response.text().await.unwrap_or_default();
            let detail = serde_json::from_str::<Value>(&text)
                .ok()
                .and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_owned))
                .unwrap_or(text);
            let suffix = if detail.is_empty() { ".".to_owned() } else { format!(": {detail}") };
            return Err(EngineError::new(Some(status.as_u16()), format!("Engine could not create the PDF (HTTP {}){suffix}", status.as_u16())));
        }
        let pdf = response.bytes().await.map_err(|e| EngineError::new(Some(status.as_u16()), format!("Cannot read the PDF: {e}")))?;
        if pdf.len() > self.max_bytes {
            return Err(EngineError::new(None, format!("PDF exceeds {} bytes.", self.max_bytes)));
        }
        if !pdf.starts_with(b"%PDF-") {
            return Err(EngineError::new(None, "Engine response is not a PDF."));
        }
        Ok(pdf.to_vec())
    }

    fn unreachable(&self, error: reqwest::Error) -> EngineError {
        EngineError::new(None, format!("Cannot reach the Reports.Web engine at {}: {error}", self.url))
    }
}