2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-02-19 00:58:05 -05:00
|
|
|
# Discourse specific cache, enforces 1 day expiry
|
2013-05-13 04:04:03 -04:00
|
|
|
|
2014-01-06 00:50:04 -05:00
|
|
|
class Cache < ActiveSupport::Cache::Store
|
|
|
|
|
2015-02-19 00:58:05 -05:00
|
|
|
# nothing is cached for longer than 1 day EVER
|
|
|
|
# there is no reason to have data older than this clogging redis
|
|
|
|
# it is dangerous cause if we rename keys we will be stuck with
|
|
|
|
# pointless data
|
|
|
|
MAX_CACHE_AGE = 1.day unless defined? MAX_CACHE_AGE
|
|
|
|
|
2014-01-06 00:50:04 -05:00
|
|
|
def initialize(opts = {})
|
2015-02-19 00:58:05 -05:00
|
|
|
@namespace = opts[:namespace] || "_CACHE_"
|
2014-01-06 00:50:04 -05:00
|
|
|
super(opts)
|
2013-05-13 04:04:03 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def redis
|
2014-01-06 00:50:04 -05:00
|
|
|
$redis
|
|
|
|
end
|
|
|
|
|
|
|
|
def reconnect
|
|
|
|
redis.reconnect
|
|
|
|
end
|
|
|
|
|
2018-05-03 09:41:41 -04:00
|
|
|
def keys(pattern = "*")
|
2018-12-14 19:53:52 -05:00
|
|
|
redis.scan_each(match: "#{@namespace}:#{pattern}").to_a
|
2018-05-03 09:41:41 -04:00
|
|
|
end
|
|
|
|
|
2014-01-06 00:50:04 -05:00
|
|
|
def clear
|
2018-05-03 09:41:41 -04:00
|
|
|
keys.each do |k|
|
2015-02-19 00:58:05 -05:00
|
|
|
redis.del(k)
|
2013-05-13 04:04:03 -04:00
|
|
|
end
|
2014-01-06 00:50:04 -05:00
|
|
|
end
|
2013-05-13 04:04:03 -04:00
|
|
|
|
2017-08-31 00:06:56 -04:00
|
|
|
def normalize_key(key, opts = nil)
|
2019-05-02 18:17:27 -04:00
|
|
|
"#{@namespace}:#{key}"
|
2013-05-13 04:04:03 -04:00
|
|
|
end
|
|
|
|
|
2014-01-06 00:50:04 -05:00
|
|
|
protected
|
|
|
|
|
|
|
|
def read_entry(key, options)
|
|
|
|
if data = redis.get(key)
|
2014-01-07 01:36:47 -05:00
|
|
|
data = Marshal.load(data)
|
2014-01-06 00:50:04 -05:00
|
|
|
ActiveSupport::Cache::Entry.new data
|
|
|
|
end
|
2014-01-07 01:36:47 -05:00
|
|
|
rescue
|
|
|
|
# corrupt cache, fail silently for now, remove rescue later
|
2013-05-13 04:04:03 -04:00
|
|
|
end
|
|
|
|
|
2014-01-06 00:50:04 -05:00
|
|
|
def write_entry(key, entry, options)
|
2014-01-07 01:36:47 -05:00
|
|
|
dumped = Marshal.dump(entry.value)
|
2015-02-19 00:58:05 -05:00
|
|
|
expiry = options[:expires_in] || MAX_CACHE_AGE
|
|
|
|
redis.setex(key, expiry, dumped)
|
2014-01-06 00:50:04 -05:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_entry(key, options)
|
|
|
|
redis.del key
|
2013-05-13 04:04:03 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|