Skip to content

Commit 5134da9

Browse files
author
Sergio García Prado
authored
Merge pull request #185 from minos-framework/0.5.3
0.5.3
2 parents d063903 + e457d62 commit 5134da9

File tree

60 files changed

+1603
-1241
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+1603
-1241
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ services:
104104
depends_on:
105105
- zookeeper
106106
environment:
107-
KAFKA_ADVERTISED_HOST_NAME: kafka
107+
KAFKA_ADVERTISED_HOST_NAME: localhost
108108
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
109109
postgres:
110110
restart: always
@@ -715,7 +715,7 @@ Execute the following command to start the microservice:
715715
python foo/main.py
716716
```
717717

718-
Now, if a new instance is created (with a rest call, like in the [previous section](#Expose a Command)), the `FooCreated` event will be handled and the microservice's console will print something like:
718+
Now, if a new instance is created (with a rest call, like in the [previous section](#expose-a-command)), the `FooCreated` event will be handled and the microservice's console will print something like:
719719

720720
```
721721
A Foo was created: Event(...)

packages/core/minos-microservice-aggregate/HISTORY.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,12 @@
7676
* Add `get_all` method to `RootEntity` and `SnapshotRepository` to get all the stored instance on the repository.
7777
* Rename `SnapshotService` command topics to avoid collisions with application-level topics.
7878
* Rename `TransactionService` command topics to avoid collisions with application-level topics.
79-
* Minor changes.
79+
* Minor changes.
80+
81+
0.5.3 (2022-03-04)
82+
------------------
83+
84+
* Add `RefException` to be raised when some reference cannot be resolved.
85+
* Improve attribute and item accessors of `Ref`, `Event` and `FieldDiffContainer`
86+
* Deprecate `Event.get_one` in favor of `Event.get_field`.
87+
* Deprecate `Event.get_all` in favor of `Event.get_fields`.

packages/core/minos-microservice-aggregate/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
.PHONY: docs
1+
.PHONY: docs dist
22

33
lint:
44
poetry run flake8

packages/core/minos-microservice-aggregate/minos/aggregate/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
__author__ = "Minos Framework Devs"
22
__email__ = "[email protected]"
3-
__version__ = "0.5.2"
3+
__version__ = "0.5.3"
44

55
from .actions import (
66
Action,
@@ -42,6 +42,7 @@
4242
EventRepositoryConflictException,
4343
EventRepositoryException,
4444
NotFoundException,
45+
RefException,
4546
SnapshotRepositoryConflictException,
4647
SnapshotRepositoryException,
4748
TransactionNotFoundException,

packages/core/minos-microservice-aggregate/minos/aggregate/entities/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ def from_diff(cls: Type[T], event: Event, *args, **kwargs) -> T:
349349
version=event.version,
350350
created_at=event.created_at,
351351
updated_at=event.created_at,
352-
**event.get_all(),
352+
**event.get_fields(),
353353
**kwargs,
354354
)
355355

packages/core/minos-microservice-aggregate/minos/aggregate/entities/refs/models.py

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
annotations,
33
)
44

5+
import logging
56
from typing import (
67
Any,
78
Generic,
@@ -39,7 +40,11 @@
3940
from ...contextvars import (
4041
IS_REPOSITORY_SERIALIZATION_CONTEXT_VAR,
4142
)
43+
from ...exceptions import (
44+
RefException,
45+
)
4246

47+
logger = logging.getLogger(__name__)
4348
MT = TypeVar("MT", bound=Model)
4449

4550

@@ -56,13 +61,55 @@ def __init__(self, data: Union[MT, UUID], *args, broker_pool: BrokerClientPool =
5661

5762
self._broker_pool = broker_pool
5863

64+
def __setitem__(self, key: str, value: Any) -> None:
65+
try:
66+
return super().__setitem__(key, value)
67+
except KeyError as exc:
68+
if key == "uuid":
69+
self.data = value
70+
return
71+
72+
try:
73+
self.data[key] = value
74+
except Exception:
75+
raise exc
76+
77+
def __getitem__(self, item: str) -> Any:
78+
try:
79+
return super().__getitem__(item)
80+
except KeyError as exc:
81+
if item == "uuid":
82+
return self.uuid
83+
84+
try:
85+
return self.data[item]
86+
except Exception:
87+
raise exc
88+
89+
def __setattr__(self, key: str, value: Any) -> None:
90+
try:
91+
return super().__setattr__(key, value)
92+
except AttributeError as exc:
93+
if key == "uuid":
94+
self.data = value
95+
return
96+
97+
try:
98+
setattr(self.data, key, value)
99+
except Exception:
100+
raise exc
101+
59102
def __getattr__(self, item: str) -> Any:
60103
try:
61104
return super().__getattr__(item)
62105
except AttributeError as exc:
63-
if item != "data":
106+
if item == "data":
107+
raise exc
108+
109+
try:
64110
return getattr(self.data, item)
65-
raise exc
111+
except Exception:
112+
raise exc
66113

67114
@property
68115
def int(self) -> int:
@@ -146,6 +193,14 @@ def uuid(self) -> UUID:
146193
return self.data
147194
return self.data.uuid
148195

196+
@uuid.setter
197+
def uuid(self, value: UUID) -> None:
198+
"""Set the uuid that identifies the ``Model``.
199+
200+
:return: This method does not return anything.
201+
"""
202+
raise RuntimeError("The 'uuid' must be set through the '__setattr__' method.") # pragma: no cover
203+
149204
@property
150205
def data_cls(self) -> Optional[type]:
151206
"""Get data class if available.
@@ -178,6 +233,8 @@ async def resolve(self, force: bool = False, **kwargs) -> None:
178233
@staticmethod
179234
async def _get_response(broker: BrokerClient, **kwargs) -> MT:
180235
message = await broker.receive(**kwargs)
236+
if not message.ok:
237+
raise RefException(f"The received message is not ok: {message!r}")
181238
return message.content
182239

183240
@property

packages/core/minos-microservice-aggregate/minos/aggregate/entities/refs/resolvers.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from asyncio import (
23
gather,
34
)
@@ -29,13 +30,18 @@
2930
BrokerMessageV1Payload,
3031
)
3132

33+
from ...exceptions import (
34+
RefException,
35+
)
3236
from .extractors import (
3337
RefExtractor,
3438
)
3539
from .injectors import (
3640
RefInjector,
3741
)
3842

43+
logger = logging.getLogger(__name__)
44+
3945

4046
class RefResolver:
4147
"""Ref Resolver class."""
@@ -76,5 +82,10 @@ async def _query(self, references: dict[str, set[UUID]]) -> dict[UUID, Model]:
7682

7783
@staticmethod
7884
async def _get_response(broker: BrokerClient, count: int, **kwargs) -> Iterable[Model]:
79-
messages = [message async for message in broker.receive_many(count, **kwargs)]
85+
messages = list()
86+
async for message in broker.receive_many(count, **kwargs):
87+
if not message.ok:
88+
raise RefException(f"The received message is not ok: {message!r}")
89+
messages.append(message)
90+
8091
return chain(*(message.content for message in messages))

packages/core/minos-microservice-aggregate/minos/aggregate/events/fields.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,10 @@ def __init__(
9393

9494
self._mapper = _build_mapper(self._fields)
9595

96-
def __getattr__(self, item: str) -> Any:
96+
def __getitem__(self, item: str) -> Any:
9797
try:
98-
return super().__getattr__(item)
99-
except AttributeError as exc:
98+
return super().__getitem__(item)
99+
except KeyError as exc:
100100
try:
101101
return self.get_one(item)
102102
except Exception:

packages/core/minos-microservice-aggregate/minos/aggregate/events/models.py

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
)
44

55
import logging
6+
import warnings
67
from datetime import (
78
datetime,
89
)
@@ -64,20 +65,40 @@ def simplified_name(self) -> str:
6465
def __lt__(self, other: Any) -> bool:
6566
return isinstance(other, type(self)) and self.version < other.version
6667

67-
def __getattr__(self, item: str) -> Any:
68+
def __getitem__(self, item: str) -> Any:
6869
try:
69-
return super().__getattr__(item)
70-
except AttributeError as exc:
70+
return super().__getitem__(item)
71+
except KeyError as exc:
7172
if item != "fields_diff":
7273
try:
73-
return self.get_one(item)
74+
return self.get_field(item)
7475
except Exception:
7576
raise exc
7677
raise exc
7778

79+
def __getattr__(self, item: str) -> Any:
80+
try:
81+
return super().__getattr__(item)
82+
except AttributeError as exc:
83+
try:
84+
return self[item]
85+
except Exception:
86+
raise exc
87+
7888
def get_one(self, name: str, return_diff: bool = False) -> Union[FieldDiff, Any, list[FieldDiff], list[Any]]:
7989
"""Get first field diff with given name.
8090
91+
:param name: The name of the field diff.
92+
:param return_diff: If ``True`` the result is returned as field diff instances, otherwise the result is
93+
returned as value instances.
94+
:return: A ``FieldDiff`` instance.
95+
"""
96+
warnings.warn("get_one() method is deprecated by get_field() and will be removed soon.", DeprecationWarning)
97+
return self.get_field(name, return_diff)
98+
99+
def get_field(self, name: str, return_diff: bool = False) -> Union[FieldDiff, Any, list[FieldDiff], list[Any]]:
100+
"""Get first field diff with given name.
101+
81102
:param name: The name of the field diff.
82103
:param return_diff: If ``True`` the result is returned as field diff instances, otherwise the result is
83104
returned as value instances.
@@ -88,6 +109,16 @@ def get_one(self, name: str, return_diff: bool = False) -> Union[FieldDiff, Any,
88109
def get_all(self, return_diff: bool = False) -> dict[str, Union[FieldDiff, Any, list[FieldDiff], list[Any]]]:
89110
"""Get all field diffs with given name.
90111
112+
:param return_diff: If ``True`` the result is returned as field diff instances, otherwise the result is
113+
returned as value instances.
114+
:return: A list of ``FieldDiff`` instances.
115+
"""
116+
warnings.warn("get_all() method is deprecated by get_fields() and will be removed soon.", DeprecationWarning)
117+
return self.get_fields(return_diff)
118+
119+
def get_fields(self, return_diff: bool = False) -> dict[str, Union[FieldDiff, Any, list[FieldDiff], list[Any]]]:
120+
"""Get all field diffs with given name.
121+
91122
:param return_diff: If ``True`` the result is returned as field diff instances, otherwise the result is
92123
returned as value instances.
93124
:return: A list of ``FieldDiff`` instances.

packages/core/minos-microservice-aggregate/minos/aggregate/exceptions.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from .entities import (
1515
RootEntity,
1616
)
17-
from .models import (
17+
from .events import (
1818
Event,
1919
)
2020

@@ -73,3 +73,7 @@ class AlreadyDeletedException(SnapshotRepositoryException):
7373

7474
class ValueObjectException(AggregateException):
7575
"""If an attribute of an immutable class is modified, this exception will be raised"""
76+
77+
78+
class RefException(AggregateException):
79+
"""Exception to be raised when some reference can not be resolved."""

0 commit comments

Comments
 (0)