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.
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord::XA
4
+
5
+ # Prepended to the MySQL adapters.
6
+ # While a connection is enlisted in an XA transaction, Active Record's own BEGIN, COMMIT and ROLLBACK are rerouted.
7
+ #
8
+ # * BEGIN becomes XA START, issued lazily as Rails materialises the transaction, so a database the block never touches never joins.
9
+ # * COMMIT becomes a no-op: the coordinator commits every branch itself while the Rails transaction blocks are still open.
10
+ # * ROLLBACK becomes XA END and XA ROLLBACK, unless the coordinator has already resolved the branch.
11
+ #
12
+ module AdapterExtension
13
+ attr_accessor :xa_branch # the Branch this connection is enlisted in, or nil
14
+
15
+ # Starts the XA branch instead of a local transaction.
16
+ #
17
+ # @return [void]
18
+ def begin_db_transaction
19
+ return super unless xa_branch
20
+
21
+ xa_branch.start!
22
+ end
23
+
24
+ # Sets the isolation level for the next transaction, then starts the XA branch.
25
+ #
26
+ # @param isolation [Symbol] the isolation level, e.g. :read_committed
27
+ # @return [void]
28
+ def begin_isolated_db_transaction(isolation)
29
+ return super unless xa_branch
30
+
31
+ internal_execute(
32
+ "SET TRANSACTION ISOLATION LEVEL #{ transaction_isolation_levels.fetch(isolation) }",
33
+ "TRANSACTION", allow_retry: false, materialize_transactions: false
34
+ )
35
+
36
+ xa_branch.start!
37
+ end
38
+
39
+ # Does nothing for an enlisted connection whose branch the coordinator resolved.
40
+ # Reaching it otherwise means Rails is committing without the coordinator, a bug in ActiveRecord::XA, so it fails closed.
41
+ #
42
+ # @raise [Error] if the coordinator has not resolved the branch
43
+ # @return [void]
44
+ def commit_db_transaction
45
+ branch = xa_branch
46
+ return super unless branch
47
+ return if branch.resolved?
48
+
49
+ branch.rollback!
50
+
51
+ raise Error, "XA branch #{ branch.xid } reached COMMIT without the coordinator; rolled back"
52
+ end
53
+
54
+ # Rolls the XA branch back, unless the coordinator has already resolved it.
55
+ #
56
+ # @return [void]
57
+ def exec_rollback_db_transaction
58
+ branch = xa_branch
59
+ return super unless branch
60
+ return if branch.resolved?
61
+
62
+ branch.rollback!
63
+ end
64
+
65
+ # Reports that ROLLBACK AND CHAIN is unavailable, since it is not valid inside XA.
66
+ # Rails then restarts with a rollback and a fresh XA START under the same XID, which MySQL allows.
67
+ #
68
+ # @return [Boolean] false while enlisted, the adapter's answer otherwise
69
+ def supports_restart_db_transaction?
70
+ return false if xa_branch
71
+
72
+ super
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord::XA
4
+
5
+ # One database's part in a global transaction, tracking MySQL's XA state.
6
+ #
7
+ # nil -> :active -> :idle -> :prepared -> :committed
8
+ # \________\_________\___-> :rolled_back
9
+ #
10
+ # :in_doubt means this process could not finish the branch and has left it to recovery.
11
+ # Either its commit decision may be in the log without XA COMMIT having been seen to succeed here, or its rollback failed.
12
+ # The log decides what becomes of it, and nothing in this process touches it again.
13
+ #
14
+ class Branch
15
+ attr_reader :connection # the participant's Active Record connection
16
+ attr_reader :xid # the branch's Xid
17
+ attr_reader :state # the XA state, as above
18
+ attr_accessor :ar_transaction # the Rails transaction the branch runs inside
19
+
20
+ # --- States ---
21
+
22
+ # States from which Rails may (re)start the branch.
23
+ #
24
+ STARTABLE = [ nil, :active, :rolled_back ].freeze
25
+
26
+ # States in which the branch is finished as far as this process is concerned.
27
+ #
28
+ RESOLVED = %i[committed rolled_back in_doubt].freeze
29
+
30
+ # Creates a branch that has not started yet.
31
+ #
32
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter] the participant's connection
33
+ # @param xid [Xid] the branch's XID
34
+ # @return [Branch] the new branch
35
+ def initialize(connection, xid)
36
+ @connection = connection
37
+ @xid = xid
38
+ @state = nil
39
+ end
40
+
41
+ # --- Queries ---
42
+
43
+ # Whether XA START has run, i.e. the block touched this database.
44
+ #
45
+ # @return [Boolean] true once the branch has started
46
+ def started?
47
+ !@state.nil?
48
+ end
49
+
50
+ # Whether the branch needs nothing more from Rails' own COMMIT or ROLLBACK.
51
+ #
52
+ # @return [Boolean] true when committed, rolled back or left to recovery
53
+ def resolved?
54
+ RESOLVED.include?(@state)
55
+ end
56
+
57
+ # Whether the branch has been left to recovery.
58
+ #
59
+ # @return [Boolean] true when in doubt
60
+ def in_doubt?
61
+ @state == :in_doubt
62
+ end
63
+
64
+ # --- XA statements ---
65
+
66
+ # Issues XA START.
67
+ # Rails begins the transaction lazily, begins it again after rolling back a requires_new block that came before the first write, and again on a fresh session when the connection drops before the first write.
68
+ # All of that happens while the block runs.
69
+ # Once the coordinator has begun ending the branch, starting it would reopen an XID that is prepared or already resolved.
70
+ #
71
+ # @raise [UnsupportedOperation] if the coordinator has begun ending the branch
72
+ # @return [Symbol] the new state, :active
73
+ def start!
74
+ unless STARTABLE.include?(@state)
75
+ raise UnsupportedOperation, "XA branch #{ xid } is #{ @state } and cannot be started again"
76
+ end
77
+
78
+ execute("XA START #{ xid.to_sql(connection) }")
79
+
80
+ @state = :active
81
+ end
82
+
83
+ # Issues XA END and XA PREPARE: phase one of the commit.
84
+ #
85
+ # @return [Symbol] the new state, :prepared
86
+ def end_and_prepare!
87
+ execute("XA END #{ xid.to_sql(connection) }")
88
+ @state = :idle
89
+ execute("XA PREPARE #{ xid.to_sql(connection) }")
90
+
91
+ @state = :prepared
92
+ end
93
+
94
+ # Issues XA COMMIT on a prepared branch: phase two of the commit.
95
+ #
96
+ # @return [Symbol] the new state, :committed
97
+ def commit!
98
+ execute("XA COMMIT #{ xid.to_sql(connection) }")
99
+
100
+ @state = :committed
101
+ end
102
+
103
+ # Commits a transaction whose only active branch is this one, with no prepare and no log.
104
+ #
105
+ # @return [Symbol] the new state, :committed
106
+ def commit_one_phase!
107
+ execute("XA END #{ xid.to_sql(connection) }")
108
+ @state = :idle
109
+ execute("XA COMMIT #{ xid.to_sql(connection) } ONE PHASE")
110
+
111
+ @state = :committed
112
+ end
113
+
114
+ # Rolls the branch back from whichever state it is in.
115
+ # A branch that never started has nothing to roll back.
116
+ #
117
+ # @raise [Error] if the branch is in doubt, since its commit decision may be logged
118
+ # @return [Symbol, nil] the new state, :rolled_back, or nil if it never started
119
+ def rollback!
120
+ case @state
121
+ when :active
122
+ end_before_rollback
123
+ execute("XA ROLLBACK #{ xid.to_sql(connection) }")
124
+ when :idle, :prepared
125
+ execute("XA ROLLBACK #{ xid.to_sql(connection) }")
126
+ when :in_doubt
127
+ raise Error, "refusing to roll back #{ xid }: its commit decision may be logged"
128
+ end
129
+
130
+ @state = :rolled_back unless @state.nil?
131
+ end
132
+
133
+ # --- Recovery hand-off ---
134
+
135
+ # Leaves the branch to recovery: nothing in this process will commit or roll it back.
136
+ #
137
+ # @return [Symbol] the new state, :in_doubt
138
+ def mark_in_doubt!
139
+ @state = :in_doubt
140
+ end
141
+
142
+ # Takes the branch back after the log settled on abort, so this process can roll it back after all.
143
+ #
144
+ # @return [Symbol, nil] :prepared if the branch was in doubt, nil otherwise
145
+ def release_from_doubt!
146
+ @state = :prepared if in_doubt?
147
+ end
148
+
149
+ private
150
+
151
+ # Issues XA END ahead of a rollback, ignoring a failure.
152
+ # When a statement in the block was the victim of a deadlock, MySQL has already undone the branch and marked it rollback-only.
153
+ # XA END then fails with XA_RBDEADLOCK, but XA ROLLBACK is still needed to close the branch, and its result is the one that counts.
154
+ #
155
+ # @return [void]
156
+ def end_before_rollback
157
+ execute("XA END #{ xid.to_sql(connection) }")
158
+ rescue ActiveRecord::StatementInvalid
159
+ nil
160
+ end
161
+
162
+ # Runs an XA statement without retrying it and without materialising Rails' lazy transactions.
163
+ #
164
+ # @param sql [String] the statement
165
+ # @return [ActiveRecord::Result] the result
166
+ def execute(sql)
167
+ connection.send(:internal_execute, sql, "TRANSACTION",
168
+ allow_retry: false, materialize_transactions: false)
169
+ end
170
+ end
171
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module ActiveRecord::XA
6
+
7
+ # Settings for ActiveRecord::XA, set once at boot through ActiveRecord::XA.configure.
8
+ # Classes may be given as names, so an initializer never has to load models.
9
+ #
10
+ class Configuration
11
+ attr_accessor :decision_log_class # class (or class name) whose database holds the decision log
12
+ attr_accessor :participants # classes (or class names) covering every database that takes part, for recovery
13
+ attr_accessor :recovery_grace_period # seconds a transaction must have been running before recovery touches it
14
+ attr_accessor :abort_retention # seconds recovery keeps an abort marker
15
+ attr_accessor :namespace # overrides the name the XID namespace is derived from
16
+ attr_accessor :on_incomplete_commit # called as ->(gtrid, failures) when a committed branch could not apply XA COMMIT
17
+ attr_accessor :logger # where ActiveRecord::XA reports problems, or nil
18
+
19
+ # Creates a configuration with the defaults.
20
+ # The grace period of a minute leaves a running transaction alone; the abort retention of a day outlasts any coordinator pause.
21
+ #
22
+ # @return [Configuration] the new configuration
23
+ def initialize
24
+ @decision_log_class = nil
25
+ @participants = []
26
+ @recovery_grace_period = 60
27
+ @abort_retention = 24 * 60 * 60
28
+ @namespace = nil
29
+ @on_incomplete_commit = nil
30
+ @logger = Logger.new($stderr, progname: "ActiveRecord::XA")
31
+ end
32
+
33
+ # Resolves the decision log class.
34
+ #
35
+ # @raise [ConfigurationError] if none is set
36
+ # @return [Class] the class
37
+ def resolved_decision_log_class
38
+ resolve(decision_log_class) or raise ConfigurationError, "set ActiveRecord::XA.config.decision_log_class"
39
+ end
40
+
41
+ # Resolves the participants.
42
+ #
43
+ # @return [Array<Class>] the classes
44
+ def resolved_participants
45
+ Array(participants).map { |klass| resolve(klass) }
46
+ end
47
+
48
+ private
49
+
50
+ # Turns a class name into the class, leaving a class as it is.
51
+ #
52
+ # @param klass [Class, String, Symbol, nil] the class or its name
53
+ # @return [Class, nil] the class
54
+ def resolve(klass)
55
+ klass.is_a?(String) || klass.is_a?(Symbol) ? Object.const_get(klass.to_s) : klass
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,374 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord::XA
4
+
5
+ # Runs one global transaction.
6
+ #
7
+ # 1. Opens a normal Rails transaction on each participant, nested, with the connection enlisted so Rails' BEGIN becomes XA START.
8
+ # 2. Runs the block.
9
+ # 3. Inside the innermost Rails transaction, before any of them exits: runs before_commit callbacks, XA PREPAREs every branch, logs the commit decision, then XA COMMITs every branch.
10
+ # 4. Lets the Rails blocks exit. Their COMMITs are no-ops.
11
+ # 5. Runs after_commit callbacks, once the data is durable everywhere and every connection is an ordinary one again.
12
+ #
13
+ # Any failure before the decision is logged rolls back every branch.
14
+ # From the moment the decision may be in the log, nothing here rolls a branch back: what could not be committed is left in doubt for recovery.
15
+ #
16
+ class Coordinator
17
+ attr_reader :gtrid # the global transaction id shared by every branch
18
+
19
+ # Prepares a transaction over the given participants.
20
+ #
21
+ # @param record_classes [Array<Class>] Active Record classes, one or more per participating database
22
+ # @param log [DecisionLog] where the commit decision is written
23
+ # @param config [Configuration] settings for logging and notification
24
+ # @raise [ArgumentError] unless the classes span at least two databases
25
+ # @return [Coordinator] the new coordinator
26
+ def initialize(record_classes, log:, config: ActiveRecord::XA.config)
27
+ @pools = record_classes.map(&:connection_pool).uniq
28
+ @log = log
29
+ @config = config
30
+ @gtrid = Xid.generate_gtrid(log.namespace)
31
+ @branches = []
32
+ @rollback_requested = false
33
+ @outcome = :rolled_back
34
+
35
+ if @pools.size < 2
36
+ raise ArgumentError, "ActiveRecord::XA.transaction needs classes on at least two different databases"
37
+ end
38
+ end
39
+
40
+ # Runs the block inside the global transaction and commits or rolls back every database together.
41
+ #
42
+ # @yield the work to do, using models as normal
43
+ # @return [Object] the block's value, or nil when it raised ActiveRecord::Rollback
44
+ def run(&block)
45
+ result = nil
46
+ nest(@pools.each_with_index.to_a) { result = run_block(&block) }
47
+
48
+ result
49
+ ensure
50
+ release_callbacks
51
+ end
52
+
53
+ private
54
+
55
+ # --- Opening the participants' transactions ---
56
+
57
+ # Opens the participants' transactions one inside the other.
58
+ # Each connection is borrowed only while its transaction is open: with_connection reuses one the caller already holds, and otherwise hands it back to the pool afterwards, as Model.transaction does.
59
+ #
60
+ # @param remaining [Array<Array(ActiveRecord::ConnectionAdapters::ConnectionPool, Integer)>] pools still to open, with their positions
61
+ # @yield the block to run inside the innermost transaction
62
+ # @return [Object] the block's value
63
+ def nest(remaining, &block)
64
+ return block.call if remaining.empty?
65
+
66
+ pool, index = remaining.first
67
+
68
+ pool.with_connection do |connection|
69
+ if connection.transaction_open?
70
+ raise TransactionAlreadyOpen,
71
+ "#{ pool.db_config.name } already has an open transaction; ActiveRecord::XA must open the outermost one"
72
+ end
73
+
74
+ enlist(connection, Xid.new(@gtrid, Xid.bqual(index, pool.db_config.name))) do
75
+ nest(remaining.drop(1), &block)
76
+ end
77
+ end
78
+ end
79
+
80
+ # Enlists a connection in the global transaction and opens its Rails transaction.
81
+ # The default isolation level is applied the way Model.transaction applies it; with that default set, Rails refuses every save inside a transaction opened without it.
82
+ # Before the connection can reach anyone else through the pool it is de-enlisted, and closed if its branch was left for recovery, so the server lets go of it.
83
+ #
84
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter] the participant's connection
85
+ # @param xid [Xid] the branch's XID
86
+ # @yield runs inside the participant's transaction
87
+ # @return [Object] the block's value
88
+ def enlist(connection, xid)
89
+ branch = Branch.new(connection, xid)
90
+ @branches << branch
91
+ connection.xa_branch = branch
92
+ default_isolation = ActiveRecord.default_transaction_isolation_level
93
+
94
+ connection.pool.with_pool_transaction_isolation_level(default_isolation, false) do
95
+ connection.transaction do
96
+ branch.ar_transaction = connection.current_transaction
97
+ branch.ar_transaction.xa_hold_callbacks!
98
+ yield
99
+ # Rails swallows ActiveRecord::Rollback where the innermost transaction ends.
100
+ # Every participant has to roll back, so each level raises it again for the one outside it.
101
+ #
102
+ raise ActiveRecord::Rollback if @rollback_requested
103
+ end
104
+ end
105
+ ensure
106
+ connection.xa_branch = nil
107
+ discard_connection(connection) if branch&.in_doubt?
108
+ end
109
+
110
+ # Runs the block and commits as Rails would.
111
+ # Rails commits when a transaction block exits early via return, break or throw, and rolls back when the block raises or its thread is being killed.
112
+ #
113
+ # @yield the caller's block
114
+ # @return [Object] the block's value
115
+ def run_block
116
+ outcome = :left_early
117
+ result = yield
118
+ outcome = :finished
119
+ finish!
120
+
121
+ result
122
+ rescue Exception => e
123
+ outcome = :raised
124
+ @rollback_requested = e.is_a?(ActiveRecord::Rollback)
125
+
126
+ raise
127
+ ensure
128
+ finish! if outcome == :left_early && Thread.current.status != "aborting"
129
+ end
130
+
131
+ # --- Committing ---
132
+
133
+ # Runs before_commit callbacks, then commits the branches that started, in one phase or two.
134
+ #
135
+ # @return [void]
136
+ def finish!
137
+ run_before_commit_callbacks
138
+ active = @branches.select(&:started?)
139
+
140
+ case active.size
141
+ when 0 then @outcome = :committed
142
+ when 1 then commit_one_phase(active.first)
143
+ else two_phase_commit(active)
144
+ end
145
+ end
146
+
147
+ # Runs before_commit callbacks while every branch is still open, because they may write, possibly to another database.
148
+ # The order is the one nested Rails transactions give: innermost first.
149
+ # A callback can enrol records in a branch that has already had its turn, and Rails would give those a before_commit of their own, so the branch gets another pass.
150
+ # A branch still in the middle of a pass does not, which is what Rails does too and is what keeps this finite.
151
+ #
152
+ # @return [void]
153
+ def run_before_commit_callbacks
154
+ finished = []
155
+
156
+ @branches.reverse_each do |branch|
157
+ before_commit_pass(branch, finished, [ branch ])
158
+ finished << branch
159
+ end
160
+ end
161
+
162
+ # Runs one branch's pass, visiting any finished branch that gained records while it ran.
163
+ #
164
+ # @param branch [Branch] the branch whose pass this is
165
+ # @param finished [Array<Branch>] branches that have had their first pass
166
+ # @param in_progress [Array<Branch>] branches whose pass is running, which are never revisited
167
+ # @return [void]
168
+ def before_commit_pass(branch, finished, in_progress)
169
+ branch.ar_transaction.xa_run_before_commit! do
170
+ (finished - in_progress).each do |other|
171
+ next unless other.ar_transaction.xa_before_commit_pending?
172
+
173
+ before_commit_pass(other, finished, in_progress + [ other ])
174
+ end
175
+ end
176
+ end
177
+
178
+ # Commits the only branch that started, with no prepare and no log.
179
+ #
180
+ # @param branch [Branch] the branch
181
+ # @raise [PrepareFailed] if the commit fails
182
+ # @return [void]
183
+ def commit_one_phase(branch)
184
+ @outcome = :unknown
185
+ branch.commit_one_phase!
186
+
187
+ @outcome = :committed
188
+ rescue => e
189
+ rollback_all([ branch ])
190
+ # If the rollback failed as well, the commit may have gone through after all, and the outcome stays unknown.
191
+ #
192
+ @outcome = :rolled_back if branch.state == :rolled_back
193
+
194
+ raise PrepareFailed, "one-phase commit failed on #{ branch.xid }: #{ e.message }"
195
+ end
196
+
197
+ # Prepares every branch, logs the decision, then commits every branch.
198
+ # Once the decision is durable the transaction is committed, so a failed XA COMMIT is reported rather than raised: the caller retrying would duplicate work.
199
+ #
200
+ # @param active [Array<Branch>] the branches that started
201
+ # @raise [PrepareFailed] if a branch fails to prepare
202
+ # @return [void]
203
+ def two_phase_commit(active)
204
+ begin
205
+ active.each(&:end_and_prepare!)
206
+ rescue => e
207
+ rollback_all(active)
208
+
209
+ raise PrepareFailed, "prepare failed: #{ e.message }"
210
+ end
211
+
212
+ log_commit_decision(active)
213
+
214
+ failures = active.filter_map do |branch|
215
+ branch.commit!
216
+
217
+ nil
218
+ rescue => e
219
+ [ branch, e ]
220
+ end
221
+
222
+ if failures.empty?
223
+ complete_log
224
+ else
225
+ report_incomplete(failures)
226
+ end
227
+ end
228
+
229
+ # --- The decision ---
230
+
231
+ # Logs the commit decision.
232
+ # Once the insert has been sent the decision may be durable, whatever happens to this process next, so the branches stop being ours to roll back first.
233
+ # An exception or a killed thread from here on leaves them prepared for recovery instead of undoing half a committed transaction.
234
+ #
235
+ # @param active [Array<Branch>] the prepared branches
236
+ # @raise [DecisionLogFailed] if the decision did not stand and everything was rolled back
237
+ # @raise [OutcomeUnknown] if the log could not say what was decided
238
+ # @return [void]
239
+ def log_commit_decision(active)
240
+ @outcome = :unknown
241
+ active.each(&:mark_in_doubt!)
242
+ @log.record_commit!(@gtrid, active.map { |branch| branch.connection.pool.db_config.name })
243
+
244
+ @outcome = :committed
245
+ rescue ActiveRecord::ConnectionNotEstablished => e
246
+ # No connection to the log could be had (it is down, or its pool is exhausted), so the insert was never sent and nothing is in doubt.
247
+ #
248
+ abandon_commit(active, e)
249
+ rescue => e
250
+ settle_failed_decision(active, e)
251
+ end
252
+
253
+ # Lets the log settle a failed insert.
254
+ # An insert that was sent and failed proves nothing: the row can be written and its acknowledgement lost, or recovery may have decided first.
255
+ # We ask for "abort", which the primary key refuses if the commit row is there, and go with whichever decision stands.
256
+ #
257
+ # @param active [Array<Branch>] the prepared branches
258
+ # @param error [Exception] why the insert failed
259
+ # @raise [DecisionLogFailed] if the decision is abort
260
+ # @raise [OutcomeUnknown] if the log cannot be asked
261
+ # @return [void]
262
+ def settle_failed_decision(active, error)
263
+ standing = begin
264
+ @log.settle!(@gtrid)
265
+ rescue => e
266
+ raise OutcomeUnknown, "could not log the commit decision for #{ @gtrid } (#{ error.message }) " \
267
+ "or find out whether it was logged (#{ e.message }); recovery will finish the transaction"
268
+ end
269
+
270
+ if standing == :commit
271
+ @outcome = :committed
272
+ else
273
+ abandon_commit(active, error)
274
+ end
275
+ end
276
+
277
+ # Rolls every branch back after the decision failed to stand.
278
+ #
279
+ # @param active [Array<Branch>] the prepared branches
280
+ # @param error [Exception] why the decision failed
281
+ # @raise [DecisionLogFailed] always
282
+ # @return [void]
283
+ def abandon_commit(active, error)
284
+ active.each(&:release_from_doubt!)
285
+ rollback_all(active)
286
+ @outcome = :rolled_back
287
+
288
+ raise DecisionLogFailed, decision_failure_message(error)
289
+ end
290
+
291
+ # Explains why the decision did not stand.
292
+ #
293
+ # @param error [Exception] why the decision failed
294
+ # @return [String] the message
295
+ def decision_failure_message(error)
296
+ if error.is_a?(ActiveRecord::RecordNotUnique)
297
+ "recovery rolled #{ @gtrid } back before its commit decision was logged; " \
298
+ "the transaction ran for longer than recovery_grace_period"
299
+ else
300
+ "could not log commit decision for #{ @gtrid }: #{ error.message }"
301
+ end
302
+ end
303
+
304
+ # --- Cleaning up ---
305
+
306
+ # Rolls the given branches back, leaving any that fail to recovery.
307
+ # With no commit decision in the log, recovery rolls them back (presumed abort).
308
+ # Marking them stops Rails trying again as the blocks unwind, which would only bury the error that brought us here.
309
+ #
310
+ # @param branches [Array<Branch>] the branches
311
+ # @return [void]
312
+ def rollback_all(branches)
313
+ branches.each do |branch|
314
+ branch.rollback!
315
+ rescue => e
316
+ @config.logger&.error("ActiveRecord::XA: could not roll back #{ branch.xid }, leaving it to recovery: #{ e.message }")
317
+ branch.mark_in_doubt!
318
+ end
319
+ end
320
+
321
+ # Deletes the decision once every branch has committed.
322
+ # A failure is harmless: recovery prunes decisions with no prepared branches left.
323
+ #
324
+ # @return [void]
325
+ def complete_log
326
+ @log.complete!(@gtrid)
327
+ rescue => e
328
+ @config.logger&.warn("ActiveRecord::XA: could not clear decision #{ @gtrid }: #{ e.message }")
329
+ end
330
+
331
+ # Reports branches that are committed by decision but failed to apply XA COMMIT.
332
+ # The transaction is committed, so a notifier that fails must not make it look otherwise to the caller.
333
+ #
334
+ # @param failures [Array<Array(Branch, Exception)>] the branches and their errors
335
+ # @return [void]
336
+ def report_incomplete(failures)
337
+ details = failures.map { |b, e| "#{ b.xid }: #{ e.class }: #{ e.message }" }.join("; ")
338
+ @config.logger&.error("ActiveRecord::XA: #{ @gtrid } committed but not yet applied everywhere: #{ details }")
339
+
340
+ @config.on_incomplete_commit&.call(@gtrid, failures)
341
+ rescue => e
342
+ @config.logger&.error("ActiveRecord::XA: on_incomplete_commit raised #{ e.class }: #{ e.message }")
343
+ end
344
+
345
+ # Runs after_commit or after_rollback callbacks, innermost transaction first as Rails would.
346
+ # Which of the two follows how the global transaction ended, not how each Rails block happened to exit; when the outcome is not known, neither runs.
347
+ # By now every participant's transaction has closed, so a callback can use any of the databases, or start another ActiveRecord::XA transaction.
348
+ # One database's callbacks failing does not cost the others theirs; the first error is raised once all have run.
349
+ #
350
+ # @return [void]
351
+ def release_callbacks
352
+ action = { committed: :commit_records, rolled_back: :rollback_records }[@outcome]
353
+ error = nil
354
+
355
+ @branches.reverse_each do |branch|
356
+ branch.ar_transaction&.xa_release_callbacks!(action)
357
+ rescue => e
358
+ error ||= e
359
+ end
360
+
361
+ raise error if error
362
+ end
363
+
364
+ # Closes a connection that may still hold a prepared branch, so the server detaches it.
365
+ #
366
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] the connection
367
+ # @return [void]
368
+ def discard_connection(connection)
369
+ connection.disconnect!
370
+ rescue => e
371
+ @config.logger&.warn("ActiveRecord::XA: error discarding connection: #{ e.message }")
372
+ end
373
+ end
374
+ end