|
2 | 2 | import warnings |
3 | 3 |
|
4 | 4 | from faststream._compat import TypeAlias, override |
| 5 | +from faststream.app import FastStream |
5 | 6 | from faststream.broker.core.asyncronous import BrokerAsyncUsecase |
6 | 7 | from faststream.types import SendableMessage |
7 | 8 | from taskiq import AsyncBroker, BrokerMessage |
@@ -44,10 +45,7 @@ async def shutdown(self) -> None: |
44 | 45 |
|
45 | 46 | async def kick(self, message: BrokerMessage) -> None: |
46 | 47 | """Call wrapped FastStream broker `publish` method.""" |
47 | | - labels = message.labels |
48 | | - labels.pop("schedule", None) |
49 | | - msg = await resolve_msg(labels.pop("message", message.message)) |
50 | | - await self.broker.publish(msg, **labels) |
| 48 | + await _broker_publish(self.broker, message) |
51 | 49 |
|
52 | 50 | async def listen( |
53 | 51 | self, |
@@ -90,3 +88,49 @@ def task( # type: ignore[override] |
90 | 88 | schedule=schedule, |
91 | 89 | **kwargs, |
92 | 90 | )(lambda: None) |
| 91 | + |
| 92 | + |
| 93 | +class AppWrapper(BrokerWrapper): |
| 94 | + """Wrap FastStream instance to taskiq compatible object. |
| 95 | +
|
| 96 | + Attributes: |
| 97 | + app : FastStream instance. |
| 98 | +
|
| 99 | + Methods: |
| 100 | + __init__ : Initializes the object. |
| 101 | + startup : Startup wrapper FastStream. |
| 102 | + shutdown : Shutdown wrapper FastStream. |
| 103 | + kick : Call wrapped FastStream broker `publish` method. |
| 104 | + task : Register FastStream scheduled task. |
| 105 | + """ |
| 106 | + |
| 107 | + def __init__(self, app: FastStream) -> None: |
| 108 | + super(BrokerWrapper, self).__init__() |
| 109 | + self.app = app |
| 110 | + |
| 111 | + async def startup(self) -> None: |
| 112 | + """Startup wrapper FastStream broker.""" |
| 113 | + await super(BrokerWrapper, self).startup() |
| 114 | + await self.app._startup() # noqa: SLF001 |
| 115 | + |
| 116 | + async def shutdown(self) -> None: |
| 117 | + """Shutdown wrapper FastStream broker.""" |
| 118 | + await self.app._shutdown() # noqa: SLF001 |
| 119 | + await super(BrokerWrapper, self).shutdown() |
| 120 | + |
| 121 | + async def kick(self, message: BrokerMessage) -> None: |
| 122 | + """Call wrapped FastStream broker `publish` method.""" |
| 123 | + assert ( # noqa: S101 |
| 124 | + self.app.broker |
| 125 | + ), "You should setup application broker firts" |
| 126 | + await _broker_publish(self.app.broker, message) |
| 127 | + |
| 128 | + |
| 129 | +async def _broker_publish( |
| 130 | + broker: BrokerAsyncUsecase[typing.Any, typing.Any], |
| 131 | + message: BrokerMessage, |
| 132 | +) -> None: |
| 133 | + labels = message.labels |
| 134 | + labels.pop("schedule", None) |
| 135 | + msg = await resolve_msg(labels.pop("message", message.message)) |
| 136 | + await broker.publish(msg, **labels) |
0 commit comments