entity_cache.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # frozen_string_literal: true
  2. require 'singleton'
  3. class EntityCache
  4. include Singleton
  5. MAX_EXPIRATION = 7.days.freeze
  6. def status(url)
  7. Rails.cache.fetch(to_key(:status, url), expires_in: MAX_EXPIRATION) { FetchRemoteStatusService.new.call(url) }
  8. end
  9. def mention(username, domain)
  10. Rails.cache.fetch(to_key(:mention, username, domain), expires_in: MAX_EXPIRATION) { Account.select(:id, :username, :domain, :url).find_remote(username, domain) }
  11. end
  12. def emoji(shortcodes, domain)
  13. shortcodes = Array(shortcodes)
  14. return [] if shortcodes.empty?
  15. cached = Rails.cache.read_multi(*shortcodes.map { |shortcode| to_key(:emoji, shortcode, domain) })
  16. uncached_ids = []
  17. shortcodes.each do |shortcode|
  18. uncached_ids << shortcode unless cached.key?(to_key(:emoji, shortcode, domain))
  19. end
  20. unless uncached_ids.empty?
  21. uncached = CustomEmoji.enabled.where(shortcode: shortcodes, domain: domain).index_by(&:shortcode)
  22. uncached.each_value { |item| Rails.cache.write(to_key(:emoji, item.shortcode, domain), item, expires_in: MAX_EXPIRATION) }
  23. end
  24. shortcodes.filter_map { |shortcode| cached[to_key(:emoji, shortcode, domain)] || uncached[shortcode] }
  25. end
  26. def to_key(type, *ids)
  27. "#{type}:#{ids.compact.map(&:downcase).join(':')}"
  28. end
  29. end