File: string_marshaller.rb

package info (click to toggle)
ruby-dalli 5.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 992 kB
  • sloc: ruby: 9,447; sh: 19; makefile: 4
file content (65 lines) | stat: -rw-r--r-- 1,734 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module Dalli
  module Protocol
    ##
    # Dalli::Protocol::StringMarshaller is a pass-through marshaller for use with
    # the :raw client option. It bypasses serialization and compression entirely,
    # expecting values to already be strings (e.g., pre-serialized by Rails'
    # ActiveSupport::Cache). It still enforces the maximum value size limit.
    ##
    class StringMarshaller
      DEFAULTS = {
        # max size of value in bytes (default is 1 MB, can be overriden with "memcached -I <size>")
        value_max_bytes: 1024 * 1024
      }.freeze

      attr_reader :value_max_bytes

      def initialize(client_options)
        @value_max_bytes = client_options.fetch(:value_max_bytes) do
          DEFAULTS.fetch(:value_max_bytes)
        end.to_i
      end

      def store(key, value, _options = nil)
        raise MarshalError, "Dalli in :raw mode only supports strings, got: #{value.class}" unless value.is_a?(String)

        error_if_over_max_value_bytes(key, value)
        [value, 0]
      end

      def retrieve(value, _flags)
        value
      end

      # Interface compatibility methods - these return nil since
      # StringMarshaller bypasses serialization and compression entirely.

      def serializer
        nil
      end

      def compressor
        nil
      end

      def compression_min_size
        nil
      end

      def compress_by_default?
        false
      end

      private

      def error_if_over_max_value_bytes(key, value)
        return if value.bytesize <= value_max_bytes

        message = "Value for #{key} over max size: #{value_max_bytes} <= #{value.bytesize}"
        raise Dalli::ValueOverMaxSize, message
      end
    end
  end
end