summaryrefslogtreecommitdiff
path: root/app/services/dependency_proxy/find_cached_manifest_service.rb
blob: ea09445584a87e29c629d21745fb45598c1c39c0 (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
# frozen_string_literal: true

module DependencyProxy
  class FindCachedManifestService < 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
                        .active
                        .find_by_file_name_or_digest(file_name: @file_name, digest: @tag)

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

      return respond if cached_manifest_matches?(head_result)
      return respond if @manifest && head_result[:status] == :error

      success(manifest: nil, from_cache: false)
    rescue Timeout::Error, *Gitlab::HTTP::HTTP_ERRORS
      respond
    end

    private

    def cached_manifest_matches?(head_result)
      return false if head_result[:status] == :error

      @manifest && @manifest.digest == head_result[:digest] && @manifest.content_type == head_result[:content_type]
    end

    def respond(from_cache: true)
      if @manifest
        @manifest.read!

        success(manifest: @manifest, from_cache: from_cache)
      else
        error('Failed to download the manifest from the external registry', 503)
      end
    end
  end
end