summaryrefslogtreecommitdiff
path: root/app/services/dependency_proxy/find_or_create_manifest_service.rb
blob: 6b46f5e4c59dd1e4bac6dcf9896c2b92e1e9ef84 (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
49
50
51
52
# frozen_string_literal: true

module DependencyProxy
  class FindOrCreateManifestService < DependencyProxy::BaseService
    def initialize(group, image, tag, token)
      @group = group
      @image = image
      @tag = tag
      @token = token
      @file_name = "#{@image}:#{@tag}.json"
      @manifest = nil
    end

    def execute
      @manifest = @group.dependency_proxy_manifests
                        .find_or_initialize_by_file_name(@file_name)

      head_result = DependencyProxy::HeadManifestService.new(@image, @tag, @token).execute

      return success(manifest: @manifest) if cached_manifest_matches?(head_result)

      pull_new_manifest
      respond
    rescue Timeout::Error, *Gitlab::HTTP::HTTP_ERRORS
      respond
    end

    private

    def pull_new_manifest
      DependencyProxy::PullManifestService.new(@image, @tag, @token).execute_with_manifest do |new_manifest|
        @manifest.update!(
          digest: new_manifest[:digest],
          file: new_manifest[:file],
          size: new_manifest[:file].size
        )
      end
    end

    def cached_manifest_matches?(head_result)
      @manifest && @manifest.digest == head_result[:digest]
    end

    def respond
      if @manifest.persisted?
        success(manifest: @manifest)
      else
        error('Failed to download the manifest from the external registry', 503)
      end
    end
  end
end