fastapi-app-builder 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ """Monkey-patching utilities to make standard APIRouter work with DI.
2
+
3
+ This module patches FastAPI's parameter analysis to recognize potential
4
+ service types (Protocols, ABCs) and automatically inject them using Depends.
5
+
6
+ The patch is applied at module import time, and service resolution happens
7
+ at request time. This allows routers to be defined in separate files and
8
+ imported before services are registered.
9
+
10
+ Usage:
11
+ from fastapi_app_builder import AppBuilder
12
+ from controllers import user_router # Can import before registering!
13
+
14
+ builder = AppBuilder()
15
+ builder.services.add_scoped(IUserService, UserService)
16
+ builder.add_controller(user_router)
17
+ app = builder.build()
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import functools
23
+ import inspect
24
+ from collections.abc import Callable
25
+ from typing import TYPE_CHECKING, Any, Protocol
26
+
27
+ from fastapi import Depends
28
+
29
+ if TYPE_CHECKING:
30
+ from .container import Services
31
+
32
+ # Global registry - shared across all Services instances
33
+ _global_services: Services | None = None
34
+ _patched = False
35
+ _original_analyze_param: Any = None
36
+
37
+
38
+ def set_global_services(services: Services) -> None:
39
+ """Set the global services container for injection."""
40
+ global _global_services
41
+ _global_services = services
42
+
43
+
44
+ def get_global_services() -> Services | None:
45
+ """Get the global services container."""
46
+ return _global_services
47
+
48
+
49
+ def _is_potential_service_type(annotation: Any) -> bool:
50
+ """Check if an annotation looks like a service type (Protocol or ABC).
51
+
52
+ This is used at decoration time to determine if a parameter should be
53
+ treated as an injectable service. We check for Protocol and ABC because
54
+ these are commonly used for interface definitions in DI patterns.
55
+ """
56
+ if not isinstance(annotation, type):
57
+ return False
58
+
59
+ # Check if it's a Protocol
60
+ # Protocol classes have _is_protocol attribute set to True
61
+ if getattr(annotation, '_is_protocol', False):
62
+ return True
63
+
64
+ # Check if any base class is a Protocol
65
+ for base in getattr(annotation, '__mro__', []):
66
+ if getattr(base, '_is_protocol', False) and base is not Protocol:
67
+ return True
68
+
69
+ # Check if it's an ABC (Abstract Base Class)
70
+ from abc import ABC, ABCMeta
71
+ if isinstance(annotation, ABCMeta) or ABC in getattr(annotation, '__mro__', []):
72
+ # But not built-in ABCs like Sequence, Mapping, etc.
73
+ module = getattr(annotation, '__module__', '')
74
+ if not module.startswith('collections') and not module.startswith('typing'):
75
+ return True
76
+
77
+ return False
78
+
79
+
80
+ def _apply_patch() -> None:
81
+ """Apply the FastAPI patch to recognize injectable types.
82
+
83
+ This patch intercepts FastAPI's parameter analysis and:
84
+ 1. At decoration time: detects potential service types (Protocols, ABCs)
85
+ 2. At request time: resolves the actual service from the container
86
+
87
+ This allows routers to be defined before services are registered.
88
+ """
89
+ global _patched, _original_analyze_param
90
+ if _patched:
91
+ return
92
+
93
+ try:
94
+ from fastapi.dependencies import utils as dep_utils
95
+ from pydantic_core import PydanticUndefined
96
+
97
+ # Store the original function for potential restoration
98
+ _original_analyze_param = dep_utils.analyze_param
99
+ original_analyze_param = _original_analyze_param
100
+
101
+ @functools.wraps(original_analyze_param)
102
+ def patched_analyze_param(
103
+ *,
104
+ param_name: str,
105
+ annotation: Any,
106
+ value: Any,
107
+ is_path_param: bool,
108
+ **kwargs: Any,
109
+ ) -> Any:
110
+ # Check if no default is set (inspect._empty, PydanticUndefined, or None)
111
+ has_no_default = (
112
+ value is None
113
+ or value is PydanticUndefined
114
+ or value is inspect.Parameter.empty
115
+ )
116
+
117
+ # Determine if this parameter should be treated as an injectable service:
118
+ # 1. Protocol/ABC → always injectable (works before registration)
119
+ # 2. Registered concrete class → injectable
120
+ services = get_global_services()
121
+ is_injectable = False
122
+
123
+ if has_no_default and isinstance(annotation, type):
124
+ if _is_potential_service_type(annotation):
125
+ # Protocols and ABCs are always injectable
126
+ is_injectable = True
127
+ elif services is not None and services.is_registered(annotation):
128
+ # Concrete classes that are explicitly registered
129
+ is_injectable = True
130
+
131
+ if is_injectable:
132
+ # Create a dependency resolver that looks up the service at request time
133
+ service_type = annotation # Capture for closure
134
+
135
+ def make_resolver(svc_type: type) -> Callable[[], Any]:
136
+ def resolver() -> Any:
137
+ svc = get_global_services()
138
+ if svc is None:
139
+ from .exceptions import ServiceNotRegisteredError
140
+ raise ServiceNotRegisteredError(
141
+ "No service container configured. "
142
+ "Create an AppBuilder before handling requests."
143
+ )
144
+ if not svc.is_registered(svc_type):
145
+ from .exceptions import ServiceNotRegisteredError
146
+ raise ServiceNotRegisteredError(
147
+ f"Service {svc_type.__name__} is not registered. "
148
+ f"Register it with builder.services.add_*()"
149
+ )
150
+ return svc.resolve(svc_type)
151
+ return resolver
152
+
153
+ # Replace with a Depends call
154
+ value = Depends(make_resolver(service_type))
155
+ # Change annotation to Any to avoid Pydantic validation
156
+ annotation = Any
157
+
158
+ return original_analyze_param(
159
+ param_name=param_name,
160
+ annotation=annotation,
161
+ value=value,
162
+ is_path_param=is_path_param,
163
+ **kwargs,
164
+ )
165
+
166
+ dep_utils.analyze_param = patched_analyze_param
167
+ _patched = True
168
+ except Exception as e:
169
+ # If patching fails, log a warning
170
+ import warnings
171
+ warnings.warn(
172
+ f"Failed to patch FastAPI for automatic DI. "
173
+ f"Use InjectableRouter instead. Error: {e}",
174
+ stacklevel=2,
175
+ )
176
+
177
+
178
+ def _reset_patch() -> None:
179
+ """Reset the patch state (for testing).
180
+
181
+ This restores the original analyze_param function and clears the services.
182
+ After calling this, _apply_patch() can be called again.
183
+ """
184
+ global _patched, _global_services, _original_analyze_param
185
+
186
+ # Restore original function if we have it
187
+ if _original_analyze_param is not None:
188
+ try:
189
+ from fastapi.dependencies import utils as dep_utils
190
+ dep_utils.analyze_param = _original_analyze_param
191
+ except ImportError:
192
+ pass
193
+
194
+ _patched = False
195
+ _global_services = None
196
+ _original_analyze_param = None
197
+
198
+
199
+ # Apply patch at module import time
200
+ # This ensures the patch is in place before any routers are defined
201
+ _apply_patch()
File without changes
@@ -0,0 +1,76 @@
1
+ """Service resolver for accessing services from anywhere during a request.
2
+
3
+ This module provides a `resolve()` function that can be used to get services
4
+ from anywhere in your code during a request, not just in route handlers.
5
+
6
+ Usage:
7
+ from fastapi_app_builder import resolve
8
+
9
+ class UserService:
10
+ def get_user(self, id: int):
11
+ # Resolve a service from anywhere
12
+ cache = resolve(ICacheService)
13
+ return cache.get(f"user:{id}")
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import TypeVar
19
+
20
+ from .exceptions import ServiceNotRegisteredError
21
+ from .patch import get_global_services
22
+
23
+ T = TypeVar("T")
24
+
25
+
26
+ def resolve(service_type: type[T]) -> T:
27
+ """Resolve a service from anywhere during a request.
28
+
29
+ This function allows you to get a registered service from anywhere in your
30
+ code, not just in route handlers. It uses the current request's scope for
31
+ scoped services.
32
+
33
+ Args:
34
+ service_type: The service type/interface to resolve
35
+
36
+ Returns:
37
+ The resolved service instance
38
+
39
+ Raises:
40
+ ServiceNotRegisteredError: If no service container is configured or
41
+ the service type is not registered
42
+ ScopeNotFoundError: If resolving a scoped service outside a request
43
+
44
+ Example:
45
+ from fastapi_app_builder import resolve
46
+
47
+ class OrderService:
48
+ def create_order(self, items: list):
49
+ # Get services on-demand
50
+ inventory = resolve(IInventoryService)
51
+ payment = resolve(IPaymentService)
52
+
53
+ for item in items:
54
+ inventory.reserve(item)
55
+
56
+ return payment.charge(items)
57
+
58
+ Note:
59
+ While this works, prefer constructor injection when possible.
60
+ Constructor injection makes dependencies explicit and easier to test.
61
+ """
62
+ services = get_global_services()
63
+
64
+ if services is None:
65
+ raise ServiceNotRegisteredError(
66
+ "No service container configured. "
67
+ "Make sure to create an AppBuilder and call build() or extend()."
68
+ )
69
+
70
+ if not services.is_registered(service_type):
71
+ raise ServiceNotRegisteredError(
72
+ f"Service {service_type.__name__} is not registered. "
73
+ f"Register it with builder.services.add_*()"
74
+ )
75
+
76
+ return services.resolve(service_type)