use crate::printdata::PrintData;
use serde_json::Value;
use std::{fmt, time::Duration};
pub const MAX_BYTES: usize = 32 * 1024 * 1024;
#[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() }
}
}
#[derive(Clone)]
pub struct ReportsWebEngine {
url: String,
client: reqwest::Client,
max_bytes: usize,
}
impl ReportsWebEngine {
pub fn new(url: &str) -> Result<Self, EngineError> {
Self::with_timeout(url, Duration::from_secs(90))
}
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()))
}
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 })
}
pub fn url(&self) -> &str {
&self.url
}
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}")))
}
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
}
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))
}
}