class Faulty::Cache::FaultTolerantProxy

A wrapper for cache backends that may raise errors

{Faulty#initialize} automatically wraps all non-fault-tolerant cache backends with this class.

If the cache backend raises a `StandardError`, it will be captured and sent to the notifier. Reads errors will return `nil`, and writes will be a no-op.

Constants

Options

Options for {FaultTolerantProxy}

@!attribute [r] notifier

@return [Events::Notifier] A Faulty notifier

Attributes

options[R]

Public Class Methods

new(cache, **options, &block) click to toggle source

@param cache [Cache::Interface] The cache backend to wrap @param options [Hash] Attributes for {Options} @yield [Options] For setting options in a block

# File lib/faulty/cache/fault_tolerant_proxy.rb, line 35
def initialize(cache, **options, &block)
  @cache = cache
  @options = Options.new(options, &block)
end
wrap(cache, **options, &block) click to toggle source

Wrap a cache in a FaultTolerantProxy unless it's already fault tolerant

@param cache [Cache::Interface] The cache to maybe wrap @return [Cache::Interface] The original cache or a {FaultTolerantProxy}

# File lib/faulty/cache/fault_tolerant_proxy.rb, line 44
def self.wrap(cache, **options, &block)
  return cache if cache.fault_tolerant?

  new(cache, **options, &block)
end

Public Instance Methods

fault_tolerant?() click to toggle source

This cache makes any cache fault tolerant, so this is always `true`

@return [true]

# File lib/faulty/cache/fault_tolerant_proxy.rb, line 80
def fault_tolerant?
  true
end
read(key) click to toggle source

Read from the cache safely

If the backend raises a `StandardError`, this will return `nil`.

@param (see Cache::Interface#read) @return [Object, nil] The value if found, or nil if not found or if an

error was raised.
# File lib/faulty/cache/fault_tolerant_proxy.rb, line 57
def read(key)
  @cache.read(key)
rescue StandardError => e
  options.notifier.notify(:cache_failure, key: key, action: :read, error: e)
  nil
end
write(key, value, expires_in: nil) click to toggle source

Write to the cache safely

If the backend raises a `StandardError`, the write will be ignored

@param (see Cache::Interface#write) @return [void]

# File lib/faulty/cache/fault_tolerant_proxy.rb, line 70
def write(key, value, expires_in: nil)
  @cache.write(key, value, expires_in: expires_in)
rescue StandardError => e
  options.notifier.notify(:cache_failure, key: key, action: :write, error: e)
  nil
end