python-event-sourcery 0.5.1a4__py3-none-any.whl → 0.5.2__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.
@@ -73,6 +73,7 @@ class Event(BaseModel, extra="forbid"):
73
73
 
74
74
 
75
75
  TEvent = TypeVar("TEvent", bound=Event)
76
+ TContext = TypeVar("TContext", bound=BaseModel)
76
77
 
77
78
 
78
79
  class Context(BaseModel, extra="allow"):
@@ -127,8 +128,18 @@ class WrappedEvent(Generic[TEvent]):
127
128
  context: Context = dataclasses.field(default_factory=Context)
128
129
 
129
130
  @classmethod
130
- def wrap(cls, event: TEvent, version: int | None) -> "WrappedEvent[TEvent]":
131
- return WrappedEvent[TEvent](event=event, version=version)
131
+ def wrap(
132
+ cls,
133
+ event: TEvent,
134
+ version: int | None,
135
+ context: Context | None = None,
136
+ ) -> "WrappedEvent[TEvent]":
137
+ return WrappedEvent[TEvent](
138
+ event=event, version=version, context=context or Context()
139
+ )
140
+
141
+ def get_context(self, context_type: type[TContext]) -> TContext:
142
+ return context_type.model_validate(self.context.model_dump())
132
143
 
133
144
 
134
145
  @dataclasses.dataclass(frozen=True)
@@ -1,7 +1,8 @@
1
1
  __all__ = [
2
2
  "Aggregate",
3
3
  "Repository",
4
+ "WrappedAggregate",
4
5
  ]
5
6
 
6
- from event_sourcery.event_sourcing.aggregate import Aggregate
7
+ from event_sourcery.event_sourcing.aggregate import Aggregate, WrappedAggregate
7
8
  from event_sourcery.event_sourcing.repository import Repository
@@ -1,9 +1,11 @@
1
+ import dataclasses
1
2
  from collections.abc import Iterator
2
3
  from contextlib import contextmanager
3
- from typing import ClassVar
4
+ from datetime import datetime
5
+ from typing import ClassVar, Generic, TypeVar
4
6
 
5
- from event_sourcery import StreamCategory
6
- from event_sourcery.event import Event
7
+ from event_sourcery import StreamCategory, StreamId
8
+ from event_sourcery.event import Context, Event
7
9
 
8
10
 
9
11
  class Aggregate:
@@ -19,12 +21,16 @@ class Aggregate:
19
21
 
20
22
  Attributes:
21
23
  category (ClassVar[StreamCategory]): StreamCategory for the aggregate type (group streams).
22
- _changes (list[Event]): List of yet not persisted events.
24
+ __changes__ (list[Event]): List of yet not persisted events.
23
25
  """
24
26
 
25
27
  category: ClassVar[StreamCategory]
26
28
  _changes: list[Event]
27
29
 
30
+ @property
31
+ def __changes__(self) -> list[Event]:
32
+ return list(getattr(self, "_changes", []))
33
+
28
34
  @contextmanager
29
35
  def __persisting_changes__(self) -> Iterator[Iterator[Event]]:
30
36
  """
@@ -36,8 +42,7 @@ class Aggregate:
36
42
  Returns:
37
43
  Iterator[Iterator[Event]]: Iterator over unpersisted events.
38
44
  """
39
- yield iter(getattr(self, "_changes", []))
40
- self._changes = []
45
+ yield iter(self.__changes__)
41
46
 
42
47
  def __apply__(self, event: Event) -> None:
43
48
  """
@@ -65,3 +70,54 @@ class Aggregate:
65
70
  self._changes = []
66
71
  self.__apply__(event)
67
72
  self._changes.append(event)
73
+
74
+
75
+ TAggregate = TypeVar("TAggregate", bound=Aggregate)
76
+ TContext = TypeVar("TContext", bound=Context)
77
+
78
+
79
+ @dataclasses.dataclass()
80
+ class WrappedAggregate(Generic[TAggregate]):
81
+ """
82
+ Wraps an aggregate instance with stream-level metadata.
83
+
84
+ Provides access to the aggregate alongside information such as version,
85
+ timestamps, and whether the aggregate is newly created. Follows the same
86
+ wrapper pattern as ``WrappedEvent``.
87
+
88
+ Attributes:
89
+ aggregate: The aggregate instance.
90
+ stream_id: The stream identity (UUID + category).
91
+ context: The context passed for this operation, if any.
92
+ created_at: Timestamp of the first event in the stream.
93
+ updated_at: Timestamp of the last event in the stream.
94
+ stored_version: Number of events persisted before this session.
95
+ """
96
+
97
+ aggregate: TAggregate
98
+ stream_id: StreamId
99
+ context: Context = dataclasses.field(default_factory=Context)
100
+ stored_version: int = 0
101
+ created_at: datetime | None = None
102
+ updated_at: datetime | None = None
103
+
104
+ @property
105
+ def version(self) -> int:
106
+ """Current version of the aggregate, including pending events."""
107
+ return self.stored_version + len(getattr(self.aggregate, "__changes__", []))
108
+
109
+ @property
110
+ def is_new(self) -> bool:
111
+ """Whether the aggregate is newly created (no events existed before)."""
112
+ return self.stored_version == 0
113
+
114
+ def get_context(self, context_type: type[TContext]) -> TContext:
115
+ """Convert the stored context to a specific context type.
116
+
117
+ Args:
118
+ context_type: The target context class to validate against.
119
+
120
+ Returns:
121
+ An instance of *context_type* populated from the stored context data.
122
+ """
123
+ return context_type.model_validate(self.context.model_dump())
@@ -3,8 +3,9 @@ from contextlib import contextmanager
3
3
  from typing import Generic, TypeVar, cast
4
4
 
5
5
  from event_sourcery import EventStore, StreamId, StreamUUID
6
- from event_sourcery.event import Event, WrappedEvent
6
+ from event_sourcery.event import Context, Event, WrappedEvent
7
7
  from event_sourcery.event_sourcing import Aggregate
8
+ from event_sourcery.event_sourcing.aggregate import WrappedAggregate
8
9
 
9
10
  TAggregate = TypeVar("TAggregate", bound=Aggregate)
10
11
  TEvent = TypeVar("TEvent", bound=Event)
@@ -27,45 +28,48 @@ class Repository(Generic[TAggregate]):
27
28
  self,
28
29
  uuid: StreamUUID,
29
30
  aggregate: TAggregate,
30
- ) -> Iterator[TAggregate]:
31
+ context: Context | None = None,
32
+ ) -> Iterator[WrappedAggregate[TAggregate]]:
31
33
  """
32
34
  Context manager for loading an aggregate instance.
33
35
 
34
36
  Loads the aggregate's event stream, replays events to reconstruct its state,
35
- yields the aggregate for use, and persists any new events emitted during the
36
- context.
37
+ yields a ``WrappedAggregate`` containing the aggregate and stream metadata,
38
+ and persists any new events emitted during the context.
37
39
 
38
40
  Args:
39
41
  uuid (StreamUUID): The unique identifier of the aggregate's stream.
40
42
  aggregate (TAggregate): The aggregate initial instance to load state into.
43
+ context (Context | None): Optional context to attach to all emitted events.
41
44
 
42
45
  Yields:
43
- TAggregate: The loaded and ready-to-use aggregate instance.
46
+ WrappedAggregate[TAggregate]: The aggregate wrapped with stream metadata.
44
47
  """
45
48
  stream_id = StreamId(uuid=uuid, name=uuid.name, category=aggregate.category)
46
- old_version = self._load(stream_id, aggregate)
47
- yield aggregate
48
- self._save(aggregate, old_version, stream_id)
49
49
 
50
- def _load(self, stream_id: StreamId, aggregate: TAggregate) -> int:
51
- stream = self._event_store.load_stream(stream_id)
52
- last_version = 0
53
- for envelope in stream:
54
- aggregate.__apply__(envelope.event)
55
- last_version = cast(int, envelope.version)
50
+ wrapped = WrappedAggregate(
51
+ aggregate=aggregate,
52
+ stream_id=stream_id,
53
+ context=context or Context(),
54
+ )
55
+ self._load(wrapped)
56
+ yield wrapped
57
+ self._save(wrapped)
56
58
 
57
- return last_version
59
+ def _load(self, wrapped: WrappedAggregate[TAggregate]) -> None:
60
+ stream = self._event_store.load_stream(wrapped.stream_id)
61
+ for envelope in stream:
62
+ wrapped.aggregate.__apply__(envelope.event)
63
+ wrapped.stored_version = cast(int, envelope.version)
64
+ if wrapped.created_at is None:
65
+ wrapped.created_at = envelope.created_at
66
+ wrapped.updated_at = envelope.created_at
58
67
 
59
- def _save(
60
- self,
61
- aggregate: TAggregate,
62
- old_version: int,
63
- stream_id: StreamId,
64
- ) -> None:
65
- with aggregate.__persisting_changes__() as pending:
66
- start_from = old_version + 1
68
+ def _save(self, wrapped: WrappedAggregate[TAggregate]) -> None:
69
+ with wrapped.aggregate.__persisting_changes__() as pending:
70
+ start_from = wrapped.stored_version + 1
67
71
  events = [
68
- WrappedEvent.wrap(event, version)
72
+ WrappedEvent.wrap(event, version, context=wrapped.context)
69
73
  for version, event in enumerate(pending, start=start_from)
70
74
  ]
71
75
 
@@ -74,6 +78,6 @@ class Repository(Generic[TAggregate]):
74
78
 
75
79
  self._event_store.append(
76
80
  *events,
77
- stream_id=stream_id,
78
- expected_version=old_version,
81
+ stream_id=wrapped.stream_id,
82
+ expected_version=wrapped.stored_version,
79
83
  )
@@ -1,7 +1,7 @@
1
1
  from typing import Protocol
2
2
 
3
3
  from sqlalchemy import MetaData
4
- from sqlalchemy.orm import registry
4
+ from sqlalchemy.orm import DeclarativeBase, registry
5
5
  from sqlalchemy.orm.clsregistry import ClsRegistryToken
6
6
 
7
7
  from event_sourcery_sqlalchemy.models.base import (
@@ -28,7 +28,7 @@ _class_registry: dict[str, type | ClsRegistryToken] = {}
28
28
 
29
29
 
30
30
  def configure_models(
31
- base: type[BaseProto],
31
+ base: type[BaseProto | DeclarativeBase],
32
32
  event_model: type[BaseEvent] = DefaultEvent,
33
33
  stream_model: type[BaseStream] = DefaultStream,
34
34
  snapshot_model: type[BaseSnapshot] = DefaultSnapshot,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: python-event-sourcery
3
- Version: 0.5.1a4
3
+ Version: 0.5.2
4
4
  Summary: A library for event-based systems in Python.
5
5
  License: MIT
6
6
  Author: Sebastian Buczyński
@@ -2,7 +2,7 @@ event_sourcery/__init__.py,sha256=gPheLaW9KCkRAINF28lVep9KZQnT_cLwj_7BZjLtBr8,69
2
2
  event_sourcery/_event_store/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
3
  event_sourcery/_event_store/backend.py,sha256=hTNUvbqAkKhy058ytxdtQcU7rp4Svd8AVNKaC8wJ-hc,7036
4
4
  event_sourcery/_event_store/event/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
- event_sourcery/_event_store/event/dto.py,sha256=G7VnVWxbsqJMmfog1AiRVoP4FNJ_52cYgjQS74EzTRU,6184
5
+ event_sourcery/_event_store/event/dto.py,sha256=FTvvCd_unm3Lw0x3knCpjf8beUNfNIw3que1vDYxHWw,6495
6
6
  event_sourcery/_event_store/event/encryption.py,sha256=CIUqcBN7NdQkUiFbG92ewB1jasRK-nvpTONXZrP9s88,8419
7
7
  event_sourcery/_event_store/event/registry.py,sha256=zozQkvRVhlUSwqmjlZqZtBOXTt6yVO0MJtbpxv8fu_Y,4026
8
8
  event_sourcery/_event_store/event/serde.py,sha256=a-QF5lDAoSC7pPPEyAD7aPz39cHtB6aykJ0WkWdkKbQ,2403
@@ -19,9 +19,9 @@ event_sourcery/_event_store/versioning.py,sha256=-e0OTmoQXm6e2V3_c95V95RuBPgb4Ku
19
19
  event_sourcery/backend.py,sha256=Hq-x8HBTr_v8LWBOTNv4m2KtcV6dPNm7XPGZ80G_Iss,413
20
20
  event_sourcery/encryption.py,sha256=MyzuknP1x9Qx-2wTOzu4yCepvN7o0s90lB8FMhpecx0,340
21
21
  event_sourcery/event.py,sha256=Cyqcl04zohcJ-4e3t_J6h4dKg1ZOazOAlta29Zi_ubY,471
22
- event_sourcery/event_sourcing/__init__.py,sha256=W81aRvYniw4_2Pwqhv44I5cwyezTV5QStmDSG4XWQXc,176
23
- event_sourcery/event_sourcing/aggregate.py,sha256=EDWBre4HtFocakibqNxYJTAnlgFyQqeU_5CG0PuideY,2207
24
- event_sourcery/event_sourcing/repository.py,sha256=wFEt0dx_4g_OPqwTypyQUrvxksywOaWhFEvEm7K3mtg,2587
22
+ event_sourcery/event_sourcing/__init__.py,sha256=p6jcxZzJztZP6_YqqkNHRvWaVyuUrETlMRIUiqcQrFE,218
23
+ event_sourcery/event_sourcing/aggregate.py,sha256=62B7jSxbFGGPQpdpAL2KGrSg9glHeOproVovy2vbqJA,4186
24
+ event_sourcery/event_sourcing/repository.py,sha256=bWHATdBZcJyl9IIM0O28X3YKGU-zRo3sYYZ6zybZnKQ,3093
25
25
  event_sourcery/exceptions.py,sha256=asE9qwi0dDByrRTs01BaN5SYtf4rasKFU47IDhV_0jY,1037
26
26
  event_sourcery/in_transaction.py,sha256=wmWJ67Pts0TBRWq0VWTnCyECyfuXHKw7KZTOfittzFU,183
27
27
  event_sourcery/interfaces.py,sha256=XAuWIDO5o95NfGRxu9_cXcxMI2AKTbD1s6Oh2E2QfnE,645
@@ -53,13 +53,13 @@ event_sourcery_sqlalchemy/dto.py,sha256=Q9wkni0rAF6fx65kYKK6xRADAAcBCGTE5ms00QSc
53
53
  event_sourcery_sqlalchemy/event_store.py,sha256=WN0pU9Bjb9w9R2o0sEGEPxMjfAnvePSAEVjuWGnwNAo,8882
54
54
  event_sourcery_sqlalchemy/guid.py,sha256=OnDd50YHxiARgWtDylcwydcaxxd6-nn9su9b_imsuJU,1179
55
55
  event_sourcery_sqlalchemy/jsonb.py,sha256=fvrn60ECqJFjVF6E613IOPgXt-twuSqUtDuyMltO-ac,806
56
- event_sourcery_sqlalchemy/models/__init__.py,sha256=9SY9t9vmjbpj4Wr1WFpO5_vFuDICMTiEQbBhNZDN3Dk,2817
56
+ event_sourcery_sqlalchemy/models/__init__.py,sha256=oEqiEwDclR0l3m5GKldy-XX5Dlh4BI0f-7Mf8KclI2I,2852
57
57
  event_sourcery_sqlalchemy/models/base.py,sha256=zOpI829M53MKLYyU0KmjxcVMvM_rqMKgFxlKCBnl_-s,7783
58
58
  event_sourcery_sqlalchemy/models/default.py,sha256=gPo3dAV4mR38qb7jBqedsgT7gCawZ-1DKUSfEm6r-Ts,597
59
59
  event_sourcery_sqlalchemy/outbox.py,sha256=gYiT621xFqxMF9yBFTcwIGvwGGZtX0vsNKnRciEcqRs,3396
60
60
  event_sourcery_sqlalchemy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
61
61
  event_sourcery_sqlalchemy/subscription.py,sha256=5g0p1BoGrfeolA1IZZ5PLfs0fmHP9AYVnBwRvr0U2F4,6800
62
- python_event_sourcery-0.5.1a4.dist-info/LICENSE,sha256=ufzizVlKJ_TRa5OZMIHzSrciFMdlx7ec29nUPLSe_zQ,1077
63
- python_event_sourcery-0.5.1a4.dist-info/METADATA,sha256=veGuv3TZ4Y3RdEu_oBQ6trEGZpzrJGBCr-0wmQRCgY0,4922
64
- python_event_sourcery-0.5.1a4.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88
65
- python_event_sourcery-0.5.1a4.dist-info/RECORD,,
62
+ python_event_sourcery-0.5.2.dist-info/LICENSE,sha256=ufzizVlKJ_TRa5OZMIHzSrciFMdlx7ec29nUPLSe_zQ,1077
63
+ python_event_sourcery-0.5.2.dist-info/METADATA,sha256=ORmH7r2YNCulscgF-EUsk5aJEox40VIKTipD3zzKluY,4920
64
+ python_event_sourcery-0.5.2.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88
65
+ python_event_sourcery-0.5.2.dist-info/RECORD,,