Skip to content

StreamPublisher

faststream.redis.publisher.usecase.StreamPublisher #

StreamPublisher(*, stream, reply_to, headers, broker_middlewares, middlewares, schema_, title_, description_, include_in_schema)

Bases: LogicPublisher

Source code in faststream/redis/publisher/usecase.py
def __init__(
    self,
    *,
    stream: "StreamSub",
    reply_to: str,
    headers: Optional["AnyDict"],
    # Regular publisher options
    broker_middlewares: Iterable["BrokerMiddleware[UnifyRedisDict]"],
    middlewares: Iterable["PublisherMiddleware"],
    # AsyncAPI options
    schema_: Optional[Any],
    title_: Optional[str],
    description_: Optional[str],
    include_in_schema: bool,
) -> None:
    super().__init__(
        reply_to=reply_to,
        headers=headers,
        broker_middlewares=broker_middlewares,
        middlewares=middlewares,
        schema_=schema_,
        title_=title_,
        description_=description_,
        include_in_schema=include_in_schema,
    )

    self.stream = stream

title_ instance-attribute #

title_ = title_

description_ instance-attribute #

description_ = description_

include_in_schema instance-attribute #

include_in_schema = include_in_schema

name property #

name

Returns the name of the API operation.

description property #

description

Returns the description of the API operation.

schema_ instance-attribute #

schema_ = schema_

mock instance-attribute #

mock = None

calls instance-attribute #

calls = []

reply_to instance-attribute #

reply_to = reply_to

headers instance-attribute #

headers = headers

stream instance-attribute #

stream = stream

setup #

setup(*, producer)
Source code in faststream/broker/publisher/usecase.py
@override
def setup(  # type: ignore[override]
    self,
    *,
    producer: Optional["ProducerProto"],
) -> None:
    self._producer = producer

schema #

schema()

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

Source code in faststream/asyncapi/abc.py
def schema(self) -> Dict[str, Channel]:
    """Returns the schema of the API operation as a dictionary of channel names and channel objects."""
    if self.include_in_schema:
        return self.get_schema()
    else:
        return {}

add_middleware #

add_middleware(middleware)
Source code in faststream/broker/publisher/usecase.py
def add_middleware(self, middleware: "BrokerMiddleware[MsgType]") -> None:
    self._broker_middlewares = (*self._broker_middlewares, middleware)

create abstractmethod staticmethod #

create()

Abstract factory to create a real Publisher.

Source code in faststream/broker/publisher/proto.py
@staticmethod
@abstractmethod
def create() -> "PublisherProto[MsgType]":
    """Abstract factory to create a real Publisher."""
    ...

get_name abstractmethod #

get_name()

Name property fallback.

Source code in faststream/asyncapi/abc.py
@abstractmethod
def get_name(self) -> str:
    """Name property fallback."""
    raise NotImplementedError()

get_description #

get_description()

Description property fallback.

Source code in faststream/asyncapi/abc.py
def get_description(self) -> Optional[str]:
    """Description property fallback."""
    return None

get_schema abstractmethod #

get_schema()

Generate AsyncAPI schema.

Source code in faststream/asyncapi/abc.py
@abstractmethod
def get_schema(self) -> Dict[str, Channel]:
    """Generate AsyncAPI schema."""
    raise NotImplementedError()

get_payloads #

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

    if self.schema_:
        params = {"response__": (self.schema_, ...)}

        call_model: CallModel[Any, Any] = CallModel(
            call=lambda: None,
            model=create_model("Fake"),
            response_model=create_model(  # type: ignore[call-overload]
                "",
                __config__=get_config_base(),
                **params,
            ),
            params=params,
        )

        body = get_response_schema(
            call_model,
            prefix=f"{self.name}:Message",
        )
        if body:  # pragma: no branch
            payloads.append((body, ""))

    else:
        for call in self.calls:
            call_model = build_call_model(call)
            body = get_response_schema(
                call_model,
                prefix=f"{self.name}:Message",
            )
            if body:
                payloads.append((body, to_camelcase(unwrap(call).__name__)))

    return payloads

set_test #

set_test(*, mock, with_fake)

Turn publisher to testing mode.

Source code in faststream/broker/publisher/usecase.py
def set_test(
    self,
    *,
    mock: Annotated[
        MagicMock,
        Doc("Mock object to check in tests."),
    ],
    with_fake: Annotated[
        bool,
        Doc("Whetevet publisher's fake subscriber created or not."),
    ],
) -> None:
    """Turn publisher to testing mode."""
    self.mock = mock
    self._fake_handler = with_fake

reset_test #

reset_test()

Turn off publisher's testing mode.

Source code in faststream/broker/publisher/usecase.py
def reset_test(self) -> None:
    """Turn off publisher's testing mode."""
    self._fake_handler = False
    self.mock = None

subscriber_property #

subscriber_property(*, name_only)
Source code in faststream/redis/publisher/usecase.py
@override
def subscriber_property(self, *, name_only: bool) -> "AnyDict":
    return {
        "channel": None,
        "list": None,
        "stream": self.stream.name if name_only else self.stream,
    }

add_prefix #

add_prefix(prefix)
Source code in faststream/redis/publisher/usecase.py
def add_prefix(self, prefix: str) -> None:
    stream_sub = deepcopy(self.stream)
    stream_sub.name = "".join((prefix, stream_sub.name))
    self.stream = stream_sub

publish async #

publish(message=None, stream=None, reply_to='', headers=None, correlation_id=None, *, maxlen=None, rpc=False, rpc_timeout=30.0, raise_timeout=False, _extra_middlewares=())
Source code in faststream/redis/publisher/usecase.py
@override
async def publish(
    self,
    message: Annotated[
        "SendableMessage",
        Doc("Message body to send."),
    ] = None,
    stream: Annotated[
        Optional[str],
        Doc("Redis Stream object name to send message."),
    ] = None,
    reply_to: Annotated[
        str,
        Doc("Reply message destination PubSub object name."),
    ] = "",
    headers: Annotated[
        Optional["AnyDict"],
        Doc("Message headers to store metainformation."),
    ] = None,
    correlation_id: Annotated[
        Optional[str],
        Doc(
            "Manual message **correlation_id** setter. "
            "**correlation_id** is a useful option to trace messages."
        ),
    ] = None,
    *,
    maxlen: Annotated[
        Optional[int],
        Doc(
            "Redis Stream maxlen publish option. "
            "Remove eldest message if maxlen exceeded."
        ),
    ] = None,
    # rpc args
    rpc: Annotated[
        bool,
        Doc("Whether to wait for reply in blocking mode."),
        deprecated(
            "Deprecated in **FastStream 0.5.17**. "
            "Please, use `request` method instead. "
            "Argument will be removed in **FastStream 0.6.0**."
        ),
    ] = False,
    rpc_timeout: Annotated[
        Optional[float],
        Doc("RPC reply waiting time."),
        deprecated(
            "Deprecated in **FastStream 0.5.17**. "
            "Please, use `request` method with `timeout` instead. "
            "Argument will be removed in **FastStream 0.6.0**."
        ),
    ] = 30.0,
    raise_timeout: Annotated[
        bool,
        Doc(
            "Whetever to raise `TimeoutError` or return `None` at **rpc_timeout**. "
            "RPC request returns `None` at timeout by default."
        ),
        deprecated(
            "Deprecated in **FastStream 0.5.17**. "
            "`request` always raises TimeoutError instead. "
            "Argument will be removed in **FastStream 0.6.0**."
        ),
    ] = False,
    # publisher specific
    _extra_middlewares: Annotated[
        Iterable["PublisherMiddleware"],
        Doc("Extra middlewares to wrap publishing process."),
    ] = (),
) -> Optional[Any]:
    assert self._producer, NOT_CONNECTED_YET  # nosec B101

    stream_sub = StreamSub.validate(stream or self.stream)
    maxlen = maxlen or stream_sub.maxlen
    reply_to = reply_to or self.reply_to
    headers = headers or self.headers
    correlation_id = correlation_id or gen_cor_id()

    call: AsyncFunc = self._producer.publish

    for m in chain(
        (
            _extra_middlewares
            or (m(None).publish_scope for m in self._broker_middlewares)
        ),
        self._middlewares,
    ):
        call = partial(m, call)

    return await call(
        message,
        stream=stream_sub.name,
        maxlen=maxlen,
        # basic args
        reply_to=reply_to,
        headers=headers,
        correlation_id=correlation_id,
        # RPC args
        rpc=rpc,
        rpc_timeout=rpc_timeout,
        raise_timeout=raise_timeout,
    )

request async #

request(message=None, stream=None, *, maxlen=None, correlation_id=None, headers=None, timeout=30.0, _extra_middlewares=())
Source code in faststream/redis/publisher/usecase.py
@override
async def request(
    self,
    message: Annotated[
        "SendableMessage",
        Doc("Message body to send."),
    ] = None,
    stream: Annotated[
        Optional[str],
        Doc("Redis Stream object name to send message."),
    ] = None,
    *,
    maxlen: Annotated[
        Optional[int],
        Doc(
            "Redis Stream maxlen publish option. "
            "Remove eldest message if maxlen exceeded."
        ),
    ] = None,
    correlation_id: Annotated[
        Optional[str],
        Doc(
            "Manual message **correlation_id** setter. "
            "**correlation_id** is a useful option to trace messages."
        ),
    ] = None,
    headers: Annotated[
        Optional["AnyDict"],
        Doc("Message headers to store metainformation."),
    ] = None,
    timeout: Annotated[
        Optional[float],
        Doc("RPC reply waiting time."),
    ] = 30.0,
    # publisher specific
    _extra_middlewares: Annotated[
        Iterable["PublisherMiddleware"],
        Doc("Extra middlewares to wrap publishing process."),
    ] = (),
) -> "RedisMessage":
    assert self._producer, NOT_CONNECTED_YET  # nosec B101

    kwargs = {
        "stream": StreamSub.validate(stream or self.stream).name,
        # basic args
        "headers": headers or self.headers,
        "correlation_id": correlation_id or gen_cor_id(),
        "timeout": timeout,
    }

    request: AsyncFunc = self._producer.request

    for pub_m in chain(
        (
            _extra_middlewares
            or (m(None).publish_scope for m in self._broker_middlewares)
        ),
        self._middlewares,
    ):
        request = partial(pub_m, request)

    published_msg = await request(
        message,
        **kwargs,
    )

    async with AsyncExitStack() as stack:
        return_msg: Callable[[RedisMessage], Awaitable[RedisMessage]] = return_input
        for m in self._broker_middlewares:
            mid = m(published_msg)
            await stack.enter_async_context(mid)
            return_msg = partial(mid.consume_scope, return_msg)

        parsed_msg = await self._producer._parser(published_msg)
        parsed_msg._decoded_body = await self._producer._decoder(parsed_msg)
        parsed_msg._source_type = SourceType.Response
        return await return_msg(parsed_msg)

    raise AssertionError("unreachable")