ruby_event_store-outbox_relay 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.
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ # Inspects and resolves deliveries the relay gave up on.
6
+ #
7
+ # Requeueing moves a dead letter back to the outbox as a fresh message, with
8
+ # its attempts reset, in one transaction together with removing the dead
9
+ # letter.
10
+ class DeadLetters
11
+ include Enumerable
12
+
13
+ BATCH_SIZE = 1000
14
+
15
+ # @param message_klass [Class] ActiveRecord model of event_store_outbox_messages
16
+ # @param dead_letter_klass [Class] ActiveRecord model of event_store_outbox_dead_letters
17
+ # @param clock [#call] returns the current time
18
+ def initialize(message_klass: Message, dead_letter_klass: DeadLetter, clock: -> { Time.now.utc })
19
+ @message_klass = message_klass
20
+ @dead_letter_klass = dead_letter_klass
21
+ @clock = clock
22
+ end
23
+
24
+ # @yieldparam dead_letter [DeadLetter] oldest first
25
+ def each(&block)
26
+ dead_letter_klass.find_each(&block)
27
+ end
28
+
29
+ # @return [Integer]
30
+ def count
31
+ dead_letter_klass.count
32
+ end
33
+
34
+ # @param id [Integer]
35
+ # @raise [ActiveRecord::RecordNotFound]
36
+ def requeue(id)
37
+ raise_not_found(id) if move(dead_letter_klass.where(id: id)).zero?
38
+ end
39
+
40
+ # @param topic [String, nil] only dead letters of this topic
41
+ # @param subscriber [String, nil] only dead letters of this subscriber
42
+ # @return [Integer] number of requeued dead letters
43
+ def requeue_all(topic: nil, subscriber: nil)
44
+ scope = dead_letter_klass.where({ topic: topic, subscriber: subscriber }.compact).order(:id).limit(BATCH_SIZE)
45
+ requeued = 0
46
+ while (moved = move(scope)).positive?
47
+ requeued += moved
48
+ end
49
+ requeued
50
+ end
51
+
52
+ # @param id [Integer]
53
+ # @raise [ActiveRecord::RecordNotFound]
54
+ def discard(id)
55
+ raise_not_found(id) if dead_letter_klass.where(id: id).delete_all.zero?
56
+ end
57
+
58
+ private
59
+
60
+ attr_reader :message_klass, :dead_letter_klass, :clock
61
+
62
+ def move(scope)
63
+ dead_letter_klass.transaction(requires_new: true) do
64
+ now = clock.call
65
+ rows = scope.lock.pluck(:event_id, :topic, :subscriber)
66
+ message_klass.insert_all!(
67
+ rows.map do |event_id, topic, subscriber|
68
+ { event_id: event_id, topic: topic, subscriber: subscriber, next_attempt_at: now, created_at: now }
69
+ end,
70
+ returning: false,
71
+ )
72
+ scope.delete_all
73
+ end
74
+ end
75
+
76
+ def raise_not_found(id)
77
+ raise ::ActiveRecord::RecordNotFound.new("Couldn't find dead letter with id=#{id}", dead_letter_klass.name, "id", id)
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+ require "ruby_event_store/active_record"
5
+
6
+ module RubyEventStore
7
+ module OutboxRelay
8
+ class MigrationGenerator
9
+ include ActiveRecord::MigrationGeneratorMethods
10
+
11
+ TEMPLATE_DIRECTORY_BY_ADAPTER = { "postgresql" => "postgres", "mysql2" => "mysql", "sqlite" => "sqlite" }.freeze
12
+
13
+ def call(database_adapter, migration_path)
14
+ path, content = generate(database_adapter, migration_path)
15
+ File.write(path, content)
16
+ path
17
+ end
18
+
19
+ def generate(database_adapter, migration_path)
20
+ [build_path(migration_path), migration_code(database_adapter)]
21
+ end
22
+
23
+ private
24
+
25
+ def migration_code(database_adapter)
26
+ template(database_adapter).result_with_hash(migration_version: migration_version)
27
+ end
28
+
29
+ def template(database_adapter)
30
+ directory = TEMPLATE_DIRECTORY_BY_ADAPTER.fetch(database_adapter.adapter_name)
31
+ migration_template(File.join(__dir__, "templates", directory), "create_event_store_outbox_tables")
32
+ end
33
+
34
+ def build_path(migration_path)
35
+ File.join(migration_path.to_s, "#{timestamp}_create_event_store_outbox_tables.rb")
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateEventStoreOutboxTables < ActiveRecord::Migration[<%= migration_version %>]
4
+ def change
5
+ create_table :event_store_outbox_messages do |t|
6
+ t.string :event_id, null: false, limit: 36
7
+ t.string :topic, null: false
8
+ t.string :subscriber, null: false
9
+ t.integer :attempts, null: false, default: 0
10
+ t.datetime :next_attempt_at, null: false, precision: 6
11
+ t.text :last_error
12
+ t.datetime :created_at, null: false, precision: 6
13
+ t.index %i[next_attempt_at id], name: "index_event_store_outbox_messages_due"
14
+ end
15
+
16
+ create_table :event_store_outbox_dead_letters do |t|
17
+ t.string :event_id, null: false, limit: 36
18
+ t.string :topic, null: false
19
+ t.string :subscriber, null: false
20
+ t.integer :attempts, null: false
21
+ t.string :error_class, null: false
22
+ t.text :error_message
23
+ t.text :backtrace
24
+ t.datetime :first_enqueued_at, null: false, precision: 6
25
+ t.datetime :dead_at, null: false, precision: 6
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateEventStoreOutboxTables < ActiveRecord::Migration[<%= migration_version %>]
4
+ def change
5
+ create_table :event_store_outbox_messages do |t|
6
+ t.uuid :event_id, null: false
7
+ t.string :topic, null: false
8
+ t.string :subscriber, null: false
9
+ t.integer :attempts, null: false, default: 0
10
+ t.datetime :next_attempt_at, null: false, precision: 6
11
+ t.text :last_error
12
+ t.datetime :created_at, null: false, precision: 6
13
+ t.index %i[next_attempt_at id], name: "index_event_store_outbox_messages_due"
14
+ end
15
+
16
+ create_table :event_store_outbox_dead_letters do |t|
17
+ t.uuid :event_id, null: false
18
+ t.string :topic, null: false
19
+ t.string :subscriber, null: false
20
+ t.integer :attempts, null: false
21
+ t.string :error_class, null: false
22
+ t.text :error_message
23
+ t.text :backtrace
24
+ t.datetime :first_enqueued_at, null: false, precision: 6
25
+ t.datetime :dead_at, null: false, precision: 6
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateEventStoreOutboxTables < ActiveRecord::Migration[<%= migration_version %>]
4
+ def change
5
+ create_table :event_store_outbox_messages do |t|
6
+ t.string :event_id, null: false, limit: 36
7
+ t.string :topic, null: false
8
+ t.string :subscriber, null: false
9
+ t.integer :attempts, null: false, default: 0
10
+ t.datetime :next_attempt_at, null: false, precision: 6
11
+ t.text :last_error
12
+ t.datetime :created_at, null: false, precision: 6
13
+ t.index %i[next_attempt_at id], name: "index_event_store_outbox_messages_due"
14
+ end
15
+
16
+ create_table :event_store_outbox_dead_letters do |t|
17
+ t.string :event_id, null: false, limit: 36
18
+ t.string :topic, null: false
19
+ t.string :subscriber, null: false
20
+ t.integer :attempts, null: false
21
+ t.string :error_class, null: false
22
+ t.text :error_message
23
+ t.text :backtrace
24
+ t.datetime :first_enqueued_at, null: false, precision: 6
25
+ t.datetime :dead_at, null: false, precision: 6
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,206 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ # A pending delivery of one event to one async subscriber.
6
+ class Message < ::ActiveRecord::Base
7
+ self.table_name = "event_store_outbox_messages"
8
+ end
9
+
10
+ # A delivery that exhausted its attempts or can never succeed.
11
+ class DeadLetter < ::ActiveRecord::Base
12
+ self.table_name = "event_store_outbox_dead_letters"
13
+ end
14
+
15
+ # All reads and writes of the outbox tables.
16
+ #
17
+ # Inserts never ask for the generated id (RETURNING), which PostgreSQL would
18
+ # answer only to a role that can also SELECT from the table.
19
+ #
20
+ # The messages are written in the very transaction of the events, which holds
21
+ # only when the models reach the database of the event store through the same
22
+ # connection. The default ones inherit from ActiveRecord::Base; for an event
23
+ # store on another connection, pass models inheriting from the class that
24
+ # holds it.
25
+ #
26
+ # A message is due when next_attempt_at <= now. Claiming a message moves its
27
+ # next_attempt_at to the end of a lease, so a relay that crashes mid-batch
28
+ # releases its messages simply by the lease running out.
29
+ class Outbox
30
+ MESSAGE_LIMIT = 1000
31
+ BACKTRACE_LINES = 20
32
+
33
+ # A claimed message, detached from the database.
34
+ Entry = Data.define(:outbox_id, :event_id, :topic, :subscriber, :attempts, :created_at)
35
+
36
+ # What the outbox holds right now. +backlog+ counts the messages that are due,
37
+ # and +dead_letters+ the dead letters, each up to STATS_LIMIT. +oldest_due_age+
38
+ # is how many seconds the oldest due message has waited, nil when none is due.
39
+ # Messages being delivered are leased, hence not due.
40
+ Stats = Data.define(:backlog, :oldest_due_age, :dead_letters)
41
+ STATS_LIMIT = 10_000
42
+
43
+ # @param message_klass [Class] ActiveRecord model of event_store_outbox_messages
44
+ # @param dead_letter_klass [Class] ActiveRecord model of event_store_outbox_dead_letters
45
+ def initialize(message_klass: Message, dead_letter_klass: DeadLetter)
46
+ @message_klass = message_klass
47
+ @dead_letter_klass = dead_letter_klass
48
+ end
49
+
50
+ # Runs the block, which persists the records, and inserts one message per
51
+ # (record, async subscriber of its topic) in the same transaction, so the
52
+ # events and their pending deliveries are committed or rolled back
53
+ # together. When no record has an async subscriber, the block runs alone,
54
+ # without opening a transaction.
55
+ #
56
+ # @param records [Array<RubyEventStore::Record>]
57
+ # @param topics [Array<String>] the topic of each record, in order
58
+ # @param subscriptions [AsyncSubscriptions]
59
+ # @param now [Time]
60
+ # @yield persists the records
61
+ # @return the block's result
62
+ def append(records, topics:, subscriptions:, now:)
63
+ rows = message_rows(records, topics, subscriptions, now)
64
+ return yield if rows.empty?
65
+
66
+ transaction { yield.tap { message_klass.insert_all!(rows, returning: false) } }
67
+ end
68
+
69
+ # Locks up to batch_size due messages, oldest first, skipping ones another
70
+ # relay holds, and leases them until lease_until.
71
+ #
72
+ # @return [Array<Entry>]
73
+ def claim(batch_size, now:, lease_until:)
74
+ transaction do
75
+ entries = due(batch_size, now).map { |message| entry_for(message) }
76
+ message_klass.where(id: entries.map(&:outbox_id)).update_all(next_attempt_at: lease_until) unless entries.empty?
77
+ entries
78
+ end
79
+ end
80
+
81
+ # @param now [Time]
82
+ # @return [Stats]
83
+ def stats(now:)
84
+ due = message_klass.where(next_attempt_at: ..now)
85
+ oldest = due.minimum(:next_attempt_at)
86
+ Stats.new(
87
+ backlog: capped_count(due),
88
+ oldest_due_age: oldest && now - oldest,
89
+ dead_letters: capped_count(dead_letter_klass),
90
+ )
91
+ end
92
+
93
+ # Makes claimed messages due again at once, instead of when their lease
94
+ # runs out, without counting an attempt: for messages that were claimed but
95
+ # not tried.
96
+ #
97
+ # @param ids [Array<Integer>]
98
+ # @param now [Time]
99
+ def release(ids, now:)
100
+ message_klass.where(id: ids).update_all(next_attempt_at: now)
101
+ end
102
+
103
+ # @param ids [Array<Integer>]
104
+ def delete(ids)
105
+ message_klass.where(id: ids).delete_all unless ids.empty?
106
+ end
107
+
108
+ # Records a failed attempt and schedules the next one.
109
+ #
110
+ # @param message [Entry]
111
+ def reschedule(message, attempts:, next_attempt_at:, error:)
112
+ message_klass.where(id: message.outbox_id).update_all(
113
+ attempts: attempts,
114
+ next_attempt_at: next_attempt_at,
115
+ last_error: error_summary(error),
116
+ )
117
+ end
118
+
119
+ # Moves a message to the dead letters. Does nothing when the message is
120
+ # already gone, e.g. delivered by another relay after this one's lease ran out.
121
+ #
122
+ # @param message [Entry]
123
+ # @return [Boolean] whether the message was moved
124
+ def bury(message, attempts:, error:, now:)
125
+ transaction do
126
+ moved = message_klass.where(id: message.outbox_id).delete_all.positive?
127
+ dead_letter_klass.insert!(dead_letter_row(message, attempts, error, now), returning: false) if moved
128
+ moved
129
+ end
130
+ end
131
+
132
+ private
133
+
134
+ attr_reader :message_klass, :dead_letter_klass
135
+
136
+ def transaction(&block)
137
+ message_klass.transaction(requires_new: true, &block)
138
+ end
139
+
140
+ def message_rows(records, topics, subscriptions, now)
141
+ records.zip(topics).flat_map do |record, message_topic|
142
+ subscriptions
143
+ .names_for(message_topic)
144
+ .map do |subscriber|
145
+ {
146
+ event_id: record.event_id,
147
+ topic: message_topic,
148
+ subscriber: subscriber,
149
+ next_attempt_at: now,
150
+ created_at: now,
151
+ }
152
+ end
153
+ end
154
+ end
155
+
156
+ # Counts at most STATS_LIMIT rows, in the database. count, count(nil) and
157
+ # count(:all) all issue the very same COUNT(*), so mutating the argument
158
+ # can't be told apart. mutant:disable
159
+ def capped_count(scope)
160
+ scope.limit(STATS_LIMIT).count(:all)
161
+ end
162
+
163
+ def entry_for(message)
164
+ Entry.new(
165
+ outbox_id: message.id,
166
+ event_id: message.event_id,
167
+ topic: message.topic,
168
+ subscriber: message.subscriber,
169
+ attempts: message.attempts,
170
+ created_at: message.created_at,
171
+ )
172
+ end
173
+
174
+ def due(batch_size, now)
175
+ message_klass
176
+ .select(:id, :event_id, :topic, :subscriber, :attempts, :created_at)
177
+ .where(next_attempt_at: ..now)
178
+ .order(:next_attempt_at, :id)
179
+ .limit(batch_size)
180
+ .lock("FOR UPDATE SKIP LOCKED")
181
+ end
182
+
183
+ def dead_letter_row(message, attempts, error, now)
184
+ {
185
+ event_id: message.event_id,
186
+ topic: message.topic,
187
+ subscriber: message.subscriber,
188
+ attempts: attempts,
189
+ error_class: error.class.to_s,
190
+ error_message: truncate(error.message),
191
+ backtrace: Array(error.backtrace).first(BACKTRACE_LINES).join("\n"),
192
+ first_enqueued_at: message.created_at,
193
+ dead_at: now,
194
+ }
195
+ end
196
+
197
+ def error_summary(error)
198
+ truncate("#{error.class}: #{error.message}")
199
+ end
200
+
201
+ def truncate(text)
202
+ text[0, MESSAGE_LIMIT]
203
+ end
204
+ end
205
+ end
206
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails_event_store"
4
+ require_relative "../outbox_relay"
5
+
6
+ module RubyEventStore
7
+ module OutboxRelay
8
+ # A RailsEventStore::Client with async subscriptions delivered through the
9
+ # outbox, see ClientExtension. Requires rails_event_store, which this gem
10
+ # doesn't depend on, so it is loaded on its own:
11
+ #
12
+ # gem "ruby_event_store-outbox_relay", require: "ruby_event_store/outbox_relay/rails"
13
+ class RailsClient < RailsEventStore::Client
14
+ include ClientExtension
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module RubyEventStore
6
+ module OutboxRelay
7
+ class Railtie < ::Rails::Railtie
8
+ rake_tasks { load File.expand_path("../../tasks/outbox_relay.rake", __dir__) }
9
+ end
10
+ end
11
+ end