Class: ZplRenderer::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/zpl_renderer/engine.rb

Overview

Invokes the offline Rust renderer binary over stdin/stdout.

Constant Summary collapse

PROTOCOL_VERSION =
1

Instance Method Summary collapse

Constructor Details

#initialize(binary_path: nil) ⇒ Engine

Returns a new instance of Engine.



12
13
14
# File 'lib/zpl_renderer/engine.rb', line 12

def initialize(binary_path: nil)
  @binary_path = binary_path
end

Instance Method Details

#render(zpl, options) ⇒ Object



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
# File 'lib/zpl_renderer/engine.rb', line 16

def render(zpl, options)
  request = JSON.generate(
    protocol: PROTOCOL_VERSION,
    zpl: zpl.to_s,
    format: options.format.to_s,
    width_mm: options.width_mm,
    height_mm: options.height_mm,
    dpmm: options.dpmm,
    index: options.index
  )

  stdout = +"".b
  stderr = +"".b
  status = nil

  begin
    Timeout.timeout(options.timeout) do
      Open3.popen3(binary_path, "--json") do |stdin, out, err, wait_thr|
        stdin.binmode
        out.binmode
        err.binmode

        stdin.write(request)
        stdin.close

        stdout = out.read
        stderr = err.read
        status = wait_thr.value
      end
    end
  rescue Timeout::Error
    raise TimeoutError, "render timed out after #{options.timeout}s"
  rescue Errno::ENOENT
    raise BinaryMissingError, Binary.missing_message
  end

  unless status&.success?
    message = stderr.to_s.strip
    message = "renderer exited with status #{status&.exitstatus}" if message.empty?
    raise_for_message!(message)
  end

  if stdout.bytesize > options.max_output_bytes
    raise OutputTooLargeError,
          "output is #{stdout.bytesize} bytes; max_output_bytes=#{options.max_output_bytes}"
  end

  stdout
end