Class: Spree::ShippingLabels::StoreFile

Inherits:
Object
  • Object
show all
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/spree/shipping_labels/store_file.rb

Overview

Fetches a purchased label from the provider's hosted URL into Spree's own private storage, so the merchant can reprint after the carrier's link has expired and a disconnected integration never breaks a warehouse. Called right after purchase and retried by Spree::ShippingLabels::StoreFileJob when that first fetch fails.

Constant Summary collapse

READ_TIMEOUT =
30
OPEN_TIMEOUT =
10
FETCH_ERRORS =

Everything a carrier CDN can fail with that is not a bug here: a blocked or unresolvable address, a refused or slow connection, a bad certificate.

[
  SsrfFilter::Error, SocketError, Timeout::Error, OpenSSL::SSL::SSLError,
  SystemCallError, Net::HTTPBadResponse, Net::ProtocolError, URI::InvalidURIError
].freeze

Instance Method Summary collapse

Methods included from Spree::ServiceModule::Base

prepended

Instance Method Details

#call(shipping_label:) ⇒ Spree::ServiceModule::Result

Returns the label with its file attached.

Parameters:

Returns:



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
# File 'app/services/spree/shipping_labels/store_file.rb', line 25

def call(shipping_label:)
  return success(shipping_label) if shipping_label.file.attached?

  url = shipping_label.file_url
  if url.blank?
    shipping_label.errors.add(:file, :no_file_url, message: I18n.t('spree.shipping_labels.errors.no_file_url'))
    return failure(shipping_label)
  end

  begin
    response = SsrfFilter.get(url, http_options: { read_timeout: READ_TIMEOUT, open_timeout: OPEN_TIMEOUT })
  rescue *FETCH_ERRORS => e
    # A carrier CDN that is down, slow or refuses the address is an
    # ordinary outcome here, not an exception the caller should handle:
    # the purchase behind it is already a fact, and the job retries.
    shipping_label.errors.add(:file, :file_fetch_failed, status: e.message,
                              message: I18n.t('spree.shipping_labels.errors.file_fetch_failed', status: e.message))
    return failure(shipping_label)
  end

  unless response.is_a?(Net::HTTPSuccess)
    shipping_label.errors.add(:file, :file_fetch_failed, status: response.code,
                              message: I18n.t('spree.shipping_labels.errors.file_fetch_failed', status: response.code))
    return failure(shipping_label)
  end

  attach(shipping_label, response.body, url)
  shipping_label.save ? success(shipping_label) : failure(shipping_label)
end