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