dalli 5.2.10 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/dalli/client.rb CHANGED
@@ -39,8 +39,6 @@ module Dalli
39
39
  # memcached, Dalli counts the key and 63 bytes of item overhead against this limit along
40
40
  # with the (serialized, compressed) value, so the largest value that can be stored is
41
41
  # value_max_bytes - key bytesize - 63. Larger values raise Dalli::ValueOverMaxSize.
42
- # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
43
- # Set this explicitly when reading larger items written by another client.
44
42
  # - :serializer - defaults to Marshal
45
43
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
46
44
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
@@ -79,8 +77,8 @@ module Dalli
79
77
  #
80
78
  def initialize(servers = nil, options = {})
81
79
  @normalized_servers = ::Dalli::ServersArgNormalizer.normalize_servers(servers)
80
+ warn_removed_options(options)
82
81
  @options = normalize_options(options)
83
- warn_removed_options(@options)
84
82
  @key_manager = ::Dalli::KeyManager.new(@options)
85
83
  @ring = nil
86
84
  end
@@ -136,6 +134,10 @@ module Dalli
136
134
  # - :return_last_access [Boolean] return seconds since last access
137
135
  # - :return_ttl_remaining [Boolean] return seconds of TTL remaining (-1 if no TTL)
138
136
  # - :skip_lru_bump [Boolean] don't bump LRU or update access stats
137
+ # - :vivify_ttl [Integer] on a miss, create a stub that lives this long
138
+ # (sanitized like any other TTL) and report won_recache
139
+ # - :recache_ttl [Integer] report won_recache when the item's remaining
140
+ # TTL is below this
139
141
  #
140
142
  # @return [Hash] containing:
141
143
  # - :value - the cached value (or nil on miss)
@@ -162,6 +164,8 @@ module Dalli
162
164
  #
163
165
  def get_with_metadata(key, options = {})
164
166
  validate_routing_tokens!(options)
167
+ validate_ttl!(:vivify_ttl, options[:vivify_ttl])
168
+ validate_integer!(:recache_ttl, options[:recache_ttl])
165
169
  # A retry re-runs this method with its original arguments, so `key` must
166
170
  # stay as the caller gave it; reassigning it would add the namespace again.
167
171
  validated_key = @key_manager.validate_key(key.to_s)
@@ -202,11 +206,17 @@ module Dalli
202
206
  #
203
207
  # `req_options` accepts :p_token/:l_token, applied to every key in the batch.
204
208
  #
205
- # A transient network error is retried automatically. If a server remains
206
- # unreachable after retrying, raises Dalli::NetworkError rather than
207
- # silently omitting that server's keys from the result.
209
+ # A transient network error is retried automatically. If a server stops
210
+ # during the call and is still unreachable after retrying, raises
211
+ # Dalli::NetworkError only with `failover: false`; with failover (the
212
+ # default) its keys go to another server, or are left out when no server
213
+ # is left. See "Network Errors and Retries" in the README.
208
214
  #
209
- # @raise [Dalli::NetworkError] if a server is unreachable after retrying
215
+ # A retry starts the batch again, so a block can be yielded a key it was
216
+ # already yielded before the error.
217
+ #
218
+ # @raise [Dalli::NetworkError] if a server stops during the call and is
219
+ # still unreachable after retrying, without failover
210
220
  # rubocop:disable-next Style/ExplicitBlockArgument
211
221
  def get_multi(*keys, req_options: nil)
212
222
  keys.flatten!
@@ -244,14 +254,18 @@ module Dalli
244
254
  #
245
255
  # `req_options` accepts :p_token/:l_token, applied to every key in the batch.
246
256
  #
247
- # A transient network error is retried automatically. If a server remains
248
- # unreachable after retrying, raises Dalli::NetworkError rather than
249
- # returning its keys as misses or yielding a partial result.
257
+ # A transient network error is retried automatically. If a server stops
258
+ # during the call and is still unreachable after retrying, raises
259
+ # Dalli::NetworkError only with `failover: false`; with failover (the
260
+ # default) its keys go to another server, or are left out when no server
261
+ # is left. See "Network Errors and Retries" in the README. The block is
262
+ # called only once every server has replied, so never twice for a key.
250
263
  #
251
264
  # @param keys [Array<String>] the keys to fetch
252
265
  # @param req_options [Hash, nil] routing-token options
253
266
  # @return [Hash] key => { value:, cas:, stale:, miss: }
254
- # @raise [Dalli::NetworkError] if a server is unreachable after retrying
267
+ # @raise [Dalli::NetworkError] if a server stops during the call and is
268
+ # still unreachable after retrying, without failover
255
269
  def get_multi_with_metadata(*keys, req_options: nil, &block)
256
270
  keys.flatten!
257
271
  keys.compact!
@@ -308,6 +322,9 @@ module Dalli
308
322
  # { 'key' => [value, cas_id] }
309
323
  #
310
324
  # `req_options` accepts :p_token/:l_token, applied to every key in the batch.
325
+ #
326
+ # Network errors are handled as in #get_multi, and as there a retry can
327
+ # yield a key a second time.
311
328
  def get_multi_cas(*keys, req_options: nil)
312
329
  validate_routing_tokens!(req_options)
313
330
 
@@ -330,11 +347,12 @@ module Dalli
330
347
  # written to the cache and returned.
331
348
  def fetch(key, ttl = nil, req_options = nil)
332
349
  req_options = req_options.nil? ? CACHE_NILS : req_options.merge(CACHE_NILS) if cache_nils
350
+ ttl = ttl_or_default(ttl)
333
351
  val = get(key, req_options)
334
352
  return val unless block_given? && not_found?(val)
335
353
 
336
354
  new_val = yield
337
- add(key, new_val, ttl_or_default(ttl), req_options)
355
+ add(key, new_val, ttl, req_options)
338
356
  new_val
339
357
  end
340
358
 
@@ -371,7 +389,10 @@ module Dalli
371
389
  def fetch_with_lock(key, ttl: nil, lock_ttl: 30, recache_threshold: nil, req_options: nil, &block)
372
390
  raise ArgumentError, 'Block is required for fetch_with_lock' unless block_given?
373
391
 
374
- validate_integer!(:lock_ttl, lock_ttl)
392
+ # ttl is only used once the block has run; checked now so a bad one
393
+ # raises before the lock is taken
394
+ ttl_or_default(ttl)
395
+ validate_ttl!(:lock_ttl, lock_ttl)
375
396
  validate_integer!(:recache_threshold, recache_threshold)
376
397
  validate_routing_tokens!(req_options)
377
398
  # Left unchanged for the retry below; see get_with_metadata
@@ -465,8 +486,10 @@ module Dalli
465
486
  nil
466
487
  end
467
488
 
489
+ # set_cas without its CAS check: the CAS here is always 0
468
490
  def set(key, value, ttl = nil, req_options = nil)
469
- set_cas(key, value, 0, ttl, req_options)
491
+ validate_routing_tokens!(req_options)
492
+ perform(:set, key, value, ttl_or_default(ttl), 0, req_options)
470
493
  end
471
494
 
472
495
  ##
@@ -474,16 +497,20 @@ module Dalli
474
497
  # This method is more efficient than calling set() in a loop because
475
498
  # it batches requests by server and uses quiet mode.
476
499
  #
477
- # A transient network error is retried automatically. If a server remains
478
- # unreachable after retrying, raises Dalli::NetworkError; keys already
479
- # sent to other servers before the error are not rolled back.
500
+ # A transient network error is retried automatically. If a server stops
501
+ # during the call and is still unreachable after retrying, raises
502
+ # Dalli::NetworkError only with `failover: false`; with failover (the
503
+ # default) its keys go to another server, or are left out when no server
504
+ # is left. See "Network Errors and Retries" in the README. Keys already
505
+ # written to other servers before an error are not rolled back.
480
506
  #
481
507
  # @param hash [Hash] key-value pairs to set
482
508
  # @param ttl [Integer] time-to-live in seconds (optional, uses default if not provided)
483
509
  # @param req_options [Hash] options passed to each set operation; accepts
484
510
  # :p_token/:l_token, applied to every key in the batch
485
511
  # @return [void]
486
- # @raise [Dalli::NetworkError] if a server is unreachable after retrying
512
+ # @raise [Dalli::NetworkError] if a server stops during the call and is
513
+ # still unreachable after retrying, without failover
487
514
  #
488
515
  # Example:
489
516
  # client.set_multi({ 'key1' => 'value1', 'key2' => 'value2' }, 300)
@@ -504,7 +531,11 @@ module Dalli
504
531
  ##
505
532
  # Set the key-value pair, verifying existing CAS.
506
533
  # Returns the resulting CAS value if succeeded, and falsy otherwise.
534
+ # The CAS must be an Integer (or a String of decimal digits) between 0 and
535
+ # 2**64 - 1, or nil; anything else raises ArgumentError. A CAS of 0 or nil
536
+ # means an unconditional set.
507
537
  def set_cas(key, value, cas, ttl = nil, req_options = nil)
538
+ validate_uint64!(:cas, cas)
508
539
  validate_routing_tokens!(req_options)
509
540
  perform(:set, key, value, ttl_or_default(ttl), cas, req_options)
510
541
  end
@@ -527,18 +558,22 @@ module Dalli
527
558
  ##
528
559
  # Conditionally add a key/value pair, verifying existing CAS, only if the
529
560
  # key already exists on the server. Returns the new CAS value if the
530
- # operation succeeded, or falsy otherwise.
561
+ # operation succeeded, or falsy otherwise. The CAS is validated as in
562
+ # #set_cas.
531
563
  def replace_cas(key, value, cas, ttl = nil, req_options = nil)
564
+ validate_uint64!(:cas, cas)
532
565
  validate_routing_tokens!(req_options)
533
566
  perform(:replace, key, value, ttl_or_default(ttl), cas, req_options)
534
567
  end
535
568
 
536
569
  # Delete a key/value pair, verifying existing CAS.
537
570
  # Returns true if succeeded, and falsy otherwise.
538
- # Delete a key, optionally with a CAS check.
571
+ # Delete a key, optionally with a CAS check. The CAS is validated as in
572
+ # #set_cas.
539
573
  #
540
574
  # `req_options` accepts the same meta-delete options as #delete.
541
575
  def delete_cas(key, cas = 0, req_options = nil)
576
+ validate_uint64!(:cas, cas)
542
577
  validate_delete_options!(req_options)
543
578
  validate_routing_tokens!(req_options)
544
579
  perform(:delete, key, cas, req_options)
@@ -590,9 +625,10 @@ module Dalli
590
625
  # is whichever one the caller asked for. This is best-effort: a transient
591
626
  # network error is retried automatically, and keys handled before the
592
627
  # error are not recounted, so the result may under-report when a retry
593
- # occurs. If a server remains unreachable after retrying, raises
594
- # Dalli::NetworkError.
595
- # @raise [Dalli::NetworkError] if a server is unreachable after retrying
628
+ # occurs. A server that stops during the call is handled as in
629
+ # #set_multi.
630
+ # @raise [Dalli::NetworkError] if a server stops during the call and is
631
+ # still unreachable after retrying, without failover
596
632
  #
597
633
  # Example:
598
634
  # client.delete_multi(['key1', 'key2', 'key3'])
@@ -630,9 +666,8 @@ module Dalli
630
666
 
631
667
  ##
632
668
  # Incr adds the given amount to the counter on the memcached server.
633
- # Amt must be a positive integer value.
634
- # Default, if given, must be an Integer (or a String of decimal digits);
635
- # anything else raises ArgumentError.
669
+ # Amt, and default if given, must be Integers (or Strings of decimal
670
+ # digits) between 0 and 2**64 - 1; anything else raises ArgumentError.
636
671
  #
637
672
  # If default is nil, the counter must already exist or the operation
638
673
  # will fail and will return nil. Otherwise this method will return
@@ -644,18 +679,17 @@ module Dalli
644
679
  #
645
680
  # If the value already exists, it must have been set with raw: true
646
681
  def incr(key, amt = 1, ttl = nil, default = nil, req_options = nil)
647
- check_positive!(amt)
648
- validate_integer!(:default, default)
682
+ amt = validate_uint64!(:amt, amt)
683
+ default = validate_uint64!(:default, default)
649
684
  validate_routing_tokens!(req_options)
650
685
 
651
- perform(:incr, key, amt.to_i, ttl_or_default(ttl), default, req_options)
686
+ perform(:incr, key, amt, ttl_or_default(ttl), default, req_options)
652
687
  end
653
688
 
654
689
  ##
655
690
  # Decr subtracts the given amount from the counter on the memcached server.
656
- # Amt must be a positive integer value.
657
- # Default, if given, must be an Integer (or a String of decimal digits);
658
- # anything else raises ArgumentError.
691
+ # Amt, and default if given, must be Integers (or Strings of decimal
692
+ # digits) between 0 and 2**64 - 1; anything else raises ArgumentError.
659
693
  #
660
694
  # memcached counters are unsigned and cannot hold negative values. Calling
661
695
  # decr on a counter which is 0 will just return 0.
@@ -670,20 +704,23 @@ module Dalli
670
704
  #
671
705
  # If the value already exists, it must have been set with raw: true
672
706
  def decr(key, amt = 1, ttl = nil, default = nil, req_options = nil)
673
- check_positive!(amt)
674
- validate_integer!(:default, default)
707
+ amt = validate_uint64!(:amt, amt)
708
+ default = validate_uint64!(:default, default)
675
709
  validate_routing_tokens!(req_options)
676
710
 
677
- perform(:decr, key, amt.to_i, ttl_or_default(ttl), default, req_options)
711
+ perform(:decr, key, amt, ttl_or_default(ttl), default, req_options)
678
712
  end
679
713
 
680
714
  ##
681
715
  # Flush the memcached server, at 'delay' seconds in the future.
682
716
  # Delay defaults to zero seconds, which means an immediate flush.
717
+ # Delay must be a non-negative Integer (or a String of decimal digits);
718
+ # anything else raises ArgumentError.
683
719
  # Every server is attempted. If any of them fails, the first error is
684
720
  # raised once all the others have been flushed.
685
721
  ##
686
722
  def flush(delay = 0)
723
+ validate_uint64!(:delay, delay)
687
724
  first_error = nil
688
725
  results = ring.servers.map do |s|
689
726
  s.request(:flush, delay)
@@ -776,15 +813,7 @@ module Dalli
776
813
 
777
814
  raise ArgumentError, 'tombstone_ttl requires invalidate: true' unless req_options[:invalidate]
778
815
 
779
- # tombstone_kwargs coerces this with Integer(), deep inside the request
780
- # path; validated here first so a bad value raises cleanly instead of
781
- # unwinding through Protocol::Base#request, which would close the
782
- # connection on the ArgumentError Integer() raises.
783
- begin
784
- Integer(tombstone_ttl)
785
- rescue ArgumentError, TypeError
786
- raise ArgumentError, "tombstone_ttl must be an integer, got #{tombstone_ttl.inspect}"
787
- end
816
+ validate_ttl!(:tombstone_ttl, tombstone_ttl)
788
817
  end
789
818
 
790
819
  def record_hit_miss_metrics(span, key_count, hit_count)
@@ -820,9 +849,20 @@ module Dalli
820
849
  end
821
850
  end
822
851
 
823
- def single_server
852
+ # retried is true once a request to the server has failed with a
853
+ # RetryableNetworkError. Without failover, finding the server down then
854
+ # means that request failed, which raises, rather than the server being
855
+ # down before the operation began, which returns nil. With failover it
856
+ # returns nil either way, as the multi-server path leaves keys out when
857
+ # no server is left.
858
+ def single_server(retried: false)
824
859
  server = ring.servers.first
825
- server if server&.alive?
860
+ return server if server&.alive?
861
+ if retried && !ring.failover?
862
+ raise Dalli::NetworkError, "#{server&.name} failed during this request and is still unreachable"
863
+ end
864
+
865
+ nil
826
866
  end
827
867
 
828
868
  # The three single_server_* fast-path methods below share one contract,
@@ -831,20 +871,22 @@ module Dalli
831
871
  # socket_max_failures, same as the pipelined path's retry), and a hard
832
872
  # NetworkError -- the server genuinely unreachable, not just blipping --
833
873
  # propagates to the caller rather than being swallowed into a silently
834
- # wrong result. Only server_for_key/single_server finding no live server
835
- # to route to at all is still silent, matching Ring#keys_grouped_by_server
836
- # dropping a key it can't route on both the single- and multi-server paths.
874
+ # wrong result, including (without failover) the server going down before
875
+ # the retry, which single_server raises for. Otherwise finding no live
876
+ # server is still silent, matching Ring#keys_grouped_by_server dropping a
877
+ # key it can't route on both the single- and multi-server paths. Each
878
+ # method sets retried before it retries; a local keeps its value across
879
+ # a retry.
837
880
  def single_server_get_multi(keys, req_options = nil)
838
- # A new array, so the retry below starts again from the caller's keys
839
- validated_keys = keys.map { |k| @key_manager.validate_key(k.to_s) }
840
- return {} unless (server = single_server)
881
+ retried ||= false
882
+ caller_keys = @key_manager.caller_keys_by_wire_key(keys)
883
+ return {} unless (server = single_server(retried: retried))
841
884
 
842
- result = server.request(:read_multi_req, validated_keys, req_options)
843
- result.transform_keys! { |k| @key_manager.key_without_namespace(k) }
844
- result
885
+ results_for_caller_keys(server.request(:read_multi_req, caller_keys.keys, req_options), caller_keys)
845
886
  rescue Dalli::RetryableNetworkError => e
846
887
  Dalli.logger.debug { e.inspect }
847
888
  Dalli.logger.debug { 'retrying single-server get_multi because of network error' }
889
+ retried = true
848
890
  retry
849
891
  rescue Dalli::UnexpectedReplyKeyError => e
850
892
  # The connection is closed and the keys are treated as missing, as the
@@ -854,40 +896,54 @@ module Dalli
854
896
  end
855
897
 
856
898
  def single_server_get_multi_with_metadata(keys, req_options = nil)
857
- validated_keys = keys.map { |k| @key_manager.validate_key(k.to_s) }
858
- return {} unless (server = single_server)
899
+ retried ||= false
900
+ caller_keys = @key_manager.caller_keys_by_wire_key(keys)
901
+ return {} unless (server = single_server(retried: retried))
859
902
 
860
- result = server.request(:read_multi_with_metadata_req, validated_keys, req_options)
861
- result.transform_keys! { |k| @key_manager.key_without_namespace(k) }
862
- result
903
+ results_for_caller_keys(server.request(:read_multi_with_metadata_req, caller_keys.keys, req_options),
904
+ caller_keys)
863
905
  rescue Dalli::RetryableNetworkError => e
864
906
  Dalli.logger.debug { e.inspect }
865
907
  Dalli.logger.debug { 'retrying single-server get_multi_with_metadata because of network error' }
908
+ retried = true
866
909
  retry
867
910
  rescue Dalli::UnexpectedReplyKeyError => e
868
911
  Dalli.logger.warn { e.message }
869
912
  {}
870
913
  end
871
914
 
915
+ # Replies name the key as sent; returns them under the caller's keys,
916
+ # skipping any key that wasn't requested
917
+ def results_for_caller_keys(results, caller_keys)
918
+ results.each_with_object({}) do |(key, value), hash|
919
+ caller_key = @key_manager.caller_key(caller_keys, key)
920
+ hash[caller_key] = value if caller_key
921
+ end
922
+ end
923
+
872
924
  def single_server_set_multi(hash, ttl, req_options)
925
+ retried ||= false
873
926
  pairs = hash.transform_keys { |k| @key_manager.validate_key(k.to_s) }
874
- return unless (server = single_server)
927
+ return unless (server = single_server(retried: retried))
875
928
 
876
929
  server.request(:write_multi_req, pairs, ttl, req_options)
877
930
  rescue Dalli::RetryableNetworkError => e
878
931
  Dalli.logger.debug { e.inspect }
879
932
  Dalli.logger.debug { 'retrying single-server set_multi because of network error' }
933
+ retried = true
880
934
  retry
881
935
  end
882
936
 
883
937
  def single_server_delete_multi(keys, req_options = nil)
938
+ retried ||= false
884
939
  validated_keys = keys.map { |k| @key_manager.validate_key(k.to_s) }
885
- return 0 unless (server = single_server)
940
+ return 0 unless (server = single_server(retried: retried))
886
941
 
887
942
  server.request(:delete_multi_req, validated_keys, req_options)
888
943
  rescue Dalli::RetryableNetworkError => e
889
944
  Dalli.logger.debug { e.inspect }
890
945
  Dalli.logger.debug { 'retrying single-server delete_multi because of network error' }
946
+ retried = true
891
947
  retry
892
948
  end
893
949
 
@@ -919,10 +975,6 @@ module Dalli
919
975
  attrs
920
976
  end
921
977
 
922
- def check_positive!(amt)
923
- raise ArgumentError, "Positive values only: #{amt}" if amt.negative?
924
- end
925
-
926
978
  # Numeric arguments that become meta protocol flags (GHSA-6wmv-xq9m-fmp7).
927
979
  # RequestFormatter converts them to Integer as the wire-level backstop;
928
980
  # checking here too gives the caller a clean ArgumentError for the same
@@ -935,6 +987,27 @@ module Dalli
935
987
  raise ArgumentError, "#{name} must be an Integer, got #{value.inspect}"
936
988
  end
937
989
 
990
+ MAX_UINT64 = (2**64) - 1
991
+ private_constant :MAX_UINT64
992
+
993
+ # CAS values, incr/decr amounts and initial values, and the flush delay
994
+ # are read by memcached as unsigned 64-bit integers. RequestFormatter
995
+ # raises on anything else as the wire-level backstop; checking here first
996
+ # keeps the connection open, for the reason given for routing tokens
997
+ # below. Accepts an Integer or a String of decimal digits, and returns it
998
+ # as an Integer.
999
+ def validate_uint64!(name, value)
1000
+ return if value.nil?
1001
+
1002
+ int = case value
1003
+ when Integer then value
1004
+ when String then Integer(value, 10, exception: false)
1005
+ end
1006
+ return int if int && int >= 0 && int <= MAX_UINT64
1007
+
1008
+ raise ArgumentError, "#{name} must be an Integer between 0 and #{MAX_UINT64}, got #{value.inspect}"
1009
+ end
1010
+
938
1011
  # Validated here, before the request reaches Protocol::Base#request, rather
939
1012
  # than only at the RequestFormatter level. Reaching only the formatter's
940
1013
  # check means unwinding through Protocol::Base#request, which logs the
@@ -963,15 +1036,16 @@ module Dalli
963
1036
 
964
1037
  def cas_core(key, always_set, ttl = nil, req_options = nil)
965
1038
  validate_routing_tokens!(req_options)
1039
+ ttl = ttl_or_default(ttl)
966
1040
  (value, cas) = perform(:cas, key, req_options)
967
1041
  return if !always_set && cas_miss?(value, cas)
968
1042
 
969
1043
  newvalue = yield(value)
970
1044
  # A CAS of 0 means the key was missing. A set with CAS 0 is unconditional,
971
1045
  # so add instead: it fails if another client created the key meanwhile.
972
- return perform(:add, key, newvalue, ttl_or_default(ttl), req_options) if cas.zero?
1046
+ return perform(:add, key, newvalue, ttl, req_options) if cas.zero?
973
1047
 
974
- perform(:set, key, newvalue, ttl_or_default(ttl), cas, req_options)
1048
+ perform(:set, key, newvalue, ttl, cas, req_options)
975
1049
  end
976
1050
 
977
1051
  # The CAS lookup returns [nil, 0] on a miss rather than NOT_FOUND, and a
@@ -1000,12 +1074,47 @@ module Dalli
1000
1074
 
1001
1075
  ##
1002
1076
  # Uses the argument TTL or the client-wide default. Ensures
1003
- # that the value is an integer
1077
+ # that the value is an integer memcached accepts as an expiration
1004
1078
  ##
1005
1079
  def ttl_or_default(ttl)
1006
- (ttl || @options[:expires_in]).to_i
1007
- rescue NoMethodError
1008
- raise ArgumentError, "Cannot convert ttl (#{ttl}) to an integer"
1080
+ ttl ||= @options[:expires_in] || 0
1081
+ # validate_ttl!'s fast path, without the call
1082
+ return ttl if ttl.is_a?(Integer) && ttl >= Protocol::TtlSanitizer::MIN_EXPIRATION_TIME &&
1083
+ ttl <= Protocol::TtlSanitizer::MAX_ACCEPTABLE_EXPIRATION_INTERVAL
1084
+
1085
+ validate_ttl!(:ttl, ttl)
1086
+ end
1087
+
1088
+ # Returns the TTL as an Integer, sanitized (see TtlSanitizer), raising
1089
+ # ArgumentError unless memcached can use it. An interval over 30 days comes
1090
+ # back as the Unix time it becomes, so the request path doesn't convert it
1091
+ # again. A String must be a whole number in decimal, as for the other
1092
+ # numeric arguments; anything else is converted with to_i, so a Float or
1093
+ # an ActiveSupport::Duration still works. Once sanitized it must fit memcached's signed 32-bit expiration time. A
1094
+ # negative TTL is allowed: memcached stores the item as already expired.
1095
+ # memcached rejects a TTL outside that with CLIENT_ERROR, which a quiet
1096
+ # block or set_multi silently discards, so it is checked here, before the
1097
+ # request is written.
1098
+ def validate_ttl!(name, value)
1099
+ return if value.nil?
1100
+ # The usual case: an Integer TTL that TtlSanitizer leaves unchanged
1101
+ return value if value.is_a?(Integer) && value >= Protocol::TtlSanitizer::MIN_EXPIRATION_TIME &&
1102
+ value <= Protocol::TtlSanitizer::MAX_ACCEPTABLE_EXPIRATION_INTERVAL
1103
+
1104
+ ttl = ttl_to_i(name, value)
1105
+ min = Protocol::TtlSanitizer::MIN_EXPIRATION_TIME
1106
+ max = Protocol::TtlSanitizer::MAX_EXPIRATION_TIME
1107
+ ttl = Protocol::TtlSanitizer.sanitize(ttl)
1108
+ return ttl if ttl.between?(min, max)
1109
+
1110
+ raise ArgumentError, "#{name} must be a number of seconds no smaller than #{min} or a Unix time " \
1111
+ "no later than #{max}, got #{value.inspect}"
1112
+ end
1113
+
1114
+ def ttl_to_i(name, value)
1115
+ value.is_a?(String) ? Integer(value, 10) : value.to_i
1116
+ rescue ArgumentError, NoMethodError, FloatDomainError
1117
+ raise ArgumentError, "#{name} must be an Integer, got #{value.inspect}"
1009
1118
  end
1010
1119
 
1011
1120
  def ring
@@ -1020,7 +1129,10 @@ module Dalli
1020
1129
  #
1021
1130
  # This method also forces retries on network errors - when
1022
1131
  # a particular memcached instance becomes unreachable, or the
1023
- # operation times out.
1132
+ # operation times out. Once some of the request has been sent, only
1133
+ # one that is safe to apply twice is retried; for the others
1134
+ # (incr, decr, append, prepend, add, replace and CAS writes)
1135
+ # Protocol::Base#request raises a NetworkError, which isn't retried.
1024
1136
  ##
1025
1137
  # rubocop:disable Naming/MethodParameterName
1026
1138
  def perform(op, key, ...)
@@ -1049,13 +1161,12 @@ module Dalli
1049
1161
  end
1050
1162
 
1051
1163
  # Works on a copy so the caller's hash is neither modified here nor able
1052
- # to change this client's configuration later.
1164
+ # to change this client's configuration later. Credentials are dropped:
1165
+ # Dalli 5 doesn't use them, and kept they could show up in #inspect.
1053
1166
  def normalize_options(options)
1054
- opts = options.dup
1055
- opts[:expires_in] = opts[:expires_in].to_i if opts[:expires_in]
1167
+ opts = options.except(:username, :password)
1168
+ opts[:expires_in] = ttl_to_i(:expires_in, opts[:expires_in]) if opts[:expires_in]
1056
1169
  opts
1057
- rescue NoMethodError
1058
- raise ArgumentError, "cannot convert :expires_in => #{opts[:expires_in].inspect} to an integer"
1059
1170
  end
1060
1171
 
1061
1172
  REMOVED_OPTIONS = {
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'zlib'
4
+ require 'stringio'
4
5
 
5
6
  module Dalli
6
7
  ##
@@ -9,7 +10,7 @@ module Dalli
9
10
  ##
10
11
  class Compressor
11
12
  def self.compress(data)
12
- deflate_fully(Zlib::Deflate.new, data)
13
+ Zlib::Deflate.deflate(data)
13
14
  end
14
15
 
15
16
  # DEFLATE can't expand data by more than about 1032:1
@@ -23,51 +24,11 @@ module Dalli
23
24
  # as the output passes it, so a small compressed value can't expand into
24
25
  # gigabytes of memory.
25
26
  def self.decompress(data, max_bytes: nil)
26
- return inflate_fully(Zlib::Inflate.new, data) unless may_exceed?(data, max_bytes)
27
+ return Zlib::Inflate.inflate(data) unless may_exceed?(data, max_bytes)
27
28
 
28
29
  inflate_within_limit(Zlib::Inflate.new, data, max_bytes)
29
30
  end
30
31
 
31
- # Ruby's zlib extension can return from a call before zlib has finished
32
- # when a signal interrupts it (ruby/zlib#49). One-shot calls like
33
- # Zlib::Deflate.deflate then raise or, with zlib 3.2.4, return truncated
34
- # output, so these call finish until the stream has ended.
35
- def self.deflate_fully(deflater, data)
36
- finish_stream(deflater, deflater.deflate(data, Zlib::FINISH))
37
- ensure
38
- deflater.close
39
- end
40
-
41
- def self.inflate_fully(inflater, data)
42
- finish_stream(inflater, feed(inflater, data) || String.new(encoding: Encoding::BINARY))
43
- ensure
44
- inflater.close
45
- end
46
-
47
- # zlib gem 3.2.3 and earlier retry an interrupted inflate even when it has
48
- # used up its input, and raise the Z_BUF_ERROR zlib returns for that. The
49
- # output so far stays in the stream, and finish raises for input that is
50
- # truly truncated.
51
- def self.feed(inflater, data, &)
52
- inflater.inflate(data, &)
53
- rescue Zlib::BufError
54
- nil
55
- end
56
-
57
- def self.finish_stream(stream, out)
58
- out << next_chunk(stream) until stream.finished?
59
- out
60
- end
61
-
62
- # Each finish makes progress, so one that returns nothing means the
63
- # stream can't end: the compressed input is truncated
64
- def self.next_chunk(stream)
65
- chunk = stream.finish
66
- raise Zlib::BufError, 'buffer error' if chunk.empty?
67
-
68
- chunk
69
- end
70
-
71
32
  # False when even the largest possible expansion stays within max_bytes,
72
33
  # so the value can be inflated in one step
73
34
  def self.may_exceed?(data, max_bytes)
@@ -82,15 +43,16 @@ module Dalli
82
43
  # with Zlib::Inflate.inflate; finish would return it as output
83
44
  break if inflater.finished?
84
45
  end
85
- append_within_limit(out, next_chunk(inflater), max_bytes) until inflater.finished?
86
- out
46
+ return out if inflater.finished?
47
+
48
+ append_within_limit(out, inflater.finish, max_bytes)
87
49
  ensure
88
50
  inflater.close
89
51
  end
90
52
 
91
53
  # Both yielded and returned output count toward the limit
92
54
  def self.inflate_slice(inflater, slice, out, max_bytes)
93
- rest = feed(inflater, slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
55
+ rest = inflater.inflate(slice) { |chunk| append_within_limit(out, chunk, max_bytes) }
94
56
  append_within_limit(out, rest, max_bytes)
95
57
  end
96
58
 
@@ -108,18 +70,19 @@ module Dalli
108
70
  # entry.
109
71
  ##
110
72
  class GzipCompressor
111
- # MAX_WBITS + 16 makes zlib write and read the gzip format (and check its CRC)
112
- WINDOW_BITS = Zlib::MAX_WBITS + 16
113
-
114
73
  def self.compress(data)
115
- Compressor.deflate_fully(Zlib::Deflate.new(Zlib::DEFAULT_COMPRESSION, WINDOW_BITS), data)
74
+ io = StringIO.new(+'', 'w')
75
+ gz = Zlib::GzipWriter.new(io)
76
+ gz.write(data)
77
+ gz.close
78
+ io.string
116
79
  end
117
80
 
118
81
  def self.decompress(data, max_bytes: nil)
119
- inflater = Zlib::Inflate.new(WINDOW_BITS)
120
- return Compressor.inflate_fully(inflater, data) unless Compressor.may_exceed?(data, max_bytes)
82
+ return Zlib::GzipReader.new(StringIO.new(data, 'rb')).read unless Compressor.may_exceed?(data, max_bytes)
121
83
 
122
- Compressor.inflate_within_limit(inflater, data, max_bytes)
84
+ # MAX_WBITS + 16 makes zlib read the gzip format (and check its CRC)
85
+ Compressor.inflate_within_limit(Zlib::Inflate.new(Zlib::MAX_WBITS + 16), data, max_bytes)
123
86
  end
124
87
  end
125
88
  end