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.
- checksums.yaml +7 -0
- data/README.md +172 -0
- data/bin/res_outbox_relay +7 -0
- data/lib/ruby_event_store/outbox_relay/active_job_dispatcher.rb +121 -0
- data/lib/ruby_event_store/outbox_relay/async_subscriptions.rb +89 -0
- data/lib/ruby_event_store/outbox_relay/cli.rb +99 -0
- data/lib/ruby_event_store/outbox_relay/client.rb +11 -0
- data/lib/ruby_event_store/outbox_relay/client_extension.rb +105 -0
- data/lib/ruby_event_store/outbox_relay/configuration.rb +45 -0
- data/lib/ruby_event_store/outbox_relay/dead_letters.rb +81 -0
- data/lib/ruby_event_store/outbox_relay/generators/migration_generator.rb +39 -0
- data/lib/ruby_event_store/outbox_relay/generators/templates/mysql/create_event_store_outbox_tables_template.erb +28 -0
- data/lib/ruby_event_store/outbox_relay/generators/templates/postgres/create_event_store_outbox_tables_template.erb +28 -0
- data/lib/ruby_event_store/outbox_relay/generators/templates/sqlite/create_event_store_outbox_tables_template.erb +28 -0
- data/lib/ruby_event_store/outbox_relay/outbox.rb +206 -0
- data/lib/ruby_event_store/outbox_relay/rails.rb +17 -0
- data/lib/ruby_event_store/outbox_relay/railtie.rb +11 -0
- data/lib/ruby_event_store/outbox_relay/relay.rb +398 -0
- data/lib/ruby_event_store/outbox_relay/retry_policy.rb +59 -0
- data/lib/ruby_event_store/outbox_relay/version.rb +7 -0
- data/lib/ruby_event_store/outbox_relay.rb +16 -0
- data/lib/tasks/outbox_relay.rake +61 -0
- data/support/systemd/res-outbox-relay.service +54 -0
- metadata +140 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "logger"
|
|
4
|
+
require "active_support/notifications"
|
|
5
|
+
|
|
6
|
+
module RubyEventStore
|
|
7
|
+
module OutboxRelay
|
|
8
|
+
# Independent process delivering outbox messages to async subscribers
|
|
9
|
+
# (Client#subscribe_async).
|
|
10
|
+
#
|
|
11
|
+
# Each batch is claimed in a short transaction that leases the messages
|
|
12
|
+
# (see Outbox), then delivered with no transaction open, so a slow or
|
|
13
|
+
# failing subscriber never holds database locks, and a job enqueued by the
|
|
14
|
+
# dispatcher is never deferred until after the message is gone. Delivered
|
|
15
|
+
# messages are deleted in one statement per batch.
|
|
16
|
+
#
|
|
17
|
+
# A failed delivery is retried according to the RetryPolicy and
|
|
18
|
+
# dead-lettered once it gives up. That goes as well for a message whose event
|
|
19
|
+
# can't be read or deserialized (MissingEvent, or the error of the mapper), or
|
|
20
|
+
# whose subscriber is not registered in this process (UnknownSubscriber): each
|
|
21
|
+
# can come right when a deploy has rolled out to the relay. List the ones that
|
|
22
|
+
# can't in the RetryPolicy's +permanent_errors+ to dead-letter them at once.
|
|
23
|
+
# The exception is a failure of the database while reading the events: it
|
|
24
|
+
# says nothing about any message, so it fails the whole batch, and its
|
|
25
|
+
# messages are handed back at once, with their attempts untouched.
|
|
26
|
+
#
|
|
27
|
+
# When it delivers one message at a time, a relay stops once 80% of the lease
|
|
28
|
+
# has passed and hands back what it had not tried (BatchResult#deferred), so a
|
|
29
|
+
# slow subscriber costs a smaller batch rather than duplicates. A single
|
|
30
|
+
# subscriber slower than the lease itself needs a longer +lease_duration+.
|
|
31
|
+
#
|
|
32
|
+
# Delivery is at least once: a relay that crashes after dispatching, but
|
|
33
|
+
# before deleting, redelivers once the lease runs out.
|
|
34
|
+
#
|
|
35
|
+
# It reports through +instrumentation+ (ActiveSupport::Notifications by
|
|
36
|
+
# default), under names ending in ".outbox_relay.ruby_event_store":
|
|
37
|
+
#
|
|
38
|
+
# * +process_batch+, around each batch, with the counts of BatchResult;
|
|
39
|
+
# * +message_failed+, for each message that failed to be delivered, with
|
|
40
|
+
# +outbox_id+, +event_id+, +topic+, +subscriber+, +attempts+, +error_class+
|
|
41
|
+
# and +outcome+ (+:retried+ or +:dead+). Never the error's message, which can
|
|
42
|
+
# echo event data;
|
|
43
|
+
# * +stats+, every +stats_interval+ seconds, with the fields of Outbox::Stats.
|
|
44
|
+
class Relay
|
|
45
|
+
# Outcome of one #process_batch call. +unrecorded+ counts the messages whose
|
|
46
|
+
# failure could not be recorded, which stay in the outbox untouched and come
|
|
47
|
+
# back once their lease runs out. +deferred+ counts those left untried because
|
|
48
|
+
# the batch was running out of its lease, which are due again at once.
|
|
49
|
+
BatchResult =
|
|
50
|
+
Data.define(:claimed, :delivered, :retried, :dead, :unrecorded, :deferred) do
|
|
51
|
+
def self.empty
|
|
52
|
+
new(claimed: 0, delivered: 0, retried: 0, dead: 0, unrecorded: 0, deferred: 0)
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Raised for a message whose event is not in the event store. It is retried like
|
|
57
|
+
# any other failure, unless the RetryPolicy lists it as permanent.
|
|
58
|
+
class MissingEvent < StandardError; end
|
|
59
|
+
|
|
60
|
+
# Raised for a message whose subscriber is not subscribed in this process. It is
|
|
61
|
+
# retried like any other failure, unless the RetryPolicy lists it as permanent.
|
|
62
|
+
class UnknownSubscriber < StandardError; end
|
|
63
|
+
|
|
64
|
+
Prepared = Data.define(:event, :record, :correlation_id)
|
|
65
|
+
Pending = Data.define(:message, :subscriber, :prepared)
|
|
66
|
+
private_constant :Prepared, :Pending
|
|
67
|
+
|
|
68
|
+
# Defaults of the options below. The command line and the documentation
|
|
69
|
+
# quote them, so they are kept in one place.
|
|
70
|
+
DEFAULT_BATCH_SIZE = 100
|
|
71
|
+
DEFAULT_POLL_INTERVAL = 1
|
|
72
|
+
DEFAULT_LEASE_DURATION = 300
|
|
73
|
+
DEFAULT_STATS_INTERVAL = 30
|
|
74
|
+
|
|
75
|
+
BACKTRACE_LINES = 10
|
|
76
|
+
EVENT_NAMESPACE = "outbox_relay.ruby_event_store"
|
|
77
|
+
LEASE_SHARE = 0.8
|
|
78
|
+
DEFERRED = Object.new.freeze
|
|
79
|
+
private_constant :BACKTRACE_LINES, :EVENT_NAMESPACE, :LEASE_SHARE, :DEFERRED
|
|
80
|
+
|
|
81
|
+
# @param client [Object] the application's Client, extended with
|
|
82
|
+
# ClientExtension (an OutboxRelay::Client or RailsClient); async
|
|
83
|
+
# subscriptions, the outbox, the mapper and the event store are all read
|
|
84
|
+
# from it. In the relay process, use the very client of the application,
|
|
85
|
+
# so both share one list of subscribers
|
|
86
|
+
# @param batch_size [Integer] how many messages to claim per batch
|
|
87
|
+
# @param poll_interval [Numeric] how long to sleep when nothing was due
|
|
88
|
+
# @param lease_duration [Numeric] seconds a claimed message stays hidden
|
|
89
|
+
# from other relays; must comfortably exceed the time to deliver a batch
|
|
90
|
+
# @param retry_policy [RetryPolicy]
|
|
91
|
+
# @param clock [#call] returns the current time
|
|
92
|
+
# @param signals [#trap] where the shutdown handlers are installed
|
|
93
|
+
# @param instrumentation [#instrument] receives the notifications listed above
|
|
94
|
+
# @param stats_interval [Numeric, nil] seconds between +stats+ notifications;
|
|
95
|
+
# nil turns them off
|
|
96
|
+
# @param logger [Logger]
|
|
97
|
+
# @raise [ArgumentError] when the client isn't extended with ClientExtension
|
|
98
|
+
def initialize(
|
|
99
|
+
client:,
|
|
100
|
+
batch_size: DEFAULT_BATCH_SIZE,
|
|
101
|
+
poll_interval: DEFAULT_POLL_INTERVAL,
|
|
102
|
+
lease_duration: DEFAULT_LEASE_DURATION,
|
|
103
|
+
retry_policy: RetryPolicy.new,
|
|
104
|
+
clock: -> { Time.now.utc },
|
|
105
|
+
signals: Signal,
|
|
106
|
+
instrumentation: ActiveSupport::Notifications,
|
|
107
|
+
stats_interval: DEFAULT_STATS_INTERVAL,
|
|
108
|
+
logger: Logger.new($stdout)
|
|
109
|
+
)
|
|
110
|
+
unless client.respond_to?(:outbox) && client.respond_to?(:async_subscriptions)
|
|
111
|
+
raise ArgumentError,
|
|
112
|
+
"client must be extended with RubyEventStore::OutboxRelay::ClientExtension, " \
|
|
113
|
+
"e.g. an OutboxRelay::Client or a RailsClient, got #{client.class}"
|
|
114
|
+
end
|
|
115
|
+
@client = client
|
|
116
|
+
@batch_size = batch_size
|
|
117
|
+
@poll_interval = poll_interval
|
|
118
|
+
@lease_duration = lease_duration
|
|
119
|
+
@retry_policy = retry_policy
|
|
120
|
+
@clock = clock
|
|
121
|
+
@signals = signals
|
|
122
|
+
@instrumentation = instrumentation
|
|
123
|
+
@stats_interval = stats_interval
|
|
124
|
+
@logger = logger
|
|
125
|
+
@shutting_down = false
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Runs the relay loop until SIGINT/SIGTERM. Sleeps poll_interval whenever
|
|
129
|
+
# no message was due.
|
|
130
|
+
def run
|
|
131
|
+
install_signal_handlers
|
|
132
|
+
logger.info("Starting RubyEventStore::OutboxRelay")
|
|
133
|
+
log_subscribers
|
|
134
|
+
|
|
135
|
+
until @shutting_down
|
|
136
|
+
result = process_batch_safely
|
|
137
|
+
log_batch(result)
|
|
138
|
+
publish_stats_if_due
|
|
139
|
+
sleep(poll_interval) if result.claimed.zero?
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
logger.info("Gracefully shutting down")
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Claims and delivers a single batch of due messages.
|
|
146
|
+
#
|
|
147
|
+
# @return [BatchResult]
|
|
148
|
+
def process_batch
|
|
149
|
+
instrumentation.instrument("process_batch.#{EVENT_NAMESPACE}", {}) do |payload|
|
|
150
|
+
deliver_batch.tap { |result| payload.merge!(result.to_h) }
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
private
|
|
155
|
+
|
|
156
|
+
attr_reader :client,
|
|
157
|
+
:batch_size,
|
|
158
|
+
:poll_interval,
|
|
159
|
+
:lease_duration,
|
|
160
|
+
:retry_policy,
|
|
161
|
+
:clock,
|
|
162
|
+
:signals,
|
|
163
|
+
:instrumentation,
|
|
164
|
+
:stats_interval,
|
|
165
|
+
:logger
|
|
166
|
+
|
|
167
|
+
def deliver_batch
|
|
168
|
+
now = clock.call
|
|
169
|
+
messages = outbox.claim(batch_size, now: now, lease_until: now + lease_duration)
|
|
170
|
+
return BatchResult.empty if messages.empty?
|
|
171
|
+
|
|
172
|
+
outcomes = deliver_all(messages, prepare_or_release(messages, now), now + (lease_duration * LEASE_SHARE))
|
|
173
|
+
delivered = outcomes.fetch(:delivered, [])
|
|
174
|
+
deferred = outcomes.fetch(:deferred, [])
|
|
175
|
+
outbox.delete(delivered.map(&:outbox_id))
|
|
176
|
+
release(deferred, clock.call)
|
|
177
|
+
|
|
178
|
+
BatchResult.new(
|
|
179
|
+
claimed: messages.size,
|
|
180
|
+
delivered: delivered.size,
|
|
181
|
+
retried: outcomes.fetch(:retried, []).size,
|
|
182
|
+
dead: outcomes.fetch(:dead, []).size,
|
|
183
|
+
unrecorded: outcomes.fetch(:unrecorded, []).size,
|
|
184
|
+
deferred: deferred.size,
|
|
185
|
+
)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def prepare_or_release(messages, now)
|
|
189
|
+
prepare_events(messages.map(&:event_id).uniq)
|
|
190
|
+
rescue StandardError
|
|
191
|
+
release(messages, now)
|
|
192
|
+
raise
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def release(messages, now)
|
|
196
|
+
return if messages.empty?
|
|
197
|
+
outbox.release(messages.map(&:outbox_id), now: now)
|
|
198
|
+
rescue StandardError => e
|
|
199
|
+
logger.error("Could not release #{messages.size} outbox message(s) that were not tried: #{e.class}")
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def outbox
|
|
203
|
+
client.outbox
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def subscriptions
|
|
207
|
+
client.async_subscriptions
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
def log_subscribers
|
|
211
|
+
registered = subscriptions.to_h
|
|
212
|
+
if registered.empty?
|
|
213
|
+
logger.warn("No async subscribers registered: every message will fail as unknown, and be retried until it is dead-lettered")
|
|
214
|
+
else
|
|
215
|
+
registered.each { |topic, names| logger.info("Async subscribers of #{topic}: #{names.join(", ")}") }
|
|
216
|
+
end
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
def log_batch(result)
|
|
220
|
+
return if result.claimed.zero?
|
|
221
|
+
logger.debug(
|
|
222
|
+
"Batch: claimed=#{result.claimed} delivered=#{result.delivered} retried=#{result.retried} dead=#{result.dead} " \
|
|
223
|
+
"unrecorded=#{result.unrecorded} deferred=#{result.deferred}",
|
|
224
|
+
)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def publish_stats_if_due
|
|
228
|
+
return unless stats_interval
|
|
229
|
+
now = clock.call
|
|
230
|
+
return if @stats_at && now - @stats_at < stats_interval
|
|
231
|
+
@stats_at = now
|
|
232
|
+
instrumentation.instrument("stats.#{EVENT_NAMESPACE}", outbox.stats(now: now).to_h)
|
|
233
|
+
rescue StandardError => e
|
|
234
|
+
logger.error("Error while collecting outbox stats: #{e.class}")
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
def instrument_failure(message, attempts, error, outcome)
|
|
238
|
+
instrumentation.instrument(
|
|
239
|
+
"message_failed.#{EVENT_NAMESPACE}",
|
|
240
|
+
outbox_id: message.outbox_id,
|
|
241
|
+
event_id: message.event_id,
|
|
242
|
+
topic: message.topic,
|
|
243
|
+
subscriber: message.subscriber,
|
|
244
|
+
attempts: attempts,
|
|
245
|
+
error_class: error.class.to_s,
|
|
246
|
+
outcome: outcome,
|
|
247
|
+
)
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
def process_batch_safely
|
|
251
|
+
process_batch
|
|
252
|
+
rescue StandardError => e
|
|
253
|
+
logger.error("Error while processing outbox batch: #{e.class}")
|
|
254
|
+
logger.debug("Outbox batch error detail: #{e.message}\n#{Array(e.backtrace).first(BACKTRACE_LINES).join("\n")}")
|
|
255
|
+
BatchResult.empty
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def prepare_events(event_ids)
|
|
259
|
+
events = read_events(event_ids)
|
|
260
|
+
event_ids.to_h { |event_id| [event_id, prepare_event(event_id, events)] }
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def read_events(event_ids)
|
|
264
|
+
client.read.events(event_ids).to_h { |event| [event.event_id, event] }
|
|
265
|
+
rescue ::ActiveRecord::ActiveRecordError
|
|
266
|
+
raise
|
|
267
|
+
rescue StandardError
|
|
268
|
+
event_ids.to_h { |event_id| [event_id, read_event(event_id)] }
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
def read_event(event_id)
|
|
272
|
+
client.read.event(event_id)
|
|
273
|
+
rescue ::ActiveRecord::ActiveRecordError
|
|
274
|
+
raise
|
|
275
|
+
rescue StandardError => e
|
|
276
|
+
e
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
def prepare_event(event_id, events)
|
|
280
|
+
event = events[event_id]
|
|
281
|
+
raise event if event.is_a?(StandardError)
|
|
282
|
+
raise MissingEvent, "event #{event_id} not found" unless event
|
|
283
|
+
Prepared.new(
|
|
284
|
+
event: event,
|
|
285
|
+
record: client.mapper.events_to_records([event]).first,
|
|
286
|
+
correlation_id: event.metadata.fetch(:correlation_id),
|
|
287
|
+
)
|
|
288
|
+
rescue StandardError => e
|
|
289
|
+
e
|
|
290
|
+
end
|
|
291
|
+
|
|
292
|
+
def deliver_all(messages, prepared, deadline)
|
|
293
|
+
outcomes = {}
|
|
294
|
+
pending = []
|
|
295
|
+
messages.each do |message|
|
|
296
|
+
prepared_event = prepared.fetch(message.event_id)
|
|
297
|
+
pending << Pending.new(message, resolve_subscriber(message, prepared_event), prepared_event)
|
|
298
|
+
rescue StandardError => e
|
|
299
|
+
outcomes[message] = record_failure(message) { fail_dispatch(message, e) }
|
|
300
|
+
end
|
|
301
|
+
pending.zip(dispatch_all(pending, deadline)) { |item, result| outcomes[item.message] = settle(item.message, result) }
|
|
302
|
+
messages.group_by { |message| outcomes.fetch(message) }
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def resolve_subscriber(message, prepared)
|
|
306
|
+
raise prepared if prepared.is_a?(StandardError)
|
|
307
|
+
subscriptions.resolve(message.topic, message.subscriber) or
|
|
308
|
+
raise UnknownSubscriber, "#{message.subscriber} is not subscribed to #{message.topic}"
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
def settle(message, result)
|
|
312
|
+
case result
|
|
313
|
+
when nil
|
|
314
|
+
:delivered
|
|
315
|
+
when DEFERRED
|
|
316
|
+
:deferred
|
|
317
|
+
else
|
|
318
|
+
record_failure(message) { fail_dispatch(message, result) }
|
|
319
|
+
end
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
def dispatch_all(pending, deadline)
|
|
323
|
+
return dispatch_each(pending, deadline) unless subscriptions.bulk? && pending.any?
|
|
324
|
+
dispatch_in_bulk(pending, deadline)
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
def dispatch_in_bulk(pending, deadline)
|
|
328
|
+
subscriptions.dispatch_all(
|
|
329
|
+
pending.map do |item|
|
|
330
|
+
AsyncSubscriptions::Delivery.new(subscriber: item.subscriber, event: item.prepared.event, record: item.prepared.record)
|
|
331
|
+
end,
|
|
332
|
+
)
|
|
333
|
+
rescue StandardError
|
|
334
|
+
dispatch_each(pending, deadline)
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
def dispatch_each(pending, deadline)
|
|
338
|
+
pending.map { |item| clock.call > deadline ? DEFERRED : dispatch(item.subscriber, item.prepared) }
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
def dispatch(subscriber, prepared)
|
|
342
|
+
client.with_metadata(correlation_id: prepared.correlation_id, causation_id: prepared.event.event_id) do
|
|
343
|
+
subscriptions.dispatch(subscriber, prepared.event, prepared.record)
|
|
344
|
+
end
|
|
345
|
+
nil
|
|
346
|
+
rescue StandardError => e
|
|
347
|
+
e
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
def record_failure(message)
|
|
351
|
+
yield
|
|
352
|
+
rescue StandardError => e
|
|
353
|
+
logger.error("Could not record the failure of outbox message #{message.outbox_id}: #{e.class}")
|
|
354
|
+
:unrecorded
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
def fail_dispatch(message, error)
|
|
358
|
+
attempts = message.attempts + 1
|
|
359
|
+
retry_policy.retry?(error, attempts) ? reschedule(message, attempts, error) : bury(message, error)
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
def reschedule(message, attempts, error)
|
|
363
|
+
next_attempt_at = retry_policy.next_attempt_at(attempts, clock.call)
|
|
364
|
+
outbox.reschedule(message, attempts: attempts, next_attempt_at: next_attempt_at, error: error)
|
|
365
|
+
logger.warn(
|
|
366
|
+
"Outbox message #{message.outbox_id} (event #{message.event_id}, #{message.subscriber}) failed " \
|
|
367
|
+
"attempt #{attempts}/#{retry_policy.max_attempts}, next at #{next_attempt_at.iso8601}: #{error.class}",
|
|
368
|
+
)
|
|
369
|
+
instrument_failure(message, attempts, error, :retried)
|
|
370
|
+
:retried
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
def bury(message, error)
|
|
374
|
+
attempts = message.attempts + 1
|
|
375
|
+
if outbox.bury(message, attempts: attempts, error: error, now: clock.call)
|
|
376
|
+
logger.error(
|
|
377
|
+
"Outbox message #{message.outbox_id} (event #{message.event_id}, #{message.subscriber}) moved to dead letters " \
|
|
378
|
+
"after #{attempts} attempt(s): #{error.class}",
|
|
379
|
+
)
|
|
380
|
+
instrument_failure(message, attempts, error, :dead)
|
|
381
|
+
end
|
|
382
|
+
:dead
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
def install_signal_handlers
|
|
386
|
+
%w[INT TERM].each { |signal| chain_signal_handler(signal) }
|
|
387
|
+
end
|
|
388
|
+
|
|
389
|
+
def chain_signal_handler(signal)
|
|
390
|
+
previous =
|
|
391
|
+
signals.trap(signal) do |signo|
|
|
392
|
+
@shutting_down = true
|
|
393
|
+
previous.call(signo) if previous.respond_to?(:call)
|
|
394
|
+
end
|
|
395
|
+
end
|
|
396
|
+
end
|
|
397
|
+
end
|
|
398
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RubyEventStore
|
|
4
|
+
module OutboxRelay
|
|
5
|
+
# Decides whether a failed dispatch is retried, and when.
|
|
6
|
+
#
|
|
7
|
+
# The delay grows exponentially from base_delay, is capped at max_delay and
|
|
8
|
+
# randomly stretched by up to jitter (a fraction of the delay), so messages
|
|
9
|
+
# that failed together don't all come back at the same moment. With the
|
|
10
|
+
# defaults, a message is dead-lettered after 25 attempts spread over roughly
|
|
11
|
+
# 13 hours.
|
|
12
|
+
class RetryPolicy
|
|
13
|
+
# @param max_attempts [Integer] attempts after which a message is dead-lettered
|
|
14
|
+
# @param base_delay [Numeric] seconds before the first retry
|
|
15
|
+
# @param max_delay [Numeric] upper bound of a single delay, in seconds
|
|
16
|
+
# @param jitter [Float] maximum random stretch of a delay, as a fraction of it
|
|
17
|
+
# @param permanent_errors [Array<Class>] dispatch errors dead-lettered on
|
|
18
|
+
# first occurrence instead of being retried
|
|
19
|
+
# @param random [Random]
|
|
20
|
+
def initialize(
|
|
21
|
+
max_attempts: 25,
|
|
22
|
+
base_delay: 1,
|
|
23
|
+
max_delay: 3600,
|
|
24
|
+
jitter: 0.2,
|
|
25
|
+
permanent_errors: [],
|
|
26
|
+
random: Random.new
|
|
27
|
+
)
|
|
28
|
+
raise ArgumentError, "max_attempts must be at least 1" if max_attempts < 1
|
|
29
|
+
@max_attempts = max_attempts
|
|
30
|
+
@base_delay = base_delay
|
|
31
|
+
@max_delay = max_delay
|
|
32
|
+
@jitter = jitter
|
|
33
|
+
@permanent_errors = permanent_errors
|
|
34
|
+
@random = random
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
attr_reader :max_attempts
|
|
38
|
+
|
|
39
|
+
# @param error [Exception] the dispatch failure
|
|
40
|
+
# @param attempts [Integer] attempts made so far, including the failed one
|
|
41
|
+
# @return [Boolean]
|
|
42
|
+
def retry?(error, attempts)
|
|
43
|
+
attempts < max_attempts && permanent_errors.none? { |klass| klass === error }
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# @param attempts [Integer] attempts made so far, including the failed one
|
|
47
|
+
# @param now [Time]
|
|
48
|
+
# @return [Time] when the next attempt is due
|
|
49
|
+
def next_attempt_at(attempts, now)
|
|
50
|
+
delay = [base_delay * (2**(attempts - 1)), max_delay].min
|
|
51
|
+
now + (delay * (1 + (jitter * random.rand)))
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
attr_reader :base_delay, :max_delay, :jitter, :permanent_errors, :random
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ruby_event_store"
|
|
4
|
+
require "ruby_event_store/active_record"
|
|
5
|
+
require_relative "outbox_relay/version"
|
|
6
|
+
require_relative "outbox_relay/configuration"
|
|
7
|
+
require_relative "outbox_relay/async_subscriptions"
|
|
8
|
+
require_relative "outbox_relay/active_job_dispatcher"
|
|
9
|
+
require_relative "outbox_relay/outbox"
|
|
10
|
+
require_relative "outbox_relay/retry_policy"
|
|
11
|
+
require_relative "outbox_relay/dead_letters"
|
|
12
|
+
require_relative "outbox_relay/client_extension"
|
|
13
|
+
require_relative "outbox_relay/client"
|
|
14
|
+
require_relative "outbox_relay/relay"
|
|
15
|
+
require_relative "outbox_relay/generators/migration_generator"
|
|
16
|
+
require_relative "outbox_relay/railtie" if defined?(::Rails::Railtie)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "shellwords"
|
|
4
|
+
require_relative "../ruby_event_store/outbox_relay/generators/migration_generator"
|
|
5
|
+
|
|
6
|
+
namespace :ruby_event_store do
|
|
7
|
+
connect = -> { ::ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"]) if ENV["DATABASE_URL"] }
|
|
8
|
+
dead_letters = lambda do
|
|
9
|
+
require_relative "../ruby_event_store/outbox_relay"
|
|
10
|
+
connect.call
|
|
11
|
+
RubyEventStore::OutboxRelay::DeadLetters.new
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
desc "Generate migration creating the outbox tables"
|
|
15
|
+
task "outbox_relay:install_migration" => :environment do
|
|
16
|
+
connect.call
|
|
17
|
+
database_adapter =
|
|
18
|
+
RubyEventStore::ActiveRecord::DatabaseAdapter.from_string(::ActiveRecord::Base.connection.adapter_name)
|
|
19
|
+
path =
|
|
20
|
+
RubyEventStore::OutboxRelay::MigrationGenerator.new.call(database_adapter, ENV["MIGRATION_PATH"] || "db/migrate")
|
|
21
|
+
puts "Migration file created #{path}"
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
desc "Run the outbox relay (independent, long-running process; see --help for options)"
|
|
25
|
+
task "outbox_relay:run" do
|
|
26
|
+
require_relative "../ruby_event_store/outbox_relay/cli"
|
|
27
|
+
RubyEventStore::OutboxRelay::CLI.new.run(Shellwords.split(ENV["OUTBOX_RELAY_ARGS"].to_s))
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
desc "List outbox dead letters"
|
|
31
|
+
task "outbox_relay:dead_letters:list" => :environment do
|
|
32
|
+
dead_letters.call.each do |dead_letter|
|
|
33
|
+
puts [
|
|
34
|
+
dead_letter.id,
|
|
35
|
+
dead_letter.event_id,
|
|
36
|
+
dead_letter.topic,
|
|
37
|
+
dead_letter.subscriber,
|
|
38
|
+
dead_letter.attempts,
|
|
39
|
+
dead_letter.error_class,
|
|
40
|
+
dead_letter.dead_at.utc.iso8601,
|
|
41
|
+
].join("\t")
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
desc "Move outbox dead letter(s) back to the outbox: ID, or all (optionally narrowed by TOPIC and SUBSCRIBER)"
|
|
46
|
+
task "outbox_relay:dead_letters:retry", [:id] => :environment do |_task, args|
|
|
47
|
+
if args.fetch(:id) == "all"
|
|
48
|
+
count = dead_letters.call.requeue_all(topic: ENV["TOPIC"], subscriber: ENV["SUBSCRIBER"])
|
|
49
|
+
puts "Requeued #{count} dead letter(s)"
|
|
50
|
+
else
|
|
51
|
+
dead_letters.call.requeue(Integer(args.fetch(:id)))
|
|
52
|
+
puts "Requeued dead letter #{args.fetch(:id)}"
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
desc "Delete an outbox dead letter permanently"
|
|
57
|
+
task "outbox_relay:dead_letters:discard", [:id] => :environment do |_task, args|
|
|
58
|
+
dead_letters.call.discard(Integer(args.fetch(:id)))
|
|
59
|
+
puts "Discarded dead letter #{args.fetch(:id)}"
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=Rails Event Store transactional outbox relay
|
|
3
|
+
# The relay is an independent process with its own lifecycle, not a child of the
|
|
4
|
+
# web application. After a restart it catches up from the outbox table (messages
|
|
5
|
+
# whose lease ran out become due again), so start order relative to the
|
|
6
|
+
# application doesn't matter.
|
|
7
|
+
After=network.target postgresql.service mysql.service
|
|
8
|
+
|
|
9
|
+
[Service]
|
|
10
|
+
Type=simple
|
|
11
|
+
WorkingDirectory=/var/www/app/current
|
|
12
|
+
Environment=RAILS_ENV=production
|
|
13
|
+
# Holds DATABASE_URL. Keep it readable by root only (chmod 600): the URL carries
|
|
14
|
+
# the database password, which must never be passed as an argument, where every
|
|
15
|
+
# local user could read it from the process list.
|
|
16
|
+
EnvironmentFile=/etc/res-outbox-relay.env
|
|
17
|
+
ExecStart=/usr/bin/env bundle exec res_outbox_relay \
|
|
18
|
+
--require=config/outbox_relay.rb \
|
|
19
|
+
--batch-size=100 \
|
|
20
|
+
--poll-interval=1.0
|
|
21
|
+
|
|
22
|
+
# Any number of instances (e.g. on several hosts) is safe thanks to
|
|
23
|
+
# FOR UPDATE SKIP LOCKED and leases: there is no need to make sure exactly one runs.
|
|
24
|
+
Restart=always
|
|
25
|
+
RestartSec=5
|
|
26
|
+
|
|
27
|
+
User=deploy
|
|
28
|
+
Group=deploy
|
|
29
|
+
|
|
30
|
+
# Hardening. The relay only talks to the database and the job queue over the
|
|
31
|
+
# network and writes to stdout, so it needs no privileges and a read-only system.
|
|
32
|
+
# If the application writes elsewhere (logs, tmp), list those paths in
|
|
33
|
+
# ReadWritePaths=. Use ProtectHome=true instead if gems are not installed under /home.
|
|
34
|
+
NoNewPrivileges=true
|
|
35
|
+
CapabilityBoundingSet=
|
|
36
|
+
PrivateTmp=true
|
|
37
|
+
PrivateDevices=true
|
|
38
|
+
ProtectSystem=strict
|
|
39
|
+
ProtectHome=read-only
|
|
40
|
+
ProtectKernelTunables=true
|
|
41
|
+
ProtectKernelModules=true
|
|
42
|
+
ProtectKernelLogs=true
|
|
43
|
+
ProtectControlGroups=true
|
|
44
|
+
ProtectClock=true
|
|
45
|
+
RestrictSUIDSGID=true
|
|
46
|
+
RestrictNamespaces=true
|
|
47
|
+
RestrictRealtime=true
|
|
48
|
+
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
|
49
|
+
LockPersonality=true
|
|
50
|
+
SystemCallArchitectures=native
|
|
51
|
+
UMask=0077
|
|
52
|
+
|
|
53
|
+
[Install]
|
|
54
|
+
WantedBy=multi-user.target
|