Skip to main content

laminapdf_render/
error.rs

1//! [`RenderError`]: what a render backend can refuse or fail with, in the ADR 0026 contract.
2
3use laminapdf_syntax::{Diagnostic, ErrorCode, ErrorKind, Location, Position};
4use serde_json::{Map, Value, json};
5
6/// Why a render backend refused a request or couldn't render.
7///
8/// Every variant has a stable [`code`](RenderError::code) from `fixtures/codes.json`: the new
9/// ones under `renderErrors`, the rest reused from the groups that already define them
10/// (`page-index-out-of-range`, `password-required`, `wrong-password`, `data-pending`, `source`,
11/// `cancelled`, `invalid-argument`). Messages never contain text read from the document.
12///
13/// Added in 0.2.0.
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[non_exhaustive]
16pub enum RenderError {
17    /// The requested tile is bigger than [`RenderLimits`](crate::RenderLimits) allow
18    /// (`render-too-large`). Checked before anything is allocated.
19    #[error("a {width}×{height} pixel tile exceeds the render limit of {limit} {unit}")]
20    TooLarge {
21        /// Tile width in pixels.
22        width: u64,
23        /// Tile height in pixels.
24        height: u64,
25        /// The limit that was exceeded.
26        limit: u64,
27        /// `pixels` (per tile) or `pixels per side`.
28        unit: &'static str,
29    },
30    /// The input is longer than [`RenderLimits::max_input_bytes`](crate::RenderLimits) for a
31    /// backend that reads the whole file into memory (`render-too-large`).
32    #[error("the input is {len} bytes, over the render limit of {limit} bytes")]
33    InputTooLarge {
34        /// The input's length.
35        len: u64,
36        /// The limit.
37        limit: u64,
38    },
39    /// A request that can never be valid: a non-finite or non-positive scale, an empty tile, a
40    /// tile outside the page (`invalid-argument`).
41    #[error("invalid render request: {what}")]
42    InvalidRequest {
43        /// What is wrong (fixed text).
44        what: &'static str,
45    },
46    /// The output buffer doesn't have exactly the bytes the tile needs (`invalid-argument`).
47    #[error("the output buffer holds {actual} bytes but the tile needs {expected}")]
48    BufferSize {
49        /// The bytes the tile needs ([`TilePlan::byte_len`](crate::TilePlan::byte_len)).
50        expected: usize,
51        /// The bytes the caller passed.
52        actual: usize,
53    },
54    /// The page index is past the last page (`page-index-out-of-range`, ADR 0027: 0-based).
55    #[error("page index {index} is out of range for a document of {count} pages")]
56    PageIndexOutOfRange {
57        /// The index asked for.
58        index: u32,
59        /// The number of pages.
60        count: u32,
61    },
62    /// The document is encrypted and no password was given (`password-required`).
63    #[error("the document is encrypted and needs a password")]
64    PasswordRequired,
65    /// The password given doesn't open the document (`wrong-password`).
66    #[error("the password does not open the document")]
67    WrongPassword,
68    /// The source hasn't got these bytes yet: fetch them and call again (`data-pending`).
69    #[error("{} byte range(s) of the input are not available yet", ranges.len())]
70    DataPending {
71        /// The missing `(offset, length)` ranges.
72        ranges: Vec<(u64, u64)>,
73    },
74    /// The source failed to read these bytes (`source`).
75    #[error("bytes {offset}..+{len} of the input could not be read")]
76    Source {
77        /// First byte of the failed range.
78        offset: u64,
79        /// Length of the failed range.
80        len: u64,
81    },
82    /// The engine couldn't open the document or render the page: a damaged or unsupported
83    /// file, or an engine failure (`render-failed`).
84    #[error("the {backend} backend could not {stage} the document")]
85    Failed {
86        /// `pdfium` or `hayro`.
87        backend: &'static str,
88        /// `open` or `render`.
89        stage: &'static str,
90    },
91    /// An export's encoder failed on a page that was drawn (`export-failed`): it writes into
92    /// memory, so this is a bug, never the document's fault.
93    #[error("the {format} encoder failed")]
94    ExportFailed {
95        /// `png`, `jpeg` or `tiff`.
96        format: &'static str,
97    },
98    /// The engine isn't available: the PDFium library couldn't be found or bound
99    /// (`render-backend-unavailable`).
100    #[error("the {backend} backend is not available")]
101    Unavailable {
102        /// `pdfium` or `hayro`.
103        backend: &'static str,
104    },
105    /// A [`CancelToken`](crate::CancelToken) stopped the render (`cancelled`).
106    #[error("the render was cancelled")]
107    Cancelled,
108}
109
110impl RenderError {
111    /// The codes this crate adds to `fixtures/codes.json` (under `renderErrors`). The other
112    /// variants reuse codes defined by other groups.
113    ///
114    /// Added in 0.2.0.
115    pub const CODES: &'static [&'static str] = &[
116        "render-too-large",
117        "render-failed",
118        "render-backend-unavailable",
119        "export-failed",
120    ];
121
122    /// The variant's entry in the generated [`ErrorCode`] table (one per entry of
123    /// `fixtures/codes.json`), which holds its code string, kind, hint and `docsUrl`.
124    ///
125    /// Added in 0.2.0.
126    #[must_use]
127    pub const fn error_code(&self) -> ErrorCode {
128        match self {
129            Self::TooLarge { .. } | Self::InputTooLarge { .. } => ErrorCode::RenderTooLarge,
130            Self::InvalidRequest { .. } | Self::BufferSize { .. } => ErrorCode::InvalidArgument,
131            Self::PageIndexOutOfRange { .. } => ErrorCode::PageIndexOutOfRange,
132            Self::PasswordRequired => ErrorCode::PasswordRequired,
133            Self::WrongPassword => ErrorCode::WrongPassword,
134            Self::DataPending { .. } => ErrorCode::DataPending,
135            Self::Source { .. } => ErrorCode::Source,
136            Self::Failed { .. } => ErrorCode::RenderFailed,
137            Self::Unavailable { .. } => ErrorCode::RenderBackendUnavailable,
138            Self::ExportFailed { .. } => ErrorCode::ExportFailed,
139            Self::Cancelled => ErrorCode::Cancelled,
140        }
141    }
142
143    /// A stable kebab-case code for this error (ADR 0026 §1).
144    ///
145    /// Added in 0.2.0.
146    #[must_use]
147    pub const fn code(&self) -> &'static str {
148        self.error_code().as_str()
149    }
150
151    /// The kind of this error ([ADR 0026] §2), from the generated [`ErrorCode`] table.
152    ///
153    /// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
154    ///
155    /// Added in 0.2.0.
156    #[must_use]
157    pub const fn kind(&self) -> ErrorKind {
158        self.error_code().kind()
159    }
160
161    /// The [ADR 0026] §1 object: what a binding hands to another language. `data` holds the
162    /// fields each code's `docs/errors` page lists; nothing in it is read from the document.
163    ///
164    /// [ADR 0026]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0026-error-and-diagnostic-contract.md
165    ///
166    /// Added in 0.2.0.
167    #[must_use]
168    pub fn diagnostic(&self) -> Diagnostic {
169        Diagnostic::error(self.error_code(), self.to_string())
170            .with_location(self.location())
171            .with_data(self.data())
172    }
173
174    /// The `data` of [`RenderError::diagnostic`].
175    fn data(&self) -> Map<String, Value> {
176        match self {
177            Self::TooLarge {
178                width,
179                height,
180                limit,
181                unit,
182            } => fields([
183                ("width", json!(width)),
184                ("height", json!(height)),
185                ("limit", json!(limit)),
186                ("unit", json!(unit)),
187            ]),
188            Self::InputTooLarge { len, limit } => fields([("len", json!(len)), ("limit", json!(limit))]),
189            Self::InvalidRequest { what } => fields([("argument", json!("request")), ("detail", json!(what))]),
190            Self::BufferSize { .. } => fields([
191                ("argument", json!("output")),
192                ("detail", json!("the buffer does not hold exactly the tile's bytes")),
193            ]),
194            Self::PageIndexOutOfRange { index, count } => fields([("index", json!(index)), ("count", json!(count))]),
195            Self::DataPending { ranges } => fields([("ranges", json!(ranges))]),
196            Self::Failed { backend, stage } => fields([("backend", json!(backend)), ("stage", json!(stage))]),
197            Self::Unavailable { backend } => fields([("backend", json!(backend))]),
198            Self::ExportFailed { format } => fields([("format", json!(format))]),
199            Self::PasswordRequired | Self::WrongPassword | Self::Source { .. } | Self::Cancelled => Map::new(),
200        }
201    }
202
203    /// Where the error was found (ADR 0026 §1.1): the failed byte range for a source error;
204    /// nothing else has a position in the document.
205    ///
206    /// Added in 0.2.0.
207    #[must_use]
208    pub fn location(&self) -> Location {
209        match self {
210            Self::Source { offset, .. } => Location::from(Position::FileOffset(*offset)),
211            Self::TooLarge { .. }
212            | Self::InputTooLarge { .. }
213            | Self::InvalidRequest { .. }
214            | Self::BufferSize { .. }
215            | Self::PageIndexOutOfRange { .. }
216            | Self::PasswordRequired
217            | Self::WrongPassword
218            | Self::DataPending { .. }
219            | Self::Failed { .. }
220            | Self::ExportFailed { .. }
221            | Self::Unavailable { .. }
222            | Self::Cancelled => Location::NONE,
223        }
224    }
225}
226
227/// A `data` object from its entries.
228fn fields<const N: usize>(entries: [(&str, Value); N]) -> Map<String, Value> {
229    entries.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()
230}
231
232impl From<laminapdf_cos::SourceError> for RenderError {
233    fn from(e: laminapdf_cos::SourceError) -> Self {
234        match e {
235            laminapdf_cos::SourceError::Pending { offset, len } => Self::DataPending {
236                ranges: vec![(offset, len)],
237            },
238            laminapdf_cos::SourceError::Failed { offset, len } => Self::Source { offset, len },
239            // SourceError is non_exhaustive: a future variant is a read that failed somewhere.
240            _ => Self::Source { offset: 0, len: 0 },
241        }
242    }
243}
244
245#[cfg(test)]
246mod tests {
247
248    use super::RenderError;
249
250    /// One sample of every variant.
251    fn samples() -> Vec<RenderError> {
252        vec![
253            RenderError::TooLarge {
254                width: 1,
255                height: 1,
256                limit: 0,
257                unit: "pixels",
258            },
259            RenderError::InputTooLarge { len: 2, limit: 1 },
260            RenderError::InvalidRequest { what: "x" },
261            RenderError::BufferSize { expected: 4, actual: 0 },
262            RenderError::PageIndexOutOfRange { index: 1, count: 1 },
263            RenderError::PasswordRequired,
264            RenderError::WrongPassword,
265            RenderError::DataPending { ranges: vec![(0, 1)] },
266            RenderError::Source { offset: 0, len: 1 },
267            RenderError::Failed {
268                backend: "hayro",
269                stage: "open",
270            },
271            RenderError::Unavailable { backend: "pdfium" },
272            RenderError::ExportFailed { format: "png" },
273            RenderError::Cancelled,
274        ]
275    }
276
277    /// Every variant's §1 object validates against the generated `laminapdf.error/1` schema.
278    #[test]
279    fn every_diagnostic_matches_the_error_schema() {
280        let schema: serde_json::Value =
281            serde_json::from_str(include_str!("../../laminapdf/schemas/error.schema.json")).unwrap();
282        let id = schema["$id"].as_str().unwrap().to_owned();
283        let mut schemas = boon::Schemas::new();
284        let mut compiler = boon::Compiler::new();
285        compiler.add_resource(&id, schema).unwrap();
286        let index = compiler.compile(&id, &mut schemas).unwrap();
287        for e in samples() {
288            let value = e.diagnostic().to_json();
289            if let Err(report) = schemas.validate(&value, index) {
290                panic!("{value} does not match laminapdf.error/1:\n{report}");
291            }
292        }
293    }
294
295    /// A `data-pending` lists its ranges as `[offset, length]` pairs under `data.ranges`, the
296    /// shape `@laminapdf/sdk`'s `LaminaPdfError.ranges` takes.
297    #[test]
298    fn data_pending_lists_its_ranges_as_pairs() {
299        let e = RenderError::DataPending {
300            ranges: vec![(0, 1), (4096, 512)],
301        };
302        assert_eq!(
303            e.diagnostic().to_json()["data"]["ranges"],
304            serde_json::json!([[0, 1], [4096, 512]])
305        );
306    }
307
308    #[test]
309    fn every_variant_has_the_kind_codes_json_lists() {
310        let codes: serde_json::Value = serde_json::from_str(include_str!("../../../fixtures/codes.json")).unwrap();
311        for e in samples() {
312            let listed = codes
313                .as_object()
314                .unwrap()
315                .values()
316                .filter_map(serde_json::Value::as_array)
317                .flatten()
318                .find(|c| c["code"] == e.code())
319                .unwrap_or_else(|| panic!("{} is not in codes.json", e.code()));
320            assert_eq!(listed["kind"].as_str().unwrap(), e.kind().as_str(), "{}", e.code());
321        }
322    }
323}