broadcast_message.rb 2.08 KB
Newer Older
1 2
# frozen_string_literal: true

3
class BroadcastMessage < ActiveRecord::Base
4
  include CacheMarkdownField
5 6
  include Sortable

7
  cache_markdown_field :message, pipeline: :broadcast_message, whitelisted: true
8

Robert Speicher's avatar
Robert Speicher committed
9
  validates :message,   presence: true
10
  validates :starts_at, presence: true
Robert Speicher's avatar
Robert Speicher committed
11
  validates :ends_at,   presence: true
12

Robert Speicher's avatar
Robert Speicher committed
13 14
  validates :color, allow_blank: true, color: true
  validates :font,  allow_blank: true, color: true
15

16 17 18
  default_value_for :color, '#E75E40'
  default_value_for :font,  '#FFFFFF'

19 20
  CACHE_KEY = 'broadcast_message_current_json'.freeze
  LEGACY_CACHE_KEY = 'broadcast_message_current'.freeze
21 22 23

  after_commit :flush_redis_cache

24
  def self.current
25
    messages = cache.fetch(CACHE_KEY, as: BroadcastMessage, expires_in: cache_expires_in) do
26
      remove_legacy_cache_key
27
      current_and_future_messages
28
    end
29

30
    return [] unless messages&.present?
31 32 33 34 35

    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.
36
    cache.expire(CACHE_KEY) if now_or_future.empty?
37 38 39 40 41

    now_or_future.select(&:now?)
  end

  def self.current_and_future_messages
42
    where('ends_at > :now', now: Time.zone.now).order_id_asc
43 44
  end

45 46 47 48
  def self.cache
    Gitlab::JsonCache.new(cache_key_with_version: false)
  end

49 50 51 52
  def self.cache_expires_in
    nil
  end

53 54 55 56 57
  # This can be removed in GitLab 12.0+
  # The old cache key had an indefinite lifetime, and in an HA
  # environment a one-shot migration would not work because the cache
  # would be repopulated by a node that has not been upgraded.
  def self.remove_legacy_cache_key
58
    cache.expire(LEGACY_CACHE_KEY)
59 60
  end

61 62 63 64 65 66 67 68 69 70 71
  def active?
    started? && !ended?
  end

  def started?
    Time.zone.now >= starts_at
  end

  def ended?
    ends_at < Time.zone.now
  end
72

73 74 75 76 77 78 79 80 81 82 83 84
  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

85
  def flush_redis_cache
86
    self.class.cache.expire(CACHE_KEY)
87
    self.class.remove_legacy_cache_key
88
  end
89
end