콘텐츠로 이동

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
def initialize(app: SpakkyApplication) -> None:
    """Initialize the spakky-data plugin.

    Registers the common configuration, sync aspect, and aggregate collector.
    The async aspect follows DataConfig, also consumed by persistence providers.
    """
    config = DataConfig()
    app.add(DataConfig)
    app.add(TransactionalAspect)
    app.add(AggregateCollector)
    app.add(TransactionSynchronization)

    if config.support_async_mode:
        app.add(AsyncTransactionalAspect)

공통 설정

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
def __init__(self) -> None:
    """Read the common data configuration from environment variables."""
    super().__init__()

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.

Repository(*, name='', scope=Scope.SINGLETON) dataclass

Bases: Pod

Stereotype for repository classes handling data access.

Repositories provide an abstraction over data sources, implementing data access patterns and queries.

영속성

EntityNotFoundError

Bases: AbstractSpakkyDomainError

Raised when an entity cannot be found by the given identifier.

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 an aggregate by ID.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def get(self, aggregate_id: AggregateIdT_contra) -> AggregateRootT:
    """Get an aggregate by ID."""
    ...

get_or_none(aggregate_id) abstractmethod

Get an aggregate by ID, or None if not found.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def get_or_none(self, aggregate_id: AggregateIdT_contra) -> AggregateRootT | None:
    """Get an aggregate by ID, or None if not found."""
    ...

contains(aggregate_id) abstractmethod

Check if an aggregate with the given ID exists.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def contains(self, aggregate_id: AggregateIdT_contra) -> bool:
    """Check if an aggregate with the given ID exists."""
    ...

range(aggregate_ids) abstractmethod

Get multiple aggregates by their IDs.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def range(
    self, aggregate_ids: Sequence[AggregateIdT_contra]
) -> Sequence[AggregateRootT]:
    """Get multiple aggregates by their IDs."""
    ...

save(aggregate) abstractmethod

Persist an aggregate and return the saved instance.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def save(self, aggregate: AggregateRootT) -> AggregateRootT:
    """Persist an aggregate and return the saved instance."""
    ...

save_all(aggregates) abstractmethod

Persist multiple aggregates and return the saved instances.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def save_all(
    self, aggregates: Sequence[AggregateRootT]
) -> Sequence[AggregateRootT]:
    """Persist multiple aggregates and return the saved instances."""
    ...

delete(aggregate) abstractmethod

Delete an aggregate and return the deleted instance.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def delete(self, aggregate: AggregateRootT) -> AggregateRootT:
    """Delete an aggregate and return the deleted instance."""
    ...

delete_all(aggregates) abstractmethod

Delete multiple aggregates and return the deleted instances.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
def delete_all(
    self, aggregates: Sequence[AggregateRootT]
) -> Sequence[AggregateRootT]:
    """Delete multiple aggregates and return the deleted instances."""
    ...

IAsyncGenericRepository

Bases: ABC

Asynchronous generic repository interface for aggregate persistence.

get(aggregate_id) abstractmethod async

Get an aggregate by ID.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def get(self, aggregate_id: AggregateIdT_contra) -> AggregateRootT:
    """Get an aggregate by ID."""
    ...

get_or_none(aggregate_id) abstractmethod async

Get an aggregate by ID, or None if not found.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def get_or_none(
    self, aggregate_id: AggregateIdT_contra
) -> AggregateRootT | None:
    """Get an aggregate by ID, or None if not found."""
    ...

contains(aggregate_id) abstractmethod async

Check if an aggregate with the given ID exists.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def contains(self, aggregate_id: AggregateIdT_contra) -> bool:
    """Check if an aggregate with the given ID exists."""
    ...

range(aggregate_ids) abstractmethod async

Get multiple aggregates by their IDs.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def range(
    self, aggregate_ids: Sequence[AggregateIdT_contra]
) -> Sequence[AggregateRootT]:
    """Get multiple aggregates by their IDs."""
    ...

save(aggregate) abstractmethod async

Persist an aggregate and return the saved instance.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def save(self, aggregate: AggregateRootT) -> AggregateRootT:
    """Persist an aggregate and return the saved instance."""
    ...

save_all(aggregates) abstractmethod async

Persist multiple aggregates and return the saved instances.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def save_all(
    self, aggregates: Sequence[AggregateRootT]
) -> Sequence[AggregateRootT]:
    """Persist multiple aggregates and return the saved instances."""
    ...

delete(aggregate) abstractmethod async

Delete an aggregate and return the deleted instance.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def delete(self, aggregate: AggregateRootT) -> AggregateRootT:
    """Delete an aggregate and return the deleted instance."""
    ...

delete_all(aggregates) abstractmethod async

Delete multiple aggregates and return the deleted instances.

Source code in core/spakky-data/src/spakky/data/persistency/repository.py
@abstractmethod
async def delete_all(
    self, aggregates: Sequence[AggregateRootT]
) -> Sequence[AggregateRootT]:
    """Delete multiple aggregates and return the deleted instances."""
    ...

Propagation

Bases: StrEnum

How a transaction scope relates to a transaction already in progress.

REQUIRED = 'required' class-attribute instance-attribute

Join the transaction in progress, or start a new one when there is none.

REQUIRES_NEW = 'requires_new' class-attribute instance-attribute

Always start a separate transaction that commits on its own.

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.

transaction instance-attribute

The physical transaction this scope belongs to.

owner instance-attribute

True for the scope that opened the physical transaction.

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
def __init__(self, autocommit: bool = True) -> None:
    """Initialize the transaction.

    Args:
        autocommit: Whether to auto-commit on successful exit.
    """
    self.autocommit_enabled = autocommit
    self._frames = ContextVar("spakky_transaction_frames", default=())

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 owner tells whether the scope

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
@final
@contextmanager
def scope(self, propagation: Propagation = Propagation.REQUIRED) -> Generator[Self]:
    """Run a block inside a transaction scope with the given propagation.

    Args:
        propagation: How the scope relates to a transaction in progress.

    Yields:
        This transaction.

    Raises:
        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.
    """
    self._begin(propagation)
    try:
        yield self
    except BaseException as error:
        self._finish(error)
        raise
    self._finish(None)

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
@abstractmethod
def initialize(self) -> None:
    """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.
    """
    ...

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
def join(self) -> None:
    """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.
    """

leave()

Undo the binding made by join() when the joined scope exits.

Implementations that keep no resource per context leave this as it is.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
def leave(self) -> None:
    """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

Release the physical transaction opened by the last initialize().

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
def dispose(self) -> None:
    """Release the physical transaction opened by the last ``initialize()``."""
    ...

commit() abstractmethod

Commit the current physical transaction.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
def commit(self) -> None:
    """Commit the current physical transaction."""
    ...

rollback() abstractmethod

Roll back the current physical transaction.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
def rollback(self) -> None:
    """Roll back the current physical transaction."""
    ...

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
def __init__(self, autocommit: bool = True) -> None:
    """Initialize the async transaction.

    Args:
        autocommit: Whether to auto-commit on successful exit.
    """
    self.autocommit_enabled = autocommit
    self._frames = ContextVar("spakky_async_transaction_frames", default=())

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 owner tells whether the scope

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
@final
@asynccontextmanager
async def scope(
    self, propagation: Propagation = Propagation.REQUIRED
) -> AsyncGenerator[Self]:
    """Run a block inside a transaction scope with the given propagation.

    Args:
        propagation: How the scope relates to a transaction in progress.

    Yields:
        This transaction.

    Raises:
        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.
    """
    await self._begin(propagation)
    try:
        yield self
    except BaseException as error:
        await self._finish(error)
        raise
    await self._finish(None)

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
@abstractmethod
async def initialize(self) -> None:
    """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.
    """
    ...

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
async def join(self) -> None:
    """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.
    """

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.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
async def leave(self) -> None:
    """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

Release the physical transaction opened by the last initialize().

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
async def dispose(self) -> None:
    """Release the physical transaction opened by the last ``initialize()``."""
    ...

commit() abstractmethod async

Commit the current physical transaction.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
async def commit(self) -> None:
    """Commit the current physical transaction."""
    ...

rollback() abstractmethod async

Roll back the current physical transaction.

Source code in core/spakky-data/src/spakky/data/persistency/transaction.py
@abstractmethod
async def rollback(self) -> None:
    """Roll back the current physical transaction."""
    ...

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
def __init__(self) -> None:
    self._buffers = ContextVar("spakky_collected_aggregates", default=())
    self._committed = ContextVar("spakky_committed_aggregates", default=())

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
def collect(self, aggregate: AbstractAggregateRoot) -> None:
    """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.

    Args:
        aggregate: The aggregate to track.

    Raises:
        TransactionAlreadyFinishedError: The transaction of the current
            scope has already committed or rolled back.

    Example:
        >>> collector = AggregateCollector()
        >>> user = User.create(name="Alice")
        >>> collector.collect(user)
    """
    self._usable_buffer().aggregates.append(aggregate)

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
def all(self) -> Sequence[AbstractAggregateRoot]:
    """Get the aggregates tracked by the physical transaction of the scope.

    Returns:
        Sequence of tracked aggregates.

    Raises:
        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
    """
    return list(self._usable_buffer().aggregates)

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
def clear(self) -> None:
    """Clear the aggregates tracked by the physical transaction of the scope.

    Raises:
        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
    """
    self._usable_buffer().aggregates.clear()

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
def begin_transaction(self, transaction: PhysicalTransaction) -> None:
    """Open an empty buffer for a physical transaction a scope just opened.

    Args:
        transaction: The physical transaction opened by the scope.
    """
    self._buffers.set(
        (*self._current_buffers(), AggregateBuffer(transaction=transaction))
    )

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
def join_transaction(self, transaction: PhysicalTransaction) -> None:
    """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.

    Args:
        transaction: The physical transaction joined by the scope.
    """
    buffers = self._current_buffers()
    joined = next(
        (
            buffer
            for buffer in reversed(buffers)
            if buffer.transaction is transaction
        ),
        buffers[-1],
    )
    self._buffers.set((*buffers, joined))

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
def leave_transaction(self) -> None:
    """Stop collecting for the transaction joined by ``join_transaction()``.

    Raises:
        AggregateBufferNotOpenError: No transaction buffer is open.
    """
    buffers = self._current_buffers()
    if len(buffers) == 1:
        raise AggregateBufferNotOpenError()
    self._buffers.set(buffers[:-1])

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
def commit_transaction(self) -> None:
    """Hand the aggregates of the current buffer over for publishing.

    Called right after the physical transaction committed.

    Raises:
        AggregateBufferNotOpenError: No transaction buffer is open.
    """
    buffer = self._release_buffer()
    self._committed.set((*self._committed.get(), *buffer.aggregates))

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
def discard_transaction(self) -> None:
    """Drop the aggregates of the current buffer (rolled back).

    Raises:
        AggregateBufferNotOpenError: No transaction buffer is open.
    """
    self._release_buffer()

drain_committed()

Take the aggregates of the transactions committed so far.

Returns:

Type Description
Sequence[AbstractAggregateRoot]

Aggregates handed over by commit_transaction() since the last

Sequence[AbstractAggregateRoot]

drain, in collection order.

Source code in core/spakky-data/src/spakky/data/persistency/aggregate_collector.py
def drain_committed(self) -> Sequence[AbstractAggregateRoot]:
    """Take the aggregates of the transactions committed so far.

    Returns:
        Aggregates handed over by ``commit_transaction()`` since the last
        drain, in collection order.
    """
    committed = list(self._committed.get())
    self._committed.set(())
    return committed

AbstractSpakkyPersistencyError

Bases: AbstractSpakkyFrameworkError, ABC

Base error for persistency layer operations.

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

ProxyModel

Immutable read-only projection model identified by an equatable ID.

__eq__(other)

Compare by ID equality.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
def __eq__(self, other: object) -> bool:
    """Compare by ID equality."""
    if not isinstance(other, type(self)):
        return False
    return self.id == other.id

__hash__()

Hash based on ID.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
def __hash__(self) -> int:
    """Hash based on ID."""
    return hash(self.id)

IGenericProxy

Bases: ABC

Synchronous read-only proxy interface for querying projections.

get(proxy_id) abstractmethod

Get a proxy model by ID.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
def get(self, proxy_id: ProxyIdT_contra) -> ProxyModelT_co:
    """Get a proxy model by ID."""
    ...

get_or_none(proxy_id) abstractmethod

Get a proxy model by ID, or None if not found.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
def get_or_none(self, proxy_id: ProxyIdT_contra) -> ProxyModelT_co | None:
    """Get a proxy model by ID, or None if not found."""
    ...

contains(proxy_id) abstractmethod

Check if a proxy model with the given ID exists.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
def contains(self, proxy_id: ProxyIdT_contra) -> bool:
    """Check if a proxy model with the given ID exists."""
    ...

range(proxy_ids) abstractmethod

Get multiple proxy models by their IDs.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
def range(self, proxy_ids: Sequence[ProxyIdT_contra]) -> Sequence[ProxyModelT_co]:
    """Get multiple proxy models by their IDs."""
    ...

IAsyncGenericProxy

Bases: ABC

Asynchronous read-only proxy interface for querying projections.

get(proxy_id) abstractmethod async

Get a proxy model by ID.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
async def get(self, proxy_id: ProxyIdT_contra) -> ProxyModelT_co:
    """Get a proxy model by ID."""
    ...

get_or_none(proxy_id) abstractmethod async

Get a proxy model by ID, or None if not found.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
async def get_or_none(self, proxy_id: ProxyIdT_contra) -> ProxyModelT_co | None:
    """Get a proxy model by ID, or None if not found."""
    ...

contains(proxy_id) abstractmethod async

Check if a proxy model with the given ID exists.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
async def contains(self, proxy_id: ProxyIdT_contra) -> bool:
    """Check if a proxy model with the given ID exists."""
    ...

range(proxy_ids) abstractmethod async

Get multiple proxy models by their IDs.

Source code in core/spakky-data/src/spakky/data/external/proxy.py
@abstractmethod
async def range(
    self, proxy_ids: Sequence[ProxyIdT_contra]
) -> Sequence[ProxyModelT_co]:
    """Get multiple proxy models by their IDs."""
    ...

AbstractSpakkyExternalError

Bases: AbstractSpakkyFrameworkError, ABC

Base error for external proxy operations.

Aspect

Propagation

Bases: StrEnum

How a transaction scope relates to a transaction already in progress.

REQUIRED = 'required' class-attribute instance-attribute

Join the transaction in progress, or start a new one when there is none.

REQUIRES_NEW = 'requires_new' class-attribute instance-attribute

Always start a separate transaction that commits on its own.

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
def __init__(
    self,
    transaction: AbstractAsyncTransaction,
    collector: AggregateCollector,
    synchronization: TransactionSynchronization,
) -> None:
    self._transaction = transaction
    self._collector = collector
    self._synchronization = synchronization

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
def __init__(
    self,
    transaction: AbstractTransaction,
    collector: AggregateCollector,
    synchronization: TransactionSynchronization,
) -> None:
    self._transaction = transaction
    self._collector = collector
    self._synchronization = synchronization

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.

Source code in core/spakky-data/src/spakky/data/aspects/transactional.py
def transactional[**P, R](func: Callable[P, R]) -> Callable[P, R]:
    """Decorator for marking methods as transactional.

    Args:
        func: The function to decorate.
    Returns:
        The decorated function with transactional annotation.
    """
    return Transactional()(func)