mankai-cache-sql 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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 10cd1db778033c694badab3c088ad3e5815d129914266d9c0010e3c9d83cded1
4
+ data.tar.gz: 966ae16a580ae3271a51eed9cb61bd2f66360f69c41def829bc7e8f15f148870
5
+ SHA512:
6
+ metadata.gz: 2c80cc0beda91d386fa95c9a9f8a3e1fc59d2f7f923ddd74d50eb4e0b4a852e63cc4e31c2606f4a68198166897f66b5c3b0a914c807053d8061c4c58e0d2336e
7
+ data.tar.gz: b6a673f4beeaedd0c647b870fc223b536549ff92ca9e1f728a429e62dea2b4d38607e0aeb3386e362cfae49707492410f67ecc064a897366cbbe877542c8b61a
data/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
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
+ - A SQL store for mankai-cache (PostgreSQL, MySQL 8+, MariaDB, SQLite): entries found by a 64-bit key hash, upserted, and expired oldest-first by age, entry count or total size in a background thread or inline.
13
+ - An idempotent migration, with `Migration.install` and `Migration.apply`.
14
+ - A warning at boot when a SQLite connection would stall other threads while waiting for a lock, with the one-line fix.
15
+ - `Migration.install` takes `gateway:` (e.g. `gateway: :cache`) to write the migration into `config/db/<gateway>_migrate`, for a cache table in a separate Hanami database.
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,143 @@
1
+ <img src="../../assets/logo/mankai-logo.svg" alt="Mankai" width="72">
2
+
3
+ # mankai-cache-sql
4
+
5
+ A SQL store for [mankai-cache](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache): entries live in a table, shared by every server
6
+ that uses the database. Works with PostgreSQL, MySQL 8+, MariaDB and SQLite.
7
+
8
+ ## Setup
9
+
10
+ ```ruby
11
+ # Gemfile
12
+ gem "mankai-cache"
13
+ gem "mankai-cache-sql"
14
+ ```
15
+
16
+ Add the table's migration to your app, then run it:
17
+
18
+ ```bash
19
+ bundle exec ruby -e 'require "mankai/cache/sql"; Mankai::Cache::SQL::Migration.install(root: ".")'
20
+ ```
21
+
22
+ ```bash
23
+ bundle exec hanami db migrate
24
+ ```
25
+
26
+ The migration is yours to adapt. It is idempotent, so running it twice does no harm. Pass
27
+ `table: :my_cache` to `install` for another table name, and the same `table:` to the store.
28
+
29
+ ```ruby
30
+ # config/providers/cache.rb
31
+ require "mankai/cache"
32
+ require "mankai/cache/sql"
33
+
34
+ Hanami.app.register_provider(:cache, from: :mankai_cache) do
35
+ configure do |config|
36
+ config.store = Hanami.env?(:test) ? :memory : Mankai::Cache::SQL.store(max_age: 7 * 86_400)
37
+ end
38
+ end
39
+ ```
40
+
41
+ The store uses the app's default database gateway (`"db.gateway"`), so the app needs Hanami's
42
+ database set up (`DATABASE_URL`). Tests use the memory store here; to test against the table,
43
+ use the SQL store in tests too and clear it before each example.
44
+
45
+ ### SQLite
46
+
47
+ By default, a SQLite connection waiting for a lock holds Ruby's global lock, so every other thread in the process (web requests, background expiry) stops for up to 5 seconds. Tell the connection to wait without blocking other threads:
48
+
49
+ ```ruby
50
+ # config/providers/db.rb
51
+ Hanami.app.configure_provider :db do
52
+ config.gateway :default do |gw|
53
+ gw.connection_options after_connect: ->(conn) { conn.busy_handler_timeout = 5000 }
54
+ end
55
+ end
56
+ ```
57
+
58
+ mankai-cache-sql leaves your connection as it is and prints a warning until it has an `after_connect`.
59
+
60
+ ## Options
61
+
62
+ `Mankai::Cache::SQL.store(...)` takes:
63
+
64
+ | Option | Default | Description |
65
+ |---|---|---|
66
+ | `gateway` | `"db.gateway"` | A container key (`"db.gateways.cache"` for a [separate database](#a-separate-database)), a ROM gateway or a `Sequel::Database`. |
67
+ | `table` | `:cache_entries` | The table's name. Use the same `table:` as `Migration.install`. |
68
+ | `max_age` | `14 * 86_400` (two weeks) | Seconds since an entry was last written after which expiry deletes it, whatever its `expires_in`. `nil` keeps entries until `max_entries` or `max_size` needs the room. |
69
+ | `max_entries` | `nil` | Most entries to keep (estimated). `nil` for no limit. |
70
+ | `max_size` | `nil` | Most bytes of keys and values to keep (estimated). `nil` for no limit. |
71
+ | `expiry_batch_size` | `100` | How many of the oldest entries each expiry pass looks at. A pass runs every `expiry_batch_size / 2` writes. |
72
+ | `expiry` | `:thread` | `:thread` runs expiry passes in a background thread; `:inline` runs them in the writing thread. |
73
+ | `clock` | `-> { Time.now }` | Returns the current Time, for `created_at` and `max_age`. |
74
+ | `on_error` | warns | Called with errors raised by background expiry passes. |
75
+
76
+ Unknown options raise `ArgumentError`, and a bad `gateway` or `expiry` raises
77
+ `Mankai::Cache::ConfigurationError`, when the provider starts.
78
+
79
+ ### Expiry caveats
80
+
81
+ - `max_age` counts from the entry's last write (`created_at`), not from its `expires_in`. An
82
+ entry written with `expires_in: 30 * 86_400` is still deleted after `max_age`. Set `max_age`
83
+ at least as long as your longest `expires_in`, or `nil`.
84
+ - `expires_in` is checked on read, so an expired entry stays in the table until an expiry pass
85
+ deletes it by age or size.
86
+ - A pass only looks at the oldest `expiry_batch_size` entries, by id. An overwritten entry keeps
87
+ its id, so keys that are rewritten often (a counter, a popular fragment) stay at the front with
88
+ a fresh `created_at`. When the whole batch is such keys, passes delete nothing by age, and
89
+ entries behind them are only deleted once `max_entries` or `max_size` is reached. If you have
90
+ a few hot keys, set `max_entries` or `max_size`, or raise `expiry_batch_size` above the
91
+ number of hot keys.
92
+
93
+ ### A separate database
94
+
95
+ A cache table grows and churns, so it can be worth keeping out of the app's database. Hanami
96
+ connects one database per gateway, and finds a gateway's URL in `DATABASE_URL__<NAME>`:
97
+
98
+ ```bash
99
+ # .env
100
+ DATABASE_URL=postgres://localhost/bookshelf
101
+ DATABASE_URL__CACHE=postgres://localhost/bookshelf_cache
102
+ ```
103
+
104
+ `hanami db migrate` runs each gateway's migrations from its own directory, here
105
+ `config/db/cache_migrate`. Install the migration there:
106
+
107
+ ```bash
108
+ bundle exec ruby -e 'require "mankai/cache/sql"; Mankai::Cache::SQL::Migration.install(root: ".", gateway: :cache)'
109
+ bundle exec hanami db create
110
+ bundle exec hanami db migrate
111
+ ```
112
+
113
+ Then point the store at the gateway:
114
+
115
+ ```ruby
116
+ config.store = Mankai::Cache::SQL.store(gateway: "db.gateways.cache")
117
+ ```
118
+
119
+ In the test environment, Hanami adds `_test` to the database names in these URLs.
120
+
121
+ ## How it works
122
+
123
+ - **Lookups.** Each row has `key_hash`, the first 8 bytes of the key's SHA-256 digest, with a
124
+ unique index. Lookups use it, so the index stays small however long keys are. The full key is
125
+ stored too and compared on read.
126
+ - **Writes** are one upsert (`ON CONFLICT` on PostgreSQL and SQLite, `ON DUPLICATE KEY` on
127
+ MySQL and MariaDB), for one entry or many.
128
+ - **Increments** lock the row (`FOR UPDATE`, or an immediate transaction on SQLite). When there
129
+ is no row yet and another process inserts one first, the increment retries on top of it.
130
+ - **Expiry.** Entries are not deleted when they expire: the cache checks expiry when it reads.
131
+ Instead, after every `expiry_batch_size / 2` writes, an expiry pass looks at the oldest
132
+ `expiry_batch_size` entries (by id, so no index on times is needed):
133
+ - Over `max_entries` or `max_size`, it deletes all of them.
134
+ - Otherwise it deletes those older than `max_age`.
135
+
136
+ Passes delete up to twice as fast as entries are written, so the table stays near its limits.
137
+ Counts and sizes are estimated (the span of ids, and the average size of the newest 1,000
138
+ entries), so checking them stays cheap on large tables.
139
+ - An overwritten entry keeps its id, and so its place in that order: with `max_entries` or
140
+ `max_size`, a key first written long ago may be deleted before newer keys.
141
+
142
+ `cache.cleanup` runs an expiry pass now. With `expiry: :thread`, `cache.close` (called when the
143
+ provider stops) waits for a running pass.
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ class Cache
5
+ module SQL
6
+ # Deletes the oldest entries, a batch at a time.
7
+ #
8
+ # Entries are deleted in insertion order (by id), so no index on expiry times is needed.
9
+ # From the oldest `batch_size` entries, those older than `max_age` are deleted; when the
10
+ # table is over `max_entries` or `max_size`, all of them are.
11
+ #
12
+ # Counts and sizes are estimates, so that checking them stays cheap on large tables: the
13
+ # entry count is the span of ids, and the size is that count times the average size of the
14
+ # newest 1,000 entries.
15
+ #
16
+ # @api private
17
+ # @since 0.1.0
18
+ class Expiry
19
+ # @api private
20
+ # @since 0.1.0
21
+ SIZE_SAMPLE = 1000
22
+
23
+ # @api private
24
+ # @since 0.1.0
25
+ attr_reader :max_age, :max_entries, :max_size, :batch_size
26
+
27
+ # @api private
28
+ # @since 0.1.0
29
+ def initialize(dataset:, max_age:, max_entries:, max_size:, batch_size:)
30
+ @dataset = dataset
31
+ @max_age = max_age
32
+ @max_entries = max_entries
33
+ @max_size = max_size
34
+ @batch_size = batch_size
35
+ end
36
+
37
+ # @param now [Time]
38
+ # @return [Integer] how many entries were deleted
39
+ #
40
+ # @api private
41
+ # @since 0.1.0
42
+ def call(now)
43
+ ids = @dataset.order(:id).limit(batch_size).select_map(:id)
44
+ return 0 if ids.empty?
45
+
46
+ scope = @dataset.where(id: ids)
47
+ unless over_limits?
48
+ return 0 unless max_age
49
+
50
+ scope = scope.where(Sequel[:created_at] < now - max_age)
51
+ end
52
+ scope.delete
53
+ end
54
+
55
+ # @api private
56
+ # @since 0.1.0
57
+ def over_limits?
58
+ return false unless max_entries || max_size
59
+
60
+ entries = estimated_entries
61
+ (max_entries && entries > max_entries) || (max_size && estimated_size(entries) > max_size)
62
+ end
63
+
64
+ # @api private
65
+ # @since 0.1.0
66
+ def estimated_entries
67
+ first, last = @dataset.get([Sequel.function(:min, :id).as(:first), Sequel.function(:max, :id).as(:last)])
68
+ last ? last - first + 1 : 0
69
+ end
70
+
71
+ # @api private
72
+ # @since 0.1.0
73
+ def estimated_size(entries)
74
+ sample = @dataset.reverse(:id).limit(SIZE_SAMPLE).select(:byte_size)
75
+ average = @dataset.db.from(sample.as(:sample)).avg(:byte_size)
76
+ average ? (average.to_f * entries).to_i : 0
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+ require "fileutils"
5
+
6
+ module Mankai
7
+ class Cache
8
+ module SQL
9
+ # Renders mankai-cache-sql's migration, and installs it into an app.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ module Migration
14
+ # @api private
15
+ # @since 0.1.0
16
+ NAME = "create_mankai_cache_entries"
17
+
18
+ # @api private
19
+ # @since 0.1.0
20
+ TEMPLATE = File.join(__dir__, "templates", "create_cache_entries.rb.erb")
21
+
22
+ module_function
23
+
24
+ # @param migration_dsl ["ROM::SQL", "Sequel"] the object whose .migration builds it.
25
+ # Hanami apps use ROM::SQL; plain Sequel projects use Sequel.
26
+ #
27
+ # @api public
28
+ # @since 0.1.0
29
+ def render(table: Store::DEFAULT_TABLE, migration_dsl: "ROM::SQL")
30
+ ERB.new(File.read(TEMPLATE), trim_mode: "-").result_with_hash(table: table, migration_dsl: migration_dsl)
31
+ end
32
+
33
+ # Writes the migration into config/db/migrate, unless the app has it already.
34
+ #
35
+ # @param gateway [Symbol, String, nil] a Hanami database gateway other than :default, e.g.
36
+ # :cache for a separate cache database: the migration then goes into
37
+ # config/db/<gateway>_migrate, where `hanami db migrate` looks for that gateway's
38
+ # migrations
39
+ # @return [String] the migration's path
40
+ #
41
+ # @api public
42
+ # @since 0.1.0
43
+ def install(root:, out: $stdout, table: Store::DEFAULT_TABLE, gateway: nil, now: Time.now.utc)
44
+ dir = File.join(root.to_s, "config", "db", migrations_dir(gateway))
45
+ existing = Dir.glob(File.join(dir, "*_#{NAME}.rb")).min
46
+ if existing
47
+ out.puts "Migration already exists: #{existing}"
48
+ return existing
49
+ end
50
+
51
+ FileUtils.mkdir_p(dir)
52
+ path = File.join(dir, "#{now.strftime("%Y%m%d%H%M%S")}_#{NAME}.rb")
53
+ File.write(path, render(table: table))
54
+ out.puts "Created #{path}"
55
+ out.puts "Run `hanami db migrate` to create the table."
56
+ path
57
+ end
58
+
59
+ # @api private
60
+ # @since 0.1.0
61
+ def migrations_dir(gateway)
62
+ gateway.nil? || gateway.to_s == "default" ? "migrate" : "#{gateway}_migrate"
63
+ end
64
+
65
+ # Applies the migration directly to a Sequel database. For tests and non-Hanami use.
66
+ #
67
+ # @api public
68
+ # @since 0.1.0
69
+ def apply(db, direction = :up, table: Store::DEFAULT_TABLE)
70
+ Sequel.extension :migration
71
+ source = render(table: table, migration_dsl: "Sequel")
72
+ eval(source, TOPLEVEL_BINDING, TEMPLATE).apply(db, direction) # rubocop:disable Security/Eval
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,271 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Mankai
6
+ class Cache
7
+ module SQL
8
+ # Keeps entries in a SQL table, shared by every process that uses the database.
9
+ #
10
+ # Entries are found by `key_hash`, the first 8 bytes of the key's SHA-256 digest, so the
11
+ # unique index stays small however long keys are; the full key is stored too and checked on
12
+ # read. Writes are upserts.
13
+ #
14
+ # Entries are not deleted when they expire (the cache checks expiry when it reads). Instead,
15
+ # after every `expiry_batch_size / 2` writes the oldest entries are deleted, a batch at a
16
+ # time, by age and by the table's size (see Expiry). That runs in a background thread by
17
+ # default; `expiry: :inline` runs it in the writing thread instead.
18
+ #
19
+ # An overwritten entry keeps its place in that order, so with `max_entries` or `max_size`
20
+ # a key written long ago and overwritten since may be deleted before newer keys.
21
+ #
22
+ # @api public
23
+ # @since 0.1.0
24
+ class Store
25
+ include Cache::Store
26
+
27
+ # @api public
28
+ # @since 0.1.0
29
+ DEFAULT_TABLE = :cache_entries
30
+
31
+ # @api private
32
+ # @since 0.1.0
33
+ EXPIRY_MODES = %i[thread inline].freeze
34
+
35
+ # @api public
36
+ # @since 0.1.0
37
+ attr_reader :db, :table, :expiry
38
+
39
+ # @param db [Sequel::Database]
40
+ # @param table [Symbol]
41
+ # @param max_age [Numeric, nil] seconds to keep entries (two weeks by default); nil keeps
42
+ # them until max_entries or max_size needs the room
43
+ # @param max_entries [Integer, nil]
44
+ # @param max_size [Integer, nil] bytes of keys and values
45
+ # @param expiry_batch_size [Integer] how many of the oldest entries each expiry pass looks at
46
+ # @param expiry [:thread, :inline] where expiry passes run
47
+ # @param clock [#call] returns the current Time
48
+ # @param on_error [#call] called with errors raised by a background expiry pass
49
+ #
50
+ # @api public
51
+ # @since 0.1.0
52
+ def initialize(
53
+ db:,
54
+ table: DEFAULT_TABLE,
55
+ max_age: 14 * 86_400,
56
+ max_entries: nil,
57
+ max_size: nil,
58
+ expiry_batch_size: 100,
59
+ expiry: :thread,
60
+ clock: -> { Time.now },
61
+ on_error: ->(error) { warn("[mankai-cache-sql] cache expiry failed: #{error.class}: #{error.message}") }
62
+ )
63
+ unless EXPIRY_MODES.include?(expiry)
64
+ raise ConfigurationError, "expiry must be one of #{EXPIRY_MODES.inspect}, got #{expiry.inspect}"
65
+ end
66
+
67
+ @db = db
68
+ @table = table.to_sym
69
+ @expiry = Expiry.new(
70
+ dataset: dataset, max_age: max_age, max_entries: max_entries, max_size: max_size,
71
+ batch_size: expiry_batch_size
72
+ )
73
+ @expiry_mode = expiry
74
+ @expire_every = [expiry_batch_size / 2, 1].max
75
+ @clock = clock
76
+ @on_error = on_error
77
+ @writes = 0
78
+ @lock = Mutex.new
79
+ @expiring = nil
80
+ end
81
+
82
+ # @api public
83
+ # @since 0.1.0
84
+ def read(key)
85
+ row = dataset.where(key_hash: key_hash(key)).select(:key, :value).first
86
+ String.new(row[:value]).b if row && same_key?(row, key)
87
+ end
88
+
89
+ # @api public
90
+ # @since 0.1.0
91
+ def read_multi(keys)
92
+ by_hash = keys.to_h { |key| [key_hash(key), key] }
93
+ dataset.where(key_hash: by_hash.keys).select(:key_hash, :key, :value).each_with_object({}) do |row, found|
94
+ key = by_hash[row[:key_hash]]
95
+ found[key] = String.new(row[:value]).b if key && same_key?(row, key)
96
+ end
97
+ end
98
+
99
+ # @api public
100
+ # @since 0.1.0
101
+ def write(key, data, expires_at:)
102
+ write_multi({key => data}, expires_at: expires_at)
103
+ end
104
+
105
+ # @api public
106
+ # @since 0.1.0
107
+ def write_multi(entries, expires_at:)
108
+ return true if entries.empty?
109
+
110
+ now = @clock.call
111
+ upsert(entries.map { |key, data| row(key, data, now) })
112
+ wrote(entries.size)
113
+ true
114
+ end
115
+
116
+ # @api public
117
+ # @since 0.1.0
118
+ def delete(key)
119
+ dataset.where(key_hash: key_hash(key)).delete.positive?
120
+ end
121
+
122
+ # @api public
123
+ # @since 0.1.0
124
+ def delete_multi(keys)
125
+ dataset.where(key_hash: keys.map { |key| key_hash(key) }).delete
126
+ end
127
+
128
+ # Locks the entry's row while the block runs. When there is no row yet and another process
129
+ # inserts one first, the block runs again with that process's data.
130
+ #
131
+ # @api public
132
+ # @since 0.1.0
133
+ def update(key)
134
+ hash = key_hash(key)
135
+ loop do
136
+ written = db.transaction(**lock_options) do
137
+ row = dataset.where(key_hash: hash).for_update.select(:key, :value).first
138
+ data, = yield(row && same_key?(row, key) ? String.new(row[:value]).b : nil)
139
+ row ? replace(hash, key, data) : insert(key, data)
140
+ end
141
+ break if written
142
+ end
143
+ wrote(1)
144
+ end
145
+
146
+ # @api public
147
+ # @since 0.1.0
148
+ def clear
149
+ dataset.delete
150
+ true
151
+ end
152
+
153
+ # Runs an expiry pass now (see Expiry). Expired entries are not looked for one by one.
154
+ #
155
+ # @return [Integer] how many entries were deleted
156
+ #
157
+ # @api public
158
+ # @since 0.1.0
159
+ def cleanup(_now = nil)
160
+ @expiry.call(@clock.call)
161
+ end
162
+
163
+ # Waits for a running background expiry pass.
164
+ #
165
+ # @api public
166
+ # @since 0.1.0
167
+ def close
168
+ @lock.synchronize { @expiring }&.join
169
+ end
170
+
171
+ # @api private
172
+ # @since 0.1.0
173
+ def dataset
174
+ db[table]
175
+ end
176
+
177
+ private
178
+
179
+ # @api private
180
+ # @since 0.1.0
181
+ def key_hash(key)
182
+ Digest::SHA256.digest(key).unpack1("q>")
183
+ end
184
+
185
+ # @api private
186
+ # @since 0.1.0
187
+ def same_key?(row, key)
188
+ row[:key].b == key.b
189
+ end
190
+
191
+ # @api private
192
+ # @since 0.1.0
193
+ def row(key, data, now)
194
+ {
195
+ key_hash: key_hash(key), key: Sequel.blob(key.b), value: Sequel.blob(data.b),
196
+ byte_size: key.bytesize + data.bytesize, created_at: now
197
+ }
198
+ end
199
+
200
+ # @api private
201
+ # @since 0.1.0
202
+ def upsert(rows)
203
+ if db.database_type == :mysql
204
+ dataset.on_duplicate_key_update(:key, :value, :byte_size, :created_at).multi_insert(rows)
205
+ else
206
+ excluded = %i[key value byte_size created_at].to_h { |column| [column, Sequel[:excluded][column]] }
207
+ dataset.insert_conflict(target: :key_hash, update: excluded).multi_insert(rows)
208
+ end
209
+ end
210
+
211
+ # @api private
212
+ # @since 0.1.0
213
+ def replace(hash, key, data)
214
+ dataset.where(key_hash: hash).update(row(key, data, @clock.call).except(:key_hash))
215
+ true
216
+ end
217
+
218
+ # @return [Boolean] false when another process inserted the row first
219
+ #
220
+ # @api private
221
+ # @since 0.1.0
222
+ def insert(key, data)
223
+ db.transaction(savepoint: true) { dataset.insert(row(key, data, @clock.call)) }
224
+ true
225
+ rescue Sequel::UniqueConstraintViolation
226
+ false
227
+ end
228
+
229
+ # SQLite has no row locks: take the write lock up front, so two increments cannot both
230
+ # read the old value.
231
+ #
232
+ # @api private
233
+ # @since 0.1.0
234
+ def lock_options
235
+ db.database_type == :sqlite ? {mode: :immediate} : {}
236
+ end
237
+
238
+ # Counts writes, and starts an expiry pass every `expire_every` of them.
239
+ #
240
+ # @api private
241
+ # @since 0.1.0
242
+ def wrote(count)
243
+ due = @lock.synchronize do
244
+ @writes += count
245
+ next false if @writes < @expire_every
246
+
247
+ @writes = 0
248
+ true
249
+ end
250
+ return unless due
251
+
252
+ @expiry_mode == :inline ? cleanup : expire_in_background
253
+ end
254
+
255
+ # @api private
256
+ # @since 0.1.0
257
+ def expire_in_background
258
+ @lock.synchronize do
259
+ return if @expiring&.alive?
260
+
261
+ @expiring = Thread.new do
262
+ cleanup
263
+ rescue StandardError => exception
264
+ @on_error.call(exception)
265
+ end
266
+ end
267
+ end
268
+ end
269
+ end
270
+ end
271
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The table for mankai-cache-sql. This migration is yours: adapt it as needed.
4
+ #
5
+ # It is idempotent: an existing table is left alone, so running it twice (or having two copies
6
+ # of it) does no harm.
7
+ <%= migration_dsl %>.migration do
8
+ up do
9
+ create_table? :<%= table %> do
10
+ primary_key :id, type: :Bignum
11
+ # The first 8 bytes of the key's SHA-256 digest: entries are found by this, so the index
12
+ # stays small however long keys are.
13
+ Bignum :key_hash, null: false
14
+ File :key, null: false
15
+ # Up to 16 MB on MySQL and MariaDB; unlimited elsewhere.
16
+ File :value, null: false, size: :medium
17
+ Integer :byte_size, null: false
18
+ Time :created_at, null: false
19
+
20
+ index :key_hash, unique: true
21
+ end
22
+ end
23
+
24
+ down do
25
+ drop_table? :<%= table %>
26
+ end
27
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ class Cache
5
+ module SQL
6
+ # @api public
7
+ # @since 0.1.0
8
+ VERSION = "0.1.0"
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sequel"
4
+ require "zeitwerk"
5
+ require "mankai/cache"
6
+
7
+ module Mankai
8
+ class Cache
9
+ # SQL store for mankai-cache.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ module SQL
14
+ # @api private
15
+ # @since 0.1.0
16
+ def self.gem_loader
17
+ @gem_loader ||= Zeitwerk::Loader.new.tap do |loader|
18
+ root = File.expand_path("../..", __dir__)
19
+ loader.tag = "mankai-cache-sql"
20
+ loader.inflector = Zeitwerk::GemInflector.new("#{root}/mankai-cache-sql.rb")
21
+ loader.push_dir(root)
22
+ loader.ignore(
23
+ "#{root}/mankai-cache-sql.rb",
24
+ "#{root}/mankai/cache/sql/version.rb",
25
+ "#{root}/mankai/cache/sql/templates"
26
+ )
27
+ loader.inflector.inflect("sql" => "SQL")
28
+ end
29
+ end
30
+
31
+ gem_loader.setup
32
+ require_relative "sql/version"
33
+
34
+ # A store factory for the provider:
35
+ #
36
+ # config.store = Mankai::Cache::SQL.store(max_age: 7 * 86_400)
37
+ #
38
+ # @param gateway [String, ROM::Gateway, Sequel::Database] a container key (default
39
+ # "db.gateway"; use "db.gateways.cache" for a separate database), a ROM gateway, or a
40
+ # Sequel::Database
41
+ # @param options see Store#initialize
42
+ #
43
+ # @api public
44
+ # @since 0.1.0
45
+ def self.store(gateway: "db.gateway", **options)
46
+ ->(container) { Store.new(db: database(gateway, container), **options) }
47
+ end
48
+
49
+ # @api private
50
+ # @since 0.1.0
51
+ def self.database(gateway, container)
52
+ gateway = container[gateway] if gateway.is_a?(String)
53
+ gateway = gateway.connection if gateway.respond_to?(:connection) && !gateway.is_a?(Sequel::Database)
54
+ if gateway.is_a?(Sequel::Database)
55
+ warn_about_sqlite_locking(gateway)
56
+ return gateway
57
+ end
58
+
59
+ raise ConfigurationError,
60
+ "gateway must be a container key, a ROM gateway or a Sequel::Database, got #{gateway.inspect}"
61
+ end
62
+
63
+ # See the README: a SQLite connection waiting for a lock otherwise stalls every thread.
64
+ #
65
+ # @api private
66
+ # @since 0.1.0
67
+ def self.warn_about_sqlite_locking(db)
68
+ return unless db.database_type == :sqlite && db.opts[:after_connect].nil?
69
+
70
+ warn "[mankai-cache] SQLite connections hold Ruby's global lock while waiting for a database lock, " \
71
+ "stalling other threads (such as background expiry). Add after_connect: ->(conn) " \
72
+ "{ conn.busy_handler_timeout = 5000 } to the database's connection options (see the mankai-cache-sql README)."
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "mankai/cache/sql"
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "mankai/cache/sql/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "mankai-cache-sql"
9
+ spec.authors = ["Ibrahim Diallo"]
10
+ spec.email = ["thisis@ibrahimd.com"]
11
+ spec.license = "MIT"
12
+ spec.version = Mankai::Cache::SQL::VERSION.dup
13
+ spec.homepage = "https://github.com/thisisibrahimd/mankai"
14
+ spec.metadata["github_repo"] = "https://github.com/thisisibrahimd/mankai"
15
+ spec.metadata["source_code_uri"] = "https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql"
16
+ spec.metadata["changelog_uri"] = "https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-cache-sql/CHANGELOG.md"
17
+ spec.metadata["rubygems_mfa_required"] = "true"
18
+
19
+ spec.summary = "SQL database store for mankai-cache"
20
+ spec.description = <<~TEXT
21
+ Keeps cache entries in a SQL table (PostgreSQL, MySQL 8+, MariaDB, SQLite), found by a
22
+ 64-bit key hash and expired oldest-first by age, entry count or total size.
23
+ TEXT
24
+ spec.files = Dir["CHANGELOG.md", "LICENSE", "README.md", "mankai-cache-sql.gemspec", "lib/**/*"]
25
+ spec.require_paths = ["lib"]
26
+
27
+ spec.extra_rdoc_files = ["README.md", "CHANGELOG.md", "LICENSE"]
28
+
29
+ spec.required_ruby_version = ">= 3.3"
30
+
31
+ spec.add_runtime_dependency "mankai-cache", "~> 0.1.0"
32
+ spec.add_runtime_dependency "sequel", "~> 5.70"
33
+ spec.add_runtime_dependency "zeitwerk", "~> 2.6"
34
+ end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mankai-cache-sql
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ibrahim Diallo
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: mankai-cache
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.1.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.1.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: sequel
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '5.70'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '5.70'
40
+ - !ruby/object:Gem::Dependency
41
+ name: zeitwerk
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '2.6'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '2.6'
54
+ description: |
55
+ Keeps cache entries in a SQL table (PostgreSQL, MySQL 8+, MariaDB, SQLite), found by a
56
+ 64-bit key hash and expired oldest-first by age, entry count or total size.
57
+ email:
58
+ - thisis@ibrahimd.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files:
62
+ - CHANGELOG.md
63
+ - LICENSE
64
+ - README.md
65
+ files:
66
+ - CHANGELOG.md
67
+ - LICENSE
68
+ - README.md
69
+ - lib/mankai-cache-sql.rb
70
+ - lib/mankai/cache/sql.rb
71
+ - lib/mankai/cache/sql/expiry.rb
72
+ - lib/mankai/cache/sql/migration.rb
73
+ - lib/mankai/cache/sql/store.rb
74
+ - lib/mankai/cache/sql/templates/create_cache_entries.rb.erb
75
+ - lib/mankai/cache/sql/version.rb
76
+ - mankai-cache-sql.gemspec
77
+ homepage: https://github.com/thisisibrahimd/mankai
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ github_repo: https://github.com/thisisibrahimd/mankai
82
+ source_code_uri: https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-cache-sql
83
+ changelog_uri: https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-cache-sql/CHANGELOG.md
84
+ rubygems_mfa_required: 'true'
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '3.3'
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubygems_version: 4.0.20
100
+ specification_version: 4
101
+ summary: SQL database store for mankai-cache
102
+ test_files: []