2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-07-28 22:25:19 -04:00
|
|
|
class DistributedMemoizer
|
|
|
|
# never wait for longer that 1 second for a cross process lock
|
2022-04-05 13:29:58 -04:00
|
|
|
MAX_WAIT = 1
|
2013-07-28 22:25:19 -04:00
|
|
|
|
|
|
|
# memoize a key across processes and machines
|
2022-04-05 13:29:58 -04:00
|
|
|
def self.memoize(key, duration = 60 * 60 * 24, redis = Discourse.redis)
|
|
|
|
redis_lock_key = self.redis_lock_key(key)
|
2013-07-28 22:25:19 -04:00
|
|
|
redis_key = self.redis_key(key)
|
|
|
|
|
2022-04-05 13:29:58 -04:00
|
|
|
DistributedMutex.synchronize(redis_lock_key, redis: redis, validity: MAX_WAIT) do
|
|
|
|
result = redis.get(redis_key)
|
2013-11-25 18:21:41 -05:00
|
|
|
|
2022-04-05 13:29:58 -04:00
|
|
|
unless result
|
|
|
|
result = yield
|
|
|
|
redis.setex(redis_key, duration, result)
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
2022-04-05 13:29:58 -04:00
|
|
|
result
|
|
|
|
end
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis_lock_key(key)
|
2022-04-05 13:29:58 -04:00
|
|
|
"memoize_lock_#{key}"
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis_key(key)
|
2022-04-05 13:29:58 -04:00
|
|
|
"memoize_#{key}"
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
end
|