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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 100b8d79e21d656df01028a30285c7bd5bb42fa789222f2548d27505cd593752
4
+ data.tar.gz: bd3e26262bc9d7eb21fb2a048df44cdbf53aa0bd59f5006fced5b9fd13381c32
5
+ SHA512:
6
+ metadata.gz: 8d8a571648ebab4b6fe384a7753998e001f1e368050af99b017b05cc3062091c35e97376de20c4b2761b7dc950c05ec0821db61c1dd3f8f9bf30ca47c2677731
7
+ data.tar.gz: a3dac37ce96385d5d542da2586c00a72ce52765fe0e4a37cb5a287d929a41e1151ae85d742b7df7172b968d1db0b65dd364b1b350a75688ed019dee910ad2a55
data/README.md ADDED
@@ -0,0 +1,172 @@
1
+ # Ruby Event Store — Outbox Relay
2
+
3
+ Transactional outbox for Rails Event Store, built on two small tables next to `event_store_events`. The events table is never altered.
4
+
5
+ `publish` writes the event and, in the same SQL transaction, one **outbox message** per async subscriber of that event. A separate, independent process (the **relay**) claims due messages in short transactions, delivers them with no transaction open, and deletes them once delivered. The write and the "intent to deliver" are atomic, so a crash between saving an event and notifying subscribers can no longer lose the notification.
6
+
7
+ Delivery is decided **per subscriber**, not per event:
8
+
9
+ - **`subscribe_sync`** (identical to the original `subscribe`, kept as a working alias) — the handler is called synchronously, in-process, exactly as it always has been.
10
+ - **`subscribe_async`** — the handler is delivered exclusively by the relay, by default through ActiveJob.
11
+
12
+ `publish` still dispatches to every sync subscriber immediately, after the transaction commits. The two kinds are disjoint sets of handlers, so nothing is ever delivered twice by the two paths. Event types without async subscribers write no outbox messages at all.
13
+
14
+ ## Why not the existing `ruby_event_store-outbox` gem?
15
+
16
+ `ruby_event_store-outbox` transactionally enqueues background jobs (Sidekiq) into a dedicated outbox table. This gem calls a broker-shaped dispatcher directly, the same way a synchronous `publish` would, and keeps per-subscriber retry state and a dead letter table instead of a job format of its own. Use whichever shape fits your infrastructure; they solve overlapping but distinct problems and can coexist.
17
+
18
+ ## Design
19
+
20
+ ```
21
+ publish ──▶ [ BEGIN; INSERT event(s); INSERT outbox message per (event, async subscriber); COMMIT ] ──▶ sync subscribers
22
+
23
+ relay: claim ──▶ dispatch (no transaction) ──▶ delete delivered
24
+ │ │
25
+ │ lease ├─ failed ──▶ retry later (backoff)
26
+ ▼ └─ gave up ──▶ dead letters
27
+ next_attempt_at
28
+ ```
29
+
30
+ - **`event_store_outbox_messages`** — one row per (event, subscriber): `event_id`, `topic`, `subscriber` (the handler's class name), `attempts`, `next_attempt_at`, `last_error`. It only ever holds work still to do, so it stays small.
31
+ - **`event_store_outbox_dead_letters`** — deliveries that exhausted their attempts or failed with a permanent error, with the error class, message and backtrace. See [Dead letters](https://railseventstore.org/docs/advanced-topics/outbox-relay#dead-letters).
32
+ - The relay claims messages with `FOR UPDATE SKIP LOCKED` in a transaction that only moves `next_attempt_at` to the end of a **lease** (five minutes by default). Other relays skip leased messages, and a relay that crashes mid-batch releases its messages simply by the lease running out.
33
+ - The relay reads the event from `event_store_events` by id when it delivers; the outbox never duplicates event data.
34
+ - **No monkeypatching, no ambient state.** The outbox client is a subclass of `RubyEventStore::Client` (or `RailsEventStore::Client`) that overrides `publish`; requiring this gem changes no existing class, and the event repository is not touched at all. `append` is not overridden and, as documented, notifies no one, so it writes no messages.
35
+
36
+ ## Requirements
37
+
38
+ - Ruby >= 3.3
39
+ - `ruby_event_store` and `ruby_event_store-active_record` >= 3.0.0 and < 4: the outbox client's `publish` repeats the steps of `RubyEventStore::Client#publish`, and relies on its internals, hence the pin
40
+ - `activerecord` and `activejob` >= 7.1
41
+ - `rails_event_store` >= 3.0.0, only for `RailsClient`
42
+ - PostgreSQL (any supported version) or MySQL >= 8.0 (relay concurrency relies on `SKIP LOCKED`, available since MySQL 8.0). SQLite works for a single relay instance only: it has no row locks.
43
+
44
+ ## Installation (app)
45
+
46
+ Add to your Gemfile:
47
+
48
+ ```ruby
49
+ gem "ruby_event_store-outbox_relay"
50
+ ```
51
+
52
+ In a Rails application, load the Rails integration too, which defines `RailsClient` and needs `rails_event_store`:
53
+
54
+ ```ruby
55
+ gem "ruby_event_store-outbox_relay", require: "ruby_event_store/outbox_relay/rails"
56
+ ```
57
+
58
+ Generate and run the migration creating the outbox tables:
59
+
60
+ ```
61
+ bundle exec rake ruby_event_store:outbox_relay:install_migration
62
+ bin/rails db:migrate
63
+ ```
64
+
65
+ Requiring the gem changes nothing by itself. You opt in by building your client from `RubyEventStore::OutboxRelay::Client` (a `RubyEventStore::Client`) or, in Rails, `RubyEventStore::OutboxRelay::RailsClient` (a `RailsEventStore::Client`), which take the same arguments as the classes they extend. Both gain `subscribe_sync`, `subscribe_async`, `async_subscriptions` and `outbox`:
66
+
67
+ ```ruby
68
+ event_store = RubyEventStore::OutboxRelay::RailsClient.new
69
+
70
+ event_store.subscribe_sync(OrderMailer, to: [OrderPlaced])
71
+ event_store.subscribe_async(OrderReportJob, to: [OrderPlaced])
72
+
73
+ event_store.publish(OrderPlaced.new(data: { order_id: order.id }))
74
+ # OrderMailer runs immediately. OrderReportJob only runs once the relay delivers the message.
75
+ ```
76
+
77
+ To extend a client class of your own instead, include the module into a subclass of a client: `class EventStoreClient < RailsEventStore::Client; include RubyEventStore::OutboxRelay::ClientExtension; end`.
78
+
79
+ The application uses the registered subscribers to decide which messages to write; the relay uses them to resolve a message's `subscriber` name back to a handler. It resolves names only through this registry — never by constant lookup — so a row in the outbox table can only ever reach a handler you registered. A message naming an unregistered subscriber is retried, and dead-lettered once the retry policy gives up. Run the relay with the very client of your application (see below), so the list of async subscribers is defined once.
80
+
81
+ The subscriber must be a named class: its name is what the outbox stores. Unlike `subscribe_sync`, `subscribe_async` takes no block.
82
+
83
+ `async_subscriptions` defaults to `RubyEventStore::OutboxRelay::ActiveJobDispatcher` with the YAML serializer, so handlers must be ActiveJob classes; the relay enqueues each batch of jobs at once, see [Throughput](https://railseventstore.org/docs/advanced-topics/outbox-relay#throughput). Pass a different one at construction time:
84
+
85
+ ```ruby
86
+ dispatcher = RubyEventStore::ImmediateDispatcher.new(scheduler: MyScheduler.new)
87
+ RubyEventStore::OutboxRelay::RailsClient.new(
88
+ async_subscriptions: RubyEventStore::OutboxRelay::AsyncSubscriptions.new(dispatcher: dispatcher),
89
+ )
90
+ ```
91
+
92
+ The outbox is written in the very transaction of the events, which holds only when the outbox tables are reached through the same connection as the event store. The outbox models inherit from `ActiveRecord::Base`, so that is the case when the event store does too. If the event store lives on another connection, say through an abstract base class of its own, give the client an outbox built on models that inherit from that class, and the same to the dead letter tasks:
93
+
94
+ ```ruby
95
+ class OutboxMessage < EventStoreRecord; self.table_name = "event_store_outbox_messages"; end
96
+ class OutboxDeadLetter < EventStoreRecord; self.table_name = "event_store_outbox_dead_letters"; end
97
+
98
+ outbox = RubyEventStore::OutboxRelay::Outbox.new(message_klass: OutboxMessage, dead_letter_klass: OutboxDeadLetter)
99
+ client = RubyEventStore::OutboxRelay::RailsClient.new(repository: repository, outbox: outbox)
100
+ RubyEventStore::OutboxRelay::DeadLetters.new(message_klass: OutboxMessage, dead_letter_klass: OutboxDeadLetter)
101
+ ```
102
+
103
+ `publish(event, topic: "custom")` writes messages for the async subscribers of that topic, exactly as it notifies the sync subscribers of that topic.
104
+
105
+ ## Installation (relay process)
106
+
107
+ The relay reads its subscriptions, outbox and mapper straight from a `Client` — the one of your application, so `subscribe_async` is called in one place only. Point the process at a file that loads the application and builds the relay, with `--require`:
108
+
109
+ ```ruby
110
+ # config/outbox_relay.rb
111
+ require_relative "environment"
112
+
113
+ RubyEventStore::OutboxRelay::Configuration.configure do |**options|
114
+ RubyEventStore::OutboxRelay::Relay.new(client: Rails.configuration.event_store, **options)
115
+ end
116
+ ```
117
+
118
+ The block receives the options given on the command line as keywords, `logger` always among them, and passes them on to `Relay.new`. A block that can't take one of them makes the relay fail at startup, naming it, instead of running with a batch size that was not the one asked for.
119
+
120
+ Synchronous subscribers of the client are never triggered by the relay. The relay refuses a client that isn't an outbox client, and at startup it logs the async subscribers of every topic, warning when there are none — in which case every message would fail, and be dead-lettered in the end.
121
+
122
+ Run it:
123
+
124
+ ```
125
+ DATABASE_URL="postgres://relay@db/app" bundle exec res_outbox_relay --require=config/outbox_relay.rb
126
+ ```
127
+
128
+ Run it as many instances as you like — `FOR UPDATE SKIP LOCKED` plus leases mean concurrent relays never claim the same message. A systemd unit template (`Restart=always`) is included at `support/systemd/res-outbox-relay.service`; a `bundle exec rake ruby_event_store:outbox_relay:run` task is also available for environments that prefer rake.
129
+
130
+ ### `Relay` options
131
+
132
+ | Option | Default | Description |
133
+ | ----------------- | -------------------- | ---------------------------------------------------------------------------------------------------- |
134
+ | `batch_size` | 100 | Messages claimed per batch |
135
+ | `poll_interval` | 1 | Seconds to sleep when nothing was due |
136
+ | `lease_duration` | 300 | Seconds a claimed message stays hidden from other relays. Must comfortably exceed a batch's delivery time; a shorter lease means a slow batch is delivered twice |
137
+ | `retry_policy` | `RetryPolicy.new` | When to retry and when to give up |
138
+
139
+ `--require`, `--batch-size`, `--poll-interval`, `--lease-duration`, `--stats-interval` (`--no-stats` turns the notification off) and `--log-level` are available on the command line; what you don't give keeps the default of the relay. The database comes from `DATABASE_URL`, see [Security](https://railseventstore.org/docs/advanced-topics/outbox-relay#security).
140
+
141
+ ## Going further
142
+
143
+ The [full documentation](https://railseventstore.org/docs/advanced-topics/outbox-relay) covers what this README leaves out:
144
+
145
+ - **Retries and dead letters** — the `RetryPolicy`, which failures are dead-lettered at once, and the `DeadLetters` API and rake tasks to list, requeue and discard.
146
+ - **Observability** — the `ActiveSupport::Notifications` the relay publishes (`process_batch`, `message_failed`, `stats`) and `Outbox#stats`.
147
+ - **Throughput** — measured numbers, bulk enqueue through `ActiveJobDispatcher`, batch size and lease.
148
+ - **Security** — least-privilege database grants, the hardened systemd unit, and the risk of `YAML.unsafe_load` in the default serializer. In short: the database comes from `DATABASE_URL`, never from an argument, and the relay resolves subscribers only through the `subscribe_async` registry.
149
+
150
+ ## Guarantees
151
+
152
+ - **Atomicity.** An event and the outbox messages for its async subscribers are written in one transaction. If either write fails, neither persists, and sync subscribers are not notified.
153
+ - **At-least-once delivery, per subscriber.** A message is deleted only after its dispatch returned. A failure retries only that subscriber's message — the event's other subscribers are not called again. A relay that crashes after dispatching but before deleting redelivers once its lease runs out. Async subscribers must be idempotent by `event_id`.
154
+ - **Dispatch outside any transaction.** A slow or failing subscriber never holds database locks. A job enqueued by the dispatcher is never deferred until after the message is gone, so `enqueue_after_transaction_commit` in ActiveJob cannot lose it.
155
+ - **A message that can't be delivered can't block the queue.** It backs off, then goes to the dead letters.
156
+ - **No duplicated work across relay instances**, via `SELECT ... FOR UPDATE SKIP LOCKED` and leases.
157
+ - **Same metadata context as a synchronous publish** — `correlation_id`/`causation_id` are reproduced through `with_metadata` exactly as `Client#publish` does it.
158
+ - **No ordering guarantee.** Messages are claimed oldest first, but with several relays, retries and ActiveJob, handlers can observe events out of order.
159
+
160
+ ## Contributing
161
+
162
+ Bug reports and pull requests are welcome on GitHub at https://github.com/RailsEventStore/rails_event_store.
163
+
164
+ ## Releasing
165
+
166
+ 1. Bump version
167
+ 2. `make build`
168
+ 3. `make push`
169
+
170
+ ## License
171
+
172
+ MIT
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "ruby_event_store/outbox_relay/cli"
5
+
6
+ cli = RubyEventStore::OutboxRelay::CLI.new
7
+ cli.run(ARGV)
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_job"
4
+
5
+ module RubyEventStore
6
+ module OutboxRelay
7
+ # Delivers to ActiveJob subscribers, one job per delivery.
8
+ #
9
+ # Unlike RailsEventStore::ActiveJobScheduler it can enqueue a whole batch
10
+ # with one ActiveJob.perform_all_later, which adapters turn into a single
11
+ # round trip (Sidekiq's push_bulk, an insert_all of jobs, ...) instead of
12
+ # one per job. The adapter is expected to mark each job it enqueued
13
+ # (job.successfully_enqueued), as ActiveJob's own adapters do: a job left
14
+ # unmarked is reported as not enqueued and retried.
15
+ #
16
+ # ActiveJob.perform_all_later skips the enqueue callbacks (before_enqueue,
17
+ # around_enqueue, after_enqueue), and enqueues a job even when one of them
18
+ # would have halted it. So only jobs without enqueue callbacks of their own
19
+ # are enqueued in bulk; the others are enqueued one by one, callbacks
20
+ # included. The callbacks ActiveJob adds itself (logging, instrumentation)
21
+ # don't count. Telling them apart relies on internals of ActiveJob, so the
22
+ # gem pins its major version, and should they change, or a job not expose
23
+ # them, that job is simply enqueued one by one, with its callbacks.
24
+ class ActiveJobDispatcher
25
+ ACTIVE_JOB_DIRECTORY = "#{File.dirname(::ActiveJob.method(:gem_version).source_location.first)}/".freeze
26
+ private_constant :ACTIVE_JOB_DIRECTORY
27
+
28
+ # Raised for a job that a bulk enqueue reports as not enqueued.
29
+ class NotEnqueued < StandardError; end
30
+
31
+ # @param serializer [#dump] serializes the record into the job's payload;
32
+ # the subscriber's job is expected to deserialize it the same way
33
+ def initialize(serializer:)
34
+ @serializer = serializer
35
+ end
36
+
37
+ # Enqueues one job, callbacks included.
38
+ #
39
+ # @param subscriber [Class] an ActiveJob class
40
+ # @param record [RubyEventStore::Record]
41
+ # @raise [ActiveJob::EnqueueError] when the adapter failed to enqueue the job.
42
+ # A job that an enqueue callback halted is not an error, as it isn't for
43
+ # ActiveJob itself
44
+ def call(subscriber, _event, record)
45
+ error = enqueue_one(subscriber.new(payload_for(record)))
46
+ raise error if error
47
+ end
48
+
49
+ # Enqueues the deliveries, in bulk where the job allows it.
50
+ #
51
+ # A delivery whose job can't even be built, say because its record can't be
52
+ # serialized, is reported as failed, and the others carry on. When a bulk
53
+ # enqueue fails as a whole, its jobs are enqueued one by one, so a single
54
+ # job can't take the others down. A job that had already been pushed before
55
+ # the failure may then be pushed twice, in keeping with at-least-once
56
+ # delivery.
57
+ #
58
+ # Unlike #call, it doesn't run inside Client#with_metadata: a batch mixes
59
+ # events. Its handlers, when they run in the process, can derive the
60
+ # correlation from the delivery's event (its correlation_id, and its own
61
+ # event_id as the causation_id).
62
+ #
63
+ # @param deliveries [Array<AsyncSubscriptions::Delivery>]
64
+ # @return [Array<Exception, nil>] for each delivery, why it wasn't enqueued, or nil
65
+ def call_all(deliveries)
66
+ results = Array.new(deliveries.size)
67
+ bulk = []
68
+ deliveries.each_with_index do |delivery, index|
69
+ job = delivery.subscriber.new(payload_for(delivery.record))
70
+ bulk?(delivery.subscriber) ? bulk << [index, job] : results[index] = enqueue_one(job)
71
+ rescue StandardError => e
72
+ results[index] = e
73
+ end
74
+ enqueue_bulk(bulk, results)
75
+ results
76
+ end
77
+
78
+ # @param subscriber [Class, Object]
79
+ # @return [Boolean]
80
+ def verify(subscriber)
81
+ Class === subscriber && !!(subscriber < ActiveJob::Base)
82
+ end
83
+
84
+ private
85
+
86
+ attr_reader :serializer
87
+
88
+ def payload_for(record)
89
+ record.serialize(serializer).to_h.transform_keys(&:to_s)
90
+ end
91
+
92
+ def bulk?(subscriber)
93
+ subscriber.respond_to?(:_enqueue_callbacks) && subscriber._enqueue_callbacks.all? { |callback| built_in?(callback) }
94
+ end
95
+
96
+ def built_in?(callback)
97
+ callback.respond_to?(:filter) && callback.filter.respond_to?(:source_location) &&
98
+ callback.filter.source_location&.first&.start_with?(ACTIVE_JOB_DIRECTORY)
99
+ end
100
+
101
+ def enqueue_bulk(bulk, results)
102
+ return if bulk.empty?
103
+ ActiveJob.perform_all_later(bulk.map(&:last))
104
+ bulk.each { |index, job| results[index] = not_enqueued(job) unless job.successfully_enqueued? }
105
+ rescue StandardError
106
+ bulk.each { |index, job| results[index] = enqueue_one(job) }
107
+ end
108
+
109
+ def not_enqueued(job)
110
+ job.enqueue_error || NotEnqueued.new("#{job.class} was not enqueued")
111
+ end
112
+
113
+ def enqueue_one(job)
114
+ job.enqueue
115
+ job.enqueue_error
116
+ rescue StandardError => e
117
+ e
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ # Registry of subscribers delivered by the relay (Client#subscribe_async),
6
+ # together with the dispatcher that delivers to them.
7
+ #
8
+ # Subscribers are identified by their class name, which is what gets
9
+ # persisted in the outbox. The relay resolves a persisted name back to a
10
+ # subscriber only through this registry, never through constant lookup, so
11
+ # data in the outbox table can only ever reach handlers registered here.
12
+ class AsyncSubscriptions
13
+ # One event to hand to one subscriber.
14
+ Delivery = Data.define(:subscriber, :event, :record)
15
+
16
+ # @param dispatcher [#call, #verify] delivers an event to one subscriber,
17
+ # e.g. RubyEventStore::ImmediateDispatcher. One that also responds to
18
+ # #call_all is handed whole batches, see #dispatch_all
19
+ def initialize(dispatcher:)
20
+ @dispatcher = dispatcher
21
+ @subscribers = Hash.new { |hash, topic| hash[topic] = {} }
22
+ end
23
+
24
+ # @param subscriber [Class] a named class accepted by the dispatcher
25
+ # @param topics [Array<String>]
26
+ # @raise [ArgumentError] when the subscriber is not a named class
27
+ # @raise [RubyEventStore::InvalidHandler] when the dispatcher rejects it
28
+ def add(subscriber, topics)
29
+ name = subscriber_name(subscriber)
30
+ raise InvalidHandler.new("Handler #{subscriber} is invalid for dispatcher #{dispatcher}") unless dispatcher.verify(subscriber)
31
+ topics.each { |topic| @subscribers[topic][name] = subscriber }
32
+ end
33
+
34
+ # @return [Hash{String => Array<String>}] names of the subscribers registered for each topic
35
+ def to_h
36
+ @subscribers.transform_values(&:keys)
37
+ end
38
+
39
+ # @param topic [String]
40
+ # @return [Array<String>] names of subscribers registered for the topic
41
+ def names_for(topic)
42
+ @subscribers.fetch(topic, {}).keys
43
+ end
44
+
45
+ # @param topic [String]
46
+ # @param name [String]
47
+ # @return [Class, nil] the subscriber registered under that name for the topic
48
+ def resolve(topic, name)
49
+ @subscribers.fetch(topic, {})[name]
50
+ end
51
+
52
+ # @param subscriber [Class]
53
+ # @param event [RubyEventStore::Event]
54
+ # @param record [RubyEventStore::Record]
55
+ def dispatch(subscriber, event, record)
56
+ dispatcher.call(subscriber, event, record)
57
+ end
58
+
59
+ # @return [Boolean] whether the dispatcher delivers whole batches at once
60
+ def bulk?
61
+ dispatcher.respond_to?(:call_all)
62
+ end
63
+
64
+ # Delivers a batch through a dispatcher that responds to #call_all, which
65
+ # takes an Array of Delivery and returns, for each, the error that kept it
66
+ # from being delivered, or nil.
67
+ #
68
+ # A batch mixes events, so it isn't delivered inside Client#with_metadata,
69
+ # as a single delivery through #dispatch is. A dispatcher that runs handlers
70
+ # in the process derives the correlation from each delivery's event: its
71
+ # correlation_id, and its event_id as the causation_id.
72
+ #
73
+ # @param deliveries [Array<Delivery>]
74
+ # @return [Array<Exception, nil>]
75
+ def dispatch_all(deliveries)
76
+ dispatcher.call_all(deliveries)
77
+ end
78
+
79
+ private
80
+
81
+ attr_reader :dispatcher
82
+
83
+ def subscriber_name(subscriber)
84
+ raise ArgumentError, "async subscriber must be a named class, got #{subscriber.inspect}" unless Class === subscriber && subscriber.name
85
+ subscriber.name
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "logger"
5
+ require_relative "version"
6
+ require_relative "configuration"
7
+ require_relative "relay"
8
+
9
+ module RubyEventStore
10
+ module OutboxRelay
11
+ class CLI
12
+ DEFAULTS = {
13
+ batch_size: nil,
14
+ poll_interval: nil,
15
+ lease_duration: nil,
16
+ stats_interval: nil,
17
+ stats: true,
18
+ log_level: :info,
19
+ require_path: nil,
20
+ }.freeze
21
+ Options = Struct.new(*DEFAULTS.keys)
22
+
23
+ class Parser
24
+ def self.parse(argv)
25
+ options = Options.new(*DEFAULTS.values)
26
+ OptionParser
27
+ .new do |o|
28
+ o.banner = "Usage: res_outbox_relay --require=config/outbox_relay.rb [options]"
29
+ o.separator "The database is taken from the DATABASE_URL environment variable, never from an argument, " \
30
+ "so its credentials stay out of the process list."
31
+
32
+ o.on(
33
+ "--require=PATH",
34
+ "Ruby file that calls RubyEventStore::OutboxRelay::Configuration.configure " \
35
+ "to build the relay (typically Relay.new(client: ...)). Mandatory.",
36
+ ) { |v| options.require_path = v }
37
+
38
+ o.on("--batch-size=BATCH_SIZE", Integer, "Amount of messages claimed in one batch. Default: #{Relay::DEFAULT_BATCH_SIZE}") do |v|
39
+ options.batch_size = v
40
+ end
41
+
42
+ o.on(
43
+ "--poll-interval=SECONDS",
44
+ Float,
45
+ "How long to sleep before next check when there was nothing to do. Default: #{Relay::DEFAULT_POLL_INTERVAL}",
46
+ ) { |v| options.poll_interval = v }
47
+
48
+ o.on(
49
+ "--lease-duration=SECONDS",
50
+ Float,
51
+ "How long a claimed message stays hidden from other relays; must exceed the time to deliver " \
52
+ "a batch. Default: #{Relay::DEFAULT_LEASE_DURATION}",
53
+ ) { |v| options.lease_duration = v }
54
+
55
+ o.on(
56
+ "--stats-interval=SECONDS",
57
+ Float,
58
+ "How often the stats notification is published. Default: #{Relay::DEFAULT_STATS_INTERVAL}",
59
+ ) { |v| options.stats_interval = v }
60
+
61
+ o.on("--no-stats", "Don't publish the stats notification") { options.stats = false }
62
+
63
+ o.on(
64
+ "--log-level=LOG_LEVEL",
65
+ %i[fatal error warn info debug],
66
+ "Logging level, one of: fatal, error, warn, info, debug. Default: info",
67
+ ) { |v| options.log_level = v.to_sym }
68
+
69
+ o.on_tail("--version", "Show version") do
70
+ puts VERSION
71
+ exit
72
+ end
73
+ end
74
+ .parse(argv)
75
+ options
76
+ end
77
+ end
78
+
79
+ def run(argv)
80
+ options = Parser.parse(argv)
81
+ raise ArgumentError, "--require is mandatory, see --help" unless options.require_path
82
+
83
+ require "active_record"
84
+ ::ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"]) if ENV["DATABASE_URL"]
85
+ require File.expand_path(options.require_path)
86
+
87
+ Configuration.build(**overrides(options)).run
88
+ end
89
+
90
+ private
91
+
92
+ def overrides(options)
93
+ given = options.to_h.slice(:batch_size, :poll_interval, :lease_duration, :stats_interval).compact
94
+ given[:stats_interval] = nil unless options.stats
95
+ given.merge(logger: Logger.new($stdout, level: options.log_level, progname: "RES-OutboxRelay"))
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ # A RubyEventStore::Client with async subscriptions delivered through the
6
+ # outbox, see ClientExtension.
7
+ class Client < RubyEventStore::Client
8
+ include ClientExtension
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ # Adds async subscriptions to a RubyEventStore::Client subclass, without
6
+ # touching ruby_event_store itself.
7
+ #
8
+ # #subscribe_sync (aliased as #subscribe, unchanged) delivers synchronously
9
+ # and in-process exactly as before; #subscribe_async delivers exclusively
10
+ # through the outbox relay. #publish persists, in the same transaction as
11
+ # the events, one outbox message per (event, async subscriber of its
12
+ # topic), then dispatches to sync subscribers exactly like the original.
13
+ # #append is untouched and, as documented, notifies no one: it never writes
14
+ # outbox messages.
15
+ #
16
+ # Include it into your own client class, or use one of the ready-made ones,
17
+ # Client and, after requiring "ruby_event_store/outbox_relay/rails",
18
+ # RailsClient. Requiring this gem changes no existing class.
19
+ #
20
+ # #publish repeats the steps of RubyEventStore::Client#publish, and relies on
21
+ # the client's internals to do so. That is why the gem pins the major
22
+ # version of ruby_event_store, and a spec fails should one of them go.
23
+ module ClientExtension
24
+ # @param async_subscriptions [AsyncSubscriptions] registry of
25
+ # #subscribe_async subscribers, read by the Relay. Defaults to one
26
+ # dispatching through ActiveJobDispatcher with the YAML serializer, the
27
+ # same serialization RailsEventStore::Client uses by default for its
28
+ # own async handlers.
29
+ # @param outbox [Outbox] storage of pending deliveries
30
+ def initialize(async_subscriptions: nil, outbox: nil, **kwargs)
31
+ super(**kwargs)
32
+ @async_subscriptions = async_subscriptions || default_async_subscriptions
33
+ @outbox = outbox || Outbox.new
34
+ end
35
+
36
+ # @return [Mappers::BatchMapper]
37
+ def mapper
38
+ @mapper
39
+ end
40
+
41
+ # @return [AsyncSubscriptions]
42
+ attr_reader :async_subscriptions
43
+
44
+ # @return [Outbox]
45
+ attr_reader :outbox
46
+
47
+ # Persists event(s), together with an outbox message for every async
48
+ # subscriber of each event's topic, then notifies sync subscribers --
49
+ # otherwise identical to RubyEventStore::Client#publish.
50
+ #
51
+ # @param (see RubyEventStore::Client#publish)
52
+ # @return [self]
53
+ def publish(events, topic: nil, stream_name: GLOBAL_STREAM, expected_version: :any)
54
+ enriched_events = enrich_events_metadata(events)
55
+ records = transform(enriched_events)
56
+ topics = enriched_events.map { |event| topic || event.event_type }
57
+ outbox.append(records, topics: topics, subscriptions: async_subscriptions, now: Time.now.utc) do
58
+ append_records_to_stream(records, stream_name: stream_name, expected_version: expected_version)
59
+ end
60
+ enriched_events.zip(records, topics) { |event, record, event_topic| dispatch_sync(event_topic, event, record) }
61
+ self
62
+ end
63
+
64
+ # Subscribes a handler invoked synchronously, in-process -- identical
65
+ # behavior to the original #subscribe, kept below as a working alias for
66
+ # backward compatibility.
67
+ #
68
+ # @param (see RubyEventStore::Client#subscribe)
69
+ def subscribe_sync(subscriber = nil, to:, &block)
70
+ subscribe(subscriber, to: to, &block)
71
+ end
72
+
73
+ # Subscribes a handler delivered exclusively by the outbox relay, instead
74
+ # of synchronously in-process. The subscriber must be a named class: its
75
+ # name is what the outbox stores, and it must be subscribed the same way
76
+ # in both the application and the relay process.
77
+ #
78
+ # @param subscriber [Class] the handler class delivered by the relay
79
+ def subscribe_async(subscriber, to:)
80
+ async_subscriptions.add(subscriber, to.map { |event_klass| @event_type_resolver.call(event_klass) })
81
+ end
82
+
83
+ private
84
+
85
+ def dispatch_sync(topic, event, record)
86
+ with_metadata(correlation_id: event.metadata.fetch(:correlation_id), causation_id: event.event_id) do
87
+ if @broker.public_method(:call).arity == 3
88
+ @broker.call(topic, event, record)
89
+ else
90
+ warn <<~EOW
91
+ Message broker shall support topics.
92
+ Topic WILL BE IGNORED in the current broker.
93
+ Modify the broker implementation to pass topic as an argument to broker.call method.
94
+ EOW
95
+ @broker.call(event, record)
96
+ end
97
+ end
98
+ end
99
+
100
+ def default_async_subscriptions
101
+ AsyncSubscriptions.new(dispatcher: ActiveJobDispatcher.new(serializer: Serializers::YAML))
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyEventStore
4
+ module OutboxRelay
5
+ module Configuration
6
+ class NotConfigured < StandardError; end
7
+
8
+ class << self
9
+ # Sets how the command line builds the relay. The block receives the
10
+ # options the command line gave, as keywords (+batch_size+, +poll_interval+,
11
+ # +lease_duration+, +stats_interval+, always +logger+), and passes them on:
12
+ #
13
+ # Configuration.configure { |**options| Relay.new(client: client, **options) }
14
+ #
15
+ # @yieldparam options [Hash] the options given on the command line
16
+ # @yieldreturn [Relay]
17
+ def configure(&block)
18
+ @build_block = block
19
+ end
20
+
21
+ # @raise [NotConfigured] before #configure was called
22
+ # @raise [ArgumentError] when the block can't take one of the overrides, which
23
+ # would otherwise be ignored without a word
24
+ def build(**overrides)
25
+ raise NotConfigured, "call RubyEventStore::OutboxRelay::Configuration.configure first" unless @build_block
26
+ ignored = ignored_by(@build_block, overrides.keys)
27
+ unless ignored.empty?
28
+ raise ArgumentError,
29
+ "the configure block ignores #{ignored.join(", ")}: " \
30
+ "declare them, or take **options and pass them on to Relay.new"
31
+ end
32
+ @build_block.call(**overrides)
33
+ end
34
+
35
+ private
36
+
37
+ def ignored_by(block, keys)
38
+ parameters = block.parameters
39
+ return [] if parameters.any? { |type, _| type == :keyrest }
40
+ keys - parameters.select { |type, _| %i[key keyreq].include?(type) }.map(&:last)
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end