mankai-sockets-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: adbd033d437055e0154dd1a94ee71045f305741be1cd342bca18d2fbb0c985a6
4
+ data.tar.gz: f31180a58dee4109b5cd48c55ec138cc861093d18933d815ae82cb8ef3ad5a94
5
+ SHA512:
6
+ metadata.gz: ca3e6488e38bc01da98c34b6c5fdb18da16eadde0fab18c51223011bfe9f5d37cfa07ffdda97d33abe579a9f5451193e5d8cebe4e3b09b8b6a2ec432bbce5259
7
+ data.tar.gz: 702510b7c57eef4ebf6e8a25e4a91b287061c802d310883151b20c125efe4e85b270772114aa40913858ee1145237faa8bcadf75b9e35582e18cd2dc2889dd7b
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
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 backend that carries broadcasts between processes through a messages table, with publisher-side writes that join the caller's transaction.
13
+ - A per-process polling listener with a quiet connection pool, per-stream cursors, collision checks and error backoff.
14
+ - Retention trimming by age, in a background thread or inline, with warnings for pool size, time precision and SQLite locking.
15
+ - A dry-schema options validator, a factory with gateway resolution, a migration installer and a `hanami sockets install --backend=sql` hook.
16
+
17
+ ### Fixed
18
+
19
+ - A stream only receives messages published after it started being watched: the listener no longer delivers retained messages to a newly subscribed stream.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Mankai contributors
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,125 @@
1
+ <img src="../../assets/logo/mankai-logo.svg" alt="Mankai" width="72">
2
+
3
+ # mankai-sockets-sql
4
+
5
+ A database-backed backend for `mankai-sockets`, so broadcasts reach subscribers on other
6
+ processes: several Puma workers or servers, a separate sockets process, or a job worker that
7
+ broadcasts. Messages travel through a table that a polling listener reads and a trimmer prunes.
8
+
9
+ ## Install
10
+
11
+ Both gems go in the `:cli` group, so `hanami sockets install` can load the SQL gem and write the
12
+ migration:
13
+
14
+ ```ruby
15
+ # Gemfile
16
+ gem "mankai-sockets", group: [:default, :cli]
17
+ gem "mankai-sockets-sql", group: [:default, :cli]
18
+ ```
19
+
20
+ ```bash
21
+ bundle install
22
+ bundle exec hanami sockets install --backend=sql
23
+ bundle exec hanami db migrate
24
+ ```
25
+
26
+ The installer writes `create_mankai_sockets_messages` into `config/db/migrate` (and copies the
27
+ browser client; see mankai-sockets). The migration is idempotent: an existing table is left alone.
28
+ Keep the table in the app's database, or put it in a separate one by pointing `gateway:` at a
29
+ second gateway.
30
+
31
+ The app needs hanami-db with a database configured, such as `DATABASE_URL`, so that `db.gateway`
32
+ exists.
33
+
34
+ ## Configure the provider
35
+
36
+ Require the SQL gem and set the backend. Everything else stays as it is in a memory setup; the
37
+ provider still needs `allowed_origins`, `channels`, and an `authenticator` (or
38
+ `allow_anonymous = true`):
39
+
40
+ ```ruby
41
+ # config/providers/sockets.rb
42
+ require "mankai/sockets"
43
+ require "mankai/sockets/sql"
44
+
45
+ Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
46
+ configure do |config|
47
+ config.backend =
48
+ if Hanami.env?(:test)
49
+ :memory
50
+ else
51
+ Mankai::Sockets::SQL.backend(gateway: "db.gateway")
52
+ end
53
+ config.authenticator = lambda do |request, _token_subject|
54
+ user_id = request.session[:user_id]
55
+ user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
56
+ end
57
+ config.allowed_origins = :same_origin
58
+ config.channels = {"chat" => "channels.chat"}
59
+ end
60
+ end
61
+ ```
62
+
63
+ ## Options
64
+
65
+ `Mankai::Sockets::SQL.backend(**options)` takes:
66
+
67
+ | Option | Default | Description |
68
+ |---|---|---|
69
+ | `gateway` | `"db.gateway"` | Container key, a gateway with `#connection`, or a `Sequel::Database` |
70
+ | `table` | `:sockets_messages` | Table name |
71
+ | `polling_interval` | `0.1` | Seconds between polls |
72
+ | `batch_size` | `500` | Rows read per poll |
73
+ | `retention` | `86_400` | Seconds to keep messages |
74
+ | `trim_every` | `100` | Publishes between trims |
75
+ | `trim_batch_size` | `200` | Rows deleted per trim |
76
+ | `trim` | `:thread` | `:thread` trims on a background thread; `:inline` trims inside `publish` |
77
+ | `silence_polling` | `true` | Poll with a second connection pool that has no loggers, so polls stay out of the SQL log |
78
+
79
+ Unknown or invalid options raise `Mankai::Sockets::ConfigurationError` at boot.
80
+
81
+ ## How it works
82
+
83
+ `publish` inserts a row on the app's connection, so it joins the caller's transaction and rolls
84
+ back with it. It works without a listener, so a job worker or a console can broadcast without
85
+ serving sockets. The row stores the first eight bytes of the stream name's SHA-256 digest as a
86
+ signed integer and the payload as JSON in a TEXT column (65,535 bytes on MySQL, which is why the
87
+ core gem's `max_payload_size` defaults to 60,000).
88
+
89
+ Each process that serves sockets starts one listener and, in `:thread` mode, one trim thread with
90
+ its first websocket. The listener polls for new rows on the streams its connections watch, and
91
+ checks the stored stream name before delivering, so a digest collision can never send a message
92
+ to the wrong stream.
93
+
94
+ A stream receives only messages published after it started being watched. Rows kept for
95
+ `retention` are never replayed: not when a listener starts, and not when a client subscribes to a
96
+ stream nobody in that process was watching. Delivery is at most once and isn't retried, so don't
97
+ rely on this backend for durable event delivery.
98
+
99
+ ## Database notes
100
+
101
+ The app's pool needs `executor_threads` connections for channel code that queries, plus one for
102
+ the listener. With `silence_polling`, the listener polls through a second pool built from the same
103
+ settings, which opens one more connection per process. Warnings are logged at boot for:
104
+
105
+ - An app pool smaller than the executor threads plus one. Raise `max_connections` on the database
106
+ URL.
107
+ - MySQL or MariaDB connections without fractional seconds. Add `fractional_seconds=true` to the URL.
108
+ - SQLite connections without a busy handler.
109
+
110
+ The gem never changes the app's connection; it says how to fix it.
111
+
112
+ ## Retention
113
+
114
+ Every `trim_every` publishes, the trimmer deletes up to `trim_batch_size` rows older than
115
+ `retention`, oldest first. Run it on demand with:
116
+
117
+ ```ruby
118
+ Hanami.app["sockets.backend"].trim
119
+ ```
120
+
121
+ ## Tests
122
+
123
+ Use the `:memory` backend in your app's tests. This gem's own specs use SQLite by default; set
124
+ `DATABASE_URL` to run them on PostgreSQL, MySQL or MariaDB, and `make test/matrix` runs every
125
+ supported database.
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ module SQL
8
+ # The Backend contract over a messages table. Publishes happen on the app's connection, so
9
+ # they join the caller's transaction; polling uses a separate quiet pool.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ class Backend
14
+ # @api private
15
+ # @since 0.1.0
16
+ DEFAULT_TABLE = :sockets_messages
17
+
18
+ # @api private
19
+ # @since 0.1.0
20
+ attr_reader :table, :options
21
+
22
+ # @api private
23
+ # @since 0.1.0
24
+ def initialize(db:, table:, clock:, instrumenter:, options:, quiet_db: nil)
25
+ @db = db
26
+ @table = table
27
+ @clock = clock
28
+ @instrumenter = instrumenter
29
+ @options = options
30
+ @listeners = {}
31
+ @mutex = Mutex.new
32
+ @writes = 0
33
+ @pid = nil
34
+ @quiet_db = quiet_db
35
+ @trimmer = Trimmer.new(
36
+ db: db, table: table, retention: options[:retention],
37
+ batch_size: options[:trim_batch_size], clock: clock,
38
+ instrumenter: instrumenter, mode: options[:trim]
39
+ )
40
+ end
41
+
42
+ # Inserts a message and returns its id. Works before #start.
43
+ #
44
+ # @api public
45
+ # @since 0.1.0
46
+ def publish(stream_name, payload)
47
+ id = @db[@table].insert(
48
+ stream_hash: self.class.stream_hash(stream_name),
49
+ stream: stream_name,
50
+ payload: payload,
51
+ created_at: @clock.call
52
+ )
53
+ count_writes
54
+ id
55
+ end
56
+
57
+ # @api public
58
+ # @since 0.1.0
59
+ def subscribe(stream_name, listener)
60
+ @mutex.synchronize { (@listeners[stream_name] ||= {})[listener] = true }
61
+ end
62
+
63
+ # @api public
64
+ # @since 0.1.0
65
+ def unsubscribe(stream_name, listener)
66
+ @mutex.synchronize do
67
+ listeners = @listeners[stream_name]
68
+ next unless listeners
69
+
70
+ listeners.delete(listener)
71
+ @listeners.delete(stream_name) if listeners.empty?
72
+ end
73
+ end
74
+
75
+ # Starts the listener and trimmer in this process. Idempotent per process; objects from
76
+ # a parent process are dropped rather than stopped.
77
+ #
78
+ # @api public
79
+ # @since 0.1.0
80
+ def start
81
+ @mutex.synchronize do
82
+ next if @pid == Process.pid
83
+
84
+ @pid = Process.pid
85
+ @quiet_db ||= Factory.quiet_copy(@db)
86
+ @listener = build_listener
87
+ @trimmer.start
88
+ @listener.start
89
+ end
90
+ end
91
+
92
+ # @api public
93
+ # @since 0.1.0
94
+ def stop
95
+ @mutex.synchronize do
96
+ @listener&.stop
97
+ @listener = nil
98
+ @trimmer.stop
99
+ @quiet_db&.disconnect
100
+ @pid = nil
101
+ end
102
+ end
103
+
104
+ # Runs a trim now.
105
+ #
106
+ # @api public
107
+ # @since 0.1.0
108
+ def trim
109
+ @trimmer.delete_old
110
+ end
111
+
112
+ # @api private
113
+ # @since 0.1.0
114
+ def self.stream_hash(stream)
115
+ Digest::SHA256.digest(stream.to_s).unpack1("q>")
116
+ end
117
+
118
+ private
119
+
120
+ # @api private
121
+ # @since 0.1.0
122
+ def build_listener
123
+ Listener.new(
124
+ db: @quiet_db,
125
+ table: @table,
126
+ hashes: -> { @mutex.synchronize { @listeners.keys.map { |name| self.class.stream_hash(name) } } },
127
+ streams: ->(hash) {
128
+ @mutex.synchronize {
129
+ @listeners.keys.find { |name|
130
+ self.class.stream_hash(name) == hash
131
+ }
132
+ }
133
+ },
134
+ on_message: ->(broadcast) { deliver(broadcast) },
135
+ polling_interval: @options[:polling_interval],
136
+ batch_size: @options[:batch_size],
137
+ silence_polling: @options[:silence_polling],
138
+ instrumenter: @instrumenter
139
+ )
140
+ end
141
+
142
+ # @api private
143
+ # @since 0.1.0
144
+ def deliver(broadcast)
145
+ listeners = @mutex.synchronize { (@listeners[broadcast.stream] || {}).keys }
146
+ listeners.each { |listener| listener.call(broadcast) }
147
+ end
148
+
149
+ # @api private
150
+ # @since 0.1.0
151
+ def count_writes
152
+ return if @options[:trim_every] <= 0 || @options[:retention] <= 0
153
+
154
+ @mutex.synchronize do
155
+ @writes += 1
156
+ if @writes >= @options[:trim_every]
157
+ @writes = 0
158
+ @trimmer.call
159
+ end
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ module SQL
6
+ # Builds the backend from the provider's context and the options given to SQL.backend.
7
+ #
8
+ # @api private
9
+ # @since 0.1.0
10
+ module Factory
11
+ # Makes SQLite wait for locks without holding Ruby's global lock.
12
+ #
13
+ # @api private
14
+ # @since 0.1.0
15
+ SQLITE_BUSY_HANDLER = ->(connection) { connection.busy_handler_timeout = 5000 }
16
+
17
+ module_function
18
+
19
+ # @api private
20
+ # @since 0.1.0
21
+ def call(context, **raw_options)
22
+ options = Options.call(raw_options)
23
+ db = resolve_database(options[:gateway], context.container)
24
+ warn_about_database(db, context, context.logger)
25
+
26
+ Backend.new(
27
+ db: db,
28
+ table: options[:table],
29
+ clock: context.clock,
30
+ instrumenter: context.instrumenter,
31
+ options: options,
32
+ quiet_db: options[:silence_polling] ? quiet_copy(db) : db
33
+ )
34
+ end
35
+
36
+ # Backs `hanami sockets install --backend=sql`.
37
+ #
38
+ # @api private
39
+ # @since 0.1.0
40
+ def install(root:, out:, table: :sockets_messages)
41
+ Migration.install(root: root, out: out, table: table)
42
+ end
43
+
44
+ # @api private
45
+ # @since 0.1.0
46
+ def resolve_database(gateway, container)
47
+ gateway = container[gateway] if gateway.is_a?(String) && container
48
+ gateway = gateway.connection if gateway.respond_to?(:connection) && !gateway.is_a?(Sequel::Database)
49
+ return gateway if gateway.is_a?(Sequel::Database)
50
+
51
+ raise ConfigurationError,
52
+ "gateway must be a container key, a gateway with #connection, or a Sequel::Database, " \
53
+ "got #{gateway.inspect}"
54
+ end
55
+
56
+ # A second pool for polling, without the app's loggers. In-memory SQLite cannot share a
57
+ # pool across connections, so it keeps the app's pool.
58
+ #
59
+ # @api private
60
+ # @since 0.1.0
61
+ def quiet_copy(db)
62
+ return db if db.database_type == :sqlite && [nil, "", ":memory:"].include?(db.opts[:database])
63
+
64
+ options = db.opts.except(:loggers, :logger, :orig_opts).merge(logger: nil, test: false)
65
+ options[:after_connect] ||= SQLITE_BUSY_HANDLER if db.database_type == :sqlite
66
+ Sequel.connect(options)
67
+ end
68
+
69
+ # @api private
70
+ # @since 0.1.0
71
+ def warn_about_database(db, context, logger)
72
+ warn_about_pool_size(db, context.executor_threads, logger)
73
+ warn_about_time_precision(db, logger)
74
+ warn_about_sqlite_locking(db, logger)
75
+ end
76
+
77
+ # @api private
78
+ # @since 0.1.0
79
+ def warn_about_pool_size(db, executor_threads, logger)
80
+ needed = executor_threads.to_i + 1
81
+ size = db.pool.respond_to?(:max_size) ? db.pool.max_size : nil
82
+ return unless size && size < needed
83
+
84
+ logger&.warn(
85
+ "[mankai-sockets] database pool size #{size} is smaller than the #{needed} connections " \
86
+ "this process may need (executor threads + polling). Raise max_connections on the database URL."
87
+ )
88
+ end
89
+
90
+ # @api private
91
+ # @since 0.1.0
92
+ def warn_about_time_precision(db, logger)
93
+ return unless db.database_type == :mysql && !db.supports_timestamp_usecs?
94
+
95
+ logger&.warn(
96
+ "[mankai-sockets] this connection stores times in whole seconds. Add " \
97
+ "fractional_seconds=true to the database URL."
98
+ )
99
+ end
100
+
101
+ # @api private
102
+ # @since 0.1.0
103
+ def warn_about_sqlite_locking(db, logger)
104
+ return unless db.database_type == :sqlite && db.opts[:after_connect].nil?
105
+
106
+ logger&.warn(
107
+ "[mankai-sockets] SQLite connections hold Ruby's global lock while waiting for a " \
108
+ "database lock. Add after_connect: ->(conn) { conn.busy_handler_timeout = 5000 } to the " \
109
+ "database's connection options."
110
+ )
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ module SQL
6
+ # Polls the messages table for new rows on the streams the hub listens to. One thread per
7
+ # process, using its own connection pool so polling does not use the app's connections.
8
+ # A stream only receives messages published after it started being watched.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ class Listener
13
+ # @api private
14
+ # @since 0.1.0
15
+ MAX_BACKOFF = 5
16
+ # @api private
17
+ # @since 0.1.0
18
+ INITIAL_BACKOFF = 0.1
19
+
20
+ # @param db [Sequel::Database] the quiet pool
21
+ # @param table [Symbol]
22
+ # @param hashes [#call] returns the stream hashes currently watched
23
+ # @param streams [#call] maps a hash back to its stream name
24
+ # @param on_message [#call] receives a Broadcast
25
+ #
26
+ # @api private
27
+ # @since 0.1.0
28
+ def initialize(db:, table:, hashes:, streams:, on_message:, polling_interval:, batch_size:,
29
+ silence_polling:, instrumenter:)
30
+ @db = db
31
+ @table = table
32
+ @hashes = hashes
33
+ @streams = streams
34
+ @on_message = on_message
35
+ @polling_interval = polling_interval
36
+ @batch_size = batch_size
37
+ @silence_polling = silence_polling
38
+ @instrumenter = instrumenter
39
+ @last_id = 0
40
+ @mark = 0
41
+ @watched_from = {}
42
+ @thread = nil
43
+ @stopping = false
44
+ end
45
+
46
+ # @api private
47
+ # @since 0.1.0
48
+ def start
49
+ return if @thread
50
+
51
+ @last_id = max_id
52
+ @mark = @last_id
53
+ @watched_from = {}
54
+ @stopping = false
55
+ @thread = Thread.new { run }
56
+ end
57
+
58
+ # @api private
59
+ # @since 0.1.0
60
+ def stop
61
+ @stopping = true
62
+ @thread&.join
63
+ @thread = nil
64
+ end
65
+
66
+ private
67
+
68
+ # @api private
69
+ # @since 0.1.0
70
+ def run
71
+ backoff = INITIAL_BACKOFF
72
+ until @stopping
73
+ begin
74
+ tick
75
+ backoff = INITIAL_BACKOFF
76
+ rescue StandardError => exception
77
+ @instrumenter.instrument(:error, exception: exception)
78
+ sleep backoff
79
+ backoff = [backoff * 2, MAX_BACKOFF].min
80
+ end
81
+ sleep @polling_interval
82
+ end
83
+ end
84
+
85
+ # A stream only receives rows written after it started being watched: retained rows for
86
+ # a stream nobody was listening to are never replayed. The highest id is read before the
87
+ # watched streams, so a stream that first appears in this tick was subscribed after the
88
+ # previous tick's mark, and every row published after the subscribe has a higher id.
89
+ #
90
+ # @api private
91
+ # @since 0.1.0
92
+ def tick
93
+ mark = max_id
94
+ watched = @hashes.call
95
+ @watched_from = watched.to_h { |hash| [hash, @watched_from.fetch(hash, @mark)] }
96
+ if watched.empty?
97
+ @last_id = [@last_id, mark].max
98
+ else
99
+ poll(watched)
100
+ end
101
+ @mark = mark
102
+ end
103
+
104
+ # @api private
105
+ # @since 0.1.0
106
+ def max_id
107
+ @db[@table].get(Sequel.function(:max, :id)).to_i
108
+ end
109
+
110
+ # @api private
111
+ # @since 0.1.0
112
+ def poll(hashes)
113
+ rows = @db[@table]
114
+ .where(Sequel[:id] > @last_id)
115
+ .where(stream_hash: hashes)
116
+ .order(:id).limit(@batch_size).all
117
+ rows.each do |row|
118
+ verify_and_deliver(row, hashes) if row[:id] > @watched_from.fetch(row[:stream_hash], 0)
119
+ @last_id = row[:id]
120
+ end
121
+ end
122
+
123
+ # A truncated digest can collide: only deliver when the stored stream name matches the
124
+ # name the listener subscribed to.
125
+ #
126
+ # @api private
127
+ # @since 0.1.0
128
+ def verify_and_deliver(row, hashes)
129
+ hash = row[:stream_hash]
130
+ return unless hashes.include?(hash)
131
+ return unless @streams.call(hash) == row[:stream]
132
+
133
+ @on_message.call(
134
+ Mankai::Sockets::Broadcast.new(stream: row[:stream], id: row[:id], payload: row[:payload])
135
+ )
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+ require "fileutils"
5
+
6
+ module Mankai
7
+ module Sockets
8
+ module SQL
9
+ # Renders and installs the messages migration.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ module Migration
14
+ # @api private
15
+ # @since 0.1.0
16
+ NAME = "create_mankai_sockets_messages"
17
+ # @api private
18
+ # @since 0.1.0
19
+ TEMPLATE = File.join(__dir__, "templates", "create_sockets_messages.rb.erb")
20
+
21
+ module_function
22
+
23
+ # @param migration_dsl ["ROM::SQL", "Sequel"]
24
+ # @return [String] the migration source
25
+ #
26
+ # @api public
27
+ # @since 0.1.0
28
+ def render(table: :sockets_messages, migration_dsl: "ROM::SQL")
29
+ ERB.new(File.read(TEMPLATE), trim_mode: "-").result_with_hash(
30
+ table: table, migration_dsl: migration_dsl
31
+ )
32
+ end
33
+
34
+ # @return [String] the migration's path
35
+ #
36
+ # @api public
37
+ # @since 0.1.0
38
+ def install(root:, out: $stdout, table: :sockets_messages, now: Time.now.utc)
39
+ dir = File.join(root.to_s, "config", "db", "migrate")
40
+ existing = Dir.glob(File.join(dir, "*_#{NAME}.rb")).min
41
+ if existing
42
+ out.puts "Migration already exists: #{existing}"
43
+ return existing
44
+ end
45
+
46
+ FileUtils.mkdir_p(dir)
47
+ path = File.join(dir, "#{now.strftime("%Y%m%d%H%M%S")}_#{NAME}.rb")
48
+ File.write(path, render(table: table))
49
+ out.puts "Created #{path}"
50
+ out.puts "Run your app's database migration task to create the table."
51
+ path
52
+ end
53
+
54
+ # Applies the migration to a Sequel database, for tests and non-Hanami use.
55
+ #
56
+ # @api public
57
+ # @since 0.1.0
58
+ def apply(db, direction = :up, table: :sockets_messages)
59
+ Sequel.extension :migration
60
+ source = render(table: table, migration_dsl: "Sequel")
61
+ eval(source, TOPLEVEL_BINDING, TEMPLATE).apply(db, direction) # rubocop:disable Security/Eval
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/schema"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ module SQL
8
+ # Validates and fills in defaults for the options given to SQL.backend.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ module Options
13
+ # @api private
14
+ # @since 0.1.0
15
+ DEFAULTS = {
16
+ gateway: "db.gateway",
17
+ table: :sockets_messages,
18
+ polling_interval: 0.1,
19
+ batch_size: 500,
20
+ retention: 86_400,
21
+ trim_every: 100,
22
+ trim_batch_size: 200,
23
+ trim: :thread,
24
+ silence_polling: true
25
+ }.freeze
26
+
27
+ # @api private
28
+ # @since 0.1.0
29
+ Schema = Dry::Schema.define do
30
+ config.validate_keys = true
31
+ optional(:gateway)
32
+ optional(:table)
33
+ optional(:polling_interval).filled(:float, gt?: 0)
34
+ optional(:batch_size).filled(:integer, gt?: 0)
35
+ optional(:retention).filled(:integer, gt?: 0)
36
+ optional(:trim_every).filled(:integer, gt?: 0)
37
+ optional(:trim_batch_size).filled(:integer, gt?: 0)
38
+ optional(:trim).filled(:symbol, included_in?: %i[thread inline])
39
+ optional(:silence_polling).filled(:bool)
40
+ end
41
+
42
+ module_function
43
+
44
+ # @return [Hash] options with defaults
45
+ # @raise [ConfigurationError] for unknown or invalid options
46
+ #
47
+ # @api private
48
+ # @since 0.1.0
49
+ def call(raw)
50
+ options = raw.to_h
51
+ options[:polling_interval] = options[:polling_interval].to_f if options[:polling_interval].is_a?(Integer)
52
+ if options.key?(:table) && !(options[:table].is_a?(String) || options[:table].is_a?(Symbol))
53
+ raise ConfigurationError, "mankai-sockets-sql table must be a String or Symbol"
54
+ end
55
+
56
+ result = Schema.call(options)
57
+ if result.failure?
58
+ raise ConfigurationError, "invalid mankai-sockets-sql options: #{result.errors.to_h}"
59
+ end
60
+
61
+ DEFAULTS.merge(result.to_h)
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The messages table for mankai-sockets-sql. This migration is yours: adapt it as needed.
4
+ #
5
+ # It is idempotent: an existing table is left alone, so running it twice does no harm.
6
+ <%= migration_dsl %>.migration do
7
+ up do
8
+ create_table? :<%= table %> do
9
+ primary_key :id, type: :Bignum
10
+ # First 8 bytes of the stream name's SHA-256 digest, as a signed integer.
11
+ Bignum :stream_hash, null: false
12
+ String :stream, size: 255, null: false
13
+ # TEXT holds up to 65,535 bytes on MySQL and MariaDB.
14
+ String :payload, text: true, null: false
15
+ Time :created_at, null: false
16
+
17
+ index [:stream_hash, :id]
18
+ end
19
+ end
20
+
21
+ down do
22
+ drop_table? :<%= table %>
23
+ end
24
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ module SQL
6
+ # Deletes the oldest messages, a batch at a time. In :thread mode a single background
7
+ # thread handles one trim at a time; in :inline mode publishes do the work.
8
+ #
9
+ # @api private
10
+ # @since 0.1.0
11
+ class Trimmer
12
+ # @api private
13
+ # @since 0.1.0
14
+ def initialize(db:, table:, retention:, batch_size:, clock:, instrumenter:, mode: :thread)
15
+ @db = db
16
+ @table = table
17
+ @retention = retention
18
+ @batch_size = batch_size
19
+ @clock = clock
20
+ @instrumenter = instrumenter
21
+ @mode = mode
22
+ @queue = Queue.new
23
+ @thread = nil
24
+ end
25
+
26
+ # @api private
27
+ # @since 0.1.0
28
+ def start
29
+ return unless @mode == :thread
30
+ return if @thread
31
+
32
+ @thread = Thread.new do
33
+ loop do
34
+ job = @queue.pop
35
+ break if job.nil?
36
+
37
+ begin
38
+ job.call
39
+ rescue StandardError => exception
40
+ @instrumenter.instrument(:error, exception: exception)
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ # @api private
47
+ # @since 0.1.0
48
+ def call
49
+ if @mode == :inline
50
+ delete_old
51
+ else
52
+ start
53
+ @queue << -> { delete_old }
54
+ end
55
+ end
56
+
57
+ # @return [Integer] how many messages were deleted
58
+ #
59
+ # @api private
60
+ # @since 0.1.0
61
+ def delete_old
62
+ cutoff = @clock.call - @retention
63
+ dataset = @db[@table]
64
+ ids = dataset.where { created_at < cutoff }.order(:id).limit(@batch_size).select_map(:id)
65
+ return 0 if ids.empty?
66
+
67
+ dataset.where(id: ids).delete
68
+ end
69
+
70
+ # @api private
71
+ # @since 0.1.0
72
+ def stop
73
+ return unless @thread
74
+
75
+ @queue << nil
76
+ @thread.join
77
+ @thread = nil
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
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,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sequel"
4
+ require "zeitwerk"
5
+ require "mankai/sockets"
6
+
7
+ module Mankai
8
+ module Sockets
9
+ # SQL backend for mankai-sockets: broadcasts travel between processes through a table.
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-sockets-sql"
20
+ loader.inflector = Zeitwerk::GemInflector.new("#{root}/mankai-sockets-sql.rb")
21
+ loader.push_dir(root)
22
+ loader.ignore(
23
+ "#{root}/mankai-sockets-sql.rb",
24
+ "#{root}/mankai/sockets/sql/{version}.rb",
25
+ "#{root}/mankai/sockets/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 factory for the provider's `backend` setting.
35
+ #
36
+ # @param options [Hash] see Options
37
+ # @return [Proc] called with the provider's Context
38
+ #
39
+ # @api public
40
+ # @since 0.1.0
41
+ def self.backend(**options)
42
+ ->(context) { Factory.call(context, **options) }
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "mankai/sockets/sql"
@@ -0,0 +1,33 @@
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/sockets/sql/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "mankai-sockets-sql"
9
+ spec.authors = ["Mankai contributors"]
10
+ spec.license = "MIT"
11
+ spec.version = Mankai::Sockets::SQL::VERSION.dup
12
+ spec.homepage = "https://github.com/thisisibrahimd/mankai"
13
+ spec.metadata["github_repo"] = "https://github.com/thisisibrahimd/mankai"
14
+ spec.metadata["source_code_uri"] = "https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-sockets-sql"
15
+ spec.metadata["changelog_uri"] = "https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-sockets-sql/CHANGELOG.md"
16
+ spec.metadata["rubygems_mfa_required"] = "true"
17
+
18
+ spec.summary = "Database-backed broadcasts for mankai-sockets"
19
+ spec.description = <<~TEXT
20
+ A mankai-sockets backend that carries broadcasts between processes through a database table,
21
+ with a polling listener, retention trimming and an installer for Hanami apps.
22
+ TEXT
23
+ spec.files = Dir["CHANGELOG.md", "LICENSE", "README.md", "mankai-sockets-sql.gemspec", "lib/**/*"]
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.extra_rdoc_files = ["README.md", "CHANGELOG.md", "LICENSE"]
27
+
28
+ spec.required_ruby_version = ">= 3.3"
29
+
30
+ spec.add_runtime_dependency "mankai-sockets", "~> 0.1.0"
31
+ spec.add_runtime_dependency "sequel", "~> 5.70"
32
+ spec.add_runtime_dependency "zeitwerk", "~> 2.6"
33
+ end
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mankai-sockets-sql
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mankai contributors
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-sockets
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
+ A mankai-sockets backend that carries broadcasts between processes through a database table,
56
+ with a polling listener, retention trimming and an installer for Hanami apps.
57
+ executables: []
58
+ extensions: []
59
+ extra_rdoc_files:
60
+ - CHANGELOG.md
61
+ - LICENSE
62
+ - README.md
63
+ files:
64
+ - CHANGELOG.md
65
+ - LICENSE
66
+ - README.md
67
+ - lib/mankai-sockets-sql.rb
68
+ - lib/mankai/sockets/sql.rb
69
+ - lib/mankai/sockets/sql/backend.rb
70
+ - lib/mankai/sockets/sql/factory.rb
71
+ - lib/mankai/sockets/sql/listener.rb
72
+ - lib/mankai/sockets/sql/migration.rb
73
+ - lib/mankai/sockets/sql/options.rb
74
+ - lib/mankai/sockets/sql/templates/create_sockets_messages.rb.erb
75
+ - lib/mankai/sockets/sql/trimmer.rb
76
+ - lib/mankai/sockets/sql/version.rb
77
+ - mankai-sockets-sql.gemspec
78
+ homepage: https://github.com/thisisibrahimd/mankai
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ github_repo: https://github.com/thisisibrahimd/mankai
83
+ source_code_uri: https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-sockets-sql
84
+ changelog_uri: https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-sockets-sql/CHANGELOG.md
85
+ rubygems_mfa_required: 'true'
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '3.3'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 4.0.20
101
+ specification_version: 4
102
+ summary: Database-backed broadcasts for mankai-sockets
103
+ test_files: []