Coverage for faststream/_internal/endpoint/subscriber/hints.py: 93%
37 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 Iterator
2from types import UnionType
3from typing import TYPE_CHECKING, Annotated, Any, Union, get_args, get_origin
5from faststream._internal._compat import ExceptionGroup
6from faststream._internal.configs import (
7 UnderlyingDriverAnnotation,
8 UnderlyingDriverAnnotations,
9)
10from faststream.exceptions import SetupError
12if TYPE_CHECKING:
13 from fast_depends.core import CallModel
14 from fast_depends.library.serializer import OptionItem
17def check_context_annotations(
18 dependent: "CallModel",
19 annotations: UnderlyingDriverAnnotations,
20) -> None:
21 """Reject call model arguments annotated with a broker's own driver class.
23 Context annotations never reach the model's params, so any driver class
24 found there would be validated as message data.
26 Args:
27 dependent: the handler's call model, dependencies included.
28 annotations: driver type hint to the context annotation replacing it. An
29 `UnderlyingDriverAnnotation` value also names the import to suggest.
30 """
31 messages = [
32 _format_hint(option.field_name, hint, annotations[hint], dependency)
33 for dependency, option in _options(dependent)
34 if (hint := _find_mapped(option.field_type, annotations)) is not None
35 ]
36 # a dependency shared by several arguments is still one mistake
37 errors = [SetupError(m) for m in dict.fromkeys(messages)]
39 if len(errors) == 1:
40 raise errors[0]
42 if errors:
43 msg = f"`{dependent.call_name}` has arguments FastStream cannot inject."
44 raise ExceptionGroup(msg, errors)
47def _options(
48 model: "CallModel",
49 dependency: str | None = None,
50) -> Iterator[tuple[str | None, "OptionItem"]]:
51 for option in model.params:
52 yield dependency, option
54 for key in (*model.dependencies.values(), *model.extra_dependencies):
55 sub_model = model.dependency_provider.get_dependant(key)
56 yield from _options(sub_model, sub_model.call_name)
59def _find_mapped(hint: Any, annotations: UnderlyingDriverAnnotations) -> Any:
60 origin = get_origin(hint)
62 if origin is Annotated:
63 return _find_mapped(get_args(hint)[0], annotations)
65 if origin is Union or origin is UnionType:
66 for arg in get_args(hint):
67 if (mapped := _find_mapped(arg, annotations)) is not None:
68 return mapped
69 return None
71 if origin is not None and origin in annotations:
72 return origin
74 try:
75 return hint if hint in annotations else None
76 except TypeError:
77 # An unhashable hint cannot be a key, so it cannot be mapped.
78 return None
81def _format_hint(
82 field_name: str,
83 hint: Any,
84 annotation: Any,
85 dependency: str | None,
86) -> str:
87 owner = f" of dependency `{dependency}`" if dependency else ""
88 message = (
89 f"`{field_name}`{owner} is annotated with `{_describe(hint)}`, "
90 "which FastStream cannot inject.\n"
91 )
93 if isinstance(annotation, UnderlyingDriverAnnotation):
94 return (
95 f"{message}Use the context annotation instead:\n"
96 f"\n from {annotation.module} import {annotation.name}\n"
97 )
99 return f"{message}Use the corresponding context annotation instead: `{annotation}`"
102def _describe(hint: Any) -> str:
103 if isinstance(hint, type): 103 ↛ 106line 103 didn't jump to line 106 because the condition on line 103 was always true
104 return f"{hint.__module__}.{hint.__qualname__}"
106 return str(hint)