Skip to main content

reports_web/
engine.rs

1//! Client for the Reports.Web engine (`ghcr.io/reportsweb/engine`): POST PREPEJ JSON to `/render/pdf`.
2use crate::printdata::PrintData;
3use serde_json::Value;
4use std::{fmt, time::Duration};
5
6/// Largest print data and PDF accepted, in bytes (32 MiB).
7pub const MAX_BYTES: usize = 32 * 1024 * 1024;
8
9/// Error from the Reports.Web engine. `status` is the HTTP status, or `None` for transport errors.
10#[derive(Debug, Clone)]
11pub struct EngineError {
12    pub status: Option<u16>,
13    pub message: String,
14}
15
16impl fmt::Display for EngineError {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.write_str(&self.message)
19    }
20}
21
22impl std::error::Error for EngineError {}
23
24impl EngineError {
25    fn new(status: Option<u16>, message: impl Into<String>) -> Self {
26        Self { status, message: message.into() }
27    }
28}
29
30/// Async client for the Reports.Web engine.
31///
32/// ```no_run
33/// # async fn run(print_data: reports_web::PrintData) -> Result<(), Box<dyn std::error::Error>> {
34/// let engine = reports_web::ReportsWebEngine::new("http://127.0.0.1:3107")?;
35/// let pdf: Vec<u8> = engine.render_pdf(&print_data).await?;
36/// # Ok(()) }
37/// ```
38#[derive(Clone)]
39pub struct ReportsWebEngine {
40    url: String,
41    client: reqwest::Client,
42    max_bytes: usize,
43}
44
45impl ReportsWebEngine {
46    /// Client for `url` with a 90 second timeout.
47    pub fn new(url: &str) -> Result<Self, EngineError> {
48        Self::with_timeout(url, Duration::from_secs(90))
49    }
50
51    /// Client for `REPORTS_ENGINE_URL`, or `http://127.0.0.1:3107` when unset.
52    pub fn from_env() -> Result<Self, EngineError> {
53        Self::new(&std::env::var("REPORTS_ENGINE_URL").unwrap_or_else(|_| "http://127.0.0.1:3107".into()))
54    }
55
56    /// Client for `url` with the given request timeout.
57    pub fn with_timeout(url: &str, timeout: Duration) -> Result<Self, EngineError> {
58        let client = reqwest::Client::builder()
59            .connect_timeout(Duration::from_secs(10))
60            .timeout(timeout)
61            .redirect(reqwest::redirect::Policy::none())
62            .build()
63            .map_err(|e| EngineError::new(None, format!("Cannot create the HTTP client: {e}")))?;
64        Ok(Self { url: url.trim_end_matches('/').to_owned(), client, max_bytes: MAX_BYTES })
65    }
66
67    /// Engine base URL.
68    pub fn url(&self) -> &str {
69        &self.url
70    }
71
72    /// `GET /health`, e.g. `{"status":"ok","engine":"C++ WebAssembly"}`.
73    pub async fn health(&self) -> Result<Value, EngineError> {
74        let response = self.client.get(format!("{}/health", self.url)).send().await.map_err(|e| self.unreachable(e))?;
75        let status = response.status();
76        if !status.is_success() {
77            return Err(EngineError::new(Some(status.as_u16()), format!("Engine health check failed (HTTP {status}).")));
78        }
79        response.json().await.map_err(|e| EngineError::new(Some(status.as_u16()), format!("Invalid health response: {e}")))
80    }
81
82    /// Render a [`PrintData`] to PDF.
83    pub async fn render_pdf(&self, print_data: &PrintData) -> Result<Vec<u8>, EngineError> {
84        let json = print_data.to_json(false).map_err(|e| EngineError::new(None, e.to_string()))?;
85        self.render_pdf_json(json.into_bytes()).await
86    }
87
88    /// Render PREPEJ JSON (bytes or text) to PDF.
89    pub async fn render_pdf_json(&self, json: impl Into<Vec<u8>>) -> Result<Vec<u8>, EngineError> {
90        let payload = json.into();
91        if payload.len() > MAX_BYTES {
92            return Err(EngineError::new(None, "Print data exceeds 32 MiB."));
93        }
94        let response = self
95            .client
96            .post(format!("{}/render/pdf", self.url))
97            .header(reqwest::header::CONTENT_TYPE, "application/json")
98            .body(payload)
99            .send()
100            .await
101            .map_err(|e| self.unreachable(e))?;
102        let status = response.status();
103        if !status.is_success() {
104            let text = response.text().await.unwrap_or_default();
105            let detail = serde_json::from_str::<Value>(&text)
106                .ok()
107                .and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_owned))
108                .unwrap_or(text);
109            let suffix = if detail.is_empty() { ".".to_owned() } else { format!(": {detail}") };
110            return Err(EngineError::new(Some(status.as_u16()), format!("Engine could not create the PDF (HTTP {}){suffix}", status.as_u16())));
111        }
112        let pdf = response.bytes().await.map_err(|e| EngineError::new(Some(status.as_u16()), format!("Cannot read the PDF: {e}")))?;
113        if pdf.len() > self.max_bytes {
114            return Err(EngineError::new(None, format!("PDF exceeds {} bytes.", self.max_bytes)));
115        }
116        if !pdf.starts_with(b"%PDF-") {
117            return Err(EngineError::new(None, "Engine response is not a PDF."));
118        }
119        Ok(pdf.to_vec())
120    }
121
122    fn unreachable(&self, error: reqwest::Error) -> EngineError {
123        EngineError::new(None, format!("Cannot reach the Reports.Web engine at {}: {error}", self.url))
124    }
125}