entity_cache.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 = [shortcodes] unless shortcodes.is_a?(Array)
  14. cached = Rails.cache.read_multi(*shortcodes.map { |shortcode| to_key(:emoji, shortcode, domain) })
  15. uncached_ids = []
  16. shortcodes.each do |shortcode|
  17. uncached_ids << shortcode unless cached.key?(to_key(:emoji, shortcode, domain))
  18. end
  19. unless uncached_ids.empty?
  20. uncached = CustomEmoji.where(shortcode: shortcodes, domain: domain, disabled: false).each_with_object({}) { |item, h| h[item.shortcode] = item }
  21. uncached.each_value { |item| Rails.cache.write(to_key(:emoji, item.shortcode, domain), item, expires_in: MAX_EXPIRATION) }
  22. end
  23. shortcodes.map { |shortcode| cached[to_key(:emoji, shortcode, domain)] || uncached[shortcode] }.compact
  24. end
  25. def to_key(type, *ids)
  26. "#{type}:#{ids.compact.map(&:downcase).join(':')}"
  27. end
  28. end