Skip to content

RabbitSubscriber

faststream.rabbit.subscriber.RabbitSubscriber #

RabbitSubscriber(
    config: RabbitSubscriberConfig,
    specification: SubscriberSpecification[Any, Any],
    calls: CallsCollection[IncomingMessage],
)

Bases: SubscriberUsecase['IncomingMessage']

A class to handle logic for RabbitMQ message consumption.

Source code in faststream/rabbit/subscriber/usecase.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(
    self,
    config: "RabbitSubscriberConfig",
    specification: "SubscriberSpecification[Any, Any]",
    calls: "CallsCollection[IncomingMessage]",
) -> None:
    parser = AioPikaParser(pattern=config.queue.path_regex)
    config.decoder = parser.decode_message
    config.parser = parser.parse_message
    super().__init__(
        config,
        specification=specification,
        calls=calls,
    )

    self.queue = config.queue
    self.exchange = config.exchange

    self.consume_args = config.consume_args or {}

    self.__no_ack = config.ack_first

    self._consumer_tag: str | None = None
    self._queue_obj: RobustQueue | None = None
    self.channel = config.channel

lock instance-attribute #

lock: AbstractContextManager[Any] = nullcontext()

graceful_timeout instance-attribute #

graceful_timeout: float | None

calls instance-attribute #

calls = calls

specification instance-attribute #

specification = specification

ack_policy instance-attribute #

ack_policy = config.ack_policy

running instance-attribute #

running = False

queue instance-attribute #

queue = config.queue

exchange instance-attribute #

exchange = config.exchange

consume_args instance-attribute #

consume_args = config.consume_args or {}

channel instance-attribute #

channel = config.channel

app_id property #

app_id: str | None

add_call #

add_call(
    *,
    parser_: Optional[CustomCallable],
    decoder_: Optional[CustomCallable],
    dependencies_: Sequence[Dependant],
    codec_: Optional[CodecProto] = None,
) -> Self
Source code in faststream/_internal/endpoint/subscriber/usecase.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def add_call(
    self,
    *,
    parser_: Optional["CustomCallable"],
    decoder_: Optional["CustomCallable"],
    dependencies_: Sequence["Dependant"],
    codec_: Optional["CodecProto"] = None,
) -> Self:
    self._call_options = _CallOptions(
        parser=parser_,
        decoder=decoder_,
        dependencies=dependencies_,
        codec=codec_,
    )
    return self

consume async #

consume(msg: MsgType) -> Any

Consume a message asynchronously.

Source code in faststream/_internal/endpoint/subscriber/usecase.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
async def consume(self, msg: MsgType) -> Any:
    """Consume a message asynchronously."""
    if not self.running:
        return None

    try:
        return await self.process_message(msg)

    except StopConsume:
        # Stop handler at StopConsume exception
        await self.stop()

    except SystemExit:
        # Stop handler at `exit()` call
        await self.stop()

        if app := self._outer_config.context.get("app"):
            app.exit()

    except Exception:  # nosec B110  # ruff: ignore[try-except-pass]
        # All other exceptions were logged by CriticalLogMiddleware
        pass

process_message async #

process_message(msg: MsgType) -> Response

Execute all message processing stages.

Source code in faststream/_internal/endpoint/subscriber/usecase.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
async def process_message(self, msg: MsgType) -> "Response":
    """Execute all message processing stages."""
    context = self._outer_config.context
    logger_state = self._outer_config.logger

    async with AsyncExitStack() as stack:
        stack.enter_context(self.lock)

        # Enter context before middlewares
        stack.enter_context(
            context.scopes(
                (
                    ("handler_", self),
                    ("logger", logger_state.logger.logger),
                    *self._outer_config.extra_context.items(),
                ),
            ),
        )

        # reserve place for context scope under the middlewares __aexit__
        # because middlewares should be exited before context scope release
        message_scope = stack.enter_context(ExitStack())

        # enter all middlewares
        middlewares: list[BaseMiddleware] = []
        for base_m in self.__build__middlewares_stack():
            middleware = base_m(msg, context=context)
            middlewares.append(middleware)
            await stack.enter_async_context(middleware)

        cache: dict[Any, Any] = {}
        parsing_error: Exception | None = None
        for h in self.calls:
            try:
                message = await h.is_suitable(msg, cache)
            except Exception as e:
                parsing_error = e
                break

            if message is not None:
                message_scope.enter_context(
                    context.scopes(
                        (
                            ("log_context", self.get_log_context(message)),
                            ("message", message),
                        ),
                    ),
                )

                result_msg = ensure_response(
                    await h.call(
                        message=message,
                        # consumer middlewares
                        _extra_middlewares=(
                            m.consume_scope for m in middlewares[::-1]
                        ),
                    ),
                )

                if not result_msg.correlation_id:
                    result_msg.correlation_id = message.correlation_id

                for p in chain(
                    self.__get_response_publisher(message),
                    h.handler._publishers,
                ):
                    await p._publish(
                        result_msg.as_publish_command(),
                        _extra_middlewares=(
                            m.publish_scope for m in middlewares[::-1]
                        ),
                    )

                # Return data for tests
                return result_msg

        # Suitable handler was not found or
        # parsing/decoding exception occurred.
        # Reraise it to catch in tests
        if parsing_error:
            raise parsing_error

        error_msg = f"There is no suitable handler for {msg=}"
        raise SubscriberNotFound(error_msg)

    # An error was raised and processed by some middleware
    return ensure_response(None)

schema #

schema() -> dict[str, SubscriberSpec]
Source code in faststream/_internal/endpoint/subscriber/usecase.py
525
526
527
def schema(self) -> dict[str, "SubscriberSpec"]:
    self._build_fastdepends_model()
    return self.specification.get_schema()

routing #

routing() -> str
Source code in faststream/rabbit/subscriber/usecase.py
77
78
def routing(self) -> str:
    return f"{self._outer_config.prefix}{self.queue.routing()}"

start async #

start() -> None

Starts the consumer for the RabbitMQ queue.

Source code in faststream/rabbit/subscriber/usecase.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@override
async def start(self) -> None:
    """Starts the consumer for the RabbitMQ queue."""
    await super().start()

    queue_to_bind = self.queue.add_prefix(self._outer_config.prefix)

    declarer = self._outer_config.declarer

    self._queue_obj = queue = await declarer.declare_queue(
        queue_to_bind,
        channel=self.channel,
    )

    if (
        queue_to_bind.declare  # queue just getted from RMQ
        and self.exchange.name  # check Exchange is not default
    ):
        exchange = await declarer.declare_exchange(
            self.exchange,
            channel=self.channel,
        )

        await queue.bind(
            exchange,
            routing_key=queue_to_bind.routing(),
            arguments=queue_to_bind.bind_arguments,
            timeout=queue_to_bind.timeout,
            robust=self.queue.robust,
        )

    if self.calls:
        self._consumer_tag = await self._queue_obj.consume(
            # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage
            self.consume,  # type: ignore[arg-type]
            no_ack=self.__no_ack,
            arguments=self.consume_args,
        )

    self._post_start()

stop async #

stop() -> None
Source code in faststream/rabbit/subscriber/usecase.py
121
122
123
124
125
126
127
128
129
130
async def stop(self) -> None:
    await super().stop()

    if self._queue_obj is not None:
        if self._consumer_tag is not None:  # pragma: no branch
            if not self._queue_obj.channel.is_closed:
                await self._queue_obj.cancel(self._consumer_tag)
            self._consumer_tag = None

        self._queue_obj = None

get_one async #

get_one(
    *, timeout: float = 5.0, no_ack: bool = True
) -> RabbitMessage | None
Source code in faststream/rabbit/subscriber/usecase.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@override
async def get_one(
    self,
    *,
    timeout: float = 5.0,
    no_ack: bool = True,
) -> "RabbitMessage | None":
    assert self._queue_obj, "You should start subscriber at first."
    assert not self.calls, (
        "You can't use `get_one` method if subscriber has registered handlers."
    )

    sleep_interval = timeout / 10

    raw_message: IncomingMessage | None = None
    with (
        contextlib.suppress(asyncio.exceptions.CancelledError),
        anyio.move_on_after(timeout),
    ):
        while (  # ruff: ignore[async-busy-wait]
            raw_message := await self._queue_obj.get(
                fail=False,
                no_ack=no_ack,
                timeout=timeout,
            )
        ) is None:
            await anyio.sleep(sleep_interval)

    context = self._outer_config.context
    async_parser, async_decoder = self._get_parser_and_decoder()

    msg: RabbitMessage | None = await process_msg(  # type: ignore[assignment]
        msg=raw_message,
        middlewares=(
            m(raw_message, context=context) for m in self._broker_middlewares
        ),
        parser=async_parser,
        decoder=async_decoder,
    )
    return msg

build_log_context staticmethod #

build_log_context(
    message: Optional[StreamMessage[Any]],
    queue: RabbitQueue,
    exchange: Optional[RabbitExchange] = None,
) -> dict[str, str]
Source code in faststream/rabbit/subscriber/usecase.py
221
222
223
224
225
226
227
228
229
230
231
@staticmethod
def build_log_context(
    message: Optional["StreamMessage[Any]"],
    queue: "RabbitQueue",
    exchange: Optional["RabbitExchange"] = None,
) -> dict[str, str]:
    return {
        "queue": queue.name,
        "exchange": getattr(exchange, "name", ""),
        "message_id": getattr(message, "message_id", ""),
    }

get_log_context #

get_log_context(
    message: Optional[StreamMessage[Any]],
) -> dict[str, str]
Source code in faststream/rabbit/subscriber/usecase.py
233
234
235
236
237
238
239
240
241
def get_log_context(
    self,
    message: Optional["StreamMessage[Any]"],
) -> dict[str, str]:
    return self.build_log_context(
        message=message,
        queue=self.queue,
        exchange=self.exchange,
    )