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