Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

Spakky DDD

Spakky Framework를 위한 Domain-Driven Design 빌딩 블록입니다. Entity, AggregateRoot, ValueObject, DomainEvent, Command, Query 모델의 공통 기반을 제공합니다.

설치

pip install spakky-domain

주요 기능

  • Entity: 고유 identity와 생명주기를 가진 객체
  • Value Object: 속성 값으로 비교되는 불변 객체
  • Aggregate Root: 이벤트 관리를 포함하는 일관성 경계
  • Domain Event: 이벤트 기반 아키텍처를 위한 불변 이벤트
  • CQRS: Command와 Query 유스케이스 추상화

빠른 시작

엔티티

엔티티는 시간이 지나도 유지되는 고유 identity를 가진 객체입니다.

from uuid import UUID, uuid4

from spakky.core.common.mutability import mutable
from spakky.domain.models.entity import AbstractEntity


@mutable
class User(AbstractEntity[UUID]):
    name: str
    email: str

    @classmethod
    def next_id(cls) -> UUID:
        return uuid4()

    def validate(self) -> None:
        if not self.email:
            raise ValueError("Email is required")

엔티티는 비즈니스 필드가 바뀔 때마다 version(UUID v7)과 updated_at을 스스로 갱신합니다. 동시에 persisted_version에 "저장소에 있다고 알고 있는 version"을 기억합니다. 생성자에 넘긴 version이 그대로 persisted_version이 되므로 저장소에서 복원한 엔티티는 저장된 version을, 새 엔티티는 최초 version을 가집니다. 저장소 구현은 쓰기에 성공한 뒤 mark_persisted()를 호출해 이 값을 현재 version으로 옮깁니다. 이 정보는 도메인 객체 안에만 있고, 낙관적 lock 비교는 spakky-sqlalchemy 같은 저장소 구현이 수행합니다.

user = User(uid=uid, version=stored_version, name="John", email="john@example.com")
user.name = "Jane"

user.version            # 새 UUID
user.persisted_version  # stored_version
user.mark_persisted()   # 저장소가 쓰기 성공 후 호출
user.persisted_version  # user.version과 같음

값 객체

값 객체는 불변이며 속성 값으로 비교됩니다.

from spakky.core.common.mutability import immutable
from spakky.domain.models.value_object import AbstractValueObject


@immutable
class Money(AbstractValueObject):
    amount: int
    currency: str

    def validate(self) -> None:
        if self.amount < 0:
            raise ValueError("Amount cannot be negative")

애그리거트 루트

애그리거트 루트는 도메인 이벤트를 관리하는 엔티티입니다.

from typing import Self
from uuid import UUID, uuid4

from spakky.core.common.mutability import mutable, immutable
from spakky.domain.models.aggregate_root import AbstractAggregateRoot
from spakky.domain.models.event import AbstractDomainEvent


@immutable
class OrderCreatedEvent(AbstractDomainEvent):
    order_id: UUID
    customer_id: UUID


@mutable
class Order(AbstractAggregateRoot[UUID]):
    customer_id: UUID
    total: int

    @classmethod
    def next_id(cls) -> UUID:
        return uuid4()

    def validate(self) -> None:
        if self.total < 0:
            raise ValueError("Total cannot be negative")

    @classmethod
    def create(cls, customer_id: UUID, total: int) -> Self:
        order = cls(uid=cls.next_id(), customer_id=customer_id, total=total)
        order.add_event(OrderCreatedEvent(order_id=order.uid, customer_id=customer_id))
        return order

도메인 이벤트

도메인 이벤트는 도메인 내부의 상태 변화를 표현합니다.

from spakky.core.common.mutability import immutable
from spakky.domain.models.event import AbstractDomainEvent, AbstractIntegrationEvent


# Internal domain event
@immutable
class UserRegistered(AbstractDomainEvent):
    user_id: str
    email: str


# Cross-boundary integration event
@immutable
class UserRegisteredIntegration(AbstractIntegrationEvent):
    user_id: str
    email: str

CQRS 유스케이스

읽기와 쓰기 작업을 분리합니다.

핵심 원칙:

  • Command: 도메인 Aggregate 영속화에 Repository 사용
  • Query: ORM/SQL로 직접 구현(Repository에 query 메서드 추가 금지)
  • Query 관심사를 도메인 레이어 밖에 두어 도메인 오염을 방지합니다.
from uuid import UUID

from spakky.core.common.mutability import immutable
from spakky.domain.application.command import AbstractCommand, IAsyncCommandUseCase
from spakky.domain.application.query import AbstractQuery, IAsyncQueryUseCase


# Command
@immutable
class CreateUserCommand(AbstractCommand):
    name: str
    email: str


class CreateUserUseCase(IAsyncCommandUseCase[CreateUserCommand, UUID]):
    async def run(self, command: CreateUserCommand) -> UUID:
        # Business logic here
        ...


# Query
@immutable
class GetUserQuery(AbstractQuery):
    user_id: UUID


class GetUserUseCase(IAsyncQueryUseCase[GetUserQuery, User | None]):
    async def run(self, query: GetUserQuery) -> User | None:
        # Business logic here
        ...

API 레퍼런스

모델

클래스 설명
AbstractEntity[T] identity type T를 가진 엔티티의 기반 클래스
AbstractAggregateRoot[T] 도메인 이벤트를 관리하는 Entity
AbstractValueObject 불변 value object
AbstractEvent 모든 이벤트의 기반 클래스
AbstractDomainEvent 도메인 이벤트(bounded context 내부)
AbstractIntegrationEvent 통합 이벤트(경계 간 통신)

애플리케이션

클래스 설명
AbstractCommand command DTO의 기반 클래스
AbstractQuery query DTO의 기반 클래스
ICommandUseCase 동기 command use case interface
IAsyncCommandUseCase 비동기 command use case interface
IQueryUseCase 동기 query use case interface
IAsyncQueryUseCase 비동기 query use case interface

관련 패키지

패키지 설명
spakky-data Repository와 transaction 추상화
spakky-event Event publisher/consumer interface와 @EventHandler stereotype

개발 검증

패키지 단위 검증은 해당 패키지 디렉토리에서 실행합니다.

uv run ruff format .
uv run ruff check .
uv run pyrefly check
uv run pytest

pytest는 각 패키지 pyproject.toml의 coverage 설정을 사용합니다.

라이선스

MIT License

Metadata

Release files for spakky-domain 13.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

Source distribution for spakky-domain 13.0.0
File Size Uploaded Provenance Actions
spakky_domain-13.0.0.tar.gz 11.1 kB With provenance Details for spakky_domain-13.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spakky-domain 13.0.0
File Interpreter ABI Platform Actions
spakky_domain-13.0.0-py3-none-any.whl Python 3 none any Details for spakky_domain-13.0.0-py3-none-any.whl

Total release size: 26.6 kB

Release files / spakky_domain-13.0.0.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL spakky_domain-13.0.0.tar.gz
Size 11.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e129c63018f4a49ac3fc4656dbf5316187d4b9505e559d8ad4b7515e028a4c3a
BLAKE2b-256 checksum
How to use checksums
105ff97e0a69a2ea3a728509f046a12e8c1c97c685aa94022131eb36de2b0143
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / spakky_domain-13.0.0-py3-none-any.whl

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL spakky_domain-13.0.0-py3-none-any.whl
Size 15.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
53d75f9ce74956a7f365961c9aa625ebb1a6f4085d5ae9e460160671e86abde3
BLAKE2b-256 checksum
How to use checksums
b67dfe84ef42e57bc9936936e59ead8f05c7cb207488fe15480653226d16bf7a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for spakky-domain 13.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Change of provenance

The configuration that created this release differs from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for spakky_domain-13.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page