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.
- fastspine/__init__.py +48 -0
- fastspine/abstract/owner_base.py +16 -0
- fastspine/alembic/__init__.py +4 -0
- fastspine/alembic/alembic.py +95 -0
- fastspine/alembic/config.py +40 -0
- fastspine/boostrap.py +78 -0
- fastspine/cache/cache_decorater.py +264 -0
- fastspine/cache/cache_encoder.py +87 -0
- fastspine/cache/cache_exception.py +4 -0
- fastspine/cache/cache_model.py +32 -0
- fastspine/cache/cache_service.py +144 -0
- fastspine/cache/key_builder.py +134 -0
- fastspine/cache/redis_cache.py +158 -0
- fastspine/celery/base_task.py +106 -0
- fastspine/celery/engine.py +52 -0
- fastspine/cli/scoped_typer.py +47 -0
- fastspine/ctx/ctx_pool.py +73 -0
- fastspine/database/engine.py +131 -0
- fastspine/decorators/contextualize_decorator.py +54 -0
- fastspine/decorators/retry_decorator.py +66 -0
- fastspine/decorators/upsert_decorator.py +107 -0
- fastspine/dependencies/database.py +193 -0
- fastspine/dependencies/profiler.py +37 -0
- fastspine/dependencies/repository_manager.py +202 -0
- fastspine/dependencies/services.py +140 -0
- fastspine/exception/access_exception.py +13 -0
- fastspine/exception/action_not_allowed_exception.py +13 -0
- fastspine/exception/base_app_exception.py +28 -0
- fastspine/exception/exception_handler.py +9 -0
- fastspine/exception/not_found_exception.py +13 -0
- fastspine/exception/security_exception.py +13 -0
- fastspine/exception/soft_delete_exception.py +13 -0
- fastspine/lib/__init__.py +4 -0
- fastspine/lib/contextualize.py +352 -0
- fastspine/lib/profiler.py +284 -0
- fastspine/mailer/mailer_service.py +44 -0
- fastspine/middleware/request_middleware.py +67 -0
- fastspine/middleware/session_middleware.py +38 -0
- fastspine/mixins/__init__.py +4 -0
- fastspine/mixins/representable.py +12 -0
- fastspine/mixins/soft_delete.py +41 -0
- fastspine/mixins/timestamps.py +35 -0
- fastspine/models/base.py +18 -0
- fastspine/redis/client.py +23 -0
- fastspine/repositories/abstract_repository.py +267 -0
- fastspine/repositories/base_repository.py +422 -0
- fastspine/repositories/external_base_repository.py +12 -0
- fastspine/repositories/repository_manager.py +101 -0
- fastspine/schemas/pagination_model.py +26 -0
- fastspine/services/api_service.py +292 -0
- fastspine/services/base_service.py +18 -0
- fastspine/settings/__init__.py +74 -0
- fastspine/settings/app_settings.py +5 -0
- fastspine/settings/cache_settings.py +32 -0
- fastspine/settings/celery_settings.py +10 -0
- fastspine/settings/mailer_settings.py +12 -0
- fastspine/settings/profiler_settings.py +10 -0
- fastspine/types/__init__.py +3 -0
- fastspine/types/types.py +6 -0
- fastspine/util/class_util.py +110 -0
- fastspine/util/conversion.py +37 -0
- fastspine/util/dataframe_util.py +30 -0
- fastspine/util/dates.py +34 -0
- fastspine/util/debug_util.py +29 -0
- fastspine/util/emails.py +14 -0
- fastspine/util/files.py +29 -0
- fastspine/util/math.py +3 -0
- fastspine-1.0.0.dist-info/METADATA +372 -0
- fastspine-1.0.0.dist-info/RECORD +71 -0
- fastspine-1.0.0.dist-info/WHEEL +4 -0
- fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
fastspine/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from .abstract.owner_base import OwnerBase
|
|
2
|
+
from .boostrap import FastSpineApp, run_fast_core_app
|
|
3
|
+
from .cache.cache_decorater import cache_method, cache_method_async, cache_response
|
|
4
|
+
from .celery.base_task import BaseTask
|
|
5
|
+
from .dependencies.profiler import load_profiler
|
|
6
|
+
from .dependencies.repository_manager import get_repository_manager, load_repository_manager
|
|
7
|
+
from .dependencies.services import (
|
|
8
|
+
load_service,
|
|
9
|
+
load_services,
|
|
10
|
+
service_dep,
|
|
11
|
+
)
|
|
12
|
+
from .exception.access_exception import AccessDeniedError
|
|
13
|
+
from .exception.action_not_allowed_exception import ActionNotAllowedError
|
|
14
|
+
from .exception.base_app_exception import BaseAppError, BaseError
|
|
15
|
+
from .exception.not_found_exception import NotFoundError
|
|
16
|
+
from .exception.security_exception import SecurityAlertError
|
|
17
|
+
from .repositories.base_repository import BaseRepository
|
|
18
|
+
from .repositories.external_base_repository import ExternalBaseRepository
|
|
19
|
+
from .repositories.repository_manager import RepositoryManager
|
|
20
|
+
from .services.base_service import BaseService
|
|
21
|
+
from .settings import get_core_settings
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"BaseRepository",
|
|
25
|
+
"ExternalBaseRepository",
|
|
26
|
+
"OwnerBase",
|
|
27
|
+
"get_core_settings",
|
|
28
|
+
"run_fast_core_app",
|
|
29
|
+
"load_service",
|
|
30
|
+
"load_services",
|
|
31
|
+
"service_dep",
|
|
32
|
+
"RepositoryManager",
|
|
33
|
+
"BaseService",
|
|
34
|
+
"get_repository_manager",
|
|
35
|
+
"load_repository_manager",
|
|
36
|
+
"load_profiler",
|
|
37
|
+
"BaseTask",
|
|
38
|
+
"BaseAppError",
|
|
39
|
+
"BaseError",
|
|
40
|
+
"AccessDeniedError",
|
|
41
|
+
"ActionNotAllowedError",
|
|
42
|
+
"NotFoundError",
|
|
43
|
+
"SecurityAlertError",
|
|
44
|
+
"FastSpineApp",
|
|
45
|
+
"cache_response",
|
|
46
|
+
"cache_method_async",
|
|
47
|
+
"cache_method",
|
|
48
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import final
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class OwnerBase(ABC):
|
|
6
|
+
"""Abstract base class for objects that have an owner."""
|
|
7
|
+
|
|
8
|
+
@abstractmethod
|
|
9
|
+
def get_owner(self) -> str:
|
|
10
|
+
"""Get the owner of the object."""
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
@final
|
|
14
|
+
def is_owner(self, email: str) -> bool:
|
|
15
|
+
"""Check if the given email is the owner of the object."""
|
|
16
|
+
return self.get_owner() == email
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import time
|
|
3
|
+
import os
|
|
4
|
+
from alembic import context
|
|
5
|
+
from logging.config import fileConfig
|
|
6
|
+
from sqlalchemy import engine_from_config, pool
|
|
7
|
+
from sqlalchemy.exc import OperationalError
|
|
8
|
+
|
|
9
|
+
from ..models.base import Base
|
|
10
|
+
|
|
11
|
+
def _import_all_models(directories_dict: dict[str, str]) -> None:
|
|
12
|
+
"""Import all Python modules in the specified directories and their subdirectories."""
|
|
13
|
+
for directory, base_package in directories_dict.items():
|
|
14
|
+
for root, dirs, files in os.walk(directory): # noqa: B007
|
|
15
|
+
package_path = root.replace(directory, "").strip(os.path.sep).replace(os.path.sep, ".")
|
|
16
|
+
package_name = f"{base_package}.{package_path}" if package_path else base_package
|
|
17
|
+
|
|
18
|
+
for file in files:
|
|
19
|
+
if file.endswith(".py") and file != "__init__.py":
|
|
20
|
+
module_name = file[:-3] # Remove `.py`
|
|
21
|
+
full_module_name = f"{package_name}.{module_name}"
|
|
22
|
+
try:
|
|
23
|
+
importlib.import_module(full_module_name)
|
|
24
|
+
except ModuleNotFoundError as e:
|
|
25
|
+
print(f"Module {full_module_name} not found: {e}")
|
|
26
|
+
except Exception as e:
|
|
27
|
+
print(f"An error occurred while importing {full_module_name}: {e}")
|
|
28
|
+
|
|
29
|
+
def run_migrations_offline(db_uri: str, models_directory: str, models_folder: str|None = None) -> None:
|
|
30
|
+
# Specify the directory containing your models
|
|
31
|
+
models_folder = models_folder or os.path.join(os.path.dirname(__file__), "../src/models")
|
|
32
|
+
models_directory_base = models_folder
|
|
33
|
+
models_directories = {
|
|
34
|
+
models_directory_base: models_directory,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
config = context.config
|
|
38
|
+
# Interpret the config file for Python logging.
|
|
39
|
+
# This line sets up loggers basically.
|
|
40
|
+
if config.config_file_name is not None:
|
|
41
|
+
fileConfig(config.config_file_name)
|
|
42
|
+
|
|
43
|
+
_import_all_models(models_directories)
|
|
44
|
+
# add your model's MetaData object here
|
|
45
|
+
# for 'autogenerate' support
|
|
46
|
+
# from myapp import mymodel
|
|
47
|
+
# target_metadata = mymodel.Base.metadata
|
|
48
|
+
target_metadata = Base.metadata
|
|
49
|
+
|
|
50
|
+
url = db_uri
|
|
51
|
+
context.configure(
|
|
52
|
+
url=url,
|
|
53
|
+
target_metadata=target_metadata,
|
|
54
|
+
literal_binds=True,
|
|
55
|
+
dialect_opts={"paramstyle": "named"},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
with context.begin_transaction():
|
|
59
|
+
context.run_migrations()
|
|
60
|
+
|
|
61
|
+
def run_migrations_online(db_uri: str) -> None:
|
|
62
|
+
"""Run migrations in 'online' mode.
|
|
63
|
+
|
|
64
|
+
In this scenario we need to create an Engine
|
|
65
|
+
and associate a connection with the context.
|
|
66
|
+
|
|
67
|
+
"""
|
|
68
|
+
config = context.config
|
|
69
|
+
config.set_main_option("sqlalchemy.url", db_uri)
|
|
70
|
+
connectable = engine_from_config(
|
|
71
|
+
config.get_section(config.config_ini_section, {}),
|
|
72
|
+
prefix="sqlalchemy.",
|
|
73
|
+
poolclass=pool.NullPool,
|
|
74
|
+
)
|
|
75
|
+
target_metadata = Base.metadata
|
|
76
|
+
max_retries = 10
|
|
77
|
+
retry_delay = 1
|
|
78
|
+
|
|
79
|
+
for attempt in range(max_retries):
|
|
80
|
+
try:
|
|
81
|
+
with connectable.connect() as connection:
|
|
82
|
+
context.configure(connection=connection, target_metadata=target_metadata)
|
|
83
|
+
|
|
84
|
+
with context.begin_transaction():
|
|
85
|
+
context.run_migrations()
|
|
86
|
+
break
|
|
87
|
+
except OperationalError as e:
|
|
88
|
+
if attempt < max_retries - 1:
|
|
89
|
+
print(f"Database connection failed (attempt {attempt + 1}/{max_retries}): {e}")
|
|
90
|
+
print(f"Retrying in {retry_delay} seconds...")
|
|
91
|
+
time.sleep(retry_delay)
|
|
92
|
+
retry_delay = min(retry_delay * 2, 30) # Exponential backoff, max 30s
|
|
93
|
+
else:
|
|
94
|
+
print(f"Failed to connect to database after {max_retries} attempts")
|
|
95
|
+
raise
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from fastspine.database.engine import DBConfig
|
|
2
|
+
from pydantic import SecretStr
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _get_url(settings: DBConfig | None, service:str = 'postgres') -> str:
|
|
6
|
+
"""Return the database URL from the config object."""
|
|
7
|
+
if settings is None:
|
|
8
|
+
raise ValueError("Config is not configured")
|
|
9
|
+
if not isinstance(settings.password, SecretStr):
|
|
10
|
+
raise TypeError("Password must be of type SecretStr.")
|
|
11
|
+
|
|
12
|
+
return _create_db_engine(
|
|
13
|
+
settings.user,
|
|
14
|
+
settings.password.get_secret_value(),
|
|
15
|
+
settings.host,
|
|
16
|
+
str(settings.port),
|
|
17
|
+
settings.dbname,
|
|
18
|
+
service=service
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def get_postgres_url(settings: DBConfig | None) -> str:
|
|
22
|
+
return _get_url(settings, service='postgresql')
|
|
23
|
+
|
|
24
|
+
def get_mysql_url(settings: DBConfig | None) -> str:
|
|
25
|
+
return _get_url(settings, service='mysql')
|
|
26
|
+
|
|
27
|
+
def _create_db_engine(user, password, host, port, db_name, service: str = "postgresql") -> str:
|
|
28
|
+
return (
|
|
29
|
+
service + "://"
|
|
30
|
+
+ user
|
|
31
|
+
+ ":"
|
|
32
|
+
+ password
|
|
33
|
+
+ "@"
|
|
34
|
+
+ host
|
|
35
|
+
+ ":"
|
|
36
|
+
+ port
|
|
37
|
+
+ "/"
|
|
38
|
+
+ db_name
|
|
39
|
+
)
|
|
40
|
+
|
fastspine/boostrap.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from fastapi import FastAPI
|
|
2
|
+
from pydantic_settings import BaseSettings
|
|
3
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
4
|
+
|
|
5
|
+
from .exception.base_app_exception import BaseAppError
|
|
6
|
+
from .exception.exception_handler import value_error_handler
|
|
7
|
+
from .settings import CoreSettings, init_core_settings
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FastSpineApp(FastAPI):
|
|
11
|
+
"""A FastAPI application with core settings and middleware."""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
*,
|
|
16
|
+
settings: BaseSettings | None = None,
|
|
17
|
+
use_asgi_middleware: bool = False,
|
|
18
|
+
**kwargs,
|
|
19
|
+
):
|
|
20
|
+
"""Initialize the FastCoreApp with optional settings and middleware choice.
|
|
21
|
+
|
|
22
|
+
Accepts every keyword argument `FastAPI.__init__` accepts (`title`, `debug`,
|
|
23
|
+
`lifespan`, ...), forwarded as-is, in addition to `settings` and `use_asgi_middleware`.
|
|
24
|
+
"""
|
|
25
|
+
self.core_settings: CoreSettings = init_core_settings(settings=settings)
|
|
26
|
+
kwargs.setdefault("title", self.core_settings.PROJECT_NAME)
|
|
27
|
+
super().__init__(**kwargs)
|
|
28
|
+
self.add_exception_handler(BaseAppError, value_error_handler)
|
|
29
|
+
|
|
30
|
+
if use_asgi_middleware:
|
|
31
|
+
from .middleware.request_middleware import RequestMiddlewareASGI as RequestMiddleware
|
|
32
|
+
from .middleware.session_middleware import DBSessionMiddlewareASGI as DBSessionMiddleware
|
|
33
|
+
else:
|
|
34
|
+
from .middleware.request_middleware import RequestMiddleware
|
|
35
|
+
from .middleware.session_middleware import DBSessionMiddleware
|
|
36
|
+
|
|
37
|
+
self.add_middleware(RequestMiddleware)
|
|
38
|
+
self.add_middleware(DBSessionMiddleware)
|
|
39
|
+
|
|
40
|
+
if self.core_settings.DEBUG_MODE and use_asgi_middleware:
|
|
41
|
+
for m in self.user_middleware:
|
|
42
|
+
if issubclass(m.cls, BaseHTTPMiddleware):
|
|
43
|
+
raise RuntimeError(
|
|
44
|
+
f"BaseHTTPMiddleware {m.cls.__name__} is not compatible with streaming mode. Please use the ASGI middleware variants for streaming responses."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def run_fast_core_app(settings: BaseSettings | None = None, use_asgi_middleware: bool = False) -> FastAPI:
|
|
49
|
+
"""Initialize the FastAPI core application.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
settings (BaseSettings): The settings instance containing configuration.
|
|
53
|
+
use_asgi_middleware (bool): Whether to use ASGI middleware for streaming responses.
|
|
54
|
+
|
|
55
|
+
This function sets up the core settings, middleware, and routes for the FastAPI application.
|
|
56
|
+
"""
|
|
57
|
+
core_settings: CoreSettings = init_core_settings(settings=settings)
|
|
58
|
+
app = FastAPI(title=core_settings.PROJECT_NAME)
|
|
59
|
+
app.add_exception_handler(BaseAppError, value_error_handler)
|
|
60
|
+
|
|
61
|
+
if use_asgi_middleware:
|
|
62
|
+
from .middleware.request_middleware import RequestMiddlewareASGI as RequestMiddleware
|
|
63
|
+
from .middleware.session_middleware import DBSessionMiddlewareASGI as DBSessionMiddleware
|
|
64
|
+
else:
|
|
65
|
+
from .middleware.request_middleware import RequestMiddleware
|
|
66
|
+
from .middleware.session_middleware import DBSessionMiddleware
|
|
67
|
+
|
|
68
|
+
app.add_middleware(RequestMiddleware)
|
|
69
|
+
app.add_middleware(DBSessionMiddleware)
|
|
70
|
+
|
|
71
|
+
if core_settings.DEBUG_MODE and use_asgi_middleware:
|
|
72
|
+
for m in app.user_middleware:
|
|
73
|
+
if issubclass(m.cls, BaseHTTPMiddleware):
|
|
74
|
+
raise RuntimeError(
|
|
75
|
+
f"BaseHTTPMiddleware {m.cls.__name__} is not compatible with streaming mode. Please use the ASGI middleware variants for streaming responses."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
return app
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
from datetime import timedelta
|
|
2
|
+
from functools import wraps
|
|
3
|
+
from inspect import iscoroutinefunction
|
|
4
|
+
from typing import Any, Callable, TypeVar, cast
|
|
5
|
+
|
|
6
|
+
from fastapi import HTTPException, Request
|
|
7
|
+
|
|
8
|
+
from ..ctx.ctx_pool import ctxpool
|
|
9
|
+
from ..dependencies.profiler import fetch_profiler
|
|
10
|
+
from .cache_encoder import CacheResponseEncoder, PickledEncoder
|
|
11
|
+
from .cache_exception import CacheError
|
|
12
|
+
from .key_builder import KeyBuilder
|
|
13
|
+
from .redis_cache import cache_get, cache_set, lock, sync_cache_get, sync_cache_set, sync_lock
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T", bound=Callable[..., Any])
|
|
16
|
+
|
|
17
|
+
_UNSET = object() # distinguishes "handler not called yet" from a legitimate `None` result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _log_cache_hit(function_name: str, cache_key: str) -> None:
|
|
21
|
+
profiler = fetch_profiler()
|
|
22
|
+
profiler.info("Cache hit", extra={"function": function_name, "cache_key": cache_key, "checkpoint": 1})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _log_cache_miss(function_name: str, cache_key: str) -> None:
|
|
26
|
+
profiler = fetch_profiler()
|
|
27
|
+
profiler.info("Cache miss", extra={"function": function_name, "cache_key": cache_key, "checkpoint": -1})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _log_cache_error(function_name: str, cache_key: str, error: Exception) -> None:
|
|
31
|
+
profiler = fetch_profiler()
|
|
32
|
+
profiler.error(
|
|
33
|
+
"Cache error",
|
|
34
|
+
extra={"function": function_name, "cache_key": cache_key, "error": str(error), "checkpoint": 0},
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def cache_response(
|
|
39
|
+
expire: int | timedelta = 60,
|
|
40
|
+
version: str = "v1",
|
|
41
|
+
key_prefix: str = "cache",
|
|
42
|
+
exclude_params: list[str] | None = None,
|
|
43
|
+
ignore_errors: bool = True,
|
|
44
|
+
):
|
|
45
|
+
"""Decorator to cache the response in routes of an sync route."""
|
|
46
|
+
|
|
47
|
+
def decorator(func: T) -> T:
|
|
48
|
+
if (not iscoroutinefunction(func)) and not callable(func):
|
|
49
|
+
raise TypeError("The decorated function must be callable or an async function.")
|
|
50
|
+
|
|
51
|
+
@wraps(func)
|
|
52
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
53
|
+
"""Wrapper function to handle caching logic."""
|
|
54
|
+
request: Request | None = ctxpool.get("request_context")
|
|
55
|
+
if request is None:
|
|
56
|
+
raise RuntimeError("Request object is required for cache_response")
|
|
57
|
+
|
|
58
|
+
if request.method != "GET":
|
|
59
|
+
raise HTTPException(
|
|
60
|
+
status_code=405,
|
|
61
|
+
detail="Cache response is only applicable for GET requests",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
expire_seconds = expire.total_seconds() if isinstance(expire, timedelta) else expire
|
|
65
|
+
params = {**request.path_params, **request.query_params}
|
|
66
|
+
if exclude_params:
|
|
67
|
+
for param in exclude_params:
|
|
68
|
+
params.pop(param, None)
|
|
69
|
+
cache_key = KeyBuilder.request_key_builder(
|
|
70
|
+
func=func,
|
|
71
|
+
version=version,
|
|
72
|
+
key_prefix=key_prefix,
|
|
73
|
+
params=params,
|
|
74
|
+
)
|
|
75
|
+
redis_lock = lock(cache_key)
|
|
76
|
+
if redis_lock is None:
|
|
77
|
+
return await func(*args, **kwargs)
|
|
78
|
+
|
|
79
|
+
acquired = False
|
|
80
|
+
try:
|
|
81
|
+
result = _UNSET
|
|
82
|
+
if request.headers.get("X-Cache-Bypass") == "true":
|
|
83
|
+
result = await func(*args, **kwargs)
|
|
84
|
+
await cache_set(cache_key, result, int(expire_seconds), CacheResponseEncoder)
|
|
85
|
+
return result
|
|
86
|
+
|
|
87
|
+
cached = await cache_get(cache_key, CacheResponseEncoder)
|
|
88
|
+
|
|
89
|
+
if cached is not None:
|
|
90
|
+
return cached
|
|
91
|
+
acquired = await redis_lock.acquire(blocking=True, timeout=30)
|
|
92
|
+
if not acquired:
|
|
93
|
+
raise RuntimeError("Failed to acquire Redis lock")
|
|
94
|
+
cached = await cache_get(cache_key, CacheResponseEncoder)
|
|
95
|
+
|
|
96
|
+
if cached is not None:
|
|
97
|
+
return cached
|
|
98
|
+
result = await func(*args, **kwargs)
|
|
99
|
+
if isinstance(result, Exception):
|
|
100
|
+
return result # Return error response without caching
|
|
101
|
+
await cache_set(cache_key, result, int(expire_seconds), CacheResponseEncoder)
|
|
102
|
+
return result
|
|
103
|
+
|
|
104
|
+
except CacheError as e:
|
|
105
|
+
if not ignore_errors:
|
|
106
|
+
raise HTTPException(status_code=500, detail=f"Cache operation failed: {str(e)}") from e
|
|
107
|
+
if result is not _UNSET:
|
|
108
|
+
return result # Already computed - don't call the handler a second time
|
|
109
|
+
return await func(*args, **kwargs)
|
|
110
|
+
finally:
|
|
111
|
+
if acquired:
|
|
112
|
+
await redis_lock.release()
|
|
113
|
+
|
|
114
|
+
return cast(T, wrapper)
|
|
115
|
+
|
|
116
|
+
return decorator
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def cache_method_async(
|
|
120
|
+
expire: int | timedelta = 60,
|
|
121
|
+
version: str = "v1",
|
|
122
|
+
key_prefix: str = "cache",
|
|
123
|
+
ignore_errors: bool = True,
|
|
124
|
+
use_compression: bool = False,
|
|
125
|
+
log_cache_hits: bool = False,
|
|
126
|
+
log_cache_misses: bool = False,
|
|
127
|
+
log_cache_errors: bool = False,
|
|
128
|
+
):
|
|
129
|
+
"""Decorator to cache the response of an async function."""
|
|
130
|
+
|
|
131
|
+
def decorator(func: T) -> T:
|
|
132
|
+
expire_seconds = expire.total_seconds() if isinstance(expire, timedelta) else expire
|
|
133
|
+
if (not iscoroutinefunction(func)) and not callable(func):
|
|
134
|
+
raise TypeError("The decorated function must be callable or an async function.")
|
|
135
|
+
|
|
136
|
+
@wraps(func)
|
|
137
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
138
|
+
"""Wrapper function to handle caching logic."""
|
|
139
|
+
cache_key = KeyBuilder.key_builder(
|
|
140
|
+
func,
|
|
141
|
+
namespace=f"{key_prefix}:{version}",
|
|
142
|
+
args=args,
|
|
143
|
+
kwargs=kwargs,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
redis_lock = lock(cache_key)
|
|
147
|
+
if redis_lock is None:
|
|
148
|
+
if log_cache_misses:
|
|
149
|
+
_log_cache_miss(func.__name__, cache_key)
|
|
150
|
+
return await func(*args, **kwargs)
|
|
151
|
+
|
|
152
|
+
acquired = False
|
|
153
|
+
try:
|
|
154
|
+
result = _UNSET
|
|
155
|
+
cached = await cache_get(cache_key, PickledEncoder, use_compression=use_compression)
|
|
156
|
+
|
|
157
|
+
if cached is not None:
|
|
158
|
+
if log_cache_hits:
|
|
159
|
+
_log_cache_hit(func.__name__, cache_key)
|
|
160
|
+
return cached
|
|
161
|
+
|
|
162
|
+
acquired = await redis_lock.acquire(blocking=True)
|
|
163
|
+
|
|
164
|
+
if not acquired:
|
|
165
|
+
raise RuntimeError("Failed to acquire Redis lock")
|
|
166
|
+
cached = await cache_get(cache_key, PickledEncoder, use_compression=use_compression)
|
|
167
|
+
|
|
168
|
+
if cached is not None:
|
|
169
|
+
if log_cache_hits:
|
|
170
|
+
_log_cache_hit(func.__name__, cache_key)
|
|
171
|
+
return cached
|
|
172
|
+
|
|
173
|
+
if log_cache_misses:
|
|
174
|
+
_log_cache_miss(func.__name__, cache_key)
|
|
175
|
+
result = await func(*args, **kwargs)
|
|
176
|
+
|
|
177
|
+
if isinstance(result, Exception):
|
|
178
|
+
return result # Return error response without caching
|
|
179
|
+
|
|
180
|
+
await cache_set(cache_key, result, int(expire_seconds), PickledEncoder, use_compression=use_compression)
|
|
181
|
+
|
|
182
|
+
return result
|
|
183
|
+
|
|
184
|
+
except CacheError as e:
|
|
185
|
+
if not ignore_errors:
|
|
186
|
+
raise HTTPException(status_code=500, detail=f"Cache operation failed: {e!s}") from e
|
|
187
|
+
# If cache fails, execute the original function
|
|
188
|
+
if log_cache_errors:
|
|
189
|
+
_log_cache_error(func.__name__, cache_key, e)
|
|
190
|
+
if result is not _UNSET:
|
|
191
|
+
return result # Already computed - don't call the handler a second time
|
|
192
|
+
return await func(*args, **kwargs)
|
|
193
|
+
finally:
|
|
194
|
+
if acquired:
|
|
195
|
+
await redis_lock.release()
|
|
196
|
+
|
|
197
|
+
return cast(T, async_wrapper)
|
|
198
|
+
|
|
199
|
+
return decorator
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cache_method(
|
|
203
|
+
expire: int | timedelta = 60,
|
|
204
|
+
version: str = "v1",
|
|
205
|
+
key_prefix: str = "cache",
|
|
206
|
+
ignore_errors: bool = True,
|
|
207
|
+
use_compression: bool = False,
|
|
208
|
+
):
|
|
209
|
+
"""Decorator to cache the response of an sync function."""
|
|
210
|
+
|
|
211
|
+
def decorator(func: T) -> T:
|
|
212
|
+
expire_seconds = expire.total_seconds() if isinstance(expire, timedelta) else expire
|
|
213
|
+
if (iscoroutinefunction(func)) and not callable(func):
|
|
214
|
+
raise TypeError("The decorated function must be callable or an sync function.")
|
|
215
|
+
|
|
216
|
+
@wraps(func)
|
|
217
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
218
|
+
"""Wrapper function to handle caching logic."""
|
|
219
|
+
cache_key = KeyBuilder.key_builder(
|
|
220
|
+
func,
|
|
221
|
+
namespace=f"{key_prefix}:{version}",
|
|
222
|
+
args=args,
|
|
223
|
+
kwargs=kwargs,
|
|
224
|
+
)
|
|
225
|
+
redis_lock = sync_lock(cache_key)
|
|
226
|
+
if redis_lock is None:
|
|
227
|
+
return func(*args, **kwargs)
|
|
228
|
+
|
|
229
|
+
acquired = False
|
|
230
|
+
try:
|
|
231
|
+
result = _UNSET
|
|
232
|
+
cached = sync_cache_get(cache_key, PickledEncoder, use_compression=use_compression)
|
|
233
|
+
|
|
234
|
+
if cached is not None:
|
|
235
|
+
return cached
|
|
236
|
+
acquired = redis_lock.acquire(blocking=True)
|
|
237
|
+
if not acquired:
|
|
238
|
+
raise RuntimeError("Failed to acquire Redis lock")
|
|
239
|
+
|
|
240
|
+
cached = sync_cache_get(cache_key, PickledEncoder, use_compression=use_compression)
|
|
241
|
+
if cached is not None:
|
|
242
|
+
return cached
|
|
243
|
+
|
|
244
|
+
result = func(*args, **kwargs)
|
|
245
|
+
|
|
246
|
+
if isinstance(result, Exception):
|
|
247
|
+
return result # Return error response without caching
|
|
248
|
+
|
|
249
|
+
sync_cache_set(cache_key, result, int(expire_seconds), PickledEncoder, use_compression=use_compression)
|
|
250
|
+
return result
|
|
251
|
+
|
|
252
|
+
except CacheError as e:
|
|
253
|
+
if not ignore_errors:
|
|
254
|
+
raise HTTPException(status_code=500, detail=f"Cache operation failed: {str(e)}") from e
|
|
255
|
+
if result is not _UNSET:
|
|
256
|
+
return result # Already computed - don't call the handler a second time
|
|
257
|
+
return func(*args, **kwargs)
|
|
258
|
+
finally:
|
|
259
|
+
if acquired:
|
|
260
|
+
redis_lock.release()
|
|
261
|
+
|
|
262
|
+
return cast(T, sync_wrapper)
|
|
263
|
+
|
|
264
|
+
return decorator
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pickle
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Encoder(Protocol):
|
|
9
|
+
"""Abstract base class for encoding and decoding cache responses."""
|
|
10
|
+
|
|
11
|
+
@staticmethod
|
|
12
|
+
def encode(value: Any) -> Any:
|
|
13
|
+
"""Encodes a response into a string format."""
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
@staticmethod
|
|
17
|
+
def decode(encoded_value: Any) -> dict:
|
|
18
|
+
"""Decodes a string back into a response dictionary."""
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CacheResponseEncoder:
|
|
23
|
+
"""A class to encode cache responses."""
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def encode(value: Any) -> str:
|
|
27
|
+
"""Encodes a response dictionary into a string format.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
response (dict): The response dictionary to encode.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
str: The encoded response as a string.
|
|
34
|
+
"""
|
|
35
|
+
if isinstance(value, BaseModel):
|
|
36
|
+
serialized = json.dumps(value.model_dump())
|
|
37
|
+
elif isinstance(value, list) and all(isinstance(i, BaseModel) for i in value):
|
|
38
|
+
serialized = json.dumps([i.model_dump() for i in value])
|
|
39
|
+
else:
|
|
40
|
+
serialized = json.dumps(value)
|
|
41
|
+
return str(serialized)
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def decode(encoded_response: str) -> dict:
|
|
45
|
+
"""Decodes a string back into a response dictionary.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
encoded_response (str): The encoded response string.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
dict: The decoded response dictionary.
|
|
52
|
+
"""
|
|
53
|
+
try:
|
|
54
|
+
return json.loads(encoded_response)
|
|
55
|
+
except json.JSONDecodeError as e:
|
|
56
|
+
raise ValueError(f"Failed to decode response: {str(e)}") from e
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PickledEncoder:
|
|
60
|
+
"""A class to encode cache responses using pickle."""
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def encode(value: Any) -> bytes:
|
|
64
|
+
"""Encodes a response dictionary into a string format.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
response (dict): The response dictionary to encode.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
str: The encoded response as a string.
|
|
71
|
+
"""
|
|
72
|
+
return pickle.dumps(value)
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def decode(encoded_response: bytes) -> Any:
|
|
76
|
+
"""Decodes a string back into a response dictionary.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
encoded_response (str): The encoded response string.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
dict: The decoded response dictionary.
|
|
83
|
+
"""
|
|
84
|
+
try:
|
|
85
|
+
return pickle.loads(encoded_response) # noqa: S301
|
|
86
|
+
except pickle.UnpicklingError as e:
|
|
87
|
+
raise ValueError(f"Failed to decode response: {str(e)}") from e
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CachableModel(BaseModel, ABC):
|
|
7
|
+
"""Abstract base class for cacheable models."""
|
|
8
|
+
|
|
9
|
+
@abstractmethod
|
|
10
|
+
def get_cache_identifier(self) -> str:
|
|
11
|
+
"""Get a unique identifier for the cache entry.
|
|
12
|
+
|
|
13
|
+
This identifier should be unique for each instance of the model
|
|
14
|
+
and should not change over time. It is used to store and retrieve
|
|
15
|
+
the cached data.
|
|
16
|
+
"""
|
|
17
|
+
raise NotImplementedError("Subclasses must implement this method")
|
|
18
|
+
|
|
19
|
+
@abstractmethod
|
|
20
|
+
def get_cache_expire_seconds(self) -> int:
|
|
21
|
+
"""Get the expiration time for the cache entry in seconds.
|
|
22
|
+
|
|
23
|
+
Use 0 for no expiration. This is useful for caching data that should not expire.
|
|
24
|
+
Use a positive integer for data that should expire after a certain time.
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
raise NotImplementedError("Subclasses must implement this method")
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def cache_expire_seconds(self) -> int:
|
|
31
|
+
"""Get the expiration time for the cache entry in seconds."""
|
|
32
|
+
return self.get_cache_expire_seconds()
|