Transaction boundary for persistence operations.
One UnitOfWork is one database transaction (see ADR-0027). Use it as a
context manager. The changes made inside the block commit together when the
block ends, and roll back together when it raises::
with UnitOfWork():
repo = domain.repository_for(Order)
order = repo.get(order_id)
order.confirm()
repo.add(order)
Command handlers and the @use_case decorator wrap their execution in a
UnitOfWork automatically, so explicit usage is typically only needed in
application services or scripts.
A UnitOfWork started while another is active on the same context joins the
outermost one. Every write, read and event goes to the outermost
UnitOfWork, and only that one commits or rolls back. A rollback in a nested
UnitOfWork rolls back the whole transaction. There are no savepoints, and
an inner UnitOfWork cannot commit on its own. If the outermost UnitOfWork
then tries to commit, it rolls back and raises: the exception that failed
the nested UnitOfWork, or TransactionError when the nested one called
rollback() without an exception. To coordinate several aggregates, use
domain events. Events reach the outbox in the same commit,
so they are delivered only when the transaction commits (see ADR-0015).
Within one transaction, a second read of an aggregate returns the instance
already loaded. On commit, the events raised on aggregates saved through
add() are written to the outbox and dispatched to brokers and the event
store. Events raised on an aggregate that was only read are not persisted.
In a domain with command_processing = "sync", a command processed with
domain.process(command, asynchronous=True) inside the block is stored
at once and handled after the block commits, in its own UnitOfWork. The
deferred commands run in the order they were processed, after the sync
event handlers of this commit. When this UnitOfWork commits inside a sync
event handler, its events wait for the dispatch already running, so its
deferred commands run before their handlers. A command that a sync event
handler defers belongs to the handler's own UnitOfWork, so it runs before
the deferred commands of the UnitOfWork that raised the event. A rollback
means they never run.
Source code in src/protean/core/unit_of_work.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 | def __init__(self) -> None:
self.domain = current_domain
self._in_progress = False
self._sessions: dict[str, SessionProtocol] = {}
self._messages_to_dispatch: list[tuple[str, dict[str, Any], str | None]] = []
# One instance per aggregate for the whole transaction, keyed by
# provider and then by aggregate class and id. A read of an aggregate
# already here returns this instance, so its versions and event
# position never have to be reconciled across copies.
self._identity_map: defaultdict[str, dict[tuple[type, Any], Any]] = defaultdict(
dict
)
# The identity-map entries that were saved, by provider, class and id.
self._saved: set[tuple[str, type, Any]] = set()
# Identifies the transaction in progress. A UnitOfWork can be started
# again after it ends, so the object alone does not.
self._transaction: object | None = None
# A UnitOfWork started while another is already active on this context is
# a participant in the outer transaction (see ``start``). ``_nested`` marks
# it; ``_rollback_only`` is set on the outermost UoW when a participant
# rolls back, dooming the whole transaction. ``_rollback_cause`` keeps the
# first exception that failed a participant, so the outermost commit can
# raise it instead of the caller losing it.
self._nested = False
self._rollback_only = False
self._rollback_cause: BaseException | None = None
# Work that must happen only once this transaction's writes are durable
# (see ``run_after_commit``). A rollback discards it.
self._after_commit: list[Callable[[], None]] = []
# Commands processed with ``asynchronous=True`` inside this transaction
# in a sync domain. Each runs once this transaction has committed, in
# its own UnitOfWork. A rollback discards them.
self._deferred_commands: list[Callable[[], None]] = []
# Results of commands processed inside this transaction, by idempotency
# key, with None for a deferred command. Their keys reach the
# idempotency store only on commit, so a repeat of the same key before
# then is caught here instead.
self._pending_idempotency_results: dict[str, Any] = {}
# ``(schema, identifier)`` of each row written by ``save_if_absent``
# that the latest commit dropped, because another writer committed a
# row with the same unique key first. Only sessions that stage such
# rows (in-memory) report drops. Unlike the state above, it outlives
# the commit, so the caller can read it after the block.
self._dropped_rows: set[tuple[str, Any]] = set()
|
start
Begin the transaction and push this UnitOfWork onto the context stack.
Opens no session and no database connection. The session, and on
SQLAlchemy the BEGIN, starts at the first repository access. A
handler method that reaches no repository runs no transaction and holds
no pooled connection (see ADR-0031).
When another UnitOfWork is already active on this context, this one
joins it and is not pushed onto the stack. current_uow stays the
outermost UnitOfWork, and this one's commit and rollback defer
to it.
Source code in src/protean/core/unit_of_work.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352 | def start(self) -> None:
"""Begin the transaction and push this UnitOfWork onto the context stack.
Opens no session and no database connection. The session, and on
SQLAlchemy the ``BEGIN``, starts at the first repository access. A
handler method that reaches no repository runs no transaction and holds
no pooled connection (see ADR-0031).
When another UnitOfWork is already active on this context, this one
joins it and is not pushed onto the stack. ``current_uow`` stays the
outermost UnitOfWork, and this one's ``commit`` and ``rollback`` defer
to it.
"""
# Recompute nesting on every start: a UnitOfWork instance can be reused, so
# a stale ``_nested``/``_rollback_only``/``_rollback_cause`` from a prior
# use must not leak into this one. (A UoW previously used as nested, then
# reused as the outermost, would otherwise keep ``_nested=True`` and no-op
# its commit, silently losing the transaction and leaving itself on the
# context stack.)
self._nested = _uow_stack.top is not None
self._rollback_only = False
self._rollback_cause = None
self._dropped_rows = set()
self._in_progress = True
if self._nested:
return
self._transaction = object()
# Log transaction capability warnings for each configured provider
for provider_name, provider in self.domain.databases.items():
if DatabaseCapabilities.TRANSACTIONS not in provider.capabilities:
if DatabaseCapabilities.SIMULATED_TRANSACTIONS in provider.capabilities:
logger.debug(
"Provider '%s' uses simulated transactions. "
"Commit and rollback hold only within this process; "
"nothing is durable.",
provider_name,
)
else:
logger.warning(
"Provider '%s' does not support transactions. "
"UoW will manage identity map and events "
"but commit/rollback are not atomic.",
provider_name,
)
# Open no session or connection here. ADR-0031 relies on a handler
# method that reaches no repository holding no pooled connection.
self._in_progress = True
_uow_stack.push(self)
|
commit
Commit all changes, persist outbox messages, and dispatch events.
| RAISES |
DESCRIPTION |
InvalidOperationError
|
If the UnitOfWork is not in progress.
|
ExpectedVersionError
|
On optimistic concurrency conflict.
|
TransactionError
|
If the underlying database commit fails, or if a
nested UnitOfWork called rollback() without an exception.
The transaction is rolled back first. Also raised, after the
writes are durable, when a synchronously dispatched event
handler or a deferred command fails.
|
BaseException
|
The exception that failed a nested UnitOfWork, when
one did. The transaction is rolled back first.
|
Source code in src/protean/core/unit_of_work.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414 | def commit(self) -> None:
"""Commit all changes, persist outbox messages, and dispatch events.
Raises:
InvalidOperationError: If the UnitOfWork is not in progress.
ExpectedVersionError: On optimistic concurrency conflict.
TransactionError: If the underlying database commit fails, or if a
nested UnitOfWork called ``rollback()`` without an exception.
The transaction is rolled back first. Also raised, after the
writes are durable, when a synchronously dispatched event
handler or a deferred command fails.
BaseException: The exception that failed a nested UnitOfWork, when
one did. The transaction is rolled back first.
"""
# Raise error if there the Unit Of Work is not active
logger.debug("uow.committing", extra={"uow_id": id(self)})
if not self._in_progress:
raise InvalidOperationError("UnitOfWork is not in progress")
if self._nested:
# A participant in an outer UnitOfWork: the outermost UoW owns the real
# commit, so there is nothing to commit or dispatch here. Reset our own
# state (it is empty, since a nested UoW routes everything to the
# outermost) for symmetry with the non-nested path and safe reuse.
self._reset()
return
if self._rollback_only:
# A nested participant rolled back, dooming the whole transaction. Roll
# back instead of committing; nothing is persisted or dispatched.
# Read the cause first: ``rollback()`` clears it.
cause = self._rollback_cause
self.rollback()
if cause is not None:
raise cause
raise TransactionError(
"The transaction was marked rollback-only because a nested "
"UnitOfWork rolled back, so it was rolled back instead of committed."
)
tracer = self.domain.tracer
with tracer.start_as_current_span(
"protean.uow.commit",
record_exception=False,
set_status_on_exception=False,
) as span:
# Propagate correlation and causation IDs from the message being processed
msg = g.get("message_in_context")
if msg is not None and hasattr(msg, "metadata") and msg.metadata:
domain_meta = getattr(msg.metadata, "domain", None)
if domain_meta is not None:
correlation_id = getattr(domain_meta, "correlation_id", None)
if correlation_id:
span.set_attribute("protean.correlation_id", correlation_id)
causation_id = getattr(domain_meta, "causation_id", None)
if causation_id:
span.set_attribute("protean.causation_id", causation_id)
self._do_commit(span)
|
rollback
Roll back all changes and close sessions.
| RAISES |
DESCRIPTION |
InvalidOperationError
|
If the UnitOfWork is not in progress.
|
Source code in src/protean/core/unit_of_work.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741 | def rollback(self) -> None:
"""Roll back all changes and close sessions.
Raises:
InvalidOperationError: If the UnitOfWork is not in progress.
"""
# Raise error if the Unit Of Work is not active
if not self._in_progress:
raise InvalidOperationError("UnitOfWork is not in progress")
if self._nested:
# A participant cannot roll back only its own work (there are no
# savepoints), so it dooms the whole transaction: mark the outermost
# UoW rollback-only. The real session rollback happens when that
# outermost UoW exits (its commit sees the flag, or an exception
# propagating out of the block drives its rollback directly). Reset our
# own (empty) state for symmetry with the non-nested path.
outermost = _uow_stack.top
if outermost is not None:
outermost._rollback_only = True
self._reset()
return
# Record UoW outcome for the access log wide event
from protean.domain.context import has_domain_context # noqa: PLC0415
if has_domain_context():
g._access_log_uow_outcome = "rolled_back"
# Exit from Unit of Work. Guarded on identity so a double-pop (when the
# relational commit failed after _do_commit already popped this UoW)
# cannot pop a parent UnitOfWork off the stack.
if _uow_stack.top is self:
_uow_stack.pop()
# The transaction ends here, so drop the participant's exception and the
# traceback it holds.
self._rollback_cause = None
self._settle_versions_on_rollback()
try:
for session in self._sessions.values():
session.rollback()
logger.debug("uow.rollback_successful")
except Exception: # a failed rollback still resets the UoW; logged
logger.exception("uow.rollback_failed")
self._reset()
|
get_session
get_session(provider_name: str) -> SessionProtocol
Get session for provider, initializing one if it doesn't exist
Source code in src/protean/core/unit_of_work.py
| def get_session(self, provider_name: str) -> "SessionProtocol":
"""Get session for provider, initializing one if it doesn't exist"""
if provider_name in self._sessions:
return self._sessions[provider_name]
else:
return self._initialize_session(provider_name)
|