BigW Consortium Gitlab

base_event_fetcher.rb 1.57 KB
Newer Older
1 2
module Gitlab
  module CycleAnalytics
3
    class BaseEventFetcher
4
      include BaseQuery
5

6
      attr_reader :projections, :query, :stage, :order
7

8 9
      MAX_EVENTS = 50

10 11
      def initialize(project:, stage:, options:)
        @project = project
12
        @stage = stage
13
        @options = options
14 15 16
      end

      def fetch
James Lopez committed
17
        update_author!
18 19

        event_result.map do |event|
20
          serialize(event) if has_permission?(event['id'])
21
        end.compact
22
      end
23

James Lopez committed
24 25 26 27
      def order
        @order || default_order
      end

28
      private
29

30
      def update_author!
James Lopez committed
31 32
        return unless event_result.any? && event_result.first['author_id']

33
        Updater.update!(event_result, from: 'author_id', to: 'author', klass: User)
34 35 36
      end

      def event_result
37 38 39 40 41 42
        @event_result ||= ActiveRecord::Base.connection.exec_query(events_query.to_sql).to_a
      end

      def events_query
        diff_fn = subtract_datetimes_diff(base_query, @options[:start_time_attrs], @options[:end_time_attrs])

43
        base_query.project(extract_diff_epoch(diff_fn).as('total_time'), *projections).order(order.desc).take(MAX_EVENTS)
44 45 46
      end

      def default_order
47
        [@options[:start_time_attrs]].flatten.first
48 49
      end

50 51 52 53
      def serialize(_event)
        raise NotImplementedError.new("Expected #{self.name} to implement serialize(event)")
      end

54 55 56 57 58 59 60 61 62 63
      def has_permission?(id)
        allowed_ids.nil? || allowed_ids.include?(id.to_i)
      end

      def allowed_ids
        nil
      end

      def event_result_ids
        event_result.map { |event| event['id'] }
64 65 66 67
      end
    end
  end
end