mankai-cache 0.1.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 +7 -0
- data/CHANGELOG.md +23 -0
- data/LICENSE +20 -0
- data/README.md +368 -0
- data/lib/mankai/cache/coder.rb +102 -0
- data/lib/mankai/cache/entry.rb +17 -0
- data/lib/mankai/cache/errors.rb +34 -0
- data/lib/mankai/cache/instrumenter.rb +92 -0
- data/lib/mankai/cache/key.rb +56 -0
- data/lib/mankai/cache/provider_source.rb +161 -0
- data/lib/mankai/cache/serializers/json.rb +27 -0
- data/lib/mankai/cache/serializers/marshal.rb +25 -0
- data/lib/mankai/cache/serializers.rb +39 -0
- data/lib/mankai/cache/store.rb +61 -0
- data/lib/mankai/cache/stores/file.rb +189 -0
- data/lib/mankai/cache/stores/memory.rb +145 -0
- data/lib/mankai/cache/stores/null.rb +53 -0
- data/lib/mankai/cache/testing/store_examples.rb +69 -0
- data/lib/mankai/cache/version.rb +9 -0
- data/lib/mankai/cache/view_helpers.rb +54 -0
- data/lib/mankai/cache.rb +348 -0
- data/lib/mankai-cache.rb +3 -0
- data/mankai-cache.gemspec +34 -0
- metadata +100 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 7047924b7ded79adf58a858744573dd111873a46884d7735bdc0d3f9e70560e0
|
|
4
|
+
data.tar.gz: 3e9d824bb82404da4d1aa32443c3bfebd664d4110635302183d2afa621440cda
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 979ea138c6450d98fb76f1ad6e2f7ab1fd11e8f8eefd41d36a0a74a3c4748635e3bb12c5ab390d9f3b63995633c20233be3428f351a9ac38183f0ec6108fcd30
|
|
7
|
+
data.tar.gz: 4e91b60410fe843a2becca6e1ff637550268a61ddff18c538de85f9c127bae78d829e183f12bc0e28df16bf95ebe76fab4dc3ff265e3c533a27d93c084545c9d
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Break Versioning](https://www.taoensso.com/break-versioning).
|
|
7
|
+
|
|
8
|
+
## [0.1.0]
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `Mankai::Cache` with `read`, `write`, `fetch` (with `force`, `skip_nil` and `race_condition_ttl`), `exist?`, `delete`, the `_multi` variants, `increment`, `decrement`, `clear` and `cleanup`.
|
|
13
|
+
- Keys from strings, symbols, numbers, times, arrays, hashes and objects with `cache_key`; entry versions, including from `cache_version`; namespaces and shortened long keys.
|
|
14
|
+
- Marshal and JSON serializers, and compression of large values.
|
|
15
|
+
- Memory, file and null stores, the `Store` contract, and shared RSpec examples for stores.
|
|
16
|
+
- A dry-system provider source registering the `"cache"` component, a `cache` template helper, and events on the app's notifications bus.
|
|
17
|
+
- Values the serializer cannot dump (such as ROM structs with `:marshal`) raise `Mankai::Cache::SerializationError`, which says to cache plain data such as `to_h` instead, rather than a bare `TypeError`.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- Non-String versions (e.g. `version: 3`) now match on `read`, `fetch`, `exist?`, `read_multi` and `fetch_multi`; versions are compared as Strings.
|
|
22
|
+
- A Time in a cache key is no longer converted to UTC in place; the caller's Time is left unchanged.
|
|
23
|
+
- Events for failed operations now include `time:` as well as `exception:`, so subscribers that read `event[:time]` no longer raise `KeyError` and hide the original error.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ibrahim Diallo <thisis@ibrahimd.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
the Software without restriction, including without limitation the rights to
|
|
8
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
<img src="../../assets/logo/mankai-logo.svg" alt="Mankai" width="72">
|
|
2
|
+
|
|
3
|
+
# mankai-cache
|
|
4
|
+
|
|
5
|
+
Caching for [Hanami](https://hanamirb.org) apps. The cache is a component you inject, and it
|
|
6
|
+
keeps entries in a store you choose: memory, files, or a SQL table with
|
|
7
|
+
[mankai-cache-sql](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql).
|
|
8
|
+
|
|
9
|
+
```ruby
|
|
10
|
+
# app/actions/books/show.rb
|
|
11
|
+
module Bookshelf
|
|
12
|
+
module Actions
|
|
13
|
+
module Books
|
|
14
|
+
class Show < Bookshelf::Action
|
|
15
|
+
include Deps["cache", "repos.book_repo"]
|
|
16
|
+
|
|
17
|
+
def handle(request, response)
|
|
18
|
+
id = request.params[:id]
|
|
19
|
+
response[:book] = cache.fetch(["books", id], expires_in: 600) { book_repo.find(id)&.to_h }
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The block's result is cached, so it has to be something the serializer can store. Cache plain
|
|
28
|
+
data such as `book.to_h`, not the struct a repo returns: see [Serializers](#serializers).
|
|
29
|
+
|
|
30
|
+
## Setup
|
|
31
|
+
|
|
32
|
+
```ruby
|
|
33
|
+
# Gemfile
|
|
34
|
+
gem "mankai-cache"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
# config/providers/cache.rb
|
|
39
|
+
require "mankai/cache"
|
|
40
|
+
|
|
41
|
+
Hanami.app.register_provider(:cache, from: :mankai_cache) do
|
|
42
|
+
configure do |config|
|
|
43
|
+
config.store = Hanami.env?(:test) ? :memory : :file
|
|
44
|
+
config.expires_in = 3600
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
This registers `"cache"`, a `Mankai::Cache`; `include Deps["cache"]` wherever you need it. Tests
|
|
50
|
+
use the memory store, which starts empty in each process; clear it before each example (see
|
|
51
|
+
[Testing](#testing)).
|
|
52
|
+
|
|
53
|
+
### Settings
|
|
54
|
+
|
|
55
|
+
| Setting | Default | Description |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `store` | `:memory` | `:memory`, `:file` or `:null`; a store object (responds to `read` and `write`); or a factory called with the container, such as `Mankai::Cache::SQL.store(...)`. Anything else raises `ConfigurationError`. |
|
|
58
|
+
| `store_options` | `{}` | Keyword options for a built-in store: `size:` for `:memory` (bytes, default `32 * 1024 * 1024`), `path:` for `:file` (default: the app's `tmp/cache`). Ignored for store objects and factories. |
|
|
59
|
+
| `namespace` | `nil` | Prefixed to every key (`"bookshelf:books/1"`), e.g. to share a store between apps. |
|
|
60
|
+
| `expires_in` | `nil` | Default lifetime of entries, in seconds. `nil` keeps them until the store evicts them. |
|
|
61
|
+
| `serializer` | `:marshal` | `:marshal`, `:json`, or an object with `dump` and `load`. See [Serializers](#serializers). |
|
|
62
|
+
| `compress` | `true` | Deflate large values, when that makes them smaller. |
|
|
63
|
+
| `compress_threshold` | `1024` | Smallest value, in bytes, that `compress` deflates. |
|
|
64
|
+
| `max_key_size` | `250` | Keys longer than this many bytes are shortened and given a SHA-256 suffix. |
|
|
65
|
+
| `notifications_key` | `"notifications"` | Container key of the dry-monitor bus that [events](#events) go to. Events are skipped when the container has no such key. |
|
|
66
|
+
| `clock` | `-> { Time.now }` | Returns the current Time, for expiry. |
|
|
67
|
+
|
|
68
|
+
Outside Hanami, build one directly:
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
cache = Mankai::Cache.new(store: Mankai::Cache::Stores::Memory.new, expires_in: 300)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Reading and writing
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
cache.write("greeting", "hello", expires_in: 60)
|
|
78
|
+
cache.read("greeting") # => "hello"
|
|
79
|
+
cache.exist?("greeting") # => true
|
|
80
|
+
cache.delete("greeting") # => true
|
|
81
|
+
|
|
82
|
+
cache.fetch(["books", id]) { book_repo.find(id).to_h } # runs the block on a miss only
|
|
83
|
+
cache.fetch(key, force: true) { ... } # always runs it, and stores the result
|
|
84
|
+
cache.fetch(key, skip_nil: true) { ... } # does not store nil
|
|
85
|
+
|
|
86
|
+
cache.write_multi({"a" => 1, "b" => 2})
|
|
87
|
+
cache.read_multi("a", "b", "c") # => {"a" => 1, "b" => 2}
|
|
88
|
+
cache.fetch_multi("a", "b", "c") { |key| compute(key) } # computes only "c"
|
|
89
|
+
cache.delete_multi(["a", "b"]) # => 2
|
|
90
|
+
|
|
91
|
+
cache.increment("signups") # => 1, atomically
|
|
92
|
+
cache.decrement("signups", 1) # => 0
|
|
93
|
+
|
|
94
|
+
cache.cleanup # deletes expired entries (memory and file stores)
|
|
95
|
+
cache.clear # deletes everything in the store
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`write`, `write_multi`, `fetch` and `fetch_multi` take `expires_in:` (seconds) or `expires_at:`
|
|
99
|
+
(a Time), and `version:`. `read`, `read_multi` and `exist?` take `version:`.
|
|
100
|
+
|
|
101
|
+
`clear` deletes every entry in the store, including entries written under other namespaces. On
|
|
102
|
+
the SQL store, `cleanup` runs an expiry pass (see
|
|
103
|
+
[mankai-cache-sql](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql#how-it-works)).
|
|
104
|
+
|
|
105
|
+
### Keys
|
|
106
|
+
|
|
107
|
+
A key can be a String, Symbol, number, boolean, `nil`, Time or Date; an object with a
|
|
108
|
+
`cache_key` method; or an Array or Hash of those. Arrays are joined with "/", so
|
|
109
|
+
`["books", 1, :en]` is stored as `"books/1/en"`. Anything else raises
|
|
110
|
+
`Mankai::Cache::InvalidKeyError`, because `to_s` of most objects includes a memory address and
|
|
111
|
+
would never hit.
|
|
112
|
+
|
|
113
|
+
### Versions
|
|
114
|
+
|
|
115
|
+
An entry written with a version is a miss when read with another one, or with none. Versions are
|
|
116
|
+
compared as Strings, so `version: 3` and `version: "3"` match.
|
|
117
|
+
|
|
118
|
+
```ruby
|
|
119
|
+
cache.write("settings", settings, version: 3)
|
|
120
|
+
cache.read("settings", version: 3) # => settings
|
|
121
|
+
cache.read("settings", version: 4) # => nil
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Objects with a `cache_version` method supply it themselves, so a record's key can stay the same
|
|
125
|
+
while its version changes. In a Hanami app, add the methods to the struct class:
|
|
126
|
+
|
|
127
|
+
```ruby
|
|
128
|
+
# app/structs/book.rb
|
|
129
|
+
module Bookshelf
|
|
130
|
+
module Structs
|
|
131
|
+
class Book < Bookshelf::DB::Struct
|
|
132
|
+
def cache_key = "books/#{id}"
|
|
133
|
+
def cache_version = updated_at.to_i
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```ruby
|
|
140
|
+
cache.fetch(book) { render_card(book) } # recomputed after the book is updated
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The struct is only the key here; the cached value is the String that `render_card` returns.
|
|
144
|
+
|
|
145
|
+
### Recomputing popular entries once
|
|
146
|
+
|
|
147
|
+
When a popular entry expires, every request that misses it would recompute it at the same time.
|
|
148
|
+
With `race_condition_ttl:`, the first caller writes the expired value back for that many
|
|
149
|
+
seconds and recomputes it; callers in the meantime get the old value:
|
|
150
|
+
|
|
151
|
+
```ruby
|
|
152
|
+
cache.fetch("homepage/stats", expires_in: 300, race_condition_ttl: 10) { expensive_stats }
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Caching parts of a page
|
|
156
|
+
|
|
157
|
+
Hanami generates `app/views/helpers.rb` and `app/views/context.rb`. Add the helper to the first
|
|
158
|
+
and the cache to the second:
|
|
159
|
+
|
|
160
|
+
```ruby
|
|
161
|
+
# app/views/helpers.rb
|
|
162
|
+
module Bookshelf
|
|
163
|
+
module Views
|
|
164
|
+
module Helpers
|
|
165
|
+
include Mankai::Cache::ViewHelpers
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
```ruby
|
|
172
|
+
# app/views/context.rb
|
|
173
|
+
module Bookshelf
|
|
174
|
+
module Views
|
|
175
|
+
class Context < Hanami::View::Context
|
|
176
|
+
include Deps["cache"]
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Then wrap the fragment in a template:
|
|
183
|
+
|
|
184
|
+
```erb
|
|
185
|
+
<% books.each do |book| %>
|
|
186
|
+
<%= cache ["v1", book] do %>
|
|
187
|
+
<%= render "books/card", book: book %>
|
|
188
|
+
<% end %>
|
|
189
|
+
<% end %>
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The helper takes the same options as `fetch` and stores entries under `"views/"`. The key follows
|
|
193
|
+
the [key rules](#keys): `book` here needs a `cache_key` method (see [Versions](#versions)), or
|
|
194
|
+
the helper raises `InvalidKeyError`. Without one, use its id and update time:
|
|
195
|
+
`cache ["v1", "books", book.id, book.updated_at]`.
|
|
196
|
+
|
|
197
|
+
The key has to change whenever the HTML should:
|
|
198
|
+
|
|
199
|
+
- Put in the records the HTML shows, with their versions (or their update times).
|
|
200
|
+
- Add anything else the HTML depends on, such as the locale or the current user's role.
|
|
201
|
+
- Template changes are not tracked: bump a version in the key (`"v1"` above) when you change the
|
|
202
|
+
markup.
|
|
203
|
+
|
|
204
|
+
Whole responses need nothing from this gem: Hanami responses already have `cache_control`,
|
|
205
|
+
`expires` and `fresh(etag:, last_modified:)` for HTTP caching.
|
|
206
|
+
|
|
207
|
+
## Stores
|
|
208
|
+
|
|
209
|
+
| | Memory | File | SQL ([mankai-cache-sql](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql)) | Null |
|
|
210
|
+
|---|---|---|---|---|
|
|
211
|
+
| Shared between processes | No | On one machine | Yes | — |
|
|
212
|
+
| Survives restarts | No | Yes | Yes | — |
|
|
213
|
+
| Evicts | Least recently used, over `size` | Only on `cleanup` | Oldest first, by age and size | — |
|
|
214
|
+
| Good for | Development, single-process apps | One server | Several servers | Tests, turning caching off |
|
|
215
|
+
|
|
216
|
+
**Memory** (`Stores::Memory.new(size: 32 * 1024 * 1024)`) keeps entries in a hash. Over `size`
|
|
217
|
+
bytes, it evicts the least recently used entries until it is at three quarters. Entries are kept
|
|
218
|
+
encoded, so changing a value you read never changes the cached copy. Each Puma worker has its
|
|
219
|
+
own.
|
|
220
|
+
|
|
221
|
+
**File** (`Stores::File.new(path: "tmp/cache")`) keeps one file per entry, named by the key's
|
|
222
|
+
SHA-256 digest in two levels of subdirectories (`ab/cd/abcd...`). Writes go to a temporary file
|
|
223
|
+
that is renamed into place, and `increment` holds a lock file. Entries are only deleted when they
|
|
224
|
+
are overwritten or when `cleanup` runs, so run `cache.cleanup` from a recurring job if keys come
|
|
225
|
+
and go. With the provider, the path defaults to the app's `tmp/cache`.
|
|
226
|
+
|
|
227
|
+
**Null** (`Stores::Null.new`) keeps nothing, so `fetch` always runs its block. Use it to turn
|
|
228
|
+
caching off in an environment.
|
|
229
|
+
|
|
230
|
+
**SQL** keeps entries in a table. Over `max_age` (two weeks by default), `max_entries` or
|
|
231
|
+
`max_size`, it deletes the oldest entries, a batch at a time. See
|
|
232
|
+
[mankai-cache-sql](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql).
|
|
233
|
+
|
|
234
|
+
### Writing a store
|
|
235
|
+
|
|
236
|
+
A store keeps encoded entries (binary strings) under string keys; the cache does everything else.
|
|
237
|
+
Include `Mankai::Cache::Store` and implement:
|
|
238
|
+
|
|
239
|
+
```ruby
|
|
240
|
+
read(key) # => String or nil
|
|
241
|
+
write(key, data, expires_at:) # => true; expires_at is seconds since the epoch, or nil
|
|
242
|
+
delete(key) # => whether there was an entry
|
|
243
|
+
update(key) { |data| ... } # atomically yields the current data (or nil) and writes the
|
|
244
|
+
# [data, expires_at] the block returns
|
|
245
|
+
clear # deletes every entry
|
|
246
|
+
cleanup(now) # deletes entries expired at `now`, if the store keeps them
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The module provides `read_multi`, `write_multi` and `delete_multi` one key at a time, and a
|
|
250
|
+
`close` that does nothing; override them where your store can do better. Check your store
|
|
251
|
+
against the shared examples:
|
|
252
|
+
|
|
253
|
+
```ruby
|
|
254
|
+
require "mankai/cache/testing/store_examples"
|
|
255
|
+
|
|
256
|
+
RSpec.describe MyStore do
|
|
257
|
+
subject(:store) { MyStore.new }
|
|
258
|
+
|
|
259
|
+
it_behaves_like "a mankai-cache store"
|
|
260
|
+
end
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Serializers
|
|
264
|
+
|
|
265
|
+
`:marshal` (the default) round-trips Strings, numbers, Symbols, Times, Arrays, Hashes and
|
|
266
|
+
instances of your own named classes. It cannot dump ROM structs (the objects Hanami repos return),
|
|
267
|
+
Procs or IO objects. ROM builds struct classes at runtime, so Marshal cannot refer to them by name.
|
|
268
|
+
Writing one raises `Mankai::Cache::SerializationError`. Cache plain data instead:
|
|
269
|
+
|
|
270
|
+
```ruby
|
|
271
|
+
cache.fetch(["books", id]) { book_repo.find(id).to_h } # a Hash
|
|
272
|
+
cache.fetch(["books", "count"]) { book_repo.count } # an Integer
|
|
273
|
+
cache.fetch(["books", id, "card"]) { render_card(book) } # a String
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Anyone who can write to a `:marshal` store can make the app load arbitrary objects, so keep the
|
|
277
|
+
store private to the app. After a deploy, entries for classes that no longer exist are misses.
|
|
278
|
+
|
|
279
|
+
`:json` is safe to read from anywhere, but only round-trips plain data: Hashes come back with
|
|
280
|
+
String keys, and Symbols and Times come back as Strings. Other objects are written as their
|
|
281
|
+
`to_s`.
|
|
282
|
+
|
|
283
|
+
Any object with `dump(value)` returning a String and `load(string)` works too. Have `dump` raise
|
|
284
|
+
`TypeError` for values it can't handle, and the cache turns that into `SerializationError`.
|
|
285
|
+
|
|
286
|
+
## Events
|
|
287
|
+
|
|
288
|
+
The cache publishes events on the app's dry-monitor bus (Hanami registers it as
|
|
289
|
+
`"notifications"`). Event names are Symbols:
|
|
290
|
+
|
|
291
|
+
| Event | Payload |
|
|
292
|
+
|---|---|
|
|
293
|
+
| `:"mankai.cache.read"` | `key:`, `hit:` |
|
|
294
|
+
| `:"mankai.cache.read_multi"` | `keys:`, `hits:` (the keys that hit) |
|
|
295
|
+
| `:"mankai.cache.fetch"` | `key:`, `hit:` |
|
|
296
|
+
| `:"mankai.cache.write"` | `key:` |
|
|
297
|
+
| `:"mankai.cache.write_multi"` | `keys:` |
|
|
298
|
+
| `:"mankai.cache.delete"` | `key:` |
|
|
299
|
+
| `:"mankai.cache.delete_multi"` | `keys:` |
|
|
300
|
+
| `:"mankai.cache.increment"` | `key:`, `amount:` (negative for `decrement`) |
|
|
301
|
+
| `:"mankai.cache.clear"` | |
|
|
302
|
+
| `:"mankai.cache.cleanup"` | |
|
|
303
|
+
|
|
304
|
+
Keys are the stored strings, after namespacing. Every event also has `time:`, in milliseconds.
|
|
305
|
+
When the operation raises, the event has `exception:` too, and may lack `hit:`.
|
|
306
|
+
|
|
307
|
+
The events are registered when the cache provider starts; subscribing before that raises
|
|
308
|
+
`Dry::Events::InvalidSubscriberError`. Subscribe in the provider's `after(:start)` callback:
|
|
309
|
+
|
|
310
|
+
```ruby
|
|
311
|
+
# config/providers/cache.rb
|
|
312
|
+
require "mankai/cache"
|
|
313
|
+
|
|
314
|
+
Hanami.app.register_provider(:cache, from: :mankai_cache) do
|
|
315
|
+
configure do |config|
|
|
316
|
+
config.store = Hanami.env?(:test) ? :memory : :file
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
after(:start) do
|
|
320
|
+
target["notifications"].subscribe(:"mankai.cache.fetch") do |event|
|
|
321
|
+
payload = event.payload
|
|
322
|
+
target["logger"].debug(
|
|
323
|
+
"cache #{payload[:hit] ? "hit" : "miss"} #{payload[:key]} (#{payload[:time]}ms)"
|
|
324
|
+
)
|
|
325
|
+
end
|
|
326
|
+
end
|
|
327
|
+
end
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
`event[:name]` raises `KeyError` for a key the payload lacks, so read optional keys from
|
|
331
|
+
`event.payload`.
|
|
332
|
+
|
|
333
|
+
## Errors
|
|
334
|
+
|
|
335
|
+
All errors inherit from `Mankai::Cache::Error`.
|
|
336
|
+
|
|
337
|
+
| Error | Raised when |
|
|
338
|
+
|---|---|
|
|
339
|
+
| `Mankai::Cache::ConfigurationError` | The provider or a store is set up wrongly: an unknown store or serializer, a `:file` store without a path outside Hanami, or a view context without the cache for the `cache` helper. |
|
|
340
|
+
| `Mankai::Cache::InvalidKeyError` | A key part is not a String, Symbol, number, boolean, `nil`, Time, Date, Array or Hash and has no `cache_key` method. |
|
|
341
|
+
| `Mankai::Cache::SerializationError` | The serializer can't dump a value, such as a ROM struct with `:marshal`. The original error is its `cause`. |
|
|
342
|
+
|
|
343
|
+
Data that can't be decoded on read (a removed class, another format, corruption) is a miss, not
|
|
344
|
+
an error.
|
|
345
|
+
|
|
346
|
+
## Testing
|
|
347
|
+
|
|
348
|
+
Use the memory store in tests and clear it before each example, so examples don't see each
|
|
349
|
+
other's entries:
|
|
350
|
+
|
|
351
|
+
```ruby
|
|
352
|
+
# spec/support/cache.rb
|
|
353
|
+
RSpec.configure do |config|
|
|
354
|
+
config.before { Hanami.app["cache"].clear }
|
|
355
|
+
end
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
To test expiry without sleeping, build a cache with a clock you control and pass it to the
|
|
359
|
+
object under test:
|
|
360
|
+
|
|
361
|
+
```ruby
|
|
362
|
+
now = Time.utc(2026, 1, 1, 12)
|
|
363
|
+
cache = Mankai::Cache.new(clock: -> { now })
|
|
364
|
+
|
|
365
|
+
cache.write("a", 1, expires_in: 60)
|
|
366
|
+
now += 61
|
|
367
|
+
cache.read("a") # => nil
|
|
368
|
+
```
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "zlib"
|
|
5
|
+
|
|
6
|
+
module Mankai
|
|
7
|
+
class Cache
|
|
8
|
+
# Encodes entries into binary strings for stores, and back.
|
|
9
|
+
#
|
|
10
|
+
# Layout: format (1 byte), flags (1 byte), expiry (8-byte double, 0 for none), version length
|
|
11
|
+
# (2 bytes), version, then the serialized value, deflated when that makes it smaller.
|
|
12
|
+
#
|
|
13
|
+
# Data that does not decode (another format, a class that no longer exists, corruption)
|
|
14
|
+
# loads as nil, which callers treat as a miss.
|
|
15
|
+
#
|
|
16
|
+
# @api public
|
|
17
|
+
# @since 0.1.0
|
|
18
|
+
class Coder
|
|
19
|
+
# @api private
|
|
20
|
+
# @since 0.1.0
|
|
21
|
+
FORMAT = 1
|
|
22
|
+
# @api private
|
|
23
|
+
# @since 0.1.0
|
|
24
|
+
HEADER = "CCGn"
|
|
25
|
+
# @api private
|
|
26
|
+
# @since 0.1.0
|
|
27
|
+
HEADER_SIZE = 12
|
|
28
|
+
# @api private
|
|
29
|
+
# @since 0.1.0
|
|
30
|
+
COMPRESSED = 0b1
|
|
31
|
+
# @api private
|
|
32
|
+
# @since 0.1.0
|
|
33
|
+
LOAD_ERRORS = [ArgumentError, TypeError, EncodingError, Zlib::Error, ::JSON::ParserError].freeze
|
|
34
|
+
# @api private
|
|
35
|
+
# @since 0.1.0
|
|
36
|
+
DUMP_ERRORS = [TypeError, ::JSON::GeneratorError].freeze
|
|
37
|
+
|
|
38
|
+
# @api public
|
|
39
|
+
# @since 0.1.0
|
|
40
|
+
attr_reader :serializer, :compress, :compress_threshold
|
|
41
|
+
|
|
42
|
+
# @param serializer [:marshal, :json, #dump, #load] see Serializers
|
|
43
|
+
# @param compress [Boolean] deflate values of at least compress_threshold bytes
|
|
44
|
+
#
|
|
45
|
+
# @api public
|
|
46
|
+
# @since 0.1.0
|
|
47
|
+
def initialize(serializer: :marshal, compress: true, compress_threshold: 1024)
|
|
48
|
+
@serializer = Serializers.resolve(serializer)
|
|
49
|
+
@compress = compress
|
|
50
|
+
@compress_threshold = compress_threshold
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# @return [String] binary
|
|
54
|
+
# @raise [SerializationError] when the serializer cannot dump the value
|
|
55
|
+
#
|
|
56
|
+
# @api public
|
|
57
|
+
# @since 0.1.0
|
|
58
|
+
def dump(entry)
|
|
59
|
+
payload = serialize(entry.value)
|
|
60
|
+
flags = 0
|
|
61
|
+
if compress && payload.bytesize >= compress_threshold
|
|
62
|
+
deflated = Zlib::Deflate.deflate(payload)
|
|
63
|
+
payload, flags = deflated, COMPRESSED if deflated.bytesize < payload.bytesize
|
|
64
|
+
end
|
|
65
|
+
version = entry.version.to_s.b
|
|
66
|
+
[FORMAT, flags, entry.expires_at || 0.0, version.bytesize].pack(HEADER) << version << payload
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# @return [Entry, nil] nil when the data does not decode
|
|
70
|
+
#
|
|
71
|
+
# @api public
|
|
72
|
+
# @since 0.1.0
|
|
73
|
+
def load(data)
|
|
74
|
+
data = data.b
|
|
75
|
+
format, flags, expires_at, size = data.unpack(HEADER)
|
|
76
|
+
return unless format == FORMAT && size
|
|
77
|
+
|
|
78
|
+
version = data.byteslice(HEADER_SIZE, size).force_encoding(Encoding::UTF_8)
|
|
79
|
+
payload = data.byteslice((HEADER_SIZE + size)..)
|
|
80
|
+
payload = Zlib::Inflate.inflate(payload) if flags.anybits?(COMPRESSED)
|
|
81
|
+
Entry.new(
|
|
82
|
+
value: serializer.load(payload),
|
|
83
|
+
expires_at: expires_at.zero? ? nil : expires_at,
|
|
84
|
+
version: version.empty? ? nil : version
|
|
85
|
+
)
|
|
86
|
+
rescue *LOAD_ERRORS
|
|
87
|
+
nil
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
private
|
|
91
|
+
|
|
92
|
+
# @api private
|
|
93
|
+
# @since 0.1.0
|
|
94
|
+
def serialize(value)
|
|
95
|
+
serializer.dump(value).b
|
|
96
|
+
rescue *DUMP_ERRORS => exception
|
|
97
|
+
raise SerializationError, "cannot cache #{value.class} with #{serializer} (#{exception.message}). Cache " \
|
|
98
|
+
"plain data instead, such as a struct's to_h, or configure a serializer that can dump it"
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Mankai
|
|
4
|
+
class Cache
|
|
5
|
+
# A cached value with its expiry (seconds since the epoch, or nil for never) and version.
|
|
6
|
+
#
|
|
7
|
+
# @api private
|
|
8
|
+
# @since 0.1.0
|
|
9
|
+
Entry = Data.define(:value, :expires_at, :version) do
|
|
10
|
+
# @api private
|
|
11
|
+
# @since 0.1.0
|
|
12
|
+
def expired?(now)
|
|
13
|
+
!expires_at.nil? && expires_at <= now
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Mankai
|
|
4
|
+
class Cache
|
|
5
|
+
# Base class for every error raised by mankai-cache and its stores.
|
|
6
|
+
#
|
|
7
|
+
# @api public
|
|
8
|
+
# @since 0.1.0
|
|
9
|
+
class Error < StandardError
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Raised when the cache or its provider is set up wrongly (e.g. an unknown store name).
|
|
13
|
+
#
|
|
14
|
+
# @api public
|
|
15
|
+
# @since 0.1.0
|
|
16
|
+
class ConfigurationError < Error
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Raised when a value cannot be turned into a cache key.
|
|
20
|
+
#
|
|
21
|
+
# @api public
|
|
22
|
+
# @since 0.1.0
|
|
23
|
+
class InvalidKeyError < Error
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Raised when the serializer cannot turn a value into bytes, e.g. :marshal and a ROM struct.
|
|
27
|
+
# Cache plain data instead (such as `struct.to_h`), or configure a serializer that can.
|
|
28
|
+
#
|
|
29
|
+
# @api public
|
|
30
|
+
# @since 0.1.0
|
|
31
|
+
class SerializationError < Error
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Mankai
|
|
4
|
+
class Cache
|
|
5
|
+
# Publishes events on a dry-monitor notifications bus, such as a Hanami app's "notifications"
|
|
6
|
+
# component. Without a bus, events are skipped.
|
|
7
|
+
#
|
|
8
|
+
# Events (each "mankai.cache.<name>"):
|
|
9
|
+
# read key:, hit:
|
|
10
|
+
# read_multi keys:, hits:
|
|
11
|
+
# fetch key:, hit:
|
|
12
|
+
# write key:
|
|
13
|
+
# write_multi keys:
|
|
14
|
+
# delete key:
|
|
15
|
+
# delete_multi keys:
|
|
16
|
+
# increment key:, amount:
|
|
17
|
+
# clear
|
|
18
|
+
# cleanup
|
|
19
|
+
#
|
|
20
|
+
# Events are Symbols, e.g. :"mankai.cache.fetch". They are registered when the instrumenter
|
|
21
|
+
# is built (when the cache provider starts), so subscribe after that. Every event has `time:`
|
|
22
|
+
# (milliseconds); when the operation raises, the event also has `exception:`.
|
|
23
|
+
#
|
|
24
|
+
# @api private
|
|
25
|
+
# @since 0.1.0
|
|
26
|
+
class Instrumenter
|
|
27
|
+
# @api private
|
|
28
|
+
# @since 0.1.0
|
|
29
|
+
PREFIX = "mankai.cache"
|
|
30
|
+
# @api private
|
|
31
|
+
# @since 0.1.0
|
|
32
|
+
EVENTS = %i[read read_multi fetch write write_multi delete delete_multi increment clear cleanup].freeze
|
|
33
|
+
|
|
34
|
+
attr_reader :notifications
|
|
35
|
+
|
|
36
|
+
# @api private
|
|
37
|
+
# @since 0.1.0
|
|
38
|
+
def initialize(notifications = nil)
|
|
39
|
+
@notifications = notifications
|
|
40
|
+
@registered = Set.new
|
|
41
|
+
# Registered up front, so the app can subscribe before the first event.
|
|
42
|
+
EVENTS.each { |event| register(event) } if notifications
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Runs the block inside the event, returning the block's result. The block may add to the
|
|
46
|
+
# payload (e.g. whether a read was a hit).
|
|
47
|
+
#
|
|
48
|
+
# @api private
|
|
49
|
+
# @since 0.1.0
|
|
50
|
+
def instrument(event, payload = {})
|
|
51
|
+
return yield(payload) unless notifications
|
|
52
|
+
|
|
53
|
+
id = register(event)
|
|
54
|
+
result = nil
|
|
55
|
+
started = now
|
|
56
|
+
begin
|
|
57
|
+
notifications.instrument(id, payload) { result = yield(payload) }
|
|
58
|
+
rescue Exception => exception # rubocop:disable Lint/RescueException
|
|
59
|
+
# dry-monitor skips the event when the block raises; publish it with the error instead.
|
|
60
|
+
notifications.instrument(id, payload.merge(exception: exception, time: now - started))
|
|
61
|
+
raise
|
|
62
|
+
end
|
|
63
|
+
result
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
private
|
|
67
|
+
|
|
68
|
+
# Milliseconds, like dry-monitor's `time:`.
|
|
69
|
+
#
|
|
70
|
+
# @api private
|
|
71
|
+
# @since 0.1.0
|
|
72
|
+
def now
|
|
73
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# @api private
|
|
77
|
+
# @since 0.1.0
|
|
78
|
+
def register(event)
|
|
79
|
+
id = :"#{PREFIX}.#{event}"
|
|
80
|
+
unless @registered.include?(id)
|
|
81
|
+
notifications.register_event(id)
|
|
82
|
+
@registered << id
|
|
83
|
+
end
|
|
84
|
+
id
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# @api private
|
|
88
|
+
# @since 0.1.0
|
|
89
|
+
NULL = new(nil)
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|