You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.3 KiB

  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. 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).index_by(&:shortcode)
  21. uncached.each_value { |item| Rails.cache.write(to_key(:emoji, item.shortcode, domain), item, expires_in: MAX_EXPIRATION) }
  22. end
  23. shortcodes.filter_map { |shortcode| cached[to_key(:emoji, shortcode, domain)] || uncached[shortcode] }
  24. end
  25. def to_key(type, *ids)
  26. "#{type}:#{ids.compact.map(&:downcase).join(':')}"
  27. end
  28. end