gitlab-triage 1.57.0 → 1.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,7 @@ require_relative 'rest_api_network'
33
33
  require_relative 'network_adapters/httparty_adapter'
34
34
  require_relative 'network_adapters/graphql_adapter'
35
35
  require_relative 'graphql_queries/query_builder'
36
+ require_relative 'milestone_wildcards'
36
37
  require_relative 'sources/work_items_rest_source'
37
38
  require_relative 'validators/params_validator'
38
39
  require_relative 'validators/policy_validator'
@@ -47,6 +48,8 @@ module Gitlab
47
48
  # This filter map is used to help make the filter_resource method
48
49
  # smaller. We loop through each of the keys (conditions) and map
49
50
  # that to the filters that will be used for it.
51
+ # A filter enabled for work_items must also be added to
52
+ # Validators::PolicyValidator::RUBY_WORK_ITEM_CONDITIONS.
50
53
  FILTER_MAP = {
51
54
  date: {
52
55
  'branches' => Filters::BranchDateFilter,
@@ -70,10 +73,10 @@ module Gitlab
70
73
  ALLOWED_STATE_VALUES = {
71
74
  issues: %w[opened closed],
72
75
  merge_requests: %w[opened closed merged],
73
- work_items: %w[opened closed]
76
+ work_items: Validators::PolicyValidator::WORK_ITEM_STATES
74
77
  }.with_indifferent_access.freeze
75
- MILESTONE_TIMEBOX_VALUES = %w[none any upcoming started].freeze
76
- ITERATION_SELECTION_VALUES = %w[none any].freeze
78
+ MILESTONE_TIMEBOX_VALUES = MilestoneWildcards::VALUES
79
+ ITERATION_SELECTION_VALUES = Validators::PolicyValidator::ITERATION_WILDCARDS
77
80
  EpicsTriagingForProjectImpossibleError = Class.new(StandardError)
78
81
  MultiPolicyInInjectionModeError = Class.new(StandardError)
79
82
 
@@ -97,6 +100,7 @@ module Gitlab
97
100
 
98
101
  def perform
99
102
  Validators::PolicyValidator.new(resource_rules).validate!
103
+ assert_moved_to_supported!
100
104
 
101
105
  puts "Performing a dry run.\n\n" if options.dry_run
102
106
 
@@ -221,6 +225,13 @@ module Gitlab
221
225
  raise EpicsTriagingForProjectImpossibleError, "Epics can only be triaged at the group level. Please set the `--source groups` option."
222
226
  end
223
227
 
228
+ def assert_moved_to_supported!
229
+ work_items_definition = resource_rules[:work_items]
230
+ return if work_items_definition.blank? || !right_resource_type_for_resource_option?('work_items')
231
+
232
+ work_items_source.assert_moved_to_supported!(work_items_definition)
233
+ end
234
+
224
235
  def resource_rules
225
236
  @resource_rules ||= policies.delete(:resource_rules) { {} }
226
237
  end
@@ -447,7 +458,7 @@ module Gitlab
447
458
  end
448
459
 
449
460
  def fetch_resources(resource_type, expanded_conditions, rule_definition)
450
- return fetch_work_items(expanded_conditions) if resource_type == 'work_items'
461
+ return fetch_work_items(expanded_conditions, rule_definition) if resource_type == 'work_items'
451
462
 
452
463
  resources = []
453
464
 
@@ -511,19 +522,13 @@ module Gitlab
511
522
  resources
512
523
  end
513
524
 
514
- def fetch_work_items(expanded_conditions)
525
+ def fetch_work_items(expanded_conditions, rule_definition)
515
526
  conditions = expanded_conditions.dup
516
527
  conditions[:iids] = options.resource_reference[1..] if options.resource_reference
517
528
 
518
- # The work_items path bypasses build_get_url, so validate `state` here
519
- # the same way the URL builders do for the other resource types.
520
- if conditions[:state]
521
- ParamsValidator.new(
522
- [{ name: 'state', type: String, values: ALLOWED_STATE_VALUES[:work_items] }],
523
- { 'state' => conditions[:state] }).validate!
524
- end
525
-
526
- work_items_source.list(conditions)
529
+ # The work_items path bypasses build_get_url, so `state` is not checked by
530
+ # the URL builders. PolicyValidator checks it in #perform before any fetch.
531
+ work_items_source.list(conditions, rule_definition)
527
532
  end
528
533
 
529
534
  def attach_resource_type(resources, resource_type)
@@ -679,12 +684,8 @@ module Gitlab
679
684
  return if milestone_value.empty?
680
685
 
681
686
  # Issues API should use the `milestone_id` param for timebox values, and `milestone` for milestone title
682
- args =
683
- if resource_type.to_sym == :issues && MILESTONE_TIMEBOX_VALUES.include?(milestone_value.downcase)
684
- ['milestone_id', milestone_value.titleize] # The API only accepts titleized values.
685
- else
686
- ['milestone', milestone_value]
687
- end
687
+ wildcard = MilestoneWildcards.api_value(milestone_value) if resource_type.to_sym == :issues
688
+ args = wildcard ? ['milestone_id', wildcard] : ['milestone', milestone_value]
688
689
 
689
690
  APIQueryBuilders::SingleQueryParamBuilder.new(*args)
690
691
  end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/core_ext/string/inflections'
4
+
5
+ module Gitlab
6
+ module Triage
7
+ # Milestone condition values that select a group of milestones rather than one
8
+ # title. Kept apart from Engine so the work items source and the policy validator
9
+ # can share it: Engine requires both of them.
10
+ module MilestoneWildcards
11
+ VALUES = %w[none any upcoming started].freeze
12
+
13
+ # The Issues API (milestone_id) and the Work Items API (milestone_wildcard_id)
14
+ # only accept the capitalised form, for example Started. Returns nil for a title.
15
+ def self.api_value(milestone)
16
+ value = milestone.to_s.downcase
17
+
18
+ value.titleize if VALUES.include?(value)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -126,6 +126,7 @@ module Gitlab
126
126
  tracker&.record('DELETE', url)
127
127
 
128
128
  {
129
+ status: response.code,
129
130
  results: response.parsed_response,
130
131
  ratelimit_remaining: rate_limit_remaining(response.headers),
131
132
  ratelimit_reset_at: rate_limit_reset_at(response.headers)
@@ -23,14 +23,29 @@ module Gitlab
23
23
  iid: resource[:iid],
24
24
  web_url: resource[:web_url],
25
25
  title: resource[:title],
26
+ description: features.dig(:description, :description),
26
27
  state: resource[:state],
27
28
  confidential: resource[:confidential],
28
29
  created_at: resource[:created_at],
29
30
  updated_at: resource[:updated_at],
31
+ closed_at: resource[:closed_at],
30
32
  author: resource[:author],
33
+ closed_by: resource[:closed_by],
34
+ moved_to_id: resource[:moved_to_id],
35
+ moved_to_work_item_url: resource[:moved_to_work_item_url],
36
+ # Same shape as the Issues API, which full_resource_reference and
37
+ # the {{full_reference}} placeholder read.
38
+ references: ({ full: resource[:reference] } if resource[:reference]),
31
39
  labels: label_titles(features),
32
40
  assignees: assignees(features),
41
+ # The issues API's deprecated single assignee, read by {{assignee}}.
42
+ assignee: assignees(features).first,
33
43
  milestone: features[:milestone],
44
+ upvotes: features.dig(:award_emoji, :upvotes),
45
+ downvotes: features.dig(:award_emoji, :downvotes),
46
+ # Flat string, like the Issues API: ruby conditions compare
47
+ # resource[:health_status] with values such as 'at_risk'.
48
+ health_status: features.dig(:health_status, :health_status),
34
49
  work_item_type: resource.dig(:work_item_type, :name),
35
50
  work_item_status: status_name(features),
36
51
  start_date: features.dig(:start_and_due_date, :start_date),
@@ -83,6 +83,10 @@ module Gitlab
83
83
  (actions.keys.map(&:to_sym) & %i[labels remove_labels assignees]).any?
84
84
  end
85
85
 
86
+ def work_item_state?
87
+ actions.key?(:state)
88
+ end
89
+
86
90
  def build_issue
87
91
  raise NotImplementedError
88
92
  end
@@ -147,6 +147,7 @@ module Gitlab
147
147
 
148
148
  rate_limit_debug(response) if options.debug
149
149
  rate_limit_wait(response)
150
+ warn_on_failed_delete(url, response)
150
151
  end
151
152
 
152
153
  private
@@ -218,6 +219,21 @@ module Gitlab
218
219
  sleep(1) until Time.now >= reset_at
219
220
  end
220
221
 
222
+ # Warns rather than raises, so one refused DELETE does not stop the
223
+ # other deletions of the rule.
224
+ def warn_on_failed_delete(url, response)
225
+ status = response[:status]
226
+ return if status.nil? || (200..299).cover?(status)
227
+
228
+ results = response[:results]
229
+ message = results['message'] || results['error'] if results.is_a?(Hash)
230
+
231
+ warning = "DELETE #{url} failed with status #{status}"
232
+ warning += ": #{message}" if message
233
+
234
+ puts Gitlab::Triage::UI.warn(warning)
235
+ end
236
+
221
237
  def raise_unexpected_response(results)
222
238
  raise Errors::Network::UnexpectedResponse, "Unexpected response: #{results.inspect}"
223
239
  end
@@ -2,10 +2,13 @@
2
2
 
3
3
  require 'active_support/all'
4
4
 
5
+ require_relative '../milestone_wildcards'
5
6
  require_relative '../url_builders/url_builder'
6
7
  require_relative '../normalizers/work_item_normalizer'
7
8
  require_relative '../errors'
8
9
  require_relative '../ui'
10
+ require_relative '../resource/instance_version'
11
+ require_relative '../validators/policy_validator'
9
12
 
10
13
  module Gitlab
11
14
  module Triage
@@ -19,16 +22,28 @@ module Gitlab
19
22
  #
20
23
  # The source is a self-contained peer to the engine's inline issues /
21
24
  # merge_requests / branches fetch: it owns list URL building, filter
22
- # push-down, normalization, and the PATCH update path. Comment creation
23
- # is not yet available on the Work Items REST API, so the `comment`
24
- # action is rejected at load time by Validators::PolicyValidator.
25
+ # push-down, normalization, the PATCH update path, and the notes /
26
+ # discussions write path used by the `comment` action.
25
27
  class WorkItemsRestSource
26
28
  UnavailableError = Class.new(StandardError)
27
29
  ScopeError = Class.new(StandardError)
30
+ NoteNotCreatedError = Class.new(StandardError)
31
+ UnsupportedVersionError = Class.new(StandardError)
32
+
33
+ MOVED_TO_ID_MINIMUM_VERSION = '19.6'
34
+ # moved_to_work_item_url is returned before 19.6 too, so only moved_to_id is checked.
35
+ MOVED_TO_ID_PATTERN = /\bmoved_to_id\b/
28
36
 
29
37
  # Base fields opted into on the list endpoint. The endpoint is sparse
30
38
  # by default (id, iid, global_id, title only); every field a filter or
31
39
  # template reads must be requested here or it comes back nil.
40
+ # Up to 19.5, GitLab drops a field it does not know without an error, so there
41
+ # moved_to_id (https://gitlab.com/gitlab-org/gitlab/-/merge_requests/266007)
42
+ # comes back nil for every work item, moved or not. Since 19.6 an unknown
43
+ # field or feature fails the whole list request with a 400.
44
+ # moved_to_id is an integer here, where the work items GraphQL API returns a
45
+ # WorkItem global ID. Both work items APIs return nil when the token cannot
46
+ # read the target; the Issues REST API returns it regardless.
32
47
  LIST_FIELDS = %w[
33
48
  state
34
49
  confidential
@@ -38,15 +53,25 @@ module Gitlab
38
53
  author
39
54
  namespace
40
55
  work_item_type
56
+ reference
57
+ closed_at
58
+ closed_by
59
+ moved_to_work_item_url
60
+ moved_to_id
41
61
  ].freeze
42
62
 
43
- # Widget payloads opted into via `features`.
63
+ # Widget payloads opted into via `features`. status and health_status are EE
64
+ # only: CE accepts them on read endpoints and leaves them out of the response,
65
+ # as an unlicensed EE namespace does, so their values are then nil.
44
66
  LIST_FEATURES = %w[
45
67
  labels
46
68
  assignees
47
69
  milestone
48
70
  status
49
71
  start_and_due_date
72
+ award_emoji
73
+ health_status
74
+ description
50
75
  ].freeze
51
76
 
52
77
  def initialize(network:, options:, per_page: 100, normalizer: Normalizers::WorkItemNormalizer.new)
@@ -56,16 +81,61 @@ module Gitlab
56
81
  @normalizer = normalizer
57
82
  end
58
83
 
59
- def list(conditions)
84
+ # rule_definition is the policy's own rule hash, which the engine passes so the
85
+ # fallback moved_to_id check can name the rule that fetched.
86
+ def list(conditions, rule_definition = nil)
60
87
  raw = @network.query_api(build_list_url(conditions))
61
88
 
62
89
  raise_if_unavailable!(raw)
90
+ raise_if_moved_to_missing!(raw, conditions, rule_definition)
63
91
 
64
92
  raw.map { |item| resolve_project_id!(@normalizer.call(item)) }
65
93
  end
66
94
 
67
- def update(resource, features)
68
- @network.patch_api(work_item_url(resource), features: features)
95
+ # Before 19.6, GitLab leaves moved_to_id out without an error, so a rule that
96
+ # skips moved work items would act on all of them. The engine calls this before
97
+ # any rule in the policy file runs, so when GitLab returns its version the file
98
+ # cannot stop halfway.
99
+ def assert_moved_to_supported!(work_items_definition)
100
+ labels_by_rule = moved_to_labels_by_rule(work_items_definition)
101
+ return if labels_by_rule.empty?
102
+
103
+ rule_labels = labels_by_rule.values
104
+
105
+ version = readable_instance_version
106
+ version_short = version.to_s[/^\d+\.\d+/]
107
+
108
+ if version_short.nil?
109
+ # Without a version, fall back to checking the list responses, which stops
110
+ # the run when an affected rule fetches instead of before any rule runs.
111
+ @moved_to_labels_to_check = labels_by_rule
112
+ puts Gitlab::Triage::UI.warn(
113
+ "Could not read the GitLab version. moved_to_id needs GitLab #{MOVED_TO_ID_MINIMUM_VERSION} or later, " \
114
+ "so #{rule_labels.join(', ')} will stop the run if the work items " \
115
+ "#{rule_labels.one? ? 'it fetches' : 'they fetch'} have no moved_to_id.\n\n")
116
+ return
117
+ end
118
+
119
+ return if Gem::Version.new(version_short) >= Gem::Version.new(MOVED_TO_ID_MINIMUM_VERSION)
120
+
121
+ raise_moved_to_unsupported(rule_labels, "This instance is #{version}.")
122
+ end
123
+
124
+ def update(resource, features, attributes = {})
125
+ body = attributes.dup
126
+ body[:features] = features if features.any?
127
+
128
+ @network.patch_api(work_item_url(resource), body)
129
+ end
130
+
131
+ # The adapter does not raise on a 4xx. Check for an error message, not a
132
+ # missing id, since a quick-action-only note returns 202 with no id.
133
+ def create_note(resource, body, sub_resource_type: 'notes')
134
+ response = @network.post_api(note_url(resource, sub_resource_type), body)
135
+ error = response[:id].blank? && (response[:message] || response[:error])
136
+ return response unless error
137
+
138
+ raise NoteNotCreatedError, "The note was not posted on #{resource[:web_url] || resource[:iid]} (#{error})."
69
139
  end
70
140
 
71
141
  # Returns [source, source_id] for the namespace the resource lives in.
@@ -127,6 +197,72 @@ module Gitlab
127
197
  ).build
128
198
  end
129
199
 
200
+ # A 500 that outlasts the retries, or a response that isn't JSON (for example a load
201
+ # balancer's HTML error page), leaves the version unknown, the same as an error hash, so
202
+ # the list responses are checked instead. A rejected token still stops the run.
203
+ def readable_instance_version
204
+ Resource::InstanceVersion.new(network: @network).version
205
+ rescue Errors::Network::InternalServerError, Errors::Network::UnexpectedResponse
206
+ nil
207
+ end
208
+
209
+ # Keyed by identity: the engine passes these same rule hashes to #list. A rule
210
+ # without a name is labelled by its one-based position in the policy file.
211
+ def moved_to_labels_by_rule(work_items_definition)
212
+ labels_by_rule = {}.compare_by_identity
213
+
214
+ Array(work_items_definition[:rules]).each.with_index(1) do |rule_definition, number|
215
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} under work_items.rules")
216
+ end
217
+
218
+ Array(work_items_definition[:summaries]).each.with_index(1) do |summary, summary_number|
219
+ summary_label = summary[:name].presence || "##{summary_number}"
220
+
221
+ Array(summary[:rules]).each.with_index(1) do |rule_definition, number|
222
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} in summary #{summary_label}")
223
+ end
224
+ end
225
+
226
+ labels_by_rule
227
+ end
228
+
229
+ def add_moved_to_label(labels_by_rule, rule_definition, position)
230
+ return unless reads_moved_to_id?(rule_definition[:conditions])
231
+
232
+ labels_by_rule[rule_definition] = "**#{rule_definition[:name].presence || position}**"
233
+ end
234
+
235
+ def reads_moved_to_id?(conditions)
236
+ conditions&.[](:ruby).to_s.match?(MOVED_TO_ID_PATTERN)
237
+ end
238
+
239
+ # GitLab 19.6 and later return moved_to_id on every work item once it is
240
+ # requested, as null when the work item was not moved. The conditions decide
241
+ # whether to check, so a copied rule hash only loses its label, not the check.
242
+ def raise_if_moved_to_missing!(raw, conditions, rule_definition)
243
+ return if @moved_to_labels_to_check.nil? || !reads_moved_to_id?(conditions)
244
+ return if raw.empty? || raw.first.key?(:moved_to_id)
245
+
246
+ rule_label = @moved_to_labels_to_check[rule_definition] ||
247
+ "**#{rule_definition&.[](:name).presence || conditions[:ruby]}**"
248
+
249
+ raise_moved_to_unsupported([rule_label],
250
+ 'This instance did not return its version, and its work items have no moved_to_id.')
251
+ end
252
+
253
+ def raise_moved_to_unsupported(rule_labels, version_explanation)
254
+ rules_clause =
255
+ if rule_labels.one?
256
+ "The ruby condition of rule #{rule_labels.first} reads"
257
+ else
258
+ "The ruby conditions of rules #{rule_labels.join(', ')} read"
259
+ end
260
+
261
+ raise UnsupportedVersionError,
262
+ "#{rules_clause} moved_to_id, which needs GitLab " \
263
+ "#{MOVED_TO_ID_MINIMUM_VERSION} or later on the work_items policy type. #{version_explanation}"
264
+ end
265
+
130
266
  # The Work Items REST API is behind the :work_item_rest_api feature
131
267
  # flag. When it is off, or the token lacks access, or the endpoint is
132
268
  # absent, the response is an error hash (e.g. a 403 "feature flag is
@@ -168,12 +304,26 @@ module Gitlab
168
304
  ).build
169
305
  end
170
306
 
307
+ def note_url(resource, sub_resource_type)
308
+ scope, scope_id = scope_for(resource)
309
+
310
+ UrlBuilders::UrlBuilder.new(
311
+ network_options: @options,
312
+ source: scope,
313
+ source_id: scope_id,
314
+ resource_type: '-/work_items',
315
+ resource_id: resource[:iid],
316
+ sub_resource_type: sub_resource_type
317
+ ).build
318
+ end
319
+
171
320
  def list_params(conditions)
172
321
  params = {
173
322
  per_page: @per_page,
174
323
  fields: LIST_FIELDS.join(','),
175
324
  features: LIST_FEATURES.join(',')
176
325
  }
326
+ params[:include_descendants] = true if @options.source == 'groups'
177
327
 
178
328
  apply_filters(params, conditions)
179
329
 
@@ -184,6 +334,8 @@ module Gitlab
184
334
  # `type` uses `work_item_type_names`, which resolves names (including
185
335
  # custom types) case-insensitively server-side - no id resolution
186
336
  # needed.
337
+ # A new work_items condition must also be added to
338
+ # Validators::PolicyValidator::API_WORK_ITEM_CONDITIONS.
187
339
  def apply_filters(params, conditions)
188
340
  params[:iids] = Array(conditions[:iids]).join(',') if conditions[:iids].present?
189
341
  params[:work_item_type_names] = Array(conditions[:type]).join(',') if conditions[:type]
@@ -193,30 +345,58 @@ module Gitlab
193
345
  params[:assignee_usernames] = Array(conditions[:assignees]).join(',') if conditions[:assignees]
194
346
  params['status[name]'] = conditions[:status] if conditions[:status]
195
347
 
348
+ apply_milestone_filter(params, conditions[:milestone]) if conditions[:milestone]
349
+ apply_weight_filter(params, conditions[:weight]) unless conditions[:weight].nil?
350
+ apply_iteration_filter(params, conditions[:iteration]) unless conditions[:iteration].nil?
196
351
  apply_date_filter(params, conditions[:date]) if conditions[:date]
197
352
  end
198
353
 
199
- def apply_date_filter(params, date_condition)
200
- attribute = date_condition[:attribute]
201
- condition = date_condition[:condition]
202
- return unless %w[created_at updated_at].include?(attribute)
354
+ # PolicyValidator rejects more than one value, so a list here has at most one.
355
+ # The Issues REST API keeps the legacy Started/Upcoming logic and this API does
356
+ # not, so the same wildcard can match different milestones (see README).
357
+ def apply_milestone_filter(params, milestone_condition)
358
+ milestone = Array(milestone_condition).first.to_s
359
+ return if milestone.empty?
360
+
361
+ wildcard = MilestoneWildcards.api_value(milestone)
362
+
363
+ if wildcard
364
+ params[:milestone_wildcard_id] = wildcard
365
+ else
366
+ params[:milestone_title] = milestone
367
+ end
368
+ end
369
+
370
+ # The API takes the wildcards titleized. Both are single words, so capitalize is enough.
371
+ def apply_weight_filter(params, weight)
372
+ Validators::PolicyValidator.validate_work_items_weight!(weight)
373
+
374
+ if Validators::PolicyValidator.weight_number?(weight)
375
+ params[:weight] = weight
376
+ else
377
+ params[:weight_wildcard_id] = weight.capitalize
378
+ end
379
+ end
203
380
 
204
- boundary = date_boundary(date_condition)
205
- return unless boundary
381
+ def apply_iteration_filter(params, iteration)
382
+ Validators::PolicyValidator.validate_work_items_iteration!(iteration)
383
+
384
+ params[:iteration_wildcard_id] = iteration.capitalize
385
+ end
206
386
 
207
- direction = condition == 'older_than' ? 'before' : 'after'
208
- params["#{attribute.delete_suffix('_at')}_#{direction}"] = boundary.iso8601
387
+ # A bad date condition would otherwise send no date filter, or the opposite one,
388
+ # and widen the matched set, so raise even if load-time validation was skipped.
389
+ def apply_date_filter(params, date_condition)
390
+ Validators::PolicyValidator.validate_work_items_date!(date_condition)
391
+
392
+ attribute = date_condition[:attribute]
393
+ direction = date_condition[:condition] == 'older_than' ? 'before' : 'after'
394
+ params["#{attribute.delete_suffix('_at')}_#{direction}"] = date_boundary(date_condition).iso8601
209
395
  end
210
396
 
211
397
  def date_boundary(date_condition)
212
- interval = date_condition[:interval]
213
- interval_type = date_condition[:interval_type]
214
- return unless interval && interval_type
215
-
216
- # A malformed interval_type raises here rather than silently dropping
217
- # the date bound, which would widen the matched set - dangerous in an
218
- # automation tool. interval_type is also validated by the date filter.
219
- interval.public_send(interval_type).ago # rubocop:disable GitlabSecurity/PublicSend -- interval_type constrained to a known set
398
+ # validate_work_items_date! limits interval_type to the date filter's INTERVAL_TYPES.
399
+ date_condition[:interval].public_send(date_condition[:interval_type]).ago # rubocop:disable GitlabSecurity/PublicSend -- interval_type constrained to a known set
220
400
  end
221
401
  end
222
402
  end