We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Enhancement: resolve forward refs when producing signature models
We need to support where users declare `from __future__ import annotations` in modules where handlers and dependencies are declared.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlite/signature.py`
Content:
```
1 from inspect import Parameter, Signature
2 from typing import (
3     TYPE_CHECKING,
4     Any,
5     ClassVar,
6     Dict,
7     Generator,
8     List,
9     Set,
10     Tuple,
11     Type,
12     Union,
13     cast,
14 )
15 
16 from pydantic import BaseConfig, BaseModel, ValidationError, create_model
17 from pydantic.fields import FieldInfo, Undefined
18 from pydantic_factories import ModelFactory
19 from typing_extensions import get_args
20 
21 from starlite.connection import Request, WebSocket
22 from starlite.enums import ScopeType
23 from starlite.exceptions import (
24     ImproperlyConfiguredException,
25     InternalServerException,
26     ValidationException,
27 )
28 from starlite.plugins.base import PluginMapping, PluginProtocol, get_plugin_for_value
29 from starlite.utils import (
30     is_dependency_field,
31     is_optional_union,
32     should_skip_dependency_validation,
33 )
34 
35 if TYPE_CHECKING:
36     from pydantic.error_wrappers import ErrorDict
37 
38     from starlite.datastructures import URL
39     from starlite.types import AnyCallable
40 
41 
42 UNDEFINED_SENTINELS = {Undefined, Signature.empty}
43 SKIP_NAMES = {"self", "cls"}
44 SKIP_VALIDATION_NAMES = {"request", "socket", "state", "scope"}
45 
46 
47 class SignatureModel(BaseModel):
48     """Pydantic model representing a signature."""
49 
50     class Config(BaseConfig):
51         arbitrary_types_allowed = True
52 
53     dependency_name_set: ClassVar[Set[str]]
54     field_plugin_mappings: ClassVar[Dict[str, PluginMapping]]
55     return_annotation: ClassVar[Any]
56 
57     @classmethod
58     def parse_values_from_connection_kwargs(
59         cls, connection: Union[Request, WebSocket], **kwargs: Any
60     ) -> Dict[str, Any]:
61         """Given a dictionary of values extracted from the connection, create an instance of the given SignatureModel
62         subclass and return the parsed values.
63 
64         This is not equivalent to calling the '.dict'  method of the pydantic model, because it doesn't convert nested
65         values into dictionary, just extracts the data from the signature model
66         """
67         try:
68             signature = cls(**kwargs)
69             return {key: signature.resolve_field_value(key) for key in cls.__fields__}
70         except ValidationError as exc:
71             raise cls.construct_exception(connection, exc) from exc
72 
73     def resolve_field_value(self, key: str) -> Any:
74         """Given a field key, return value using plugin mapping, if available."""
75         value = self.__getattribute__(key)  # pylint: disable=unnecessary-dunder-call
76         mapping = self.field_plugin_mappings.get(key)
77         return mapping.get_model_instance_for_value(value) if mapping else value
78 
79     @classmethod
80     def construct_exception(
81         cls, connection: Union[Request, WebSocket], exc: ValidationError
82     ) -> Union[InternalServerException, ValidationException]:
83         """Distinguish between validation errors that arise from parameters and dependencies.
84 
85         If both parameter and dependency values are invalid, we raise the client error first.
86 
87         Args:
88             connection: A Request or WebSocket
89             exc: A ValidationError
90 
91         Returns:
92             A ValidationException or InternalServerException
93         """
94         server_errors: List["ErrorDict"] = []
95         client_errors: List["ErrorDict"] = []
96 
97         for error in exc.errors():
98             if cls.is_server_error(error):
99                 server_errors.append(error)
100             else:
101                 client_errors.append(error)
102 
103         method, url = cls.get_connection_method_and_url(connection)
104 
105         if client_errors:
106             return ValidationException(detail=f"Validation failed for {method} {url}", extra=client_errors)
107 
108         return InternalServerException(detail=f"A dependency failed validation for {method} {url}", extra=server_errors)
109 
110     @classmethod
111     def is_server_error(cls, error: "ErrorDict") -> bool:
112         """Check whether given validation error is a server error."""
113         return error["loc"][-1] in cls.dependency_name_set
114 
115     @staticmethod
116     def get_connection_method_and_url(connection: Union[Request, WebSocket]) -> Tuple[str, "URL"]:
117         """Extract method and URL from Request or WebSocket."""
118         method = ScopeType.WEBSOCKET if isinstance(connection, WebSocket) else connection.method
119         return method, connection.url
120 
121 
122 class SignatureParameter:
123     """Represents the parameters of a callable for purpose of signature model generation."""
124 
125     __slots__ = (
126         "annotation",
127         "default",
128         "name",
129         "optional",
130     )
131 
132     annotation: Any
133     default: Any
134     name: str
135     optional: bool
136 
137     def __init__(self, fn_name: str, parameter_name: str, parameter: Parameter) -> None:
138         """Initialize SignatureParameter.
139 
140         Args:
141             fn_name: Name of function.
142             parameter_name: Name of parameter.
143             parameter: inspect.Parameter
144         """
145         if parameter.annotation is Signature.empty:
146             raise ImproperlyConfiguredException(
147                 f"Kwarg {parameter_name} of {fn_name} does not have a type annotation. If it "
148                 f"should receive any value, use the 'Any' type."
149             )
150         self.annotation = parameter.annotation
151         self.default = parameter.default
152         self.name = parameter_name
153         self.optional = is_optional_union(parameter.annotation)
154 
155     @property
156     def default_defined(self) -> bool:
157         """Return a boolean, indicating if `self.default` is not one of the undefined sentinel types."""
158         return self.default not in UNDEFINED_SENTINELS
159 
160 
161 class SignatureModelFactory:
162     """Utility class for constructing the signature model and grouping associated state.
163 
164     Instance available at `SignatureModel.factory`.
165 
166     The following attributes are populated after the `model()` method has been called to generate
167     the `SignatureModel` subclass.
168 
169     Attributes:
170         field_plugin_mappings: Maps parameter name, to `PluginMapping` where a plugin has been applied.
171         field_definitions:  Maps parameter name to the `(<type>, <default>)` tuple passed to `pydantic.create_model()`.
172         defaults: Maps parameter name to default value, if one defined.
173         dependency_name_set: The names of all known dependency parameters.
174     """
175 
176     __slots__ = (
177         "defaults",
178         "dependency_name_set",
179         "field_definitions",
180         "field_plugin_mappings",
181         "fn_name",
182         "plugins",
183         "signature",
184     )
185 
186     def __init__(self, fn: "AnyCallable", plugins: List["PluginProtocol"], dependency_names: Set[str]) -> None:
187         """Initialise `SignatureModelFactory`
188 
189         Args:
190             fn: A callable
191             plugins: A list of plugins
192             dependency_names: Dependency names
193         """
194         if fn is None:
195             raise ImproperlyConfiguredException("Parameter `fn` to `SignatureModelFactory` cannot be `None`.")
196         self.signature = Signature.from_callable(fn)
197         self.fn_name = fn.__name__ if hasattr(fn, "__name__") else "anonymous"
198         self.plugins = plugins
199         self.field_plugin_mappings: Dict[str, PluginMapping] = {}
200         self.field_definitions: Dict[str, Any] = {}
201         self.defaults: Dict[str, Any] = {}
202         self.dependency_name_set = dependency_names
203 
204     def check_for_unprovided_dependency(self, parameter: SignatureParameter) -> None:
205         """Where a dependency has been explicitly marked using the `Dependency` function, it is a configuration error if
206         that dependency has been defined without a default value, and it hasn't been provided to the handler.
207 
208         Args:
209             parameter  SignatureParameter
210 
211         Raises:
212             `ImproperlyConfiguredException`
213         """
214         if parameter.optional:
215             return
216         if not is_dependency_field(parameter.default):
217             return
218         field_info: FieldInfo = parameter.default
219         if field_info.default is not Undefined:
220             return
221         if parameter.name not in self.dependency_name_set:
222             raise ImproperlyConfiguredException(
223                 f"Explicit dependency '{parameter.name}' for '{self.fn_name}' has no default value, "
224                 f"or provided dependency."
225             )
226 
227     def collect_dependency_names(self, parameter: SignatureParameter) -> None:
228         """Add parameter name of dependencies declared using `Dependency()` function to the set of all dependency names.
229 
230         Args:
231             parameter: SignatureParameter
232         """
233         if is_dependency_field(parameter.default):
234             self.dependency_name_set.add(parameter.name)
235 
236     def set_field_default(self, parameter: SignatureParameter) -> None:
237         """If `parameter` has defined default, map it to the parameter name in `self.defaults`.
238 
239         Args:
240             parameter: SignatureParameter
241         """
242         if parameter.default_defined:
243             self.defaults[parameter.name] = parameter.default
244 
245     def get_type_annotation_from_plugin(self, parameter: SignatureParameter, plugin: PluginProtocol) -> Any:
246         """Use plugin declared for parameter annotation type to generate a pydantic model.
247 
248         Args:
249             parameter:  SignatureParameter
250             plugin: PluginProtocol
251 
252         Returns:
253             A pydantic model to be used as a type
254         """
255         type_args = get_args(parameter.annotation)
256         type_value = type_args[0] if type_args else parameter.annotation
257         self.field_plugin_mappings[parameter.name] = PluginMapping(plugin=plugin, model_class=type_value)
258         pydantic_model = plugin.to_pydantic_model_class(model_class=type_value, parameter_name=parameter.name)
259         if type_args:
260             return List[pydantic_model]  # type:ignore[valid-type]
261         return pydantic_model
262 
263     @staticmethod
264     def create_field_definition_from_parameter(parameter: SignatureParameter) -> Tuple[Any, Any]:
265         """Construct an `(<annotation>, <default>)` tuple, appropriate for `pydantic.create_model()`.
266 
267         Args:
268             parameter: SignatureParameter
269 
270         Returns:
271             tuple[Any, Any]
272         """
273         if parameter.default_defined:
274             return parameter.annotation, parameter.default
275         if not parameter.optional:
276             return parameter.annotation, ...
277         return parameter.annotation, None
278 
279     @property
280     def signature_parameters(self) -> Generator[SignatureParameter, None, None]:
281         """Create a generator of `SignatureParameters` to be included in the `SignatureModel` by iterating over the
282         parameters of the function signature.
283 
284         Returns:
285             Generator[SignatureParameter, None, None]
286         """
287         for name, parameter in filter(lambda x: x[0] not in SKIP_NAMES, self.signature.parameters.items()):
288             yield SignatureParameter(self.fn_name, name, parameter)
289 
290     @staticmethod
291     def should_skip_parameter_validation(parameter: SignatureParameter) -> bool:
292         """Identify dependencies for which provided values should not be validated.
293 
294         Args:
295             parameter (SignatureParameter): A parameter to be added to the signature model.
296 
297         Returns:
298             A boolean indicating whether injected values for this parameter should not be validated.
299         """
300         return parameter.name in SKIP_VALIDATION_NAMES or should_skip_dependency_validation(parameter.default)
301 
302     def create_signature_model(self) -> Type[SignatureModel]:
303         """Construct a `SignatureModel` type that represents the signature of `self.fn`
304 
305         Returns:
306             type[SignatureModel]
307         """
308         try:
309             for parameter in self.signature_parameters:
310                 self.check_for_unprovided_dependency(parameter)
311                 self.collect_dependency_names(parameter)
312                 self.set_field_default(parameter)
313                 if self.should_skip_parameter_validation(parameter):
314                     if is_dependency_field(parameter.default):
315                         self.field_definitions[parameter.name] = (Any, parameter.default.default)
316                     else:
317                         self.field_definitions[parameter.name] = (Any, ...)
318                     continue
319                 if ModelFactory.is_constrained_field(parameter.default):
320                     self.field_definitions[parameter.name] = (parameter.default, ...)
321                     continue
322                 plugin = get_plugin_for_value(value=parameter.annotation, plugins=self.plugins)
323                 if plugin:
324                     parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin)
325                 self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter)
326             model: Type[SignatureModel] = create_model(
327                 self.fn_name + "_signature_model", __base__=SignatureModel, **self.field_definitions
328             )
329             model.return_annotation = self.signature.return_annotation
330             model.field_plugin_mappings = self.field_plugin_mappings
331             model.dependency_name_set = self.dependency_name_set
332             return model
333         except TypeError as e:
334             raise ImproperlyConfiguredException(f"Error creating signature model for '{self.fn_name}': '{e}'") from e
335 
336 
337 def get_signature_model(value: Any) -> Type[SignatureModel]:
338     """Retrieve and validate the signature model from a provider or handler."""
339     try:
340         return cast("Type[SignatureModel]", value.signature_model)
341     except AttributeError as e:  # pragma: no cover
342         raise ImproperlyConfiguredException(f"The 'signature_model' attribute for {value} is not set") from e
343
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/starlite/signature.py b/starlite/signature.py
--- a/starlite/signature.py
+++ b/starlite/signature.py
@@ -41,7 +41,7 @@
 
 UNDEFINED_SENTINELS = {Undefined, Signature.empty}
 SKIP_NAMES = {"self", "cls"}
-SKIP_VALIDATION_NAMES = {"request", "socket", "state", "scope"}
+SKIP_VALIDATION_NAMES = {"request", "socket", "state", "scope", "receive", "send"}
 
 
 class SignatureModel(BaseModel):
@@ -178,6 +178,7 @@
         "dependency_name_set",
         "field_definitions",
         "field_plugin_mappings",
+        "fn_module_name",
         "fn_name",
         "plugins",
         "signature",
@@ -194,7 +195,8 @@
         if fn is None:
             raise ImproperlyConfiguredException("Parameter `fn` to `SignatureModelFactory` cannot be `None`.")
         self.signature = Signature.from_callable(fn)
-        self.fn_name = fn.__name__ if hasattr(fn, "__name__") else "anonymous"
+        self.fn_name = getattr(fn, "__name__", "anonymous")
+        self.fn_module_name = getattr(fn, "__module__", "pydantic.main")
         self.plugins = plugins
         self.field_plugin_mappings: Dict[str, PluginMapping] = {}
         self.field_definitions: Dict[str, Any] = {}
@@ -324,7 +326,10 @@
                     parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin)
                 self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter)
             model: Type[SignatureModel] = create_model(
-                self.fn_name + "_signature_model", __base__=SignatureModel, **self.field_definitions
+                self.fn_name + "_signature_model",
+                __base__=SignatureModel,
+                __module__=self.fn_module_name,
+                **self.field_definitions,
             )
             model.return_annotation = self.signature.return_annotation
             model.field_plugin_mappings = self.field_plugin_mappings

{"golden_diff": "diff --git a/starlite/signature.py b/starlite/signature.py\n--- a/starlite/signature.py\n+++ b/starlite/signature.py\n@@ -41,7 +41,7 @@\n \n UNDEFINED_SENTINELS = {Undefined, Signature.empty}\n SKIP_NAMES = {\"self\", \"cls\"}\n-SKIP_VALIDATION_NAMES = {\"request\", \"socket\", \"state\", \"scope\"}\n+SKIP_VALIDATION_NAMES = {\"request\", \"socket\", \"state\", \"scope\", \"receive\", \"send\"}\n \n \n class SignatureModel(BaseModel):\n@@ -178,6 +178,7 @@\n         \"dependency_name_set\",\n         \"field_definitions\",\n         \"field_plugin_mappings\",\n+        \"fn_module_name\",\n         \"fn_name\",\n         \"plugins\",\n         \"signature\",\n@@ -194,7 +195,8 @@\n         if fn is None:\n             raise ImproperlyConfiguredException(\"Parameter `fn` to `SignatureModelFactory` cannot be `None`.\")\n         self.signature = Signature.from_callable(fn)\n-        self.fn_name = fn.__name__ if hasattr(fn, \"__name__\") else \"anonymous\"\n+        self.fn_name = getattr(fn, \"__name__\", \"anonymous\")\n+        self.fn_module_name = getattr(fn, \"__module__\", \"pydantic.main\")\n         self.plugins = plugins\n         self.field_plugin_mappings: Dict[str, PluginMapping] = {}\n         self.field_definitions: Dict[str, Any] = {}\n@@ -324,7 +326,10 @@\n                     parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin)\n                 self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter)\n             model: Type[SignatureModel] = create_model(\n-                self.fn_name + \"_signature_model\", __base__=SignatureModel, **self.field_definitions\n+                self.fn_name + \"_signature_model\",\n+                __base__=SignatureModel,\n+                __module__=self.fn_module_name,\n+                **self.field_definitions,\n             )\n             model.return_annotation = self.signature.return_annotation\n             model.field_plugin_mappings = self.field_plugin_mappings\n", "issue": "Enhancement: resolve forward refs when producing signature models\nWe need to support where users declare `from __future__ import annotations` in modules where handlers and dependencies are declared.\n", "before_files": [{"content": "from inspect import Parameter, Signature\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    ClassVar,\n    Dict,\n    Generator,\n    List,\n    Set,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nfrom pydantic import BaseConfig, BaseModel, ValidationError, create_model\nfrom pydantic.fields import FieldInfo, Undefined\nfrom pydantic_factories import ModelFactory\nfrom typing_extensions import get_args\n\nfrom starlite.connection import Request, WebSocket\nfrom starlite.enums import ScopeType\nfrom starlite.exceptions import (\n    ImproperlyConfiguredException,\n    InternalServerException,\n    ValidationException,\n)\nfrom starlite.plugins.base import PluginMapping, PluginProtocol, get_plugin_for_value\nfrom starlite.utils import (\n    is_dependency_field,\n    is_optional_union,\n    should_skip_dependency_validation,\n)\n\nif TYPE_CHECKING:\n    from pydantic.error_wrappers import ErrorDict\n\n    from starlite.datastructures import URL\n    from starlite.types import AnyCallable\n\n\nUNDEFINED_SENTINELS = {Undefined, Signature.empty}\nSKIP_NAMES = {\"self\", \"cls\"}\nSKIP_VALIDATION_NAMES = {\"request\", \"socket\", \"state\", \"scope\"}\n\n\nclass SignatureModel(BaseModel):\n    \"\"\"Pydantic model representing a signature.\"\"\"\n\n    class Config(BaseConfig):\n        arbitrary_types_allowed = True\n\n    dependency_name_set: ClassVar[Set[str]]\n    field_plugin_mappings: ClassVar[Dict[str, PluginMapping]]\n    return_annotation: ClassVar[Any]\n\n    @classmethod\n    def parse_values_from_connection_kwargs(\n        cls, connection: Union[Request, WebSocket], **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Given a dictionary of values extracted from the connection, create an instance of the given SignatureModel\n        subclass and return the parsed values.\n\n        This is not equivalent to calling the '.dict'  method of the pydantic model, because it doesn't convert nested\n        values into dictionary, just extracts the data from the signature model\n        \"\"\"\n        try:\n            signature = cls(**kwargs)\n            return {key: signature.resolve_field_value(key) for key in cls.__fields__}\n        except ValidationError as exc:\n            raise cls.construct_exception(connection, exc) from exc\n\n    def resolve_field_value(self, key: str) -> Any:\n        \"\"\"Given a field key, return value using plugin mapping, if available.\"\"\"\n        value = self.__getattribute__(key)  # pylint: disable=unnecessary-dunder-call\n        mapping = self.field_plugin_mappings.get(key)\n        return mapping.get_model_instance_for_value(value) if mapping else value\n\n    @classmethod\n    def construct_exception(\n        cls, connection: Union[Request, WebSocket], exc: ValidationError\n    ) -> Union[InternalServerException, ValidationException]:\n        \"\"\"Distinguish between validation errors that arise from parameters and dependencies.\n\n        If both parameter and dependency values are invalid, we raise the client error first.\n\n        Args:\n            connection: A Request or WebSocket\n            exc: A ValidationError\n\n        Returns:\n            A ValidationException or InternalServerException\n        \"\"\"\n        server_errors: List[\"ErrorDict\"] = []\n        client_errors: List[\"ErrorDict\"] = []\n\n        for error in exc.errors():\n            if cls.is_server_error(error):\n                server_errors.append(error)\n            else:\n                client_errors.append(error)\n\n        method, url = cls.get_connection_method_and_url(connection)\n\n        if client_errors:\n            return ValidationException(detail=f\"Validation failed for {method} {url}\", extra=client_errors)\n\n        return InternalServerException(detail=f\"A dependency failed validation for {method} {url}\", extra=server_errors)\n\n    @classmethod\n    def is_server_error(cls, error: \"ErrorDict\") -> bool:\n        \"\"\"Check whether given validation error is a server error.\"\"\"\n        return error[\"loc\"][-1] in cls.dependency_name_set\n\n    @staticmethod\n    def get_connection_method_and_url(connection: Union[Request, WebSocket]) -> Tuple[str, \"URL\"]:\n        \"\"\"Extract method and URL from Request or WebSocket.\"\"\"\n        method = ScopeType.WEBSOCKET if isinstance(connection, WebSocket) else connection.method\n        return method, connection.url\n\n\nclass SignatureParameter:\n    \"\"\"Represents the parameters of a callable for purpose of signature model generation.\"\"\"\n\n    __slots__ = (\n        \"annotation\",\n        \"default\",\n        \"name\",\n        \"optional\",\n    )\n\n    annotation: Any\n    default: Any\n    name: str\n    optional: bool\n\n    def __init__(self, fn_name: str, parameter_name: str, parameter: Parameter) -> None:\n        \"\"\"Initialize SignatureParameter.\n\n        Args:\n            fn_name: Name of function.\n            parameter_name: Name of parameter.\n            parameter: inspect.Parameter\n        \"\"\"\n        if parameter.annotation is Signature.empty:\n            raise ImproperlyConfiguredException(\n                f\"Kwarg {parameter_name} of {fn_name} does not have a type annotation. If it \"\n                f\"should receive any value, use the 'Any' type.\"\n            )\n        self.annotation = parameter.annotation\n        self.default = parameter.default\n        self.name = parameter_name\n        self.optional = is_optional_union(parameter.annotation)\n\n    @property\n    def default_defined(self) -> bool:\n        \"\"\"Return a boolean, indicating if `self.default` is not one of the undefined sentinel types.\"\"\"\n        return self.default not in UNDEFINED_SENTINELS\n\n\nclass SignatureModelFactory:\n    \"\"\"Utility class for constructing the signature model and grouping associated state.\n\n    Instance available at `SignatureModel.factory`.\n\n    The following attributes are populated after the `model()` method has been called to generate\n    the `SignatureModel` subclass.\n\n    Attributes:\n        field_plugin_mappings: Maps parameter name, to `PluginMapping` where a plugin has been applied.\n        field_definitions:  Maps parameter name to the `(<type>, <default>)` tuple passed to `pydantic.create_model()`.\n        defaults: Maps parameter name to default value, if one defined.\n        dependency_name_set: The names of all known dependency parameters.\n    \"\"\"\n\n    __slots__ = (\n        \"defaults\",\n        \"dependency_name_set\",\n        \"field_definitions\",\n        \"field_plugin_mappings\",\n        \"fn_name\",\n        \"plugins\",\n        \"signature\",\n    )\n\n    def __init__(self, fn: \"AnyCallable\", plugins: List[\"PluginProtocol\"], dependency_names: Set[str]) -> None:\n        \"\"\"Initialise `SignatureModelFactory`\n\n        Args:\n            fn: A callable\n            plugins: A list of plugins\n            dependency_names: Dependency names\n        \"\"\"\n        if fn is None:\n            raise ImproperlyConfiguredException(\"Parameter `fn` to `SignatureModelFactory` cannot be `None`.\")\n        self.signature = Signature.from_callable(fn)\n        self.fn_name = fn.__name__ if hasattr(fn, \"__name__\") else \"anonymous\"\n        self.plugins = plugins\n        self.field_plugin_mappings: Dict[str, PluginMapping] = {}\n        self.field_definitions: Dict[str, Any] = {}\n        self.defaults: Dict[str, Any] = {}\n        self.dependency_name_set = dependency_names\n\n    def check_for_unprovided_dependency(self, parameter: SignatureParameter) -> None:\n        \"\"\"Where a dependency has been explicitly marked using the `Dependency` function, it is a configuration error if\n        that dependency has been defined without a default value, and it hasn't been provided to the handler.\n\n        Args:\n            parameter  SignatureParameter\n\n        Raises:\n            `ImproperlyConfiguredException`\n        \"\"\"\n        if parameter.optional:\n            return\n        if not is_dependency_field(parameter.default):\n            return\n        field_info: FieldInfo = parameter.default\n        if field_info.default is not Undefined:\n            return\n        if parameter.name not in self.dependency_name_set:\n            raise ImproperlyConfiguredException(\n                f\"Explicit dependency '{parameter.name}' for '{self.fn_name}' has no default value, \"\n                f\"or provided dependency.\"\n            )\n\n    def collect_dependency_names(self, parameter: SignatureParameter) -> None:\n        \"\"\"Add parameter name of dependencies declared using `Dependency()` function to the set of all dependency names.\n\n        Args:\n            parameter: SignatureParameter\n        \"\"\"\n        if is_dependency_field(parameter.default):\n            self.dependency_name_set.add(parameter.name)\n\n    def set_field_default(self, parameter: SignatureParameter) -> None:\n        \"\"\"If `parameter` has defined default, map it to the parameter name in `self.defaults`.\n\n        Args:\n            parameter: SignatureParameter\n        \"\"\"\n        if parameter.default_defined:\n            self.defaults[parameter.name] = parameter.default\n\n    def get_type_annotation_from_plugin(self, parameter: SignatureParameter, plugin: PluginProtocol) -> Any:\n        \"\"\"Use plugin declared for parameter annotation type to generate a pydantic model.\n\n        Args:\n            parameter:  SignatureParameter\n            plugin: PluginProtocol\n\n        Returns:\n            A pydantic model to be used as a type\n        \"\"\"\n        type_args = get_args(parameter.annotation)\n        type_value = type_args[0] if type_args else parameter.annotation\n        self.field_plugin_mappings[parameter.name] = PluginMapping(plugin=plugin, model_class=type_value)\n        pydantic_model = plugin.to_pydantic_model_class(model_class=type_value, parameter_name=parameter.name)\n        if type_args:\n            return List[pydantic_model]  # type:ignore[valid-type]\n        return pydantic_model\n\n    @staticmethod\n    def create_field_definition_from_parameter(parameter: SignatureParameter) -> Tuple[Any, Any]:\n        \"\"\"Construct an `(<annotation>, <default>)` tuple, appropriate for `pydantic.create_model()`.\n\n        Args:\n            parameter: SignatureParameter\n\n        Returns:\n            tuple[Any, Any]\n        \"\"\"\n        if parameter.default_defined:\n            return parameter.annotation, parameter.default\n        if not parameter.optional:\n            return parameter.annotation, ...\n        return parameter.annotation, None\n\n    @property\n    def signature_parameters(self) -> Generator[SignatureParameter, None, None]:\n        \"\"\"Create a generator of `SignatureParameters` to be included in the `SignatureModel` by iterating over the\n        parameters of the function signature.\n\n        Returns:\n            Generator[SignatureParameter, None, None]\n        \"\"\"\n        for name, parameter in filter(lambda x: x[0] not in SKIP_NAMES, self.signature.parameters.items()):\n            yield SignatureParameter(self.fn_name, name, parameter)\n\n    @staticmethod\n    def should_skip_parameter_validation(parameter: SignatureParameter) -> bool:\n        \"\"\"Identify dependencies for which provided values should not be validated.\n\n        Args:\n            parameter (SignatureParameter): A parameter to be added to the signature model.\n\n        Returns:\n            A boolean indicating whether injected values for this parameter should not be validated.\n        \"\"\"\n        return parameter.name in SKIP_VALIDATION_NAMES or should_skip_dependency_validation(parameter.default)\n\n    def create_signature_model(self) -> Type[SignatureModel]:\n        \"\"\"Construct a `SignatureModel` type that represents the signature of `self.fn`\n\n        Returns:\n            type[SignatureModel]\n        \"\"\"\n        try:\n            for parameter in self.signature_parameters:\n                self.check_for_unprovided_dependency(parameter)\n                self.collect_dependency_names(parameter)\n                self.set_field_default(parameter)\n                if self.should_skip_parameter_validation(parameter):\n                    if is_dependency_field(parameter.default):\n                        self.field_definitions[parameter.name] = (Any, parameter.default.default)\n                    else:\n                        self.field_definitions[parameter.name] = (Any, ...)\n                    continue\n                if ModelFactory.is_constrained_field(parameter.default):\n                    self.field_definitions[parameter.name] = (parameter.default, ...)\n                    continue\n                plugin = get_plugin_for_value(value=parameter.annotation, plugins=self.plugins)\n                if plugin:\n                    parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin)\n                self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter)\n            model: Type[SignatureModel] = create_model(\n                self.fn_name + \"_signature_model\", __base__=SignatureModel, **self.field_definitions\n            )\n            model.return_annotation = self.signature.return_annotation\n            model.field_plugin_mappings = self.field_plugin_mappings\n            model.dependency_name_set = self.dependency_name_set\n            return model\n        except TypeError as e:\n            raise ImproperlyConfiguredException(f\"Error creating signature model for '{self.fn_name}': '{e}'\") from e\n\n\ndef get_signature_model(value: Any) -> Type[SignatureModel]:\n    \"\"\"Retrieve and validate the signature model from a provider or handler.\"\"\"\n    try:\n        return cast(\"Type[SignatureModel]\", value.signature_model)\n    except AttributeError as e:  # pragma: no cover\n        raise ImproperlyConfiguredException(f\"The 'signature_model' attribute for {value} is not set\") from e\n", "path": "starlite/signature.py"}], "after_files": [{"content": "from inspect import Parameter, Signature\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    ClassVar,\n    Dict,\n    Generator,\n    List,\n    Set,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nfrom pydantic import BaseConfig, BaseModel, ValidationError, create_model\nfrom pydantic.fields import FieldInfo, Undefined\nfrom pydantic_factories import ModelFactory\nfrom typing_extensions import get_args\n\nfrom starlite.connection import Request, WebSocket\nfrom starlite.enums import ScopeType\nfrom starlite.exceptions import (\n    ImproperlyConfiguredException,\n    InternalServerException,\n    ValidationException,\n)\nfrom starlite.plugins.base import PluginMapping, PluginProtocol, get_plugin_for_value\nfrom starlite.utils import (\n    is_dependency_field,\n    is_optional_union,\n    should_skip_dependency_validation,\n)\n\nif TYPE_CHECKING:\n    from pydantic.error_wrappers import ErrorDict\n\n    from starlite.datastructures import URL\n    from starlite.types import AnyCallable\n\n\nUNDEFINED_SENTINELS = {Undefined, Signature.empty}\nSKIP_NAMES = {\"self\", \"cls\"}\nSKIP_VALIDATION_NAMES = {\"request\", \"socket\", \"state\", \"scope\", \"receive\", \"send\"}\n\n\nclass SignatureModel(BaseModel):\n    \"\"\"Pydantic model representing a signature.\"\"\"\n\n    class Config(BaseConfig):\n        arbitrary_types_allowed = True\n\n    dependency_name_set: ClassVar[Set[str]]\n    field_plugin_mappings: ClassVar[Dict[str, PluginMapping]]\n    return_annotation: ClassVar[Any]\n\n    @classmethod\n    def parse_values_from_connection_kwargs(\n        cls, connection: Union[Request, WebSocket], **kwargs: Any\n    ) -> Dict[str, Any]:\n        \"\"\"Given a dictionary of values extracted from the connection, create an instance of the given SignatureModel\n        subclass and return the parsed values.\n\n        This is not equivalent to calling the '.dict'  method of the pydantic model, because it doesn't convert nested\n        values into dictionary, just extracts the data from the signature model\n        \"\"\"\n        try:\n            signature = cls(**kwargs)\n            return {key: signature.resolve_field_value(key) for key in cls.__fields__}\n        except ValidationError as exc:\n            raise cls.construct_exception(connection, exc) from exc\n\n    def resolve_field_value(self, key: str) -> Any:\n        \"\"\"Given a field key, return value using plugin mapping, if available.\"\"\"\n        value = self.__getattribute__(key)  # pylint: disable=unnecessary-dunder-call\n        mapping = self.field_plugin_mappings.get(key)\n        return mapping.get_model_instance_for_value(value) if mapping else value\n\n    @classmethod\n    def construct_exception(\n        cls, connection: Union[Request, WebSocket], exc: ValidationError\n    ) -> Union[InternalServerException, ValidationException]:\n        \"\"\"Distinguish between validation errors that arise from parameters and dependencies.\n\n        If both parameter and dependency values are invalid, we raise the client error first.\n\n        Args:\n            connection: A Request or WebSocket\n            exc: A ValidationError\n\n        Returns:\n            A ValidationException or InternalServerException\n        \"\"\"\n        server_errors: List[\"ErrorDict\"] = []\n        client_errors: List[\"ErrorDict\"] = []\n\n        for error in exc.errors():\n            if cls.is_server_error(error):\n                server_errors.append(error)\n            else:\n                client_errors.append(error)\n\n        method, url = cls.get_connection_method_and_url(connection)\n\n        if client_errors:\n            return ValidationException(detail=f\"Validation failed for {method} {url}\", extra=client_errors)\n\n        return InternalServerException(detail=f\"A dependency failed validation for {method} {url}\", extra=server_errors)\n\n    @classmethod\n    def is_server_error(cls, error: \"ErrorDict\") -> bool:\n        \"\"\"Check whether given validation error is a server error.\"\"\"\n        return error[\"loc\"][-1] in cls.dependency_name_set\n\n    @staticmethod\n    def get_connection_method_and_url(connection: Union[Request, WebSocket]) -> Tuple[str, \"URL\"]:\n        \"\"\"Extract method and URL from Request or WebSocket.\"\"\"\n        method = ScopeType.WEBSOCKET if isinstance(connection, WebSocket) else connection.method\n        return method, connection.url\n\n\nclass SignatureParameter:\n    \"\"\"Represents the parameters of a callable for purpose of signature model generation.\"\"\"\n\n    __slots__ = (\n        \"annotation\",\n        \"default\",\n        \"name\",\n        \"optional\",\n    )\n\n    annotation: Any\n    default: Any\n    name: str\n    optional: bool\n\n    def __init__(self, fn_name: str, parameter_name: str, parameter: Parameter) -> None:\n        \"\"\"Initialize SignatureParameter.\n\n        Args:\n            fn_name: Name of function.\n            parameter_name: Name of parameter.\n            parameter: inspect.Parameter\n        \"\"\"\n        if parameter.annotation is Signature.empty:\n            raise ImproperlyConfiguredException(\n                f\"Kwarg {parameter_name} of {fn_name} does not have a type annotation. If it \"\n                f\"should receive any value, use the 'Any' type.\"\n            )\n        self.annotation = parameter.annotation\n        self.default = parameter.default\n        self.name = parameter_name\n        self.optional = is_optional_union(parameter.annotation)\n\n    @property\n    def default_defined(self) -> bool:\n        \"\"\"Return a boolean, indicating if `self.default` is not one of the undefined sentinel types.\"\"\"\n        return self.default not in UNDEFINED_SENTINELS\n\n\nclass SignatureModelFactory:\n    \"\"\"Utility class for constructing the signature model and grouping associated state.\n\n    Instance available at `SignatureModel.factory`.\n\n    The following attributes are populated after the `model()` method has been called to generate\n    the `SignatureModel` subclass.\n\n    Attributes:\n        field_plugin_mappings: Maps parameter name, to `PluginMapping` where a plugin has been applied.\n        field_definitions:  Maps parameter name to the `(<type>, <default>)` tuple passed to `pydantic.create_model()`.\n        defaults: Maps parameter name to default value, if one defined.\n        dependency_name_set: The names of all known dependency parameters.\n    \"\"\"\n\n    __slots__ = (\n        \"defaults\",\n        \"dependency_name_set\",\n        \"field_definitions\",\n        \"field_plugin_mappings\",\n        \"fn_module_name\",\n        \"fn_name\",\n        \"plugins\",\n        \"signature\",\n    )\n\n    def __init__(self, fn: \"AnyCallable\", plugins: List[\"PluginProtocol\"], dependency_names: Set[str]) -> None:\n        \"\"\"Initialise `SignatureModelFactory`\n\n        Args:\n            fn: A callable\n            plugins: A list of plugins\n            dependency_names: Dependency names\n        \"\"\"\n        if fn is None:\n            raise ImproperlyConfiguredException(\"Parameter `fn` to `SignatureModelFactory` cannot be `None`.\")\n        self.signature = Signature.from_callable(fn)\n        self.fn_name = getattr(fn, \"__name__\", \"anonymous\")\n        self.fn_module_name = getattr(fn, \"__module__\", \"pydantic.main\")\n        self.plugins = plugins\n        self.field_plugin_mappings: Dict[str, PluginMapping] = {}\n        self.field_definitions: Dict[str, Any] = {}\n        self.defaults: Dict[str, Any] = {}\n        self.dependency_name_set = dependency_names\n\n    def check_for_unprovided_dependency(self, parameter: SignatureParameter) -> None:\n        \"\"\"Where a dependency has been explicitly marked using the `Dependency` function, it is a configuration error if\n        that dependency has been defined without a default value, and it hasn't been provided to the handler.\n\n        Args:\n            parameter  SignatureParameter\n\n        Raises:\n            `ImproperlyConfiguredException`\n        \"\"\"\n        if parameter.optional:\n            return\n        if not is_dependency_field(parameter.default):\n            return\n        field_info: FieldInfo = parameter.default\n        if field_info.default is not Undefined:\n            return\n        if parameter.name not in self.dependency_name_set:\n            raise ImproperlyConfiguredException(\n                f\"Explicit dependency '{parameter.name}' for '{self.fn_name}' has no default value, \"\n                f\"or provided dependency.\"\n            )\n\n    def collect_dependency_names(self, parameter: SignatureParameter) -> None:\n        \"\"\"Add parameter name of dependencies declared using `Dependency()` function to the set of all dependency names.\n\n        Args:\n            parameter: SignatureParameter\n        \"\"\"\n        if is_dependency_field(parameter.default):\n            self.dependency_name_set.add(parameter.name)\n\n    def set_field_default(self, parameter: SignatureParameter) -> None:\n        \"\"\"If `parameter` has defined default, map it to the parameter name in `self.defaults`.\n\n        Args:\n            parameter: SignatureParameter\n        \"\"\"\n        if parameter.default_defined:\n            self.defaults[parameter.name] = parameter.default\n\n    def get_type_annotation_from_plugin(self, parameter: SignatureParameter, plugin: PluginProtocol) -> Any:\n        \"\"\"Use plugin declared for parameter annotation type to generate a pydantic model.\n\n        Args:\n            parameter:  SignatureParameter\n            plugin: PluginProtocol\n\n        Returns:\n            A pydantic model to be used as a type\n        \"\"\"\n        type_args = get_args(parameter.annotation)\n        type_value = type_args[0] if type_args else parameter.annotation\n        self.field_plugin_mappings[parameter.name] = PluginMapping(plugin=plugin, model_class=type_value)\n        pydantic_model = plugin.to_pydantic_model_class(model_class=type_value, parameter_name=parameter.name)\n        if type_args:\n            return List[pydantic_model]  # type:ignore[valid-type]\n        return pydantic_model\n\n    @staticmethod\n    def create_field_definition_from_parameter(parameter: SignatureParameter) -> Tuple[Any, Any]:\n        \"\"\"Construct an `(<annotation>, <default>)` tuple, appropriate for `pydantic.create_model()`.\n\n        Args:\n            parameter: SignatureParameter\n\n        Returns:\n            tuple[Any, Any]\n        \"\"\"\n        if parameter.default_defined:\n            return parameter.annotation, parameter.default\n        if not parameter.optional:\n            return parameter.annotation, ...\n        return parameter.annotation, None\n\n    @property\n    def signature_parameters(self) -> Generator[SignatureParameter, None, None]:\n        \"\"\"Create a generator of `SignatureParameters` to be included in the `SignatureModel` by iterating over the\n        parameters of the function signature.\n\n        Returns:\n            Generator[SignatureParameter, None, None]\n        \"\"\"\n        for name, parameter in filter(lambda x: x[0] not in SKIP_NAMES, self.signature.parameters.items()):\n            yield SignatureParameter(self.fn_name, name, parameter)\n\n    @staticmethod\n    def should_skip_parameter_validation(parameter: SignatureParameter) -> bool:\n        \"\"\"Identify dependencies for which provided values should not be validated.\n\n        Args:\n            parameter (SignatureParameter): A parameter to be added to the signature model.\n\n        Returns:\n            A boolean indicating whether injected values for this parameter should not be validated.\n        \"\"\"\n        return parameter.name in SKIP_VALIDATION_NAMES or should_skip_dependency_validation(parameter.default)\n\n    def create_signature_model(self) -> Type[SignatureModel]:\n        \"\"\"Construct a `SignatureModel` type that represents the signature of `self.fn`\n\n        Returns:\n            type[SignatureModel]\n        \"\"\"\n        try:\n            for parameter in self.signature_parameters:\n                self.check_for_unprovided_dependency(parameter)\n                self.collect_dependency_names(parameter)\n                self.set_field_default(parameter)\n                if self.should_skip_parameter_validation(parameter):\n                    if is_dependency_field(parameter.default):\n                        self.field_definitions[parameter.name] = (Any, parameter.default.default)\n                    else:\n                        self.field_definitions[parameter.name] = (Any, ...)\n                    continue\n                if ModelFactory.is_constrained_field(parameter.default):\n                    self.field_definitions[parameter.name] = (parameter.default, ...)\n                    continue\n                plugin = get_plugin_for_value(value=parameter.annotation, plugins=self.plugins)\n                if plugin:\n                    parameter.annotation = self.get_type_annotation_from_plugin(parameter, plugin)\n                self.field_definitions[parameter.name] = self.create_field_definition_from_parameter(parameter)\n            model: Type[SignatureModel] = create_model(\n                self.fn_name + \"_signature_model\",\n                __base__=SignatureModel,\n                __module__=self.fn_module_name,\n                **self.field_definitions,\n            )\n            model.return_annotation = self.signature.return_annotation\n            model.field_plugin_mappings = self.field_plugin_mappings\n            model.dependency_name_set = self.dependency_name_set\n            return model\n        except TypeError as e:\n            raise ImproperlyConfiguredException(f\"Error creating signature model for '{self.fn_name}': '{e}'\") from e\n\n\ndef get_signature_model(value: Any) -> Type[SignatureModel]:\n    \"\"\"Retrieve and validate the signature model from a provider or handler.\"\"\"\n    try:\n        return cast(\"Type[SignatureModel]\", value.signature_model)\n    except AttributeError as e:  # pragma: no cover\n        raise ImproperlyConfiguredException(f\"The 'signature_model' attribute for {value} is not set\") from e\n", "path": "starlite/signature.py"}]}