diff options
author | Yorick Peterse <yorickpeterse@gmail.com> | 2017-08-18 15:52:11 +0300 |
---|---|---|
committer | Yorick Peterse <yorickpeterse@gmail.com> | 2017-08-21 18:58:37 +0300 |
commit | e0b589f16166a88d18e58fbc154e0cf165732acb (patch) | |
tree | 4e329dd6f9ebe75a13d5a2985962042b9390b514 /app/models/broadcast_message.rb | |
parent | 646aae3e4f0f9c547397fdf55cc2205b0171b565 (diff) |
Fix caching of future broadcast messages
This changes the caching mechanism so we cache both current _and_ future
broadcast messages, then manually filter out those we don't want to
display. This ensures we don't need any additional queries while still
being able to display the right messages at the right time.
Fixes https://gitlab.com/gitlab-org/gitlab-ce/issues/36661
Diffstat (limited to 'app/models/broadcast_message.rb')
-rw-r--r-- | app/models/broadcast_message.rb | 32 |
1 files changed, 27 insertions, 5 deletions
diff --git a/app/models/broadcast_message.rb b/app/models/broadcast_message.rb index 3692bcc680d..fdc5a2adea0 100644 --- a/app/models/broadcast_message.rb +++ b/app/models/broadcast_message.rb @@ -19,11 +19,21 @@ class BroadcastMessage < ActiveRecord::Base after_commit :flush_redis_cache def self.current - Rails.cache.fetch(CACHE_KEY) do - where('ends_at > :now AND starts_at <= :now', now: Time.zone.now) - .reorder(id: :asc) - .to_a - end + messages = Rails.cache.fetch(CACHE_KEY) { current_and_future_messages.to_a } + + return messages if messages.empty? + + now_or_future = messages.select(&:now_or_future?) + + # If there are cached entries but none are to be displayed we'll purge the + # cache so we don't keep running this code all the time. + Rails.cache.delete(CACHE_KEY) if now_or_future.empty? + + now_or_future.select(&:now?) + end + + def self.current_and_future_messages + where('ends_at > :now', now: Time.zone.now).reorder(id: :asc) end def active? @@ -38,6 +48,18 @@ class BroadcastMessage < ActiveRecord::Base ends_at < Time.zone.now end + def now? + (starts_at..ends_at).cover?(Time.zone.now) + end + + def future? + starts_at > Time.zone.now + end + + def now_or_future? + now? || future? + end + def flush_redis_cache Rails.cache.delete(CACHE_KEY) end |