activerecord-xa 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/CHANGELOG.md +24 -0
- data/COPYRIGHT +5 -0
- data/LICENSE +9 -0
- data/README.md +262 -0
- data/docs/ARCHITECTURE.md +89 -0
- data/docs/INSTALL.md +103 -0
- data/docs/USAGE.md +103 -0
- data/lib/active_record/xa/adapter_extension.rb +75 -0
- data/lib/active_record/xa/branch.rb +171 -0
- data/lib/active_record/xa/configuration.rb +58 -0
- data/lib/active_record/xa/coordinator.rb +374 -0
- data/lib/active_record/xa/decision_log.rb +172 -0
- data/lib/active_record/xa/errors.rb +36 -0
- data/lib/active_record/xa/railtie.rb +22 -0
- data/lib/active_record/xa/recovery.rb +178 -0
- data/lib/active_record/xa/transaction_extension.rb +103 -0
- data/lib/active_record/xa/version.rb +9 -0
- data/lib/active_record/xa/xid.rb +104 -0
- data/lib/active_record/xa.rb +92 -0
- data/lib/activerecord-xa.rb +5 -0
- data/lib/generators/xa/install/install_generator.rb +41 -0
- data/lib/generators/xa/install/templates/initializer.rb.tt +21 -0
- data/lib/generators/xa/install/templates/migration.rb.tt +11 -0
- metadata +93 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 1ff1a37cc047b0069ca27795e70c01617253e6f987db89358e501c4d23452c32
|
|
4
|
+
data.tar.gz: ae408b6b452a4e5199749f5cfbe80fb3d96732b75cd98a47a9005ab2a00ad538
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: b52b51bba4c51de6be0b349448ba892283ea9c4cc7bf1440923ea8ee7b3b514391d53dd81cd3e8df47ca3f5e9848fe58a30a574c6a7c1d4e1fd0c4d3d1693a38
|
|
7
|
+
data.tar.gz: 0f97afc7ff559d28925955730aa885d82a9fcc09dc8f788c645e092e8b8e9f1bf08bda1db697914a29e986d284fd23a13870e6a984373c6d5c5c658cf4255559
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to ActiveRecord::XA are documented here.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0] - 2026-11-27
|
|
11
|
+
|
|
12
|
+
First release.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- `ActiveRecord::XA.transaction`: one transaction across several MySQL databases, using XA two-phase commit, with Rails callbacks, savepoints, isolation levels and `ActiveRecord::Rollback` working as in a normal transaction.
|
|
16
|
+
- A durable decision log and `ActiveRecord::XA.recover!`, which commits or rolls back whatever a crash leaves prepared, the same way on every database.
|
|
17
|
+
- `config.participants`, so `ActiveRecord::XA.recover!` needs no arguments, and the `xa:recover` rake task.
|
|
18
|
+
- `bin/rails generate xa:install`, writing the initializer and the decision log migration.
|
|
19
|
+
- Class names accepted for `decision_log_class` and `participants`, so initializers never load models.
|
|
20
|
+
- A benchmark of the per-transaction cost (`rake bench`).
|
|
21
|
+
- An example Rails app (`example/`): a shop and a ledger in two databases, with buttons for declined cards, crashes mid-commit and recovery.
|
|
22
|
+
|
|
23
|
+
[Unreleased]: https://github.com/studio51/activerecord-xa/compare/v0.1.0...HEAD
|
|
24
|
+
[0.1.0]: https://github.com/studio51/activerecord-xa/releases/tag/v0.1.0
|
data/COPYRIGHT
ADDED
data/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vlad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# ActiveRecord::XA
|
|
2
|
+
|
|
3
|
+
> Atomic transactions across multiple MySQL databases for Active Record.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/studio51/activerecord-xa/actions/workflows/ci.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
Nested `transaction` blocks on different databases look atomic, but they are two independent transactions:
|
|
9
|
+
|
|
10
|
+
```ruby
|
|
11
|
+
PrimaryRecord.transaction do
|
|
12
|
+
TrackerRecord.transaction do
|
|
13
|
+
TrackerEvent.create!(name: "order placed")
|
|
14
|
+
end # the tracker commits here
|
|
15
|
+
Order.create!(total: 0) # raises: the order rolls back,
|
|
16
|
+
end # the tracker event stays
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
ActiveRecord::XA runs them as one transaction using MySQL's XA two-phase commit, so every database commits or none does:
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
ActiveRecord::XA.transaction(PrimaryRecord, TrackerRecord) do
|
|
23
|
+
TrackerEvent.create!(name: "order placed")
|
|
24
|
+
Order.create!(total: 0) # raises: both roll back
|
|
25
|
+
end
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Inside the block you use models exactly as normal. The [example app](example/) shows it side by side with plain nested transactions, including crashes and recovery.
|
|
29
|
+
|
|
30
|
+
## Why use it
|
|
31
|
+
|
|
32
|
+
- **All or nothing across databases.** A failure anywhere, at any point before the commit decision, rolls back every database.
|
|
33
|
+
- **Survives crashes.** The decision is written to a durable log before anything commits. If the process dies halfway, `ActiveRecord::XA.recover!` finishes the job, the same way on every database.
|
|
34
|
+
- **Plain Rails inside.** Validations, callbacks, `requires_new` savepoints, `ActiveRecord::Rollback`, isolation levels and early `return` all behave as they do in a normal transaction.
|
|
35
|
+
- **`after_commit` you can trust.** Callbacks run once the data is durable on every database, so a job enqueued from `after_commit` never sees half a transaction.
|
|
36
|
+
- **Pay only for what you touch.** A database the block never queries never joins. If only one is touched, the commit is a single `XA COMMIT ... ONE PHASE` with no log write.
|
|
37
|
+
- **Small, with nothing to run.** About 650 lines of code on top of Active Record; no coordinator service, no queue, no extra infrastructure.
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
# Gemfile
|
|
43
|
+
gem "activerecord-xa"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
bundle install
|
|
48
|
+
bin/rails generate xa:install # add --database NAME if the log should live elsewhere
|
|
49
|
+
bin/rails db:migrate
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The generator writes `config/initializers/xa.rb` and a migration for the decision log table. List your databases in the initializer:
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
ActiveRecord::XA.configure do |config|
|
|
56
|
+
config.decision_log_class = "ApplicationRecord" # where the decision log lives
|
|
57
|
+
config.participants = %w[ApplicationRecord LedgerRecord]
|
|
58
|
+
config.on_incomplete_commit = ->(gtrid, failures) { Rails.error.report(ActiveRecord::XA::Error.new("XA in doubt: #{ gtrid }")) }
|
|
59
|
+
end
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Then run recovery on a schedule, for example every minute with Solid Queue:
|
|
63
|
+
|
|
64
|
+
```yaml
|
|
65
|
+
# config/recurring.yml
|
|
66
|
+
production:
|
|
67
|
+
xa_recovery:
|
|
68
|
+
command: "ActiveRecord::XA.recover!"
|
|
69
|
+
schedule: every minute
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
or from cron with `bin/rails xa:recover`.
|
|
73
|
+
|
|
74
|
+
## Examples
|
|
75
|
+
|
|
76
|
+
### Moving money between two databases
|
|
77
|
+
|
|
78
|
+
```ruby
|
|
79
|
+
class Transfer
|
|
80
|
+
def self.call(from:, to:, amount:)
|
|
81
|
+
ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
82
|
+
from.lock!.decrement!(:balance, amount)
|
|
83
|
+
to.lock!.increment!(:balance, amount)
|
|
84
|
+
LedgerEntry.create!(from_id: from.id, to_id: to.id, amount:)
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
If the ledger insert fails, neither balance changes.
|
|
91
|
+
|
|
92
|
+
### Writing to an analytics or tracking database alongside the main one
|
|
93
|
+
|
|
94
|
+
```ruby
|
|
95
|
+
ActiveRecord::XA.transaction(ApplicationRecord, TrackingRecord) do
|
|
96
|
+
order = Order.create!(order_params)
|
|
97
|
+
TrackingEvent.create!(name: "order.created", subject: order)
|
|
98
|
+
end
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Rolling back on purpose
|
|
102
|
+
|
|
103
|
+
```ruby
|
|
104
|
+
ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
105
|
+
invoice = Invoice.create!(attrs)
|
|
106
|
+
LedgerEntry.create!(invoice:)
|
|
107
|
+
raise ActiveRecord::Rollback if invoice.total.zero? # both roll back, nothing is raised
|
|
108
|
+
end
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Returning a value, or leaving early
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
order = ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
115
|
+
Order.create!(attrs).tap { |o| LedgerEntry.create!(order: o) }
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def place(attrs)
|
|
119
|
+
ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
120
|
+
order = Order.create!(attrs)
|
|
121
|
+
return order if order.free? # commits, as `return` does in a Rails transaction
|
|
122
|
+
LedgerEntry.create!(order:)
|
|
123
|
+
order
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Callbacks
|
|
129
|
+
|
|
130
|
+
```ruby
|
|
131
|
+
class Order < ApplicationRecord
|
|
132
|
+
after_create_commit { FulfilmentJob.perform_later(self) } # runs once both databases have committed
|
|
133
|
+
after_rollback { Rails.logger.info("order #{ id } rolled back") }
|
|
134
|
+
end
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`before_commit` callbacks run while every database is still open, so they may write to either one, and records saved by another database's callbacks get theirs too.
|
|
138
|
+
|
|
139
|
+
### Nested transactions and savepoints
|
|
140
|
+
|
|
141
|
+
```ruby
|
|
142
|
+
ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
143
|
+
order = Order.create!(attrs)
|
|
144
|
+
|
|
145
|
+
Order.transaction(requires_new: true) do # a savepoint inside the XA branch
|
|
146
|
+
Coupon.redeem!(code)
|
|
147
|
+
rescue Coupon::Expired
|
|
148
|
+
raise ActiveRecord::Rollback # undoes only the coupon
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
LedgerEntry.create!(order:)
|
|
152
|
+
end
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Retrying a deadlock
|
|
156
|
+
|
|
157
|
+
A deadlock victim rolls back everywhere and raises `ActiveRecord::Deadlocked`, so the usual retry works:
|
|
158
|
+
|
|
159
|
+
```ruby
|
|
160
|
+
attempts = 0
|
|
161
|
+
begin
|
|
162
|
+
Transfer.call(from:, to:, amount:)
|
|
163
|
+
rescue ActiveRecord::Deadlocked
|
|
164
|
+
retry if (attempts += 1) < 3
|
|
165
|
+
raise
|
|
166
|
+
end
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Handling commit failures
|
|
170
|
+
|
|
171
|
+
```ruby
|
|
172
|
+
begin
|
|
173
|
+
ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) { ... }
|
|
174
|
+
rescue ActiveRecord::XA::PrepareFailed, ActiveRecord::XA::DecisionLogFailed
|
|
175
|
+
# Rolled back everywhere. Safe to retry.
|
|
176
|
+
rescue ActiveRecord::XA::OutcomeUnknown
|
|
177
|
+
# The decision log was unreachable at the critical moment. Nothing was
|
|
178
|
+
# rolled back; recovery will finish the transaction one way or the other.
|
|
179
|
+
# Do not retry blindly: check whether the work landed first.
|
|
180
|
+
end
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Once the commit decision is logged the transaction counts as committed. A database that then fails to apply `XA COMMIT` does not raise: `on_incomplete_commit` is called and recovery applies it.
|
|
184
|
+
|
|
185
|
+
### Checking what recovery did
|
|
186
|
+
|
|
187
|
+
```ruby
|
|
188
|
+
report = ActiveRecord::XA.recover!
|
|
189
|
+
report.committed # => [#<ActiveRecord::XA::Xid ...>] branches committed from the log
|
|
190
|
+
report.rolled_back # => branches with no decision, rolled back (presumed abort)
|
|
191
|
+
report.skipped # => branches younger than the grace period
|
|
192
|
+
report.errors # => [[subject, exception], ...]
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Performance
|
|
196
|
+
|
|
197
|
+
Two-phase commit costs extra round trips and extra durable writes. A transaction that writes one row to each of two databases:
|
|
198
|
+
|
|
199
|
+
| | Statements | Durable flushes |
|
|
200
|
+
|---|---:|---:|
|
|
201
|
+
| Nested plain transactions | 6 | 2 |
|
|
202
|
+
| ActiveRecord::XA, one database touched | 4 | 1 |
|
|
203
|
+
| ActiveRecord::XA, two databases | 12 | 6 |
|
|
204
|
+
|
|
205
|
+
Measured with `bundle exec rake bench` (2,000 transactions each, one thread, Ruby 4.0.10, Rails 8.1.4, MySQL 9.7 on the same Apple M2 laptop, `innodb_flush_log_at_trx_commit=1`, `sync_binlog=1`):
|
|
206
|
+
|
|
207
|
+
| Scenario | Mean | p50 | p99 | Transactions/s |
|
|
208
|
+
|---|---:|---:|---:|---:|
|
|
209
|
+
| One database, plain transaction | 0.18 ms | 0.16 ms | 0.47 ms | 5,416 |
|
|
210
|
+
| Two databases, nested plain transactions (not atomic) | 0.35 ms | 0.33 ms | 0.74 ms | 2,838 |
|
|
211
|
+
| ActiveRecord::XA, one database touched | 0.23 ms | 0.21 ms | 0.69 ms | 4,347 |
|
|
212
|
+
| ActiveRecord::XA, two databases | 0.87 ms | 0.82 ms | 1.53 ms | 1,149 |
|
|
213
|
+
|
|
214
|
+
In short: atomicity across two databases costs about half a millisecond per transaction here, and a transaction that only touches one database costs almost nothing extra. On Linux servers, where each flush reaches stable storage, the gap grows with your storage's fsync latency, since ActiveRecord::XA does three times as many. Run the benchmark on your own hardware before relying on these numbers.
|
|
215
|
+
|
|
216
|
+
## How it works
|
|
217
|
+
|
|
218
|
+
1. A normal Rails transaction is opened on each database, but the adapter issues `XA START` instead of `BEGIN`, lazily, when the database is first queried.
|
|
219
|
+
2. Your block runs.
|
|
220
|
+
3. While all the transactions are still open, ActiveRecord::XA runs `before_commit` callbacks, then `XA END` and `XA PREPARE` on every database. Each database has now promised it can commit.
|
|
221
|
+
4. A commit decision is written to the decision log on a separate connection. This is the point of no return.
|
|
222
|
+
5. `XA COMMIT` runs on every database, then the decision is deleted.
|
|
223
|
+
6. `after_commit` callbacks run.
|
|
224
|
+
|
|
225
|
+
Recovery resolves anything a crash leaves prepared: a branch whose transaction has a logged decision is committed, one without is rolled back. Before rolling back, recovery writes an abort marker, so a coordinator that turns out to be alive cannot commit afterwards. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) has the details.
|
|
226
|
+
|
|
227
|
+
## What it does not do
|
|
228
|
+
|
|
229
|
+
- **No isolation across databases.** Between the first and last `XA COMMIT` (normally microseconds), a reader can see one database's new data without the other's.
|
|
230
|
+
- **Locks wait for recovery.** A prepared branch holds its row locks until it is resolved. If a database becomes unreachable after `PREPARE`, those rows stay locked until recovery runs, so run it often.
|
|
231
|
+
- **No DDL inside the block.** MySQL does not allow implicit commits in an XA transaction.
|
|
232
|
+
- **ActiveRecord::XA must open the outermost transaction** on every participant; it raises `TransactionAlreadyOpen` otherwise. That also means transactional tests cannot wrap ActiveRecord::XA code: use truncation for those tests.
|
|
233
|
+
|
|
234
|
+
## Requirements
|
|
235
|
+
|
|
236
|
+
- MySQL 8.0.30 or later with InnoDB, row-based or mixed binary logging, and no replication filters on the tables involved.
|
|
237
|
+
- Rails 8.1 with `mysql2` (Trilogy is hooked the same way but untested).
|
|
238
|
+
- Ruby 4.0 or later.
|
|
239
|
+
- The recovery user needs the `XA_RECOVER_ADMIN` privilege. Check that your managed host allows external XA.
|
|
240
|
+
- The decision log takes a second connection from its pool for a moment at each two-database commit. Size that pool for it.
|
|
241
|
+
|
|
242
|
+
## Documentation
|
|
243
|
+
|
|
244
|
+
- [Architecture](docs/ARCHITECTURE.md): the commit protocol, recovery, clocks and failure handling
|
|
245
|
+
- [Install & setup](docs/INSTALL.md): setup in an app, and working on the gem
|
|
246
|
+
- [Usage](docs/USAGE.md): configuration, errors and the recovery report
|
|
247
|
+
- [Changelog](CHANGELOG.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md)
|
|
248
|
+
|
|
249
|
+
## Development
|
|
250
|
+
|
|
251
|
+
```sh
|
|
252
|
+
bin/setup # bundle install, create xa_primary / xa_tracker and the xa user
|
|
253
|
+
bundle exec rake # tests, against a real MySQL server
|
|
254
|
+
bundle exec rubocop
|
|
255
|
+
bundle exec rake bench # the benchmark above
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Point the tests at another server with `MYSQL_HOST`, `MYSQL_TCP_PORT`, `MYSQL_USER` and `MYSQL_PASSWORD`. Set `SQL_LOG=1` to see the XA statements. The tests drop tables and roll back every prepared XA branch they can see, so never run them against a server with data you care about.
|
|
259
|
+
|
|
260
|
+
## License
|
|
261
|
+
|
|
262
|
+
[MIT](LICENSE), © 2026 Vlad Radulescu, Studio51 Solutions.
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
> How ActiveRecord::XA is put together, and why.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
Rails runs one transaction per database connection. Nesting `transaction` blocks for two databases gives two independent transactions: the inner one commits when its block exits, so a failure afterwards leaves one database changed and the other not.
|
|
8
|
+
|
|
9
|
+
ActiveRecord::XA turns those transactions into branches of one global transaction using MySQL's XA, an implementation of two-phase commit. Every branch first promises it can commit (`XA PREPARE`). Only when all have promised is the decision to commit written down, and only then is each branch committed. A crash at any point leaves enough behind for a recovery run to finish the job the same way on every database.
|
|
10
|
+
|
|
11
|
+
## Structure
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
lib/
|
|
15
|
+
activerecord-xa.rb lets Bundler require the gem by its name
|
|
16
|
+
active_record/xa.rb entrypoint: ActiveRecord::XA.transaction, .recover!, .configure, load hooks
|
|
17
|
+
active_record/xa/configuration.rb settings
|
|
18
|
+
active_record/xa/coordinator.rb runs one global transaction: enlist, prepare, decide, commit
|
|
19
|
+
active_record/xa/branch.rb one database's XA state machine
|
|
20
|
+
active_record/xa/xid.rb XA transaction identifiers
|
|
21
|
+
active_record/xa/decision_log.rb the durable commit / abort decisions
|
|
22
|
+
active_record/xa/recovery.rb resolves prepared branches left behind
|
|
23
|
+
active_record/xa/adapter_extension.rb reroutes BEGIN / COMMIT / ROLLBACK on enlisted connections
|
|
24
|
+
active_record/xa/transaction_extension.rb lets the coordinator time Rails' transactional callbacks
|
|
25
|
+
active_record/xa/railtie.rb the xa:recover rake task
|
|
26
|
+
generators/xa/install/ initializer and migration generator
|
|
27
|
+
test/ Minitest, against a real MySQL server
|
|
28
|
+
benchmark/transactions.rb per-transaction cost
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## The commit protocol
|
|
32
|
+
|
|
33
|
+
1. **Enlist.** The coordinator opens a normal Rails transaction on each participant, outermost first, with the connection enlisted. The adapter extension turns Rails' `BEGIN` into `XA START`. Rails begins transactions lazily, so a database the block never queries never starts a branch.
|
|
34
|
+
2. **Run the block.** Models are used as normal. Savepoints work inside an XA branch.
|
|
35
|
+
3. **before_commit.** Still inside every transaction, the coordinator runs `before_commit` callbacks, innermost database first, as nested Rails transactions would. A callback may write to any database; a branch that gains records after its turn gets another pass.
|
|
36
|
+
4. **Prepare.** `XA END` and `XA PREPARE` on every started branch. If only one branch started, it commits with `XA COMMIT ... ONE PHASE` instead and the protocol stops here.
|
|
37
|
+
5. **Decide.** The commit decision is inserted into the decision log on a separate connection. From the moment that insert is sent, every branch is marked in doubt: nothing in this process will roll it back.
|
|
38
|
+
6. **Commit.** `XA COMMIT` on every branch, then the decision row is deleted.
|
|
39
|
+
7. **Callbacks.** The Rails blocks exit (their `COMMIT` is a no-op), every connection is de-enlisted, and only then do `after_commit` callbacks run, innermost database first.
|
|
40
|
+
|
|
41
|
+
Any failure before step 5 rolls back every branch. A failure after it is reported (`on_incomplete_commit`), not raised, because the transaction is committed and a caller retrying would duplicate the work. A branch that could not be committed stays prepared, its connection is closed so the server detaches it, and recovery commits it.
|
|
42
|
+
|
|
43
|
+
## The decision log
|
|
44
|
+
|
|
45
|
+
One row per global transaction, keyed by its gtrid, with an outcome of `commit` or `abort`. The primary key is what keeps every party consistent: whoever writes a decision first wins, and the others find it and follow.
|
|
46
|
+
|
|
47
|
+
- The coordinator writes `commit` after every branch has prepared.
|
|
48
|
+
- Recovery writes `abort` before rolling back a prepared branch that has no decision (presumed abort).
|
|
49
|
+
- A coordinator whose commit insert fails cannot tell whether the row was written, so it asks for `abort` itself. If the primary key refuses, the commit row is there and it commits; otherwise it rolls back and raises `DecisionLogFailed`. If the log cannot be reached at all, it raises `OutcomeUnknown` and leaves the branches prepared for recovery.
|
|
50
|
+
- If no connection to the log could even be checked out, the insert was never sent, so the coordinator rolls back straight away.
|
|
51
|
+
|
|
52
|
+
The log is written on a connection checked out separately from its pool, so it is never part of the XA transaction, even when the table lives in a participant's database. That connection is the second one each two-database commit takes from the log's pool, for a moment. Size the pool for it, or give the log a pool of its own (an abstract class with its own `connects_to` entry pointing at the same database). With an exhausted pool the transaction rolls back with `DecisionLogFailed`; nothing is left half done.
|
|
53
|
+
|
|
54
|
+
## Recovery
|
|
55
|
+
|
|
56
|
+
`ActiveRecord::XA.recover!` lists prepared branches with `XA RECOVER` on each participant and resolves those older than the grace period:
|
|
57
|
+
|
|
58
|
+
- a logged `commit`: `XA COMMIT`
|
|
59
|
+
- no decision: write `abort`, then `XA ROLLBACK`
|
|
60
|
+
|
|
61
|
+
Each gtrid is settled once per run, so every branch of a transaction gets the same answer.
|
|
62
|
+
|
|
63
|
+
`XA RECOVER` is server-wide: participants that share a server see each other's branches, and recovery de-duplicates them. It also sees branches of any other application using the server. Every gtrid carries a namespace derived from the name of the database the decision log lives in, and recovery only touches its own. Two installations that share a server and keep their logs in databases of the same name need a `config.namespace` each.
|
|
64
|
+
|
|
65
|
+
A database that is down, or whose user lacks `XA_RECOVER_ADMIN`, is reported in `report.errors` and does not hold up the others.
|
|
66
|
+
|
|
67
|
+
Recovery then prunes finished decisions:
|
|
68
|
+
|
|
69
|
+
- A `commit` decision is deleted once no branch of it is still prepared and the row is older than the grace period, measured on the log database's own clock.
|
|
70
|
+
- An `abort` marker is kept for `abort_retention` (a day by default), so that a stalled coordinator that wakes up still finds its commit refused.
|
|
71
|
+
- A decision is only pruned by a run that was given every database the transaction used. Recovering a subset, or one shard at a time, is safe; decisions involving the other databases stay until a run covers them.
|
|
72
|
+
|
|
73
|
+
## Clocks, the grace period and long transactions
|
|
74
|
+
|
|
75
|
+
The grace period is measured from when a transaction started. That time is part of its XID and comes from the clock of the app server that began it; recovery compares it with the clock of the host it runs on. Keep those clocks in step (NTP is plenty) and the grace period well above any drift between them.
|
|
76
|
+
|
|
77
|
+
Neither clock drift nor a slow transaction can split a transaction across databases, because the decision log has the last word. What they can do is get a healthy transaction aborted: if recovery looks at a transaction older than the grace period in the few milliseconds between its branches preparing and its decision being written, it rolls it back and the coordinator raises `DecisionLogFailed`. Set `recovery_grace_period` above your longest transaction if you would rather that never happened; the cost is that branches orphaned by a crash hold their locks for that long.
|
|
78
|
+
|
|
79
|
+
## Interrupts and killed threads
|
|
80
|
+
|
|
81
|
+
Ruby can raise into a thread at any point (a request timeout, an interrupt) or kill it. Before the decision is sent, that rolls everything back, as in Rails. After it, nothing is rolled back: branches that have not committed yet stay prepared for recovery, and `after_commit` callbacks still run, because the data is committed. When the outcome is genuinely unknown, neither `after_commit` nor `after_rollback` runs, as in Rails when a `COMMIT`'s connection is lost.
|
|
82
|
+
|
|
83
|
+
## Key decisions
|
|
84
|
+
|
|
85
|
+
- **Presumed abort.** Only commit decisions need to be durable before acting; anything undecided is rolled back. This keeps the common path to one log insert and one delete per transaction.
|
|
86
|
+
- **The log arbitrates, not the clock.** The grace period only avoids disturbing transactions that are still running. Correctness comes from the primary key on the decision log.
|
|
87
|
+
- **Rails stays in charge of the block.** ActiveRecord::XA reroutes three adapter methods and times four transaction hooks; everything else inside the block is ordinary Active Record. The price is coupling to Active Record internals (`internal_execute`, the transaction stack), so each Rails minor version is tested before the gemspec allows it.
|
|
88
|
+
- **Lazy enlistment.** A database joins only when queried, which makes ActiveRecord::XA nearly free when a block touches one database. With lazy transactions switched off on a connection (calling `raw_connection` does that for good), its branch starts when the transaction opens and always takes part in the two-phase commit.
|
|
89
|
+
- **Separate branches on a shared server.** Two databases on the same MySQL server still get two branches. MySQL treats them as unrelated transactions: neither sees the other's uncommitted changes, and if both touch the same row the second waits for the first until `innodb_lock_wait_timeout`.
|
data/docs/INSTALL.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Install & setup
|
|
2
|
+
|
|
3
|
+
## Requirements
|
|
4
|
+
|
|
5
|
+
- Ruby 4.0 or later, Rails 8.1.
|
|
6
|
+
- MySQL 8.0.30 or later with InnoDB. Earlier versions can leave XA state and the binary log inconsistent after a crash.
|
|
7
|
+
- Row-based or mixed binary logging, and no replication filters on the tables ActiveRecord::XA writes.
|
|
8
|
+
- The database user that runs recovery needs `XA_RECOVER_ADMIN`. Some managed hosts restrict external XA; check yours.
|
|
9
|
+
|
|
10
|
+
## In a Rails application
|
|
11
|
+
|
|
12
|
+
```ruby
|
|
13
|
+
# Gemfile
|
|
14
|
+
gem "activerecord-xa"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
bundle install
|
|
19
|
+
bin/rails generate xa:install
|
|
20
|
+
bin/rails db:migrate
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The generator writes:
|
|
24
|
+
|
|
25
|
+
- `config/initializers/xa.rb`, where you name the decision log's class and the participating classes;
|
|
26
|
+
- a migration that creates the `xa_decisions` table. Pass `--database NAME` to put it in another database's migrations path, if the log should live there.
|
|
27
|
+
|
|
28
|
+
A typical multi-database setup:
|
|
29
|
+
|
|
30
|
+
```yaml
|
|
31
|
+
# config/database.yml
|
|
32
|
+
production:
|
|
33
|
+
primary:
|
|
34
|
+
adapter: mysql2
|
|
35
|
+
database: shop
|
|
36
|
+
ledger:
|
|
37
|
+
adapter: mysql2
|
|
38
|
+
database: ledger
|
|
39
|
+
migrations_paths: db/ledger_migrate
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```ruby
|
|
43
|
+
class ApplicationRecord < ActiveRecord::Base
|
|
44
|
+
primary_abstract_class
|
|
45
|
+
connects_to database: { writing: :primary }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
class LedgerRecord < ActiveRecord::Base
|
|
49
|
+
self.abstract_class = true
|
|
50
|
+
connects_to database: { writing: :ledger }
|
|
51
|
+
end
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
# config/initializers/xa.rb
|
|
56
|
+
ActiveRecord::XA.configure do |config|
|
|
57
|
+
config.decision_log_class = "ApplicationRecord"
|
|
58
|
+
config.participants = %w[ApplicationRecord LedgerRecord]
|
|
59
|
+
config.logger = Rails.logger
|
|
60
|
+
end
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Grant the recovery privilege once per server:
|
|
64
|
+
|
|
65
|
+
```sql
|
|
66
|
+
GRANT XA_RECOVER_ADMIN ON *.* TO 'app'@'%';
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Schedule recovery, every minute is a good default: `bin/rails xa:recover` from cron, or a Solid Queue recurring task with `command: "ActiveRecord::XA.recover!"`.
|
|
70
|
+
|
|
71
|
+
### Testing an application that uses ActiveRecord::XA
|
|
72
|
+
|
|
73
|
+
ActiveRecord::XA must open the outermost transaction on every participant, so code that calls it cannot run inside Rails' transactional tests. Turn them off for those tests and clean up by truncation:
|
|
74
|
+
|
|
75
|
+
```ruby
|
|
76
|
+
class TransferTest < ActiveSupport::TestCase
|
|
77
|
+
self.use_transactional_tests = false
|
|
78
|
+
|
|
79
|
+
teardown { [ Account, LedgerEntry ].each(&:delete_all) }
|
|
80
|
+
end
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Working on the gem
|
|
84
|
+
|
|
85
|
+
The tests run against a real MySQL server with two databases, `xa_primary` and `xa_tracker`, and a user `xa` (password `xa`) with `XA_RECOVER_ADMIN`.
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
git clone https://github.com/studio51/activerecord-xa.git && cd activerecord-xa
|
|
89
|
+
bin/setup # bundle install, then create the databases and the user as root
|
|
90
|
+
bundle exec rake # tests
|
|
91
|
+
bundle exec rubocop # lint
|
|
92
|
+
bundle exec rake bench # benchmark
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`bin/setup` connects as `MYSQL_ROOT_USER` (default `root`, password `MYSQL_ROOT_PASSWORD`). The tests and benchmark read `MYSQL_HOST`, `MYSQL_TCP_PORT`, `MYSQL_USER` and `MYSQL_PASSWORD`.
|
|
96
|
+
|
|
97
|
+
The tests drop tables and roll back every prepared XA branch they can see. Use a throwaway server, for example:
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
docker run -d --name xa-mysql -p 3307:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:8.4
|
|
101
|
+
MYSQL_HOST=127.0.0.1 MYSQL_TCP_PORT=3307 bin/setup
|
|
102
|
+
MYSQL_HOST=127.0.0.1 MYSQL_TCP_PORT=3307 bundle exec rake
|
|
103
|
+
```
|
data/docs/USAGE.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Usage
|
|
2
|
+
|
|
3
|
+
## API
|
|
4
|
+
|
|
5
|
+
### `ActiveRecord::XA.transaction(*record_classes) { ... }`
|
|
6
|
+
|
|
7
|
+
Runs the block as one transaction across every database the classes connect to. Pass one Active Record class per database (usually the abstract base classes); classes on the same database count once, and at least two databases are required.
|
|
8
|
+
|
|
9
|
+
Returns the block's value, or `nil` when the block raises `ActiveRecord::Rollback`. Exceptions from the block roll everything back and are re-raised unchanged, so `ActiveRecord::RecordInvalid`, `ActiveRecord::Deadlocked` and friends reach you as usual.
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
result = ActiveRecord::XA.transaction(ApplicationRecord, LedgerRecord) do
|
|
13
|
+
account.update!(balance: account.balance - 10)
|
|
14
|
+
LedgerEntry.create!(account:, amount: -10)
|
|
15
|
+
end
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
It must open the outermost transaction on every participant. Calling it inside another transaction on one of them raises `ActiveRecord::XA::TransactionAlreadyOpen`.
|
|
19
|
+
|
|
20
|
+
### `ActiveRecord::XA.recover!(*record_classes)`
|
|
21
|
+
|
|
22
|
+
Resolves prepared branches left by a crash or a failed commit, and prunes finished decisions. With no arguments it uses `config.participants`. Returns an `ActiveRecord::XA::Recovery::Report`:
|
|
23
|
+
|
|
24
|
+
| Field | Contents |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `committed` | `Xid`s committed because the log says commit |
|
|
27
|
+
| `rolled_back` | `Xid`s rolled back because no decision was logged |
|
|
28
|
+
| `skipped` | `Xid`s younger than the grace period, left alone |
|
|
29
|
+
| `pruned` | gtrids whose decisions were deleted |
|
|
30
|
+
| `errors` | `[subject, exception]` pairs; the subject is an `Xid`, a database name, or `:prune` |
|
|
31
|
+
|
|
32
|
+
Run it regularly: `bin/rails xa:recover` prints a one-line summary and any errors.
|
|
33
|
+
|
|
34
|
+
### `ActiveRecord::XA.configure { |config| ... }`
|
|
35
|
+
|
|
36
|
+
| Setting | Default | Meaning |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| `decision_log_class` | none, required | Class (or class name) whose database holds the decision log |
|
|
39
|
+
| `participants` | `[]` | Classes (or names) covering every participating database, used by `recover!` with no arguments |
|
|
40
|
+
| `recovery_grace_period` | `60` | Seconds a transaction must have been running before recovery touches it |
|
|
41
|
+
| `abort_retention` | `86400` | Seconds recovery keeps an abort marker, so a stalled coordinator cannot commit late |
|
|
42
|
+
| `namespace` | the log database's name | What the XID namespace is derived from; set it when two installations share a server and their logs live in databases of the same name |
|
|
43
|
+
| `on_incomplete_commit` | `nil` | Called as `->(gtrid, failures)` when a committed transaction could not apply `XA COMMIT` on some database; `failures` is `[[branch, exception], ...]`. Exceptions from it are logged, not raised |
|
|
44
|
+
| `logger` | `Logger.new($stderr)` | Where ActiveRecord::XA reports problems; `nil` silences it |
|
|
45
|
+
|
|
46
|
+
### `ActiveRecord::XA::DecisionLog.create_table_sql`
|
|
47
|
+
|
|
48
|
+
The DDL for the decision log table, for a hand-written migration:
|
|
49
|
+
|
|
50
|
+
```ruby
|
|
51
|
+
def up
|
|
52
|
+
execute ActiveRecord::XA::DecisionLog.create_table_sql
|
|
53
|
+
end
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Errors
|
|
57
|
+
|
|
58
|
+
Every error inherits from `ActiveRecord::XA::Error`.
|
|
59
|
+
|
|
60
|
+
| Error | When | State afterwards |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `PrepareFailed` | A database failed `XA PREPARE`, or a one-phase commit failed | Rolled back everywhere |
|
|
63
|
+
| `DecisionLogFailed` | The commit decision could not be written, or recovery had already aborted the transaction | Rolled back everywhere |
|
|
64
|
+
| `OutcomeUnknown` | The decision may or may not have been written and the log could not be asked | Nothing rolled back; recovery finishes it either way |
|
|
65
|
+
| `TransactionAlreadyOpen` | A participant already had an open transaction | Nothing started |
|
|
66
|
+
| `ConfigurationError` | No decision log class, or no participants for `recover!` | Nothing started |
|
|
67
|
+
| `UnsupportedOperation` | Something tried to reopen a branch that is being committed | |
|
|
68
|
+
|
|
69
|
+
## Examples
|
|
70
|
+
|
|
71
|
+
### Several classes on the same database
|
|
72
|
+
|
|
73
|
+
Classes that share a connection pool count as one participant, so it is fine to pass model classes rather than abstract ones:
|
|
74
|
+
|
|
75
|
+
```ruby
|
|
76
|
+
ActiveRecord::XA.transaction(Order, Invoice, LedgerEntry) { ... } # Order and Invoice share a database
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Isolation levels
|
|
80
|
+
|
|
81
|
+
`ActiveRecord.default_transaction_isolation_level` applies to every branch. A nested `transaction(isolation:)` behaves as in Rails, which only allows it on the outermost transaction.
|
|
82
|
+
|
|
83
|
+
### Alerting on incomplete commits
|
|
84
|
+
|
|
85
|
+
```ruby
|
|
86
|
+
ActiveRecord::XA.configure do |config|
|
|
87
|
+
config.on_incomplete_commit = lambda do |gtrid, failures|
|
|
88
|
+
Rails.error.report(ActiveRecord::XA::Error.new("XA in doubt: #{ gtrid }"),
|
|
89
|
+
context: { branches: failures.map { |branch, error| [ branch.xid.to_s, error.message ] } })
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Recovery as a job
|
|
95
|
+
|
|
96
|
+
```ruby
|
|
97
|
+
class ActiveRecord::XARecoveryJob < ApplicationJob
|
|
98
|
+
def perform
|
|
99
|
+
report = ActiveRecord::XA.recover!
|
|
100
|
+
report.errors.each { |subject, error| Rails.error.report(error, context: { subject: subject.to_s }) }
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
```
|