summaryrefslogtreecommitdiff
path: root/app/services/dependency_proxy/download_blob_service.rb
blob: 3c690683bf624b5beaef628b9f0fad8017c164be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
# frozen_string_literal: true

module DependencyProxy
  class DownloadBlobService < DependencyProxy::BaseService
    class DownloadError < StandardError
      attr_reader :http_status

      def initialize(message, http_status)
        @http_status = http_status

        super(message)
      end
    end

    def initialize(image, blob_sha, token)
      @image = image
      @blob_sha = blob_sha
      @token = token
      @temp_file = Tempfile.new
    end

    def execute
      File.open(@temp_file.path, "wb") do |file|
        Gitlab::HTTP.get(blob_url, headers: auth_headers, stream_body: true) do |fragment|
          if [301, 302, 307].include?(fragment.code)
            # do nothing
          elsif fragment.code == 200
            file.write(fragment)
          else
            raise DownloadError.new('Non-success response code on downloading blob fragment', fragment.code)
          end
        end
      end

      success(file: @temp_file)
    rescue DownloadError => exception
      error(exception.message, exception.http_status)
    rescue Timeout::Error => exception
      error(exception.message, 599)
    end

    private

    def blob_url
      registry.blob_url(@image, @blob_sha)
    end
  end
end