Skip to content
This repository was archived by the owner on Jan 28, 2022. It is now read-only.

Commit ca4c525

Browse files
author
Sergio García Prado
authored
Merge pull request #459 from Clariteia/0.3.1
0.3.1
2 parents 64c9b16 + 503ce00 commit ca4c525

File tree

19 files changed

+195
-170
lines changed

19 files changed

+195
-170
lines changed

HISTORY.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,12 @@ History
151151
* Rename `Consumer` and `ConsumerService` as `BrokerConsumer` and `BrokerConsumerService` respectively.
152152
* Rename `Producer` and `ProducerService` as `BrokerProducer` and `BrokerProducerService` respectively.
153153
* Rename `HandlerRequest`, `HandlerResponse` and `HandlerResponseException` as `BrokerRequest`, `BrokerResponse` and `BrokerResponseException` respectively.
154+
155+
0.3.1 (2021-11-30)
156+
------------------
157+
158+
* Add `identifier: UUID` and `headers: dict[str, str]` attributes to `BrokerMessage`.
159+
* Remove `saga: Optional[UUID]` and `service_name: str` attributes from `BrokerMessage`.
160+
* Now `BrokerPublisher.send` returns the `BrokerMessage` identifier instead of the entry identifier on the `Producer`'s queue.
161+
* Add `REQUEST_HEADERS_CONTEXT_VAR`.
162+
* Rename `USER_CONTEXT_VAR` and `REPLY_TOPIC_CONTEXT_VAR` as `REQUEST_USER_CONTEXT_VAR` and `REQUEST_REPLY_TOPIC_CONTEXT_VAR` respectively.

minos/networks/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
__author__ = """Clariteia Devs"""
22
__email__ = "devs@clariteia.com"
3-
__version__ = "0.3.0"
3+
__version__ = "0.3.1"
44

55
from .brokers import (
6-
REPLY_TOPIC_CONTEXT_VAR,
6+
REQUEST_HEADERS_CONTEXT_VAR,
7+
REQUEST_REPLY_TOPIC_CONTEXT_VAR,
78
BrokerConsumer,
89
BrokerConsumerService,
910
BrokerHandler,
@@ -56,7 +57,7 @@
5657
MinosRedefinedEnrouteDecoratorException,
5758
)
5859
from .requests import (
59-
USER_CONTEXT_VAR,
60+
REQUEST_USER_CONTEXT_VAR,
6061
Request,
6162
Response,
6263
ResponseException,

minos/networks/brokers/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
BrokerResponseException,
1515
)
1616
from .messages import (
17-
REPLY_TOPIC_CONTEXT_VAR,
17+
REQUEST_HEADERS_CONTEXT_VAR,
18+
REQUEST_REPLY_TOPIC_CONTEXT_VAR,
1819
BrokerMessage,
1920
BrokerMessageStatus,
2021
BrokerMessageStrategy,

minos/networks/brokers/dynamic/brokers.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
from typing import (
1111
Optional,
1212
)
13+
from uuid import (
14+
UUID,
15+
)
1316

1417
from aiopg import (
1518
Cursor,
@@ -84,15 +87,15 @@ async def _destroy(self) -> None:
8487
await super()._destroy()
8588

8689
# noinspection PyUnusedLocal
87-
async def send(self, *args, reply_topic: None = None, **kwargs) -> None:
90+
async def send(self, *args, reply_topic: None = None, **kwargs) -> UUID:
8891
"""Send a ``BrokerMessage``.
8992
9093
:param args: Additional positional arguments.
9194
:param reply_topic: This argument is ignored if ignored in favor of ``self.topic``.
9295
:param kwargs: Additional named arguments.
93-
:return: This method does not return anything.
96+
:return: The ``UUID`` identifier of the message.
9497
"""
95-
await self.publisher.send(*args, reply_topic=self.topic, **kwargs)
98+
return await self.publisher.send(*args, reply_topic=self.topic, **kwargs)
9699

97100
async def get_one(self, *args, **kwargs) -> BrokerHandlerEntry:
98101
"""Get one handler entry from the given topics.

minos/networks/brokers/dynamic/pools.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
BrokerConsumer,
3636
)
3737
from ..messages import (
38-
REPLY_TOPIC_CONTEXT_VAR,
38+
REQUEST_REPLY_TOPIC_CONTEXT_VAR,
3939
)
4040
from ..publishers import (
4141
BrokerPublisher,
@@ -150,9 +150,9 @@ def __init__(self, wrapper: AsyncContextManager[DynamicBroker]):
150150

151151
async def __aenter__(self) -> DynamicBroker:
152152
handler = await self.wrapper.__aenter__()
153-
self._token = REPLY_TOPIC_CONTEXT_VAR.set(handler.topic)
153+
self._token = REQUEST_REPLY_TOPIC_CONTEXT_VAR.set(handler.topic)
154154
return handler
155155

156156
async def __aexit__(self, exc_type, exc_val, exc_tb):
157-
REPLY_TOPIC_CONTEXT_VAR.reset(self._token)
157+
REQUEST_REPLY_TOPIC_CONTEXT_VAR.reset(self._token)
158158
await self.wrapper.__aexit__(exc_type, exc_val, exc_tb)

minos/networks/brokers/handlers/handlers.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,15 @@
5252
MinosActionNotFoundException,
5353
)
5454
from ...requests import (
55-
USER_CONTEXT_VAR,
55+
REQUEST_USER_CONTEXT_VAR,
5656
Response,
5757
ResponseException,
5858
)
5959
from ...utils import (
6060
consume_queue,
6161
)
6262
from ..messages import (
63+
REQUEST_HEADERS_CONTEXT_VAR,
6364
BrokerMessage,
6465
BrokerMessageStatus,
6566
)
@@ -304,42 +305,49 @@ async def dispatch_one(self, entry: BrokerHandlerEntry) -> None:
304305

305306
fn = self.get_callback(entry.callback)
306307
message = entry.data
307-
data, status = await fn(message)
308+
data, status, headers = await fn(message)
308309

309310
if message.reply_topic is not None:
310311
await self.publisher.send(
311-
data, topic=message.reply_topic, saga=message.saga, status=status, user=message.user
312+
data,
313+
topic=message.reply_topic,
314+
identifier=message.identifier,
315+
status=status,
316+
user=message.user,
317+
headers=headers,
312318
)
313319

314320
@staticmethod
315321
def get_callback(
316322
fn: Callable[[BrokerRequest], Union[Optional[BrokerRequest], Awaitable[Optional[BrokerRequest]]]]
317-
) -> Callable[[BrokerMessage], Awaitable[tuple[Any, BrokerMessageStatus]]]:
323+
) -> Callable[[BrokerMessage], Awaitable[tuple[Any, BrokerMessageStatus, dict[str, str]]]]:
318324
"""Get the handler function to be used by the Broker Handler.
319325
320326
:param fn: The action function.
321327
:return: A wrapper function around the given one that is compatible with the Broker Handler API.
322328
"""
323329

324-
async def _fn(raw: BrokerMessage) -> tuple[Any, BrokerMessageStatus]:
330+
async def _fn(raw: BrokerMessage) -> tuple[Any, BrokerMessageStatus, dict[str, str]]:
325331
request = BrokerRequest(raw)
326-
token = USER_CONTEXT_VAR.set(request.user)
332+
user_token = REQUEST_USER_CONTEXT_VAR.set(request.user)
333+
headers_token = REQUEST_HEADERS_CONTEXT_VAR.set(raw.headers)
327334

328335
try:
329336
response = fn(request)
330337
if isawaitable(response):
331338
response = await response
332339
if isinstance(response, Response):
333340
response = await response.content()
334-
return response, BrokerMessageStatus.SUCCESS
341+
return response, BrokerMessageStatus.SUCCESS, REQUEST_HEADERS_CONTEXT_VAR.get()
335342
except ResponseException as exc:
336343
logger.warning(f"Raised an application exception: {exc!s}")
337-
return repr(exc), BrokerMessageStatus.ERROR
344+
return repr(exc), BrokerMessageStatus.ERROR, REQUEST_HEADERS_CONTEXT_VAR.get()
338345
except Exception as exc:
339346
logger.exception(f"Raised a system exception: {exc!r}")
340-
return repr(exc), BrokerMessageStatus.SYSTEM_ERROR
347+
return repr(exc), BrokerMessageStatus.SYSTEM_ERROR, REQUEST_HEADERS_CONTEXT_VAR.get()
341348
finally:
342-
USER_CONTEXT_VAR.reset(token)
349+
REQUEST_USER_CONTEXT_VAR.reset(user_token)
350+
REQUEST_HEADERS_CONTEXT_VAR.reset(headers_token)
343351

344352
return _fn
345353

minos/networks/brokers/messages.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,42 +16,51 @@
1616
)
1717
from uuid import (
1818
UUID,
19+
uuid4,
1920
)
2021

2122
from minos.common import (
2223
DeclarativeModel,
2324
)
2425

25-
REPLY_TOPIC_CONTEXT_VAR: Final[ContextVar[Optional[str]]] = ContextVar("reply_topic", default=None)
26+
REQUEST_REPLY_TOPIC_CONTEXT_VAR: Final[ContextVar[Optional[str]]] = ContextVar("reply_topic", default=None)
27+
REQUEST_HEADERS_CONTEXT_VAR: Final[ContextVar[Optional[dict[str, str]]]] = ContextVar("headers", default=None)
2628

2729

2830
class BrokerMessage(DeclarativeModel):
2931
"""Broker Message class."""
3032

3133
topic: str
3234
data: Any
33-
service_name: str
34-
saga: Optional[UUID]
35+
identifier: UUID
3536
reply_topic: Optional[str]
3637
user: Optional[UUID]
3738
status: BrokerMessageStatus
3839
strategy: BrokerMessageStrategy
40+
headers: dict[str, str]
3941

4042
def __init__(
4143
self,
4244
topic: str,
4345
data: Any,
44-
service_name: str,
4546
*,
47+
identifier: Optional[UUID] = None,
4648
status: Optional[BrokerMessageStatus] = None,
4749
strategy: Optional[BrokerMessageStrategy] = None,
50+
headers: Optional[dict[str, str]] = None,
4851
**kwargs
4952
):
53+
if identifier is None:
54+
identifier = uuid4()
5055
if status is None:
5156
status = BrokerMessageStatus.SUCCESS
5257
if strategy is None:
5358
strategy = BrokerMessageStrategy.UNICAST
54-
super().__init__(topic, data, service_name, status=status, strategy=strategy, **kwargs)
59+
if headers is None:
60+
headers = dict()
61+
super().__init__(
62+
topic=topic, data=data, identifier=identifier, status=status, strategy=strategy, headers=headers, **kwargs
63+
)
5564

5665
@property
5766
def ok(self) -> bool:

minos/networks/brokers/publishers/publishers.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
)
44

55
import logging
6-
from abc import (
7-
ABC,
8-
)
96
from typing import (
107
Any,
118
Optional,
@@ -34,56 +31,55 @@
3431
logger = logging.getLogger(__name__)
3532

3633

37-
class BrokerPublisher(BrokerPublisherSetup, ABC):
34+
class BrokerPublisher(BrokerPublisherSetup):
3835
"""Broker Publisher class."""
3936

40-
def __init__(self, *args, service_name: str, **kwargs):
41-
super().__init__(*args, **kwargs)
42-
self.service_name = service_name
43-
4437
@classmethod
4538
def _from_config(cls, *args, config: MinosConfig, **kwargs) -> BrokerPublisher:
4639
# noinspection PyProtectedMember
47-
return cls(*args, service_name=config.service.name, **config.broker.queue._asdict(), **kwargs)
40+
return cls(*args, **config.broker.queue._asdict(), **kwargs)
4841

4942
# noinspection PyMethodOverriding
5043
async def send(
5144
self,
5245
data: Any,
5346
topic: str,
5447
*,
55-
saga: Optional[UUID] = None,
48+
identifier: Optional[UUID] = None,
5649
reply_topic: Optional[str] = None,
5750
user: Optional[UUID] = None,
5851
status: BrokerMessageStatus = BrokerMessageStatus.SUCCESS,
5952
strategy: BrokerMessageStrategy = BrokerMessageStrategy.UNICAST,
53+
headers: Optional[dict[str, str]] = None,
6054
**kwargs,
61-
) -> int:
55+
) -> UUID:
6256
"""Send a ``BrokerMessage``.
6357
6458
:param data: The data to be send.
6559
:param topic: Topic in which the message will be published.
66-
:param saga: Saga identifier.
60+
:param identifier: The identifier of the message.
6761
:param reply_topic: An optional topic name to wait for a response.
6862
:param user: The user identifier that send the message.
6963
:param status: The status code of the message.
7064
:param strategy: The publishing strategy.
65+
:param headers: A mapping of string values identified by a string key.
7166
:param kwargs: Additional named arguments.
72-
:return: This method does not return anything.
67+
:return: The ``UUID`` identifier of the message.
7368
"""
7469

7570
message = BrokerMessage(
7671
topic=topic,
7772
data=data,
78-
saga=saga,
73+
identifier=identifier,
7974
status=status,
8075
reply_topic=reply_topic,
8176
user=user,
82-
service_name=self.service_name,
8377
strategy=strategy,
78+
headers=headers,
8479
)
8580
logger.info(f"Publishing '{message!s}'...")
86-
return await self.enqueue(message.topic, message.strategy, message.avro_bytes)
81+
await self.enqueue(message.topic, message.strategy, message.avro_bytes)
82+
return message.identifier
8783

8884
async def enqueue(self, topic: str, strategy: BrokerMessageStrategy, raw: bytes) -> int:
8985
"""Send a sequence of bytes to the given topic.

minos/networks/requests.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@
3030
MinosException,
3131
)
3232

33-
USER_CONTEXT_VAR: Final[ContextVar[Optional[UUID]]] = ContextVar("user", default=None)
34-
USER_CONTEXT_VAR.set(None) # needed to "register" the context variable.
33+
REQUEST_USER_CONTEXT_VAR: Final[ContextVar[Optional[UUID]]] = ContextVar("user", default=None)
3534

3635

3736
class Request(ABC):

minos/networks/rest/handlers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
EnrouteBuilder,
3030
)
3131
from ..requests import (
32-
USER_CONTEXT_VAR,
32+
REQUEST_USER_CONTEXT_VAR,
3333
Response,
3434
ResponseException,
3535
)
@@ -128,7 +128,7 @@ async def _fn(request: web.Request) -> web.Response:
128128
logger.info(f"Dispatching '{request!s}' from '{request.remote!s}'...")
129129

130130
request = RestRequest(request)
131-
token = USER_CONTEXT_VAR.set(request.user)
131+
token = REQUEST_USER_CONTEXT_VAR.set(request.user)
132132

133133
try:
134134
response = fn(request)
@@ -146,7 +146,7 @@ async def _fn(request: web.Request) -> web.Response:
146146
logger.exception(f"Raised a system exception: {exc!r}")
147147
raise web.HTTPInternalServerError()
148148
finally:
149-
USER_CONTEXT_VAR.reset(token)
149+
REQUEST_USER_CONTEXT_VAR.reset(token)
150150

151151
return _fn
152152

0 commit comments

Comments
 (0)