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
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module ActiveRecord::XA
|
|
7
|
+
|
|
8
|
+
# Durable record of how global transactions were decided, one row per gtrid.
|
|
9
|
+
#
|
|
10
|
+
# * "commit" is written by the coordinator after every branch has prepared and before the first XA COMMIT, and deleted once every branch has committed.
|
|
11
|
+
# * "abort" is written by recovery before it rolls back a prepared branch that has no decision (presumed abort), and by a coordinator that cannot tell whether its commit row was written.
|
|
12
|
+
#
|
|
13
|
+
# The primary key makes the two exclude each other.
|
|
14
|
+
# That is what keeps a slow coordinator and a recovery run from deciding differently: whoever inserts first wins and the other follows.
|
|
15
|
+
#
|
|
16
|
+
# Rows are written on a connection checked out separately from the pool, so they are never part of the XA transaction, even when the table lives in a participant's database.
|
|
17
|
+
#
|
|
18
|
+
class DecisionLog
|
|
19
|
+
TABLE = "xa_decisions".freeze # the log's table name
|
|
20
|
+
|
|
21
|
+
# The DDL for the log's table, for a migration on the decision log's database.
|
|
22
|
+
#
|
|
23
|
+
# @return [String] a CREATE TABLE IF NOT EXISTS statement
|
|
24
|
+
def self.create_table_sql
|
|
25
|
+
<<~SQL
|
|
26
|
+
CREATE TABLE IF NOT EXISTS #{ TABLE } (
|
|
27
|
+
gtrid VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
28
|
+
outcome VARCHAR(8) NOT NULL,
|
|
29
|
+
participants TEXT NOT NULL,
|
|
30
|
+
created_at DATETIME(6) NOT NULL
|
|
31
|
+
) ENGINE=InnoDB
|
|
32
|
+
SQL
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
attr_reader :namespace # eight hex digits that go into every gtrid this log decides
|
|
36
|
+
|
|
37
|
+
# Creates a log on a pool.
|
|
38
|
+
# The namespace tells this log's transactions from those of any other ActiveRecord::XA installation whose branches show up in the same XA RECOVER, such as another application on a shared server or another environment of this one.
|
|
39
|
+
# By default it comes from the name of the database the log lives in, which is the same from every app server.
|
|
40
|
+
#
|
|
41
|
+
# @param pool [ActiveRecord::ConnectionAdapters::ConnectionPool] the pool of the database holding the table
|
|
42
|
+
# @param namespace [String, nil] a name to derive the namespace from instead of the database name
|
|
43
|
+
# @return [DecisionLog] the new log
|
|
44
|
+
def initialize(pool, namespace: nil)
|
|
45
|
+
@pool = pool
|
|
46
|
+
@namespace = Digest::SHA256.hexdigest(namespace || pool.db_config.database.to_s)[0, 8]
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# --- Schema ---
|
|
50
|
+
|
|
51
|
+
# Creates the log's table if it is missing.
|
|
52
|
+
#
|
|
53
|
+
# @return [void]
|
|
54
|
+
def create_table!
|
|
55
|
+
with_connection { |c| c.execute(self.class.create_table_sql) }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# --- Decisions ---
|
|
59
|
+
|
|
60
|
+
# Logs the decision to commit.
|
|
61
|
+
#
|
|
62
|
+
# @param gtrid [String] the transaction's gtrid
|
|
63
|
+
# @param participants [Array<String>] the database config names that hold a branch, so recovery can tell when it has looked at all of them
|
|
64
|
+
# @raise [ActiveRecord::RecordNotUnique] if the gtrid is already decided
|
|
65
|
+
# @return [void]
|
|
66
|
+
def record_commit!(gtrid, participants)
|
|
67
|
+
insert(gtrid, :commit, participants)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Decides "abort" unless a decision is already there.
|
|
71
|
+
#
|
|
72
|
+
# @param gtrid [String] the transaction's gtrid
|
|
73
|
+
# @return [Symbol] the decision that stands, :abort or :commit
|
|
74
|
+
def settle!(gtrid)
|
|
75
|
+
insert(gtrid, :abort, [])
|
|
76
|
+
|
|
77
|
+
:abort
|
|
78
|
+
rescue ActiveRecord::RecordNotUnique
|
|
79
|
+
outcome(gtrid) or raise Error, "the decision for #{ gtrid } was removed while it was being read"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Reads a transaction's decision.
|
|
83
|
+
#
|
|
84
|
+
# @param gtrid [String] the transaction's gtrid
|
|
85
|
+
# @return [Symbol, nil] :commit, :abort, or nil if undecided
|
|
86
|
+
def outcome(gtrid)
|
|
87
|
+
with_connection do |c|
|
|
88
|
+
c.select_value("SELECT outcome FROM #{ TABLE } WHERE gtrid = #{ c.quote(gtrid) }")&.to_sym
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Deletes a transaction's decision, once it is no longer needed.
|
|
93
|
+
#
|
|
94
|
+
# @param gtrid [String] the transaction's gtrid
|
|
95
|
+
# @return [void]
|
|
96
|
+
def complete!(gtrid)
|
|
97
|
+
with_connection { |c| c.delete("DELETE FROM #{ TABLE } WHERE gtrid = #{ c.quote(gtrid) }") }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Lists every gtrid in the log.
|
|
101
|
+
#
|
|
102
|
+
# @return [Array<String>] the gtrids
|
|
103
|
+
def entries
|
|
104
|
+
with_connection { |c| c.select_values("SELECT gtrid FROM #{ TABLE }") }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# --- Pruning ---
|
|
108
|
+
|
|
109
|
+
# Reads the log database's clock, which also stamps the rows.
|
|
110
|
+
# Ages are worked out against it in SQL, so no other clock comes into pruning.
|
|
111
|
+
#
|
|
112
|
+
# @return [String] the current UTC time, with microseconds
|
|
113
|
+
def now
|
|
114
|
+
with_connection { |c| c.select_value("SELECT CAST(UTC_TIMESTAMP(6) AS CHAR)") }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# Lists decisions old enough to prune.
|
|
118
|
+
#
|
|
119
|
+
# @param time [String] the reference time, a value from #now
|
|
120
|
+
# @param commit_age [Numeric] seconds a commit decision must be old
|
|
121
|
+
# @param abort_age [Numeric] seconds an abort marker must be old
|
|
122
|
+
# @return [Array<Array(String, Array<String>)>] [gtrid, participants] pairs
|
|
123
|
+
def expired(time, commit_age:, abort_age:)
|
|
124
|
+
rows = with_connection do |c|
|
|
125
|
+
c.select_rows(<<~SQL)
|
|
126
|
+
SELECT gtrid, participants FROM #{ TABLE }
|
|
127
|
+
WHERE created_at <= CAST(#{ c.quote(time) } AS DATETIME(6)) - INTERVAL
|
|
128
|
+
(CASE outcome WHEN 'commit' THEN #{ microseconds(commit_age) } ELSE #{ microseconds(abort_age) } END) MICROSECOND
|
|
129
|
+
SQL
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
rows.map { |gtrid, participants| [ gtrid, JSON.parse(participants) ] }
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
private
|
|
136
|
+
|
|
137
|
+
# Inserts a decision row, stamped by the database clock.
|
|
138
|
+
#
|
|
139
|
+
# @param gtrid [String] the transaction's gtrid
|
|
140
|
+
# @param outcome [Symbol] :commit or :abort
|
|
141
|
+
# @param participants [Array<String>] the database config names that hold a branch
|
|
142
|
+
# @return [void]
|
|
143
|
+
def insert(gtrid, outcome, participants)
|
|
144
|
+
with_connection do |c|
|
|
145
|
+
c.insert(
|
|
146
|
+
"INSERT INTO #{ TABLE } (gtrid, outcome, participants, created_at) VALUES " \
|
|
147
|
+
"(#{ c.quote(gtrid) }, #{ c.quote(outcome.to_s) }, #{ c.quote(JSON.generate(participants)) }, UTC_TIMESTAMP(6))",
|
|
148
|
+
"ActiveRecord::XA"
|
|
149
|
+
)
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Converts seconds to whole microseconds for an SQL interval.
|
|
154
|
+
#
|
|
155
|
+
# @param seconds [Numeric] the duration
|
|
156
|
+
# @return [Integer] the duration in microseconds
|
|
157
|
+
def microseconds(seconds)
|
|
158
|
+
(seconds * 1_000_000).round
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Checks out a connection of its own, outside any transaction, and reads it uncached so a caller with the query cache on still sees the log as it is now.
|
|
162
|
+
#
|
|
163
|
+
# @yieldparam connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] the connection
|
|
164
|
+
# @return [Object] the block's value
|
|
165
|
+
def with_connection
|
|
166
|
+
connection = @pool.checkout
|
|
167
|
+
connection.uncached { yield connection }
|
|
168
|
+
ensure
|
|
169
|
+
@pool.checkin(connection) if connection
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
end
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord::XA
|
|
4
|
+
|
|
5
|
+
# Base class of every error ActiveRecord::XA raises.
|
|
6
|
+
#
|
|
7
|
+
class Error < StandardError; end
|
|
8
|
+
|
|
9
|
+
# ActiveRecord::XA is not configured, e.g. no decision log class is set.
|
|
10
|
+
#
|
|
11
|
+
class ConfigurationError < Error; end
|
|
12
|
+
|
|
13
|
+
# A participant connection already had an open transaction, so it cannot be enlisted.
|
|
14
|
+
# XA START cannot join an existing local transaction.
|
|
15
|
+
#
|
|
16
|
+
class TransactionAlreadyOpen < Error; end
|
|
17
|
+
|
|
18
|
+
# Phase one failed on some database, or a one-phase commit failed.
|
|
19
|
+
# Everything was rolled back.
|
|
20
|
+
#
|
|
21
|
+
class PrepareFailed < Error; end
|
|
22
|
+
|
|
23
|
+
# The commit decision could not be written, or recovery had already aborted the transaction.
|
|
24
|
+
# Everything was rolled back.
|
|
25
|
+
#
|
|
26
|
+
class DecisionLogFailed < Error; end
|
|
27
|
+
|
|
28
|
+
# The commit decision may or may not have reached the log, and the log could not be asked.
|
|
29
|
+
# Nothing was rolled back: the branches stay prepared and recovery finishes the transaction whichever way the log says.
|
|
30
|
+
#
|
|
31
|
+
class OutcomeUnknown < Error; end
|
|
32
|
+
|
|
33
|
+
# Something tried to use a connection in a way XA does not allow, e.g. reopening a finished branch.
|
|
34
|
+
#
|
|
35
|
+
class UnsupportedOperation < Error; end
|
|
36
|
+
end
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord::XA
|
|
4
|
+
|
|
5
|
+
# Plugs ActiveRecord::XA into a Rails application: adds the xa:recover task.
|
|
6
|
+
# The install generator is found by Rails on its own, under lib/generators.
|
|
7
|
+
#
|
|
8
|
+
class Railtie < Rails::Railtie
|
|
9
|
+
rake_tasks do
|
|
10
|
+
namespace :xa do
|
|
11
|
+
desc "Resolve prepared XA branches left by a crash or a failed commit (uses ActiveRecord::XA.config.participants)"
|
|
12
|
+
task recover: :environment do
|
|
13
|
+
report = ActiveRecord::XA.recover!
|
|
14
|
+
|
|
15
|
+
puts "committed: #{ report.committed.size }, rolled back: #{ report.rolled_back.size }, " \
|
|
16
|
+
"skipped: #{ report.skipped.size }, pruned: #{ report.pruned.size }, errors: #{ report.errors.size }"
|
|
17
|
+
report.errors.each { |subject, error| puts " #{ subject }: #{ error.class }: #{ error.message }" }
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord::XA
|
|
4
|
+
|
|
5
|
+
# Resolves branches left PREPARED by a crash or a failed commit.
|
|
6
|
+
#
|
|
7
|
+
# * "commit" logged: XA COMMIT
|
|
8
|
+
# * no decision: log "abort", then XA ROLLBACK (presumed abort)
|
|
9
|
+
#
|
|
10
|
+
# XIDs younger than the grace period are left alone, so recovery does not disturb a coordinator that is simply mid-commit.
|
|
11
|
+
# That is a courtesy, not what keeps the two from disagreeing: a transaction can outlive the grace period, which is measured from when it started.
|
|
12
|
+
# The abort marker is what makes it safe: it takes the gtrid's place in the log, so a coordinator that is still alive finds it cannot log "commit" and rolls back too.
|
|
13
|
+
#
|
|
14
|
+
# XA RECOVER lists every prepared XID on the server, not just the database the connection points at, so participants sharing a server see each other's branches.
|
|
15
|
+
# XIDs are de-duplicated, and any connection to the right server can resolve a detached branch.
|
|
16
|
+
# It also lists the branches of anyone else using that server, so only XIDs carrying this decision log's namespace are touched.
|
|
17
|
+
#
|
|
18
|
+
# Needs the XA_RECOVER_ADMIN privilege on each database.
|
|
19
|
+
#
|
|
20
|
+
class Recovery
|
|
21
|
+
|
|
22
|
+
# What a recovery run did.
|
|
23
|
+
# Each list holds Xids, except pruned, which holds gtrids, and errors, which holds [subject, exception] pairs.
|
|
24
|
+
# The subject of an error is the Xid that could not be resolved, the name of a database that could not be asked, or :prune.
|
|
25
|
+
#
|
|
26
|
+
Report = Struct.new(:committed, :rolled_back, :skipped, :pruned, :errors) do
|
|
27
|
+
# Creates an empty report.
|
|
28
|
+
#
|
|
29
|
+
# @return [Report] the report
|
|
30
|
+
def initialize = super([], [], [], [], [])
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Prepares a recovery run.
|
|
34
|
+
#
|
|
35
|
+
# @param record_classes [Array<Class>] Active Record classes covering every database that takes part in ActiveRecord::XA transactions
|
|
36
|
+
# @param log [DecisionLog] the decision log
|
|
37
|
+
# @param grace [Numeric] seconds a transaction must have been running before recovery touches it
|
|
38
|
+
# @param abort_retention [Numeric] seconds to keep an abort marker
|
|
39
|
+
# @return [Recovery] the new run
|
|
40
|
+
def initialize(record_classes, log:, grace:, abort_retention: ActiveRecord::XA.config.abort_retention)
|
|
41
|
+
@pools = record_classes.map(&:connection_pool).uniq
|
|
42
|
+
@log = log
|
|
43
|
+
@grace = grace
|
|
44
|
+
@abort_retention = abort_retention
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Resolves every prepared branch old enough to touch, then prunes finished decisions.
|
|
48
|
+
# A database that is down, or whose user lacks XA_RECOVER_ADMIN, is reported and does not keep the others waiting.
|
|
49
|
+
# Without an answer from every database there is no telling which decisions are finished, so nothing is pruned on such a run.
|
|
50
|
+
#
|
|
51
|
+
# @return [Report] what the run did
|
|
52
|
+
def run
|
|
53
|
+
report = Report.new
|
|
54
|
+
started = @log.now
|
|
55
|
+
@outcomes = {}
|
|
56
|
+
handled = {}
|
|
57
|
+
complete = true
|
|
58
|
+
|
|
59
|
+
@pools.each do |pool|
|
|
60
|
+
with_connection(pool) do |connection|
|
|
61
|
+
prepared_xids(connection).each do |xid|
|
|
62
|
+
next if handled[xid.to_s]
|
|
63
|
+
|
|
64
|
+
handled[xid.to_s] = true
|
|
65
|
+
resolve(connection, xid, report)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
rescue => e
|
|
69
|
+
report.errors << [ pool.db_config.name, e ]
|
|
70
|
+
complete = false
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
if complete
|
|
74
|
+
outstanding = (report.skipped + report.errors.map(&:first).grep(Xid)).map(&:gtrid)
|
|
75
|
+
prune_log(started, outstanding.uniq, report)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
report
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
# Commits or rolls back one branch, as the log says.
|
|
84
|
+
#
|
|
85
|
+
# @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] a connection to the branch's server
|
|
86
|
+
# @param xid [Xid] the branch
|
|
87
|
+
# @param report [Report] where the result goes
|
|
88
|
+
# @return [void]
|
|
89
|
+
def resolve(connection, xid, report)
|
|
90
|
+
unless old_enough?(xid.gtrid)
|
|
91
|
+
report.skipped << xid
|
|
92
|
+
|
|
93
|
+
return
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
case outcome_of(xid.gtrid)
|
|
97
|
+
when :commit
|
|
98
|
+
connection.execute("XA COMMIT #{ xid.to_sql(connection) }")
|
|
99
|
+
report.committed << xid
|
|
100
|
+
when :abort
|
|
101
|
+
connection.execute("XA ROLLBACK #{ xid.to_sql(connection) }")
|
|
102
|
+
report.rolled_back << xid
|
|
103
|
+
end
|
|
104
|
+
rescue => e
|
|
105
|
+
report.errors << [ xid, e ]
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Reads a transaction's decision, deciding abort when there is none.
|
|
109
|
+
# It is settled once per run, so every branch of a transaction gets the same answer, and the abort is written down before anything is rolled back.
|
|
110
|
+
#
|
|
111
|
+
# @param gtrid [String] the transaction's gtrid
|
|
112
|
+
# @return [Symbol] :commit or :abort
|
|
113
|
+
def outcome_of(gtrid)
|
|
114
|
+
@outcomes[gtrid] ||= @log.outcome(gtrid) || @log.settle!(gtrid)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# Deletes decisions that are finished and old enough.
|
|
118
|
+
# A commit decision waits the grace period, counted from when its row was written: a row that old was there before this run looked for prepared branches, so any still waiting were just committed above, or are outstanding.
|
|
119
|
+
# An abort marker stays for abort_retention, in case the coordinator it stopped is still alive and about to try its commit.
|
|
120
|
+
# Either way, only a run that was given every database a transaction used has seen all its branches.
|
|
121
|
+
#
|
|
122
|
+
# @param started [String] when this run started, on the log database's clock
|
|
123
|
+
# @param outstanding_gtrids [Array<String>] transactions with a branch still waiting
|
|
124
|
+
# @param report [Report] where the result goes
|
|
125
|
+
# @return [void]
|
|
126
|
+
def prune_log(started, outstanding_gtrids, report)
|
|
127
|
+
covered = @pools.map { |pool| pool.db_config.name }
|
|
128
|
+
|
|
129
|
+
@log.expired(started, commit_age: @grace, abort_age: @abort_retention).each do |gtrid, participants|
|
|
130
|
+
next if outstanding_gtrids.include?(gtrid)
|
|
131
|
+
next unless (participants - covered).empty?
|
|
132
|
+
|
|
133
|
+
@log.complete!(gtrid)
|
|
134
|
+
report.pruned << gtrid
|
|
135
|
+
end
|
|
136
|
+
rescue => e
|
|
137
|
+
report.errors << [ :prune, e ]
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# Lists this installation's prepared branches on a server.
|
|
141
|
+
# The length columns of XA RECOVER count bytes, and the data is not always single-byte.
|
|
142
|
+
#
|
|
143
|
+
# @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] a connection to the server
|
|
144
|
+
# @return [Array<Xid>] the branches
|
|
145
|
+
def prepared_xids(connection)
|
|
146
|
+
rows = connection.uncached { connection.select_rows("XA RECOVER") }
|
|
147
|
+
|
|
148
|
+
rows.filter_map do |format_id, gtrid_length, bqual_length, data|
|
|
149
|
+
next unless Integer(format_id) == Xid::FORMAT_ID
|
|
150
|
+
|
|
151
|
+
gl = Integer(gtrid_length)
|
|
152
|
+
xid = Xid.new(data.byteslice(0, gl), data.byteslice(gl, Integer(bqual_length)))
|
|
153
|
+
|
|
154
|
+
xid if Xid.namespace(xid.gtrid) == @log.namespace
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Whether a transaction has been running for longer than the grace period.
|
|
159
|
+
#
|
|
160
|
+
# @param gtrid [String] the transaction's gtrid
|
|
161
|
+
# @return [Boolean] true if recovery may touch it
|
|
162
|
+
def old_enough?(gtrid)
|
|
163
|
+
Time.now - Xid.created_at(gtrid) >= @grace
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
# Checks out a connection of its own for one database.
|
|
167
|
+
#
|
|
168
|
+
# @param pool [ActiveRecord::ConnectionAdapters::ConnectionPool] the database's pool
|
|
169
|
+
# @yieldparam connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] the connection
|
|
170
|
+
# @return [Object] the block's value
|
|
171
|
+
def with_connection(pool)
|
|
172
|
+
connection = pool.checkout
|
|
173
|
+
yield connection
|
|
174
|
+
ensure
|
|
175
|
+
pool.checkin(connection) if connection
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord::XA
|
|
4
|
+
|
|
5
|
+
# Prepended to Active Record's transaction class.
|
|
6
|
+
# Lets the coordinator decide when a participant's transactional callbacks run, instead of Rails running them as each transaction block exits.
|
|
7
|
+
#
|
|
8
|
+
# before_commit must run while every branch is still open, since the callbacks may write.
|
|
9
|
+
# The coordinator runs it early, in passes, and Rails is stopped from running it a second time.
|
|
10
|
+
#
|
|
11
|
+
# after_commit and after_rollback must wait until every participant's transaction has closed.
|
|
12
|
+
# Until then some connections are still enlisted, with Rails believing a transaction is open that MySQL has already finished.
|
|
13
|
+
#
|
|
14
|
+
module TransactionExtension
|
|
15
|
+
|
|
16
|
+
# --- Rails' hooks, held back while the coordinator is in charge ---
|
|
17
|
+
|
|
18
|
+
# Runs before_commit callbacks, unless the coordinator already ran them.
|
|
19
|
+
#
|
|
20
|
+
# @return [void]
|
|
21
|
+
def before_commit_records
|
|
22
|
+
super unless @xa_runs_before_commit
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Runs after_commit callbacks, unless the coordinator is holding them.
|
|
26
|
+
#
|
|
27
|
+
# @return [void]
|
|
28
|
+
def commit_records
|
|
29
|
+
super unless @xa_holds_callbacks
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Runs after_rollback callbacks, unless the coordinator is holding them.
|
|
33
|
+
#
|
|
34
|
+
# @return [void]
|
|
35
|
+
def rollback_records
|
|
36
|
+
super unless @xa_holds_callbacks
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# --- Coordinator API ---
|
|
40
|
+
|
|
41
|
+
# Holds after_commit and after_rollback until #xa_release_callbacks!.
|
|
42
|
+
#
|
|
43
|
+
# @return [Boolean] true
|
|
44
|
+
def xa_hold_callbacks!
|
|
45
|
+
@xa_holds_callbacks = true
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Runs the held callbacks as the coordinator says the global transaction ended, whatever Rails made of its own block.
|
|
49
|
+
# With nil it runs neither set, as Rails does when it cannot tell whether a COMMIT went through.
|
|
50
|
+
#
|
|
51
|
+
# @param action [Symbol, nil] :commit_records, :rollback_records or nil
|
|
52
|
+
# @return [void]
|
|
53
|
+
def xa_release_callbacks!(action)
|
|
54
|
+
@xa_holds_callbacks = false
|
|
55
|
+
|
|
56
|
+
public_send(action) if action
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Whether anything has been enrolled since the last before_commit pass.
|
|
60
|
+
#
|
|
61
|
+
# @return [Boolean] true if records or callbacks are waiting for a pass
|
|
62
|
+
def xa_before_commit_pending?
|
|
63
|
+
records.to_a.size > @xa_records_done.to_i || @callbacks.to_a.size > @xa_callbacks_done.to_i
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Runs one before_commit pass, for whatever was enrolled since the previous one.
|
|
67
|
+
# Yields once those have run, then counts everything enrolled in the meantime as done.
|
|
68
|
+
# Rails likewise gives no before_commit to records that a transaction's own callbacks add to it.
|
|
69
|
+
#
|
|
70
|
+
# @yield runs while this pass is in progress, so the coordinator can visit other branches
|
|
71
|
+
# @return [void]
|
|
72
|
+
def xa_run_before_commit!
|
|
73
|
+
@xa_runs_before_commit = true
|
|
74
|
+
fresh_records = records.to_a.drop(@xa_records_done.to_i)
|
|
75
|
+
fresh_callbacks = @callbacks.to_a.drop(@xa_callbacks_done.to_i)
|
|
76
|
+
|
|
77
|
+
if @run_commit_callbacks
|
|
78
|
+
xa_before_commit(fresh_records)
|
|
79
|
+
fresh_callbacks.each(&:before_commit)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
yield if block_given?
|
|
83
|
+
@xa_records_done = records.to_a.size
|
|
84
|
+
|
|
85
|
+
@xa_callbacks_done = @callbacks.to_a.size
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
private
|
|
89
|
+
|
|
90
|
+
# Runs before_commit on the given records, picking instances the way Transaction#before_commit_records does.
|
|
91
|
+
#
|
|
92
|
+
# @param records [Array<ActiveRecord::Base>] the records enrolled since the last pass
|
|
93
|
+
# @return [void]
|
|
94
|
+
def xa_before_commit(records)
|
|
95
|
+
if ActiveRecord.before_committed_on_all_records
|
|
96
|
+
last_copy = records.each_with_object({}) { |record, copies| copies[record] = record }
|
|
97
|
+
records.uniq(&:__id__).each { |record| record.before_committed! if record.equal?(last_copy[record]) }
|
|
98
|
+
else
|
|
99
|
+
records.uniq.each(&:before_committed!)
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
|
|
5
|
+
module ActiveRecord::XA
|
|
6
|
+
|
|
7
|
+
# An XA transaction identifier: MySQL names a branch by (gtrid, bqual, formatID).
|
|
8
|
+
# The gtrid is shared by every branch of one global transaction, and the bqual names the branch.
|
|
9
|
+
# The formatID marks the XID as ActiveRecord::XA's in XA RECOVER output.
|
|
10
|
+
# The gtrid also carries the namespace of the decision log that decides it, so recovery can tell its own transactions from another installation's, and its creation time, for the grace period.
|
|
11
|
+
#
|
|
12
|
+
# axa-<namespace>-<start time in ms>-<random>
|
|
13
|
+
#
|
|
14
|
+
class Xid
|
|
15
|
+
|
|
16
|
+
# --- Format ---
|
|
17
|
+
|
|
18
|
+
FORMAT_ID = 0x41584131 # "AXA1", marks ActiveRecord::XA's XIDs in XA RECOVER
|
|
19
|
+
PREFIX = "axa".freeze # first segment of every gtrid
|
|
20
|
+
MAX_PART_BYTES = 64 # MySQL's limit for gtrid and for bqual, in bytes
|
|
21
|
+
|
|
22
|
+
# The shape of a gtrid ActiveRecord::XA generated.
|
|
23
|
+
#
|
|
24
|
+
GTRID = /\A#{ PREFIX }-(?<namespace>\h{8})-(?<millis>\d{1,15})-\h+\z/
|
|
25
|
+
|
|
26
|
+
attr_reader :gtrid # global transaction id, shared by every branch
|
|
27
|
+
attr_reader :bqual # branch qualifier, unique within the gtrid
|
|
28
|
+
|
|
29
|
+
class << self
|
|
30
|
+
|
|
31
|
+
# Generates a gtrid for a new global transaction.
|
|
32
|
+
#
|
|
33
|
+
# @param namespace [String] the decision log's namespace, eight hex digits
|
|
34
|
+
# @return [String] the gtrid, at most 47 bytes
|
|
35
|
+
def generate_gtrid(namespace)
|
|
36
|
+
"#{ PREFIX }-#{ namespace }-#{ (Time.now.to_f * 1000).to_i }-#{ SecureRandom.hex(12) }"
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Builds the qualifier for one branch.
|
|
40
|
+
# The index keeps it unique within its gtrid, and the database name is there for whoever reads XA RECOVER.
|
|
41
|
+
# A long multi-byte name is cut on a byte boundary, so a split trailing character is dropped.
|
|
42
|
+
#
|
|
43
|
+
# @param index [Integer] the participant's position in the transaction
|
|
44
|
+
# @param name [String] the participant's database config name
|
|
45
|
+
# @return [String] the qualifier, at most 64 bytes of valid UTF-8
|
|
46
|
+
def bqual(index, name)
|
|
47
|
+
"#{ index }-#{ name }".byteslice(0, MAX_PART_BYTES).scrub("")
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Reads the namespace out of a gtrid.
|
|
51
|
+
#
|
|
52
|
+
# @param gtrid [String] the gtrid
|
|
53
|
+
# @return [String, nil] the namespace, or nil if ActiveRecord::XA did not make the gtrid
|
|
54
|
+
def namespace(gtrid)
|
|
55
|
+
parse(gtrid)&.[](:namespace)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Reads the start time out of a gtrid.
|
|
59
|
+
#
|
|
60
|
+
# @param gtrid [String] the gtrid
|
|
61
|
+
# @return [Time, nil] when the transaction started, or nil if ActiveRecord::XA did not make the gtrid
|
|
62
|
+
def created_at(gtrid)
|
|
63
|
+
millis = parse(gtrid)&.[](:millis)
|
|
64
|
+
|
|
65
|
+
Time.at(millis.to_i / 1000.0) if millis
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
private
|
|
69
|
+
|
|
70
|
+
# Matches a gtrid against the format ActiveRecord::XA generates.
|
|
71
|
+
#
|
|
72
|
+
# @param gtrid [String] the gtrid
|
|
73
|
+
# @return [MatchData, nil] the match, or nil
|
|
74
|
+
def parse(gtrid)
|
|
75
|
+
GTRID.match(gtrid) if gtrid.valid_encoding?
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Creates an XID.
|
|
80
|
+
#
|
|
81
|
+
# @param gtrid [String] the global transaction id
|
|
82
|
+
# @param bqual [String] the branch qualifier
|
|
83
|
+
# @return [Xid] the new XID
|
|
84
|
+
def initialize(gtrid, bqual)
|
|
85
|
+
@gtrid = gtrid
|
|
86
|
+
@bqual = bqual
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Renders the XID for an XA statement.
|
|
90
|
+
#
|
|
91
|
+
# @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] the connection that quotes the parts
|
|
92
|
+
# @return [String] the quoted gtrid, bqual and formatID, comma separated
|
|
93
|
+
def to_sql(connection)
|
|
94
|
+
"#{ connection.quote(gtrid) },#{ connection.quote(bqual) },#{ FORMAT_ID }"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Renders the XID for logs and error messages.
|
|
98
|
+
#
|
|
99
|
+
# @return [String] gtrid/bqual
|
|
100
|
+
def to_s
|
|
101
|
+
"#{ gtrid }/#{ bqual }"
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|