2015-02-18 23:58:05 -06:00
|
|
|
# Discourse specific cache, enforces 1 day expiry
|
2013-05-13 03:04:03 -05:00
|
|
|
|
2014-01-05 23:50:04 -06:00
|
|
|
class Cache < ActiveSupport::Cache::Store
|
|
|
|
|
2015-02-18 23:58:05 -06: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-05 23:50:04 -06:00
|
|
|
def initialize(opts = {})
|
2015-02-18 23:58:05 -06:00
|
|
|
@namespace = opts[:namespace] || "_CACHE_"
|
2014-01-05 23:50:04 -06:00
|
|
|
super(opts)
|
2013-05-13 03:04:03 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def redis
|
2014-01-05 23:50:04 -06:00
|
|
|
$redis
|
|
|
|
end
|
|
|
|
|
|
|
|
def reconnect
|
|
|
|
redis.reconnect
|
|
|
|
end
|
|
|
|
|
2018-05-03 08:41:41 -05:00
|
|
|
def keys(pattern = "*")
|
2018-12-14 18:53:52 -06:00
|
|
|
redis.scan_each(match: "#{@namespace}:#{pattern}").to_a
|
2018-05-03 08:41:41 -05:00
|
|
|
end
|
|
|
|
|
2014-01-05 23:50:04 -06:00
|
|
|
def clear
|
2018-05-03 08:41:41 -05:00
|
|
|
keys.each do |k|
|
2015-02-18 23:58:05 -06:00
|
|
|
redis.del(k)
|
2013-05-13 03:04:03 -05:00
|
|
|
end
|
2014-01-05 23:50:04 -06:00
|
|
|
end
|
2013-05-13 03:04:03 -05:00
|
|
|
|
2017-08-30 23:06:56 -05:00
|
|
|
def normalize_key(key, opts = nil)
|
2015-02-18 23:58:05 -06:00
|
|
|
"#{@namespace}:" << key
|
2013-05-13 03:04:03 -05:00
|
|
|
end
|
|
|
|
|
2014-01-05 23:50:04 -06:00
|
|
|
protected
|
|
|
|
|
|
|
|
def read_entry(key, options)
|
|
|
|
if data = redis.get(key)
|
2014-01-07 00:36:47 -06:00
|
|
|
data = Marshal.load(data)
|
2014-01-05 23:50:04 -06:00
|
|
|
ActiveSupport::Cache::Entry.new data
|
|
|
|
end
|
2014-01-07 00:36:47 -06:00
|
|
|
rescue
|
|
|
|
# corrupt cache, fail silently for now, remove rescue later
|
2013-05-13 03:04:03 -05:00
|
|
|
end
|
|
|
|
|
2014-01-05 23:50:04 -06:00
|
|
|
def write_entry(key, entry, options)
|
2014-01-07 00:36:47 -06:00
|
|
|
dumped = Marshal.dump(entry.value)
|
2015-02-18 23:58:05 -06:00
|
|
|
expiry = options[:expires_in] || MAX_CACHE_AGE
|
|
|
|
redis.setex(key, expiry, dumped)
|
2014-01-05 23:50:04 -06:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_entry(key, options)
|
|
|
|
redis.del key
|
2013-05-13 03:04:03 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|