class Stockpile::Executor

Stockpile::Executor

Executes passed in block of code and writes computed result into cache with an expiration of a given TTL. If execution is locked will wait for value to appear in cache instead. Will timeout after given amount of time and will execute block if no value can be read from cache.

Attributes

db[R]
key[R]
ttl[R]

Public Class Methods

new(db, key, ttl) click to toggle source
# File lib/stockpile/executor.rb, line 31
def initialize(db, key, ttl)
  @db = db
  @key = key
  @ttl = ttl
end
perform(db: :default, key:, ttl:, &block) click to toggle source
# File lib/stockpile/executor.rb, line 27
def self.perform(db: :default, key:, ttl:, &block)
  new(db, key, ttl).perform(&block)
end

Public Instance Methods

perform(&block) click to toggle source
# File lib/stockpile/executor.rb, line 37
def perform(&block)
  if execution(&block).success?
    cache_and_release_execution
  else
    wait_for_cache_or_yield(&block)
  end
end

Private Instance Methods

cache_and_release_execution() click to toggle source
# File lib/stockpile/executor.rb, line 57
def cache_and_release_execution
  Stockpile::Cache.set(
    db: db,
    key: key,
    payload: execution.result,
    ttl: ttl,
    compress: compress?
  )

  execution.release_lock
  execution.result
end
compress?() click to toggle source
# File lib/stockpile/executor.rb, line 47
def compress?
  RedisConnections.compression?(db: db)
end
execution() { || ... } click to toggle source
# File lib/stockpile/executor.rb, line 51
def execution
  @execution ||= Stockpile::Lock.perform_locked(db: db, lock_key: lock_key) do
    yield
  end
end
lock_key() click to toggle source
# File lib/stockpile/executor.rb, line 70
def lock_key
  Stockpile::LOCK_PREFIX + key
end
wait_for_cache_or_yield() { || ... } click to toggle source
# File lib/stockpile/executor.rb, line 74
def wait_for_cache_or_yield
  Timeout.timeout(Stockpile.configuration.slumber) do
    Stockpile::Cache.get_deferred(db: db, key: key, compress: compress?)
  end
rescue Timeout::Error
  yield
end