Skip to content

LogicNatsHandler

faststream.nats.handler.LogicNatsHandler #

LogicNatsHandler(subject: str, log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]], queue: str = '', stream: Optional[JStream] = None, pull_sub: Optional[PullSub] = None, extra_options: Optional[AnyDict] = None, graceful_timeout: Optional[float] = None, max_workers: int = 1, description: Optional[str] = None, title: Optional[str] = None, include_in_schema: bool = True)

Bases: AsyncHandler[Msg]

A class to represent a NATS handler.

Initialize the NATS handler.

Source code in faststream/nats/handler.py
def __init__(
    self,
    subject: Annotated[
        str,
        Doc("NATS subject to subscribe"),
    ],
    log_context_builder: Annotated[
        Callable[[StreamMessage[Any]], Dict[str, str]],
        Doc("Function to create log extra data by message"),
    ],
    queue: Annotated[
        str,
        Doc("NATS queue name"),
    ] = "",
    stream: Annotated[
        Optional[JStream],
        Doc("NATS Stream object"),
    ] = None,
    pull_sub: Annotated[
        Optional[PullSub],
        Doc("NATS Pull consumer parameters container"),
    ] = None,
    extra_options: Annotated[
        Optional[AnyDict],
        Doc("Extra arguments for subscription creation"),
    ] = None,
    graceful_timeout: Annotated[
        Optional[float],
        Doc(
            "Wait up to this time (if set) in graceful shutdown mode. "
            "Kills task forcefully if expired."
        ),
    ] = None,
    max_workers: Annotated[
        int,
        Doc("Process up to this parameter messages concurrently"),
    ] = 1,
    # AsyncAPI information
    description: Annotated[
        Optional[str],
        Doc("AsyncAPI subscriber description"),
    ] = None,
    title: Annotated[
        Optional[str],
        Doc("AsyncAPI subscriber title"),
    ] = None,
    include_in_schema: Annotated[
        bool,
        Doc("Whether to include the handler in AsyncAPI schema"),
    ] = True,
) -> None:
    """Initialize the NATS handler."""
    reg, path = compile_path(
        subject,
        replace_symbol="*",
        patch_regex=lambda x: x.replace(".>", "..+"),
    )
    self.subject = path
    self.path_regex = reg

    self.queue = queue

    self.stream = stream
    self.pull_sub = pull_sub
    self.extra_options = extra_options or {}

    super().__init__(
        log_context_builder=log_context_builder,
        description=description,
        include_in_schema=include_in_schema,
        title=title,
        graceful_timeout=graceful_timeout,
    )

    self.max_workers = max_workers
    self.subscription = None

    self.send_stream, self.receive_stream = anyio.create_memory_object_stream(
        max_buffer_size=max_workers
    )
    self.limiter = anyio.Semaphore(max_workers)
    self.task = None

call_name property #

call_name: str

Returns the name of the handler call.

calls instance-attribute #

calls: List[Tuple[HandlerCallWrapper[MsgType, Any, SendableMessage], Callable[[StreamMessage[MsgType]], Awaitable[bool]], AsyncParser[MsgType, Any], AsyncDecoder[StreamMessage[MsgType]], Sequence[Callable[[Any], BaseMiddleware]], CallModel[Any, SendableMessage]]]

description property #

description: Optional[str]

Returns the description of the handler.

extra_options instance-attribute #

extra_options = extra_options or {}

global_middlewares instance-attribute #

global_middlewares: Sequence[Callable[[Any], BaseMiddleware]] = []

graceful_timeout instance-attribute #

graceful_timeout = graceful_timeout

include_in_schema instance-attribute #

include_in_schema = include_in_schema

limiter instance-attribute #

limiter = Semaphore(max_workers)

lock instance-attribute #

lock = MultiLock()

log_context_builder instance-attribute #

log_context_builder = log_context_builder

max_workers instance-attribute #

max_workers = max_workers

path_regex instance-attribute #

path_regex = reg

pull_sub instance-attribute #

pull_sub = pull_sub

queue instance-attribute #

queue = queue

receive_stream instance-attribute #

receive_stream: MemoryObjectReceiveStream[Msg]

running instance-attribute #

running = False

send_stream instance-attribute #

send_stream: MemoryObjectSendStream[Msg]

stream instance-attribute #

stream = stream

subject instance-attribute #

subject = path

subscription instance-attribute #

subscription: Union[None, Subscription, PushSubscription, PullSubscription] = None

task instance-attribute #

task: Optional[Task[Any]] = None

task_group instance-attribute #

task_group: Optional[TaskGroup]

add_call #

add_call(*, handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn], dependant: CallModel[P_HandlerParams, T_HandlerReturn], parser: Optional[CustomParser[Msg, NatsMessage]], decoder: Optional[CustomDecoder[NatsMessage]], filter: Filter[NatsMessage], middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]]) -> None
Source code in faststream/nats/handler.py
def add_call(
    self,
    *,
    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],
    dependant: CallModel[P_HandlerParams, T_HandlerReturn],
    parser: Optional[CustomParser[Msg, NatsMessage]],
    decoder: Optional[CustomDecoder[NatsMessage]],
    filter: Filter[NatsMessage],
    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],
) -> None:
    parser_ = Parser if self.stream is None else JsParser
    super().add_call(
        handler=handler,
        parser=resolve_custom_func(parser, parser_.parse_message),
        decoder=resolve_custom_func(decoder, parser_.decode_message),
        filter=filter,  # type: ignore[arg-type]
        dependant=dependant,
        middlewares=middlewares,
    )

close async #

close() -> None

Clean up handler subscription, cancel consume task in graceful mode.

Source code in faststream/nats/handler.py
async def close(self) -> None:
    """Clean up handler subscription, cancel consume task in graceful mode."""
    await super().close()

    if self.subscription is not None:
        await self.subscription.unsubscribe()
        self.subscription = None

    if self.task is not None:
        self.task.cancel()
        self.task = None

consume async #

consume(msg: MsgType) -> SendableMessage

Consume a message asynchronously.

PARAMETER DESCRIPTION
msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION
SendableMessage

The sendable message.

RAISES DESCRIPTION
StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION
Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override
async def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]
    """Consume a message asynchronously.

    Args:
        msg: The message to be consumed.

    Returns:
        The sendable message.

    Raises:
        StopConsume: If the consumption needs to be stopped.

    Raises:
        Exception: If an error occurs during consumption.

    """
    result: Optional[WrappedReturn[SendableMessage]] = None
    result_msg: SendableMessage = None

    if not self.running:
        return result_msg

    log_context_tag: Optional["Token[Any]"] = None
    async with AsyncExitStack() as stack:
        stack.enter_context(self.lock)

        stack.enter_context(context.scope("handler_", self))

        gl_middlewares: List[BaseMiddleware] = [
            await stack.enter_async_context(m(msg)) for m in self.global_middlewares
        ]

        logged = False
        processed = False
        for handler, filter_, parser, decoder, middlewares, _ in self.calls:
            local_middlewares: List[BaseMiddleware] = [
                await stack.enter_async_context(m(msg)) for m in middlewares
            ]

            all_middlewares = gl_middlewares + local_middlewares

            # TODO: add parser & decoder caches
            message = await parser(msg)

            if not logged:  # pragma: no branch
                log_context_tag = context.set_local(
                    "log_context",
                    self.log_context_builder(message),
                )

            message.decoded_body = await decoder(message)
            message.processed = processed

            if await filter_(message):
                assert (  # nosec B101
                    not processed
                ), "You can't process a message with multiple consumers"

                try:
                    async with AsyncExitStack() as consume_stack:
                        for m_consume in all_middlewares:
                            message.decoded_body = (
                                await consume_stack.enter_async_context(
                                    m_consume.consume_scope(message.decoded_body)
                                )
                            )

                        result = await cast(
                            Awaitable[Optional[WrappedReturn[SendableMessage]]],
                            handler.call_wrapped(message),
                        )

                    if result is not None:
                        result_msg, pub_response = result

                        # TODO: suppress all publishing errors and raise them after all publishers will be tried
                        for publisher in (pub_response, *handler._publishers):
                            if publisher is not None:
                                async with AsyncExitStack() as pub_stack:
                                    result_to_send = result_msg

                                    for m_pub in all_middlewares:
                                        result_to_send = (
                                            await pub_stack.enter_async_context(
                                                m_pub.publish_scope(result_to_send)
                                            )
                                        )

                                    await publisher.publish(
                                        message=result_to_send,
                                        correlation_id=message.correlation_id,
                                    )

                except StopConsume:
                    await self.close()
                    handler.trigger()

                except HandlerException as e:  # pragma: no cover
                    handler.trigger()
                    raise e

                except Exception as e:
                    handler.trigger(error=e)
                    raise e

                else:
                    handler.trigger(result=result[0] if result else None)
                    message.processed = processed = True
                    if IS_OPTIMIZED:  # pragma: no cover
                        break

        assert not self.running or processed, "You have to consume message"  # nosec B101

    if log_context_tag is not None:
        context.reset_local("log_context", log_context_tag)

    return result_msg

get_payloads #

get_payloads() -> List[Tuple[AnyDict, str]]

Get the payloads of the handler.

Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:
    """Get the payloads of the handler."""
    payloads: List[Tuple[AnyDict, str]] = []

    for h, _, _, _, _, dep in self.calls:
        body = parse_handler_params(
            dep,
            prefix=f"{self._title or self.call_name}:Message",
        )
        payloads.append(
            (
                body,
                to_camelcase(unwrap(h._original_call).__name__),
            ),
        )

    return payloads

get_routing_hash staticmethod #

get_routing_hash(subject: str) -> str

Get handler hash by outer data.

Using to find handler in broker.handlers dictionary.

Source code in faststream/nats/handler.py
@staticmethod
def get_routing_hash(
    subject: Annotated[str, Doc("NATS subject to consume messages")],
) -> str:
    """Get handler hash by outer data.

    Using to find handler in `broker.handlers` dictionary.
    """
    return subject

name #

name() -> str

Returns the name of the API operation.

Source code in faststream/asyncapi/base.py
@abstractproperty
def name(self) -> str:
    """Returns the name of the API operation."""
    raise NotImplementedError()

schema #

schema() -> Dict[str, Channel]

Returns the schema of the API operation as a dictionary of channel names and channel objects.

Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover
    """Returns the schema of the API operation as a dictionary of channel names and channel objects."""
    return {}

start async #

start(connection: Union[Client, JetStreamContext]) -> None

Create NATS subscription and start consume task.

Source code in faststream/nats/handler.py
@override
async def start(  # type: ignore[override]
    self,
    connection: Annotated[
        Union[Client, JetStreamContext],
        Doc("NATS client or JS Context object using to create subscription"),
    ],
) -> None:
    """Create NATS subscription and start consume task."""
    cb: Callable[[Msg], Awaitable[SendableMessage]]
    if self.max_workers > 1:
        self.task = asyncio.create_task(self._serve_consume_queue())
        cb = self.__put_msg
    else:
        cb = self.consume

    if self.pull_sub is not None:
        connection = cast(JetStreamContext, connection)

        if self.stream is None:
            raise ValueError("Pull subscriber can be used only with a stream")

        self.subscription = await connection.pull_subscribe(
            subject=self.subject,
            **self.extra_options,
        )
        self.task = asyncio.create_task(self._consume_pull(cb))

    else:
        self.subscription = await connection.subscribe(
            subject=self.subject,
            queue=self.queue,
            cb=cb,  # type: ignore[arg-type]
            **self.extra_options,
        )

    await super().start()