Class: Faulty::Cache::FaultTolerantProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/faulty/cache/fault_tolerant_proxy.rb

Overview

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.

Defined Under Namespace

Classes: Options

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache, **options) {|Options| ... } ⇒ FaultTolerantProxy

Returns a new instance of FaultTolerantProxy.

Parameters:

Yields:

  • (Options)

    For setting options in a block



33
34
35
36
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 33

def initialize(cache, **options, &block)
  @cache = cache
  @options = Options.new(options, &block)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



14
15
16
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 14

def options
  @options
end

Class Method Details

.wrap(cache, **options, &block) ⇒ Cache::Interface

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

Parameters:

Returns:



42
43
44
45
46
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 42

def self.wrap(cache, **options, &block)
  return cache if cache.fault_tolerant?

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

Instance Method Details

#fault_tolerant?true

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

Returns:

  • (true)


78
79
80
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 78

def fault_tolerant?
  true
end

#read(key) ⇒ Object?

Read from the cache safely

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

Parameters:

  • key (String)

    The cache key

Returns:

  • (Object, nil)

    The value if found, or nil if not found or if an error was raised.



55
56
57
58
59
60
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 55

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) ⇒ void

This method returns an undefined value.

Write to the cache safely

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

Parameters:

  • key (String)

    The cache key

  • expires_in (Integer, nil) (defaults to: nil)

    The number of seconds until this cache entry expires. If nil, no expiration is set.

  • value (Object)

    The value to write to the cache



68
69
70
71
72
73
# File 'lib/faulty/cache/fault_tolerant_proxy.rb', line 68

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