project_cache_worker.rb 1.4 KB
Newer Older
1 2
# frozen_string_literal: true

3
# Worker for updating any project specific caches.
4
class ProjectCacheWorker
5
  include ApplicationWorker
6

7 8
  LEASE_TIMEOUT = 15.minutes.to_i

9
  # project_id - The ID of the project for which to flush the cache.
Markus Koller's avatar
Markus Koller committed
10 11 12 13 14
  # files - An Array containing extra types of files to refresh such as
  #         `:readme` to flush the README and `:changelog` to flush the
  #         CHANGELOG.
  # statistics - An Array containing columns from ProjectStatistics to
  #              refresh, if empty all columns will be refreshed
15
  # rubocop: disable CodeReuse/ActiveRecord
Markus Koller's avatar
Markus Koller committed
16
  def perform(project_id, files = [], statistics = [])
17
    project = Project.find_by(id: project_id)
18

19
    return unless project && project.repository.exists?
20

21
    update_statistics(project, statistics.map(&:to_sym))
22

23 24 25
    project.repository.refresh_method_caches(files.map(&:to_sym))

    project.cleanup
26
  end
27
  # rubocop: enable CodeReuse/ActiveRecord
28

29
  def update_statistics(project, statistics = [])
30
    return if Gitlab::Database.read_only?
31
    return unless try_obtain_lease_for(project.id, :update_statistics)
32

33
    Rails.logger.info("Updating statistics for project #{project.id}")
34

35
    project.statistics.refresh!(only: statistics)
36
  end
37

38 39 40 41 42 43
  private

  def try_obtain_lease_for(project_id, section)
    Gitlab::ExclusiveLease
      .new("project_cache_worker:#{project_id}:#{section}", timeout: LEASE_TIMEOUT)
      .try_obtain
44
  end
45
end