ensure_stage_service.rb 1.3 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7 8 9 10 11
module Ci
  ##
  # We call this service everytime we persist a CI/CD job.
  #
  # In most cases a job should already have a stage assigned,  but in cases it
  # doesn't have we need to either find existing one or create a brand new
  # stage.
  #
  class EnsureStageService < BaseService
12
    EnsureStageError = Class.new(StandardError)
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
    def execute(build)
      @build = build

      return if build.stage_id.present?
      return if build.invalid?

      ensure_stage.tap do |stage|
        build.stage_id = stage.id

        yield stage if block_given?
      end
    end

    private

29
    def ensure_stage(attempts: 2)
30
      find_stage || create_stage
31 32
    rescue ActiveRecord::RecordNotUnique
      retry if (attempts -= 1) > 0
33

34
      raise EnsureStageError, <<~EOS
35 36 37
        We failed to find or create a unique pipeline stage after 2 retries.
        This should never happen and is most likely the result of a bug in
        the database load balancing code.
38
      EOS
39 40 41 42 43 44 45 46
    end

    def find_stage
      @build.pipeline.stages.find_by(name: @build.stage)
    end

    def create_stage
      Ci::Stage.create!(name: @build.stage,
47
                        position: @build.stage_idx,
48 49 50 51 52
                        pipeline: @build.pipeline,
                        project: @build.project)
    end
  end
end