explicit-python 2.5.0__py3-none-any.whl → 3.1.0__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.
- explicit/adapters/db.py +8 -5
- explicit/adapters/fs.py +4 -2
- explicit/adapters/messaging.py +5 -3
- explicit/contrib/domain/model/__init__.py +5 -2
- explicit/contrib/domain/model/fields.py +11 -10
- explicit/contrib/messagebus/event_registry.py +19 -13
- explicit/domain/__init__.py +48 -22
- explicit/domain/factories.py +8 -8
- explicit/domain/fields.py +62 -4
- explicit/domain/model.py +66 -58
- explicit/domain/types.py +17 -13
- explicit/domain/validation/exceptions.py +31 -20
- explicit/messagebus/__init__.py +3 -1
- explicit/messagebus/commands.py +24 -34
- explicit/messagebus/dependency_injection.py +13 -13
- explicit/messagebus/events.py +47 -47
- explicit/messagebus/exceptions.py +3 -1
- explicit/messagebus/messagebus.py +24 -15
- explicit/messagebus/queries.py +15 -16
- explicit/unit_of_work.py +15 -25
- {explicit_python-2.5.0.dist-info → explicit_python-3.1.0.dist-info}/METADATA +10 -9
- explicit_python-3.1.0.dist-info/RECORD +31 -0
- explicit_python-2.5.0.dist-info/RECORD +0 -31
- {explicit_python-2.5.0.dist-info → explicit_python-3.1.0.dist-info}/WHEEL +0 -0
- {explicit_python-2.5.0.dist-info → explicit_python-3.1.0.dist-info}/licenses/LICENSE +0 -0
- {explicit_python-2.5.0.dist-info → explicit_python-3.1.0.dist-info}/top_level.txt +0 -0
|
@@ -1,21 +1,28 @@
|
|
|
1
1
|
"""Исключения предметной области."""
|
|
2
|
-
from collections import defaultdict
|
|
3
|
-
from functools import wraps
|
|
4
|
-
from typing import List
|
|
5
|
-
from typing import Mapping
|
|
6
2
|
|
|
7
|
-
from
|
|
3
|
+
from collections import (
|
|
4
|
+
defaultdict,
|
|
5
|
+
)
|
|
6
|
+
from collections.abc import (
|
|
7
|
+
Mapping,
|
|
8
|
+
)
|
|
9
|
+
from functools import (
|
|
10
|
+
wraps,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from pydantic import (
|
|
14
|
+
ValidationError as PydanticValidationError,
|
|
15
|
+
)
|
|
8
16
|
|
|
9
17
|
|
|
10
18
|
NON_FIELD_ERRORS = '__all__'
|
|
11
19
|
|
|
12
20
|
|
|
13
|
-
def init_messages_dict() -> Mapping[str,
|
|
21
|
+
def init_messages_dict() -> Mapping[str, list[str]]:
|
|
14
22
|
return defaultdict(list)
|
|
15
23
|
|
|
16
24
|
|
|
17
25
|
class DomainValidationError(Exception):
|
|
18
|
-
|
|
19
26
|
"""Ошибка валидации данных модели предметной области.
|
|
20
27
|
|
|
21
28
|
.. code-block:: python
|
|
@@ -32,9 +39,9 @@ class DomainValidationError(Exception):
|
|
|
32
39
|
"""
|
|
33
40
|
|
|
34
41
|
def __init__(self, message, code=None, params=None):
|
|
35
|
-
"""
|
|
36
|
-
|
|
37
|
-
dictionary
|
|
42
|
+
"""The `message` argument can be a single error, a list of errors, or a dictionary.
|
|
43
|
+
|
|
44
|
+
The dictionary maps field names to lists of errors.
|
|
38
45
|
|
|
39
46
|
What we define as an "error" can be either a simple string or an
|
|
40
47
|
instance of DomainValidationError with its message attribute set, and
|
|
@@ -50,9 +57,7 @@ class DomainValidationError(Exception):
|
|
|
50
57
|
elif not hasattr(message, 'message'):
|
|
51
58
|
message = message.error_list
|
|
52
59
|
else:
|
|
53
|
-
message, code, params = (
|
|
54
|
-
message.message, message.code, message.params
|
|
55
|
-
)
|
|
60
|
+
message, code, params = (message.message, message.code, message.params)
|
|
56
61
|
|
|
57
62
|
if isinstance(message, dict):
|
|
58
63
|
self.error_dict = {}
|
|
@@ -69,8 +74,7 @@ class DomainValidationError(Exception):
|
|
|
69
74
|
if not isinstance(sub_message, DomainValidationError):
|
|
70
75
|
sub_message = DomainValidationError(sub_message)
|
|
71
76
|
if hasattr(sub_message, 'error_dict'):
|
|
72
|
-
self.error_list.extend(
|
|
73
|
-
sum(sub_message.error_dict.values(), []))
|
|
77
|
+
self.error_list.extend(sum(sub_message.error_dict.values(), []))
|
|
74
78
|
else:
|
|
75
79
|
self.error_list.extend(sub_message.error_list)
|
|
76
80
|
|
|
@@ -123,7 +127,6 @@ class DomainValidationError(Exception):
|
|
|
123
127
|
|
|
124
128
|
|
|
125
129
|
def handle_pydantic_validation_error(fn):
|
|
126
|
-
|
|
127
130
|
"""Конвертирует PydanticValidationError в DomainValidationError.
|
|
128
131
|
|
|
129
132
|
.. code-block:: python
|
|
@@ -138,11 +141,19 @@ def handle_pydantic_validation_error(fn):
|
|
|
138
141
|
try:
|
|
139
142
|
return fn(*args, **kwargs)
|
|
140
143
|
except PydanticValidationError as error:
|
|
144
|
+
errors = error.errors()
|
|
145
|
+
# Ошибки варианта Unset в Union[X, Unset] и теги вариантов в loc не нужны в ответе.
|
|
146
|
+
unset_unions = {e['loc'][:-1] for e in errors if e.get('ctx', {}).get('class') == 'Unset'}
|
|
141
147
|
errors_dict = defaultdict(list)
|
|
142
|
-
for
|
|
143
|
-
|
|
144
|
-
|
|
148
|
+
for e in errors:
|
|
149
|
+
if e.get('ctx', {}).get('class') == 'Unset':
|
|
150
|
+
continue
|
|
151
|
+
loc = [item for i, item in enumerate(e['loc']) if e['loc'][:i] not in unset_unions]
|
|
152
|
+
msg = str(e['ctx']['error']) if e['type'] in ('value_error', 'assertion_error') else e['msg']
|
|
153
|
+
for field in loc or ['__root__']:
|
|
154
|
+
errors_dict[field].append(msg)
|
|
145
155
|
if errors_dict:
|
|
146
156
|
raise DomainValidationError(errors_dict) from error
|
|
147
|
-
|
|
157
|
+
raise
|
|
158
|
+
|
|
148
159
|
return wrapper
|
explicit/messagebus/__init__.py
CHANGED
explicit/messagebus/commands.py
CHANGED
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
"""Шина сообщений: обработка команд на обновление данных."""
|
|
2
|
-
from abc import ABC
|
|
3
|
-
from typing import Any
|
|
4
|
-
from typing import Dict
|
|
5
|
-
from typing import Protocol
|
|
6
|
-
from typing import Tuple
|
|
7
|
-
from typing import Type
|
|
8
2
|
|
|
9
|
-
from
|
|
3
|
+
from abc import (
|
|
4
|
+
ABC,
|
|
5
|
+
)
|
|
6
|
+
from typing import (
|
|
7
|
+
Any,
|
|
8
|
+
Protocol,
|
|
9
|
+
)
|
|
10
10
|
|
|
11
|
-
from
|
|
11
|
+
from pydantic.main import (
|
|
12
|
+
BaseModel,
|
|
13
|
+
)
|
|
12
14
|
|
|
13
|
-
from .
|
|
15
|
+
from explicit.domain import (
|
|
16
|
+
HasUnsetValues,
|
|
17
|
+
)
|
|
14
18
|
|
|
19
|
+
from .exceptions import (
|
|
20
|
+
NoHandlerError,
|
|
21
|
+
)
|
|
15
22
|
|
|
16
|
-
class Command(HasUnsetValues, BaseModel):
|
|
17
23
|
|
|
24
|
+
class Command(HasUnsetValues, BaseModel):
|
|
18
25
|
"""Объект запроса на обновление данных.
|
|
19
26
|
|
|
20
27
|
.. code-block:: python
|
|
@@ -25,9 +32,7 @@ class Command(HasUnsetValues, BaseModel):
|
|
|
25
32
|
|
|
26
33
|
"""
|
|
27
34
|
|
|
28
|
-
def dict_by_prefix(
|
|
29
|
-
self, prefix: str, *, removeprefix=False, exclude=None
|
|
30
|
-
) -> dict:
|
|
35
|
+
def dict_by_prefix(self, prefix: str, *, removeprefix=False, exclude=None) -> dict:
|
|
31
36
|
assert prefix, f'prefix not set: "{prefix}"'
|
|
32
37
|
|
|
33
38
|
if exclude is None:
|
|
@@ -38,20 +43,12 @@ class Command(HasUnsetValues, BaseModel):
|
|
|
38
43
|
return k.removeprefix(prefix)
|
|
39
44
|
return k
|
|
40
45
|
|
|
41
|
-
fields = (
|
|
42
|
-
(removeprefix_(k), v)
|
|
43
|
-
for k, v in self.dict().items()
|
|
44
|
-
if k.startswith(prefix)
|
|
45
|
-
)
|
|
46
|
+
fields = ((removeprefix_(k), v) for k, v in self.model_dump().items() if k.startswith(prefix))
|
|
46
47
|
|
|
47
|
-
return dict(
|
|
48
|
-
(k, v) for k, v in fields
|
|
49
|
-
if k not in exclude
|
|
50
|
-
)
|
|
48
|
+
return dict((k, v) for k, v in fields if k not in exclude)
|
|
51
49
|
|
|
52
50
|
|
|
53
51
|
class CommandHandler(Protocol):
|
|
54
|
-
|
|
55
52
|
"""Обработчик команды.
|
|
56
53
|
|
|
57
54
|
.. code-block:: python
|
|
@@ -67,36 +64,29 @@ class CommandHandler(Protocol):
|
|
|
67
64
|
|
|
68
65
|
|
|
69
66
|
class CommandBusMixin(ABC):
|
|
70
|
-
|
|
71
67
|
"""Примесь к шине сообщений, реализует обработку команд на обновление данных."""
|
|
72
68
|
|
|
73
|
-
_command_handlers_value:
|
|
69
|
+
_command_handlers_value: dict[type[Command], CommandHandler]
|
|
74
70
|
|
|
75
71
|
@property
|
|
76
|
-
def _command_handlers(self) ->
|
|
72
|
+
def _command_handlers(self) -> dict[type[Command], CommandHandler]:
|
|
77
73
|
if not hasattr(self, '_command_handlers_value'):
|
|
78
74
|
self._command_handlers_value = {}
|
|
79
75
|
return self._command_handlers_value
|
|
80
76
|
|
|
81
|
-
def add_command_handler(self, command:
|
|
77
|
+
def add_command_handler(self, command: type[Command], handler: CommandHandler) -> None:
|
|
82
78
|
"""Регистрация обработчика команды."""
|
|
83
|
-
|
|
84
79
|
assert issubclass(command, Command)
|
|
85
80
|
assert callable(handler)
|
|
86
81
|
self._command_handlers[command] = handler
|
|
87
82
|
|
|
88
|
-
def add_command_handlers(
|
|
89
|
-
self,
|
|
90
|
-
*handlers: Tuple[Type[Command], CommandHandler]
|
|
91
|
-
) -> None:
|
|
83
|
+
def add_command_handlers(self, *handlers: tuple[type[Command], CommandHandler]) -> None:
|
|
92
84
|
"""Регистрация обработчиков команд."""
|
|
93
|
-
|
|
94
85
|
for command, handler in handlers:
|
|
95
86
|
self.add_command_handler(command, handler)
|
|
96
87
|
|
|
97
88
|
def handle_command(self, command: Command):
|
|
98
89
|
"""Передача запроса обработчику типа данной команды."""
|
|
99
|
-
|
|
100
90
|
assert isinstance(command, Command)
|
|
101
91
|
handler = self._command_handlers.get(type(command))
|
|
102
92
|
if handler is None:
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
"""Шина сообщений: внедрение зависимостей."""
|
|
2
|
-
|
|
3
|
-
from typing import Any
|
|
4
|
-
from typing import Callable
|
|
5
|
-
from typing import Dict
|
|
6
|
-
from typing import Optional
|
|
2
|
+
|
|
7
3
|
import inspect
|
|
8
4
|
import logging
|
|
5
|
+
from collections.abc import (
|
|
6
|
+
Callable,
|
|
7
|
+
)
|
|
8
|
+
from functools import (
|
|
9
|
+
partial,
|
|
10
|
+
)
|
|
11
|
+
from typing import (
|
|
12
|
+
Any,
|
|
13
|
+
)
|
|
9
14
|
|
|
10
15
|
|
|
11
16
|
logger = logging.getLogger(__name__)
|
|
@@ -21,10 +26,9 @@ class AlreadyRegisteredDependencyError(Exception):
|
|
|
21
26
|
|
|
22
27
|
|
|
23
28
|
class DependencyInjectionMixin:
|
|
24
|
-
|
|
25
29
|
"""Примесь к шине сообщений, реализует управление зависимостями и их внедрение."""
|
|
26
30
|
|
|
27
|
-
_dependencies:
|
|
31
|
+
_dependencies: dict[str, Callable]
|
|
28
32
|
|
|
29
33
|
def register_dependency(self, alias: str, dependency: Callable):
|
|
30
34
|
"""Зарегистрировать зависимость."""
|
|
@@ -45,16 +49,12 @@ class DependencyInjectionMixin:
|
|
|
45
49
|
except KeyError as e:
|
|
46
50
|
raise UnknownDependencyError(f'Зависимость для аргумента "{alias}" не найдена') from e
|
|
47
51
|
|
|
48
|
-
def _inject_dependencies(self, target: Callable, exclude:
|
|
52
|
+
def _inject_dependencies(self, target: Callable, exclude: set[str] | None = None) -> Callable:
|
|
49
53
|
"""Внедряет зависимости в target."""
|
|
50
54
|
exclude = exclude or set()
|
|
51
55
|
|
|
52
56
|
target_signature = inspect.signature(target)
|
|
53
57
|
# определяем зависимости, которые ожидает обработчик
|
|
54
|
-
deps = {
|
|
55
|
-
name: self._get_dependency(name)
|
|
56
|
-
for name in target_signature.parameters.keys()
|
|
57
|
-
if name not in exclude
|
|
58
|
-
}
|
|
58
|
+
deps = {name: self._get_dependency(name) for name in target_signature.parameters.keys() if name not in exclude}
|
|
59
59
|
logger.debug('В обработчик %s внедрены зависимости %s', target, deps)
|
|
60
60
|
return partial(target, **deps)
|
explicit/messagebus/events.py
CHANGED
|
@@ -1,49 +1,65 @@
|
|
|
1
1
|
"""Шина сообщений: обработка событий."""
|
|
2
|
-
from abc import ABC
|
|
3
|
-
from typing import TYPE_CHECKING
|
|
4
|
-
from typing import Any
|
|
5
|
-
from typing import Callable
|
|
6
|
-
from typing import Dict
|
|
7
|
-
from typing import List
|
|
8
|
-
from typing import Optional
|
|
9
|
-
from typing import Type
|
|
10
|
-
from uuid import uuid4
|
|
11
|
-
import json
|
|
12
|
-
|
|
13
|
-
from more_itertools.recipes import consume
|
|
14
|
-
from pydantic.fields import Field
|
|
15
|
-
from pydantic.json import pydantic_encoder
|
|
16
2
|
|
|
17
|
-
|
|
3
|
+
import json
|
|
4
|
+
from abc import (
|
|
5
|
+
ABC,
|
|
6
|
+
)
|
|
7
|
+
from collections.abc import (
|
|
8
|
+
Callable,
|
|
9
|
+
)
|
|
10
|
+
from typing import (
|
|
11
|
+
TYPE_CHECKING,
|
|
12
|
+
Any,
|
|
13
|
+
)
|
|
14
|
+
from uuid import (
|
|
15
|
+
uuid4,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from more_itertools.recipes import (
|
|
19
|
+
consume,
|
|
20
|
+
)
|
|
21
|
+
from pydantic.fields import (
|
|
22
|
+
Field,
|
|
23
|
+
)
|
|
24
|
+
from pydantic_core import (
|
|
25
|
+
to_jsonable_python,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from explicit.domain.model import (
|
|
29
|
+
asdict,
|
|
30
|
+
)
|
|
18
31
|
|
|
19
32
|
|
|
20
33
|
if TYPE_CHECKING:
|
|
21
|
-
from dataclasses import
|
|
22
|
-
|
|
23
|
-
|
|
34
|
+
from dataclasses import (
|
|
35
|
+
dataclass,
|
|
36
|
+
)
|
|
24
37
|
else:
|
|
25
|
-
from pydantic.dataclasses import
|
|
38
|
+
from pydantic.dataclasses import (
|
|
39
|
+
dataclass,
|
|
40
|
+
)
|
|
26
41
|
|
|
27
42
|
|
|
28
43
|
@dataclass
|
|
29
44
|
class EventMeta:
|
|
30
45
|
id: str = Field(default_factory=lambda: str(uuid4()))
|
|
31
|
-
transaction_id:
|
|
32
|
-
payload:
|
|
46
|
+
transaction_id: str | None = None
|
|
47
|
+
payload: dict = Field(default_factory=dict)
|
|
33
48
|
|
|
34
49
|
|
|
35
50
|
@dataclass
|
|
36
51
|
class Event:
|
|
37
52
|
"""Событие."""
|
|
53
|
+
|
|
38
54
|
meta: EventMeta = Field(default_factory=EventMeta)
|
|
39
55
|
|
|
40
56
|
def set_transaction_id(self, transaction_id: str):
|
|
41
57
|
self.meta.transaction_id = transaction_id
|
|
42
58
|
|
|
43
|
-
def get_transaction_id(self) ->
|
|
59
|
+
def get_transaction_id(self) -> str | None:
|
|
44
60
|
return self.meta.transaction_id
|
|
45
61
|
|
|
46
|
-
def set_payload(self, payload:
|
|
62
|
+
def set_payload(self, payload: dict):
|
|
47
63
|
assert isinstance(payload, dict)
|
|
48
64
|
self.meta.payload = payload
|
|
49
65
|
|
|
@@ -52,14 +68,9 @@ class Event:
|
|
|
52
68
|
|
|
53
69
|
@classmethod
|
|
54
70
|
def from_event(cls, event: 'Event', **kwargs) -> 'Event':
|
|
55
|
-
return cls(
|
|
56
|
-
meta=EventMeta(transaction_id=event.meta.transaction_id, payload=event.meta.payload),
|
|
57
|
-
**kwargs
|
|
58
|
-
)
|
|
71
|
+
return cls(meta=EventMeta(transaction_id=event.meta.transaction_id, payload=event.meta.payload), **kwargs)
|
|
59
72
|
|
|
60
|
-
def configure_meta(
|
|
61
|
-
self, transaction_id: Optional[str] = None, payload: Optional[Dict] = None
|
|
62
|
-
) -> None:
|
|
73
|
+
def configure_meta(self, transaction_id: str | None = None, payload: dict | None = None) -> None:
|
|
63
74
|
self.meta.transaction_id = transaction_id
|
|
64
75
|
if payload:
|
|
65
76
|
assert isinstance(payload, dict)
|
|
@@ -67,11 +78,8 @@ class Event:
|
|
|
67
78
|
|
|
68
79
|
def dump(self) -> str:
|
|
69
80
|
return json.dumps(
|
|
70
|
-
{
|
|
71
|
-
|
|
72
|
-
'body': asdict(self)
|
|
73
|
-
},
|
|
74
|
-
default=pydantic_encoder
|
|
81
|
+
{'type': type(self).__name__, 'body': asdict(self)},
|
|
82
|
+
default=to_jsonable_python,
|
|
75
83
|
)
|
|
76
84
|
|
|
77
85
|
|
|
@@ -87,35 +95,27 @@ EventHandler = Callable[[Event], Any]
|
|
|
87
95
|
|
|
88
96
|
|
|
89
97
|
class EventBusMixin(ABC):
|
|
90
|
-
|
|
91
98
|
"""Примесь к шине сообщений, реализует обработку событий."""
|
|
92
99
|
|
|
93
|
-
_event_handlers_value:
|
|
100
|
+
_event_handlers_value: dict[type[Event], list[EventHandler]]
|
|
94
101
|
|
|
95
102
|
@property
|
|
96
|
-
def _event_handlers(self) ->
|
|
103
|
+
def _event_handlers(self) -> dict[type[Event], list[EventHandler]]:
|
|
97
104
|
if not hasattr(self, '_event_handlers_value'):
|
|
98
105
|
self._event_handlers_value = {}
|
|
99
106
|
return self._event_handlers_value
|
|
100
107
|
|
|
101
|
-
def add_event_handler(
|
|
102
|
-
self, event: Type[Event], handler: EventHandler
|
|
103
|
-
) -> None:
|
|
108
|
+
def add_event_handler(self, event: type[Event], handler: EventHandler) -> None:
|
|
104
109
|
"""Регистрация обработчика события."""
|
|
105
|
-
|
|
106
110
|
assert issubclass(event, Event)
|
|
107
111
|
assert callable(handler)
|
|
108
112
|
self._event_handlers.setdefault(event, []).append(handler)
|
|
109
113
|
|
|
110
114
|
def handle_event(self, event: Event):
|
|
111
115
|
"""Передача события списку обработчиков типа данного события."""
|
|
112
|
-
|
|
113
116
|
assert isinstance(event, Event)
|
|
114
117
|
|
|
115
118
|
try:
|
|
116
|
-
consume(
|
|
117
|
-
handler(event)
|
|
118
|
-
for handler in self._event_handlers[type(event)]
|
|
119
|
-
)
|
|
119
|
+
consume(handler(event) for handler in self._event_handlers[type(event)])
|
|
120
120
|
except KeyError as e:
|
|
121
121
|
raise ValueError(f'No handler for {type(event)}') from e
|
|
@@ -1,22 +1,31 @@
|
|
|
1
1
|
"""Шина сообщений."""
|
|
2
|
-
from typing import Type
|
|
3
|
-
import threading
|
|
4
2
|
|
|
5
|
-
|
|
3
|
+
import threading
|
|
6
4
|
|
|
7
|
-
from .
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
from .
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
5
|
+
from explicit.unit_of_work import (
|
|
6
|
+
AbstractUnitOfWork,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
from .commands import (
|
|
10
|
+
Command,
|
|
11
|
+
CommandBusMixin,
|
|
12
|
+
CommandHandler,
|
|
13
|
+
)
|
|
14
|
+
from .dependency_injection import (
|
|
15
|
+
DependencyInjectionMixin,
|
|
16
|
+
)
|
|
17
|
+
from .events import (
|
|
18
|
+
Event,
|
|
19
|
+
EventBusMixin,
|
|
20
|
+
EventHandler,
|
|
21
|
+
)
|
|
22
|
+
from .queries import (
|
|
23
|
+
Query,
|
|
24
|
+
QueryBusMixin,
|
|
25
|
+
)
|
|
16
26
|
|
|
17
27
|
|
|
18
28
|
class MessageBus(DependencyInjectionMixin, QueryBusMixin, CommandBusMixin, EventBusMixin):
|
|
19
|
-
|
|
20
29
|
"""Шина.
|
|
21
30
|
|
|
22
31
|
Обеспечивает доставку команды соответствующему обработчику.
|
|
@@ -38,13 +47,13 @@ class MessageBus(DependencyInjectionMixin, QueryBusMixin, CommandBusMixin, Event
|
|
|
38
47
|
self._uow = uow
|
|
39
48
|
self._set_dependencies(uow=uow, **dependencies)
|
|
40
49
|
|
|
41
|
-
def add_command_handler(self, command:
|
|
50
|
+
def add_command_handler(self, command: type[Command], handler: CommandHandler) -> None:
|
|
42
51
|
"""Внедрение зависимостей в обработчик и регистрация его обычным образом."""
|
|
43
52
|
super().add_command_handler(
|
|
44
53
|
command=command, handler=self._inject_dependencies(target=handler, exclude={'command'})
|
|
45
54
|
)
|
|
46
55
|
|
|
47
|
-
def add_event_handler(self, event:
|
|
56
|
+
def add_event_handler(self, event: type[Event], handler: EventHandler) -> None:
|
|
48
57
|
"""Внедрение зависимостей в обработчик и регистрация его обычным образом."""
|
|
49
58
|
super().add_event_handler(event=event, handler=self._inject_dependencies(target=handler, exclude={'event'}))
|
|
50
59
|
|
explicit/messagebus/queries.py
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
"""Шина сообщений: обработка запросов на чтение данных."""
|
|
2
|
-
|
|
3
|
-
from abc import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
from
|
|
2
|
+
|
|
3
|
+
from abc import (
|
|
4
|
+
ABC,
|
|
5
|
+
abstractmethod,
|
|
6
|
+
)
|
|
7
|
+
from dataclasses import (
|
|
8
|
+
dataclass,
|
|
9
|
+
)
|
|
10
|
+
from typing import (
|
|
11
|
+
Any,
|
|
12
|
+
)
|
|
8
13
|
|
|
9
14
|
|
|
10
15
|
@dataclass
|
|
@@ -13,7 +18,6 @@ class Query(ABC):
|
|
|
13
18
|
|
|
14
19
|
|
|
15
20
|
class QueryHandler(ABC):
|
|
16
|
-
|
|
17
21
|
@abstractmethod
|
|
18
22
|
def handle(self, query: Query) -> Any:
|
|
19
23
|
"""Обработка запроса на чтение данных."""
|
|
@@ -21,22 +25,18 @@ class QueryHandler(ABC):
|
|
|
21
25
|
|
|
22
26
|
|
|
23
27
|
class QueryBusMixin(ABC):
|
|
24
|
-
|
|
25
28
|
"""Примесь к шине сообщений, реализует обработку запросов на чтение данных."""
|
|
26
29
|
|
|
27
|
-
_query_handlers_value:
|
|
30
|
+
_query_handlers_value: dict[type[Query], QueryHandler]
|
|
28
31
|
|
|
29
32
|
@property
|
|
30
|
-
def _query_handlers(self) ->
|
|
31
|
-
if not hasattr(self,
|
|
33
|
+
def _query_handlers(self) -> dict[type[Query], QueryHandler]:
|
|
34
|
+
if not hasattr(self, '_query_handlers_value'):
|
|
32
35
|
self._query_handlers_value = {}
|
|
33
36
|
return self._query_handlers_value
|
|
34
37
|
|
|
35
|
-
def add_query_handler(
|
|
36
|
-
self, query: Type[Query], handler: QueryHandler
|
|
37
|
-
) -> None:
|
|
38
|
+
def add_query_handler(self, query: type[Query], handler: QueryHandler) -> None:
|
|
38
39
|
"""Регистрация обработчика запроса."""
|
|
39
|
-
|
|
40
40
|
assert issubclass(query, Query)
|
|
41
41
|
assert isinstance(handler, QueryHandler)
|
|
42
42
|
self._query_handlers[query] = handler
|
|
@@ -46,6 +46,5 @@ class QueryBusMixin(ABC):
|
|
|
46
46
|
query: Query,
|
|
47
47
|
):
|
|
48
48
|
"""Передача запроса обработчику типа данного запроса."""
|
|
49
|
-
|
|
50
49
|
assert isinstance(query, Query)
|
|
51
50
|
return self._query_handlers[type(query)].handle(query)
|
explicit/unit_of_work.py
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
"""Абстракции "Единицы работы"."""
|
|
2
|
-
|
|
3
|
-
from abc import abstractmethod
|
|
4
|
-
from queue import Queue
|
|
5
|
-
from typing import Dict
|
|
6
|
-
from typing import Optional
|
|
7
|
-
from typing import Tuple
|
|
8
|
-
from typing import Type
|
|
2
|
+
|
|
9
3
|
import threading
|
|
4
|
+
from abc import (
|
|
5
|
+
ABC,
|
|
6
|
+
abstractmethod,
|
|
7
|
+
)
|
|
8
|
+
from queue import (
|
|
9
|
+
Queue,
|
|
10
|
+
)
|
|
10
11
|
|
|
11
|
-
from explicit.adapters.db import
|
|
12
|
+
from explicit.adapters.db import (
|
|
13
|
+
AbstractRepository,
|
|
14
|
+
)
|
|
12
15
|
|
|
13
16
|
|
|
14
17
|
class RepositoryRegistry:
|
|
15
|
-
|
|
16
18
|
"""Реестр репозиториев."""
|
|
17
19
|
|
|
18
|
-
__repositories:
|
|
20
|
+
__repositories: dict[str, AbstractRepository] # pylint: disable=invalid-name
|
|
19
21
|
|
|
20
22
|
def __init__(self, uow: 'AbstractUnitOfWork'):
|
|
21
23
|
self.__repositories = {}
|
|
22
24
|
self.__uow = uow
|
|
23
25
|
|
|
24
|
-
def register(
|
|
25
|
-
self, *repositories: Tuple[str, AbstractRepository]
|
|
26
|
-
):
|
|
26
|
+
def register(self, *repositories: tuple[str, AbstractRepository]):
|
|
27
27
|
for name, repository in repositories:
|
|
28
28
|
self.__repositories[name] = repository
|
|
29
29
|
setattr(self.__uow, name, repository)
|
|
@@ -40,7 +40,6 @@ _thread_local = threading.local()
|
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
class AbstractUnitOfWork(ABC):
|
|
43
|
-
|
|
44
43
|
"""Единица работы, логическая бизнес-транзакция.
|
|
45
44
|
|
|
46
45
|
Обеспечивает атомарность выполняемых операций.
|
|
@@ -69,9 +68,7 @@ class AbstractUnitOfWork(ABC):
|
|
|
69
68
|
# данные уровня экземпляра, локальные для текущего потока
|
|
70
69
|
self._thread_local = threading.local()
|
|
71
70
|
|
|
72
|
-
def register_repositories(
|
|
73
|
-
self, *repositories: Tuple[str, AbstractRepository]
|
|
74
|
-
):
|
|
71
|
+
def register_repositories(self, *repositories: tuple[str, AbstractRepository]):
|
|
75
72
|
"""Регистрация репозиториев.
|
|
76
73
|
|
|
77
74
|
Пример:
|
|
@@ -142,17 +139,11 @@ class AbstractUnitOfWork(ABC):
|
|
|
142
139
|
|
|
143
140
|
def __enter__(self) -> 'AbstractUnitOfWork':
|
|
144
141
|
"""Начало транзакции."""
|
|
145
|
-
|
|
146
142
|
self.strategy.__enter__()
|
|
147
143
|
return self
|
|
148
144
|
|
|
149
|
-
def __exit__(
|
|
150
|
-
self,
|
|
151
|
-
exc_type: Optional[Type[Exception]],
|
|
152
|
-
*args: Tuple
|
|
153
|
-
) -> None:
|
|
145
|
+
def __exit__(self, exc_type: type[Exception] | None, *args: tuple) -> None:
|
|
154
146
|
"""Окончание транзакции."""
|
|
155
|
-
|
|
156
147
|
try:
|
|
157
148
|
if exc_type is not None:
|
|
158
149
|
self.rollback()
|
|
@@ -166,7 +157,6 @@ class AbstractUnitOfWork(ABC):
|
|
|
166
157
|
|
|
167
158
|
|
|
168
159
|
class AbstractTransactionStrategy(ABC):
|
|
169
|
-
|
|
170
160
|
"""Абстрактная транзакционная стратегия."""
|
|
171
161
|
|
|
172
162
|
def __enter__(self):
|