htmlToPdf 3.0.1 → 4.0.0

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.
@@ -1,3 +1,5 @@
1
+ require "htmlToPdf/job_status"
2
+
1
3
  module HtmlToPdf
2
4
  class Configuration
3
5
  # Hash of keyword options passed straight to Ferrum::Browser.new, e.g.
@@ -25,6 +27,56 @@ module HtmlToPdf
25
27
  # request stall every other PDF render sharing that browser.
26
28
  attr_accessor :max_javascript_delay_ms
27
29
 
30
+ # Caps how many conversions (HtmlToPdf::BrowserPool#with_page calls) may
31
+ # run against the shared browser at once, via a Concurrent::Semaphore —
32
+ # see HtmlToPdf::ConcurrencyLimiter. nil (default) means unbounded, i.e.
33
+ # today's exact behavior. Applies to both the synchronous controller path
34
+ # and background jobs, since both funnel through the same one Chrome
35
+ # process per Ruby process (see docs/architecture.md's scaling note).
36
+ attr_accessor :max_concurrent_renders
37
+
38
+ # Where HtmlToPdf::JobStatus persists a background job's state so it's
39
+ # readable from a different process than the one running the job (e.g.
40
+ # your web process checking on a Sidekiq worker). Defaults to a
41
+ # Rails.cache-backed store (HtmlToPdf::JobStatus::CacheStore) — swap in
42
+ # your own by assigning any object responding to #read(job_id)/
43
+ # #write(job_id, attrs). See docs/background-jobs.md for the
44
+ # cross-process-visibility caveat with memory_store/file_store.
45
+ attr_accessor :job_status_store
46
+
47
+ # How long a HtmlToPdf::JobStatus entry is kept in job_status_store
48
+ # before it's eligible for eviction. Defaults to 24 hours.
49
+ attr_accessor :job_status_ttl
50
+
51
+ # The ActiveJob queue HtmlToPdf::GenerateJob enqueues onto. Defaults to
52
+ # :default. Read dynamically per-enqueue (via queue_as's block form), so
53
+ # this is safe to change at runtime, unlike job_retry settings — see
54
+ # docs/background-jobs.md.
55
+ attr_accessor :job_queue_name
56
+
57
+ # Optional Procs invoked after a background job completes/fails for
58
+ # good, i.e. after retries are exhausted for on_job_failure. Each is
59
+ # called with the HtmlToPdf::JobStatus record (on_job_failure also gets
60
+ # the exception as a second argument). Never invoked for the synchronous
61
+ # controller path.
62
+ attr_accessor :on_job_success, :on_job_failure
63
+
64
+ # Hash of options (e.g. { host: "app.example.com", protocol: "https" })
65
+ # used to build the ActionController::Renderer HtmlToPdf::Renderer calls
66
+ # from a background job, where (unlike a real request) there's no
67
+ # request to infer a host from at all. Required to use
68
+ # HtmlToPdf.generate_later / HtmlToPdf::Renderer — see
69
+ # docs/background-jobs.md.
70
+ attr_accessor :default_url_options
71
+
72
+ # Defaults consumed by HtmlToPdf::Storage::S3Adapter so callers don't
73
+ # have to repeat them on every call. s3_client_options is passed straight
74
+ # to Aws::S3::Client.new (e.g. { region: "us-east-1" }) — leave
75
+ # credentials out of it and let the AWS SDK's default credential chain
76
+ # (an instance/task IAM role) resolve them; only set explicit credentials
77
+ # there if an instance role genuinely isn't an option.
78
+ attr_accessor :s3_bucket, :s3_client_options
79
+
28
80
  def initialize
29
81
  @browser_options = {}
30
82
  @default_layout = 'application'
@@ -32,6 +84,15 @@ module HtmlToPdf
32
84
  @tmp_dir = nil
33
85
  @allow_request_templates = false
34
86
  @max_javascript_delay_ms = 10_000
87
+ @max_concurrent_renders = nil
88
+ @job_status_store = HtmlToPdf::JobStatus::CacheStore.new
89
+ @job_status_ttl = 24 * 60 * 60
90
+ @job_queue_name = :default
91
+ @on_job_success = nil
92
+ @on_job_failure = nil
93
+ @default_url_options = nil
94
+ @s3_bucket = nil
95
+ @s3_client_options = {}
35
96
  end
36
97
  end
37
98
 
@@ -0,0 +1,41 @@
1
+ require "securerandom"
2
+ require "fileutils"
3
+
4
+ module HtmlToPdf
5
+ # Turns an already-rendered HTML string into PDF bytes via the pooled
6
+ # headless Chrome (BrowserPool). Shared by both the synchronous controller
7
+ # path (lib/htmlToPdf.rb#html_to_pdf, which gets its HTML from a real
8
+ # request's render_to_string) and HtmlToPdf::Renderer (which gets its HTML
9
+ # from ActionController::Renderer, outside of a request) — the "write to a
10
+ # temp file, point Chrome's file:// at it, clean up" steps are identical
11
+ # either way.
12
+ module Converter
13
+ module_function
14
+
15
+ def convert(html, print_options:, javascript_delay:)
16
+ # Chrome loads this over file://, not a Rails-served response, so a
17
+ # relative asset URL only resolves if config.action_controller.asset_host
18
+ # is set — see docs/rails-integration.md#the-asset_host-gotcha.
19
+ file_content = html.gsub(/\\"/, "")
20
+
21
+ tmp_dir = HtmlToPdf.configuration.tmp_dir || File.join(Rails.root, "tmp")
22
+ FileUtils.mkdir_p(tmp_dir)
23
+ source_file = File.join(tmp_dir, "#{Time.now.to_i}_#{SecureRandom.hex(8)}.html")
24
+ File.write(source_file, file_content)
25
+
26
+ begin
27
+ render_pdf(source_file, print_options: print_options, javascript_delay: javascript_delay)
28
+ ensure
29
+ File.delete(source_file) if File.exist?(source_file)
30
+ end
31
+ end
32
+
33
+ def render_pdf(source_file, print_options:, javascript_delay:)
34
+ HtmlToPdf::BrowserPool.with_page do |page|
35
+ page.go_to("file://#{source_file}")
36
+ sleep(javascript_delay / 1000.0) if javascript_delay.to_i.positive?
37
+ page.pdf(encoding: :binary, **(print_options || {}))
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,44 @@
1
+ require "htmlToPdf/renderer"
2
+ require "htmlToPdf/storage"
3
+ require "htmlToPdf/job_status"
4
+ require "htmlToPdf/browser_pool"
5
+
6
+ module HtmlToPdf
7
+ # The batteries-included background job behind HtmlToPdf.generate_later.
8
+ # Built entirely on ActiveJob's own public API (retry_on/discard_on/
9
+ # queue_as) — no Sidekiq- or Solid-Queue-specific code anywhere — so it
10
+ # runs under whichever queue adapter the host app configures
11
+ # (config.active_job.queue_adapter).
12
+ #
13
+ # Anyone who wants different retry/discard/queue semantics than the ones
14
+ # below should define their own ActiveJob class built on the same
15
+ # HtmlToPdf::Renderer / HtmlToPdf::Storage primitives this job itself
16
+ # calls, rather than trying to reconfigure this one — see
17
+ # docs/background-jobs.md for why retry attempts specifically aren't a
18
+ # HtmlToPdf.configure knob (retry_on is evaluated once, at class-definition
19
+ # time, before a host app's initializer has had a chance to run).
20
+ class GenerateJob < ActiveJob::Base
21
+ queue_as { HtmlToPdf.configuration.job_queue_name }
22
+
23
+ retry_on(*HtmlToPdf::BrowserPool::RECOVERABLE_ERRORS, wait: :polynomially_longer, attempts: 3) do |job, error|
24
+ status = HtmlToPdf::JobStatus.new(job.job_id).failed!(error)
25
+ HtmlToPdf.configuration.on_job_failure&.call(status, error)
26
+ end
27
+
28
+ discard_on ArgumentError do |job, error|
29
+ status = HtmlToPdf::JobStatus.new(job.job_id).failed!(error)
30
+ HtmlToPdf.configuration.on_job_failure&.call(status, error)
31
+ end
32
+
33
+ def perform(controller:, action:, assigns: {}, pdf_options: {}, store: nil, metadata: {})
34
+ status = HtmlToPdf::JobStatus.new(job_id, metadata: metadata)
35
+ status.processing!
36
+
37
+ pdf_bytes = HtmlToPdf::Renderer.render(controller: controller, action: action, assigns: assigns, pdf_options: pdf_options)
38
+ result = store ? HtmlToPdf::Storage.store(pdf_bytes, **store) : nil
39
+
40
+ status.completed!(result: result)
41
+ HtmlToPdf.configuration.on_job_success&.call(status)
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,31 @@
1
+ module HtmlToPdf
2
+ class JobStatus
3
+ # Default HtmlToPdf.configuration.job_status_store. Persists each job's
4
+ # state under a namespaced Rails.cache key, so a web process can read
5
+ # what a Sidekiq/Solid Queue worker process wrote.
6
+ #
7
+ # Rails.cache is zero-setup (every Rails app has one — :memory_store in
8
+ # development), but that's also its caveat: :memory_store and
9
+ # :file_store are per-process, so a web process will never see a status
10
+ # a *different* worker process wrote with either of those. Production
11
+ # needs a shared store (Redis, Solid Cache, Memcached) for job status to
12
+ # actually be visible across processes — see docs/background-jobs.md.
13
+ class CacheStore
14
+ KEY_PREFIX = "htmlToPdf:job_status:".freeze
15
+
16
+ def read(job_id)
17
+ Rails.cache.read(key_for(job_id))
18
+ end
19
+
20
+ def write(job_id, attrs)
21
+ Rails.cache.write(key_for(job_id), attrs, expires_in: HtmlToPdf.configuration.job_status_ttl)
22
+ end
23
+
24
+ private
25
+
26
+ def key_for(job_id)
27
+ "#{KEY_PREFIX}#{job_id}"
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,78 @@
1
+ require "htmlToPdf/job_status/cache_store"
2
+
3
+ module HtmlToPdf
4
+ # Tracks one HtmlToPdf::GenerateJob's lifecycle (queued -> processing ->
5
+ # completed/failed) in config.job_status_store, so it's readable from a
6
+ # different process than the one running the job — e.g. a web request
7
+ # polling on a PDF a Sidekiq/Solid Queue worker is generating.
8
+ #
9
+ # Not used by the synchronous controller path at all; that path has
10
+ # nothing to poll for, since it returns the PDF directly in the response.
11
+ class JobStatus
12
+ attr_reader :job_id, :state, :result, :error, :metadata, :queued_at, :started_at, :finished_at
13
+
14
+ def self.find(job_id)
15
+ new(job_id).tap(&:reload)
16
+ end
17
+
18
+ def initialize(job_id, metadata: {})
19
+ @job_id = job_id
20
+ @metadata = metadata
21
+ end
22
+
23
+ def reload
24
+ stored = HtmlToPdf.configuration.job_status_store.read(job_id)
25
+ assign(stored) if stored
26
+ self
27
+ end
28
+
29
+ %i[queued processing completed failed].each do |s|
30
+ define_method("#{s}?") { state == s.to_s }
31
+ end
32
+
33
+ def queued!
34
+ persist!(state: "queued", queued_at: Time.now.utc)
35
+ end
36
+
37
+ def processing!
38
+ persist!(state: "processing", started_at: Time.now.utc)
39
+ end
40
+
41
+ def completed!(result:)
42
+ persist!(state: "completed", result: result, finished_at: Time.now.utc)
43
+ end
44
+
45
+ def failed!(exception)
46
+ persist!(
47
+ state: "failed",
48
+ error: { class: exception.class.name, message: exception.message },
49
+ finished_at: Time.now.utc
50
+ )
51
+ end
52
+
53
+ private
54
+
55
+ def persist!(changes)
56
+ assign(changes)
57
+ HtmlToPdf.configuration.job_status_store.write(job_id, to_h)
58
+ self
59
+ end
60
+
61
+ def assign(attrs)
62
+ @state = attrs[:state] if attrs.key?(:state)
63
+ @result = attrs[:result] if attrs.key?(:result)
64
+ @error = attrs[:error] if attrs.key?(:error)
65
+ @metadata = attrs[:metadata] if attrs.key?(:metadata)
66
+ @queued_at = attrs[:queued_at] if attrs.key?(:queued_at)
67
+ @started_at = attrs[:started_at] if attrs.key?(:started_at)
68
+ @finished_at = attrs[:finished_at] if attrs.key?(:finished_at)
69
+ end
70
+
71
+ def to_h
72
+ {
73
+ state: state, result: result, error: error, metadata: metadata,
74
+ queued_at: queued_at, started_at: started_at, finished_at: finished_at
75
+ }
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,54 @@
1
+ require "htmlToPdf/converter"
2
+ require "htmlToPdf/print_options"
3
+
4
+ module HtmlToPdf
5
+ # Renders a controller action to PDF bytes *outside* of a request —
6
+ # there's no controller instance mid-dispatch to call render_to_string on,
7
+ # the way the synchronous `include HtmlToPdf` / around_action path does.
8
+ # Used by HtmlToPdf::GenerateJob (and anything else running in a
9
+ # background job), via ActionController::Renderer — the same Rails API
10
+ # ActionMailer itself uses to render views outside a request.
11
+ module Renderer
12
+ module_function
13
+
14
+ # controller: a controller Class (or its String name). action: Symbol/
15
+ # String. assigns: a Hash of the ivars the view needs — this is the
16
+ # actual mechanism (not `params`) for feeding a renderer-rendered
17
+ # template data; ActiveRecord objects pass through fine since ActiveJob
18
+ # serializes them via GlobalID. pdf_options: same shape taken by the
19
+ # synchronous path (:title is unused here — callers get the PDF bytes
20
+ # back directly, not a filename).
21
+ def render(controller:, action:, assigns: {}, pdf_options: {})
22
+ env = default_url_options!
23
+ controller_class = resolve_controller(controller)
24
+ layout = pdf_options[:layout] || HtmlToPdf.configuration.default_layout
25
+ print_options, javascript_delay = HtmlToPdf::PrintOptions.build(pdf_options)
26
+
27
+ html = controller_class.renderer.new(env).render(
28
+ template: "#{controller_class.controller_path}/#{action}",
29
+ assigns: assigns,
30
+ layout: layout
31
+ )
32
+
33
+ HtmlToPdf::Converter.convert(html, print_options: print_options, javascript_delay: javascript_delay)
34
+ end
35
+
36
+ def resolve_controller(controller)
37
+ controller.is_a?(String) ? controller.constantize : controller
38
+ end
39
+
40
+ def default_url_options!
41
+ env = HtmlToPdf.configuration.default_url_options
42
+ return env if env
43
+
44
+ raise ArgumentError,
45
+ "HtmlToPdf.configuration.default_url_options must be set to render a PDF outside " \
46
+ "of a request (there's no request here for HtmlToPdf::Renderer to infer a host " \
47
+ "from, unlike the synchronous controller path). Set it in your initializer, e.g. " \
48
+ 'config.default_url_options = { http_host: "app.example.com", https: true } — ' \
49
+ "note these are ActionController::Renderer's env keys (http_host/https), not " \
50
+ "config.action_mailer.default_url_options's (host/protocol). See " \
51
+ "docs/background-jobs.md."
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,35 @@
1
+ require "stringio"
2
+
3
+ module HtmlToPdf
4
+ module Storage
5
+ # Attaches the rendered PDF to an ActiveRecord record via ActiveStorage
6
+ # — `record.public_send(attachment)` must be a has_one_attached/
7
+ # has_many_attached association. Uses whatever service config/storage.yml
8
+ # already points the app at (disk, S3, GCS, ...); for direct S3 upload
9
+ # without ActiveStorage's blob/attachment bookkeeping, see S3Adapter.
10
+ class ActiveStorageAdapter
11
+ def initialize(record:, attachment:, filename: "document.pdf", content_type: "application/pdf")
12
+ @record = record
13
+ @attachment = attachment
14
+ @filename = filename
15
+ @content_type = content_type
16
+ end
17
+
18
+ def store(bytes)
19
+ unless defined?(ActiveStorage)
20
+ raise LoadError,
21
+ "ActiveStorage isn't loaded. If this app was generated with " \
22
+ "--skip-active-storage, either undo that or use " \
23
+ "HtmlToPdf::Storage::S3Adapter (adapter: :s3) instead."
24
+ end
25
+
26
+ attachable = @record.public_send(@attachment)
27
+ attachable.attach(io: StringIO.new(bytes), filename: @filename, content_type: @content_type)
28
+ blob = attachable.blob
29
+
30
+ { adapter: :active_storage, blob_id: blob.id, key: blob.key,
31
+ filename: blob.filename.to_s, byte_size: blob.byte_size }
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,48 @@
1
+ module HtmlToPdf
2
+ module Storage
3
+ # Direct S3 upload via the AWS SDK, for apps that don't use ActiveStorage
4
+ # at all and just want a plain bucket/key/URL back. htmlToPdf does not
5
+ # depend on aws-sdk-s3 — add `gem "aws-sdk-s3"` to your own Gemfile to
6
+ # use this adapter.
7
+ #
8
+ # bucket/client_options fall back to HtmlToPdf.configuration.s3_bucket/
9
+ # s3_client_options if not given per call. Prefer leaving credentials out
10
+ # of client_options and letting the AWS SDK's default credential chain
11
+ # (an EC2/ECS instance role) resolve them; only pass explicit credentials
12
+ # if an instance role genuinely isn't an option (e.g. a cross-account
13
+ # bucket).
14
+ class S3Adapter
15
+ def initialize(key:, bucket: nil, content_type: "application/pdf", client_options: nil)
16
+ @key = key
17
+ @bucket = bucket || HtmlToPdf.configuration.s3_bucket
18
+ @content_type = content_type
19
+ @client_options = client_options || HtmlToPdf.configuration.s3_client_options || {}
20
+
21
+ return if @bucket
22
+
23
+ raise ArgumentError,
24
+ "HtmlToPdf::Storage::S3Adapter needs a bucket — pass bucket: or set " \
25
+ "HtmlToPdf.configuration.s3_bucket."
26
+ end
27
+
28
+ def store(bytes)
29
+ require_aws_sdk!
30
+
31
+ client = Aws::S3::Client.new(**@client_options)
32
+ client.put_object(bucket: @bucket, key: @key, body: bytes, content_type: @content_type)
33
+ url = Aws::S3::Object.new(bucket_name: @bucket, key: @key, client: client).public_url
34
+
35
+ { adapter: :s3, bucket: @bucket, key: @key, url: url }
36
+ end
37
+
38
+ private
39
+
40
+ def require_aws_sdk!
41
+ require "aws-sdk-s3"
42
+ rescue LoadError
43
+ raise LoadError, 'aws-sdk-s3 isn\'t available — add `gem "aws-sdk-s3"` to your Gemfile ' \
44
+ "to use HtmlToPdf::Storage::S3Adapter."
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,41 @@
1
+ module HtmlToPdf
2
+ # Dispatches HtmlToPdf::Storage.store(bytes, adapter: ..., **opts) to a
3
+ # registered storage adapter. Ships with :active_storage and :s3 (see
4
+ # storage/active_storage_adapter.rb and storage/s3_adapter.rb); register
5
+ # your own with HtmlToPdf::Storage.register(:my_adapter, MyAdapterClass).
6
+ #
7
+ # An adapter is any class whose #initialize takes the **opts passed to
8
+ # .store (minus :adapter itself) and whose #store(pdf_bytes) returns a
9
+ # plain, ActiveJob-serializable Hash describing where the PDF ended up —
10
+ # that return value becomes HtmlToPdf::JobStatus#result for a background
11
+ # job, so avoid returning live objects (an ActiveStorage::Blob, an
12
+ # Aws::S3::Object) that may not survive round-tripping through the job
13
+ # status store.
14
+ module Storage
15
+ class UnknownAdapterError < StandardError; end
16
+
17
+ ADAPTERS = {}
18
+
19
+ module_function
20
+
21
+ def register(name, klass)
22
+ ADAPTERS[name.to_sym] = klass
23
+ end
24
+
25
+ def store(bytes, adapter:, **options)
26
+ klass = ADAPTERS.fetch(adapter.to_sym) do
27
+ raise UnknownAdapterError,
28
+ "Unknown HtmlToPdf storage adapter: #{adapter.inspect} " \
29
+ "(registered: #{ADAPTERS.keys.join(', ')})"
30
+ end
31
+
32
+ klass.new(**options).store(bytes)
33
+ end
34
+ end
35
+ end
36
+
37
+ require "htmlToPdf/storage/active_storage_adapter"
38
+ require "htmlToPdf/storage/s3_adapter"
39
+
40
+ HtmlToPdf::Storage.register(:active_storage, HtmlToPdf::Storage::ActiveStorageAdapter)
41
+ HtmlToPdf::Storage.register(:s3, HtmlToPdf::Storage::S3Adapter)
@@ -1,3 +1,3 @@
1
1
  module HtmlToPdf
2
- VERSION = "3.0.1"
2
+ VERSION = "4.0.0"
3
3
  end
data/lib/htmlToPdf.rb CHANGED
@@ -5,10 +5,73 @@ require "htmlToPdf/version"
5
5
  require "htmlToPdf/configuration"
6
6
  require "htmlToPdf/browser_pool"
7
7
  require "htmlToPdf/print_options"
8
+ require "htmlToPdf/converter"
9
+ require "htmlToPdf/renderer"
10
+ require "htmlToPdf/storage"
11
+ require "htmlToPdf/job_status"
12
+
13
+ # Defined eagerly (not lazily inside HtmlToPdf.generate_later) specifically
14
+ # so a separate worker process (a Sidekiq/Solid Queue process that never
15
+ # itself calls generate_later, only performs jobs the web process enqueued)
16
+ # has the class available too — ActiveJob resolves a job by class *name* at
17
+ # perform time, in whatever process that happens to be, and that process's
18
+ # own boot never otherwise touches this gem's generate_later method. Guarded
19
+ # on ActiveJob::Base being defined already (true for any ordinary Rails app
20
+ # by the time Bundler.require reaches this gem) so an app generated with
21
+ # --skip-active-job still boots — HtmlToPdf.generate_later itself raises a
22
+ # clear error in that case instead.
23
+ require "htmlToPdf/generate_job" if defined?(ActiveJob::Base)
8
24
 
9
25
  module HtmlToPdf
10
26
  extend ActiveSupport::Concern
11
27
 
28
+ class << self
29
+ # Enqueues HtmlToPdf::GenerateJob — the background-rendering counterpart
30
+ # to the synchronous `include HtmlToPdf` / around_action path, for PDFs
31
+ # slow enough that a caller shouldn't hold a connection open for them, or
32
+ # that should end up in storage (S3/ActiveStorage) rather than streamed
33
+ # back directly. See docs/background-jobs.md.
34
+ #
35
+ # controller: a controller Class (or its String name). action: Symbol/
36
+ # String. assigns: ivars the view needs (AR objects pass through fine —
37
+ # ActiveJob serializes them via GlobalID). pdf_options: same shape as the
38
+ # synchronous path's pdf_options. store: optional, e.g.
39
+ # { adapter: :active_storage, record:, attachment: } or
40
+ # { adapter: :s3, key: } — see HtmlToPdf::Storage. metadata: optional,
41
+ # arbitrary serializable data surfaced on the JobStatus record and handed
42
+ # to config.on_job_success/on_job_failure.
43
+ #
44
+ # Returns the enqueued HtmlToPdf::GenerateJob (ActiveJob::Base#job_id,
45
+ # etc.). Immediately writes a "queued" HtmlToPdf::JobStatus for that
46
+ # job_id, readable via HtmlToPdf::JobStatus.find.
47
+ def generate_later(controller:, action:, assigns: {}, pdf_options: {}, store: nil, metadata: {})
48
+ unless defined?(ActiveJob::Base)
49
+ raise LoadError,
50
+ "ActiveJob isn't loaded — HtmlToPdf.generate_later needs it. If this app was " \
51
+ "generated with --skip-active-job, either undo that or call " \
52
+ "HtmlToPdf::Renderer.render + HtmlToPdf::Storage.store directly instead (the " \
53
+ "synchronous building blocks generate_later is built from)."
54
+ end
55
+
56
+ require "htmlToPdf/generate_job"
57
+
58
+ # Built via .new + #enqueue (what .perform_later does internally)
59
+ # rather than .perform_later directly, so the "queued" status below is
60
+ # written *before* the job can possibly run — some queue adapters
61
+ # (:inline, or the :test adapter under perform_enqueued_jobs) execute
62
+ # the job synchronously as part of enqueuing it, and writing "queued"
63
+ # afterwards would then clobber a "completed"/"failed" status that
64
+ # already landed.
65
+ job = GenerateJob.new(
66
+ controller: controller, action: action, assigns: assigns,
67
+ pdf_options: pdf_options, store: store, metadata: metadata
68
+ )
69
+ JobStatus.new(job.job_id, metadata: metadata).queued!
70
+ job.enqueue
71
+ job
72
+ end
73
+ end
74
+
12
75
  # Wire up with `include HtmlToPdf` then `around_action :html_to_pdf` (not
13
76
  # `before_action`) in the controller(s) that should support it — typically
14
77
  # ApplicationController. An around_action is required: it lets the rest of
@@ -40,18 +103,7 @@ module HtmlToPdf
40
103
  end
41
104
 
42
105
  html = render_to_string(template: "#{controller_name}/#{action_name}", layout: @layout, locals: { url: Rails.application.routes.url_helpers })
43
- file_content = html.gsub(/\\&quot;/, "")
44
-
45
- tmp_dir = HtmlToPdf.configuration.tmp_dir || File.join(Rails.root, 'tmp')
46
- FileUtils.mkdir_p(tmp_dir)
47
- source_file = File.join(tmp_dir, "#{Time.now.to_i}_#{SecureRandom.hex(8)}.html")
48
- File.write(source_file, file_content)
49
-
50
- begin
51
- pdf_bytes = render_pdf(source_file)
52
- ensure
53
- File.delete(source_file) if File.exist?(source_file)
54
- end
106
+ pdf_bytes = HtmlToPdf::Converter.convert(html, print_options: @print_options, javascript_delay: @javascript_delay)
55
107
 
56
108
  deliver_pdf(pdf_bytes)
57
109
  end
@@ -72,11 +124,7 @@ module HtmlToPdf
72
124
  # markup directly) gives relative asset paths a real base URI to resolve
73
125
  # against, matching how a browser would load the page.
74
126
  def render_pdf(source_file)
75
- HtmlToPdf::BrowserPool.with_page do |page|
76
- page.go_to("file://#{source_file}")
77
- sleep(@javascript_delay / 1000.0) if @javascript_delay.to_i.positive?
78
- page.pdf(encoding: :binary, **(@print_options || {}))
79
- end
127
+ HtmlToPdf::Converter.render_pdf(source_file, print_options: @print_options, javascript_delay: @javascript_delay)
80
128
  end
81
129
 
82
130
  private
@@ -0,0 +1,83 @@
1
+ require "spec_helper"
2
+
3
+ RSpec.describe HtmlToPdf::ConcurrencyLimiter do
4
+ after { described_class.reset! }
5
+
6
+ describe ".around" do
7
+ it "yields directly, with no limiting, when max_concurrent_renders is unset (default)" do
8
+ expect(HtmlToPdf.configuration.max_concurrent_renders).to be_nil
9
+
10
+ result = described_class.around { :done }
11
+
12
+ expect(result).to eq(:done)
13
+ end
14
+
15
+ it "lets up to max_concurrent_renders callers run at once" do
16
+ HtmlToPdf.configure { |c| c.max_concurrent_renders = 2 }
17
+ started = Queue.new
18
+ release = Queue.new
19
+
20
+ threads = Array.new(2) do
21
+ Thread.new do
22
+ described_class.around do
23
+ started << :started
24
+ release.pop
25
+ end
26
+ end
27
+ end
28
+
29
+ 2.times { started.pop }
30
+ expect(threads.all?(&:alive?)).to be true
31
+ ensure
32
+ 2.times { release << :go }
33
+ threads&.each(&:join)
34
+ end
35
+
36
+ it "blocks a caller beyond the limit until a permit is released" do
37
+ HtmlToPdf.configure { |c| c.max_concurrent_renders = 1 }
38
+ holding = Queue.new
39
+ release = Queue.new
40
+ second_call_started = false
41
+
42
+ first = Thread.new do
43
+ described_class.around do
44
+ holding << :holding
45
+ release.pop
46
+ end
47
+ end
48
+ holding.pop
49
+
50
+ second = Thread.new do
51
+ described_class.around { second_call_started = true }
52
+ end
53
+
54
+ sleep 0.05
55
+ expect(second_call_started).to be false
56
+
57
+ release << :go
58
+ first.join
59
+ second.join
60
+
61
+ expect(second_call_started).to be true
62
+ end
63
+
64
+ it "releases the permit even if the block raises" do
65
+ HtmlToPdf.configure { |c| c.max_concurrent_renders = 1 }
66
+
67
+ expect { described_class.around { raise "boom" } }.to raise_error("boom")
68
+
69
+ # If the permit weren't released, this would hang — RSpec's own
70
+ # default timeout would fail the example rather than wedge the suite.
71
+ expect(described_class.around { :ok }).to eq(:ok)
72
+ end
73
+
74
+ it "resizes the semaphore when max_concurrent_renders changes" do
75
+ HtmlToPdf.configure { |c| c.max_concurrent_renders = 1 }
76
+ described_class.around { nil }
77
+
78
+ HtmlToPdf.configure { |c| c.max_concurrent_renders = 5 }
79
+
80
+ expect(described_class.semaphore_for(5).available_permits).to eq(5)
81
+ end
82
+ end
83
+ end