1use laminapdf_syntax::{Diagnostic, ErrorCode, ErrorKind, Location, Position};
4use serde_json::{Map, Value, json};
5
6#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15#[non_exhaustive]
16pub enum RenderError {
17 #[error("a {width}×{height} pixel tile exceeds the render limit of {limit} {unit}")]
20 TooLarge {
21 width: u64,
23 height: u64,
25 limit: u64,
27 unit: &'static str,
29 },
30 #[error("the input is {len} bytes, over the render limit of {limit} bytes")]
33 InputTooLarge {
34 len: u64,
36 limit: u64,
38 },
39 #[error("invalid render request: {what}")]
42 InvalidRequest {
43 what: &'static str,
45 },
46 #[error("the output buffer holds {actual} bytes but the tile needs {expected}")]
48 BufferSize {
49 expected: usize,
51 actual: usize,
53 },
54 #[error("page index {index} is out of range for a document of {count} pages")]
56 PageIndexOutOfRange {
57 index: u32,
59 count: u32,
61 },
62 #[error("the document is encrypted and needs a password")]
64 PasswordRequired,
65 #[error("the password does not open the document")]
67 WrongPassword,
68 #[error("{} byte range(s) of the input are not available yet", ranges.len())]
70 DataPending {
71 ranges: Vec<(u64, u64)>,
73 },
74 #[error("bytes {offset}..+{len} of the input could not be read")]
76 Source {
77 offset: u64,
79 len: u64,
81 },
82 #[error("the {backend} backend could not {stage} the document")]
85 Failed {
86 backend: &'static str,
88 stage: &'static str,
90 },
91 #[error("the {format} encoder failed")]
94 ExportFailed {
95 format: &'static str,
97 },
98 #[error("the {backend} backend is not available")]
101 Unavailable {
102 backend: &'static str,
104 },
105 #[error("the render was cancelled")]
107 Cancelled,
108}
109
110impl RenderError {
111 pub const CODES: &'static [&'static str] = &[
116 "render-too-large",
117 "render-failed",
118 "render-backend-unavailable",
119 "export-failed",
120 ];
121
122 #[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 #[must_use]
147 pub const fn code(&self) -> &'static str {
148 self.error_code().as_str()
149 }
150
151 #[must_use]
157 pub const fn kind(&self) -> ErrorKind {
158 self.error_code().kind()
159 }
160
161 #[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 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 #[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
227fn 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 _ => Self::Source { offset: 0, len: 0 },
241 }
242 }
243}
244
245#[cfg(test)]
246mod tests {
247
248 use super::RenderError;
249
250 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 #[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 #[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}