Class: Dalli::Protocol::TtlSanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/dalli/protocol/ttl_sanitizer.rb

Overview

Utility class for sanitizing TTL arguments based on Memcached rules. TTLs are either expirations times in seconds (with a maximum value of 30 days) or expiration timestamps. This class sanitizes TTLs to ensure they meet those restrictions.

Constant Summary collapse

MAX_ACCEPTABLE_EXPIRATION_INTERVAL =

github.com/memcached/memcached/blob/master/doc/protocol.txt#L79 > An expiration time, in seconds. Can be up to 30 days. After 30 days, is

treated as a unix timestamp of an exact date.
30 * 24 * 60 * 60

Class Method Summary collapse

Class Method Details

.as_timestamp(ttl_as_i) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/dalli/protocol/ttl_sanitizer.rb', line 29

def self.as_timestamp(ttl_as_i)
  now = current_timestamp
  return ttl_as_i if ttl_as_i > now # Already a timestamp

  Dalli.logger.debug "Expiration interval (#{ttl_as_i}) too long for Memcached " \
                     'and too short to be a future timestamp,' \
                     'converting to an expiration timestamp'
  now + ttl_as_i
end

.current_timestampObject

Pulled out into a method so it’s easy to stub time



40
41
42
# File 'lib/dalli/protocol/ttl_sanitizer.rb', line 40

def self.current_timestamp
  Time.now.to_i
end

.less_than_max_expiration_interval?(ttl_as_i) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/dalli/protocol/ttl_sanitizer.rb', line 25

def self.less_than_max_expiration_interval?(ttl_as_i)
  ttl_as_i <= MAX_ACCEPTABLE_EXPIRATION_INTERVAL
end

.sanitize(ttl) ⇒ Object

Ensures the TTL passed to Memcached is a valid TTL in the expected format.



18
19
20
21
22
23
# File 'lib/dalli/protocol/ttl_sanitizer.rb', line 18

def self.sanitize(ttl)
  ttl_as_i = ttl.to_i
  return ttl_as_i if less_than_max_expiration_interval?(ttl_as_i)

  as_timestamp(ttl_as_i)
end