2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
# Base class for services that count a single resource such as the number of
|
|
|
|
# issues for a project.
|
|
|
|
class BaseCountService
|
|
|
|
def relation_for_count
|
|
|
|
raise(
|
|
|
|
NotImplementedError,
|
|
|
|
'"relation_for_count" must be implemented and return an ActiveRecord::Relation'
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def count
|
|
|
|
Rails.cache.fetch(cache_key, cache_options) { uncached_count }.to_i
|
|
|
|
end
|
|
|
|
|
|
|
|
def count_stored?
|
|
|
|
Rails.cache.read(cache_key).present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def refresh_cache(&block)
|
2018-11-08 19:23:39 +05:30
|
|
|
update_cache_for_key(cache_key, &block)
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def uncached_count
|
|
|
|
relation_for_count.count
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_cache
|
2021-09-04 01:27:46 +05:30
|
|
|
::Gitlab::Cache.delete(cache_key)
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def raw?
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def cache_key
|
2019-12-04 20:38:33 +05:30
|
|
|
raise NotImplementedError, 'cache_key must be implemented and return a String, Array, or Hash'
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
# subclasses can override to add any specific options, such as
|
|
|
|
# super.merge({ expires_in: 5.minutes })
|
|
|
|
def cache_options
|
|
|
|
{ raw: raw? }
|
|
|
|
end
|
2018-11-08 19:23:39 +05:30
|
|
|
|
|
|
|
def update_cache_for_key(key, &block)
|
2022-08-27 11:52:29 +05:30
|
|
|
Rails.cache.write(key, block ? yield : uncached_count, raw: raw?)
|
2018-11-08 19:23:39 +05:30
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
2019-12-04 20:38:33 +05:30
|
|
|
|
2021-09-04 01:27:46 +05:30
|
|
|
BaseCountService.prepend_mod
|