Class: Dalli::Protocol::ValueSerializer

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

Overview

Dalli::Protocol::ValueSerializer compartmentalizes the logic for managing serialization and deserialization of stored values. It manages interpreting relevant options from both client and request, determining whether to serialize/deserialize on store/retrieve, and processes bitflags as necessary.

Constant Summary collapse

DEFAULTS =
{
  serializer: Marshal,
  string_fastpath: false
}.freeze
OPTIONS =
DEFAULTS.keys.freeze
@@marshal_warning_logged =

Class variable to track whether the Marshal warning has been logged

false

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(protocol_options) ⇒ ValueSerializer

Returns a new instance of ValueSerializer.



24
25
26
27
28
# File 'lib/dalli/protocol/value_serializer.rb', line 24

def initialize(protocol_options)
  @serialization_options =
    DEFAULTS.merge(protocol_options.slice(*OPTIONS))
  warn_if_marshal_default(protocol_options) unless protocol_options[:silence_marshal_warning]
end

Instance Attribute Details

#serialization_optionsObject

rubocop:disable Style/ClassVars



22
23
24
# File 'lib/dalli/protocol/value_serializer.rb', line 22

def serialization_options
  @serialization_options
end

Instance Method Details

#retrieve(value, bitflags) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dalli/protocol/value_serializer.rb', line 37

def retrieve(value, bitflags)
  serialized = bitflags.anybits?(Flags::SERIALIZED)
  if serialized
    begin
      serializer.load(value)
    rescue StandardError
      raise UnmarshalError, 'Unable to unmarshal value'
    end
  elsif bitflags.anybits?(Flags::UTF8)
    value.force_encoding(Encoding::UTF_8)
  else
    value
  end
end

#serialize_value(value) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/dalli/protocol/value_serializer.rb', line 56

def serialize_value(value)
  serializer.dump(value)
rescue Timeout::Error => e
  raise e
rescue StandardError => e
  # Serializing can throw several different types of generic Ruby exceptions.
  # Convert to a specific exception so we can special case it higher up the stack.
  exc = Dalli::MarshalError.new(e.message)
  exc.set_backtrace e.backtrace
  raise exc
end

#serializerObject



52
53
54
# File 'lib/dalli/protocol/value_serializer.rb', line 52

def serializer
  @serialization_options[:serializer]
end

#store(value, req_options, bitflags) ⇒ Object



30
31
32
33
34
35
# File 'lib/dalli/protocol/value_serializer.rb', line 30

def store(value, req_options, bitflags)
  return store_raw(value, bitflags) if req_options&.dig(:raw)
  return store_string_fastpath(value, bitflags) if use_string_fastpath?(value, req_options)

  [serialize_value(value), bitflags | Flags::SERIALIZED]
end