omg-activesupport 8.0.0.alpha1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (289) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +86 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +40 -0
  5. data/lib/active_support/actionable_error.rb +50 -0
  6. data/lib/active_support/all.rb +5 -0
  7. data/lib/active_support/array_inquirer.rb +50 -0
  8. data/lib/active_support/backtrace_cleaner.rb +163 -0
  9. data/lib/active_support/benchmark.rb +21 -0
  10. data/lib/active_support/benchmarkable.rb +53 -0
  11. data/lib/active_support/broadcast_logger.rb +251 -0
  12. data/lib/active_support/builder.rb +8 -0
  13. data/lib/active_support/cache/coder.rb +153 -0
  14. data/lib/active_support/cache/entry.rb +134 -0
  15. data/lib/active_support/cache/file_store.rb +244 -0
  16. data/lib/active_support/cache/mem_cache_store.rb +290 -0
  17. data/lib/active_support/cache/memory_store.rb +262 -0
  18. data/lib/active_support/cache/null_store.rb +62 -0
  19. data/lib/active_support/cache/redis_cache_store.rb +492 -0
  20. data/lib/active_support/cache/serializer_with_fallback.rb +152 -0
  21. data/lib/active_support/cache/strategy/local_cache.rb +201 -0
  22. data/lib/active_support/cache/strategy/local_cache_middleware.rb +45 -0
  23. data/lib/active_support/cache.rb +1104 -0
  24. data/lib/active_support/callbacks.rb +944 -0
  25. data/lib/active_support/class_attribute.rb +26 -0
  26. data/lib/active_support/code_generator.rb +79 -0
  27. data/lib/active_support/concern.rb +217 -0
  28. data/lib/active_support/concurrency/load_interlock_aware_monitor.rb +72 -0
  29. data/lib/active_support/concurrency/null_lock.rb +13 -0
  30. data/lib/active_support/concurrency/share_lock.rb +225 -0
  31. data/lib/active_support/configurable.rb +159 -0
  32. data/lib/active_support/configuration_file.rb +60 -0
  33. data/lib/active_support/core_ext/array/access.rb +100 -0
  34. data/lib/active_support/core_ext/array/conversions.rb +213 -0
  35. data/lib/active_support/core_ext/array/extract.rb +21 -0
  36. data/lib/active_support/core_ext/array/extract_options.rb +31 -0
  37. data/lib/active_support/core_ext/array/grouping.rb +109 -0
  38. data/lib/active_support/core_ext/array/inquiry.rb +19 -0
  39. data/lib/active_support/core_ext/array/wrap.rb +48 -0
  40. data/lib/active_support/core_ext/array.rb +9 -0
  41. data/lib/active_support/core_ext/benchmark.rb +13 -0
  42. data/lib/active_support/core_ext/big_decimal/conversions.rb +14 -0
  43. data/lib/active_support/core_ext/big_decimal.rb +3 -0
  44. data/lib/active_support/core_ext/class/attribute.rb +122 -0
  45. data/lib/active_support/core_ext/class/attribute_accessors.rb +6 -0
  46. data/lib/active_support/core_ext/class/subclasses.rb +24 -0
  47. data/lib/active_support/core_ext/class.rb +4 -0
  48. data/lib/active_support/core_ext/date/acts_like.rb +10 -0
  49. data/lib/active_support/core_ext/date/blank.rb +18 -0
  50. data/lib/active_support/core_ext/date/calculations.rb +161 -0
  51. data/lib/active_support/core_ext/date/conversions.rb +98 -0
  52. data/lib/active_support/core_ext/date/zones.rb +8 -0
  53. data/lib/active_support/core_ext/date.rb +7 -0
  54. data/lib/active_support/core_ext/date_and_time/calculations.rb +374 -0
  55. data/lib/active_support/core_ext/date_and_time/compatibility.rb +58 -0
  56. data/lib/active_support/core_ext/date_and_time/zones.rb +40 -0
  57. data/lib/active_support/core_ext/date_time/acts_like.rb +16 -0
  58. data/lib/active_support/core_ext/date_time/blank.rb +18 -0
  59. data/lib/active_support/core_ext/date_time/calculations.rb +215 -0
  60. data/lib/active_support/core_ext/date_time/compatibility.rb +18 -0
  61. data/lib/active_support/core_ext/date_time/conversions.rb +106 -0
  62. data/lib/active_support/core_ext/date_time.rb +7 -0
  63. data/lib/active_support/core_ext/digest/uuid.rb +76 -0
  64. data/lib/active_support/core_ext/digest.rb +3 -0
  65. data/lib/active_support/core_ext/enumerable.rb +267 -0
  66. data/lib/active_support/core_ext/erb/util.rb +201 -0
  67. data/lib/active_support/core_ext/file/atomic.rb +72 -0
  68. data/lib/active_support/core_ext/file.rb +3 -0
  69. data/lib/active_support/core_ext/hash/conversions.rb +262 -0
  70. data/lib/active_support/core_ext/hash/deep_merge.rb +42 -0
  71. data/lib/active_support/core_ext/hash/deep_transform_values.rb +46 -0
  72. data/lib/active_support/core_ext/hash/except.rb +12 -0
  73. data/lib/active_support/core_ext/hash/indifferent_access.rb +24 -0
  74. data/lib/active_support/core_ext/hash/keys.rb +143 -0
  75. data/lib/active_support/core_ext/hash/reverse_merge.rb +25 -0
  76. data/lib/active_support/core_ext/hash/slice.rb +27 -0
  77. data/lib/active_support/core_ext/hash.rb +10 -0
  78. data/lib/active_support/core_ext/integer/inflections.rb +31 -0
  79. data/lib/active_support/core_ext/integer/multiple.rb +12 -0
  80. data/lib/active_support/core_ext/integer/time.rb +22 -0
  81. data/lib/active_support/core_ext/integer.rb +5 -0
  82. data/lib/active_support/core_ext/kernel/concern.rb +14 -0
  83. data/lib/active_support/core_ext/kernel/reporting.rb +45 -0
  84. data/lib/active_support/core_ext/kernel/singleton_class.rb +8 -0
  85. data/lib/active_support/core_ext/kernel.rb +5 -0
  86. data/lib/active_support/core_ext/load_error.rb +9 -0
  87. data/lib/active_support/core_ext/module/aliasing.rb +31 -0
  88. data/lib/active_support/core_ext/module/anonymous.rb +30 -0
  89. data/lib/active_support/core_ext/module/attr_internal.rb +49 -0
  90. data/lib/active_support/core_ext/module/attribute_accessors.rb +214 -0
  91. data/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb +175 -0
  92. data/lib/active_support/core_ext/module/concerning.rb +140 -0
  93. data/lib/active_support/core_ext/module/delegation.rb +225 -0
  94. data/lib/active_support/core_ext/module/deprecation.rb +25 -0
  95. data/lib/active_support/core_ext/module/introspection.rb +62 -0
  96. data/lib/active_support/core_ext/module/redefine_method.rb +40 -0
  97. data/lib/active_support/core_ext/module/remove_method.rb +17 -0
  98. data/lib/active_support/core_ext/module.rb +13 -0
  99. data/lib/active_support/core_ext/name_error.rb +59 -0
  100. data/lib/active_support/core_ext/numeric/bytes.rb +75 -0
  101. data/lib/active_support/core_ext/numeric/conversions.rb +145 -0
  102. data/lib/active_support/core_ext/numeric/time.rb +66 -0
  103. data/lib/active_support/core_ext/numeric.rb +5 -0
  104. data/lib/active_support/core_ext/object/acts_like.rb +45 -0
  105. data/lib/active_support/core_ext/object/blank.rb +199 -0
  106. data/lib/active_support/core_ext/object/conversions.rb +6 -0
  107. data/lib/active_support/core_ext/object/deep_dup.rb +71 -0
  108. data/lib/active_support/core_ext/object/duplicable.rb +69 -0
  109. data/lib/active_support/core_ext/object/inclusion.rb +37 -0
  110. data/lib/active_support/core_ext/object/instance_variables.rb +32 -0
  111. data/lib/active_support/core_ext/object/json.rb +260 -0
  112. data/lib/active_support/core_ext/object/to_param.rb +3 -0
  113. data/lib/active_support/core_ext/object/to_query.rb +87 -0
  114. data/lib/active_support/core_ext/object/try.rb +158 -0
  115. data/lib/active_support/core_ext/object/with.rb +46 -0
  116. data/lib/active_support/core_ext/object/with_options.rb +101 -0
  117. data/lib/active_support/core_ext/object.rb +17 -0
  118. data/lib/active_support/core_ext/pathname/blank.rb +20 -0
  119. data/lib/active_support/core_ext/pathname/existence.rb +23 -0
  120. data/lib/active_support/core_ext/pathname.rb +4 -0
  121. data/lib/active_support/core_ext/range/compare_range.rb +57 -0
  122. data/lib/active_support/core_ext/range/conversions.rb +62 -0
  123. data/lib/active_support/core_ext/range/each.rb +24 -0
  124. data/lib/active_support/core_ext/range/overlap.rb +40 -0
  125. data/lib/active_support/core_ext/range.rb +6 -0
  126. data/lib/active_support/core_ext/regexp.rb +14 -0
  127. data/lib/active_support/core_ext/securerandom.rb +41 -0
  128. data/lib/active_support/core_ext/string/access.rb +95 -0
  129. data/lib/active_support/core_ext/string/behavior.rb +8 -0
  130. data/lib/active_support/core_ext/string/conversions.rb +60 -0
  131. data/lib/active_support/core_ext/string/exclude.rb +13 -0
  132. data/lib/active_support/core_ext/string/filters.rb +151 -0
  133. data/lib/active_support/core_ext/string/indent.rb +45 -0
  134. data/lib/active_support/core_ext/string/inflections.rb +300 -0
  135. data/lib/active_support/core_ext/string/inquiry.rb +16 -0
  136. data/lib/active_support/core_ext/string/multibyte.rb +58 -0
  137. data/lib/active_support/core_ext/string/output_safety.rb +228 -0
  138. data/lib/active_support/core_ext/string/starts_ends_with.rb +6 -0
  139. data/lib/active_support/core_ext/string/strip.rb +27 -0
  140. data/lib/active_support/core_ext/string/zones.rb +16 -0
  141. data/lib/active_support/core_ext/string.rb +15 -0
  142. data/lib/active_support/core_ext/symbol/starts_ends_with.rb +6 -0
  143. data/lib/active_support/core_ext/symbol.rb +3 -0
  144. data/lib/active_support/core_ext/thread/backtrace/location.rb +12 -0
  145. data/lib/active_support/core_ext/time/acts_like.rb +10 -0
  146. data/lib/active_support/core_ext/time/calculations.rb +386 -0
  147. data/lib/active_support/core_ext/time/compatibility.rb +32 -0
  148. data/lib/active_support/core_ext/time/conversions.rb +75 -0
  149. data/lib/active_support/core_ext/time/zones.rb +97 -0
  150. data/lib/active_support/core_ext/time.rb +7 -0
  151. data/lib/active_support/core_ext.rb +5 -0
  152. data/lib/active_support/current_attributes/test_helper.rb +13 -0
  153. data/lib/active_support/current_attributes.rb +233 -0
  154. data/lib/active_support/deep_mergeable.rb +53 -0
  155. data/lib/active_support/delegation.rb +202 -0
  156. data/lib/active_support/dependencies/autoload.rb +72 -0
  157. data/lib/active_support/dependencies/interlock.rb +49 -0
  158. data/lib/active_support/dependencies/require_dependency.rb +28 -0
  159. data/lib/active_support/dependencies.rb +98 -0
  160. data/lib/active_support/deprecation/behaviors.rb +148 -0
  161. data/lib/active_support/deprecation/constant_accessor.rb +74 -0
  162. data/lib/active_support/deprecation/deprecators.rb +104 -0
  163. data/lib/active_support/deprecation/disallowed.rb +54 -0
  164. data/lib/active_support/deprecation/method_wrappers.rb +68 -0
  165. data/lib/active_support/deprecation/proxy_wrappers.rb +189 -0
  166. data/lib/active_support/deprecation/reporting.rb +179 -0
  167. data/lib/active_support/deprecation.rb +81 -0
  168. data/lib/active_support/deprecator.rb +7 -0
  169. data/lib/active_support/descendants_tracker.rb +112 -0
  170. data/lib/active_support/digest.rb +22 -0
  171. data/lib/active_support/duration/iso8601_parser.rb +123 -0
  172. data/lib/active_support/duration/iso8601_serializer.rb +64 -0
  173. data/lib/active_support/duration.rb +520 -0
  174. data/lib/active_support/encrypted_configuration.rb +126 -0
  175. data/lib/active_support/encrypted_file.rb +133 -0
  176. data/lib/active_support/environment_inquirer.rb +40 -0
  177. data/lib/active_support/error_reporter/test_helper.rb +15 -0
  178. data/lib/active_support/error_reporter.rb +265 -0
  179. data/lib/active_support/evented_file_update_checker.rb +182 -0
  180. data/lib/active_support/execution_context/test_helper.rb +13 -0
  181. data/lib/active_support/execution_context.rb +53 -0
  182. data/lib/active_support/execution_wrapper.rb +150 -0
  183. data/lib/active_support/executor/test_helper.rb +7 -0
  184. data/lib/active_support/executor.rb +8 -0
  185. data/lib/active_support/file_update_checker.rb +164 -0
  186. data/lib/active_support/fork_tracker.rb +43 -0
  187. data/lib/active_support/gem_version.rb +17 -0
  188. data/lib/active_support/gzip.rb +40 -0
  189. data/lib/active_support/hash_with_indifferent_access.rb +445 -0
  190. data/lib/active_support/html_safe_translation.rb +56 -0
  191. data/lib/active_support/i18n.rb +17 -0
  192. data/lib/active_support/i18n_railtie.rb +138 -0
  193. data/lib/active_support/inflections.rb +72 -0
  194. data/lib/active_support/inflector/inflections.rb +273 -0
  195. data/lib/active_support/inflector/methods.rb +387 -0
  196. data/lib/active_support/inflector/transliterate.rb +149 -0
  197. data/lib/active_support/inflector.rb +9 -0
  198. data/lib/active_support/isolated_execution_state.rb +75 -0
  199. data/lib/active_support/json/decoding.rb +76 -0
  200. data/lib/active_support/json/encoding.rb +120 -0
  201. data/lib/active_support/json.rb +4 -0
  202. data/lib/active_support/key_generator.rb +66 -0
  203. data/lib/active_support/lazy_load_hooks.rb +107 -0
  204. data/lib/active_support/locale/en.rb +33 -0
  205. data/lib/active_support/locale/en.yml +141 -0
  206. data/lib/active_support/log_subscriber/test_helper.rb +106 -0
  207. data/lib/active_support/log_subscriber.rb +192 -0
  208. data/lib/active_support/logger.rb +55 -0
  209. data/lib/active_support/logger_silence.rb +21 -0
  210. data/lib/active_support/logger_thread_safe_level.rb +47 -0
  211. data/lib/active_support/message_encryptor.rb +374 -0
  212. data/lib/active_support/message_encryptors.rb +141 -0
  213. data/lib/active_support/message_pack/cache_serializer.rb +23 -0
  214. data/lib/active_support/message_pack/extensions.rb +305 -0
  215. data/lib/active_support/message_pack/serializer.rb +63 -0
  216. data/lib/active_support/message_pack.rb +50 -0
  217. data/lib/active_support/message_verifier.rb +368 -0
  218. data/lib/active_support/message_verifiers.rb +135 -0
  219. data/lib/active_support/messages/codec.rb +65 -0
  220. data/lib/active_support/messages/metadata.rb +146 -0
  221. data/lib/active_support/messages/rotation_configuration.rb +23 -0
  222. data/lib/active_support/messages/rotation_coordinator.rb +93 -0
  223. data/lib/active_support/messages/rotator.rb +59 -0
  224. data/lib/active_support/messages/serializer_with_fallback.rb +158 -0
  225. data/lib/active_support/multibyte/chars.rb +178 -0
  226. data/lib/active_support/multibyte/unicode.rb +42 -0
  227. data/lib/active_support/multibyte.rb +23 -0
  228. data/lib/active_support/notifications/fanout.rb +446 -0
  229. data/lib/active_support/notifications/instrumenter.rb +240 -0
  230. data/lib/active_support/notifications.rb +281 -0
  231. data/lib/active_support/number_helper/number_converter.rb +190 -0
  232. data/lib/active_support/number_helper/number_to_currency_converter.rb +46 -0
  233. data/lib/active_support/number_helper/number_to_delimited_converter.rb +30 -0
  234. data/lib/active_support/number_helper/number_to_human_converter.rb +69 -0
  235. data/lib/active_support/number_helper/number_to_human_size_converter.rb +60 -0
  236. data/lib/active_support/number_helper/number_to_percentage_converter.rb +16 -0
  237. data/lib/active_support/number_helper/number_to_phone_converter.rb +60 -0
  238. data/lib/active_support/number_helper/number_to_rounded_converter.rb +59 -0
  239. data/lib/active_support/number_helper/rounding_helper.rb +46 -0
  240. data/lib/active_support/number_helper.rb +479 -0
  241. data/lib/active_support/option_merger.rb +38 -0
  242. data/lib/active_support/ordered_hash.rb +50 -0
  243. data/lib/active_support/ordered_options.rb +147 -0
  244. data/lib/active_support/parameter_filter.rb +157 -0
  245. data/lib/active_support/proxy_object.rb +20 -0
  246. data/lib/active_support/rails.rb +26 -0
  247. data/lib/active_support/railtie.rb +161 -0
  248. data/lib/active_support/reloader.rb +138 -0
  249. data/lib/active_support/rescuable.rb +176 -0
  250. data/lib/active_support/secure_compare_rotator.rb +58 -0
  251. data/lib/active_support/security_utils.rb +38 -0
  252. data/lib/active_support/string_inquirer.rb +35 -0
  253. data/lib/active_support/subscriber.rb +146 -0
  254. data/lib/active_support/syntax_error_proxy.rb +60 -0
  255. data/lib/active_support/tagged_logging.rb +152 -0
  256. data/lib/active_support/test_case.rb +304 -0
  257. data/lib/active_support/testing/assertions.rb +332 -0
  258. data/lib/active_support/testing/autorun.rb +5 -0
  259. data/lib/active_support/testing/constant_lookup.rb +51 -0
  260. data/lib/active_support/testing/constant_stubbing.rb +54 -0
  261. data/lib/active_support/testing/declarative.rb +28 -0
  262. data/lib/active_support/testing/deprecation.rb +82 -0
  263. data/lib/active_support/testing/error_reporter_assertions.rb +107 -0
  264. data/lib/active_support/testing/file_fixtures.rb +38 -0
  265. data/lib/active_support/testing/isolation.rb +121 -0
  266. data/lib/active_support/testing/method_call_assertions.rb +69 -0
  267. data/lib/active_support/testing/parallelization/server.rb +85 -0
  268. data/lib/active_support/testing/parallelization/worker.rb +103 -0
  269. data/lib/active_support/testing/parallelization.rb +55 -0
  270. data/lib/active_support/testing/parallelize_executor.rb +81 -0
  271. data/lib/active_support/testing/setup_and_teardown.rb +57 -0
  272. data/lib/active_support/testing/stream.rb +41 -0
  273. data/lib/active_support/testing/strict_warnings.rb +43 -0
  274. data/lib/active_support/testing/tagged_logging.rb +27 -0
  275. data/lib/active_support/testing/tests_without_assertions.rb +19 -0
  276. data/lib/active_support/testing/time_helpers.rb +269 -0
  277. data/lib/active_support/time.rb +20 -0
  278. data/lib/active_support/time_with_zone.rb +609 -0
  279. data/lib/active_support/values/time_zone.rb +614 -0
  280. data/lib/active_support/version.rb +10 -0
  281. data/lib/active_support/xml_mini/jdom.rb +175 -0
  282. data/lib/active_support/xml_mini/libxml.rb +80 -0
  283. data/lib/active_support/xml_mini/libxmlsax.rb +83 -0
  284. data/lib/active_support/xml_mini/nokogiri.rb +83 -0
  285. data/lib/active_support/xml_mini/nokogirisax.rb +86 -0
  286. data/lib/active_support/xml_mini/rexml.rb +137 -0
  287. data/lib/active_support/xml_mini.rb +211 -0
  288. data/lib/active_support.rb +144 -0
  289. metadata +526 -0
@@ -0,0 +1,492 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ gem "redis", ">= 4.0.1"
5
+ require "redis"
6
+ require "redis/distributed"
7
+ rescue LoadError
8
+ warn "The Redis cache store requires the redis gem, version 4.0.1 or later. Please add it to your Gemfile: `gem \"redis\", \">= 4.0.1\"`"
9
+ raise
10
+ end
11
+
12
+ require "connection_pool"
13
+ require "active_support/core_ext/array/wrap"
14
+ require "active_support/core_ext/hash/slice"
15
+ require "active_support/core_ext/numeric/time"
16
+ require "active_support/digest"
17
+
18
+ module ActiveSupport
19
+ module Cache
20
+ # = Redis \Cache \Store
21
+ #
22
+ # Deployment note: Take care to use a <b>dedicated Redis cache</b> rather
23
+ # than pointing this at a persistent Redis server (for example, one used as
24
+ # an Active Job queue). Redis won't cope well with mixed usage patterns and it
25
+ # won't expire cache entries by default.
26
+ #
27
+ # Redis cache server setup guide: https://redis.io/topics/lru-cache
28
+ #
29
+ # * Supports vanilla Redis, hiredis, and +Redis::Distributed+.
30
+ # * Supports Memcached-like sharding across Redises with +Redis::Distributed+.
31
+ # * Fault tolerant. If the Redis server is unavailable, no exceptions are
32
+ # raised. Cache fetches are all misses and writes are dropped.
33
+ # * Local cache. Hot in-memory primary cache within block/middleware scope.
34
+ # * +read_multi+ and +write_multi+ support for Redis mget/mset. Use
35
+ # +Redis::Distributed+ 4.0.1+ for distributed mget support.
36
+ # * +delete_matched+ support for Redis KEYS globs.
37
+ class RedisCacheStore < Store
38
+ # Keys are truncated with the Active Support digest if they exceed 1kB
39
+ MAX_KEY_BYTESIZE = 1024
40
+
41
+ DEFAULT_REDIS_OPTIONS = {
42
+ connect_timeout: 1,
43
+ read_timeout: 1,
44
+ write_timeout: 1,
45
+ }
46
+
47
+ DEFAULT_ERROR_HANDLER = -> (method:, returning:, exception:) do
48
+ if logger
49
+ logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" }
50
+ end
51
+ ActiveSupport.error_reporter&.report(
52
+ exception,
53
+ severity: :warning,
54
+ source: "redis_cache_store.active_support",
55
+ )
56
+ end
57
+
58
+ # The maximum number of entries to receive per SCAN call.
59
+ SCAN_BATCH_SIZE = 1000
60
+ private_constant :SCAN_BATCH_SIZE
61
+
62
+ # Advertise cache versioning support.
63
+ def self.supports_cache_versioning?
64
+ true
65
+ end
66
+
67
+ prepend Strategy::LocalCache
68
+
69
+ class << self
70
+ # Factory method to create a new Redis instance.
71
+ #
72
+ # Handles four options: :redis block, :redis instance, single :url
73
+ # string, and multiple :url strings.
74
+ #
75
+ # Option Class Result
76
+ # :redis Proc -> options[:redis].call
77
+ # :redis Object -> options[:redis]
78
+ # :url String -> Redis.new(url: …)
79
+ # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …])
80
+ #
81
+ def build_redis(redis: nil, url: nil, **redis_options) # :nodoc:
82
+ urls = Array(url)
83
+
84
+ if redis.is_a?(Proc)
85
+ redis.call
86
+ elsif redis
87
+ redis
88
+ elsif urls.size > 1
89
+ build_redis_distributed_client(urls: urls, **redis_options)
90
+ elsif urls.empty?
91
+ build_redis_client(**redis_options)
92
+ else
93
+ build_redis_client(url: urls.first, **redis_options)
94
+ end
95
+ end
96
+
97
+ private
98
+ def build_redis_distributed_client(urls:, **redis_options)
99
+ ::Redis::Distributed.new([], DEFAULT_REDIS_OPTIONS.merge(redis_options)).tap do |dist|
100
+ urls.each { |u| dist.add_node url: u }
101
+ end
102
+ end
103
+
104
+ def build_redis_client(**redis_options)
105
+ ::Redis.new(DEFAULT_REDIS_OPTIONS.merge(redis_options))
106
+ end
107
+ end
108
+
109
+ attr_reader :max_key_bytesize
110
+ attr_reader :redis
111
+
112
+ # Creates a new Redis cache store.
113
+ #
114
+ # There are four ways to provide the Redis client used by the cache: the
115
+ # +:redis+ param can be a Redis instance or a block that returns a Redis
116
+ # instance, or the +:url+ param can be a string or an array of strings
117
+ # which will be used to create a Redis instance or a +Redis::Distributed+
118
+ # instance.
119
+ #
120
+ # Option Class Result
121
+ # :redis Proc -> options[:redis].call
122
+ # :redis Object -> options[:redis]
123
+ # :url String -> Redis.new(url: …)
124
+ # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …])
125
+ #
126
+ # No namespace is set by default. Provide one if the Redis cache
127
+ # server is shared with other apps: <tt>namespace: 'myapp-cache'</tt>.
128
+ #
129
+ # Compression is enabled by default with a 1kB threshold, so cached
130
+ # values larger than 1kB are automatically compressed. Disable by
131
+ # passing <tt>compress: false</tt> or change the threshold by passing
132
+ # <tt>compress_threshold: 4.kilobytes</tt>.
133
+ #
134
+ # No expiry is set on cache entries by default. Redis is expected to
135
+ # be configured with an eviction policy that automatically deletes
136
+ # least-recently or -frequently used keys when it reaches max memory.
137
+ # See https://redis.io/topics/lru-cache for cache server setup.
138
+ #
139
+ # Race condition TTL is not set by default. This can be used to avoid
140
+ # "thundering herd" cache writes when hot cache entries are expired.
141
+ # See ActiveSupport::Cache::Store#fetch for more.
142
+ #
143
+ # Setting <tt>skip_nil: true</tt> will not cache nil results:
144
+ #
145
+ # cache.fetch('foo') { nil }
146
+ # cache.fetch('bar', skip_nil: true) { nil }
147
+ # cache.exist?('foo') # => true
148
+ # cache.exist?('bar') # => false
149
+ def initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options)
150
+ universal_options = redis_options.extract!(*UNIVERSAL_OPTIONS)
151
+
152
+ if pool_options = self.class.send(:retrieve_pool_options, redis_options)
153
+ @redis = ::ConnectionPool.new(pool_options) { self.class.build_redis(**redis_options) }
154
+ else
155
+ @redis = self.class.build_redis(**redis_options)
156
+ end
157
+
158
+ @max_key_bytesize = MAX_KEY_BYTESIZE
159
+ @error_handler = error_handler
160
+
161
+ super(universal_options)
162
+ end
163
+
164
+ def inspect
165
+ "#<#{self.class} options=#{options.inspect} redis=#{redis.inspect}>"
166
+ end
167
+
168
+ # Cache Store API implementation.
169
+ #
170
+ # Read multiple values at once. Returns a hash of requested keys ->
171
+ # fetched values.
172
+ def read_multi(*names)
173
+ return {} if names.empty?
174
+
175
+ options = names.extract_options!
176
+ options = merged_options(options)
177
+ keys = names.map { |name| normalize_key(name, options) }
178
+
179
+ instrument_multi(:read_multi, keys, options) do |payload|
180
+ read_multi_entries(names, **options).tap do |results|
181
+ payload[:hits] = results.keys.map { |name| normalize_key(name, options) }
182
+ end
183
+ end
184
+ end
185
+
186
+ # Cache Store API implementation.
187
+ #
188
+ # Supports Redis KEYS glob patterns:
189
+ #
190
+ # h?llo matches hello, hallo and hxllo
191
+ # h*llo matches hllo and heeeello
192
+ # h[ae]llo matches hello and hallo, but not hillo
193
+ # h[^e]llo matches hallo, hbllo, ... but not hello
194
+ # h[a-b]llo matches hallo and hbllo
195
+ #
196
+ # Use \ to escape special characters if you want to match them verbatim.
197
+ #
198
+ # See https://redis.io/commands/KEYS for more.
199
+ #
200
+ # Failsafe: Raises errors.
201
+ def delete_matched(matcher, options = nil)
202
+ unless String === matcher
203
+ raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}"
204
+ end
205
+ pattern = namespace_key(matcher, options)
206
+
207
+ instrument :delete_matched, pattern do
208
+ redis.then do |c|
209
+ cursor = "0"
210
+ # Fetch keys in batches using SCAN to avoid blocking the Redis server.
211
+ nodes = c.respond_to?(:nodes) ? c.nodes : [c]
212
+
213
+ nodes.each do |node|
214
+ begin
215
+ cursor, keys = node.scan(cursor, match: pattern, count: SCAN_BATCH_SIZE)
216
+ node.del(*keys) unless keys.empty?
217
+ end until cursor == "0"
218
+ end
219
+ end
220
+ end
221
+ end
222
+
223
+ # Increment a cached integer value using the Redis incrby atomic operator.
224
+ # Returns the updated value.
225
+ #
226
+ # If the key is unset or has expired, it will be set to +amount+:
227
+ #
228
+ # cache.increment("foo") # => 1
229
+ # cache.increment("bar", 100) # => 100
230
+ #
231
+ # To set a specific value, call #write passing <tt>raw: true</tt>:
232
+ #
233
+ # cache.write("baz", 5, raw: true)
234
+ # cache.increment("baz") # => 6
235
+ #
236
+ # Incrementing a non-numeric value, or a value written without
237
+ # <tt>raw: true</tt>, will fail and return +nil+.
238
+ #
239
+ # Failsafe: Raises errors.
240
+ def increment(name, amount = 1, options = nil)
241
+ options = merged_options(options)
242
+ key = normalize_key(name, options)
243
+
244
+ instrument :increment, key, amount: amount do
245
+ failsafe :increment do
246
+ change_counter(key, amount, options)
247
+ end
248
+ end
249
+ end
250
+
251
+ # Decrement a cached integer value using the Redis decrby atomic operator.
252
+ # Returns the updated value.
253
+ #
254
+ # If the key is unset or has expired, it will be set to +-amount+:
255
+ #
256
+ # cache.decrement("foo") # => -1
257
+ #
258
+ # To set a specific value, call #write passing <tt>raw: true</tt>:
259
+ #
260
+ # cache.write("baz", 5, raw: true)
261
+ # cache.decrement("baz") # => 4
262
+ #
263
+ # Decrementing a non-numeric value, or a value written without
264
+ # <tt>raw: true</tt>, will fail and return +nil+.
265
+ #
266
+ # Failsafe: Raises errors.
267
+ def decrement(name, amount = 1, options = nil)
268
+ options = merged_options(options)
269
+ key = normalize_key(name, options)
270
+
271
+ instrument :decrement, key, amount: amount do
272
+ failsafe :decrement do
273
+ change_counter(key, -amount, options)
274
+ end
275
+ end
276
+ end
277
+
278
+ # Cache Store API implementation.
279
+ #
280
+ # Removes expired entries. Handled natively by Redis least-recently-/
281
+ # least-frequently-used expiry, so manual cleanup is not supported.
282
+ def cleanup(options = nil)
283
+ super
284
+ end
285
+
286
+ # Clear the entire cache on all Redis servers. Safe to use on
287
+ # shared servers if the cache is namespaced.
288
+ #
289
+ # Failsafe: Raises errors.
290
+ def clear(options = nil)
291
+ failsafe :clear do
292
+ if namespace = merged_options(options)[:namespace]
293
+ delete_matched "*", namespace: namespace
294
+ else
295
+ redis.then { |c| c.flushdb }
296
+ end
297
+ end
298
+ end
299
+
300
+ # Get info from redis servers.
301
+ def stats
302
+ redis.then { |c| c.info }
303
+ end
304
+
305
+ private
306
+ def pipeline_entries(entries, &block)
307
+ redis.then { |c|
308
+ if c.is_a?(Redis::Distributed)
309
+ entries.group_by { |k, _v| c.node_for(k) }.each do |node, sub_entries|
310
+ node.pipelined { |pipe| yield(pipe, sub_entries) }
311
+ end
312
+ else
313
+ c.pipelined { |pipe| yield(pipe, entries) }
314
+ end
315
+ }
316
+ end
317
+
318
+ # Store provider interface:
319
+ # Read an entry from the cache.
320
+ def read_entry(key, **options)
321
+ deserialize_entry(read_serialized_entry(key, **options), **options)
322
+ end
323
+
324
+ def read_serialized_entry(key, raw: false, **options)
325
+ failsafe :read_entry do
326
+ redis.then { |c| c.get(key) }
327
+ end
328
+ end
329
+
330
+ def read_multi_entries(names, **options)
331
+ options = merged_options(options)
332
+ return {} if names == []
333
+ raw = options&.fetch(:raw, false)
334
+
335
+ keys = names.map { |name| normalize_key(name, options) }
336
+
337
+ values = failsafe(:read_multi_entries, returning: {}) do
338
+ redis.then { |c| c.mget(*keys) }
339
+ end
340
+
341
+ names.zip(values).each_with_object({}) do |(name, value), results|
342
+ if value
343
+ entry = deserialize_entry(value, raw: raw)
344
+ unless entry.nil? || entry.expired? || entry.mismatched?(normalize_version(name, options))
345
+ begin
346
+ results[name] = entry.value
347
+ rescue DeserializationError
348
+ end
349
+ end
350
+ end
351
+ end
352
+ end
353
+
354
+ # Write an entry to the cache.
355
+ #
356
+ # Requires Redis 2.6.12+ for extended SET options.
357
+ def write_entry(key, entry, raw: false, **options)
358
+ write_serialized_entry(key, serialize_entry(entry, raw: raw, **options), raw: raw, **options)
359
+ end
360
+
361
+ def write_serialized_entry(key, payload, raw: false, unless_exist: false, expires_in: nil, race_condition_ttl: nil, pipeline: nil, **options)
362
+ # If race condition TTL is in use, ensure that cache entries
363
+ # stick around a bit longer after they would have expired
364
+ # so we can purposefully serve stale entries.
365
+ if race_condition_ttl && expires_in && expires_in > 0 && !raw
366
+ expires_in += 5.minutes
367
+ end
368
+
369
+ modifiers = {}
370
+ if unless_exist || expires_in
371
+ modifiers[:nx] = unless_exist
372
+ modifiers[:px] = (1000 * expires_in.to_f).ceil if expires_in
373
+ end
374
+
375
+ if pipeline
376
+ pipeline.set(key, payload, **modifiers)
377
+ else
378
+ failsafe :write_entry, returning: nil do
379
+ redis.then { |c| !!c.set(key, payload, **modifiers) }
380
+ end
381
+ end
382
+ end
383
+
384
+ # Delete an entry from the cache.
385
+ def delete_entry(key, **options)
386
+ failsafe :delete_entry, returning: false do
387
+ redis.then { |c| c.del(key) == 1 }
388
+ end
389
+ end
390
+
391
+ # Deletes multiple entries in the cache. Returns the number of entries deleted.
392
+ def delete_multi_entries(entries, **_options)
393
+ failsafe :delete_multi_entries, returning: 0 do
394
+ redis.then { |c| c.del(entries) }
395
+ end
396
+ end
397
+
398
+ # Nonstandard store provider API to write multiple values at once.
399
+ def write_multi_entries(entries, **options)
400
+ return if entries.empty?
401
+
402
+ failsafe :write_multi_entries do
403
+ pipeline_entries(entries) do |pipeline, sharded_entries|
404
+ options = options.dup
405
+ options[:pipeline] = pipeline
406
+ sharded_entries.each do |key, entry|
407
+ write_entry key, entry, **options
408
+ end
409
+ end
410
+ end
411
+ end
412
+
413
+ # Truncate keys that exceed 1kB.
414
+ def normalize_key(key, options)
415
+ truncate_key super&.b
416
+ end
417
+
418
+ def truncate_key(key)
419
+ if key && key.bytesize > max_key_bytesize
420
+ suffix = ":hash:#{ActiveSupport::Digest.hexdigest(key)}"
421
+ truncate_at = max_key_bytesize - suffix.bytesize
422
+ "#{key.byteslice(0, truncate_at)}#{suffix}"
423
+ else
424
+ key
425
+ end
426
+ end
427
+
428
+ def deserialize_entry(payload, raw: false, **)
429
+ if raw && !payload.nil?
430
+ Entry.new(payload)
431
+ else
432
+ super(payload)
433
+ end
434
+ end
435
+
436
+ def serialize_entry(entry, raw: false, **options)
437
+ if raw
438
+ entry.value.to_s
439
+ else
440
+ super(entry, raw: raw, **options)
441
+ end
442
+ end
443
+
444
+ def serialize_entries(entries, **options)
445
+ entries.transform_values do |entry|
446
+ serialize_entry(entry, **options)
447
+ end
448
+ end
449
+
450
+ def change_counter(key, amount, options)
451
+ redis.then do |c|
452
+ c = c.node_for(key) if c.is_a?(Redis::Distributed)
453
+
454
+ expires_in = options[:expires_in]
455
+
456
+ if expires_in
457
+ if supports_expire_nx?
458
+ count, _ = c.pipelined do |pipeline|
459
+ pipeline.incrby(key, amount)
460
+ pipeline.call(:expire, key, expires_in.to_i, "NX")
461
+ end
462
+ else
463
+ count, ttl = c.pipelined do |pipeline|
464
+ pipeline.incrby(key, amount)
465
+ pipeline.ttl(key)
466
+ end
467
+ c.expire(key, expires_in.to_i) if ttl < 0
468
+ end
469
+ else
470
+ count = c.incrby(key, amount)
471
+ end
472
+
473
+ count
474
+ end
475
+ end
476
+
477
+ def supports_expire_nx?
478
+ return @supports_expire_nx if defined?(@supports_expire_nx)
479
+
480
+ redis_versions = redis.then { |c| Array.wrap(c.info("server")).pluck("redis_version") }
481
+ @supports_expire_nx = redis_versions.all? { |v| Gem::Version.new(v) >= Gem::Version.new("7.0.0") }
482
+ end
483
+
484
+ def failsafe(method, returning: nil)
485
+ yield
486
+ rescue ::Redis::BaseError => error
487
+ @error_handler&.call(method: method, exception: error, returning: returning)
488
+ returning
489
+ end
490
+ end
491
+ end
492
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zlib"
4
+ require "active_support/core_ext/kernel/reporting"
5
+
6
+ module ActiveSupport
7
+ module Cache
8
+ module SerializerWithFallback # :nodoc:
9
+ def self.[](format)
10
+ if format.to_s.include?("message_pack") && !defined?(ActiveSupport::MessagePack)
11
+ require "active_support/message_pack"
12
+ end
13
+
14
+ SERIALIZERS.fetch(format)
15
+ end
16
+
17
+ def load(dumped)
18
+ if dumped.is_a?(String)
19
+ case
20
+ when MessagePackWithFallback.dumped?(dumped)
21
+ MessagePackWithFallback._load(dumped)
22
+ when Marshal71WithFallback.dumped?(dumped)
23
+ Marshal71WithFallback._load(dumped)
24
+ when Marshal70WithFallback.dumped?(dumped)
25
+ Marshal70WithFallback._load(dumped)
26
+ else
27
+ Cache::Store.logger&.warn("Unrecognized payload prefix #{dumped.byteslice(0).inspect}; deserializing as nil")
28
+ nil
29
+ end
30
+ elsif PassthroughWithFallback.dumped?(dumped)
31
+ PassthroughWithFallback._load(dumped)
32
+ else
33
+ Cache::Store.logger&.warn("Unrecognized payload class #{dumped.class}; deserializing as nil")
34
+ nil
35
+ end
36
+ end
37
+
38
+ private
39
+ def marshal_load(payload)
40
+ Marshal.load(payload)
41
+ rescue ArgumentError => error
42
+ raise Cache::DeserializationError, error.message
43
+ end
44
+
45
+ module PassthroughWithFallback
46
+ include SerializerWithFallback
47
+ extend self
48
+
49
+ def dump(entry)
50
+ entry
51
+ end
52
+
53
+ def dump_compressed(entry, threshold)
54
+ entry.compressed(threshold)
55
+ end
56
+
57
+ def _load(entry)
58
+ entry
59
+ end
60
+
61
+ def dumped?(dumped)
62
+ dumped.is_a?(Cache::Entry)
63
+ end
64
+ end
65
+
66
+ module Marshal70WithFallback
67
+ include SerializerWithFallback
68
+ extend self
69
+
70
+ MARK_UNCOMPRESSED = "\x00".b.freeze
71
+ MARK_COMPRESSED = "\x01".b.freeze
72
+
73
+ def dump(entry)
74
+ MARK_UNCOMPRESSED + Marshal.dump(entry.pack)
75
+ end
76
+
77
+ def dump_compressed(entry, threshold)
78
+ dumped = Marshal.dump(entry.pack)
79
+
80
+ if dumped.bytesize >= threshold
81
+ compressed = Zlib::Deflate.deflate(dumped)
82
+ return MARK_COMPRESSED + compressed if compressed.bytesize < dumped.bytesize
83
+ end
84
+
85
+ MARK_UNCOMPRESSED + dumped
86
+ end
87
+
88
+ def _load(marked)
89
+ dumped = marked.byteslice(1..-1)
90
+ dumped = Zlib::Inflate.inflate(dumped) if marked.start_with?(MARK_COMPRESSED)
91
+ Cache::Entry.unpack(marshal_load(dumped))
92
+ end
93
+
94
+ def dumped?(dumped)
95
+ dumped.start_with?(MARK_UNCOMPRESSED, MARK_COMPRESSED)
96
+ end
97
+ end
98
+
99
+ module Marshal71WithFallback
100
+ include SerializerWithFallback
101
+ extend self
102
+
103
+ MARSHAL_SIGNATURE = "\x04\x08".b.freeze
104
+
105
+ def dump(value)
106
+ Marshal.dump(value)
107
+ end
108
+
109
+ def _load(dumped)
110
+ marshal_load(dumped)
111
+ end
112
+
113
+ def dumped?(dumped)
114
+ dumped.start_with?(MARSHAL_SIGNATURE)
115
+ end
116
+ end
117
+
118
+ module MessagePackWithFallback
119
+ include SerializerWithFallback
120
+ extend self
121
+
122
+ def dump(value)
123
+ ActiveSupport::MessagePack::CacheSerializer.dump(value)
124
+ end
125
+
126
+ def _load(dumped)
127
+ ActiveSupport::MessagePack::CacheSerializer.load(dumped)
128
+ end
129
+
130
+ def dumped?(dumped)
131
+ available? && ActiveSupport::MessagePack.signature?(dumped)
132
+ end
133
+
134
+ private
135
+ def available?
136
+ return @available if defined?(@available)
137
+ silence_warnings { require "active_support/message_pack" }
138
+ @available = true
139
+ rescue LoadError
140
+ @available = false
141
+ end
142
+ end
143
+
144
+ SERIALIZERS = {
145
+ passthrough: PassthroughWithFallback,
146
+ marshal_7_0: Marshal70WithFallback,
147
+ marshal_7_1: Marshal71WithFallback,
148
+ message_pack: MessagePackWithFallback,
149
+ }
150
+ end
151
+ end
152
+ end