Skip to content

Commit 0c9bff3

Browse files
committed
Database.run_in_transaction: add span_events for using Transaction and aborted
1 parent 1102709 commit 0c9bff3

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

google/cloud/spanner_v1/session.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,9 +424,11 @@ def run_in_transaction(self, func, *args, **kw):
424424
observability_options = getattr(self._database, "observability_options", None)
425425
with trace_call(
426426
"CloudSpanner.ReadWriteTransaction", self, observability_options
427-
):
427+
) as span:
428428
while True:
429429
if self._transaction is None:
430+
if span:
431+
span.add_event("Creating Transaction")
430432
txn = self.transaction()
431433
txn.transaction_tag = transaction_tag
432434
txn.exclude_txn_from_change_streams = (
@@ -435,17 +437,38 @@ def run_in_transaction(self, func, *args, **kw):
435437
else:
436438
txn = self._transaction
437439

440+
attempts += 1
441+
442+
span_attributes = {"transaction.id": txn.id, "attempt": attempts}
443+
if span:
444+
span.add_event("Using Transaction", span_attributes)
445+
438446
try:
439-
attempts += 1
440447
return_value = func(txn, *args, **kw)
441448
except Aborted as exc:
442449
del self._transaction
450+
if span:
451+
delay_seconds = _get_retry_delay(exc, attempts)
452+
attributes = dict(delay_seconds=delay_seconds)
453+
attributes.update(span_attributes)
454+
span.add_event("Transaction was aborted, retrying", attributes)
455+
443456
_delay_until_retry(exc, deadline, attempts)
444457
continue
445458
except GoogleAPICallError:
446459
del self._transaction
460+
if span:
461+
span.add_event(
462+
"Transaction.commit failed due to GoogleAPICallError, not retrying",
463+
span_attributes,
464+
)
447465
raise
448466
except Exception:
467+
if span:
468+
span.add_event(
469+
"Invoking Transaction.rollback(), not retrying",
470+
span_attributes,
471+
)
449472
txn.rollback()
450473
raise
451474

@@ -457,9 +480,23 @@ def run_in_transaction(self, func, *args, **kw):
457480
)
458481
except Aborted as exc:
459482
del self._transaction
483+
if span:
484+
delay_seconds = _get_retry_delay(exc, attempts)
485+
attributes = dict(delay_seconds=delay_seconds)
486+
attributes.update(span_attributes)
487+
span.add_event(
488+
"Transaction.commit was aborted, retrying afresh",
489+
attributes,
490+
)
491+
460492
_delay_until_retry(exc, deadline, attempts)
461493
except GoogleAPICallError:
462494
del self._transaction
495+
if span:
496+
span.add_event(
497+
"Transaction.commit failed due to GoogleAPICallError, not retrying",
498+
span_attributes,
499+
)
463500
raise
464501
else:
465502
if self._database.log_commit_stats and txn.commit_stats:

0 commit comments

Comments
 (0)