python-ddd-framework 0.8.0__py3-none-any.whl → 0.10.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_ddd_framework/__init__.py +17 -3
- python_ddd_framework/application/builder.py +38 -32
- python_ddd_framework/application/runtime_hooks.py +5 -3
- python_ddd_framework/application/state.py +2 -0
- python_ddd_framework/auditing/sqlalchemy/mappings.py +29 -0
- python_ddd_framework/auditing/sqlalchemy/module.py +1 -2
- python_ddd_framework/auditing/sqlalchemy/store.py +23 -15
- python_ddd_framework/caching/unit_of_work.py +4 -0
- python_ddd_framework/consumer_docs/README.md +91 -0
- python_ddd_framework/consumer_docs/architecture.md +264 -0
- python_ddd_framework/consumer_docs/development.md +934 -0
- python_ddd_framework/developer_kit/templates/basic/{{cookiecutter.module_name}}/README.md +13 -1
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/README.md +18 -23
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/module.py.jinja +2 -4
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/AGENTS.md +33 -53
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/README.md +37 -18
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/pyproject.toml.jinja +15 -1
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/module.py.jinja +0 -4
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/architecture.md +22 -145
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/development.md +39 -482
- python_ddd_framework/domain/__init__.py +5 -0
- python_ddd_framework/domain/aggregates.py +5 -35
- python_ddd_framework/domain/auditing.py +11 -0
- python_ddd_framework/domain/capabilities.py +39 -0
- python_ddd_framework/domain/entities.py +0 -2
- python_ddd_framework/entity_caching/__init__.py +5 -0
- python_ddd_framework/entity_caching/cache.py +95 -0
- python_ddd_framework/entity_caching/contracts.py +22 -0
- python_ddd_framework/entity_caching/module.py +9 -0
- python_ddd_framework/entity_caching/registration.py +131 -0
- python_ddd_framework/events/aggregate.py +6 -13
- python_ddd_framework/events/runtime.py +93 -27
- python_ddd_framework/extensions/__init__.py +2 -0
- python_ddd_framework/extensions/catalog.py +4 -0
- python_ddd_framework/extensions/contracts.py +12 -2
- python_ddd_framework/identity/application.py +2 -4
- python_ddd_framework/identity/domain_rules.py +4 -2
- python_ddd_framework/identity/dtos.py +19 -20
- python_ddd_framework/identity/management.py +14 -11
- python_ddd_framework/identity/models.py +28 -36
- python_ddd_framework/identity/seeding.py +2 -2
- python_ddd_framework/identity/sqlalchemy/mappings.py +132 -0
- python_ddd_framework/identity/sqlalchemy/module.py +1 -11
- python_ddd_framework/identity/sqlalchemy/repository.py +147 -178
- python_ddd_framework/identity/sqlalchemy/session_security.py +8 -9
- python_ddd_framework/identity/sqlalchemy/stores.py +110 -86
- python_ddd_framework/identity/stores.py +5 -5
- python_ddd_framework/invocation/runtime.py +6 -0
- python_ddd_framework/services/__init__.py +2 -1
- python_ddd_framework/services/composition.py +8 -0
- python_ddd_framework/services/convention.py +28 -1
- python_ddd_framework/services/repository.py +31 -29
- python_ddd_framework/services/runtime.py +4 -0
- python_ddd_framework/settings/__init__.py +1 -6
- python_ddd_framework/settings/application.py +4 -9
- python_ddd_framework/settings/catalog.py +4 -59
- python_ddd_framework/settings/management.py +3 -13
- python_ddd_framework/settings/manager.py +9 -33
- python_ddd_framework/settings/module.py +3 -9
- python_ddd_framework/settings/sqlalchemy/mappings.py +31 -0
- python_ddd_framework/settings/sqlalchemy/module.py +1 -2
- python_ddd_framework/settings/sqlalchemy/store.py +66 -45
- python_ddd_framework/settings/values.py +0 -8
- python_ddd_framework/sqlalchemy/__init__.py +8 -6
- python_ddd_framework/sqlalchemy/alembic_runtime/env.py +3 -0
- python_ddd_framework/sqlalchemy/auditing.py +112 -30
- python_ddd_framework/sqlalchemy/conventions.py +54 -0
- python_ddd_framework/sqlalchemy/event_origins.py +163 -0
- python_ddd_framework/sqlalchemy/extensions.py +81 -49
- python_ddd_framework/sqlalchemy/locking.py +22 -0
- python_ddd_framework/sqlalchemy/mapping.py +53 -0
- python_ddd_framework/sqlalchemy/metadata.py +27 -47
- python_ddd_framework/sqlalchemy/metadata_builder.py +26 -20
- python_ddd_framework/sqlalchemy/metadata_fingerprint.py +4 -1
- python_ddd_framework/sqlalchemy/metadata_ownership.py +1 -1
- python_ddd_framework/sqlalchemy/migration.py +3 -5
- python_ddd_framework/sqlalchemy/migration_rendering.py +25 -0
- python_ddd_framework/sqlalchemy/module.py +56 -3
- python_ddd_framework/sqlalchemy/module_migration.py +4 -4
- python_ddd_framework/sqlalchemy/repository.py +139 -64
- python_ddd_framework/sqlalchemy/repository_binding.py +152 -0
- python_ddd_framework/sqlalchemy/session_provider.py +16 -21
- python_ddd_framework/sqlalchemy/tracking.py +231 -0
- python_ddd_framework/sqlalchemy/types.py +25 -0
- python_ddd_framework/sqlalchemy/unit_of_work.py +110 -6
- python_ddd_framework/unit_of_work/contracts.py +13 -6
- python_ddd_framework/unit_of_work/lifecycle.py +3 -0
- python_ddd_framework/unit_of_work/manager.py +17 -4
- python_ddd_framework-0.10.1.dist-info/METADATA +363 -0
- {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.10.1.dist-info}/RECORD +95 -85
- {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.10.1.dist-info}/WHEEL +1 -1
- python_ddd_framework-0.10.1.dist-info/licenses/LICENSE +21 -0
- python_ddd_framework/auditing/sqlalchemy/models.py +0 -31
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/setting_handlers/__init__.py.jinja +0 -1
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/models/base.py.jinja +0 -7
- python_ddd_framework/identity/sqlalchemy/models.py +0 -104
- python_ddd_framework/settings/changes.py +0 -14
- python_ddd_framework/settings/declarations.py +0 -18
- python_ddd_framework/settings/handlers.py +0 -43
- python_ddd_framework/settings/notifications.py +0 -41
- python_ddd_framework/settings/refresh.py +0 -140
- python_ddd_framework/settings/refresh_module.py +0 -52
- python_ddd_framework/settings/sqlalchemy/models.py +0 -36
- python_ddd_framework-0.8.0.dist-info/METADATA +0 -603
- python_ddd_framework-0.8.0.dist-info/licenses/LICENSE +0 -7
- /python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/{models → mappings}/__init__.py.jinja +0 -0
- {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.10.1.dist-info}/entry_points.txt +0 -0
- {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.10.1.dist-info}/licenses/src/python_ddd_framework/background_jobs/pgqueuer/UPSTREAM_LICENSE.txt +0 -0
|
@@ -4,54 +4,24 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from typing import Generic, TypeVar
|
|
6
6
|
|
|
7
|
+
from .capabilities import GeneratesLocalEvents, HasVersion
|
|
7
8
|
from .entities import Entity
|
|
8
|
-
from .errors import OptimisticConcurrencyError
|
|
9
|
-
from .event_values import _is_immutable_event
|
|
10
9
|
|
|
11
10
|
_TId = TypeVar("_TId")
|
|
12
11
|
|
|
13
12
|
|
|
14
|
-
class AggregateRoot(Entity[_TId], Generic[_TId]):
|
|
15
|
-
"""
|
|
13
|
+
class AggregateRoot(Entity[_TId], HasVersion, GeneratesLocalEvents, Generic[_TId]):
|
|
14
|
+
"""拥有领域身份、持久化版本值及尚未交接的本地事件。"""
|
|
16
15
|
|
|
17
|
-
__slots__ = ("_local_events", "_version"
|
|
16
|
+
__slots__ = ("_local_events", "_version")
|
|
18
17
|
|
|
19
18
|
def __init__(self, entity_id: _TId, *, version: int = 0) -> None:
|
|
20
19
|
super().__init__(entity_id)
|
|
21
20
|
if not isinstance(version, int) or isinstance(version, bool) or version < 0:
|
|
22
21
|
raise ValueError("aggregate version must be a non-negative integer")
|
|
23
22
|
self._version = version
|
|
24
|
-
self.
|
|
25
|
-
self._local_events: list[object] = []
|
|
23
|
+
self._restore_pending_state()
|
|
26
24
|
|
|
27
25
|
@property
|
|
28
26
|
def version(self) -> int:
|
|
29
27
|
return self._version
|
|
30
|
-
|
|
31
|
-
def raise_local_event(self, event: object) -> None:
|
|
32
|
-
if not _is_immutable_event(event):
|
|
33
|
-
raise TypeError(
|
|
34
|
-
"aggregate local events must be immutable dataclass or Pydantic values "
|
|
35
|
-
"with supported stable fields"
|
|
36
|
-
)
|
|
37
|
-
self._local_events.append(event)
|
|
38
|
-
|
|
39
|
-
def release_local_events(self) -> tuple[object, ...]:
|
|
40
|
-
events = tuple(self._local_events)
|
|
41
|
-
self._local_events.clear()
|
|
42
|
-
return events
|
|
43
|
-
|
|
44
|
-
def stage_next_version(self, expected_version: int) -> int:
|
|
45
|
-
"""Repository SPI:一次聚合实例只允许暂存一个下一版本。"""
|
|
46
|
-
|
|
47
|
-
if (
|
|
48
|
-
not isinstance(expected_version, int)
|
|
49
|
-
or isinstance(expected_version, bool)
|
|
50
|
-
or expected_version < 0
|
|
51
|
-
):
|
|
52
|
-
raise ValueError("expected_version must be a non-negative integer")
|
|
53
|
-
if self._version_staged or self._version != expected_version:
|
|
54
|
-
raise OptimisticConcurrencyError
|
|
55
|
-
self._version += 1
|
|
56
|
-
self._version_staged = True
|
|
57
|
-
return self._version
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""显式继承的领域能力;同名成员不构成框架行为的启用声明。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Protocol
|
|
5
|
+
|
|
6
|
+
from .event_values import _is_immutable_event
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HasVersion(Protocol):
|
|
10
|
+
@property
|
|
11
|
+
def version(self) -> int: ...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GeneratesLocalEvents(Protocol):
|
|
15
|
+
"""对象拥有待交接队列,交接后的事件生命周期归当前 UoW。"""
|
|
16
|
+
|
|
17
|
+
_local_events: list[object]
|
|
18
|
+
_local_event_observer: Callable[[int | None], None] | None = None
|
|
19
|
+
|
|
20
|
+
def _restore_pending_state(self) -> None:
|
|
21
|
+
self._local_events = []
|
|
22
|
+
self._local_event_observer = None
|
|
23
|
+
|
|
24
|
+
def raise_local_event(self, event: object) -> None:
|
|
25
|
+
if not _is_immutable_event(event):
|
|
26
|
+
raise TypeError(
|
|
27
|
+
"aggregate local events must be immutable dataclass or Pydantic values "
|
|
28
|
+
"with supported stable fields"
|
|
29
|
+
)
|
|
30
|
+
if self._local_event_observer is not None:
|
|
31
|
+
self._local_event_observer(len(self._local_events))
|
|
32
|
+
self._local_events.append(event)
|
|
33
|
+
|
|
34
|
+
def release_local_events(self) -> tuple[object, ...]:
|
|
35
|
+
if self._local_event_observer is not None:
|
|
36
|
+
self._local_event_observer(None)
|
|
37
|
+
events = tuple(self._local_events)
|
|
38
|
+
self._local_events.clear()
|
|
39
|
+
return events
|
|
@@ -10,8 +10,6 @@ _TId = TypeVar("_TId")
|
|
|
10
10
|
class Entity(Generic[_TId]):
|
|
11
11
|
"""Identity owner whose identifier cannot change after construction."""
|
|
12
12
|
|
|
13
|
-
__slots__ = ("_id",)
|
|
14
|
-
|
|
15
13
|
def __init__(self, entity_id: _TId) -> None:
|
|
16
14
|
if entity_id is None:
|
|
17
15
|
raise ValueError("entity id cannot be None")
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""仓储回源、映射和有序结果重建;不拥有事务或第二份缓存状态。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
from ..caching import DistributedCache, DistributedCacheEntryOptions
|
|
8
|
+
from ..errors import ResourceNotFoundError
|
|
9
|
+
from ..services import Repository
|
|
10
|
+
from .contracts import _EntityCacheKey
|
|
11
|
+
|
|
12
|
+
_TEntity = TypeVar("_TEntity")
|
|
13
|
+
_TCacheItem = TypeVar("_TCacheItem")
|
|
14
|
+
_TKey = TypeVar("_TKey", bound=_EntityCacheKey)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class _EntityCacheItem(Generic[_TCacheItem]):
|
|
19
|
+
# 独立 typed cache 身份避免普通 DistributedCache[DTO] 与实体缓存相互覆盖。
|
|
20
|
+
value: _TCacheItem
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _RepositoryEntityCache(Generic[_TEntity, _TCacheItem, _TKey]):
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
repository: Repository[_TEntity, _TKey],
|
|
27
|
+
cache: DistributedCache[_EntityCacheItem[_TCacheItem]],
|
|
28
|
+
*,
|
|
29
|
+
map_item: Callable[[_TEntity], _TCacheItem],
|
|
30
|
+
entity_id: Callable[[_TEntity], _TKey],
|
|
31
|
+
cache_key: Callable[[_TKey], str],
|
|
32
|
+
options: DistributedCacheEntryOptions,
|
|
33
|
+
entity_name: str,
|
|
34
|
+
) -> None:
|
|
35
|
+
self._repository = repository
|
|
36
|
+
self._cache = cache
|
|
37
|
+
self._map_item = map_item
|
|
38
|
+
self._entity_id = entity_id
|
|
39
|
+
self._cache_key = cache_key
|
|
40
|
+
self._options = options
|
|
41
|
+
self._entity_name = entity_name
|
|
42
|
+
|
|
43
|
+
async def find(self, entity_id: _TKey) -> _TCacheItem | None:
|
|
44
|
+
async def load() -> _EntityCacheItem[_TCacheItem] | None:
|
|
45
|
+
entity = await self._repository.find(entity_id)
|
|
46
|
+
return None if entity is None else _EntityCacheItem(value=self._map_item(entity))
|
|
47
|
+
|
|
48
|
+
item = await self._cache.get_or_add(
|
|
49
|
+
self._cache_key(entity_id), load, options_factory=lambda: self._options
|
|
50
|
+
)
|
|
51
|
+
return None if item is None else item.value
|
|
52
|
+
|
|
53
|
+
def _require(self, item: _TCacheItem | None) -> _TCacheItem:
|
|
54
|
+
if item is None:
|
|
55
|
+
raise ResourceNotFoundError(f"{self._entity_name} was not found")
|
|
56
|
+
return item
|
|
57
|
+
|
|
58
|
+
async def get(self, entity_id: _TKey) -> _TCacheItem:
|
|
59
|
+
return self._require(await self.find(entity_id))
|
|
60
|
+
|
|
61
|
+
async def find_many_as_dictionary(
|
|
62
|
+
self, entity_ids: Iterable[_TKey]
|
|
63
|
+
) -> dict[_TKey, _TCacheItem | None]:
|
|
64
|
+
keys = {self._cache_key(identity): identity for identity in entity_ids}
|
|
65
|
+
if not keys:
|
|
66
|
+
return {}
|
|
67
|
+
|
|
68
|
+
async def load(missing: list[str]) -> list[tuple[str, _EntityCacheItem[_TCacheItem]]]:
|
|
69
|
+
entities = await self._repository.get_list_by_ids(
|
|
70
|
+
[keys[key] for key in missing], include_details=True
|
|
71
|
+
)
|
|
72
|
+
return [
|
|
73
|
+
(
|
|
74
|
+
self._cache_key(self._entity_id(entity)),
|
|
75
|
+
_EntityCacheItem(value=self._map_item(entity)),
|
|
76
|
+
)
|
|
77
|
+
for entity in entities
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
found = await self._cache.get_or_add_many(keys, load, options_factory=lambda: self._options)
|
|
81
|
+
return {keys[key]: None if item is None else item.value for key, item in found}
|
|
82
|
+
|
|
83
|
+
async def find_many(self, entity_ids: Iterable[_TKey]) -> list[_TCacheItem | None]:
|
|
84
|
+
identities = list(entity_ids)
|
|
85
|
+
found = await self.find_many_as_dictionary(identities)
|
|
86
|
+
return [found[identity] for identity in identities]
|
|
87
|
+
|
|
88
|
+
async def get_many(self, entity_ids: Iterable[_TKey]) -> list[_TCacheItem]:
|
|
89
|
+
return [self._require(item) for item in await self.find_many(entity_ids)]
|
|
90
|
+
|
|
91
|
+
async def get_many_as_dictionary(self, entity_ids: Iterable[_TKey]) -> dict[_TKey, _TCacheItem]:
|
|
92
|
+
return {
|
|
93
|
+
identity: self._require(item)
|
|
94
|
+
for identity, item in (await self.find_many_as_dictionary(entity_ids)).items()
|
|
95
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""只读实体查询;写入和受管实体操作仍归 Repository。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from typing import Protocol, TypeVar
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
_EntityCacheKey = UUID | str | int
|
|
8
|
+
_TCacheItem = TypeVar("_TCacheItem")
|
|
9
|
+
_TKey = TypeVar("_TKey", bound=_EntityCacheKey)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EntityCache(Protocol[_TCacheItem, _TKey]):
|
|
13
|
+
async def find(self, entity_id: _TKey) -> _TCacheItem | None: ...
|
|
14
|
+
async def get(self, entity_id: _TKey) -> _TCacheItem: ...
|
|
15
|
+
async def find_many(self, entity_ids: Iterable[_TKey]) -> list[_TCacheItem | None]: ...
|
|
16
|
+
async def get_many(self, entity_ids: Iterable[_TKey]) -> list[_TCacheItem]: ...
|
|
17
|
+
async def find_many_as_dictionary(
|
|
18
|
+
self, entity_ids: Iterable[_TKey]
|
|
19
|
+
) -> dict[_TKey, _TCacheItem | None]: ...
|
|
20
|
+
async def get_many_as_dictionary(
|
|
21
|
+
self, entity_ids: Iterable[_TKey]
|
|
22
|
+
) -> dict[_TKey, _TCacheItem]: ...
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""实体缓存能力只声明其依赖;Host 继续选择缓存与仓储 provider。"""
|
|
2
|
+
|
|
3
|
+
from ..caching.module import CachingModule
|
|
4
|
+
from ..events.module import LocalEventsModule
|
|
5
|
+
from ..modularity import AppModule
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class EntityCachingModule(AppModule):
|
|
9
|
+
dependencies = (CachingModule, LocalEventsModule)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""将闭合实体缓存贡献到原生 DI 和本地事件,不另建服务注册表。"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from typing import Any, TypeVar, get_args
|
|
6
|
+
|
|
7
|
+
from dishka import Provider, Scope
|
|
8
|
+
from pydantic import TypeAdapter
|
|
9
|
+
|
|
10
|
+
from ..caching import DistributedCache, DistributedCacheEntryOptions
|
|
11
|
+
from ..diagnostics import LifecycleStage
|
|
12
|
+
from ..domain import Entity
|
|
13
|
+
from ..events import EntityChangedEvent, LocalEventPhase
|
|
14
|
+
from ..events.subscription import subscribe_local_event
|
|
15
|
+
from ..lifecycle import ConfigureContext
|
|
16
|
+
from ..services import Repository
|
|
17
|
+
from ..unit_of_work import UnitOfWorkManager
|
|
18
|
+
from .cache import _EntityCacheItem, _RepositoryEntityCache
|
|
19
|
+
from .contracts import EntityCache, _EntityCacheKey
|
|
20
|
+
from .module import EntityCachingModule
|
|
21
|
+
|
|
22
|
+
_TEntity = TypeVar("_TEntity")
|
|
23
|
+
_TCacheItem = TypeVar("_TCacheItem")
|
|
24
|
+
_TKey = TypeVar("_TKey", bound=_EntityCacheKey)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _validate_types(
|
|
28
|
+
entity_type: type[object], cache_item_type: type[object], key_type: type[object]
|
|
29
|
+
) -> None:
|
|
30
|
+
if not isinstance(entity_type, type) or not issubclass(entity_type, Entity):
|
|
31
|
+
raise TypeError("entity_type must derive from Entity")
|
|
32
|
+
for value in (entity_type, cache_item_type, key_type):
|
|
33
|
+
if value is Any or not isinstance(value, type) or getattr(value, "__parameters__", False):
|
|
34
|
+
raise TypeError("entity cache types must be closed classes")
|
|
35
|
+
# 可哈希不代表 JSON 编码与身份相等性一致;注册边界与公开类型约束共用来源。
|
|
36
|
+
if key_type not in get_args(_EntityCacheKey):
|
|
37
|
+
raise TypeError("entity cache key_type must be UUID, str, or int")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def add_entity_cache(
|
|
41
|
+
context: ConfigureContext,
|
|
42
|
+
entity_type: type[_TEntity],
|
|
43
|
+
cache_item_type: type[_TCacheItem],
|
|
44
|
+
key_type: type[_TKey],
|
|
45
|
+
*,
|
|
46
|
+
mapper: Callable[[_TEntity], _TCacheItem] | None = None,
|
|
47
|
+
options: DistributedCacheEntryOptions | None = None,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""在 configure 注册;替换使用现有 post 阶段 Provider OVERRIDE 仲裁。"""
|
|
50
|
+
context.services.require_active()
|
|
51
|
+
if context.stage is not LifecycleStage.CONFIGURE:
|
|
52
|
+
raise ValueError("entity cache registration requires the configure phase")
|
|
53
|
+
context.modules.require_dependency(
|
|
54
|
+
context.descriptor.key, EntityCachingModule, source=context.descriptor.declaration_source
|
|
55
|
+
)
|
|
56
|
+
_validate_types(entity_type, cache_item_type, key_type)
|
|
57
|
+
item_adapter: TypeAdapter[_TCacheItem] = TypeAdapter(cache_item_type)
|
|
58
|
+
key_adapter: TypeAdapter[_TKey] = TypeAdapter(key_type)
|
|
59
|
+
entry_options = (
|
|
60
|
+
options
|
|
61
|
+
if options is not None
|
|
62
|
+
else DistributedCacheEntryOptions(absolute_expiration_relative_to_now=timedelta(minutes=2))
|
|
63
|
+
)
|
|
64
|
+
name = f"{entity_type.__module__}.{entity_type.__qualname__}"
|
|
65
|
+
key_name = f"{key_type.__module__}.{key_type.__qualname__}"
|
|
66
|
+
|
|
67
|
+
def cache_key(identity: _TKey) -> str:
|
|
68
|
+
identity = key_adapter.validate_python(identity, strict=True)
|
|
69
|
+
encoded = key_adapter.dump_json(identity, warnings="error").decode()
|
|
70
|
+
# 实体与键类型参与命名;同 DTO 被不同实体使用也不能串值。
|
|
71
|
+
return f"{len(name)}:{name}:{len(key_name)}:{key_name}:{encoded}"
|
|
72
|
+
|
|
73
|
+
def entity_id(entity: _TEntity) -> _TKey:
|
|
74
|
+
if not isinstance(entity, entity_type) or not isinstance(entity, Entity):
|
|
75
|
+
raise TypeError("repository returned an unexpected entity type")
|
|
76
|
+
return key_adapter.validate_python(entity.id, strict=True)
|
|
77
|
+
|
|
78
|
+
def map_item(entity: _TEntity) -> _TCacheItem:
|
|
79
|
+
value = mapper(entity) if mapper is not None else entity
|
|
80
|
+
return item_adapter.validate_python(value, from_attributes=True)
|
|
81
|
+
|
|
82
|
+
def create(
|
|
83
|
+
repository: Repository[_TEntity, _TKey],
|
|
84
|
+
cache: DistributedCache[_EntityCacheItem[_TCacheItem]],
|
|
85
|
+
) -> EntityCache[_TCacheItem, _TKey]:
|
|
86
|
+
return _RepositoryEntityCache(
|
|
87
|
+
repository,
|
|
88
|
+
cache,
|
|
89
|
+
map_item=map_item,
|
|
90
|
+
entity_id=entity_id,
|
|
91
|
+
cache_key=cache_key,
|
|
92
|
+
options=entry_options,
|
|
93
|
+
entity_name=entity_type.__name__,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
async def invalidate(
|
|
97
|
+
event: EntityChangedEvent,
|
|
98
|
+
cache: DistributedCache[_EntityCacheItem[_TCacheItem]],
|
|
99
|
+
manager: UnitOfWorkManager,
|
|
100
|
+
) -> None:
|
|
101
|
+
if isinstance(event.entity, entity_type):
|
|
102
|
+
key = cache_key(entity_id(event.entity))
|
|
103
|
+
# 提交前先删;并发读可能回填旧值,因此仅在成功提交后再删一次。
|
|
104
|
+
await cache.remove(key)
|
|
105
|
+
if manager.current is not None:
|
|
106
|
+
await cache.remove(key, consider_uow=True)
|
|
107
|
+
|
|
108
|
+
# 原生工厂和函数订阅的动态注解只在此边界闭合;实例/scope/替换仍归 Dishka。
|
|
109
|
+
cache_contract = DistributedCache[_EntityCacheItem[cache_item_type]] # type: ignore[valid-type]
|
|
110
|
+
contract = EntityCache[cache_item_type, key_type] # type: ignore[valid-type]
|
|
111
|
+
create.__annotations__ = {
|
|
112
|
+
"repository": Repository[entity_type, key_type], # type: ignore[valid-type]
|
|
113
|
+
"cache": cache_contract,
|
|
114
|
+
"return": contract,
|
|
115
|
+
}
|
|
116
|
+
invalidate.__annotations__ = {
|
|
117
|
+
"event": EntityChangedEvent,
|
|
118
|
+
"cache": cache_contract,
|
|
119
|
+
"manager": UnitOfWorkManager,
|
|
120
|
+
"return": None,
|
|
121
|
+
}
|
|
122
|
+
provider = Provider()
|
|
123
|
+
provider.provide(create, provides=contract, scope=Scope.REQUEST)
|
|
124
|
+
context.services.contribute(provider, reason=f"Entity cache for {name}")
|
|
125
|
+
subscribe_local_event(
|
|
126
|
+
context,
|
|
127
|
+
EntityChangedEvent,
|
|
128
|
+
invalidate,
|
|
129
|
+
LocalEventPhase.DOMAIN,
|
|
130
|
+
reason=f"Entity cache invalidation for {name}",
|
|
131
|
+
)
|
|
@@ -2,15 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from
|
|
6
|
-
|
|
7
|
-
from ..domain import AggregateRoot
|
|
5
|
+
from ..domain import GeneratesLocalEvents
|
|
8
6
|
from ..unit_of_work.contracts import UnitOfWork
|
|
9
7
|
from .runtime import LocalEventBus
|
|
10
8
|
from .unit_of_work import _local_event_queue
|
|
11
9
|
|
|
12
|
-
_TId = TypeVar("_TId")
|
|
13
|
-
|
|
14
10
|
|
|
15
11
|
class AggregateEventCollector:
|
|
16
12
|
"""同一事件进入 DOMAIN 与 AFTER_COMMIT 队列,聚合只释放一次。"""
|
|
@@ -20,20 +16,17 @@ class AggregateEventCollector:
|
|
|
20
16
|
def __init__(self, events: LocalEventBus) -> None:
|
|
21
17
|
self._events = events
|
|
22
18
|
|
|
23
|
-
def collect(self, aggregate:
|
|
24
|
-
if not
|
|
25
|
-
raise TypeError("aggregate must
|
|
19
|
+
def collect(self, aggregate: GeneratesLocalEvents) -> tuple[object, ...]:
|
|
20
|
+
if GeneratesLocalEvents not in type(aggregate).__mro__:
|
|
21
|
+
raise TypeError("aggregate must declare GeneratesLocalEvents")
|
|
26
22
|
# 发布资格先于提取;拒绝非事务发布不能消耗聚合尚未交付的事件。
|
|
27
23
|
work = self._events._manager.require_current(transactional=True)
|
|
28
24
|
return _collect_aggregate_events(work, aggregate)
|
|
29
25
|
|
|
30
26
|
|
|
31
27
|
def _collect_aggregate_events(
|
|
32
|
-
work: UnitOfWork, aggregate:
|
|
28
|
+
work: UnitOfWork, aggregate: GeneratesLocalEvents
|
|
33
29
|
) -> tuple[object, ...]:
|
|
34
30
|
# 两个公开入口先验证事务 owner;收集不触发 flush,也不恢复已释放事件或自动重放。
|
|
35
31
|
queue = _local_event_queue(work)
|
|
36
|
-
|
|
37
|
-
for event in released:
|
|
38
|
-
queue.enqueue(event)
|
|
39
|
-
return released
|
|
32
|
+
return queue.collect_pending(aggregate)
|
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections import deque
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
6
7
|
from contextvars import ContextVar
|
|
7
8
|
from dataclasses import dataclass, field
|
|
8
9
|
from uuid import UUID, uuid4
|
|
9
10
|
|
|
10
11
|
from dishka import AsyncContainer, Scope
|
|
11
12
|
|
|
13
|
+
from ..domain import GeneratesLocalEvents
|
|
12
14
|
from ..invocation import ApplicationInvocationContext
|
|
13
15
|
from ..unit_of_work.manager import UnitOfWorkManager
|
|
14
16
|
from ..unit_of_work.options import _DEFAULT_CONNECTION_NAME
|
|
@@ -21,10 +23,9 @@ from .errors import EventCycleError, LocalEventHandlerError, PostCommitEventErro
|
|
|
21
23
|
class _EventEnvelope:
|
|
22
24
|
envelope_id: UUID
|
|
23
25
|
invocation_id: UUID
|
|
24
|
-
parent_envelope_id: UUID | None
|
|
25
26
|
event: object
|
|
26
27
|
event_type: type[object]
|
|
27
|
-
|
|
28
|
+
parents: tuple[_EventEnvelope, ...]
|
|
28
29
|
handled: set[object] = field(default_factory=set)
|
|
29
30
|
|
|
30
31
|
|
|
@@ -38,6 +39,8 @@ class _LocalEventQueue:
|
|
|
38
39
|
"_context",
|
|
39
40
|
"_current",
|
|
40
41
|
"_domain",
|
|
42
|
+
"_pending_origins",
|
|
43
|
+
"_save_changes",
|
|
41
44
|
)
|
|
42
45
|
|
|
43
46
|
def __init__(
|
|
@@ -52,11 +55,50 @@ class _LocalEventQueue:
|
|
|
52
55
|
self._domain: deque[_EventEnvelope] = deque()
|
|
53
56
|
self._after_commit: deque[_EventEnvelope] = deque()
|
|
54
57
|
self._current: _EventEnvelope | None = None
|
|
58
|
+
self._save_changes: Callable[[], Awaitable[None]] | None = None
|
|
59
|
+
self._pending_origins: dict[int, list[tuple[_EventEnvelope, ...]]] = {}
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def current_parents(self) -> tuple[_EventEnvelope, ...]:
|
|
63
|
+
return () if self._current is None else (self._current,)
|
|
64
|
+
|
|
65
|
+
def watch_source(self, source: GeneratesLocalEvents, guard: Callable[[], None]) -> None:
|
|
66
|
+
if id(source) in self._pending_origins:
|
|
67
|
+
return
|
|
68
|
+
self._pending_origins[id(source)] = [self.current_parents] * len(source._local_events)
|
|
69
|
+
|
|
70
|
+
def observe(index: int | None) -> None:
|
|
71
|
+
guard()
|
|
72
|
+
origins = self._pending_origins[id(source)]
|
|
73
|
+
if index is None:
|
|
74
|
+
origins.clear()
|
|
75
|
+
else:
|
|
76
|
+
origins.append(self.current_parents)
|
|
77
|
+
|
|
78
|
+
source._local_event_observer = observe
|
|
79
|
+
|
|
80
|
+
def forget_source(self, source: GeneratesLocalEvents) -> None:
|
|
81
|
+
self._pending_origins.pop(id(source), None)
|
|
82
|
+
source._local_event_observer = None
|
|
83
|
+
|
|
84
|
+
def collect_pending(self, source: GeneratesLocalEvents) -> tuple[object, ...]:
|
|
85
|
+
# 只复制来源,payload 仍只有领域对象中的唯一队列;释放后不恢复重放。
|
|
86
|
+
origins = tuple(self._pending_origins.get(id(source), ()))
|
|
87
|
+
parents = self.current_parents
|
|
88
|
+
released = source.release_local_events()
|
|
89
|
+
for index, event in enumerate(released):
|
|
90
|
+
self.enqueue(event, parents=origins[index] if index < len(origins) else parents)
|
|
91
|
+
return released
|
|
55
92
|
|
|
56
93
|
def enqueue(
|
|
57
|
-
self,
|
|
94
|
+
self,
|
|
95
|
+
event: object,
|
|
96
|
+
phase: LocalEventPhase | None = None,
|
|
97
|
+
*,
|
|
98
|
+
defer_domain: bool = True,
|
|
99
|
+
parents: tuple[_EventEnvelope, ...] | None = None,
|
|
58
100
|
) -> _EventEnvelope:
|
|
59
|
-
envelope = self._envelope(event)
|
|
101
|
+
envelope = self._envelope(event, parents)
|
|
60
102
|
if phase is not LocalEventPhase.AFTER_COMMIT and defer_domain:
|
|
61
103
|
self._domain.append(envelope)
|
|
62
104
|
if phase is not LocalEventPhase.DOMAIN:
|
|
@@ -64,6 +106,8 @@ class _LocalEventQueue:
|
|
|
64
106
|
return envelope
|
|
65
107
|
|
|
66
108
|
async def before_commit(self) -> None:
|
|
109
|
+
if not self._domain:
|
|
110
|
+
return
|
|
67
111
|
request = (
|
|
68
112
|
self._action_container.parent_container
|
|
69
113
|
if self._action_container.scope is Scope.ACTION
|
|
@@ -74,7 +118,16 @@ class _LocalEventQueue:
|
|
|
74
118
|
from ..invocation.scopes import _managed_action
|
|
75
119
|
|
|
76
120
|
async with _managed_action(request, self._context, committed=lambda: False) as action:
|
|
77
|
-
await
|
|
121
|
+
manager = await action.get(UnitOfWorkManager)
|
|
122
|
+
self._save_changes = manager.require_current().flush
|
|
123
|
+
try:
|
|
124
|
+
await self._drain_domain(action)
|
|
125
|
+
finally:
|
|
126
|
+
self._save_changes = None
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def has_pending(self) -> bool:
|
|
130
|
+
return bool(self._domain)
|
|
78
131
|
|
|
79
132
|
async def _drain_domain(self, action: AsyncContainer) -> None:
|
|
80
133
|
while self._domain:
|
|
@@ -113,19 +166,28 @@ class _LocalEventQueue:
|
|
|
113
166
|
if failures:
|
|
114
167
|
raise PostCommitEventError(failures=tuple(failures))
|
|
115
168
|
|
|
116
|
-
def _envelope(
|
|
169
|
+
def _envelope(
|
|
170
|
+
self, event: object, parents: tuple[_EventEnvelope, ...] | None = None
|
|
171
|
+
) -> _EventEnvelope:
|
|
117
172
|
event_type = type(event)
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
173
|
+
parents = self.current_parents if parents is None else parents
|
|
174
|
+
pending: list[tuple[_EventEnvelope, tuple[type[object], ...]]] = [
|
|
175
|
+
(parent, (parent.event_type,)) for parent in parents
|
|
176
|
+
]
|
|
177
|
+
seen: set[UUID] = set()
|
|
178
|
+
while pending:
|
|
179
|
+
ancestor, path = pending.pop()
|
|
180
|
+
if ancestor.event_type is event_type:
|
|
181
|
+
raise EventCycleError(event_type=event_type, ancestry=path)
|
|
182
|
+
if ancestor.envelope_id not in seen:
|
|
183
|
+
seen.add(ancestor.envelope_id)
|
|
184
|
+
pending.extend((parent, (parent.event_type, *path)) for parent in ancestor.parents)
|
|
122
185
|
return _EventEnvelope(
|
|
123
186
|
envelope_id=uuid4(),
|
|
124
187
|
invocation_id=self._context.invocation_id,
|
|
125
|
-
parent_envelope_id=parent.envelope_id if parent is not None else None,
|
|
126
188
|
event=event,
|
|
127
189
|
event_type=event_type,
|
|
128
|
-
|
|
190
|
+
parents=parents,
|
|
129
191
|
)
|
|
130
192
|
|
|
131
193
|
async def dispatch(self, event: object, phase: LocalEventPhase | None) -> None:
|
|
@@ -171,22 +233,26 @@ class _LocalEventQueue:
|
|
|
171
233
|
previous = self._current
|
|
172
234
|
self._current = envelope
|
|
173
235
|
try:
|
|
174
|
-
|
|
175
|
-
|
|
236
|
+
try:
|
|
237
|
+
from ..invocation.interception import _EntryInterceptionCatalog
|
|
238
|
+
from ..invocation.runtime import _InvocationRuntime
|
|
176
239
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
240
|
+
entries = await container.get(_EntryInterceptionCatalog)
|
|
241
|
+
runtime = await container.get(_InvocationRuntime)
|
|
242
|
+
await entries.invoke(
|
|
243
|
+
runtime, container, subscription.handler_type, "handle", (envelope.event,)
|
|
244
|
+
)
|
|
245
|
+
except Exception as original_error:
|
|
246
|
+
error = LocalEventHandlerError(
|
|
247
|
+
event_type=envelope.event_type,
|
|
248
|
+
handler_type=subscription.handler_type,
|
|
249
|
+
original_error=original_error,
|
|
250
|
+
committed=committed,
|
|
251
|
+
)
|
|
252
|
+
raise error from original_error
|
|
253
|
+
if self._save_changes is not None:
|
|
254
|
+
# 在父 envelope 仍有效时保存,派生事件跨刷新仍继承因果与循环检测。
|
|
255
|
+
await self._save_changes()
|
|
190
256
|
finally:
|
|
191
257
|
self._current = previous
|
|
192
258
|
|
|
@@ -4,6 +4,7 @@ from .contracts import (
|
|
|
4
4
|
ExtensionPoints,
|
|
5
5
|
ExtensionProperties,
|
|
6
6
|
ExtensionTarget,
|
|
7
|
+
HasExtraProperties,
|
|
7
8
|
ModelExtension,
|
|
8
9
|
ModelExtensions,
|
|
9
10
|
)
|
|
@@ -17,6 +18,7 @@ __all__ = (
|
|
|
17
18
|
"ExtensionProperties",
|
|
18
19
|
"ExtensionTarget",
|
|
19
20
|
"ExtensionsModule",
|
|
21
|
+
"HasExtraProperties",
|
|
20
22
|
"ModelExtension",
|
|
21
23
|
"ModelExtensions",
|
|
22
24
|
)
|
|
@@ -126,6 +126,10 @@ class ExtensionCatalog:
|
|
|
126
126
|
def property_model(self, target: ExtensionTarget) -> type[ExtensionProperties]:
|
|
127
127
|
return self._properties[target]
|
|
128
128
|
|
|
129
|
+
@property
|
|
130
|
+
def targets(self) -> tuple[ExtensionTarget, ...]:
|
|
131
|
+
return tuple(self._properties)
|
|
132
|
+
|
|
129
133
|
def annotation(self, annotation: object) -> object:
|
|
130
134
|
return self._models.annotation(annotation)
|
|
131
135
|
|