Class: Imgwire::HTTP::UploadClient

Inherits:
Object
  • Object
show all
Defined in:
lib/imgwire/http/upload_client.rb

Constant Summary collapse

RETRYABLE_ERRORS =
[
  Errno::ECONNRESET,
  Errno::ETIMEDOUT,
  IOError,
  Net::OpenTimeout,
  Net::ReadTimeout
].freeze

Instance Method Summary collapse

Instance Method Details

#put(url, upload, timeout:, max_retries:, backoff_factor:) ⇒ Object



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
# File 'lib/imgwire/http/upload_client.rb', line 17

def put(url, upload, timeout:, max_retries:, backoff_factor:)
  uri = URI.parse(url)
  attempts = 0

  begin
    attempts += 1
    upload.rewind if upload.respond_to?(:rewind)

    request = Net::HTTP::Put.new(uri)
    request['Content-Length'] = upload.content_length.to_s
    request['Content-Type'] = upload.mime_type if upload.mime_type
    request.body_stream = upload.io
    request.content_length = upload.content_length

    Net::HTTP.start(
      uri.host,
      uri.port,
      use_ssl: uri.scheme == 'https',
      open_timeout: timeout,
      read_timeout: timeout,
      write_timeout: timeout
    ) do |http|
      response = http.request(request)
      return response if response.is_a?(Net::HTTPSuccess)

      raise "Upload failed with status #{response.code}: #{response.body}"
    end
  rescue *RETRYABLE_ERRORS => e
    raise e if attempts > max_retries + 1

    sleep(backoff_factor * (2**(attempts - 1)))
    retry
  end
end