typed_cache 0.1.1

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.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. checksums.yaml.gz.sig +0 -0
  3. data/LICENSE +201 -0
  4. data/README.md +168 -0
  5. data/examples.md +190 -0
  6. data/lib/typed_cache/backend.rb +16 -0
  7. data/lib/typed_cache/backends/active_support.rb +113 -0
  8. data/lib/typed_cache/backends/memory.rb +166 -0
  9. data/lib/typed_cache/backends.rb +34 -0
  10. data/lib/typed_cache/cache_builder.rb +77 -0
  11. data/lib/typed_cache/cache_key.rb +45 -0
  12. data/lib/typed_cache/cache_ref.rb +155 -0
  13. data/lib/typed_cache/clock.rb +23 -0
  14. data/lib/typed_cache/decorator.rb +12 -0
  15. data/lib/typed_cache/decorators.rb +35 -0
  16. data/lib/typed_cache/either.rb +121 -0
  17. data/lib/typed_cache/errors.rb +64 -0
  18. data/lib/typed_cache/instrumentation.rb +112 -0
  19. data/lib/typed_cache/maybe.rb +92 -0
  20. data/lib/typed_cache/namespace.rb +162 -0
  21. data/lib/typed_cache/registry.rb +55 -0
  22. data/lib/typed_cache/snapshot.rb +72 -0
  23. data/lib/typed_cache/store/instrumented.rb +83 -0
  24. data/lib/typed_cache/store.rb +152 -0
  25. data/lib/typed_cache/version.rb +5 -0
  26. data/lib/typed_cache.rb +58 -0
  27. data/sig/generated/typed_cache/backend.rbs +17 -0
  28. data/sig/generated/typed_cache/backends/active_support.rbs +56 -0
  29. data/sig/generated/typed_cache/backends/memory.rbs +95 -0
  30. data/sig/generated/typed_cache/backends.rbs +21 -0
  31. data/sig/generated/typed_cache/cache_builder.rbs +37 -0
  32. data/sig/generated/typed_cache/cache_key.rbs +33 -0
  33. data/sig/generated/typed_cache/cache_ref.rbs +91 -0
  34. data/sig/generated/typed_cache/clock.rbs +15 -0
  35. data/sig/generated/typed_cache/decorator.rbs +14 -0
  36. data/sig/generated/typed_cache/decorators.rbs +25 -0
  37. data/sig/generated/typed_cache/either.rbs +106 -0
  38. data/sig/generated/typed_cache/errors.rbs +51 -0
  39. data/sig/generated/typed_cache/instrumentation.rbs +30 -0
  40. data/sig/generated/typed_cache/maybe.rbs +85 -0
  41. data/sig/generated/typed_cache/namespace.rbs +130 -0
  42. data/sig/generated/typed_cache/registry.rbs +25 -0
  43. data/sig/generated/typed_cache/snapshot.rbs +50 -0
  44. data/sig/generated/typed_cache/store/instrumented.rbs +37 -0
  45. data/sig/generated/typed_cache/store.rbs +104 -0
  46. data/sig/generated/typed_cache/version.rbs +5 -0
  47. data/sig/generated/typed_cache.rbs +34 -0
  48. data/sig/handwritten/gems/zeitwerk/2.7/zeitwerk.rbs +9 -0
  49. data/typed_cache.gemspec +42 -0
  50. data.tar.gz.sig +0 -0
  51. metadata +228 -0
  52. metadata.gz.sig +0 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9beff9345d3d58fb92c4cb77467271af9f8bc1212529dd7d6d21d13fa4e285ad
4
+ data.tar.gz: 0aef7f30f5f5029e8667944c4b6724694f5cf8e1bae1a7358a4c0a6c0931902b
5
+ SHA512:
6
+ metadata.gz: a848cd77e148388fc0624acdd2f5b5826c573fc418d13dc15ce1f7b75acf365d8860cff1ceb123bb0b3b8f374fba100e25b5d818f51b66ac3aea0f3e6c6fe745
7
+ data.tar.gz: 9e0929925806d7449462bb70deb7773eb19301d268cb93fc0fb321ca5ff38619c724f9e305c40e255a21a3b85e44fd80d4bed69ac97d13f4385af878a25c9f8d
checksums.yaml.gz.sig ADDED
Binary file
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # TypedCache
2
+
3
+ TypedCache is a lightweight, type-safe façade around your favourite Ruby cache
4
+ stores. It adds three things on top of the raw back-end implementation:
5
+
6
+ 1. **Namespacing** – hierarchical `Namespace` helpers prevent key collisions.
7
+ 2. **Stronger types** – RBS signatures as well as monadic types like `Either`, `Maybe`, and `Snapshot` wrap cache results so you always know whether you have a value, an error, or a cache-miss.
8
+ 3. **Composable decorators** – behaviours like instrumentation can be layered
9
+ on without touching the underlying store.
10
+
11
+ > **TL;DR** – Think _Faraday_ or _Rack_ middlewares, but for caching.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ bundle add typed_cache && bundle install
19
+ # or
20
+ gem install typed_cache
21
+ ```
22
+
23
+ This gem does is also cryptographically signed, if you want to ensure the gem was not tampered with, make sure to use these commands:
24
+
25
+ ```bash
26
+ bundle add typed_cache && bundle install --trust-policy=HighSecurity
27
+ # or
28
+ gem install typed_cache -P HighSecurity
29
+ ```
30
+
31
+ If there are issues with unsigned gems, use `MediumSecurity` instead.
32
+
33
+ ## Quick start
34
+
35
+ ```ruby
36
+ require "typed_cache"
37
+
38
+ # Build an in-memory cache with ActiveSupport-style instrumentation
39
+ store = TypedCache.builder
40
+ .with_backend(:memory, shared: true)
41
+ .with_instrumentation # or .with_decorator(:instrumented)
42
+ .build # => Either[Error, Store]
43
+ .value
44
+
45
+ users_key = store.namespace.key("users") # => CacheKey
46
+ snapshot = store.set(users_key, [1, 2, 3]) # => Either[Error, Snapshot]
47
+ puts snapshot.value # => [1, 2, 3]
48
+ ```
49
+
50
+ ## Builder API
51
+
52
+ | Step | Purpose |
53
+ | ----------------------------- | -------------------------------------------------------------- |
54
+ | `with_backend(:name, **opts)` | Mandatory. Configure the concrete **Backend** and its options. |
55
+ | `with_decorator(:key)` | Optional. Add a decorator by registry key. |
56
+ | `with_instrumentation` | Convenience alias for `with_decorator(:instrumented)`. |
57
+ | `build` | Returns `Either[Error, Store]`. |
58
+
59
+ ### Back-ends vs Decorators
60
+
61
+ - **Back-end** (`TypedCache::Backend`) – persists data (Memory, Redis, etc.).
62
+ - **Decorator** (`TypedCache::Decorator`) – wraps an existing store to add
63
+ behaviour (Instrumentation, Logging, Circuit-Breaker …).
64
+
65
+ Both include the same public `Store` interface, so they can be composed
66
+ freely. Registries keep them separate:
67
+
68
+ ```ruby
69
+ TypedCache::Backends.available # => [:memory, :active_support]
70
+ TypedCache::Decorators.available # => [:instrumented]
71
+ ```
72
+
73
+ ### Register your own
74
+
75
+ ```ruby
76
+ class RedisBackend
77
+ include TypedCache::Backend
78
+ # … implement #get, #set, etc.
79
+ end
80
+
81
+ TypedCache::Backends.register(:redis, RedisBackend)
82
+ ```
83
+
84
+ ```ruby
85
+ class LogDecorator
86
+ include TypedCache::Decorator
87
+ def initialize(store) = @store = store
88
+ def set(key, value)
89
+ puts "[cache] SET #{key}"
90
+ @store.set(key, value)
91
+ end
92
+ # delegate the rest …
93
+ end
94
+
95
+ TypedCache::Decorators.register(:logger, LogDecorator)
96
+ ```
97
+
98
+ ## Error handling
99
+
100
+ All operations return one of:
101
+
102
+ - `Either.right(Snapshot)` – success
103
+ - `Either.left(CacheMissError)` – key not present
104
+ - `Either.left(StoreError)` – transport / serialization failure
105
+
106
+ Use the monad directly or pattern-match:
107
+
108
+ ```ruby
109
+ result.fold(
110
+ ->(err) { warn err.message },
111
+ ->(snapshot) { puts snapshot.value },
112
+ )
113
+ ```
114
+
115
+ ## Instrumentation
116
+
117
+ Decorators publish ActiveSupport notifications when
118
+ `TypedCache.config.instrumentation.enabled = true`:
119
+
120
+ ```
121
+ <operation>.<namespace> # e.g. get.typed_cache
122
+ ```
123
+
124
+ Payload keys: `:namespace, :key, :duration, :cache_hit`, …
125
+
126
+ ## Further examples
127
+
128
+ For more advanced scenarios—including Rails integration, pattern matching, custom back-ends, and testing—see [examples.md](examples.md).
129
+
130
+ ## License
131
+
132
+ This work is licensed under the [Apache-2.0](./LICENSE) license.
133
+
134
+ ### Apache 2.0 License Key Terms
135
+
136
+ #### Grants
137
+
138
+ - Perpetual, worldwide, non-exclusive, royalty-free license to:
139
+ - Reproduce the work
140
+ - Prepare derivative works
141
+ - Distribute the work
142
+ - Use and sell the work
143
+
144
+ #### Requirements
145
+
146
+ - Include a copy of the Apache 2.0 License with any distribution
147
+ - Provide attribution
148
+ - Clearly mark any modifications made to the original work
149
+ - Retain all original copyright and license notices
150
+
151
+ #### Permissions
152
+
153
+ - Commercial use allowed
154
+ - Modification permitted
155
+ - Distribution of original and modified work permitted
156
+ - Patent use granted
157
+ - Private use allowed
158
+
159
+ #### Limitations
160
+
161
+ - No warranty or liability protection
162
+ - Trademark rights not transferred
163
+ - Contributors not liable for damages
164
+
165
+ #### Compatibility
166
+
167
+ - Can be used in closed-source and commercial projects
168
+ - Requires preserving original license and attribution
data/examples.md ADDED
@@ -0,0 +1,190 @@
1
+ # TypedCache Examples
2
+
3
+ This document provides practical examples of using TypedCache in real applications.
4
+
5
+ ## Basic Memory Cache
6
+
7
+ The simplest way to create a type-safe cache:
8
+
9
+ ```ruby
10
+ user_namespace = TypedCache::Namespace.at("users")
11
+
12
+ cache_result = TypedCache.builder
13
+ .with_backend(:memory, shared: true)
14
+ .with_instrumentation
15
+ .build(user_namespace) # => Either[Error, Store]
16
+
17
+ store = cache_result.value # unwrap for brevity
18
+ key = store.namespace.key("123") # => CacheKey
19
+ store.set(key, { id: 123, name: "Jane" })
20
+ ```
21
+
22
+ ## Rails Integration
23
+
24
+ Using TypedCache with `Rails.cache` and ActiveSupport notifications:
25
+
26
+ ```ruby
27
+ cache_result = TypedCache.builder
28
+ .with_backend(:active_support, Rails.cache)
29
+ .with_instrumentation
30
+ .build # defaults to TypedCache.config.default_namespace
31
+
32
+ cache = cache_result.value
33
+ cache.fetch(cache.namespace.key("header")) { render_header }
34
+ ```
35
+
36
+ ## Pattern Matching
37
+
38
+ Clean error handling with Ruby 3 pattern matching:
39
+
40
+ ```ruby
41
+ result = TypedCache.builder
42
+ .with_backend(:memory)
43
+ .build
44
+
45
+ case result
46
+ in TypedCache::Either::Right(store)
47
+ store.set(store.namespace.key("greeting"), "Hello")
48
+ in TypedCache::Either::Left(error)
49
+ warn "Failed to set up cache: #{error.message}"
50
+ end
51
+ ```
52
+
53
+ ## Multiple Caches
54
+
55
+ Reuse a preconfigured builder for several namespaces:
56
+
57
+ ```ruby
58
+ base_builder = TypedCache.builder
59
+ .with_backend(:memory, shared: true)
60
+
61
+ users_store = base_builder.build(TypedCache::Namespace.at("users")).value
62
+ posts_store = base_builder.build(TypedCache::Namespace.at("posts")).value
63
+ comments_store = base_builder.build(TypedCache::Namespace.at("comments")).value
64
+ ```
65
+
66
+ ## Cache Operations
67
+
68
+ Working with cache values using the monadic interface:
69
+
70
+ ```ruby
71
+ # Set a value
72
+ cache.set({ id: 1, name: "John" })
73
+
74
+ # Get with error handling
75
+ cache.get.fold(
76
+ ->(error) { puts "Cache miss: #{error.message}" },
77
+ ->(snapshot) { puts "Found: #{snapshot.value}" }
78
+ )
79
+
80
+ # Get with Maybe semantics (no error details)
81
+ user = cache.peek.value_or({ id: 0, name: "Anonymous" })
82
+
83
+ # Fetch with computation
84
+ result = cache.fetch do
85
+ # This block runs only on cache miss
86
+ expensive_user_lookup(user_id)
87
+ end
88
+ ```
89
+
90
+ ## Custom Backend
91
+
92
+ Registering and using a custom cache backend:
93
+
94
+ ```ruby
95
+ class SimpleStore
96
+ include TypedCache::Backend
97
+
98
+ def initialize(namespace)
99
+ @namespace = namespace
100
+ @data = {}
101
+ end
102
+
103
+ def get(key)
104
+ value = @data[key]
105
+ value ? TypedCache::Either.right(value) : TypedCache::Either.left(TypedCache::CacheMissError.new(key))
106
+ end
107
+
108
+ def set(key, value)
109
+ @data[key] = value
110
+ TypedCache::Either.right(value)
111
+ end
112
+
113
+ def delete(key)
114
+ value = @data.delete(key)
115
+ value ? TypedCache::Either.right(value) : TypedCache::Either.left(TypedCache::CacheMissError.new(key))
116
+ end
117
+
118
+ attr_reader :namespace
119
+ def store_type = "simple"
120
+ end
121
+
122
+ TypedCache::Backends.register(:simple, SimpleStore)
123
+
124
+ cache = TypedCache.builder
125
+ .with_backend(:simple)
126
+ .build.value
127
+ ```
128
+
129
+ ## Instrumentation Only
130
+
131
+ ```ruby
132
+ TypedCache.configure_instrumentation do |config|
133
+ config.enabled = true
134
+ config.namespace = "my_app_cache"
135
+ end
136
+
137
+ cache = TypedCache.builder
138
+ .with_backend(:memory)
139
+ .with_instrumentation
140
+ .build.value
141
+
142
+ cache.set(cache.namespace.key("metrics"), 42)
143
+ ```
144
+
145
+ ## Configuration Snippet
146
+
147
+ ```ruby
148
+ TypedCache.configure do |config|
149
+ config.default_namespace = "my_app"
150
+ end
151
+ ```
152
+
153
+ You can register additional decorators or back-ends as needed:
154
+
155
+ ```ruby
156
+ TypedCache::Decorators.register(:logger, MyLoggerDecorator)
157
+ TypedCache::Backends.register(:redis, MyRedisBackend)
158
+ ```
159
+
160
+ ## Thread Safety
161
+
162
+ The shared in-memory back-end is thread-safe:
163
+
164
+ ```ruby
165
+ shared_store = TypedCache.builder
166
+ .with_backend(:memory, shared: true)
167
+ .build.value
168
+
169
+ threads = 10.times.map do |i|
170
+ Thread.new { shared_store.set(shared_store.namespace.key(i.to_s), "data_") }
171
+ end
172
+ threads.each(&:join)
173
+ ```
174
+
175
+ ## Testing
176
+
177
+ Using TypedCache in tests:
178
+
179
+ ```ruby
180
+ spec_store = TypedCache.builder
181
+ .with_backend(:memory)
182
+ .build(TypedCache::Namespace.at("specs")).value
183
+
184
+ RSpec.describe "cache" do
185
+ it "stores data" do
186
+ result = spec_store.set(spec_store.namespace.key("id"), 1)
187
+ expect(result).to be_right
188
+ end
189
+ end
190
+ ```
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypedCache
4
+ # Marker mixin for concrete cache back-ends.
5
+ # A Backend *is* a Store, but the reverse is not necessarily true (decorators also
6
+ # include Store). By tagging back-ends with this module we can type-check and
7
+ # register them separately from decorators.
8
+ #
9
+ # Back-ends should *not* assume they wrap another store – they are the leaf nodes
10
+ # that actually persist data.
11
+ # @rbs generic V
12
+ module Backend
13
+ include Store #[V]
14
+ # @rbs! include Store::_Store[V]
15
+ end
16
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypedCache
4
+ module Backends
5
+ # Adapter that wraps any ActiveSupport::Cache::Store to work with TypedCache
6
+ # @rbs generic V
7
+ class ActiveSupport
8
+ include Backend #[V]
9
+
10
+ attr_reader :namespace #: Namespace
11
+ attr_reader :cache_store #: ::ActiveSupport::Cache::Store
12
+ attr_reader :default_options #: Hash[Symbol, top]
13
+
14
+ #: (Namespace, ::ActiveSupport::Cache::Store, ?Hash[Symbol, top]) -> void
15
+ def initialize(namespace, cache_store, default_options = {})
16
+ @namespace = namespace
17
+ @cache_store = cache_store
18
+ @default_options = default_options
19
+ end
20
+
21
+ # @rbs override
22
+ #: (cache_key) -> either[Error, Snapshot[V]]
23
+ def get(key)
24
+ cache_key_str = namespaced_key(key).to_s
25
+ raw_value = cache_store.read(cache_key_str, default_options)
26
+ return Either.left(CacheMissError.new(key)) if raw_value.nil?
27
+
28
+ Either.right(Snapshot.new(raw_value, source: :cache))
29
+ rescue => e
30
+ Either.left(StoreError.new(:get, key, "Failed to read from cache: #{e.message}", e))
31
+ end
32
+
33
+ # @rbs override
34
+ #: (cache_key, V) -> either[Error, Snapshot[V]]
35
+ def set(key, value)
36
+ cache_key_str = namespaced_key(key).to_s
37
+ success = cache_store.write(cache_key_str, value, default_options)
38
+
39
+ if success
40
+ Either.right(Snapshot.new(value, source: :cache))
41
+ else
42
+ Either.left(StoreError.new(:set, key, 'Failed to write to cache', nil))
43
+ end
44
+ rescue => e
45
+ Either.left(StoreError.new(:set, key, "Failed to write to cache: #{e.message}", e))
46
+ end
47
+
48
+ # @rbs override
49
+ #: (cache_key) -> either[Error, Snapshot[V]]
50
+ def delete(key)
51
+ get(key).fold(
52
+ ->(error) { Either.left(error) },
53
+ ->(snapshot) {
54
+ cache_key_str = namespaced_key(key).to_s
55
+ cache_store.delete(cache_key_str, default_options)
56
+ Either.right(snapshot)
57
+ },
58
+ )
59
+ rescue => e
60
+ Either.left(StoreError.new(:delete, key, "Failed to delete from cache: #{e.message}", e))
61
+ end
62
+
63
+ # @rbs override
64
+ #: (cache_key) -> bool
65
+ def key?(key)
66
+ cache_store.exist?(namespaced_key(key).to_s, default_options)
67
+ rescue => _e
68
+ false
69
+ end
70
+
71
+ # @rbs override
72
+ #: -> maybe[Error]
73
+ def clear
74
+ if cache_store.respond_to?(:delete_matched)
75
+ namespace_prefix_patterns.each do |pattern|
76
+ cache_store.delete_matched(pattern, default_options)
77
+ end
78
+ elsif cache_store.respond_to?(:clear)
79
+ cache_store.clear(default_options)
80
+ end
81
+ Maybe.none
82
+ rescue => e
83
+ Maybe.some(e)
84
+ end
85
+
86
+ # @rbs override
87
+ #: -> String
88
+ def store_type
89
+ 'active_support'
90
+ end
91
+
92
+ #: (Hash[Symbol, top]) -> ActiveSupport[V]
93
+ def with_options(new_options)
94
+ self.class.new(namespace, cache_store, new_options)
95
+ end
96
+
97
+ #: -> ::ActiveSupport::Cache::Store
98
+ def raw_cache
99
+ cache_store
100
+ end
101
+
102
+ private
103
+
104
+ # Regex patterns that match keys for this namespace (with trailing colon)
105
+ #: -> Array[Regexp]
106
+ def namespace_prefix_patterns
107
+ [
108
+ /\A#{Regexp.escape(namespace.to_s)}:/,
109
+ ]
110
+ end
111
+ end
112
+ end
113
+ end