safe_memoize 0.8.0 → 1.0.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.
- checksums.yaml +4 -4
- data/.yardopts +10 -0
- data/CHANGELOG.md +23 -0
- data/README.md +555 -8
- data/ROADMAP.md +7 -22
- data/Rakefile +5 -0
- data/UPGRADING.md +197 -0
- data/benchmarks/README.md +68 -0
- data/benchmarks/benchmark.rb +225 -0
- data/codecov.yml +17 -0
- data/lib/safe_memoize/adapters/opentelemetry.rb +44 -0
- data/lib/safe_memoize/adapters/statsd.rb +56 -0
- data/lib/safe_memoize/cache_metrics_methods.rb +1 -0
- data/lib/safe_memoize/cache_record_methods.rb +1 -0
- data/lib/safe_memoize/cache_store_methods.rb +1 -0
- data/lib/safe_memoize/class_methods.rb +106 -21
- data/lib/safe_memoize/configuration.rb +43 -1
- data/lib/safe_memoize/custom_key_methods.rb +1 -0
- data/lib/safe_memoize/hooks_methods.rb +31 -0
- data/lib/safe_memoize/inspection_methods.rb +2 -1
- data/lib/safe_memoize/instance_methods.rb +1 -0
- data/lib/safe_memoize/lru_methods.rb +1 -0
- data/lib/safe_memoize/public_custom_key_methods.rb +23 -0
- data/lib/safe_memoize/public_methods.rb +162 -5
- data/lib/safe_memoize/public_metrics_methods.rb +20 -0
- data/lib/safe_memoize/rails/middleware.rb +25 -0
- data/lib/safe_memoize/rails/request_scoped.rb +40 -0
- data/lib/safe_memoize/rails.rb +28 -0
- data/lib/safe_memoize/release_tooling.rb +1 -0
- data/lib/safe_memoize/version.rb +2 -1
- data/lib/safe_memoize.rb +56 -0
- data/rbi/safe_memoize.rbi +245 -0
- data/sig/safe_memoize.rbs +41 -5
- metadata +12 -1
data/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Beyond the basics, SafeMemoize ships with TTL expiration (including sliding wind
|
|
|
14
14
|
|
|
15
15
|
## The Problem
|
|
16
16
|
|
|
17
|
-
Ruby's common memoization pattern breaks with falsy values:
|
|
17
|
+
Ruby's common memoization pattern breaks with falsy values:
|
|
18
18
|
|
|
19
19
|
```ruby
|
|
20
20
|
def user
|
|
@@ -51,6 +51,22 @@ SafeMemoize uses Ruby's `prepend` mechanism. When you call `memoize :method_name
|
|
|
51
51
|
- [Bulk memoization via `memoize_all` (public, protected, and private)](#bulk-memoization)
|
|
52
52
|
- [Custom cache key generation per method](#custom-cache-keys)
|
|
53
53
|
- [TTL introspection via `memo_ttl_remaining`](#cache-inspection)
|
|
54
|
+
- [Deep single-entry inspection via `memo_inspect`](#cache-inspection)
|
|
55
|
+
- [`ArgumentError` at definition time when memoizing an undefined method](#basic-memoization)
|
|
56
|
+
- [Hook error isolation — hook exceptions never propagate to callers](#lifecycle-hooks)
|
|
57
|
+
- [Deprecation infrastructure for gem authors](#deprecation)
|
|
58
|
+
- [Optional `ActiveSupport::Notifications` integration for Rails observability](#activesupportnotifications)
|
|
59
|
+
- [Optional StatsD adapter for metrics pipelines](#statsd)
|
|
60
|
+
- [Optional OpenTelemetry adapter for distributed tracing](#opentelemetry)
|
|
61
|
+
- [Rails request-scope helpers for controllers and service objects](#rails-request-scope)
|
|
62
|
+
- [Batch cache warm-up via `memo_preload`](#cache-warm-up-and-persistence)
|
|
63
|
+
- [`on_memo_store` hook fires on every cache write](#lifecycle-hooks)
|
|
64
|
+
- [Global default TTL and max size via `SafeMemoize.configure`](#global-configuration)
|
|
65
|
+
- [`memo_touch` resets the expiry clock without recomputing](#ttl-expiration)
|
|
66
|
+
- [`memo_refresh` force-recomputes and re-caches in one call](#cache-inspection)
|
|
67
|
+
- [`memo_age` and `memo_stale?` for TTL introspection](#cache-inspection)
|
|
68
|
+
- [Class-level `key:` option for shared cache key generation](#custom-cache-keys)
|
|
69
|
+
- [`shared_memo_age` and `shared_memo_stale?` for shared cache TTL inspection](#shared-cache)
|
|
54
70
|
|
|
55
71
|
## Installation
|
|
56
72
|
|
|
@@ -88,6 +104,10 @@ class UserService
|
|
|
88
104
|
end
|
|
89
105
|
```
|
|
90
106
|
|
|
107
|
+
Calling `memoize` on a method name that does not exist raises `ArgumentError` immediately at class definition time rather than at the first runtime call.
|
|
108
|
+
|
|
109
|
+
[↑ Back to features](#features)
|
|
110
|
+
|
|
91
111
|
### With arguments
|
|
92
112
|
|
|
93
113
|
Results are cached per unique argument combination:
|
|
@@ -109,6 +129,10 @@ calc.compute(1, 2) # returns cached result
|
|
|
109
129
|
calc.compute(3, 4) # computes and caches (different args)
|
|
110
130
|
```
|
|
111
131
|
|
|
132
|
+
Argument arrays, hashes, and strings are deep-frozen into an independent copy when the cache key is built, so mutating arguments after a call cannot corrupt or miss a cached entry.
|
|
133
|
+
|
|
134
|
+
[↑ Back to features](#features)
|
|
135
|
+
|
|
112
136
|
### Nil and false safety
|
|
113
137
|
|
|
114
138
|
```ruby
|
|
@@ -123,6 +147,8 @@ class Config
|
|
|
123
147
|
end
|
|
124
148
|
```
|
|
125
149
|
|
|
150
|
+
[↑ Back to features](#features)
|
|
151
|
+
|
|
126
152
|
### Works with private methods
|
|
127
153
|
|
|
128
154
|
```ruby
|
|
@@ -142,6 +168,8 @@ class TokenProvider
|
|
|
142
168
|
end
|
|
143
169
|
```
|
|
144
170
|
|
|
171
|
+
[↑ Back to features](#features)
|
|
172
|
+
|
|
145
173
|
### Cache reset
|
|
146
174
|
|
|
147
175
|
```ruby
|
|
@@ -152,6 +180,8 @@ obj.reset_memo(:search, "ruby", page: 2) # Clears one positional/keyword c
|
|
|
152
180
|
obj.reset_all_memos # Clears all memoized values
|
|
153
181
|
```
|
|
154
182
|
|
|
183
|
+
[↑ Back to features](#features)
|
|
184
|
+
|
|
155
185
|
### Lifecycle hooks
|
|
156
186
|
|
|
157
187
|
Register callbacks that fire when cached entries are evicted or expire.
|
|
@@ -188,6 +218,14 @@ obj.on_memo_expire do |cache_key, record|
|
|
|
188
218
|
end
|
|
189
219
|
```
|
|
190
220
|
|
|
221
|
+
**`on_memo_store`** fires whenever a value is written to the cache — on a miss, via `warm_memo`, or via `load_memo`:
|
|
222
|
+
|
|
223
|
+
```ruby
|
|
224
|
+
obj.on_memo_store do |cache_key, record|
|
|
225
|
+
Rails.logger.debug("Stored #{cache_key[0]}: #{record[:value].inspect}")
|
|
226
|
+
end
|
|
227
|
+
```
|
|
228
|
+
|
|
191
229
|
Multiple hooks of the same type can be registered and all will fire. Remove them with `clear_memo_hooks`:
|
|
192
230
|
|
|
193
231
|
```ruby
|
|
@@ -200,6 +238,28 @@ obj.clear_memo_hooks # Clears all hooks
|
|
|
200
238
|
|
|
201
239
|
Hooks are per-instance and do not affect other objects of the same class.
|
|
202
240
|
|
|
241
|
+
#### Hook error isolation
|
|
242
|
+
|
|
243
|
+
Exceptions raised inside a hook never propagate to the caller. By default a warning is emitted to stderr:
|
|
244
|
+
|
|
245
|
+
```
|
|
246
|
+
[SafeMemoize] Hook error in on_miss: undefined method `log' for nil
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Configure a custom handler via `SafeMemoize.configure`:
|
|
250
|
+
|
|
251
|
+
```ruby
|
|
252
|
+
SafeMemoize.configure do |c|
|
|
253
|
+
c.on_hook_error = ->(error, hook_type, cache_key) {
|
|
254
|
+
MyErrorTracker.capture(error, context: { hook: hook_type, key: cache_key })
|
|
255
|
+
}
|
|
256
|
+
end
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Set `c.on_hook_error = :raise` to re-raise exceptions instead of swallowing them.
|
|
260
|
+
|
|
261
|
+
[↑ Back to features](#features)
|
|
262
|
+
|
|
203
263
|
### TTL expiration
|
|
204
264
|
|
|
205
265
|
```ruby
|
|
@@ -215,6 +275,23 @@ end
|
|
|
215
275
|
|
|
216
276
|
With a TTL, cached values expire automatically after the given number of seconds. The next call recomputes and refreshes the cache.
|
|
217
277
|
|
|
278
|
+
Use `memo_touch` to reset the expiry clock on a cached entry without recomputing its value:
|
|
279
|
+
|
|
280
|
+
```ruby
|
|
281
|
+
obj.memo_touch(:current_quote) # Resets TTL to the original duration
|
|
282
|
+
obj.memo_touch(:current_quote, ttl: 120) # Resets TTL to a new duration
|
|
283
|
+
# => true on success, false if the entry is not cached or already expired
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Use `memo_refresh` to force-recompute a cached entry immediately and store the new value:
|
|
287
|
+
|
|
288
|
+
```ruby
|
|
289
|
+
obj.memo_refresh(:current_quote) # Recomputes and re-caches
|
|
290
|
+
obj.memo_refresh(:find, 42) # Recomputes for one argument combination
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
[↑ Back to features](#features)
|
|
294
|
+
|
|
218
295
|
### Sliding window TTL
|
|
219
296
|
|
|
220
297
|
Add `ttl_refresh: true` to reset the expiry clock on every cache hit, so the entry only expires after a full TTL of inactivity:
|
|
@@ -232,6 +309,8 @@ end
|
|
|
232
309
|
|
|
233
310
|
Without `ttl_refresh:`, the entry expires 300 seconds after it was first cached. With it, the clock resets on every read — the entry is evicted only if the method goes 300 seconds without being called. `ttl_refresh: true` requires `ttl:` to be set and works with both per-instance and `shared: true` memoization.
|
|
234
311
|
|
|
312
|
+
[↑ Back to features](#features)
|
|
313
|
+
|
|
235
314
|
### LRU cache size limit
|
|
236
315
|
|
|
237
316
|
Pass `max_size:` to cap how many entries a method can hold. When the limit is reached the least-recently-used entry is evicted to make room:
|
|
@@ -265,6 +344,8 @@ memoize :find, max_size: 50, ttl: 300
|
|
|
265
344
|
|
|
266
345
|
The `on_evict` hook fires for LRU-evicted entries the same way it does for manual `reset_memo` calls.
|
|
267
346
|
|
|
347
|
+
[↑ Back to features](#features)
|
|
348
|
+
|
|
268
349
|
### Conditional caching
|
|
269
350
|
|
|
270
351
|
Use `if:` to cache a result only when the predicate returns truthy, or `unless:` to skip caching when it returns truthy. Calls that don't satisfy the condition recompute every time until they do.
|
|
@@ -299,8 +380,25 @@ Both options accept any callable and compose with `ttl:` and `max_size:`:
|
|
|
299
380
|
memoize :find, if: ->(result) { !result.nil? }, ttl: 60, max_size: 500
|
|
300
381
|
```
|
|
301
382
|
|
|
383
|
+
[↑ Back to features](#features)
|
|
384
|
+
|
|
302
385
|
### Cache warm-up and persistence
|
|
303
386
|
|
|
387
|
+
#### Batch warm-up via `memo_preload`
|
|
388
|
+
|
|
389
|
+
Use `memo_preload` to warm multiple argument combinations in one call. It calls the memoized method for each argument set, caches all results, and returns them in input order:
|
|
390
|
+
|
|
391
|
+
```ruby
|
|
392
|
+
obj.memo_preload(:find, [1], [2], [3])
|
|
393
|
+
# => [<User id=1>, <User id=2>, <User id=3>]
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
Each element is a separate argument list passed to the method, so keyword arguments work too:
|
|
397
|
+
|
|
398
|
+
```ruby
|
|
399
|
+
obj.memo_preload(:search, ["ruby"], ["rails"], ["rspec"])
|
|
400
|
+
```
|
|
401
|
+
|
|
304
402
|
#### Warming individual entries
|
|
305
403
|
|
|
306
404
|
Use `warm_memo` to pre-populate a cache entry without calling the method. The block provides the value:
|
|
@@ -348,6 +446,8 @@ obj.load_memo(Marshal.load(raw)) if raw
|
|
|
348
446
|
|
|
349
447
|
Loaded entries have no TTL — they persist until explicitly reset. Expired entries are excluded from `dump_memo` output, so snapshots never contain stale data.
|
|
350
448
|
|
|
449
|
+
[↑ Back to features](#features)
|
|
450
|
+
|
|
351
451
|
### Shared cache
|
|
352
452
|
|
|
353
453
|
Pass `shared: true` to store results on the class instead of per-instance. All instances share one cache, so the method is computed only once regardless of how many objects exist.
|
|
@@ -382,6 +482,8 @@ ConfigService.shared_memoized?(:database_url) # => true
|
|
|
382
482
|
ConfigService.shared_memoized?(:find, user_id) # Checks one argument combination
|
|
383
483
|
ConfigService.shared_memo_count # Total shared cached entries
|
|
384
484
|
ConfigService.shared_memo_count(:find) # Entries for one method
|
|
485
|
+
ConfigService.shared_memo_age(:feature_flags) # => 42.1 (seconds since cached)
|
|
486
|
+
ConfigService.shared_memo_stale?(:feature_flags) # => false (TTL not yet elapsed)
|
|
385
487
|
```
|
|
386
488
|
|
|
387
489
|
`shared: true` supports `ttl:`, `ttl_refresh:`, `if:`, `unless:`, and `max_size:` options.
|
|
@@ -394,6 +496,8 @@ memoize :find, shared: true, max_size: 500
|
|
|
394
496
|
|
|
395
497
|
Hooks (`on_memo_hit`, `on_memo_miss`, `on_memo_expire`, `on_memo_evict`) fire on the calling instance as usual.
|
|
396
498
|
|
|
499
|
+
[↑ Back to features](#features)
|
|
500
|
+
|
|
397
501
|
### Bulk memoization
|
|
398
502
|
|
|
399
503
|
Use `memoize_all` to memoize every public method defined on the class in one call:
|
|
@@ -432,6 +536,14 @@ Use `except:` to skip specific methods:
|
|
|
432
536
|
memoize_all except: [:version, :name]
|
|
433
537
|
```
|
|
434
538
|
|
|
539
|
+
Use `only:` to explicitly list the methods to memoize and skip all others:
|
|
540
|
+
|
|
541
|
+
```ruby
|
|
542
|
+
memoize_all only: [:database_url, :redis_url]
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
`only:` and `except:` are mutually exclusive — passing both raises `ArgumentError`.
|
|
546
|
+
|
|
435
547
|
By default only public methods defined directly on the class are memoized. Use `include_protected:` or `include_private:` to opt those visibilities in:
|
|
436
548
|
|
|
437
549
|
```ruby
|
|
@@ -442,9 +554,11 @@ memoize_all include_protected: true, include_private: true
|
|
|
442
554
|
|
|
443
555
|
Inherited methods are never affected regardless of visibility.
|
|
444
556
|
|
|
557
|
+
[↑ Back to features](#features)
|
|
558
|
+
|
|
445
559
|
### Custom cache keys
|
|
446
560
|
|
|
447
|
-
By default the cache key is derived from the method name and all arguments. Use `
|
|
561
|
+
By default the cache key is derived from the method name and all arguments. Use the `key:` option on `memoize` to set a class-level key generator that applies to every instance:
|
|
448
562
|
|
|
449
563
|
```ruby
|
|
450
564
|
class ReportService
|
|
@@ -453,9 +567,18 @@ class ReportService
|
|
|
453
567
|
def generate(user_id, options)
|
|
454
568
|
build_report(user_id, options)
|
|
455
569
|
end
|
|
456
|
-
memoize :generate
|
|
570
|
+
memoize :generate, key: ->(user_id, _options) { user_id }
|
|
457
571
|
end
|
|
458
572
|
|
|
573
|
+
# All instances share the same key logic — calls with the same user_id share one cache entry
|
|
574
|
+
svc = ReportService.new
|
|
575
|
+
svc.generate(42, {format: :pdf}) # computes and caches under key 42
|
|
576
|
+
svc.generate(42, {format: :csv}) # cache hit — same key
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
For per-instance key overrides, use `memoize_with_custom_key` on an instance (takes priority over the class-level `key:` option):
|
|
580
|
+
|
|
581
|
+
```ruby
|
|
459
582
|
svc = ReportService.new
|
|
460
583
|
|
|
461
584
|
# Cache only by user_id — ignore the options hash entirely
|
|
@@ -480,6 +603,8 @@ svc.clear_custom_keys(:generate) # Remove generator for one method
|
|
|
480
603
|
svc.clear_custom_keys # Remove all custom key generators
|
|
481
604
|
```
|
|
482
605
|
|
|
606
|
+
[↑ Back to features](#features)
|
|
607
|
+
|
|
483
608
|
### Cache inspection
|
|
484
609
|
|
|
485
610
|
```ruby
|
|
@@ -500,8 +625,32 @@ obj.memo_values(:search) # Cached signatures and values for one
|
|
|
500
625
|
obj.memo_ttl_remaining(:current_quote) # => 47.231 (seconds until expiry)
|
|
501
626
|
obj.memo_ttl_remaining(:current_user) # => nil (no TTL set)
|
|
502
627
|
obj.memo_ttl_remaining(:find, 42) # => 0 (not cached or already expired)
|
|
628
|
+
|
|
629
|
+
obj.memo_age(:current_quote) # => 12.8 (seconds since cached; nil if not cached)
|
|
630
|
+
obj.memo_stale?(:current_quote) # => false (cached but TTL not yet elapsed)
|
|
631
|
+
obj.memo_stale?(:current_user) # => false (no TTL — never stale)
|
|
503
632
|
```
|
|
504
633
|
|
|
634
|
+
`memo_inspect` returns all metadata for one cached entry in a single mutex-held read:
|
|
635
|
+
|
|
636
|
+
```ruby
|
|
637
|
+
obj.memo_inspect(:find, 42)
|
|
638
|
+
# => {
|
|
639
|
+
# cached: true,
|
|
640
|
+
# value: <result>,
|
|
641
|
+
# hits: 5,
|
|
642
|
+
# misses: 1,
|
|
643
|
+
# ttl_remaining: 47.2,
|
|
644
|
+
# age: 12.8,
|
|
645
|
+
# custom_key: nil,
|
|
646
|
+
# lru_position: 1
|
|
647
|
+
# }
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
Returns `nil` when the entry is not cached.
|
|
651
|
+
|
|
652
|
+
[↑ Back to features](#features)
|
|
653
|
+
|
|
505
654
|
### Cache metrics
|
|
506
655
|
|
|
507
656
|
Each instance tracks hits, misses, and computation time automatically.
|
|
@@ -521,18 +670,251 @@ obj.cache_stats
|
|
|
521
670
|
# ]
|
|
522
671
|
# }
|
|
523
672
|
|
|
524
|
-
obj.cache_stats_for(:find)
|
|
525
|
-
obj.cache_hit_rate
|
|
526
|
-
obj.cache_miss_rate
|
|
527
|
-
obj.cache_metrics_reset
|
|
673
|
+
obj.cache_stats_for(:find) # Stats scoped to one method
|
|
674
|
+
obj.cache_hit_rate # => 84.0 (percentage)
|
|
675
|
+
obj.cache_miss_rate # => 16.0 (percentage)
|
|
676
|
+
obj.cache_metrics_reset # Clears all collected metrics
|
|
677
|
+
obj.cache_metrics_reset(:find) # Clears metrics for one method only
|
|
528
678
|
```
|
|
529
679
|
|
|
530
680
|
Metrics are per-instance and reset independently from the cache itself — clearing metrics does not evict cached values.
|
|
531
681
|
|
|
682
|
+
[↑ Back to features](#features)
|
|
683
|
+
|
|
684
|
+
### Global configuration
|
|
685
|
+
|
|
686
|
+
Use `SafeMemoize.configure` to set defaults that apply to all subsequently memoized methods. Per-call options always take precedence over global defaults.
|
|
687
|
+
|
|
688
|
+
```ruby
|
|
689
|
+
SafeMemoize.configure do |c|
|
|
690
|
+
c.default_ttl = 300 # All memoized methods expire after 5 minutes unless overridden
|
|
691
|
+
c.default_max_size = 100 # All memoized methods cap at 100 entries unless overridden
|
|
692
|
+
end
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
Both settings apply at definition time — methods already memoized before `configure` is called are not affected. Reset all defaults back to `nil` with:
|
|
696
|
+
|
|
697
|
+
```ruby
|
|
698
|
+
SafeMemoize.reset_configuration!
|
|
699
|
+
```
|
|
700
|
+
|
|
701
|
+
The configure block also accepts `on_hook_error`, `on_deprecation`, `active_support_notifications`, and `statsd_client` (covered in [Hook error isolation](#hook-error-isolation), [Deprecation](#deprecation), [ActiveSupport::Notifications](#activesupportnotifications), and [StatsD](#statsd)).
|
|
702
|
+
|
|
703
|
+
[↑ Back to features](#features)
|
|
704
|
+
|
|
705
|
+
### ActiveSupport::Notifications
|
|
706
|
+
|
|
707
|
+
Enable opt-in integration with `ActiveSupport::Notifications` for Rails and other ActiveSupport-based stacks:
|
|
708
|
+
|
|
709
|
+
```ruby
|
|
710
|
+
SafeMemoize.configure do |c|
|
|
711
|
+
c.active_support_notifications = true
|
|
712
|
+
end
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
Once enabled, SafeMemoize emits the following events through the standard notification pipeline:
|
|
716
|
+
|
|
717
|
+
| Event | Fires when |
|
|
718
|
+
|---|---|
|
|
719
|
+
| `cache_hit.safe_memoize` | A cached value is returned |
|
|
720
|
+
| `cache_miss.safe_memoize` | The method is called and no cached value exists |
|
|
721
|
+
| `cache_store.safe_memoize` | A value is written to the cache (miss, `warm_memo`, or `load_memo`) |
|
|
722
|
+
| `cache_evict.safe_memoize` | An entry is removed via `reset_memo`, `reset_all_memos`, or LRU eviction |
|
|
723
|
+
| `cache_expire.safe_memoize` | An expired TTL entry is pruned |
|
|
724
|
+
|
|
725
|
+
Each event payload includes:
|
|
726
|
+
|
|
727
|
+
```ruby
|
|
728
|
+
{
|
|
729
|
+
method: :method_name, # Symbol
|
|
730
|
+
key: cache_key, # Array — the full cache key
|
|
731
|
+
class: "ClassName" # String — the host class name
|
|
732
|
+
}
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
Subscribe to all SafeMemoize events via the standard ActiveSupport pattern:
|
|
736
|
+
|
|
737
|
+
```ruby
|
|
738
|
+
ActiveSupport::Notifications.subscribe(/\.safe_memoize$/) do |event|
|
|
739
|
+
Rails.logger.debug("[cache] #{event.name} #{event.payload[:class]}##{event.payload[:method]}")
|
|
740
|
+
end
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
The integration is a no-op when ActiveSupport is not loaded — there is no overhead for non-Rails projects. `active_support_notifications` defaults to `false`.
|
|
744
|
+
|
|
745
|
+
[↑ Back to features](#features)
|
|
746
|
+
|
|
747
|
+
### StatsD
|
|
748
|
+
|
|
749
|
+
Route cache lifecycle events to any StatsD-compatible client via `SafeMemoize::Adapters::StatsD`. Assign the client once in your initializer:
|
|
750
|
+
|
|
751
|
+
```ruby
|
|
752
|
+
SafeMemoize.configure do |c|
|
|
753
|
+
c.statsd_client = Datadog::Statsd.new("localhost", 8125)
|
|
754
|
+
end
|
|
755
|
+
```
|
|
756
|
+
|
|
757
|
+
SafeMemoize then calls `client.increment(metric, tags: [...])` on every cache event:
|
|
758
|
+
|
|
759
|
+
| Metric | Fires when |
|
|
760
|
+
|---|---|
|
|
761
|
+
| `safe_memoize.hit` | A cached value is returned |
|
|
762
|
+
| `safe_memoize.miss` | The method is called and no cached value exists |
|
|
763
|
+
| `safe_memoize.store` | A value is written to the cache (miss, `warm_memo`, or `load_memo`) |
|
|
764
|
+
| `safe_memoize.evict` | An entry is removed via `reset_memo`, `reset_all_memos`, or LRU eviction |
|
|
765
|
+
| `safe_memoize.expire` | An expired TTL entry is pruned |
|
|
766
|
+
|
|
767
|
+
Each call includes two tags: `method:method_name` and `class:ClassName`. The client must respond to `increment(metric, tags: [...])` — the interface used by `dogstatsd-ruby`, `statsd-instrument`, and most modern StatsD clients.
|
|
768
|
+
|
|
769
|
+
If the client raises, the error is rescued and a warning is emitted to stderr rather than propagated to the caller. `statsd_client` defaults to `nil` (disabled).
|
|
770
|
+
|
|
771
|
+
[↑ Back to features](#features)
|
|
772
|
+
|
|
773
|
+
### OpenTelemetry
|
|
774
|
+
|
|
775
|
+
`SafeMemoize::Adapters::OpenTelemetry` wraps the computation on each cache miss in an OpenTelemetry span, making memoized call costs visible in distributed traces. Assign a tracer once in your initializer:
|
|
776
|
+
|
|
777
|
+
```ruby
|
|
778
|
+
SafeMemoize.configure do |c|
|
|
779
|
+
c.opentelemetry_tracer = OpenTelemetry.tracer_provider.tracer(
|
|
780
|
+
"safe_memoize",
|
|
781
|
+
SafeMemoize::VERSION
|
|
782
|
+
)
|
|
783
|
+
end
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
SafeMemoize then wraps every cache miss (the actual method call, not cache hits) in a span named `"safe_memoize.compute"` with the following attributes:
|
|
787
|
+
|
|
788
|
+
| Attribute | Value |
|
|
789
|
+
|---|---|
|
|
790
|
+
| `safe_memoize.method` | Name of the memoized method |
|
|
791
|
+
| `safe_memoize.class` | Name of the host class |
|
|
792
|
+
| `safe_memoize.cache_hit` | Always `false` — only misses are traced |
|
|
793
|
+
|
|
794
|
+
Cache hits produce no spans, so tracing overhead is zero for cached calls. The adapter is compatible with any tracer that responds to `in_span(name, attributes:, &block)` — the interface provided by `opentelemetry-sdk`, `opentelemetry-api`, and no-op tracers alike. If `opentelemetry_tracer` is `nil` (the default), the adapter is completely bypassed.
|
|
795
|
+
|
|
796
|
+
[↑ Back to features](#features)
|
|
797
|
+
|
|
798
|
+
### Rails request-scope
|
|
799
|
+
|
|
800
|
+
SafeMemoize ships optional Rails integration as a separate require (zero overhead in non-Rails apps):
|
|
801
|
+
|
|
802
|
+
```ruby
|
|
803
|
+
require "safe_memoize/rails"
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
#### Controller concern
|
|
807
|
+
|
|
808
|
+
Include `SafeMemoize::Rails::RequestScoped` in any Rails controller that also `prepend SafeMemoize`. It automatically registers `after_action :reset_all_memos` so every instance memo is cleared at the end of each request — preventing state from leaking between requests when the controller object is reused:
|
|
809
|
+
|
|
810
|
+
```ruby
|
|
811
|
+
class ApplicationController < ActionController::Base
|
|
812
|
+
prepend SafeMemoize
|
|
813
|
+
include SafeMemoize::Rails::RequestScoped
|
|
814
|
+
|
|
815
|
+
memoize :current_user
|
|
816
|
+
end
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
#### Service objects and non-controller classes
|
|
820
|
+
|
|
821
|
+
In plain classes (service objects, Active Model objects), include `RequestScoped` to gain `reset_request_memos` and call it manually at the appropriate point:
|
|
822
|
+
|
|
823
|
+
```ruby
|
|
824
|
+
class ReportService
|
|
825
|
+
prepend SafeMemoize
|
|
826
|
+
include SafeMemoize::Rails::RequestScoped
|
|
827
|
+
|
|
828
|
+
def summary(id)
|
|
829
|
+
# ...
|
|
830
|
+
end
|
|
831
|
+
memoize :summary
|
|
832
|
+
end
|
|
833
|
+
|
|
834
|
+
svc = ReportService.new
|
|
835
|
+
svc.summary(1)
|
|
836
|
+
svc.reset_request_memos # clears all instance memos
|
|
837
|
+
```
|
|
838
|
+
|
|
839
|
+
#### Middleware for tracked instances
|
|
840
|
+
|
|
841
|
+
For service objects that should be reset automatically at request boundaries, use the Rack middleware together with `SafeMemoize::Rails.track`:
|
|
842
|
+
|
|
843
|
+
```ruby
|
|
844
|
+
# config/application.rb
|
|
845
|
+
config.middleware.use SafeMemoize::Rails::Middleware
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
```ruby
|
|
849
|
+
class ReportService
|
|
850
|
+
prepend SafeMemoize
|
|
851
|
+
|
|
852
|
+
def initialize
|
|
853
|
+
SafeMemoize::Rails.track(self) # register for auto-reset
|
|
854
|
+
end
|
|
855
|
+
|
|
856
|
+
def summary(id)
|
|
857
|
+
# ...
|
|
858
|
+
end
|
|
859
|
+
memoize :summary
|
|
860
|
+
end
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
`SafeMemoize::Rails::Middleware` calls `reset_all_memos` on every tracked instance in the current thread at the end of the request, even if the app raises. Tracking is thread-local, so concurrent requests never interfere. The tracked list is cleared automatically after each reset.
|
|
864
|
+
|
|
865
|
+
[↑ Back to features](#features)
|
|
866
|
+
|
|
867
|
+
### Deprecation
|
|
868
|
+
|
|
869
|
+
SafeMemoize ships a structured deprecation helper for gem authors who build on top of it:
|
|
870
|
+
|
|
871
|
+
```ruby
|
|
872
|
+
SafeMemoize.deprecate(
|
|
873
|
+
"MyGem::OldHelper",
|
|
874
|
+
message: "Use MyGem::NewHelper instead",
|
|
875
|
+
horizon: "2.0.0"
|
|
876
|
+
)
|
|
877
|
+
# => [SafeMemoize] DEPRECATED: MyGem::OldHelper — Use MyGem::NewHelper instead (removal horizon: 2.0.0)
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
The warning is emitted to stderr by default. Configure a custom handler via `SafeMemoize.configure`:
|
|
881
|
+
|
|
882
|
+
```ruby
|
|
883
|
+
SafeMemoize.configure do |c|
|
|
884
|
+
c.on_deprecation = ->(msg) { Rails.logger.warn(msg) }
|
|
885
|
+
end
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
To raise on deprecation warnings in test environments:
|
|
889
|
+
|
|
890
|
+
```ruby
|
|
891
|
+
SafeMemoize.configure do |c|
|
|
892
|
+
c.on_deprecation = ->(msg) { raise msg }
|
|
893
|
+
end
|
|
894
|
+
```
|
|
895
|
+
|
|
896
|
+
[↑ Back to features](#features)
|
|
897
|
+
|
|
898
|
+
## Ractor compatibility
|
|
899
|
+
|
|
900
|
+
SafeMemoize is **not Ractor-compatible** in its current form. Passing a class that uses `memoize` into a `Ractor.new` block raises `RuntimeError: defined with an un-shareable Proc in a different Ractor`. There are two root causes:
|
|
901
|
+
|
|
902
|
+
1. **Non-shareable closures.** `ClassMethods#memoize` builds anonymous modules using `define_method` with blocks that close over local variables (`ttl`, `max_size`, `condition`, `shared_mutex`, …). Ruby marks those Procs as non-Ractor-shareable, so the host class cannot be sent to a Ractor.
|
|
903
|
+
|
|
904
|
+
2. **Mutable module-level state.** `SafeMemoize.configuration` reads `@configuration` from the `SafeMemoize` module — a mutable ivar on a shared constant — which raises `Ractor::IsolationError` from a non-main Ractor. This affects every memoized call because hooks and adapters always read the configuration.
|
|
905
|
+
|
|
906
|
+
**Workaround:** Use Ruby Threads instead of Ractors — SafeMemoize is fully thread-safe via double-check locking and per-instance Mutexes. If you need true parallelism with Ractors, perform computation inside the Ractor without memoization and send frozen results back via `Ractor#send`.
|
|
907
|
+
|
|
908
|
+
Ractor support is tracked in the v1.0.0 roadmap. The fix would require replacing closed-over variables with frozen shareable bindings and making `Configuration` a frozen value object, which is a significant redesign.
|
|
909
|
+
|
|
532
910
|
## Development
|
|
533
911
|
|
|
534
912
|
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt.
|
|
535
913
|
|
|
914
|
+
To run the benchmark suite: `bundle exec ruby benchmarks/benchmark.rb`.
|
|
915
|
+
|
|
916
|
+
To generate API documentation locally: `bundle exec rake doc`. Output is written to `doc/` (gitignored). The online reference is published automatically to [RubyDoc.info](https://rubydoc.info/gems/safe_memoize) on every release. Install `memery` and `memo_wise` first if you want comparison columns against those gems.
|
|
917
|
+
|
|
536
918
|
GitHub Actions also runs the full `bundle exec rake` suite automatically for pull requests, manual workflow runs, and pushes to `main` via `.github/workflows/ci.yml`.
|
|
537
919
|
|
|
538
920
|
## Releasing
|
|
@@ -568,9 +950,174 @@ To preview the changelog/version update without changing anything, use:
|
|
|
568
950
|
bin/release 0.1.1 --dry-run
|
|
569
951
|
```
|
|
570
952
|
|
|
953
|
+
## Public API and versioning guarantee
|
|
954
|
+
|
|
955
|
+
From **v1.0.0** onwards SafeMemoize follows [Semantic Versioning](https://semver.org/). The table below declares every constant, method, and option key that forms the public contract. If you only call items listed here, you are guaranteed that:
|
|
956
|
+
|
|
957
|
+
- **Patch** releases (1.x.**y**) contain bug fixes only — no behaviour changes.
|
|
958
|
+
- **Minor** releases (1.**x**.0) add new features in a backwards-compatible way.
|
|
959
|
+
- **Major** releases (**x**.0.0) may break the items below; a migration guide will be published for every such release.
|
|
960
|
+
|
|
961
|
+
Anything **not** listed here — internal modules, private methods, `@__safe_memo_*__` ivars, the structure of the cache hash itself — is subject to change without notice in any release, including patch releases.
|
|
962
|
+
|
|
963
|
+
### Top-level module
|
|
964
|
+
|
|
965
|
+
| Symbol | Kind | Notes |
|
|
966
|
+
|---|---|---|
|
|
967
|
+
| `SafeMemoize::VERSION` | constant | Semver string, always present |
|
|
968
|
+
| `SafeMemoize::Error` | class | Base error class (`< StandardError`) for rescuing any SafeMemoize-raised exception |
|
|
969
|
+
| `SafeMemoize.configure { \|c\| … }` | module method | Yields `Configuration`; sets global defaults |
|
|
970
|
+
| `SafeMemoize.configuration` | module method | Returns the current `Configuration` |
|
|
971
|
+
| `SafeMemoize.reset_configuration!` | module method | Restores all configuration to defaults |
|
|
972
|
+
| `SafeMemoize.deprecate(subject, message:, horizon:)` | module method | Emits a structured deprecation warning |
|
|
973
|
+
|
|
974
|
+
### `memoize` DSL (class method, added by `prepend SafeMemoize`)
|
|
975
|
+
|
|
976
|
+
| Option key | Type | Default | Notes |
|
|
977
|
+
|---|---|---|---|
|
|
978
|
+
| `ttl:` | `Numeric \| nil` | `nil` | Seconds until entry expires |
|
|
979
|
+
| `ttl_refresh:` | `Boolean` | `false` | Sliding window — resets clock on every hit |
|
|
980
|
+
| `max_size:` | `Integer \| nil` | `nil` | LRU entry limit per method |
|
|
981
|
+
| `if:` | `Symbol \| Proc \| nil` | `nil` | Store only when truthy |
|
|
982
|
+
| `unless:` | `Symbol \| Proc \| nil` | `nil` | Store only when falsy |
|
|
983
|
+
| `shared:` | `Boolean` | `false` | Class-level shared cache |
|
|
984
|
+
| `key:` | `Proc \| nil` | `nil` | Class-level custom key generator |
|
|
985
|
+
|
|
986
|
+
### `memoize_all` options (class method)
|
|
987
|
+
|
|
988
|
+
All `memoize` option keys above, plus:
|
|
989
|
+
|
|
990
|
+
| Option key | Type | Default |
|
|
991
|
+
|---|---|---|
|
|
992
|
+
| `except:` | `Array<Symbol>` | `[]` |
|
|
993
|
+
| `only:` | `Array<Symbol>` | `[]` |
|
|
994
|
+
| `include_protected:` | `Boolean` | `false` |
|
|
995
|
+
| `include_private:` | `Boolean` | `false` |
|
|
996
|
+
|
|
997
|
+
### Instance methods (public)
|
|
998
|
+
|
|
999
|
+
**Inspection**
|
|
1000
|
+
|
|
1001
|
+
| Method | Returns |
|
|
1002
|
+
|---|---|
|
|
1003
|
+
| `memoized?(method_name, *args, **kwargs)` | `Boolean` |
|
|
1004
|
+
| `memo_count(method_name = nil)` | `Integer` |
|
|
1005
|
+
| `memo_keys(method_name = nil)` | `Array` |
|
|
1006
|
+
| `memo_values(method_name = nil)` | `Array` |
|
|
1007
|
+
| `memo_inspect(method_name, *args, **kwargs)` | `Hash \| nil` |
|
|
1008
|
+
| `memo_ttl_remaining(method_name, *args, **kwargs)` | `Numeric \| nil` |
|
|
1009
|
+
| `memo_age(method_name, *args, **kwargs)` | `Numeric \| nil` |
|
|
1010
|
+
| `memo_stale?(method_name, *args, **kwargs)` | `Boolean` |
|
|
1011
|
+
|
|
1012
|
+
**Invalidation and mutation**
|
|
1013
|
+
|
|
1014
|
+
| Method | Returns |
|
|
1015
|
+
|---|---|
|
|
1016
|
+
| `reset_memo(method_name, *args, **kwargs)` | `nil` |
|
|
1017
|
+
| `reset_all_memos` | `nil` |
|
|
1018
|
+
| `memo_touch(method_name, *args, ttl: nil, **kwargs)` | `Boolean` |
|
|
1019
|
+
| `memo_refresh(method_name, *args, **kwargs)` | cached value |
|
|
1020
|
+
|
|
1021
|
+
**Warm-up and persistence**
|
|
1022
|
+
|
|
1023
|
+
| Method | Returns |
|
|
1024
|
+
|---|---|
|
|
1025
|
+
| `warm_memo(method_name, *args, ttl: nil, **kwargs)` | cached value |
|
|
1026
|
+
| `memo_preload(method_name, *arg_sets)` | `Array` |
|
|
1027
|
+
| `dump_memo(method_name = nil)` | `Hash` |
|
|
1028
|
+
| `load_memo(snapshot)` | `nil` |
|
|
1029
|
+
|
|
1030
|
+
**Lifecycle hooks**
|
|
1031
|
+
|
|
1032
|
+
| Method | Fires when |
|
|
1033
|
+
|---|---|
|
|
1034
|
+
| `on_memo_hit { \|key\| … }` | cache hit |
|
|
1035
|
+
| `on_memo_miss { \|key\| … }` | cache miss |
|
|
1036
|
+
| `on_memo_store { \|key, value\| … }` | value written |
|
|
1037
|
+
| `on_memo_expire { \|key\| … }` | TTL expires |
|
|
1038
|
+
| `on_memo_evict { \|key\| … }` | LRU eviction |
|
|
1039
|
+
| `clear_memo_hooks(hook_type = nil)` | — |
|
|
1040
|
+
|
|
1041
|
+
**Metrics**
|
|
1042
|
+
|
|
1043
|
+
| Method | Returns |
|
|
1044
|
+
|---|---|
|
|
1045
|
+
| `cache_stats` | `Hash` |
|
|
1046
|
+
| `cache_stats_for(method_name)` | `Hash` |
|
|
1047
|
+
| `cache_hit_rate` | `Float` |
|
|
1048
|
+
| `cache_miss_rate` | `Float` |
|
|
1049
|
+
| `cache_metrics_reset(method_name = nil)` | `nil` |
|
|
1050
|
+
|
|
1051
|
+
**Custom keys**
|
|
1052
|
+
|
|
1053
|
+
| Method | Notes |
|
|
1054
|
+
|---|---|
|
|
1055
|
+
| `memoize_with_custom_key(method_name) { \|*args, **kwargs\| … }` | Instance-level key generator |
|
|
1056
|
+
| `clear_custom_keys(method_name = nil)` | Remove one or all key generators |
|
|
1057
|
+
|
|
1058
|
+
### Shared-cache class methods (added when any method uses `shared: true`)
|
|
1059
|
+
|
|
1060
|
+
| Method | Returns |
|
|
1061
|
+
|---|---|
|
|
1062
|
+
| `reset_shared_memo(method_name, *args, **kwargs)` | `nil` |
|
|
1063
|
+
| `reset_all_shared_memos` | `nil` |
|
|
1064
|
+
| `shared_memoized?(method_name, *args, **kwargs)` | `Boolean` |
|
|
1065
|
+
| `shared_memo_count(method_name = nil)` | `Integer` |
|
|
1066
|
+
| `shared_memo_age(method_name, *args, **kwargs)` | `Numeric \| nil` |
|
|
1067
|
+
| `shared_memo_stale?(method_name, *args, **kwargs)` | `Boolean` |
|
|
1068
|
+
|
|
1069
|
+
### `SafeMemoize::Configuration` attributes
|
|
1070
|
+
|
|
1071
|
+
| Attribute | Type | Default |
|
|
1072
|
+
|---|---|---|
|
|
1073
|
+
| `default_ttl` | `Numeric \| nil` | `nil` |
|
|
1074
|
+
| `default_max_size` | `Integer \| nil` | `nil` |
|
|
1075
|
+
| `on_deprecation` | `Proc \| nil` | `nil` (writes to stderr) |
|
|
1076
|
+
| `on_hook_error` | `Proc \| nil` | `nil` (warns to stderr) |
|
|
1077
|
+
| `active_support_notifications` | `Boolean` | `false` |
|
|
1078
|
+
| `statsd_client` | `Object \| nil` | `nil` |
|
|
1079
|
+
| `opentelemetry_tracer` | `Object \| nil` | `nil` |
|
|
1080
|
+
|
|
1081
|
+
### Opt-in extensions (not guaranteed until their owning milestone ships)
|
|
1082
|
+
|
|
1083
|
+
The following are available now but reside under `require "safe_memoize/rails"` and are not covered by the v1.0.0 semver guarantee until the v1.x milestone that owns them is declared stable:
|
|
1084
|
+
|
|
1085
|
+
- `SafeMemoize::Rails` module (`track`, `reset_tracked!`)
|
|
1086
|
+
- `SafeMemoize::Rails::RequestScoped` concern
|
|
1087
|
+
- `SafeMemoize::Rails::Middleware` Rack middleware
|
|
1088
|
+
- `SafeMemoize::Adapters::StatsD`
|
|
1089
|
+
- `SafeMemoize::Adapters::OpenTelemetry`
|
|
1090
|
+
|
|
1091
|
+
## Ruby version support
|
|
1092
|
+
|
|
1093
|
+
### Supported versions
|
|
1094
|
+
|
|
1095
|
+
SafeMemoize requires **Ruby ≥ 3.3**. Every non-EOL Ruby version in the table below is actively tested in CI and receives bug-fix backports for critical issues.
|
|
1096
|
+
|
|
1097
|
+
| Ruby | Status | EOL |
|
|
1098
|
+
|---|---|---|
|
|
1099
|
+
| 3.3 | Supported | Mar 2027 |
|
|
1100
|
+
| 3.4 | Supported | Mar 2028 |
|
|
1101
|
+
| 4.0 | Supported | ~ Dec 2028 |
|
|
1102
|
+
|
|
1103
|
+
EOL dates follow the [Ruby maintenance schedule](https://www.ruby-lang.org/en/downloads/branches/).
|
|
1104
|
+
|
|
1105
|
+
### Policy
|
|
1106
|
+
|
|
1107
|
+
- **Dropping an EOL version is a minor-version change**, not a major one — it will appear in the CHANGELOG under `### Removed` and the gemspec `required_ruby_version` will be updated accordingly.
|
|
1108
|
+
- SafeMemoize targets the **current stable release plus the two previous non-EOL minors** at any given time. When Ruby releases a new version in December, CI gains a new column; when a version reaches EOL the next minor release removes it.
|
|
1109
|
+
- **No patch release will ever raise the minimum Ruby version.** Only `x.y.0` minor releases may do so.
|
|
1110
|
+
- Prerelease Rubies (dev / preview builds) are not officially supported but breakage is investigated on a best-effort basis.
|
|
1111
|
+
|
|
1112
|
+
### History
|
|
1113
|
+
|
|
1114
|
+
| Dropped in | Ruby version removed |
|
|
1115
|
+
|---|---|
|
|
1116
|
+
| v0.5.0 | Ruby 3.2 (reached EOL) |
|
|
1117
|
+
|
|
571
1118
|
## Roadmap
|
|
572
1119
|
|
|
573
|
-
See [ROADMAP.md](ROADMAP.md) for the planned path
|
|
1120
|
+
See [ROADMAP.md](ROADMAP.md) for the planned path to v1.0.0 and beyond, including upcoming features, API stability goals, and the versioning policy.
|
|
574
1121
|
|
|
575
1122
|
## Contributing
|
|
576
1123
|
|