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
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import contextvars
|
|
2
|
+
from contextvars import ContextVar
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CtxPool:
|
|
7
|
+
"""A pool for managing context variables."""
|
|
8
|
+
|
|
9
|
+
def __init__(self):
|
|
10
|
+
self._vars: dict[str, tuple[ContextVar, bool]] = {} # map: name -> (ContextVar, persistent: bool)
|
|
11
|
+
|
|
12
|
+
def new(self, name: str, default: Any = None, persistant: bool = False) -> ContextVar:
|
|
13
|
+
"""Create a new context variable with the given name and default value."""
|
|
14
|
+
var = ContextVar(name, default=default)
|
|
15
|
+
self._vars[name] = (var, persistant)
|
|
16
|
+
return var
|
|
17
|
+
|
|
18
|
+
def clear(self):
|
|
19
|
+
"""Clear all context variables in the pool."""
|
|
20
|
+
for name, (var, persistent) in self._vars.items():
|
|
21
|
+
if not persistent:
|
|
22
|
+
var.set(None)
|
|
23
|
+
|
|
24
|
+
def clear_one(self, name: str, value: Any = None):
|
|
25
|
+
"""Clear a specific context variable by name."""
|
|
26
|
+
if name in self._vars:
|
|
27
|
+
var, persistent = self._vars[name]
|
|
28
|
+
if not persistent:
|
|
29
|
+
var.set(value)
|
|
30
|
+
else:
|
|
31
|
+
raise ValueError(f"Cannot clear persistent context variable '{name}'.")
|
|
32
|
+
else:
|
|
33
|
+
raise KeyError(f"Context variable '{name}' not found in the pool.")
|
|
34
|
+
|
|
35
|
+
def get(self, name: str, default: Any = None) -> Any:
|
|
36
|
+
"""Get the value of a context variable by name."""
|
|
37
|
+
if name in self._vars:
|
|
38
|
+
var, _ = self._vars[name]
|
|
39
|
+
value = var.get()
|
|
40
|
+
if value is not None:
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
return default
|
|
44
|
+
|
|
45
|
+
def get_context_var_value[K, V](self, context_var: contextvars.ContextVar[dict[K, V] | None]) -> dict[K, V]:
|
|
46
|
+
"""Get the value of a context variable, returning an empty dictionary if it's None."""
|
|
47
|
+
_ctx_var_name = context_var.name
|
|
48
|
+
if _ctx_var_name not in self._vars:
|
|
49
|
+
raise KeyError(f"Context variable '{_ctx_var_name}' not found in the pool.")
|
|
50
|
+
|
|
51
|
+
value = context_var.get()
|
|
52
|
+
|
|
53
|
+
if value is None:
|
|
54
|
+
return {}
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
def set(self, name: str, value: Any, create: bool = True) -> Any:
|
|
58
|
+
"""Set the value of a context variable by name."""
|
|
59
|
+
if name in self._vars:
|
|
60
|
+
var, _ = self._vars[name]
|
|
61
|
+
var.set(value)
|
|
62
|
+
return value
|
|
63
|
+
if create:
|
|
64
|
+
var = self.new(name, default=value)
|
|
65
|
+
var.set(value)
|
|
66
|
+
self._vars[name] = (var, False)
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
raise KeyError(f"Context variable '{name}' not found in the pool.")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# pool instance
|
|
73
|
+
ctxpool = CtxPool()
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
from dataclasses import fields
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Self
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field, SecretStr
|
|
6
|
+
from sqlalchemy.engine import Engine
|
|
7
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
8
|
+
|
|
9
|
+
from ..types import DBEngines
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DBServices(str, Enum):
|
|
13
|
+
"""Enum for database services."""
|
|
14
|
+
|
|
15
|
+
POSTGRES = "postgres"
|
|
16
|
+
MYSQL = "mysql"
|
|
17
|
+
ASYNC_POSTGRES = "async_postgres"
|
|
18
|
+
ASYNC_MYSQL = "async_mysql"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DBConfig(BaseModel):
|
|
22
|
+
"""Database configuration dataclass."""
|
|
23
|
+
|
|
24
|
+
dbname: str = Field()
|
|
25
|
+
user: str = Field()
|
|
26
|
+
host: str = Field()
|
|
27
|
+
password: SecretStr | None = Field(default=None, repr=False)
|
|
28
|
+
service: DBServices = Field(default=DBServices.POSTGRES)
|
|
29
|
+
port: int = Field(strict=False, gt=0, le=65535)
|
|
30
|
+
async_mode: bool = Field(default=False)
|
|
31
|
+
autocommit: bool = Field(default=False)
|
|
32
|
+
|
|
33
|
+
def model_post_init(self, __context):
|
|
34
|
+
"""Validate the DBConfig fields."""
|
|
35
|
+
if not (0 < self.port <= 65535):
|
|
36
|
+
raise ValueError(f"Port {self.port} is out of range. Must be between 1 and 65535.")
|
|
37
|
+
self._set_async()
|
|
38
|
+
|
|
39
|
+
def _set_async(self):
|
|
40
|
+
"""Set async_mode based on the service."""
|
|
41
|
+
if self.service in {DBServices.ASYNC_POSTGRES, DBServices.ASYNC_MYSQL}:
|
|
42
|
+
self.async_mode = True
|
|
43
|
+
else:
|
|
44
|
+
self.async_mode = False
|
|
45
|
+
|
|
46
|
+
def set_service(self, service: str):
|
|
47
|
+
"""Set the database service."""
|
|
48
|
+
try:
|
|
49
|
+
self.service = DBServices(service)
|
|
50
|
+
self._set_async()
|
|
51
|
+
except ValueError as err:
|
|
52
|
+
raise ValueError(f"Unsupported database service: {service}") from err
|
|
53
|
+
|
|
54
|
+
def connection_url(self) -> str:
|
|
55
|
+
"""Generate the connection URL based on the configuration."""
|
|
56
|
+
driver_map = {
|
|
57
|
+
DBServices.POSTGRES: "postgresql+psycopg2",
|
|
58
|
+
DBServices.ASYNC_POSTGRES: "postgresql+asyncpg",
|
|
59
|
+
DBServices.MYSQL: "mysql+pymysql",
|
|
60
|
+
DBServices.ASYNC_MYSQL: "mysql+aiomysql",
|
|
61
|
+
}
|
|
62
|
+
driver = driver_map[self.service]
|
|
63
|
+
|
|
64
|
+
if isinstance(self.password, SecretStr):
|
|
65
|
+
return f"{driver}://{self.user}:{self.password.get_secret_value()}@{self.host}:{self.port}/{self.dbname}"
|
|
66
|
+
|
|
67
|
+
raise TypeError(f"Password must be of type SecretStr.{self.password} is of type {type(self.password)}")
|
|
68
|
+
|
|
69
|
+
def db_url(self) -> str:
|
|
70
|
+
"""Generate the connection URL based on the configuration."""
|
|
71
|
+
if isinstance(self.password, SecretStr):
|
|
72
|
+
return f"{self.service.value}://{self.user}:{self.password.get_secret_value()}@{self.host}:{self.port}/{self.dbname}"
|
|
73
|
+
|
|
74
|
+
raise TypeError(f"Password must be of type SecretStr333.{self.password} is of type {type(self.password)}")
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def get_db_config(cls, config: dict | Self) -> Self:
|
|
78
|
+
"""Get the database configuration from the provided config."""
|
|
79
|
+
if isinstance(config, cls):
|
|
80
|
+
return config
|
|
81
|
+
|
|
82
|
+
required_fields = [f.name for f in fields(cls) if f.name != "async_mode"]
|
|
83
|
+
|
|
84
|
+
if isinstance(config, dict):
|
|
85
|
+
for f_name in required_fields:
|
|
86
|
+
if f_name not in config:
|
|
87
|
+
raise TypeError(f"Missing required field '{f_name}' in config dict.")
|
|
88
|
+
return cls(**{f_name: config[f_name] for f_name in required_fields})
|
|
89
|
+
|
|
90
|
+
for f_name in required_fields:
|
|
91
|
+
if not hasattr(config, f_name):
|
|
92
|
+
raise TypeError(f"Missing required field '{f_name}' in config object.")
|
|
93
|
+
|
|
94
|
+
return cls(**{f_name: getattr(config, f_name) for f_name in required_fields})
|
|
95
|
+
|
|
96
|
+
def create_engine(self) -> Engine:
|
|
97
|
+
"""Create and return the database engine."""
|
|
98
|
+
if self.async_mode:
|
|
99
|
+
raise ValueError("Cannot create a synchronous engine in async mode.")
|
|
100
|
+
from sqlalchemy import create_engine
|
|
101
|
+
|
|
102
|
+
return create_engine(self.connection_url(), pool_pre_ping=True)
|
|
103
|
+
|
|
104
|
+
def create_async_engine(self) -> AsyncEngine:
|
|
105
|
+
"""Create and return the async database engine."""
|
|
106
|
+
if not self.async_mode:
|
|
107
|
+
raise ValueError("Cannot create an async engine in synchronous mode.")
|
|
108
|
+
from sqlalchemy.ext.asyncio import create_async_engine
|
|
109
|
+
|
|
110
|
+
if self.autocommit:
|
|
111
|
+
return create_async_engine(
|
|
112
|
+
self.connection_url(),
|
|
113
|
+
pool_pre_ping=True,
|
|
114
|
+
isolation_level="AUTOCOMMIT",
|
|
115
|
+
pool_reset_on_return=None,
|
|
116
|
+
)
|
|
117
|
+
return create_async_engine(self.connection_url(), pool_pre_ping=True)
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def init_engine(config: "dict | DBConfig") -> DBEngines:
|
|
121
|
+
"""Initialize the database engine based on the provided configuration."""
|
|
122
|
+
db_config = DBConfig.get_db_config(config)
|
|
123
|
+
if db_config.async_mode:
|
|
124
|
+
return db_config.create_async_engine()
|
|
125
|
+
return db_config.create_engine()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class DBReadonlyConfig(DBConfig):
|
|
129
|
+
"""Database configuration dataclass for readonly connections."""
|
|
130
|
+
|
|
131
|
+
autocommit: bool = Field(default=True)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from functools import wraps
|
|
3
|
+
|
|
4
|
+
from fastspine.lib.contextualize import contextualize
|
|
5
|
+
|
|
6
|
+
from ..util.class_util import function_parameters
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def with_contextualize(**context_params):
|
|
10
|
+
"""Decorator to wrap Celery tasks with contextualize context.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
**context_params: Mapping of context key to parameter name
|
|
14
|
+
e.g., input_list_id='input_list_id', task_id='request_id'
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
@client.task(bind=True, model=BaseTask, acks_late=True, reject_on_worker_lost=True)
|
|
18
|
+
@with_contextualize(input_list_id='input_list_id')
|
|
19
|
+
def cfp_list(self, input_list_id: int, ...):
|
|
20
|
+
# Function body without the contextualize wrapper
|
|
21
|
+
|
|
22
|
+
@client.task(bind=True, model=BaseTask, acks_late=True, reject_on_worker_lost=True)
|
|
23
|
+
@with_contextualize(task_id='request_id')
|
|
24
|
+
def new_request_notify(self, request_id: int, ...):
|
|
25
|
+
# Function body without the contextualize wrapper
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def decorator(func):
|
|
29
|
+
@wraps(func)
|
|
30
|
+
def wrapper(self, *args, **kwargs):
|
|
31
|
+
correlation_id = str(uuid.uuid4())
|
|
32
|
+
task_name = self.name.split(".")[-1] if hasattr(self, "name") else func.__name__
|
|
33
|
+
|
|
34
|
+
context_kwargs = {"correlation_id": correlation_id, "task_name": task_name}
|
|
35
|
+
|
|
36
|
+
# Extract specified parameters
|
|
37
|
+
if context_params:
|
|
38
|
+
params = function_parameters(func)
|
|
39
|
+
param_names = list(params.keys())[1:] # Skip 'self'
|
|
40
|
+
|
|
41
|
+
for context_key, param_name in context_params.items():
|
|
42
|
+
if param_name in param_names:
|
|
43
|
+
param_index = param_names.index(param_name)
|
|
44
|
+
if param_index < len(args):
|
|
45
|
+
context_kwargs[context_key] = args[param_index]
|
|
46
|
+
elif param_name in kwargs:
|
|
47
|
+
context_kwargs[context_key] = kwargs[param_name]
|
|
48
|
+
|
|
49
|
+
with contextualize(**context_kwargs):
|
|
50
|
+
return func(self, *args, **kwargs)
|
|
51
|
+
|
|
52
|
+
return wrapper
|
|
53
|
+
|
|
54
|
+
return decorator
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Retry helpers for transient service failures."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import functools
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from inspect import iscoroutinefunction
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def default_fallback(*args: Any, **kwargs: Any) -> None:
|
|
15
|
+
"""Raise an error after all retry attempts have failed."""
|
|
16
|
+
logger.error("Function failed after all retry attempts")
|
|
17
|
+
raise RuntimeError("Function failed after all retry attempts")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def retry(n_tries: int, sleep_time: float, fallback: Callable[..., Any] = default_fallback):
|
|
21
|
+
"""Retry synchronous or asynchronous functions after exceptions.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
n_tries: Total number of attempts, including the initial call.
|
|
25
|
+
sleep_time: Seconds to wait between failed attempts.
|
|
26
|
+
fallback: Function called after all attempts fail.
|
|
27
|
+
"""
|
|
28
|
+
if n_tries < 1:
|
|
29
|
+
raise ValueError("n_tries must be at least 1")
|
|
30
|
+
|
|
31
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
32
|
+
if iscoroutinefunction(func):
|
|
33
|
+
|
|
34
|
+
@functools.wraps(func)
|
|
35
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
36
|
+
for attempt in range(1, n_tries + 1):
|
|
37
|
+
try:
|
|
38
|
+
return await func(*args, **kwargs)
|
|
39
|
+
except Exception as error:
|
|
40
|
+
logger.warning(
|
|
41
|
+
"Function attempt failed",
|
|
42
|
+
extra={"attempt": attempt, "function": func.__name__, "exception": error},
|
|
43
|
+
)
|
|
44
|
+
if attempt < n_tries:
|
|
45
|
+
await asyncio.sleep(sleep_time)
|
|
46
|
+
return fallback(*args, **kwargs)
|
|
47
|
+
|
|
48
|
+
return async_wrapper
|
|
49
|
+
|
|
50
|
+
@functools.wraps(func)
|
|
51
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
52
|
+
for attempt in range(1, n_tries + 1):
|
|
53
|
+
try:
|
|
54
|
+
return func(*args, **kwargs)
|
|
55
|
+
except Exception as error:
|
|
56
|
+
logger.warning(
|
|
57
|
+
"Function attempt failed",
|
|
58
|
+
extra={"attempt": attempt, "function": func.__name__, "exception": error},
|
|
59
|
+
)
|
|
60
|
+
if attempt < n_tries:
|
|
61
|
+
time.sleep(sleep_time)
|
|
62
|
+
return fallback(*args, **kwargs)
|
|
63
|
+
|
|
64
|
+
return sync_wrapper
|
|
65
|
+
|
|
66
|
+
return decorator
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
from sqlalchemy.exc import OperationalError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def upsert_decorator(batch_size=100, max_attempts=5, sort_key=None):
|
|
8
|
+
"""Decorator for batch upsert operations with retry logic.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
batch_size (int): Number of records to process in each batch
|
|
12
|
+
max_attempts (int): Maximum number of retry attempts for deadlock handling
|
|
13
|
+
sort_key (callable): Optional function to sort data before batching
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def decorator(func):
|
|
17
|
+
@functools.wraps(func)
|
|
18
|
+
def wrapper(session, data, *args, **kwargs):
|
|
19
|
+
# Allow overriding decorator defaults with kwargs
|
|
20
|
+
actual_batch_size = kwargs.pop("batch_size", batch_size)
|
|
21
|
+
actual_max_attempts = kwargs.pop("max_attempts", max_attempts)
|
|
22
|
+
actual_sort_key = kwargs.pop("sort_key", sort_key)
|
|
23
|
+
|
|
24
|
+
if len(data) == 0:
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
# Sort data if sort_key is provided
|
|
28
|
+
if actual_sort_key:
|
|
29
|
+
data = sorted(data, key=actual_sort_key)
|
|
30
|
+
|
|
31
|
+
# Process data in batches
|
|
32
|
+
for i in range(0, len(data), actual_batch_size):
|
|
33
|
+
batch = data[i : i + actual_batch_size]
|
|
34
|
+
|
|
35
|
+
# Create the upsert statement using the decorated function
|
|
36
|
+
stmt = func(session, batch, *args, **kwargs)
|
|
37
|
+
|
|
38
|
+
# Execute with retry logic
|
|
39
|
+
for attempt in range(actual_max_attempts):
|
|
40
|
+
try:
|
|
41
|
+
session.execute(stmt)
|
|
42
|
+
session.commit()
|
|
43
|
+
break
|
|
44
|
+
except OperationalError as e:
|
|
45
|
+
if "deadlock detected" in str(e) and attempt < actual_max_attempts - 1:
|
|
46
|
+
session.rollback()
|
|
47
|
+
time.sleep(0.1 * (2**attempt)) # Exponential backoff
|
|
48
|
+
continue
|
|
49
|
+
raise
|
|
50
|
+
|
|
51
|
+
return wrapper
|
|
52
|
+
|
|
53
|
+
return decorator
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def class_upsert_decorator(batch_size=100, max_attempts=5, sort_key=None, session_property="db"):
|
|
57
|
+
"""Decorator for batch upsert operations with retry logic.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
batch_size (int): Number of records to process in each batch
|
|
61
|
+
max_attempts (int): Maximum number of retry attempts for deadlock handling
|
|
62
|
+
sort_key (callable): Optional function to sort data before batching
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def decorator(func):
|
|
66
|
+
@functools.wraps(func)
|
|
67
|
+
def wrapper(self, data, *args, **kwargs):
|
|
68
|
+
# Allow overriding decorator defaults with kwargs
|
|
69
|
+
actual_batch_size = kwargs.pop("batch_size", batch_size)
|
|
70
|
+
actual_max_attempts = kwargs.pop("max_attempts", max_attempts)
|
|
71
|
+
actual_sort_key = kwargs.pop("sort_key", sort_key)
|
|
72
|
+
repo_manager = getattr(self, session_property)
|
|
73
|
+
if hasattr(repo_manager, "db"):
|
|
74
|
+
session = repo_manager.db
|
|
75
|
+
else:
|
|
76
|
+
raise AttributeError(f"The repository manager does not have a '{session_property}' attribute.")
|
|
77
|
+
|
|
78
|
+
if len(data) == 0:
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
# Sort data if sort_key is provided
|
|
82
|
+
if actual_sort_key:
|
|
83
|
+
data = sorted(data, key=actual_sort_key)
|
|
84
|
+
|
|
85
|
+
# Process data in batches
|
|
86
|
+
for i in range(0, len(data), actual_batch_size):
|
|
87
|
+
batch = data[i : i + actual_batch_size]
|
|
88
|
+
|
|
89
|
+
# Create the upsert statement using the decorated function
|
|
90
|
+
stmt = func(self, batch, *args, **kwargs)
|
|
91
|
+
|
|
92
|
+
# Execute with retry logic
|
|
93
|
+
for attempt in range(actual_max_attempts):
|
|
94
|
+
try:
|
|
95
|
+
session.execute(stmt)
|
|
96
|
+
session.commit()
|
|
97
|
+
break
|
|
98
|
+
except OperationalError as e:
|
|
99
|
+
if "deadlock detected" in str(e) and attempt < actual_max_attempts - 1:
|
|
100
|
+
session.rollback()
|
|
101
|
+
time.sleep(0.1 * (2**attempt)) # Exponential backoff
|
|
102
|
+
continue
|
|
103
|
+
raise
|
|
104
|
+
|
|
105
|
+
return wrapper
|
|
106
|
+
|
|
107
|
+
return decorator
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from collections.abc import Iterable
|
|
3
|
+
from typing import Any, Callable, get_args, get_origin
|
|
4
|
+
|
|
5
|
+
from sqlalchemy.engine import Engine
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
|
7
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
8
|
+
|
|
9
|
+
from ..database.engine import DBConfig
|
|
10
|
+
from ..repositories.repository_manager import RepositoryManager
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EngineMapping:
|
|
14
|
+
"""Mapping of session classes to their respective database engines."""
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
self._mapping = {}
|
|
18
|
+
|
|
19
|
+
def add(self, repo_manager_class: type[RepositoryManager], config: dict | DBConfig):
|
|
20
|
+
"""Add a repository manager class and its corresponding engine to the mapping."""
|
|
21
|
+
engine = DBConfig.init_engine(config)
|
|
22
|
+
self._mapping[repo_manager_class] = engine
|
|
23
|
+
|
|
24
|
+
def get(self, repo_manager_class: type[RepositoryManager]):
|
|
25
|
+
"""Get the engine for a given repository manager class."""
|
|
26
|
+
return self._mapping.get(repo_manager_class)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _init_engine(config: dict | DBConfig) -> Engine | None:
|
|
30
|
+
"""Initialize the database engine based on the provided configuration."""
|
|
31
|
+
if config is None:
|
|
32
|
+
return None
|
|
33
|
+
return DBConfig.init_engine(config)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
ENGINE_MAPPING: dict[type[RepositoryManager], Engine] = {}
|
|
37
|
+
|
|
38
|
+
DB_MAPPING: dict[type[RepositoryManager], Callable[[], Any]] = {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _generic_session_arg(repo_manager_class: type[RepositoryManager]) -> type | None:
|
|
42
|
+
"""Get the session type a `RepositoryManager` subclass is generic over, if declared."""
|
|
43
|
+
for base in getattr(repo_manager_class, "__orig_bases__", ()):
|
|
44
|
+
if get_origin(base) is RepositoryManager:
|
|
45
|
+
args = get_args(base)
|
|
46
|
+
return args[0] if args else None
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_sessionmaker(repo_manager_class: type[RepositoryManager]):
|
|
51
|
+
"""Get the sessionmaker for the database."""
|
|
52
|
+
session_engine = ENGINE_MAPPING.get(repo_manager_class)
|
|
53
|
+
if session_engine is not None:
|
|
54
|
+
session_class = _generic_session_arg(repo_manager_class) or Session
|
|
55
|
+
return sessionmaker(
|
|
56
|
+
bind=session_engine,
|
|
57
|
+
class_=session_class,
|
|
58
|
+
autocommit=False,
|
|
59
|
+
autoflush=False,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
raise ValueError(f"Unknown repository manager class: {repo_manager_class}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_async_sessionmaker(repo_manager_class: type[RepositoryManager]) -> async_sessionmaker[AsyncSession]:
|
|
66
|
+
"""Get the async session factory for the database."""
|
|
67
|
+
session_engine = ENGINE_MAPPING.get(repo_manager_class)
|
|
68
|
+
if session_engine is not None:
|
|
69
|
+
return async_sessionmaker(session_engine, expire_on_commit=False)
|
|
70
|
+
|
|
71
|
+
raise ValueError(f"Unknown repository manager class: {repo_manager_class}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _load_db(repo_manager_class: type[RepositoryManager]) -> Session:
|
|
75
|
+
session_maker = get_sessionmaker(repo_manager_class)
|
|
76
|
+
return session_maker()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _aload_db(repo_manager_class: type[RepositoryManager]) -> AsyncSession:
|
|
80
|
+
session_maker = get_async_sessionmaker(repo_manager_class)
|
|
81
|
+
return session_maker()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _close_db(db_session: Session):
|
|
85
|
+
db_session.close()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def _aclose_db(db_session: AsyncSession):
|
|
89
|
+
await db_session.close()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def register_session(repo_manager_class: type[RepositoryManager], config: Any | DBConfig):
|
|
93
|
+
"""Register a session with its corresponding engine."""
|
|
94
|
+
engine = _init_engine(config)
|
|
95
|
+
|
|
96
|
+
if ENGINE_MAPPING.get(repo_manager_class) is not None:
|
|
97
|
+
raise RuntimeError(f"RepositoryManager {repo_manager_class.__name__} is already registered with an engine.")
|
|
98
|
+
|
|
99
|
+
ENGINE_MAPPING[repo_manager_class] = engine
|
|
100
|
+
|
|
101
|
+
get_db_method_name = f"get_{repo_manager_class.__name__.lower()}_db"
|
|
102
|
+
|
|
103
|
+
def generic_db_method(): # type hint won't be exact here
|
|
104
|
+
db_session = _load_db(repo_manager_class)
|
|
105
|
+
try:
|
|
106
|
+
yield db_session
|
|
107
|
+
finally:
|
|
108
|
+
_close_db(db_session)
|
|
109
|
+
|
|
110
|
+
generic_db_method.__name__ = get_db_method_name
|
|
111
|
+
current_module = sys.modules[__name__]
|
|
112
|
+
|
|
113
|
+
setattr(current_module, get_db_method_name, generic_db_method)
|
|
114
|
+
|
|
115
|
+
if DB_MAPPING.get(repo_manager_class) is not None:
|
|
116
|
+
raise RuntimeError(
|
|
117
|
+
f"RepositoryManager {repo_manager_class.__name__} is already registered with a database method."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
DB_MAPPING[repo_manager_class] = generic_db_method
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def register_async_session(repo_manager_class: type[RepositoryManager], config: Any | DBConfig):
|
|
124
|
+
"""Register an async session with its corresponding engine."""
|
|
125
|
+
engine = _init_engine(config)
|
|
126
|
+
|
|
127
|
+
if ENGINE_MAPPING.get(repo_manager_class) is not None:
|
|
128
|
+
raise RuntimeError(f"RepositoryManager {repo_manager_class.__name__} is already registered with an engine.")
|
|
129
|
+
|
|
130
|
+
ENGINE_MAPPING[repo_manager_class] = engine
|
|
131
|
+
|
|
132
|
+
get_db_method_name = f"aget_{repo_manager_class.__name__.lower()}_db"
|
|
133
|
+
|
|
134
|
+
async def generic_async_db_method():
|
|
135
|
+
db_session = _aload_db(repo_manager_class)
|
|
136
|
+
try:
|
|
137
|
+
yield db_session
|
|
138
|
+
finally:
|
|
139
|
+
await _aclose_db(db_session)
|
|
140
|
+
|
|
141
|
+
generic_async_db_method.__name__ = get_db_method_name
|
|
142
|
+
current_module = sys.modules[__name__]
|
|
143
|
+
|
|
144
|
+
setattr(current_module, get_db_method_name, generic_async_db_method)
|
|
145
|
+
|
|
146
|
+
if DB_MAPPING.get(repo_manager_class) is not None:
|
|
147
|
+
raise RuntimeError(
|
|
148
|
+
f"RepositoryManager {repo_manager_class.__name__} is already registered with a database method."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
DB_MAPPING[repo_manager_class] = generic_async_db_method
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def register_sessions(pairs: Iterable[tuple[type[RepositoryManager], Any | DBConfig]]):
|
|
155
|
+
"""Register multiple repository managers with their database configs."""
|
|
156
|
+
for repo_manager_class, config in pairs:
|
|
157
|
+
if not issubclass(repo_manager_class, RepositoryManager):
|
|
158
|
+
raise ValueError(
|
|
159
|
+
f"Unsupported repository manager type: {repo_manager_class}. Only RepositoryManager subclasses are supported."
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
session_type = _generic_session_arg(repo_manager_class)
|
|
163
|
+
is_async = session_type is not None and issubclass(session_type, AsyncSession)
|
|
164
|
+
|
|
165
|
+
db_config = DBConfig.get_db_config(config)
|
|
166
|
+
if is_async != db_config.async_mode:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"{repo_manager_class.__name__} is generic over {session_type}, which does not match "
|
|
169
|
+
f"its config's async_mode={db_config.async_mode} (service={db_config.service})."
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
if is_async:
|
|
173
|
+
register_async_session(repo_manager_class, config)
|
|
174
|
+
else:
|
|
175
|
+
register_session(repo_manager_class, config)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def unregister_sessions(repo_manager_classes: Iterable[type[RepositoryManager]]):
|
|
179
|
+
"""Unregister multiple repository managers, closing their database engines."""
|
|
180
|
+
for repo_manager_class in repo_manager_classes:
|
|
181
|
+
if not issubclass(repo_manager_class, RepositoryManager):
|
|
182
|
+
raise ValueError(
|
|
183
|
+
f"Unsupported repository manager type: {repo_manager_class}. Only RepositoryManager subclasses are supported."
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
engine = ENGINE_MAPPING.pop(repo_manager_class, None)
|
|
187
|
+
if engine is not None:
|
|
188
|
+
if isinstance(engine, AsyncEngine):
|
|
189
|
+
await engine.dispose()
|
|
190
|
+
else:
|
|
191
|
+
engine.dispose()
|
|
192
|
+
|
|
193
|
+
DB_MAPPING.pop(repo_manager_class, None)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from fastspine.lib.profiler import Profiler
|
|
2
|
+
|
|
3
|
+
from ..ctx.ctx_pool import ctxpool
|
|
4
|
+
from ..settings import get_core_settings
|
|
5
|
+
|
|
6
|
+
profiler_ctx = ctxpool.new("profiler_ctx", default=None)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def load_profiler() -> Profiler:
|
|
10
|
+
"""Return a Profiler instance outside FastApi lifecycle ie celery task."""
|
|
11
|
+
settings = get_core_settings()
|
|
12
|
+
try:
|
|
13
|
+
profiler = ctxpool.get("profiler_ctx", default=None)
|
|
14
|
+
if profiler is None:
|
|
15
|
+
profiler = Profiler(
|
|
16
|
+
name=settings.PROFILER_NAME,
|
|
17
|
+
track_memory=settings.PROFILER_TRACK_MEMORY,
|
|
18
|
+
enabled=settings.PROFILER_ENABLED,
|
|
19
|
+
level=settings.PROFILER_LOG_LEVEL,
|
|
20
|
+
)
|
|
21
|
+
profiler_ctx.set(profiler)
|
|
22
|
+
return profiler
|
|
23
|
+
except LookupError:
|
|
24
|
+
# Context variable not set, create a new Profiler instance
|
|
25
|
+
profiler = Profiler(
|
|
26
|
+
name=settings.PROFILER_NAME,
|
|
27
|
+
track_memory=settings.PROFILER_TRACK_MEMORY,
|
|
28
|
+
enabled=settings.PROFILER_ENABLED,
|
|
29
|
+
level=settings.PROFILER_LOG_LEVEL,
|
|
30
|
+
)
|
|
31
|
+
ctxpool.set("profiler_ctx", profiler)
|
|
32
|
+
return profiler
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def fetch_profiler():
|
|
36
|
+
"""Fetch the Profiler instance inside Depends."""
|
|
37
|
+
return load_profiler()
|