summaryrefslogtreecommitdiff
path: root/app/services/ci/runners/create_runner_service.rb
blob: ff4a33e431be2cb73da09d7c5d454200d862bc55 (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 Ci
  module Runners
    class CreateRunnerService
      RUNNER_CLASS_MAPPING = {
        'instance_type' => Ci::Runners::RunnerCreationStrategies::InstanceRunnerStrategy,
        'group_type' => Ci::Runners::RunnerCreationStrategies::GroupRunnerStrategy,
        'project_type' => Ci::Runners::RunnerCreationStrategies::ProjectRunnerStrategy
      }.freeze

      def initialize(user:, params:)
        @user = user
        @params = params
        @strategy = RUNNER_CLASS_MAPPING[params[:runner_type]].new(user: user, params: params)
      end

      def execute
        normalize_params

        error = strategy.validate_params
        return ServiceResponse.error(message: error, reason: :validation_error) if error

        unless strategy.authorized_user?
          return ServiceResponse.error(message: _('Insufficient permissions'), reason: :forbidden)
        end

        runner = ::Ci::Runner.new(params)

        return ServiceResponse.success(payload: { runner: runner }) if runner.save

        ServiceResponse.error(message: runner.errors.full_messages, reason: :save_error)
      end

      def normalize_params
        params[:registration_type] = :authenticated_user
        params[:active] = !params.delete(:paused) if params.key?(:paused)
        params[:creator] = user

        strategy.normalize_params
      end

      private

      attr_reader :user, :params, :strategy
    end
  end
end