imprimatur 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -215,5 +215,5 @@ pub fn define(ruby: &Ruby, native: RModule) -> Result<(), Error> {
215
215
  class.define_method("page_break", method!(NativeDocument::page_break, 0))?;
216
216
  class.define_method("render", method!(NativeDocument::render, 1))?;
217
217
  class.define_method("save", method!(NativeDocument::save, 2))?;
218
- Ok(())
218
+ matryona_machines::ruby::Class::pin_wrapped::<NativeDocument>(ruby, class).map(drop)
219
219
  }
@@ -6,6 +6,7 @@
6
6
  mod archive;
7
7
  mod barcode;
8
8
  mod blocking;
9
+ mod classes;
9
10
  mod convert;
10
11
  mod document;
11
12
  mod pdf;
@@ -18,12 +19,11 @@ use std::cell::{RefCell, RefMut};
18
19
 
19
20
  use imprimatur::style::{Align, TextDirection};
20
21
  use imprimatur::xlsx::{CellRange, Comment, Workbook, Worksheet, parse_cell_reference};
21
- use magnus::{
22
- Error, ExceptionClass, RArray, RModule, RString, Ruby, TryConvert, Value, function, method,
23
- prelude::*,
24
- };
22
+ use magnus::{Error, RArray, RString, Ruby, TryConvert, Value, function, method, prelude::*};
25
23
 
26
- use convert::{Classes, to_cell};
24
+ use classes::classes;
25
+ use convert::to_cell;
26
+ use matryona_machines::ruby::Class;
27
27
  use style::Style;
28
28
  use validation::Validation;
29
29
 
@@ -53,10 +53,9 @@ impl NativeWorkbook {
53
53
  ) -> Result<(), Error> {
54
54
  // Convert before borrowing: a Formula's #expression or a Date's
55
55
  // #year is Ruby code that could call back into this workbook.
56
- let classes = Classes::load(ruby)?;
57
56
  let mut row = Vec::with_capacity(cells.len());
58
57
  for value in cells {
59
- row.push(to_cell(ruby, value, &classes)?);
58
+ row.push(to_cell(ruby, value)?);
60
59
  }
61
60
  let styles = row_styles(ruby, style, row.len())?;
62
61
  let mut book = borrow(ruby, &rb_self.0, "workbook")?;
@@ -75,7 +74,7 @@ impl NativeWorkbook {
75
74
  style: Option<&Style>,
76
75
  ) -> Result<(), Error> {
77
76
  let (sheet, row, column) = position;
78
- let cell = to_cell(ruby, value, &Classes::load(ruby)?)?
77
+ let cell = to_cell(ruby, value)?
79
78
  .ok_or_else(|| argument_error(ruby, "a cell cannot be set to nil"))?;
80
79
  let mut book = borrow(ruby, &rb_self.0, "workbook")?;
81
80
  let sheet = sheet_mut(ruby, &mut book, sheet)?;
@@ -281,21 +280,20 @@ fn domain_error(ruby: &Ruby, error: &imprimatur::Error) -> Error {
281
280
  if let imprimatur::Error::InvalidPdfOption(message) = error {
282
281
  return argument_error(ruby, *message);
283
282
  }
284
- let name = match error {
285
- imprimatur::Error::NoTextLayer => "NoTextLayer",
286
- imprimatur::Error::PasswordRequired => "PasswordRequired",
287
- imprimatur::Error::UnsupportedDocument(_) => "UnsupportedDocument",
288
- imprimatur::Error::LimitExceeded(_) | imprimatur::Error::Cancelled => "LimitExceeded",
289
- _ => "Error",
283
+ let classes = match classes(ruby) {
284
+ Ok(classes) => classes,
285
+ Err(unloaded) => return unloaded,
290
286
  };
291
- let class = ruby
292
- .class_object()
293
- .const_get::<_, RModule>("Imprimatur")
294
- .and_then(|module| module.const_get::<_, ExceptionClass>(name));
295
- match class {
296
- Ok(class) => Error::new(class, error.to_string()),
297
- Err(lookup) => lookup,
298
- }
287
+ let class = match error {
288
+ imprimatur::Error::NoTextLayer => classes.no_text_layer,
289
+ imprimatur::Error::PasswordRequired => classes.password_required,
290
+ imprimatur::Error::UnsupportedDocument(_) => classes.unsupported_document,
291
+ imprimatur::Error::LimitExceeded(_) | imprimatur::Error::Cancelled => {
292
+ classes.limit_exceeded
293
+ }
294
+ _ => classes.error,
295
+ };
296
+ Error::new(classes::exception(ruby, class), error.to_string())
299
297
  }
300
298
 
301
299
  /// The value for a symbol among `choices`, or an `ArgumentError` naming them.
@@ -316,10 +314,13 @@ fn keyword<T: Copy>(
316
314
  #[magnus::init]
317
315
  fn init(ruby: &Ruby) -> Result<(), Error> {
318
316
  let imprimatur = ruby.define_module("Imprimatur")?;
317
+ classes::resolve(ruby, imprimatur)?;
319
318
  let style = imprimatur.define_class("Style", ruby.class_object())?;
320
319
  style.define_singleton_method("__build", function!(Style::build, 13))?;
320
+ Class::pin_wrapped::<Style>(ruby, style)?;
321
321
  let validation = imprimatur.define_class("Validation", ruby.class_object())?;
322
322
  validation.define_singleton_method("__build", function!(Validation::build, 8))?;
323
+ Class::pin_wrapped::<Validation>(ruby, validation)?;
323
324
  barcode::define(ruby, imprimatur)?;
324
325
 
325
326
  let native = imprimatur.define_module("Native")?;
@@ -336,12 +337,14 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
336
337
  zip_writer.define_method("add", method!(archive::ZipWriter::add, 3))?;
337
338
  zip_writer.define_method("comment=", method!(archive::ZipWriter::set_comment, 1))?;
338
339
  zip_writer.define_method("finish", method!(archive::ZipWriter::finish, 0))?;
340
+ Class::pin_wrapped::<archive::ZipWriter>(ruby, zip_writer)?;
339
341
  let zip_reader = native.define_class("ZipReader", ruby.class_object())?;
340
342
  zip_reader.define_singleton_method("new", function!(archive::ZipReader::new, 1))?;
341
343
  zip_reader.define_method("names", method!(archive::ZipReader::names, 0))?;
342
344
  zip_reader.define_method("entries", method!(archive::ZipReader::entries, 0))?;
343
345
  zip_reader.define_method("read", method!(archive::ZipReader::read, 2))?;
344
346
  zip_reader.define_method("extract", method!(archive::ZipReader::extract, 3))?;
347
+ Class::pin_wrapped::<archive::ZipReader>(ruby, zip_reader)?;
345
348
  document::define(ruby, native)?;
346
349
  let workbook = native.define_class("Workbook", ruby.class_object())?;
347
350
  workbook.define_singleton_method("new", function!(NativeWorkbook::new, 0))?;
@@ -357,5 +360,5 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
357
360
  workbook.define_method("next_row", method!(NativeWorkbook::next_row, 1))?;
358
361
  workbook.define_method("render", method!(NativeWorkbook::render, 0))?;
359
362
  workbook.define_method("save", method!(NativeWorkbook::save, 1))?;
360
- Ok(())
363
+ Class::pin_wrapped::<NativeWorkbook>(ruby, workbook).map(drop)
361
364
  }
@@ -4,8 +4,10 @@ use imprimatur::read::{Limits, pdf};
4
4
  use magnus::{Error, RString, Ruby};
5
5
  use serde_json::json;
6
6
  use std::path::PathBuf;
7
+ use std::time::Duration;
7
8
 
8
9
  use crate::read::without_gvl;
10
+ use crate::{argument_error, domain_error};
9
11
 
10
12
  type Keywords = (Option<usize>, Option<u64>, Option<f64>, bool);
11
13
 
@@ -29,39 +31,61 @@ pub fn pages(
29
31
  ruby: &Ruby,
30
32
  document: RString,
31
33
  keywords: Keywords,
32
- options: (u32, u32, usize, usize, usize),
34
+ options: (u32, u32, usize, usize, usize, Option<f64>),
33
35
  worker: String,
34
36
  memory_bytes: u64,
35
37
  ) -> Result<RString, Error> {
36
- let (first_page, last_page, max_pages, max_page_bytes, max_output_bytes) = options;
38
+ let (first_page, last_page, max_pages, max_page_bytes, max_output_bytes, batch_timeout) =
39
+ options;
37
40
  let options =
38
41
  pdf::ReadOptions { first_page, last_page, max_pages, max_page_bytes, max_output_bytes };
39
42
  let worker = PathBuf::from(worker);
40
43
  let process = process_limits(memory_bytes);
41
- let value = without_gvl(ruby, document, keywords, |data, limits| {
42
- let result = pdf::isolation::pages_isolated(&worker, data, &options, limits, &process)?;
43
- let pages: Vec<_> = result
44
- .pages
45
- .into_iter()
46
- .map(|page| {
47
- json!({
48
- "page": page.number,
49
- "status": page.status.as_str(),
50
- "text": page.text,
51
- "images": page.images,
52
- "truncated": page.truncated,
53
- "reason": page.reason,
54
- })
44
+ let Some(seconds) = batch_timeout else {
45
+ let result = without_gvl(ruby, document, keywords, |data, limits| {
46
+ pdf::isolation::pages_isolated(&worker, data, &options, limits, &process)
47
+ })?;
48
+ return Ok(ruby.str_new(&pages_json(result)));
49
+ };
50
+ let attempt = Duration::try_from_secs_f64(seconds)
51
+ .map_err(|_| argument_error(ruby, "batch timeout must be finite and positive"))?;
52
+ let mut recovery = pdf::isolation::Recovery::new(&options, attempt)
53
+ .map_err(|error| domain_error(ruby, &error))?;
54
+ loop {
55
+ let step = without_gvl(ruby, document, keywords, |data, limits| {
56
+ let process = pdf::isolation::ProcessLimits {
57
+ wall_time: limits.timeout_duration().unwrap_or(process.wall_time),
58
+ ..process.clone()
59
+ };
60
+ recovery.step(&worker, data, limits, &process)
61
+ })?;
62
+ if let Some(result) = step {
63
+ return Ok(ruby.str_new(&pages_json(result)));
64
+ }
65
+ }
66
+ }
67
+
68
+ fn pages_json(result: pdf::Pages) -> String {
69
+ let pages: Vec<_> = result
70
+ .pages
71
+ .into_iter()
72
+ .map(|page| {
73
+ json!({
74
+ "page": page.number,
75
+ "status": page.status.as_str(),
76
+ "text": page.text,
77
+ "images": page.images,
78
+ "truncated": page.truncated,
79
+ "reason": page.reason,
55
80
  })
56
- .collect();
57
- Ok(json!({
58
- "page_count": result.info.page_count,
59
- "encrypted": result.info.encrypted,
60
- "pages": pages,
61
81
  })
62
- .to_string())
63
- })?;
64
- Ok(ruby.str_new(&value))
82
+ .collect();
83
+ json!({
84
+ "page_count": result.info.page_count,
85
+ "encrypted": result.info.encrypted,
86
+ "pages": pages,
87
+ })
88
+ .to_string()
65
89
  }
66
90
 
67
91
  pub fn render(
@@ -127,7 +127,7 @@ pub fn without_gvl<T, F>(
127
127
  job: F,
128
128
  ) -> Result<T, Error>
129
129
  where
130
- F: Fn(&[u8], &Limits) -> imprimatur::Result<T>,
130
+ F: FnMut(&[u8], &Limits) -> imprimatur::Result<T>,
131
131
  {
132
132
  let document = crate::bytes(document);
133
133
  let cancel = Arc::new(AtomicBool::new(false));
@@ -174,7 +174,7 @@ where
174
174
  #[allow(unsafe_code)]
175
175
  unsafe extern "C" fn run<T, F>(data: *mut c_void) -> *mut c_void
176
176
  where
177
- F: Fn(&[u8], &Limits) -> imprimatur::Result<T>,
177
+ F: FnMut(&[u8], &Limits) -> imprimatur::Result<T>,
178
178
  {
179
179
  // SAFETY: `data` is the `Read<T>` without_gvl passed, alive and not
180
180
  // otherwise borrowed until this returns.
@@ -11,8 +11,9 @@ module Imprimatur
11
11
 
12
12
  def self.pages(document, first_page: 1, last_page: 0xFFFFFFFF, max_pages: 500,
13
13
  max_page_bytes: 256 * 1024, max_output_bytes: 8 * 1024 * 1024,
14
- memory_bytes: 1024 * 1024 * 1024, max_bytes: nil, **limits)
15
- options = [first_page, last_page, max_pages, max_page_bytes, max_output_bytes]
14
+ memory_bytes: 1024 * 1024 * 1024, max_bytes: nil, batch_timeout: nil, **limits)
15
+ options = [first_page, last_page, max_pages, max_page_bytes, max_output_bytes,
16
+ batch_timeout && Float(batch_timeout)]
16
17
  JSON.parse(Native.pdf_pages(Reader.read(document, max_bytes), Reader.limits(max_bytes:, **limits),
17
18
  options, RENDER_WORKER, memory_bytes),
18
19
  symbolize_names: true)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Imprimatur
4
- VERSION = '0.8.0'
4
+ VERSION = '0.9.1'
5
5
  end
data/lib/imprimatur.rb CHANGED
@@ -115,6 +115,8 @@ module Imprimatur
115
115
  # image count (nil when unknown), truncation flag and failure reason.
116
116
  # Takes +first_page:+, +last_page:+, +max_pages:+ (500),
117
117
  # +max_page_bytes:+ (256 KiB), +max_output_bytes:+ (8 MiB), and read limits.
118
+ # Optional +batch_timeout:+ caps each worker attempt; +timeout:+ then bounds
119
+ # the whole call, including one-pass recovery of timeout-unread neighbours.
118
120
  # @return [Hash] +page_count:+, +encrypted:+ and +pages:+
119
121
  def pdf_pages(document, ...) = PdfReader.pages(document, ...)
120
122
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: imprimatur
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 0.9.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -115,11 +115,13 @@ files:
115
115
  - ext/imprimatur_native/core/src/read/pdf/images.rs
116
116
  - ext/imprimatur_native/core/src/read/pdf/isolation.rs
117
117
  - ext/imprimatur_native/core/src/read/pdf/isolation/protocol.rs
118
+ - ext/imprimatur_native/core/src/read/pdf/isolation/recovery.rs
118
119
  - ext/imprimatur_native/core/src/read/pdf/isolation/stream.rs
119
120
  - ext/imprimatur_native/core/src/read/pdf/isolation/system.rs
120
121
  - ext/imprimatur_native/core/src/read/pdf/isolation/worker.rs
121
122
  - ext/imprimatur_native/core/src/read/pdf/layout.rs
122
123
  - ext/imprimatur_native/core/src/read/pdf/layout/bidi.rs
124
+ - ext/imprimatur_native/core/src/read/pdf/layout/blocks.rs
123
125
  - ext/imprimatur_native/core/src/read/pdf/lexer.rs
124
126
  - ext/imprimatur_native/core/src/read/pdf/object.rs
125
127
  - ext/imprimatur_native/core/src/read/pdf/object/name.rs
@@ -154,6 +156,7 @@ files:
154
156
  - ext/imprimatur_native/ffi/src/archive.rs
155
157
  - ext/imprimatur_native/ffi/src/barcode.rs
156
158
  - ext/imprimatur_native/ffi/src/blocking.rs
159
+ - ext/imprimatur_native/ffi/src/classes.rs
157
160
  - ext/imprimatur_native/ffi/src/convert.rs
158
161
  - ext/imprimatur_native/ffi/src/document.rs
159
162
  - ext/imprimatur_native/ffi/src/lib.rs