Coverage for faststream/asgi/factories/asyncapi/try_it_out.py: 87%
81 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
1from collections.abc import Callable, Iterable, Sequence
2from contextlib import suppress
3from typing import TYPE_CHECKING, Any, TypedDict, Union, cast
5from faststream.asgi.annotations import Request
6from faststream.asgi.handlers import PostHandler, post
7from faststream.asgi.response import AsgiResponse, JSONResponse
8from faststream.exceptions import SubscriberNotFound
10if TYPE_CHECKING:
11 from faststream._internal.broker import BrokerUsecase
12 from faststream._internal.testing.broker import TestBroker
13 from faststream.specification.schema import Tag, TagDict
16class TryItOutOptions(TypedDict, total=False):
17 sendToRealBroker: bool
18 timestamp: str
21class TryItOutMessage(TypedDict, total=False):
22 """Wrapper sent by asyncapi-try-it-plugin.
24 The plugin always wraps the user's payload inside a nested ``message``
25 field together with operation metadata::
27 {
28 "operation_id": "...",
29 "operation_type": "...",
30 "message": <actual_user_payload>
31 }
32 """
34 operation_id: str
35 operation_type: str
36 message: Any
39class TryItOutForm(TypedDict):
40 channelName: str
41 message: TryItOutMessage
42 options: TryItOutOptions
45class TryItOutProcessor:
46 """Dispatch try-it-out requests by the exact AsyncAPI channel when possible."""
48 def __init__(self, *brokers: "BrokerUsecase[Any, Any, Any]") -> None:
49 self._entries: list[
50 tuple[BrokerUsecase[Any, Any, Any], type[TestBroker[Any, Any]]]
51 ] = []
52 # `unittest.mock` comes with the test brokers: keep it out of `import faststream`
53 from faststream._internal.testing.broker import find_test_broker # ruff: ignore[import-outside-top-level]
55 for broker in brokers:
56 test_broker_cls = find_test_broker(broker)
57 if test_broker_cls is None: 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true
58 msg = f"TestBroker not available for {broker}. Please, inspect your dependencies."
59 raise ValueError(msg)
60 self._entries.append((broker, test_broker_cls))
62 if not self._entries:
63 msg = "TryItOutProcessor requires at least one broker."
64 raise ValueError(msg)
66 async def process(self, body: TryItOutForm) -> AsgiResponse:
67 """Process parsed body: validate, dry-run or publish. Returns response."""
68 channel = body.get("channelName", "")
69 destination, *_ = channel.split(":")
71 if not destination:
72 return JSONResponse({"details": "Missing channelName"}, 400)
74 if len(self._entries) == 1:
75 broker, test_broker_cls = self._entries[0]
76 else:
77 entry = next(
78 (e for e in self._entries if channel in _iter_broker_channels(e[0])),
79 None,
80 )
82 if entry is None:
83 entry = next(
84 (
85 e
86 for e in self._entries
87 if destination in _iter_broker_destinations(e[0])
88 ),
89 None,
90 )
92 if entry is None:
93 return JSONResponse(
94 {"details": f"{destination} destination not found."}, 404
95 )
97 broker, test_broker_cls = entry
98 payload: Any = body.get("message", {}).get("message")
99 use_real_broker = body.get("options", {}).get("sendToRealBroker", False)
101 try:
102 if use_real_broker: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 await broker.publish(payload, destination)
104 return JSONResponse("ok", 200)
106 same_type_brokers = (
107 broker,
108 *(
109 b
110 for b, cls in self._entries
111 if cls is test_broker_cls and b is not broker
112 ),
113 )
114 # ``test_broker_cls`` is typed as the abstract ``TestBroker`` base, whose
115 # overloaded ``__init__`` would make mypy try to instantiate the abstract
116 # class. At runtime it is always a concrete subclass; the enter result is
117 # unused here, so call it through a plain factory type.
118 test_broker_factory = cast(
119 "Callable[..., TestBroker[Any, Any]]", test_broker_cls
120 )
121 async with test_broker_factory(*same_type_brokers):
122 data = await broker.request(payload, destination, timeout=30)
123 decoded = None
124 with suppress(Exception):
125 decoded = await data.decode()
126 return JSONResponse(
127 decoded if decoded is not None and decoded != b"" else "ok", 200
128 )
130 except SubscriberNotFound:
131 return JSONResponse({"details": f"{destination} destination not found."}, 404)
133 except Exception as e:
134 return JSONResponse({"details": repr(e)}, 500)
137def make_try_it_out_handler(
138 brokers: Iterable["BrokerUsecase[Any, Any, Any]"],
139 description: str | None = None,
140 tags: Sequence[Union["Tag", "TagDict", dict[str, Any]]] | None = None,
141 unique_id: str | None = None,
142 include_in_schema: bool = False,
143) -> "PostHandler":
144 """POST handler for asyncapi-try-it-plugin (first owner of the channel wins)."""
145 processor = TryItOutProcessor(*brokers)
147 @post(
148 description=description,
149 tags=tags,
150 unique_id=unique_id,
151 include_in_schema=include_in_schema,
152 )
153 async def try_it_out(request: Request) -> AsgiResponse:
154 try:
155 body: TryItOutForm = await request.json()
157 except Exception as e:
158 return JSONResponse({"details": f"Invalid JSON: {e}"}, 400)
160 return await processor.process(body)
162 return try_it_out
165def _iter_broker_destinations(broker: "BrokerUsecase[Any, Any, Any]") -> set[str]:
166 """Destinations declared on the broker (``schema()`` key before ``:``)."""
167 destinations: set[str] = set()
169 for sub in broker.subscribers:
170 with suppress(Exception):
171 destinations.update(key.split(":", 1)[0] for key in sub.schema())
173 for pub in broker.publishers: 173 ↛ 174line 173 didn't jump to line 174 because the loop on line 173 never started
174 with suppress(Exception):
175 destinations.update(key.split(":", 1)[0] for key in pub.schema())
177 return destinations
180def _iter_broker_channels(broker: "BrokerUsecase[Any, Any, Any]") -> set[str]:
181 """Full AsyncAPI channel keys declared on the broker."""
182 channels: set[str] = set()
184 for sub in broker.subscribers:
185 with suppress(Exception):
186 channels.update(sub.schema())
188 for pub in broker.publishers: 188 ↛ 189line 188 didn't jump to line 189 because the loop on line 188 never started
189 with suppress(Exception):
190 channels.update(pub.schema())
192 return channels