Coverage for faststream/_internal/endpoint/utils.py: 97%
27 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import inspect
2from collections.abc import Awaitable, Callable, Iterable
3from contextlib import AsyncExitStack
4from functools import partial
5from typing import TYPE_CHECKING, Any, Optional, cast
7from faststream._internal.types import MsgType
8from faststream._internal.utils.functions import return_input, to_async
9from faststream.message.source_type import SourceType
11if TYPE_CHECKING:
12 from faststream._internal.types import (
13 AsyncCallable,
14 CustomCallable,
15 SyncCallable,
16 )
17 from faststream.message import StreamMessage
18 from faststream.middlewares import BaseMiddleware
21async def process_msg(
22 msg: MsgType | None,
23 *,
24 middlewares: Iterable["BaseMiddleware"],
25 parser: Callable[[MsgType], Awaitable["StreamMessage[MsgType]"]],
26 decoder: Callable[["StreamMessage[MsgType]"], "Any"],
27 source_type: SourceType = SourceType.CONSUME,
28) -> Optional["StreamMessage[MsgType]"]:
29 if msg is None:
30 return None
32 async with AsyncExitStack() as stack:
33 return_msg: Callable[
34 [StreamMessage[MsgType]],
35 Awaitable[StreamMessage[MsgType]],
36 ] = return_input
38 for m in middlewares:
39 await stack.enter_async_context(m)
40 return_msg = partial(m.consume_scope, return_msg)
42 parsed_msg = await parser(msg)
43 parsed_msg.source_type = source_type
44 parsed_msg.set_decoder(decoder)
45 return await return_msg(parsed_msg)
47 error_msg = "unreachable"
48 raise AssertionError(error_msg)
51class ParserComposition:
52 __slots__ = (
53 "custom_func",
54 "default_func",
55 "wrapped_func",
56 )
58 def __init__(
59 self,
60 custom_func: Optional["CustomCallable"],
61 default_func: "AsyncCallable",
62 ) -> None:
63 self.custom_func = custom_func
64 self.default_func = default_func
66 if custom_func is None:
67 self.wrapped_func = default_func
68 else:
69 original_params = inspect.signature(custom_func).parameters
71 if len(original_params) == 1:
72 self.wrapped_func = to_async(
73 cast("SyncCallable | AsyncCallable", custom_func)
74 )
76 else:
77 name = tuple(original_params.items())[1][0]
78 self.wrapped_func = partial(to_async(custom_func), **{name: default_func})
80 def __call__(self, *args: Any, **kwargs: Any) -> Any:
81 return self.wrapped_func(*args, **kwargs)