FastSpine 1.0.0__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.
Files changed (71) hide show
  1. fastspine/__init__.py +48 -0
  2. fastspine/abstract/owner_base.py +16 -0
  3. fastspine/alembic/__init__.py +4 -0
  4. fastspine/alembic/alembic.py +95 -0
  5. fastspine/alembic/config.py +40 -0
  6. fastspine/boostrap.py +78 -0
  7. fastspine/cache/cache_decorater.py +264 -0
  8. fastspine/cache/cache_encoder.py +87 -0
  9. fastspine/cache/cache_exception.py +4 -0
  10. fastspine/cache/cache_model.py +32 -0
  11. fastspine/cache/cache_service.py +144 -0
  12. fastspine/cache/key_builder.py +134 -0
  13. fastspine/cache/redis_cache.py +158 -0
  14. fastspine/celery/base_task.py +106 -0
  15. fastspine/celery/engine.py +52 -0
  16. fastspine/cli/scoped_typer.py +47 -0
  17. fastspine/ctx/ctx_pool.py +73 -0
  18. fastspine/database/engine.py +131 -0
  19. fastspine/decorators/contextualize_decorator.py +54 -0
  20. fastspine/decorators/retry_decorator.py +66 -0
  21. fastspine/decorators/upsert_decorator.py +107 -0
  22. fastspine/dependencies/database.py +193 -0
  23. fastspine/dependencies/profiler.py +37 -0
  24. fastspine/dependencies/repository_manager.py +202 -0
  25. fastspine/dependencies/services.py +140 -0
  26. fastspine/exception/access_exception.py +13 -0
  27. fastspine/exception/action_not_allowed_exception.py +13 -0
  28. fastspine/exception/base_app_exception.py +28 -0
  29. fastspine/exception/exception_handler.py +9 -0
  30. fastspine/exception/not_found_exception.py +13 -0
  31. fastspine/exception/security_exception.py +13 -0
  32. fastspine/exception/soft_delete_exception.py +13 -0
  33. fastspine/lib/__init__.py +4 -0
  34. fastspine/lib/contextualize.py +352 -0
  35. fastspine/lib/profiler.py +284 -0
  36. fastspine/mailer/mailer_service.py +44 -0
  37. fastspine/middleware/request_middleware.py +67 -0
  38. fastspine/middleware/session_middleware.py +38 -0
  39. fastspine/mixins/__init__.py +4 -0
  40. fastspine/mixins/representable.py +12 -0
  41. fastspine/mixins/soft_delete.py +41 -0
  42. fastspine/mixins/timestamps.py +35 -0
  43. fastspine/models/base.py +18 -0
  44. fastspine/redis/client.py +23 -0
  45. fastspine/repositories/abstract_repository.py +267 -0
  46. fastspine/repositories/base_repository.py +422 -0
  47. fastspine/repositories/external_base_repository.py +12 -0
  48. fastspine/repositories/repository_manager.py +101 -0
  49. fastspine/schemas/pagination_model.py +26 -0
  50. fastspine/services/api_service.py +292 -0
  51. fastspine/services/base_service.py +18 -0
  52. fastspine/settings/__init__.py +74 -0
  53. fastspine/settings/app_settings.py +5 -0
  54. fastspine/settings/cache_settings.py +32 -0
  55. fastspine/settings/celery_settings.py +10 -0
  56. fastspine/settings/mailer_settings.py +12 -0
  57. fastspine/settings/profiler_settings.py +10 -0
  58. fastspine/types/__init__.py +3 -0
  59. fastspine/types/types.py +6 -0
  60. fastspine/util/class_util.py +110 -0
  61. fastspine/util/conversion.py +37 -0
  62. fastspine/util/dataframe_util.py +30 -0
  63. fastspine/util/dates.py +34 -0
  64. fastspine/util/debug_util.py +29 -0
  65. fastspine/util/emails.py +14 -0
  66. fastspine/util/files.py +29 -0
  67. fastspine/util/math.py +3 -0
  68. fastspine-1.0.0.dist-info/METADATA +372 -0
  69. fastspine-1.0.0.dist-info/RECORD +71 -0
  70. fastspine-1.0.0.dist-info/WHEEL +4 -0
  71. fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,202 @@
1
+ import contextvars
2
+ import logging
3
+ from collections.abc import AsyncGenerator, Callable, Generator
4
+ from contextlib import asynccontextmanager, contextmanager
5
+ from typing import Any, cast, get_args, get_origin
6
+
7
+ from fastapi import Depends
8
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
9
+ from sqlalchemy.orm import Session
10
+
11
+ from ..ctx.ctx_pool import ctxpool
12
+ from ..dependencies.database import DB_MAPPING, ENGINE_MAPPING, _aload_db, _load_db
13
+ from ..repositories.repository_manager import RepositoryManager
14
+
15
+ _repo_manager_cache_var: contextvars.ContextVar[
16
+ dict[type[RepositoryManager[AsyncSession | Session]], RepositoryManager[AsyncSession | Session]] | None
17
+ ] = ctxpool.new("_repo_manager_cache_var", default={})
18
+
19
+ manager_annotations_classes: dict[type[Any], dict[str, Any]] = {}
20
+ _factory_cache: dict[tuple[type, bool], Callable] = {}
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ async def _close_sessions():
25
+ """Close every repository manager session `load_repository_manager` lazily opened in this context."""
26
+ cache = ctxpool.get_context_var_value(_repo_manager_cache_var)
27
+ try:
28
+ for repo_manager_class, repo_manager in cache.items():
29
+ try:
30
+ if isinstance(repo_manager.db, AsyncSession):
31
+ await repo_manager.db.close()
32
+ else:
33
+ repo_manager.db.close()
34
+ except Exception:
35
+ logger.exception(
36
+ "Failed to close repository manager session",
37
+ extra={"repo_manager_class": repo_manager_class.__name__},
38
+ )
39
+ finally:
40
+ ctxpool.clear_one("_repo_manager_cache_var")
41
+
42
+
43
+ def _close_sessions_sync():
44
+ """Close every repository manager session `load_repository_manager` lazily opened in this context."""
45
+ cache = ctxpool.get_context_var_value(_repo_manager_cache_var)
46
+ try:
47
+ for repo_manager_class, repo_manager in cache.items():
48
+ if isinstance(repo_manager.db, AsyncSession):
49
+ logger.error(
50
+ "Cannot close an AsyncSession from a sync scope; the connection will leak.",
51
+ extra={"repo_manager_class": repo_manager_class.__name__},
52
+ )
53
+ continue
54
+ try:
55
+ repo_manager.db.close()
56
+ except Exception:
57
+ logger.exception(
58
+ "Failed to close repository manager session",
59
+ extra={"repo_manager_class": repo_manager_class.__name__},
60
+ )
61
+ finally:
62
+ ctxpool.clear_one("_repo_manager_cache_var")
63
+
64
+
65
+ @asynccontextmanager
66
+ async def repository_manager_scope() -> AsyncGenerator[None]:
67
+ """Scope within which `load_repository_manager` lazily opens and caches sessions, closed on exit.
68
+
69
+ Used by non-DI scopes (e.g. a CLI command) to clean up at the end of the scope's lifetime,
70
+ without needing to know upfront which repository managers were actually used.
71
+ """
72
+ try:
73
+ yield
74
+ finally:
75
+ await _close_sessions()
76
+
77
+
78
+ @contextmanager
79
+ def repository_manager_scope_sync() -> Generator[None, None, None]:
80
+ """Scope within which `load_repository_manager` lazily opens and caches sessions, closed on exit.
81
+
82
+ Used by non-DI scopes (e.g. a Celery task or CLI command) to clean up at the end of the scope's
83
+ lifetime, without needing to know upfront which repository managers were actually used.
84
+ """
85
+ try:
86
+ yield
87
+ finally:
88
+ _close_sessions_sync()
89
+
90
+
91
+ def _read_manager_annotations[REPO_MANAGER_T: RepositoryManager](
92
+ repo_manager_class: type[REPO_MANAGER_T],
93
+ ) -> dict[str, type[Any]]:
94
+ """Read repository manager annotations."""
95
+ if repo_manager_class in manager_annotations_classes:
96
+ return manager_annotations_classes[repo_manager_class]
97
+
98
+ annotations = None
99
+ if hasattr(repo_manager_class, "__orig_bases__"):
100
+ orig_bases = getattr(repo_manager_class, "__orig_bases__", ()) # type: ignore
101
+ for base in orig_bases:
102
+ if get_origin(base) is RepositoryManager:
103
+ args = get_args(base)
104
+ if args:
105
+ session_class = args[0]
106
+ annotations = {"db": session_class}
107
+ break
108
+
109
+ if annotations is None:
110
+ raise ValueError(f"Could not determine session type for {repo_manager_class.__name__}")
111
+
112
+ manager_annotations_classes[repo_manager_class] = annotations
113
+
114
+ return annotations
115
+
116
+
117
+ def get_repository_manager[REPO_MANAGER_T: RepositoryManager](
118
+ repo_manager_class: type[REPO_MANAGER_T], isolated_session: bool = False
119
+ ) -> Callable[[], REPO_MANAGER_T]:
120
+ """Get repo instance. Used for DI inside Fastapi Depends lifecycle."""
121
+ key = (repo_manager_class, isolated_session)
122
+ if key in _factory_cache:
123
+ return _factory_cache[key]
124
+
125
+ annotations = _read_manager_annotations(repo_manager_class)
126
+ session_class = annotations.get("db") if annotations else None
127
+
128
+ # Check if it's a Session or AsyncSession subclass or bound TypeVar
129
+ is_session_type = False
130
+ if session_class and isinstance(session_class, type) and issubclass(session_class, (Session, AsyncSession)):
131
+ is_session_type = True
132
+ elif (
133
+ session_class
134
+ and hasattr(session_class, "__bound__")
135
+ and getattr(session_class, "__bound__", None) in (Session, AsyncSession)
136
+ ):
137
+ is_session_type = True
138
+ session_class = session_class.__bound__
139
+
140
+ if not is_session_type:
141
+ raise ValueError(
142
+ f"Parameter 'db' of {repo_manager_class.__name__} must be of type Session or AsyncSession {session_class} provided"
143
+ )
144
+
145
+ session_func_name = DB_MAPPING.get(repo_manager_class)
146
+
147
+ if session_func_name is None:
148
+ raise ValueError(
149
+ f"Parameter 'db' of {repo_manager_class.__name__} must be a valid Session or AsyncSession type {session_class} provided"
150
+ )
151
+
152
+ if len(annotations) > 1:
153
+ raise ValueError(
154
+ f"Repository {repo_manager_class.__name__} must have exactly one Session/AsyncSession parameter"
155
+ )
156
+
157
+ def factory(
158
+ db: Session | AsyncSession = Depends(session_func_name, use_cache=not isolated_session),
159
+ ) -> REPO_MANAGER_T:
160
+ """Factory function to create the repository manager instance."""
161
+ dependencies = {}
162
+ for param_name, param_type in annotations.items():
163
+ if (isinstance(param_type, type) and issubclass(param_type, (Session, AsyncSession))) or (
164
+ hasattr(param_type, "__bound__") and param_type.__bound__ in (Session, AsyncSession)
165
+ ):
166
+ dependencies[param_name] = db
167
+ return repo_manager_class(**dependencies)
168
+
169
+ _factory_cache[key] = factory
170
+ return factory
171
+
172
+
173
+ def load_repository_manager[REPO_MANAGER_T: RepositoryManager](
174
+ repo_manager_class: type[REPO_MANAGER_T],
175
+ ) -> REPO_MANAGER_T:
176
+ """Load repository manager.
177
+
178
+ load_repository manager is a utility function designed to create and return an instance of a repository manager class.
179
+ It is primarily used for dependency injection (DI) in contexts where FastAPI's Depends mechanism
180
+ is not available, such as background tasks or external services like Celery.
181
+ """
182
+ cache = ctxpool.get_context_var_value(_repo_manager_cache_var)
183
+
184
+ if repo_manager_class in cache:
185
+ return cast(REPO_MANAGER_T, cache[repo_manager_class])
186
+
187
+ engine = ENGINE_MAPPING.get(repo_manager_class)
188
+ if engine is None:
189
+ raise ValueError(f"{repo_manager_class.__name__} is not registered, call register_sessions() for it first.")
190
+
191
+ if isinstance(engine, AsyncEngine):
192
+ db_session = _aload_db(repo_manager_class)
193
+ else:
194
+ db_session = _load_db(repo_manager_class)
195
+
196
+ repo_instance = repo_manager_class(db=db_session)
197
+
198
+ new_cache = dict(cache)
199
+ new_cache[repo_manager_class] = repo_instance
200
+ ctxpool.set("_repo_manager_cache_var", new_cache)
201
+
202
+ return repo_instance
@@ -0,0 +1,140 @@
1
+ import inspect
2
+ from typing import Any
3
+
4
+ from fastapi import Depends
5
+
6
+ from ..ctx.ctx_pool import ctxpool
7
+ from ..dependencies.repository_manager import get_repository_manager, load_repository_manager
8
+ from ..repositories.repository_manager import RepositoryManager
9
+ from ..services.base_service import BaseService
10
+ from ..util.class_util import get_class_annotations
11
+
12
+ supported_params_type = [BaseService, RepositoryManager]
13
+ # Track dependency resolution to detect circular dependencies
14
+ _dependency_resolution_stack: set[type] = set()
15
+
16
+
17
+ def clear_cache():
18
+ """Clear service cache."""
19
+ ctxpool.clear_one("_service_cache_var")
20
+
21
+
22
+ def service_dep[SERVICE_T: BaseService](service_class: type[SERVICE_T]):
23
+ """Create a dependency function for service. Used for DI inside Fastapi Depends lifecycle."""
24
+ # Check for circular dependency
25
+ if service_class in _dependency_resolution_stack:
26
+ stack_names = [cls.__name__ for cls in _dependency_resolution_stack]
27
+ raise ValueError(
28
+ f"Circular dependency detected! Dependency chain: {' -> '.join(stack_names)} -> {service_class.__name__}"
29
+ )
30
+
31
+ _dependency_resolution_stack.add(service_class)
32
+
33
+ try:
34
+ annotations = get_class_annotations(service_class)
35
+
36
+ # Build the signature dynamically based on service dependencies
37
+ sig_params = []
38
+ sig = inspect.signature(service_class.__init__)
39
+ for param_name, param_type in annotations.items():
40
+ if inspect.isclass(param_type) and issubclass(param_type, BaseService):
41
+ # Nested service - create dependency
42
+ nested_dep = service_dep(param_type)
43
+ param = inspect.Parameter(
44
+ param_name, inspect.Parameter.KEYWORD_ONLY, default=Depends(nested_dep), annotation=param_type
45
+ )
46
+ sig_params.append(param)
47
+ elif inspect.isclass(param_type) and issubclass(param_type, RepositoryManager):
48
+ # Repository manager - use existing DI
49
+ repo_factory = get_repository_manager(param_type)
50
+ param = inspect.Parameter(
51
+ param_name, inspect.Parameter.KEYWORD_ONLY, default=Depends(repo_factory), annotation=param_type
52
+ )
53
+ sig_params.append(param)
54
+ else:
55
+ # For other parameters, check if they have defaults in the class __init__
56
+ # If they do, skip them (let the class use its defaults)
57
+ # If they don't, raise an error
58
+
59
+ if param_name in sig.parameters and sig.parameters[param_name].default != inspect.Parameter.empty:
60
+ default_value = sig.parameters[param_name].default
61
+ if hasattr(default_value, "dependency"):
62
+ # This is a FastAPI dependency - preserve it in signature
63
+ param = inspect.Parameter(
64
+ param_name, inspect.Parameter.KEYWORD_ONLY, default=default_value, annotation=param_type
65
+ )
66
+ sig_params.append(param)
67
+ else:
68
+ # Parameter has other default value, skip it
69
+ continue
70
+ else:
71
+ raise ValueError(
72
+ f"Unsupported dependency type {param_type} for parameter '{param_name}' in service {service_class.__name__}. "
73
+ f"Either provide a default value or use a supported type: {supported_params_type}"
74
+ )
75
+
76
+ def factory(**kwargs) -> SERVICE_T:
77
+ """Factory function to create the service instance."""
78
+ dependecies = {}
79
+
80
+ for param_name in annotations.keys():
81
+ if param_name in kwargs:
82
+ # Dependency provided by FastAPI DI
83
+ dependecies[param_name] = kwargs[param_name]
84
+ # For parameters with defaults, don't add them to dependencies
85
+ # Let the class constructor use its default values
86
+ return service_class(**dependecies)
87
+
88
+ # Set the signature for FastAPI to understand
89
+ factory.__signature__ = inspect.Signature(sig_params) # type: ignore[attr-defined]
90
+
91
+ return factory
92
+
93
+ finally:
94
+ # Always remove from stack when done
95
+ _dependency_resolution_stack.discard(service_class)
96
+
97
+
98
+ def load_service[SERVICE_T: BaseService](service_class: type[SERVICE_T]) -> SERVICE_T:
99
+ """Build a service instance outside FastAPI's DI, for use in CLI commands or other non-request contexts.
100
+
101
+ Resolves constructor dependencies the same way `service_dep` does (nested BaseService or
102
+ RepositoryManager parameters), but eagerly - via `load_service`/`load_repository_manager`
103
+ instead of FastAPI's `Depends()`.
104
+ """
105
+ if service_class in _dependency_resolution_stack:
106
+ stack_names = [cls.__name__ for cls in _dependency_resolution_stack]
107
+ raise ValueError(
108
+ f"Circular dependency detected! Dependency chain: {' -> '.join(stack_names)} -> {service_class.__name__}"
109
+ )
110
+
111
+ _dependency_resolution_stack.add(service_class)
112
+
113
+ try:
114
+ annotations = get_class_annotations(service_class)
115
+ sig = inspect.signature(service_class.__init__)
116
+ dependencies: dict[str, Any] = {}
117
+
118
+ for param_name, param_type in annotations.items():
119
+ if inspect.isclass(param_type) and issubclass(param_type, BaseService):
120
+ dependencies[param_name] = load_service(param_type)
121
+ elif inspect.isclass(param_type) and issubclass(param_type, RepositoryManager):
122
+ dependencies[param_name] = load_repository_manager(param_type)
123
+ elif param_name in sig.parameters and sig.parameters[param_name].default != inspect.Parameter.empty:
124
+ # Parameter has its own default (e.g. a lazy property dependency) - let it be used.
125
+ continue
126
+ else:
127
+ raise ValueError(
128
+ f"Unsupported dependency type {param_type} for parameter '{param_name}' in service {service_class.__name__}. "
129
+ f"Either provide a default value or use a supported type: {supported_params_type}"
130
+ )
131
+
132
+ return service_class(**dependencies)
133
+
134
+ finally:
135
+ _dependency_resolution_stack.discard(service_class)
136
+
137
+
138
+ def load_services(*service_classes: type[BaseService]) -> tuple[BaseService, ...]:
139
+ """Load multiple services at once, outside FastAPI's DI, each via `load_service`."""
140
+ return tuple(load_service(service_class) for service_class in service_classes)
@@ -0,0 +1,13 @@
1
+ from .base_app_exception import BaseAppError
2
+
3
+
4
+ class AccessDeniedError(BaseAppError):
5
+ """Exception raised for access denied errors.
6
+
7
+ Attributes:
8
+ STATUS_CODE -- HTTP status code for the error (default 403)
9
+ DEFAULT_MESSAGE -- default error message
10
+ """
11
+
12
+ STATUS_CODE = 403
13
+ DEFAULT_MESSAGE = "You do not have permission to access this resource"
@@ -0,0 +1,13 @@
1
+ from .base_app_exception import BaseAppError
2
+
3
+
4
+ class ActionNotAllowedError(BaseAppError):
5
+ """Exception raised for access denied errors.
6
+
7
+ Attributes:
8
+ STATUS_CODE -- HTTP status code for the error (default 403)
9
+ DEFAULT_MESSAGE -- default error message
10
+ """
11
+
12
+ STATUS_CODE = 403
13
+ DEFAULT_MESSAGE = "Action not allowed"
@@ -0,0 +1,28 @@
1
+ class BaseAppError(Exception):
2
+ """Base class for all application exceptions."""
3
+
4
+ def __init_subclass__(cls):
5
+ """Ensure that all subclasses define STATUS_CODE and DEFAULT_MESSAGE."""
6
+ super().__init_subclass__()
7
+ if not hasattr(cls, "STATUS_CODE"):
8
+ raise TypeError(f"{cls.__name__} must define STATUS_CODE constant")
9
+ if not hasattr(cls, "DEFAULT_MESSAGE"):
10
+ raise TypeError(f"{cls.__name__} must define DEFAULT_MESSAGE constant")
11
+
12
+ def __init__(self, message=None, status_code=None):
13
+ self.status_code = status_code or (
14
+ self.__class__.STATUS_CODE if hasattr(self.__class__, "STATUS_CODE") else 500
15
+ )
16
+ self.message = message or (
17
+ self.__class__.DEFAULT_MESSAGE if hasattr(self.__class__, "DEFAULT_MESSAGE") else "An error occurred"
18
+ )
19
+ super().__init__(self.message)
20
+
21
+
22
+ class BaseError(Exception):
23
+ """Base class for all application exceptions."""
24
+
25
+ def __init__(self, detail, status_code=500):
26
+ self.status_code = status_code
27
+ self.detail = detail
28
+ super().__init__(self.detail)
@@ -0,0 +1,9 @@
1
+ from fastapi import Request
2
+ from fastapi.responses import JSONResponse
3
+
4
+ from .base_app_exception import BaseAppError
5
+
6
+
7
+ async def value_error_handler(request: Request, exc: BaseAppError) -> JSONResponse:
8
+ """Handle BaseAppError exceptions."""
9
+ return JSONResponse(status_code=exc.status_code, content={"detail": str(exc)})
@@ -0,0 +1,13 @@
1
+ from .base_app_exception import BaseAppError
2
+
3
+
4
+ class NotFoundError(BaseAppError):
5
+ """Exception raised for access denied errors.
6
+
7
+ Attributes:
8
+ STATUS_CODE -- HTTP status code for the error (default 404)
9
+ DEFAULT_MESSAGE -- default error message
10
+ """
11
+
12
+ STATUS_CODE = 404
13
+ DEFAULT_MESSAGE = "Rersource not found"
@@ -0,0 +1,13 @@
1
+ from .base_app_exception import BaseAppError
2
+
3
+
4
+ class SecurityAlertError(BaseAppError):
5
+ """Exception raised for security alerts.
6
+
7
+ Attributes:
8
+ STATUS_CODE -- HTTP status code for the exception
9
+ DEFAULT_MESSAGE -- default message for the exception
10
+ """
11
+
12
+ STATUS_CODE = 403
13
+ DEFAULT_MESSAGE = " Unauthorized attempt detected. Access logged!"
@@ -0,0 +1,13 @@
1
+ from .base_app_exception import BaseAppError
2
+
3
+
4
+ class SoftDeleteError(BaseAppError):
5
+ """Exception raised for access denied errors.
6
+
7
+ Attributes:
8
+ STATUS_CODE -- HTTP status code for the error (default 403)
9
+ DEFAULT_MESSAGE -- default error message
10
+ """
11
+
12
+ STATUS_CODE = 403
13
+ DEFAULT_MESSAGE = "Action not allowed"
@@ -0,0 +1,4 @@
1
+ from .contextualize import log_context
2
+ from .profiler import Profiler
3
+
4
+ __all__ = ["Profiler", "log_context"]