File: metric.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (324 lines) | stat: -rwxr-xr-x 7,894 bytes parent folder | download
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# frozen_string_literal: true

module InternalEventsCli
  NEW_METRIC_FIELDS = [
    :key_path,
    :description,
    :product_group,
    :performance_indicator_type,
    :value_type,
    :status,
    :milestone,
    :introduced_by_url,
    :time_frame,
    :data_source,
    :data_category,
    :product_categories,
    :distribution,
    :tier,
    :tiers,
    :events
  ].freeze

  ADDITIONAL_METRIC_FIELDS = [
    :milestone_removed,
    :removed_by_url,
    :removed_by,
    :repair_issue_url,
    :value_json_schema,
    :name
  ].freeze

  # These keys will always be included in the definition yaml
  METRIC_DEFAULTS = {
    product_group: nil,
    introduced_by_url: 'TODO',
    value_type: 'number',
    status: 'active',
    data_source: 'internal_events',
    data_category: 'optional',
    performance_indicator_type: []
  }.freeze

  ExistingMetric = Struct.new(*NEW_METRIC_FIELDS, *ADDITIONAL_METRIC_FIELDS, :file_path, keyword_init: true) do
    def identifier
      events&.dig(0, 'unique')&.chomp('.id')
    end

    def actions
      events&.map { |event| event['name'] } # rubocop:disable Rails/Pluck -- not rails
    end

    def filters
      events&.map do |event|
        [event['name'], event['filter'] || {}]
      end
    end

    def filtered?
      !!filters&.any? { |(_action, filter)| filter&.any? }
    end

    def time_frame
      self[:time_frame] || 'all'
    end
  end

  NewMetric = Struct.new(*NEW_METRIC_FIELDS, :identifier, :actions, :key, :filters, keyword_init: true) do
    def formatted_output
      METRIC_DEFAULTS
        .merge(to_h.compact)
        .merge(
          key_path: key_path,
          events: events)
        .slice(*NEW_METRIC_FIELDS)
        .transform_keys(&:to_s)
        .to_yaml(line_width: 150)
    end

    def file_path
      File.join(
        *[
          distribution.directory_name,
          'config',
          'metrics',
          time_frame.directory_name,
          file_name
        ].compact
      )
    end

    def file_name
      "#{key.value}.yml"
    end

    def key_path
      key.full_path
    end

    def time_frame
      Metric::TimeFrame.new(self[:time_frame])
    end

    def identifier
      Metric::Identifier.new(self[:identifier])
    end

    def distribution
      Metric::Distribution.new(self[:distribution])
    end

    def key
      Metric::Key.new(self[:key] || actions, time_frame, identifier)
    end

    def filters
      Metric::Filters.new(self[:filters])
    end

    # Returns value for the `events` key in the metric definition.
    # Requires #actions or #filters to be set by the caller first.
    #
    # @return [Hash]
    def events
      if filters.assigned?
        self[:filters].map { |(action, filter)| event_params(action, filter) }
      else
        actions.map { |action| event_params(action) }
      end
    end

    def event_params(action, filter = nil)
      params = { 'name' => action }
      params['unique'] = identifier.reference if identifier.value
      params['filter'] = filter if filter&.any?

      params
    end

    def actions
      self[:actions] || []
    end

    # How to interpretting different values for filters:
    # nil --> not expected, assigned or filtered
    #        (metric not initialized with filters)
    # [] --> both expected and filtered
    #        (metric initialized with filters, but not yet assigned by user)
    # [['event', {}]] --> not expected, assigned or filtered
    #        (filters were expected, but then skipped by user)
    # [['event', { 'label' => 'a' }]] --> both assigned and filtered
    #        (filters exist for any event; user is done assigning)
    def filtered?
      filters.assigned? || filters.expected?
    end

    def filters_expected?
      filters.expected?
    end

    # Automatically prepended to all new descriptions
    # ex) Total count of
    # ex) Weekly/Monthly count of unique
    def description_prefix
      [
        time_frame.description,
        identifier.prefix,
        *(identifier.plural if identifier.default?)
      ].join(' ')
    end

    # Provides simplified but technically accurate description
    # to be used before the user has provided a description
    def technical_description
      event_name = actions.first if events.length == 1 && !filtered?
      event_name ||= 'the selected events'

      "#{time_frame.description} #{identifier.description % event_name}"
    end

    def bulk_assign(key_value_pairs)
      key_value_pairs.each { |key, value| self[key] = value }
    end
  end

  class Metric
    TimeFrame = Struct.new(:value) do
      def description
        case value
        when '7d'
          'Weekly'
        when '28d'
          'Monthly'
        when 'all'
          'Total'
        end
      end

      def directory_name
        "counts_#{value}"
      end

      def key_path
        description&.downcase if value != 'all'
      end
    end

    Identifier = Struct.new(:value) do
      # returns a description of the identifier with appropriate
      # grammer to interpolate a description of events
      def description
        if value.nil?
          "#{prefix} %s occurrences"
        elsif value == 'user'
          "#{prefix} users who triggered %s"
        elsif %w[project namespace].include?(value)
          "#{prefix} #{plural} where %s occurred"
        else
          "#{prefix} #{plural} from %s occurrences"
        end
      end

      # handles generic pluralization for unknown indentifers
      def plural
        default? ? "#{value}s" : "values for '#{value}'"
      end

      def prefix
        if value
          "count of unique"
        else
          "count of"
        end
      end

      # returns a slug which can be used in the
      # metric's key_path and filepath
      def key_path
        value ? "distinct_#{reference.tr('.', '_')}_from" : 'total'
      end

      # Returns the identifier string that will be included in the yml
      def reference
        default? ? "#{value}.id" : value
      end

      # Refers to the top-level identifiers not included in
      # additional_properties
      def default?
        %w[user project namespace].include?(value)
      end
    end

    Distribution = Struct.new(:value) do
      def directory_name
        'ee' unless value.include?('ce')
      end
    end

    Key = Struct.new(:events, :time_frame, :identifier) do
      # @param name_to_display [String] return the key with the
      #          provided name instead of a list of event names
      def value(name_to_display = nil)
        [
          'count',
          identifier&.key_path,
          name_to_display || name_for_events,
          time_frame&.key_path
        ].compact.join('_')
      end

      def full_path
        "#{prefix}.#{value}"
      end

      # Refers to the middle portion of a metric's `key_path`
      # pertaining to the relevent events; This does not include
      # identifier/time_frame/etc
      def name_for_events
        # user may have defined a different name for events
        return events unless events.respond_to?(:join)

        events.join('_and_')
      end

      def prefix
        if identifier.value
          'redis_hll_counters'
        else
          'counts'
        end
      end
    end

    Filters = Struct.new(:filters) do
      def expected?
        filters == []
      end

      def assigned?
        !!filters&.any? { |(_action, filter)| filter.any? }
      end

      def descriptions
        Array(filters).filter_map do |(action, filter)|
          next action if filter.none?

          "#{action}(#{describe_filter(filter)})"
        end.sort_by(&:length)
      end

      def describe_filter(filter)
        filter.map { |k, v| "#{k}=#{v}" }.join(',')
      end
    end

    def self.parse(**args)
      ExistingMetric.new(**args)
    end

    def self.new(**args)
      NewMetric.new(**args)
    end
  end
end