use laminapdf_syntax::{Diagnostic, ErrorCode, ErrorKind, Location, Position};
use serde_json::{Map, Value, json};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RenderError {
#[error("a {width}×{height} pixel tile exceeds the render limit of {limit} {unit}")]
TooLarge {
width: u64,
height: u64,
limit: u64,
unit: &'static str,
},
#[error("the input is {len} bytes, over the render limit of {limit} bytes")]
InputTooLarge {
len: u64,
limit: u64,
},
#[error("invalid render request: {what}")]
InvalidRequest {
what: &'static str,
},
#[error("the output buffer holds {actual} bytes but the tile needs {expected}")]
BufferSize {
expected: usize,
actual: usize,
},
#[error("page index {index} is out of range for a document of {count} pages")]
PageIndexOutOfRange {
index: u32,
count: u32,
},
#[error("the document is encrypted and needs a password")]
PasswordRequired,
#[error("the password does not open the document")]
WrongPassword,
#[error("{} byte range(s) of the input are not available yet", ranges.len())]
DataPending {
ranges: Vec<(u64, u64)>,
},
#[error("bytes {offset}..+{len} of the input could not be read")]
Source {
offset: u64,
len: u64,
},
#[error("the {backend} backend could not {stage} the document")]
Failed {
backend: &'static str,
stage: &'static str,
},
#[error("the {backend} backend is not available")]
Unavailable {
backend: &'static str,
},
#[error("the render was cancelled")]
Cancelled,
}
impl RenderError {
pub const CODES: &'static [&'static str] = &["render-too-large", "render-failed", "render-backend-unavailable"];
#[must_use]
pub const fn error_code(&self) -> ErrorCode {
match self {
Self::TooLarge { .. } | Self::InputTooLarge { .. } => ErrorCode::RenderTooLarge,
Self::InvalidRequest { .. } | Self::BufferSize { .. } => ErrorCode::InvalidArgument,
Self::PageIndexOutOfRange { .. } => ErrorCode::PageIndexOutOfRange,
Self::PasswordRequired => ErrorCode::PasswordRequired,
Self::WrongPassword => ErrorCode::WrongPassword,
Self::DataPending { .. } => ErrorCode::DataPending,
Self::Source { .. } => ErrorCode::Source,
Self::Failed { .. } => ErrorCode::RenderFailed,
Self::Unavailable { .. } => ErrorCode::RenderBackendUnavailable,
Self::Cancelled => ErrorCode::Cancelled,
}
}
#[must_use]
pub const fn code(&self) -> &'static str {
self.error_code().as_str()
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.error_code().kind()
}
#[must_use]
pub fn diagnostic(&self) -> Diagnostic {
Diagnostic::error(self.error_code(), self.to_string())
.with_location(self.location())
.with_data(self.data())
}
fn data(&self) -> Map<String, Value> {
match self {
Self::TooLarge {
width,
height,
limit,
unit,
} => fields([
("width", json!(width)),
("height", json!(height)),
("limit", json!(limit)),
("unit", json!(unit)),
]),
Self::InputTooLarge { len, limit } => fields([("len", json!(len)), ("limit", json!(limit))]),
Self::InvalidRequest { what } => fields([("argument", json!("request")), ("detail", json!(what))]),
Self::BufferSize { .. } => fields([
("argument", json!("output")),
("detail", json!("the buffer does not hold exactly the tile's bytes")),
]),
Self::PageIndexOutOfRange { index, count } => fields([("index", json!(index)), ("count", json!(count))]),
Self::DataPending { ranges } => fields([("ranges", json!(ranges))]),
Self::Failed { backend, stage } => fields([("backend", json!(backend)), ("stage", json!(stage))]),
Self::Unavailable { backend } => fields([("backend", json!(backend))]),
Self::PasswordRequired | Self::WrongPassword | Self::Source { .. } | Self::Cancelled => Map::new(),
}
}
#[must_use]
pub fn location(&self) -> Location {
match self {
Self::Source { offset, .. } => Location::from(Position::FileOffset(*offset)),
Self::TooLarge { .. }
| Self::InputTooLarge { .. }
| Self::InvalidRequest { .. }
| Self::BufferSize { .. }
| Self::PageIndexOutOfRange { .. }
| Self::PasswordRequired
| Self::WrongPassword
| Self::DataPending { .. }
| Self::Failed { .. }
| Self::Unavailable { .. }
| Self::Cancelled => Location::NONE,
}
}
}
fn fields<const N: usize>(entries: [(&str, Value); N]) -> Map<String, Value> {
entries.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()
}
impl From<laminapdf_cos::SourceError> for RenderError {
fn from(e: laminapdf_cos::SourceError) -> Self {
match e {
laminapdf_cos::SourceError::Pending { offset, len } => Self::DataPending {
ranges: vec![(offset, len)],
},
laminapdf_cos::SourceError::Failed { offset, len } => Self::Source { offset, len },
_ => Self::Source { offset: 0, len: 0 },
}
}
}
#[cfg(test)]
mod tests {
use super::RenderError;
fn samples() -> Vec<RenderError> {
vec![
RenderError::TooLarge {
width: 1,
height: 1,
limit: 0,
unit: "pixels",
},
RenderError::InputTooLarge { len: 2, limit: 1 },
RenderError::InvalidRequest { what: "x" },
RenderError::BufferSize { expected: 4, actual: 0 },
RenderError::PageIndexOutOfRange { index: 1, count: 1 },
RenderError::PasswordRequired,
RenderError::WrongPassword,
RenderError::DataPending { ranges: vec![(0, 1)] },
RenderError::Source { offset: 0, len: 1 },
RenderError::Failed {
backend: "hayro",
stage: "open",
},
RenderError::Unavailable { backend: "pdfium" },
RenderError::Cancelled,
]
}
#[test]
fn every_diagnostic_matches_the_error_schema() {
let schema: serde_json::Value =
serde_json::from_str(include_str!("../../laminapdf/schemas/error.schema.json")).unwrap();
let id = schema["$id"].as_str().unwrap().to_owned();
let mut schemas = boon::Schemas::new();
let mut compiler = boon::Compiler::new();
compiler.add_resource(&id, schema).unwrap();
let index = compiler.compile(&id, &mut schemas).unwrap();
for e in samples() {
let value = e.diagnostic().to_json();
if let Err(report) = schemas.validate(&value, index) {
panic!("{value} does not match laminapdf.error/1:\n{report}");
}
}
}
#[test]
fn data_pending_lists_its_ranges_as_pairs() {
let e = RenderError::DataPending {
ranges: vec![(0, 1), (4096, 512)],
};
assert_eq!(
e.diagnostic().to_json()["data"]["ranges"],
serde_json::json!([[0, 1], [4096, 512]])
);
}
#[test]
fn every_variant_has_the_kind_codes_json_lists() {
let codes: serde_json::Value = serde_json::from_str(include_str!("../../../fixtures/codes.json")).unwrap();
for e in samples() {
let listed = codes
.as_object()
.unwrap()
.values()
.filter_map(serde_json::Value::as_array)
.flatten()
.find(|c| c["code"] == e.code())
.unwrap_or_else(|| panic!("{} is not in codes.json", e.code()));
assert_eq!(listed["kind"].as_str().unwrap(), e.kind().as_str(), "{}", e.code());
}
}
}