Class: DownloaderForCloud

Inherits:
Downloader show all
Defined in:
lib/jirametrics/downloader_for_cloud.rb

Constant Summary

Constants inherited from Downloader

Downloader::CURRENT_METADATA_VERSION

Instance Attribute Summary

Attributes inherited from Downloader

#board_id_to_filter_id, #file_system, #metadata, #start_date_in_query

Instance Method Summary collapse

Methods inherited from Downloader

create, #download_features, #download_github_prs, #download_sprints, #download_statuses, #download_users, #end_progress, #extract_project_keys_from_downloaded_issues, #file_prefix, #find_board_ids, #identify_other_issues_to_be_downloaded, #initialize, #load_cached_metadata, #load_metadata, #log, #log_start, #make_jql, #metadata_pathname, #progress_dot, #remove_old_files, #save_metadata, #start_progress, #timezone_offset, #today_in_project_timezone, #update_status_history_file, #warn_about_failed_pr_download

Constructor Details

This class inherits a constructor from Downloader

Instance Method Details

#add_linked_issue_keys(issue, keys) ⇒ Object

Add the keys of issues linked to this one, skipping clone links (a clone isn't a dependency).



392
393
394
395
396
397
398
399
# File 'lib/jirametrics/downloader_for_cloud.rb', line 392

def add_linked_issue_keys issue, keys
  issue.raw['fields']['issuelinks']&.each do |link|
    next if link['type']['name'] == 'Cloners'

    linked = link['inwardIssue'] || link['outwardIssue']
    keys << linked['key'] if linked
  end
end

#attach_changelog_to_issues(issue_datas:, issue_jsons:) ⇒ Object



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
# File 'lib/jirametrics/downloader_for_cloud.rb', line 180

def attach_changelog_to_issues issue_datas:, issue_jsons:
  max_results = 10_000 # The max jira accepts is 10K
  payload = {
    'issueIdsOrKeys' => issue_datas.collect(&:key),
    'maxResults' => max_results
  }
  loop do
    response = @jira_gateway.post_request(
      relative_url: '/rest/api/3/changelog/bulkfetch',
      payload: JSON.generate(payload)
    )

    response['issueChangeLogs'].each do |issue_change_log|
      issue_id = issue_change_log['issueId']
      json = issue_jsons.find { |json| json['id'] == issue_id }

      unless json['changelog']
        # If this is our first time in, there won't be a changelog section
        json['changelog'] = {
          'startAt' => 0,
          'maxResults' => max_results,
          'total' => 0,
          'histories' => []
        }
      end

      new_changes = issue_change_log['changeHistories']
      json['changelog']['total'] += new_changes.size
      json['changelog']['histories'] += new_changes
    end

    next_page_token = response['nextPageToken']
    payload['nextPageToken'] = next_page_token
    break if next_page_token.nil?
  end
end

#attach_worklogs_to_issues(issue_datas:, issue_jsons:, max_results: 100) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/jirametrics/downloader_for_cloud.rb', line 133

def attach_worklogs_to_issues issue_datas:, issue_jsons:, max_results: 100
  issue_jsons.each do |issue_json|
    worklog = issue_json['fields']['worklog']
    next unless worklog

    total = worklog['total'].to_i
    all_worklogs = worklog['worklogs'] || []
    next if all_worklogs.size >= total

    key = issue_json['key']
    fetch_remaining_worklogs key: key, all_worklogs: all_worklogs, max_results: max_results

    issue_json['fields']['worklog'] = {
      'startAt' => 0,
      'maxResults' => all_worklogs.size,
      'total' => all_worklogs.size,
      'worklogs' => all_worklogs
    }

    log "      Enhanced #{key} with #{all_worklogs.size} worklogs"
  end
end

#build_jql(board) ⇒ Object



238
239
240
241
242
# File 'lib/jirametrics/downloader_for_cloud.rb', line 238

def build_jql board
  jql = make_jql(filter_id: @board_id_to_filter_id[board.id])
  intercept_jql = @download_config.project_config.settings['intercept_jql']
  intercept_jql ? intercept_jql.call(jql) : jql
end

#bulk_fetch_issues(issue_datas:, board:, in_initial_query:) ⇒ Object



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
# File 'lib/jirametrics/downloader_for_cloud.rb', line 88

def bulk_fetch_issues issue_datas:, board:, in_initial_query:
  # We used to use the expand option to pull in the changelog directly. Unfortunately
  # that only returns the "recent" changes, not all of them. So now we get the issue
  # without changes and then make a second call for that changes. Then we insert it
  # into the raw issue as if it had been there all along.
  log "  Downloading #{issue_datas.size} issues"
  payload = {
    'fields' => ['*all'],
    'issueIdsOrKeys' => issue_datas.collect(&:key)
  }
  response = @jira_gateway.post_request(
    relative_url: '/rest/api/3/issue/bulkfetch',
    payload: JSON.generate(payload)
  )

  attach_changelog_to_issues issue_datas: issue_datas, issue_jsons: response['issues']
  attach_worklogs_to_issues issue_datas: issue_datas, issue_jsons: response['issues']

  response['issues'].each do |issue_json|
    issue_json['exporter'] = {
      'in_initial_query' => in_initial_query
    }
    issue = Issue.new(raw: issue_json, board: board)
    data = issue_datas.find { |d| d.key == issue.key }
    unless data
      log "  Skipping #{issue.key}: returned by Jira but key not in request (issue may have been moved)"
      next
    end
    data.up_to_date = true
    data.last_modified = issue.updated
    data.issue = issue
  end

  # Mark any unmatched requests as up_to_date to prevent infinite re-fetching.
  # This happens when Jira returns a different key (moved issue) leaving the original unmatched.
  issue_datas.each do |data|
    next if data.up_to_date

    log "  Skipping #{data.key}: not returned by Jira (issue may have been deleted or moved)"
    data.up_to_date = true
  end

  issue_datas
end

Follow links one hop out from primary issues; for related (non-primary) issues, log the onward links we are deliberately not following rather than recursing into them.



366
367
368
369
370
371
372
# File 'lib/jirametrics/downloader_for_cloud.rb', line 366

def collect_or_log_related issue:, found_in_primary_query:, related_issue_keys:, issue_data_hash:
  if found_in_primary_query
    collect_related_issue_keys issue: issue, related_issue_keys: related_issue_keys
  else
    log_unfollowed_related_keys issue: issue, issue_data_hash: issue_data_hash
  end
end


374
375
376
# File 'lib/jirametrics/downloader_for_cloud.rb', line 374

def collect_related_issue_keys issue:, related_issue_keys:
  related_issue_keys.merge related_keys_for(issue)
end

#delete_issues_from_cache_that_are_not_in_server(issue_data_hash:, path:) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/jirametrics/downloader_for_cloud.rb', line 328

def delete_issues_from_cache_that_are_not_in_server issue_data_hash:, path:
  # The gotcha with deleted issues is that they just stop being returned in queries
  # and we have no way to know that they should be removed from our local cache.
  # With the new approach, we ask for every issue that Jira knows about (within
  # the parameters of the query) and then delete anything that's in our local cache
  # but wasn't returned.
  @file_system.foreach path do |file|
    next if file.start_with? '.'
    unless /^(?<key>\w+-\d+)-\d+\.json$/ =~ file
      raise "Unexpected filename in #{path}: #{file}"
    end
    next if issue_data_hash[key] # Still in Jira

    file_to_delete = File.join(path, file)
    log "  Removing #{file_to_delete} from local cache"
    file_system.unlink file_to_delete
  end
end

#download_all_issues(board:, path:, issue_data_hash:) ⇒ Object

Downloads the primary issues, then repeatedly follows related issues (parents, subtasks, links) until no new ones turn up. in_related_phase is false for the first pass and true thereafter, which controls the once-only "Identifying related issues" announcement and the loop diagnostics.



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
# File 'lib/jirametrics/downloader_for_cloud.rb', line 247

def download_all_issues board:, path:, issue_data_hash:
  checked_for_related = Set.new
  in_related_phase = false

  loop do
    related_issue_keys = Set.new
    stale = issue_data_hash.values.reject(&:up_to_date)
    if in_related_phase
      @file_system.diagnostic "Download loop: #{issue_data_hash.size} total known, " \
                              "#{stale.size} stale, #{checked_for_related.size} link-scanned"
    end
    download_stale_issues(
      stale: stale, board: board, in_related_phase: in_related_phase,
      checked_for_related: checked_for_related, related_issue_keys: related_issue_keys,
      issue_data_hash: issue_data_hash
    )

    scan_cached_issues_for_related(
      issue_data_hash: issue_data_hash, board: board,
      checked_for_related: checked_for_related, related_issue_keys: related_issue_keys
    )
    register_related_issues(
      related_issue_keys: related_issue_keys, issue_data_hash: issue_data_hash, path: path, board: board
    )
    break if related_issue_keys.empty?
    next if in_related_phase

    in_related_phase = true
    log "  Identifying related issues (parents, subtasks, links) for board #{board.id}", both: true
    log_start '  Downloading more issues '
  end

  end_progress if in_related_phase
end

#download_board_configuration(board_id:) ⇒ Object



13
14
15
16
17
18
# File 'lib/jirametrics/downloader_for_cloud.rb', line 13

def download_board_configuration board_id:
  board = super
  location = board.raw['location']
  @project_key ||= location['key'] if location&.[]('type') == 'project'
  board
end

#download_fix_versionsObject



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
# File 'lib/jirametrics/downloader_for_cloud.rb', line 20

def download_fix_versions
  return unless @project_key

  log "  Downloading fix versions for project #{@project_key}", both: true
  max_results = 50
  start_at = 0
  all_versions = []

  loop do
    json = @jira_gateway.call_url(
      relative_url: "/rest/api/3/project/#{@project_key}/version?" \
        "startAt=#{start_at}&maxResults=#{max_results}"
    )

    values = json['values'] || []
    all_versions.concat(values)
    break if json['isLast'] || values.empty?

    start_at += values.size
  end

  @file_system.save_json(
    json: all_versions,
    filename: File.join(@target_path, "#{file_prefix}_fix_versions.json")
  )
end

#download_issues(board:) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
# File 'lib/jirametrics/downloader_for_cloud.rb', line 217

def download_issues board:
  log "  Downloading primary issues for board #{board.id} from #{jira_instance_type}", both: true
  path = ensure_issues_directory
  issue_data_hash = search_for_issues jql: build_jql(board), board_id: board.id, path: path

  download_all_issues board: board, path: path, issue_data_hash: issue_data_hash

  delete_issues_from_cache_that_are_not_in_server(
    issue_data_hash: issue_data_hash, path: path
  )
end

#download_stale_issues(stale:, board:, in_related_phase:, checked_for_related:, related_issue_keys:, issue_data_hash:) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/jirametrics/downloader_for_cloud.rb', line 282

def download_stale_issues stale:, board:, in_related_phase:, checked_for_related:, related_issue_keys:,
                          issue_data_hash:
  return if stale.empty?

  log_start '  Downloading more issues ' unless in_related_phase
  stale.each_slice(100) do |slice|
    slice = bulk_fetch_issues(issue_datas: slice, board: board, in_initial_query: !in_related_phase)
    progress_dot
    save_fetched_issues(
      slice: slice, checked_for_related: checked_for_related,
      related_issue_keys: related_issue_keys, issue_data_hash: issue_data_hash
    )
  end
  end_progress unless in_related_phase
end

#ensure_issues_directoryObject



229
230
231
232
233
234
235
236
# File 'lib/jirametrics/downloader_for_cloud.rb', line 229

def ensure_issues_directory
  path = File.join(@target_path, "#{file_prefix}_issues/")
  unless @file_system.dir_exist?(path)
    log "  Creating path #{path}"
    @file_system.mkdir(path)
  end
  path
end

#fetch_remaining_worklogs(key:, all_worklogs:, max_results:) ⇒ Object

Page through the worklogs Jira didn't include inline, appending each page to all_worklogs.



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/jirametrics/downloader_for_cloud.rb', line 157

def fetch_remaining_worklogs key:, all_worklogs:, max_results:
  start_at = all_worklogs.size
  loop do
    response = @jira_gateway.call_url(
      relative_url: "/rest/api/3/issue/#{CGI.escape(key)}/worklog?startAt=#{start_at}&maxResults=#{max_results}"
    )

    worklogs = response['worklogs'] || []
    all_worklogs.concat(worklogs)

    total = response['total'].to_i
    log "        #{key} worklogs: page startAt=#{start_at}, " \
        "received=#{worklogs.size}, fetched=#{all_worklogs.size}/#{total}"
    break if all_worklogs.size >= total
    # Guard against Jira reporting a higher total than it will actually return - seen when
    # worklogs are deleted or access-restricted after the initial fetch. Without this,
    # start_at never advances and we loop forever requesting the same empty page.
    break if worklogs.empty?

    start_at += worklogs.size
  end
end

#jira_instance_typeObject



4
5
6
# File 'lib/jirametrics/downloader_for_cloud.rb', line 4

def jira_instance_type
  'Jira Cloud'
end

#last_modified(filename:) ⇒ Object



413
414
415
# File 'lib/jirametrics/downloader_for_cloud.rb', line 413

def last_modified filename:
  File.mtime(filename) if File.exist?(filename)
end

We only follow links one hop out from the primary (board) issues. If a related issue itself references further issues we haven't already downloaded, we deliberately don't follow them - but log it so we can diagnose later if an export fails because a second-hop issue was missing. See GitHub #72.



405
406
407
408
409
410
411
# File 'lib/jirametrics/downloader_for_cloud.rb', line 405

def log_unfollowed_related_keys issue:, issue_data_hash:
  onward = related_keys_for(issue).reject { |key| issue_data_hash[key] }
  return if onward.empty?

  @file_system.diagnostic "One-hop limit: not following #{onward.size} onward link(s) from related " \
                          "issue #{issue.key}: #{onward.to_a.sort.join(', ')}"
end


315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/jirametrics/downloader_for_cloud.rb', line 315

def register_related_issues related_issue_keys:, issue_data_hash:, path:, board:
  # Remove all the ones we already have
  related_issue_keys.reject! { |key| issue_data_hash[key] }

  related_issue_keys.each do |key|
    data = DownloadIssueData.new key: key
    data.found_in_primary_query = false
    data.up_to_date = false
    data.cache_path = File.join(path, "#{key}-#{board.id}.json")
    issue_data_hash[key] = data
  end
end

The parents, subtasks, and (non-cloner) linked issues that this issue references.



379
380
381
382
383
384
385
386
387
388
389
# File 'lib/jirametrics/downloader_for_cloud.rb', line 379

def related_keys_for issue
  keys = Set.new

  parent_key = issue.parent_key(project_config: @download_config.project_config)
  keys << parent_key if parent_key

  issue.raw['fields']['subtasks']&.each { |raw_subtask| keys << raw_subtask['key'] }
  add_linked_issue_keys issue, keys

  keys
end

#runObject



8
9
10
11
# File 'lib/jirametrics/downloader_for_cloud.rb', line 8

def run
  super
  download_fix_versions
end

#save_fetched_issues(slice:, checked_for_related:, related_issue_keys:, issue_data_hash:) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/jirametrics/downloader_for_cloud.rb', line 298

def save_fetched_issues slice:, checked_for_related:, related_issue_keys:, issue_data_hash:
  slice.each do |data|
    next unless data.issue

    @file_system.save_json(json: data.issue.raw, filename: data.cache_path)
    # Set the timestamp on the file to match the updated one so that we don't have
    # to parse the file just to find the timestamp
    @file_system.utime time: data.issue.updated, file: data.cache_path

    collect_or_log_related(
      issue: data.issue, found_in_primary_query: data.found_in_primary_query,
      related_issue_keys: related_issue_keys, issue_data_hash: issue_data_hash
    )
    checked_for_related << data.key
  end
end

Scan up-to-date cached primary issues we haven't checked yet - they may reference related issues that are not in the primary query result. We only follow links one hop out from the primary issues, so related (non-primary) cached issues are not followed (just logged).



350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/jirametrics/downloader_for_cloud.rb', line 350

def scan_cached_issues_for_related issue_data_hash:, board:, checked_for_related:, related_issue_keys:
  issue_data_hash.each_value do |data|
    next if checked_for_related.include?(data.key)
    next unless @file_system.file_exist?(data.cache_path)

    checked_for_related << data.key
    issue = Issue.new(raw: @file_system.load_json(data.cache_path), board: board)
    collect_or_log_related(
      issue: issue, found_in_primary_query: data.found_in_primary_query,
      related_issue_keys: related_issue_keys, issue_data_hash: issue_data_hash
    )
  end
end

#search_for_issues(jql:, board_id:, path:) ⇒ Object



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
# File 'lib/jirametrics/downloader_for_cloud.rb', line 47

def search_for_issues jql:, board_id:, path:
  log "  JQL: #{jql}"
  escaped_jql = CGI.escape jql

  hash = {}
  max_results = 5_000 # The maximum allowed by Jira
  next_page_token = nil
  issue_count = 0

  start_progress
  loop do
    relative_url = +''
    relative_url << '/rest/api/3/search/jql'
    relative_url << "?jql=#{escaped_jql}&maxResults=#{max_results}"
    relative_url << "&nextPageToken=#{next_page_token}" if next_page_token
    relative_url << '&fields=updated'

    json = @jira_gateway.call_url relative_url: relative_url
    next_page_token = json['nextPageToken']

    json['issues'].each do |i|
      key = i['key']
      data = DownloadIssueData.new key: key
      data.key = key
      data.last_modified = Time.parse i['fields']['updated']
      data.found_in_primary_query = true
      data.cache_path = File.join(path, "#{key}-#{board_id}.json")
      data.up_to_date = last_modified(filename: data.cache_path) == data.last_modified
      hash[key] = data
      issue_count += 1
    end

    progress_dot "    Found #{issue_count} issues"

    break unless next_page_token
  end
  end_progress

  hash
end