spakky-data¶
spakky-data는 Repository, Transaction, Aggregate collection 같은 데이터 접근 추상화를 제공합니다.
Repository, Transaction 추상화 — 데이터 접근 계층
spakky-data는 core 레이어의 추상 계약만 제공합니다. 애플리케이션에서 SQLAlchemy로
영속화를 구현하려면 spakky-sqlalchemy를 함께 설치하고, AbstractMappableTable /
AbstractAsyncGenericRepository 또는 AbstractGenericRepository를 사용하세요.
사용자 흐름은 데이터베이스 가이드를 먼저 보는 편이 좋습니다. 이 페이지는 실제 API 표면을 확인하기 위한 레퍼런스입니다.
플러그인 진입점¶
initialize(app)
¶
Initialize the spakky-data plugin.
Registers the common configuration, sync aspect, and aggregate collector. The async aspect follows DataConfig, also consumed by persistence providers.
Source code in core/spakky-data/src/spakky/data/main.py
공통 설정¶
Shared persistence execution-mode configuration.
DataConfig()
¶
Bases: BaseSettings
Control asynchronous transaction support across data and provider plugins.
Read the common data configuration from environment variables.
Source code in core/spakky-data/src/spakky/data/config.py
support_async_mode = True
class-attribute
instance-attribute
¶
Register async transactional aspects and provider Pods in addition to sync ones.
스테레오타입¶
Repository stereotype for data access layer.
This module provides @Repository stereotype for organizing classes that handle data persistence and retrieval.
영속성¶
EntityNotFoundError
¶
EntityAlreadyExistsError
¶
Bases: AbstractSpakkyDomainError
Raised when saving a new aggregate collides with a stored unique key.
Another aggregate already holds the same identifier or another unique key, typically because a concurrent transaction created it first. This is not a version conflict: no stored row of this aggregate was changed. The caller usually reads the existing aggregate instead of retrying the insert.
VersionConflictError
¶
Bases: AbstractSpakkyDomainError
Raised when optimistic locking detects a version conflict during save.
IGenericRepository
¶
Bases: ABC
Synchronous generic repository interface for aggregate persistence.
get(aggregate_id)
abstractmethod
¶
get_or_none(aggregate_id)
abstractmethod
¶
contains(aggregate_id)
abstractmethod
¶
range(aggregate_ids)
abstractmethod
¶
save(aggregate)
abstractmethod
¶
save_all(aggregates)
abstractmethod
¶
Persist multiple aggregates and return the saved instances.
delete(aggregate)
abstractmethod
¶
delete_all(aggregates)
abstractmethod
¶
Delete multiple aggregates and return the deleted instances.
IAsyncGenericRepository
¶
Bases: ABC
Asynchronous generic repository interface for aggregate persistence.
get(aggregate_id)
abstractmethod
async
¶
get_or_none(aggregate_id)
abstractmethod
async
¶
Get an aggregate by ID, or None if not found.
contains(aggregate_id)
abstractmethod
async
¶
range(aggregate_ids)
abstractmethod
async
¶
save(aggregate)
abstractmethod
async
¶
save_all(aggregates)
abstractmethod
async
¶
Persist multiple aggregates and return the saved instances.
delete(aggregate)
abstractmethod
async
¶
delete_all(aggregates)
abstractmethod
async
¶
Delete multiple aggregates and return the deleted instances.
Propagation
¶
Bases: StrEnum
How a transaction scope relates to a transaction already in progress.
PhysicalTransaction(rollback_only=False, finished=False)
dataclass
¶
Shared, mutable state of one physical transaction.
A physical transaction is the unit that is actually opened, committed or rolled back. Every scope that joins it, including scopes running in child tasks or threads that inherited the execution context, refers to the same object, so a failure recorded by any of them is seen by the scope that opened it, and the end of the transaction is seen by all of them.
The object is compared by identity. Resources that belong to one physical
transaction (a session, an aggregate buffer) are bound to it and read its
finished flag, so they all stop being handed out at the same moment.
rollback_only = False
class-attribute
instance-attribute
¶
True once a joined scope exited with an exception; commit is refused.
finished = False
class-attribute
instance-attribute
¶
True once the opening scope committed or rolled back.
Set right after the commit or rollback and before dispose() releases
the resource. A child task or thread that outlives the opening scope still
holds frames of this transaction in its copied context. From then on new
scopes skip it and never join it, and resources bound to it refuse to be
used, so nothing can be written to or collected for a transaction whose
outcome is already decided.
TransactionFrame(transaction, owner)
dataclass
¶
One open transaction scope in the current execution context.
Frames are kept in an immutable tuple stored in a ContextVar. A child
task or thread copies the tuple, so scopes it opens (REQUIRES_NEW)
stay in its own context, while scopes it joins still point at the shared
PhysicalTransaction of the parent. Frames whose transaction has
finished stay in such a copy but are skipped.
AbstractTransaction(autocommit=True)
¶
Bases: IDisposable, ABC
Abstract base for synchronous transaction context managers.
Scopes nest per execution context. Propagation.REQUIRED joins the
transaction in progress, and only the scope that opened the physical
transaction commits, rolls back and disposes it.
Propagation.REQUIRES_NEW always opens a separate physical transaction
through initialize(); implementations must keep the outer one intact
and restore it in dispose().
A child task or thread that copied the execution context inherits the
open scopes. A REQUIRED scope it begins joins the parent's physical
transaction, and a failure there marks that transaction rollback-only for
the parent too. A REQUIRES_NEW scope it begins stays in its own
context, so implementations must keep the per-transaction resource (e.g.
the session) in execution-context-local state, not in state shared by
every task of a request.
A child that begins a scope after the transaction it inherited has
finished does not join it: the scope joins the closest live transaction
below it or opens a new one. A joined scope that is still open when the
opening scope finishes raises TransactionAlreadyFinishedError on exit.
Implementations bind their resource to the physical transaction instead of
looking it up on their own: initialize() binds a new resource to
current_frame.transaction, join() binds the current context to the
resource of the transaction it joined and leave() undoes that. The
resource of the current frame is the one to use. Once its transaction is
finished it must be refused with TransactionAlreadyFinishedError
instead of falling back to a resource below it.
Initialize the transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
autocommit
|
bool
|
Whether to auto-commit on successful exit. |
True
|
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
is_active
property
¶
Whether a live transaction is open in the current context.
is_rollback_only
property
¶
Whether the current physical transaction can only be rolled back.
current_frame
property
¶
The innermost open scope of the current execution context.
Returns:
| Type | Description |
|---|---|
TransactionFrame
|
The frame of that scope. Its |
TransactionFrame
|
opened the physical transaction or joined it. |
Raises:
| Type | Description |
|---|---|
TransactionNotActiveError
|
No scope is open in this context. |
scope(propagation=Propagation.REQUIRED)
¶
Run a block inside a transaction scope with the given propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
propagation
|
Propagation
|
How the scope relates to a transaction in progress. |
REQUIRED
|
Yields:
| Type | Description |
|---|---|
Generator[Self]
|
This transaction. |
Raises:
| Type | Description |
|---|---|
TransactionRollbackOnlyError
|
The opening scope finished normally but a joined scope had failed, so the transaction was rolled back. |
TransactionAlreadyFinishedError
|
The scope joined a transaction that finished before the scope exited. |
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
initialize()
abstractmethod
¶
Open a new physical transaction (e.g. open a session).
Called for the outermost scope and for every REQUIRES_NEW scope,
after its frame was pushed: current_frame.transaction is the new
physical transaction to bind the resource to.
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
join()
¶
Bind the current context to the resource of the joined transaction.
Called when a REQUIRED scope joins a transaction in progress, after
its frame was pushed: current_frame.transaction is the joined
transaction. It is below the innermost frame when the innermost one
has already finished. Implementations that keep no resource per
context leave this as it is.
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
leave()
¶
Undo the binding made by join() when the joined scope exits.
Implementations that keep no resource per context leave this as it is.
dispose()
abstractmethod
¶
commit()
abstractmethod
¶
AbstractAsyncTransaction(autocommit=True)
¶
Bases: IAsyncDisposable, ABC
Abstract base for asynchronous transaction context managers.
Scopes nest per execution context. Propagation.REQUIRED joins the
transaction in progress, and only the scope that opened the physical
transaction commits, rolls back and disposes it.
Propagation.REQUIRES_NEW always opens a separate physical transaction
through initialize(); implementations must keep the outer one intact
and restore it in dispose().
A child task or thread that copied the execution context inherits the
open scopes. A REQUIRED scope it begins joins the parent's physical
transaction, and a failure there marks that transaction rollback-only for
the parent too. A REQUIRES_NEW scope it begins stays in its own
context, so implementations must keep the per-transaction resource (e.g.
the session) in execution-context-local state, not in state shared by
every task of a request.
A child that begins a scope after the transaction it inherited has
finished does not join it: the scope joins the closest live transaction
below it or opens a new one. A joined scope that is still open when the
opening scope finishes raises TransactionAlreadyFinishedError on exit.
Implementations bind their resource to the physical transaction instead of
looking it up on their own: initialize() binds a new resource to
current_frame.transaction, join() binds the current context to the
resource of the transaction it joined and leave() undoes that. The
resource of the current frame is the one to use. Once its transaction is
finished it must be refused with TransactionAlreadyFinishedError
instead of falling back to a resource below it.
Initialize the async transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
autocommit
|
bool
|
Whether to auto-commit on successful exit. |
True
|
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
is_active
property
¶
Whether a live transaction is open in the current context.
is_rollback_only
property
¶
Whether the current physical transaction can only be rolled back.
current_frame
property
¶
The innermost open scope of the current execution context.
Returns:
| Type | Description |
|---|---|
TransactionFrame
|
The frame of that scope. Its |
TransactionFrame
|
opened the physical transaction or joined it. |
Raises:
| Type | Description |
|---|---|
TransactionNotActiveError
|
No scope is open in this context. |
scope(propagation=Propagation.REQUIRED)
async
¶
Run a block inside a transaction scope with the given propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
propagation
|
Propagation
|
How the scope relates to a transaction in progress. |
REQUIRED
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[Self]
|
This transaction. |
Raises:
| Type | Description |
|---|---|
TransactionRollbackOnlyError
|
The opening scope finished normally but a joined scope had failed, so the transaction was rolled back. |
TransactionAlreadyFinishedError
|
The scope joined a transaction that finished before the scope exited. |
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
initialize()
abstractmethod
async
¶
Open a new physical transaction (e.g. open a session).
Called for the outermost scope and for every REQUIRES_NEW scope,
after its frame was pushed: current_frame.transaction is the new
physical transaction to bind the resource to.
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
join()
async
¶
Bind the current context to the resource of the joined transaction.
Called when a REQUIRED scope joins a transaction in progress, after
its frame was pushed: current_frame.transaction is the joined
transaction. It is below the innermost frame when the innermost one
has already finished. Implementations that keep no resource per
context leave this as it is.
Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
leave()
async
¶
Undo the binding made by join() when the joined scope exits.
Implementations that keep no resource per context leave this as it is.
dispose()
abstractmethod
async
¶
commit()
abstractmethod
async
¶
AggregateBuffer(transaction, aggregates=list[AbstractAggregateRoot](), released=False)
dataclass
¶
Aggregates collected by one physical transaction.
The buffer is bound to the physical transaction it collects for. That object is shared by every execution context that copied the buffer stack, so the end of the transaction is seen by child tasks and threads that still hold the buffer, at the same moment as by its session.
transaction
instance-attribute
¶
The physical transaction the aggregates belong to.
None (not applicable) for the base buffer used outside any
transaction, which never finishes.
aggregates = field(default_factory=(list[AbstractAggregateRoot]))
class-attribute
instance-attribute
¶
Aggregates collected so far, in collection order.
released = False
class-attribute
instance-attribute
¶
True once commit_transaction() or discard_transaction() took it.
AggregateCollector()
¶
Context-scoped collector with execution-local aggregate buffers.
Aggregates are buffered per physical transaction. @Transactional opens
a buffer whenever its scope opens a physical transaction (the outermost
scope or a Propagation.REQUIRES_NEW scope) and, when its scope joins a
transaction, binds the current context to the buffer of that transaction.
When a physical transaction commits, its buffer is handed over and stays
available through drain_committed() until the domain events are
published.
The stack of buffers is an immutable tuple in a ContextVar that
mirrors the @Transactional scopes of the context, but each buffer is a
shared object: a child task or thread that inherited the execution context
collects into the buffer of the transaction its scope belongs to, while a
buffer it opens itself (REQUIRES_NEW) stays in its own context. Once
that transaction has finished (PhysicalTransaction.finished), the
buffer refuses new aggregates instead of falling back to another buffer,
so an aggregate is never published with a transaction its write did not
belong to. The first element is the base buffer used outside any
transaction; it never finishes.
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
collect(aggregate)
¶
Track an aggregate that was saved during the transaction.
This method is called by Repository implementations after saving an aggregate to the database. The aggregate is added to the buffer of the physical transaction of the current scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aggregate
|
AbstractAggregateRoot
|
The aggregate to track. |
required |
Raises:
| Type | Description |
|---|---|
TransactionAlreadyFinishedError
|
The transaction of the current scope has already committed or rolled back. |
Example
collector = AggregateCollector() user = User.create(name="Alice") collector.collect(user)
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
all()
¶
Get the aggregates tracked by the physical transaction of the scope.
Returns:
| Type | Description |
|---|---|
Sequence[AbstractAggregateRoot]
|
Sequence of tracked aggregates. |
Raises:
| Type | Description |
|---|---|
TransactionAlreadyFinishedError
|
The transaction of the current scope has already committed or rolled back. |
Example
collector = AggregateCollector() user = User.create(name="Bob") collector.collect(user) len(collector.all()) 1
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
clear()
¶
Clear the aggregates tracked by the physical transaction of the scope.
Raises:
| Type | Description |
|---|---|
TransactionAlreadyFinishedError
|
The transaction of the current scope has already committed or rolled back. |
Example
collector = AggregateCollector() user = User.create(name="Charlie") collector.collect(user) collector.clear() len(collector.all()) 0
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
begin_transaction(transaction)
¶
Open an empty buffer for a physical transaction a scope just opened.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction
|
PhysicalTransaction
|
The physical transaction opened by the scope. |
required |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
join_transaction(transaction)
¶
Collect into the buffer of a transaction a scope just joined.
The joined transaction may be below the innermost buffer when the
innermost transaction has already finished. A transaction opened
without @Transactional (scope() used directly) has no buffer;
the scope then keeps collecting where the enclosing scope collects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction
|
PhysicalTransaction
|
The physical transaction joined by the scope. |
required |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
leave_transaction()
¶
Stop collecting for the transaction joined by join_transaction().
Raises:
| Type | Description |
|---|---|
AggregateBufferNotOpenError
|
No transaction buffer is open. |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
commit_transaction()
¶
Hand the aggregates of the current buffer over for publishing.
Called right after the physical transaction committed.
Raises:
| Type | Description |
|---|---|
AggregateBufferNotOpenError
|
No transaction buffer is open. |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
discard_transaction()
¶
Drop the aggregates of the current buffer (rolled back).
Raises:
| Type | Description |
|---|---|
AggregateBufferNotOpenError
|
No transaction buffer is open. |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
drain_committed()
¶
Take the aggregates of the transactions committed so far.
Returns:
| Type | Description |
|---|---|
Sequence[AbstractAggregateRoot]
|
Aggregates handed over by |
Sequence[AbstractAggregateRoot]
|
drain, in collection order. |
Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
AbstractSpakkyPersistencyError
¶
TransactionRollbackOnlyError
¶
Bases: AbstractSpakkyPersistencyError
Raised when a transaction marked rollback-only is asked to commit.
A joined (Propagation.REQUIRED) inner scope that exits with an exception
marks the whole physical transaction rollback-only. If the outermost scope
then finishes normally, the transaction is rolled back instead of committed
and this error is raised so the caller knows nothing was persisted.
TransactionNotActiveError
¶
Bases: AbstractSpakkyPersistencyError
Raised when a transaction scope is closed while no scope is open.
TransactionAlreadyFinishedError
¶
Bases: AbstractSpakkyPersistencyError
Raised when a scope uses or exits a transaction that already finished.
A child task or thread that joined (Propagation.REQUIRED) a transaction
of its parent can outlive the parent's scope. Once the scope that opened
the physical transaction has committed or rolled back, work done in the
joined scope afterwards cannot be part of that transaction. Resources bound
to the finished transaction (its session, its aggregate buffer) refuse to
be used instead of handing out another transaction's resource, and the
joined scope fails on exit instead of losing that work silently.
AggregateBufferNotOpenError
¶
Bases: AbstractSpakkyPersistencyError
Raised when a transaction buffer is closed that was never opened.
TransactionSynchronizationNotOpenError
¶
Bases: AbstractSpakkyPersistencyError
Raised when after-commit work is used while no transaction is open.
외부 Proxy¶
IGenericProxy
¶
AbstractSpakkyExternalError
¶
Aspect¶
Propagation
¶
Bases: StrEnum
How a transaction scope relates to a transaction already in progress.
Transactional(propagation=Propagation.REQUIRED)
dataclass
¶
Bases: FunctionAnnotation
Annotation for marking methods as transactional.
Methods decorated with @Transactional() will be executed within a transaction context, ensuring atomicity of operations.
With the default Propagation.REQUIRED a call made while a transaction is
in progress joins it: only the outermost scope commits and closes the
session, and an exception escaping a joined call marks the whole
transaction rollback-only. Propagation.REQUIRES_NEW always runs the
call in a separate transaction that commits on its own.
propagation = Propagation.REQUIRED
class-attribute
instance-attribute
¶
How this call relates to a transaction already in progress.
AsyncTransactionalAspect(transaction, collector, synchronization)
¶
Bases: IAsyncAspect
Aspect for managing transactions in async methods.
Intercepts async methods decorated with @Transactional and ensures that they are executed within a transaction context.
Source code in core/spakky-data/src/spakky/data/aspects/transactional.py
TransactionalAspect(transaction, collector, synchronization)
¶
Bases: IAspect
Aspect for managing transactions in sync methods.
Intercepts sync methods decorated with @Transactional and ensures that they are executed within a transaction context.
Source code in core/spakky-data/src/spakky/data/aspects/transactional.py
transactional(func)
¶
Decorator for marking methods as transactional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[P, R]
|
The function to decorate. |
required |
Returns: The decorated function with transactional annotation.