Sha256: 9ab0f4f09abfeb7fb33ed8c685734fb597a69cc483a437f45ba4e243d1111009

Contents?: true

Size: 1.84 KB

Versions: 2

Compression:

Stored size: 1.84 KB

Contents

require 'alephant/logger'
require 'time'

module Alephant
  module Broker
    module Cache
      class CachedObject
        include Logger
        attr_reader :s3_obj

        DEFAULT_TTL = 10

        def initialize(obj)
          logger.debug(event:  'SettingCachedObject',
                      content: obj,
                      method:  "#{self.class}#initialize")

          @s3_obj = obj
        end

        def update(obj)
          logger.debug(event:      'UpdatingCachedObject',
                      old_content: @s3_obj,
                      new_content: obj,
                      method:      "#{self.class}#update")

          @s3_obj = obj
        end

        def updated
          time = metadata[:'head_Last-Modified']
          Time.parse(time)
        rescue TypeError, ArgumentError => error
          logger.error(event: 'CachedObjectLastModifiedError', method: "#{self.class}#updated", error: error)
          Time.now
        end

        def ttl
          Integer(metadata[:ttl] || metadata['ttl'])
        rescue TypeError => error
          logger.error(event: 'NonIntegerTTLError', method: "#{self.class}#ttl", error: error)
          Integer(Broker.config[:revalidate_cache_ttl] || DEFAULT_TTL)
        end

        def expired?
          result = (updated + ttl) < Time.now

          logger.info(event:            'Expired?',
                      updated:          updated,
                      ttl:              ttl,
                      updated_plus_ttl: (updated + ttl),
                      now:              Time.now,
                      result:           result,
                      method:           "#{self.class}#expired?")

          result
        end

        def to_h(obj = nil)
          obj || s3_obj
        end

        private

        def metadata
          s3_obj.fetch(:meta, {})
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
alephant-broker-3.19.1 lib/alephant/broker/cache/cached_object.rb
alephant-broker-3.19.0 lib/alephant/broker/cache/cached_object.rb