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,144 @@
1
+ from typing import Any, Awaitable, Callable, TypeVar
2
+
3
+ from redis.exceptions import RedisError
4
+
5
+ from ..services.base_service import BaseService
6
+ from .cache_encoder import PickledEncoder
7
+ from .cache_exception import CacheError
8
+ from .cache_model import CachableModel
9
+ from .key_builder import KeyBuilder
10
+ from .redis_cache import (
11
+ cache_delete,
12
+ cache_get,
13
+ cache_set,
14
+ lock,
15
+ sync_cache_delete,
16
+ sync_cache_get,
17
+ sync_cache_set,
18
+ )
19
+
20
+ T = TypeVar("T")
21
+
22
+
23
+ class CacheService(BaseService):
24
+ """Service for managing cache operations."""
25
+
26
+ @staticmethod
27
+ def sync_get(plain_key: str, cls: type | None) -> Any:
28
+ """Get a value from the cache by key and optionally deserialize it into a specific class."""
29
+ if cls is None:
30
+ raise ValueError("Class type cannot be None")
31
+ cache_key = KeyBuilder.model_plain_key_builder(cls.__name__, plain_key)
32
+ return sync_cache_get(cache_key, PickledEncoder)
33
+
34
+ @staticmethod
35
+ async def get(plain_key: str, cls: type | None) -> Any:
36
+ """Get a value from the cache by key and optionally deserialize it into a specific class (async version)."""
37
+ if cls is None:
38
+ raise ValueError("Class type cannot be None")
39
+ cache_key = KeyBuilder.model_plain_key_builder(cls.__name__, plain_key)
40
+ return await cache_get(cache_key, PickledEncoder)
41
+
42
+ @staticmethod
43
+ def sync_set(object_instance: CachableModel) -> CachableModel:
44
+ """Set a value in the cache with an optional expiration time."""
45
+ if not isinstance(object_instance, CachableModel):
46
+ raise TypeError("Object must be an instance of CachableModel")
47
+ try:
48
+ cache_key = KeyBuilder.model_key_builder(object_instance)
49
+
50
+ sync_cache_set(
51
+ key=cache_key,
52
+ value=object_instance,
53
+ expire=object_instance.cache_expire_seconds,
54
+ encoder=PickledEncoder,
55
+ )
56
+
57
+ except RedisError as e:
58
+ raise CacheError(f"Error setting key {cache_key} in cache: {str(e)}") from e
59
+
60
+ return object_instance
61
+
62
+ @staticmethod
63
+ async def set(object_instance: CachableModel) -> CachableModel:
64
+ """Set a value in the cache with an optional expiration time (async version)."""
65
+ if not isinstance(object_instance, CachableModel):
66
+ raise TypeError("Object must be an instance of CachableModel")
67
+ try:
68
+ cache_key = KeyBuilder.model_key_builder(object_instance)
69
+
70
+ await cache_set(
71
+ key=cache_key,
72
+ value=object_instance,
73
+ expire=object_instance.cache_expire_seconds,
74
+ encoder=PickledEncoder,
75
+ )
76
+
77
+ except RedisError as e:
78
+ raise CacheError(f"Error setting key {cache_key} in cache: {str(e)}") from e
79
+
80
+ return object_instance
81
+
82
+ @staticmethod
83
+ async def fetch_cache(
84
+ object_instance: CachableModel,
85
+ provider: Callable[[], Awaitable[T]],
86
+ expiration: int | None = None,
87
+ ) -> T:
88
+ """Get the value of a CachableModel instance."""
89
+ if not isinstance(object_instance, CachableModel):
90
+ raise TypeError("Object must be an instance of CachableModel")
91
+ cache_key = KeyBuilder.model_key_builder(object_instance)
92
+ cached_value = await cache_get(cache_key, PickledEncoder)
93
+
94
+ if cached_value is not None:
95
+ return cached_value
96
+
97
+ # If not cached, call the provider to get the value
98
+ redis_lock = lock(cache_key)
99
+ if redis_lock is None:
100
+ return await provider()
101
+
102
+ acquired = False
103
+ try:
104
+ # stampede prevention
105
+ acquired = await redis_lock.acquire(blocking=True)
106
+
107
+ value = await provider()
108
+ expire = expiration if expiration is not None else object_instance.get_cache_expire_seconds()
109
+
110
+ # Set the value in cache
111
+ await cache_set(
112
+ key=cache_key,
113
+ value=value,
114
+ expire=expire,
115
+ encoder=PickledEncoder,
116
+ )
117
+ return value
118
+ except RedisError as e:
119
+ raise CacheError(f"Error getting key {cache_key} from cache: {str(e)}") from e
120
+ finally:
121
+ if acquired:
122
+ await redis_lock.release()
123
+
124
+ @staticmethod
125
+ def sync_delete_cache(object_instance: CachableModel) -> None:
126
+ """Delete a value from the cache by object instance."""
127
+ if not isinstance(object_instance, CachableModel):
128
+ raise TypeError("Object must be an instance of CachableModel")
129
+ cache_key = KeyBuilder.model_key_builder(object_instance)
130
+ try:
131
+ sync_cache_delete(key=cache_key)
132
+ except RedisError as e:
133
+ raise CacheError(f"Error deleting key {cache_key} from cache: {str(e)}") from e
134
+
135
+ @staticmethod
136
+ async def delete_cache(object_instance: CachableModel) -> None:
137
+ """Delete a value from the cache by object instance (async version)."""
138
+ if not isinstance(object_instance, CachableModel):
139
+ raise TypeError("Object must be an instance of CachableModel")
140
+ cache_key = KeyBuilder.model_key_builder(object_instance)
141
+ try:
142
+ await cache_delete(key=cache_key)
143
+ except RedisError as e:
144
+ raise CacheError(f"Error deleting key {cache_key} from cache: {str(e)}") from e
@@ -0,0 +1,134 @@
1
+ import hashlib
2
+ import inspect
3
+ import io
4
+ import json
5
+ from enum import Enum
6
+ from typing import Any, Callable
7
+
8
+ import polars as pl
9
+ from pydantic import BaseModel
10
+
11
+ from .cache_model import CachableModel
12
+
13
+
14
+ class KeyBuilder:
15
+ """A class to build cache keys for various entities."""
16
+
17
+ @staticmethod
18
+ def hash_key(key: str) -> str:
19
+ """Generates a hash for the given key."""
20
+ return hashlib.sha256(key.encode()).hexdigest()
21
+
22
+ @staticmethod
23
+ def _normalize_for_cache(obj: Any) -> Any:
24
+ """Normalize data structures for consistent cache keys by sorting lists and dicts."""
25
+ if isinstance(obj, pl.DataFrame):
26
+ unsupported = [name for name, dtype in obj.schema.items() if dtype == pl.Object]
27
+ if unsupported:
28
+ raise TypeError(f"Cannot build a cache key: DataFrame has unsupported Object column(s): {unsupported}")
29
+
30
+ # Sort elements within List-typed cells first, so two rows differing only by list order
31
+ # (same underlying set) don't produce different bytes - and don't destabilize the row sort
32
+ # below, which would otherwise use those lists as sort keys in their as-given order.
33
+ list_columns = [name for name, dtype in obj.schema.items() if isinstance(dtype, pl.List)]
34
+ if list_columns:
35
+ obj = obj.with_columns([pl.col(c).list.sort() for c in list_columns])
36
+
37
+ # write_ipc preserves dtype (unlike to_dict, where e.g. Int32 and Int64 columns with the
38
+ # same values collapse to identical Python ints) and avoids materializing the whole frame
39
+ # into Python objects just to build a key. rechunk() and an explicit (uncompressed)
40
+ # compression setting keep the output bytes tied only to the data, not to
41
+ # implementation details (chunk layout, default codec) that could change between
42
+ # polars versions and silently invalidate the cache.
43
+ df = obj.select(sorted(obj.columns)).sort(pl.all()).rechunk()
44
+ buf = io.BytesIO()
45
+ df.write_ipc(buf, compression="uncompressed")
46
+ return hashlib.sha256(buf.getvalue()).hexdigest()
47
+
48
+ if isinstance(obj, dict):
49
+ try:
50
+ items = sorted(obj.items())
51
+ except TypeError:
52
+ # Keys aren't mutually comparable (e.g. mixed int/str keys) - fall back to sorting
53
+ # by repr so this stays deterministic instead of raising a raw, unhelpful TypeError.
54
+ items = sorted(obj.items(), key=lambda kv: repr(kv[0]))
55
+ return {k: KeyBuilder._normalize_for_cache(v) for k, v in items}
56
+
57
+ if isinstance(obj, (list, tuple, set, frozenset)):
58
+ # Sort for consistent ordering. Sets in particular have no defined iteration order -
59
+ # it depends on PYTHONHASHSEED, which differs per worker process, so an unsorted set
60
+ # would produce a different cache key for the same logical input across workers.
61
+ try:
62
+ return sorted([KeyBuilder._normalize_for_cache(item) for item in obj])
63
+ except TypeError:
64
+ # If items are not sortable, use repr (not str) so e.g. None and "None", or 1 and
65
+ # "1", don't collide into the same cache key.
66
+ return sorted([repr(KeyBuilder._normalize_for_cache(item)) for item in obj])
67
+
68
+ if isinstance(obj, BaseModel):
69
+ return KeyBuilder._normalize_for_cache(obj.model_dump())
70
+
71
+ if isinstance(obj, Enum):
72
+ return f"{type(obj).__name__}.{obj.name}"
73
+
74
+ if hasattr(obj, "__dict__"):
75
+ raise TypeError(
76
+ f"Cannot build a cache key for unsupported type: {type(obj)!r}. "
77
+ "Use a Pydantic model, an Enum, or implement CachableModel."
78
+ )
79
+
80
+ return obj
81
+
82
+ @staticmethod
83
+ def key_builder(
84
+ func: Callable[..., Any],
85
+ namespace: str = "",
86
+ *,
87
+ args: tuple[Any, ...],
88
+ kwargs: dict[str, Any],
89
+ ) -> str:
90
+ """Builds a cache key based on the function name, module, and parameters."""
91
+ sig_params = list(inspect.signature(func).parameters)
92
+ is_bound_method = bool(sig_params) and sig_params[0] in ("self", "cls")
93
+ key_args = args[1:] if is_bound_method and args else args
94
+
95
+ # Normalize args for deterministic serialization (sort lists and dicts)
96
+ normalized_args = KeyBuilder._normalize_for_cache(key_args)
97
+
98
+ # Normalize kwargs for deterministic serialization (sort lists and dicts)
99
+ normalized_kwargs = KeyBuilder._normalize_for_cache(kwargs)
100
+
101
+ cache_key = f"{func.__module__}:{func.__name__}:{normalized_args}:{normalized_kwargs}"
102
+
103
+ return KeyBuilder.hash_key(f"{namespace}:{cache_key}")
104
+
105
+ @staticmethod
106
+ def request_key_builder(
107
+ func: Callable[..., Any],
108
+ version: str = "v1",
109
+ key_prefix: str = "cache",
110
+ params: dict | None = None,
111
+ ) -> str:
112
+ """Builds a cache key for request-based functions."""
113
+ normalized_params = KeyBuilder._normalize_for_cache(params)
114
+ cache_key = f"{key_prefix}:{version}:{func.__module__}:{func.__name__}:{json.dumps(normalized_params)}"
115
+ return KeyBuilder.hash_key(cache_key)
116
+
117
+ @staticmethod
118
+ def model_key_builder(model: CachableModel) -> str:
119
+ """Builds a cache key for a CachableModel instance."""
120
+ if not isinstance(model, CachableModel):
121
+ raise TypeError("model must be an instance of CachableModel")
122
+
123
+ cache_identifier = model.get_cache_identifier()
124
+ class_name = model.__class__.__name__
125
+ key = f"{class_name}:{cache_identifier}"
126
+ return KeyBuilder.hash_key(key)
127
+
128
+ @staticmethod
129
+ def model_plain_key_builder(cls: str, cache_identifier: str) -> str:
130
+ """Builds a plain cache key for a CachableModel instance."""
131
+ if not cache_identifier:
132
+ raise ValueError("identifier must be a non-empty string")
133
+
134
+ return KeyBuilder.hash_key(f"{cls}:{cache_identifier}")
@@ -0,0 +1,158 @@
1
+ import gzip
2
+ import json
3
+ from typing import Any, Callable, TypeVar
4
+
5
+ from redis.exceptions import RedisError
6
+ from redis.typing import ResponseT
7
+
8
+ from ..redis.client import get_redis_client, get_sync_redis_client
9
+ from .cache_encoder import Encoder, PickledEncoder
10
+ from .cache_exception import CacheError
11
+
12
+ T = TypeVar("T", bound=Callable[..., Any])
13
+
14
+
15
+ async def cache_get(key: str, decoder: type[Encoder] = PickledEncoder, use_compression: bool = False) -> Any | None:
16
+ """Retrieve a value from Redis cache by key."""
17
+ try:
18
+ redis_client = get_redis_client()
19
+ if redis_client is None:
20
+ return None
21
+ cached = await redis_client.get(key)
22
+ if cached:
23
+ if use_compression:
24
+ decompressed = gzip.decompress(cached)
25
+ return decoder.decode(decompressed)
26
+ return decoder.decode(cached)
27
+ return None
28
+
29
+ except (RedisError, json.JSONDecodeError, ValueError) as e:
30
+ raise CacheError(f"Cache get failed: {e!s}") from e
31
+
32
+
33
+ async def cache_set(
34
+ key: str, value: Any, expire: int = 60, encoder: type[Encoder] = PickledEncoder, use_compression: bool = False
35
+ ) -> bool:
36
+ """Set a value in Redis cache with an optional expiration time."""
37
+ try:
38
+ # do not cache None values
39
+ redis_client = get_redis_client()
40
+ if redis_client is None:
41
+ return False
42
+ if value is not None:
43
+ serialized = encoder.encode(value)
44
+ if use_compression:
45
+ serialized = gzip.compress(serialized)
46
+
47
+ if expire > 0:
48
+ return await redis_client.setex(key, expire, serialized)
49
+ return await redis_client.set(key, serialized)
50
+ return False
51
+ except (RedisError, TypeError) as e:
52
+ raise CacheError(f"Cache set failed: {e!s}") from e
53
+
54
+
55
+ async def cache_delete(key: str) -> bool:
56
+ """Delete a key from Redis cache."""
57
+ try:
58
+ redis_client = get_redis_client()
59
+ if redis_client is None:
60
+ return False
61
+ return await redis_client.delete(key) > 0
62
+ except RedisError as e:
63
+ raise CacheError(f"Cache delete failed: {e!s}") from e
64
+
65
+
66
+ def sync_cache_get(key: str, decoder: type[Encoder] = PickledEncoder, use_compression: bool = False) -> Any | None:
67
+ """Retrieve a value from Redis cache by key."""
68
+ try:
69
+ client = get_sync_redis_client()
70
+ if client is None:
71
+ return None
72
+ cached = client.get(key)
73
+ if cached:
74
+ if use_compression:
75
+ decompressed = gzip.decompress(cached)
76
+ return decoder.decode(decompressed)
77
+ return decoder.decode(cached)
78
+ return None
79
+
80
+ except (RedisError, json.JSONDecodeError, ValueError) as e:
81
+ raise CacheError(f"Cache get failed: {str(e)}") from e
82
+
83
+
84
+ def sync_cache_set(
85
+ key: str,
86
+ value: Any,
87
+ expire: int = 60,
88
+ encoder: type[Encoder] = PickledEncoder,
89
+ use_compression: bool = False,
90
+ ) -> ResponseT | bool:
91
+ """Set a value in Redis cache with an optional expiration time."""
92
+ try:
93
+ # do not cache None values
94
+ if value is not None:
95
+ client = get_sync_redis_client()
96
+ if client is None:
97
+ return False
98
+ serialized = encoder.encode(value)
99
+ if use_compression:
100
+ serialized = gzip.compress(serialized)
101
+
102
+ if expire > 0:
103
+ return client.setex(key, expire, serialized)
104
+ return client.set(key, serialized)
105
+ return False
106
+ except (RedisError, TypeError) as e:
107
+ raise CacheError(f"Cache set failed: {str(e)}") from e
108
+
109
+
110
+ def sync_cache_delete(key: str) -> ResponseT:
111
+ """Delete a key from Redis cache."""
112
+ try:
113
+ client = get_sync_redis_client()
114
+ if client is None:
115
+ return 0
116
+ return client.delete(key)
117
+ except RedisError as e:
118
+ raise CacheError(f"Cache delete failed: {str(e)}") from e
119
+
120
+
121
+ def sync_lock(cache_key: str):
122
+ """Context manager to lock Redis operations."""
123
+ redis_client = get_sync_redis_client()
124
+ if redis_client is None:
125
+ return None
126
+ lock_key = f"lock:{cache_key}"
127
+ return redis_client.lock(lock_key, timeout=100)
128
+
129
+
130
+ def lock(cache_key: str):
131
+ """Context manager to lock Redis operations."""
132
+ redis_client = get_redis_client()
133
+ if redis_client is None:
134
+ return None
135
+ lock_key = f"lock:{cache_key}"
136
+ return redis_client.lock(lock_key, timeout=100)
137
+
138
+
139
+ def sync_cache_size(key: str) -> int:
140
+ """Get the number of keys in the Redis cache."""
141
+ try:
142
+ redis_client = get_sync_redis_client()
143
+ if redis_client is None:
144
+ return 0
145
+ return redis_client.memory_usage(key) or 0
146
+ except RedisError as e:
147
+ raise CacheError(f"Cache size retrieval failed: {e!s}") from e
148
+
149
+
150
+ async def cache_size(key: str) -> int:
151
+ """Get the number of keys in the Redis cache."""
152
+ try:
153
+ redis_client = get_redis_client()
154
+ if redis_client is None:
155
+ return 0
156
+ return await redis_client.memory_usage(key) or 0
157
+ except RedisError as e:
158
+ raise CacheError(f"Cache size retrieval failed: {e!s}") from e
@@ -0,0 +1,106 @@
1
+ import hashlib
2
+ import importlib
3
+ import json
4
+
5
+ from celery import Task
6
+ from celery.signals import task_failure, task_postrun, task_prerun
7
+
8
+ from ..ctx.ctx_pool import ctxpool
9
+ from ..dependencies.repository_manager import _close_sessions_sync
10
+ from ..redis.client import get_redis_client
11
+ from ..settings import get_core_settings
12
+ from ..util.debug_util import DebugUtil
13
+
14
+
15
+ class BaseTask(Task):
16
+ """A base task class that can be extended for custom behavior."""
17
+
18
+ @staticmethod
19
+ def generate_unique_task_id(task_name: str, args=None, kwargs=None):
20
+ """Generate a unique task ID based on method name and arguments."""
21
+ args = args or {}
22
+ kwargs = kwargs or {}
23
+ settings = get_core_settings()
24
+ # Use method name, arguments, and keyword arguments to generate a hash
25
+ task_data = {"method": task_name, "args": args, "kwargs": kwargs}
26
+ task_data_str = json.dumps(task_data, sort_keys=True) # Ensure consistent order of keys
27
+ return f"{settings.CACHE_KEY_PREFIX}{hashlib.sha256(task_data_str.encode()).hexdigest()}"
28
+
29
+ def _cache_task_id(self, task_key):
30
+ """Store the task ID in Redis to mark the task as already executed."""
31
+ redis_client = get_redis_client()
32
+ if redis_client is not None:
33
+ return redis_client.set(task_key, "exists", nx=True) # No expiration time set
34
+
35
+ return None
36
+
37
+ def apply_async(self, args=None, kwargs=None, *other_args, **other_kwargs):
38
+ """Override apply_async to generate a unique task ID before execution."""
39
+ DebugUtil.debug(f"Applying task {self.name} with args: {args}, kwargs: {kwargs}")
40
+ task_key = BaseTask.generate_unique_task_id(self.name, args, kwargs)
41
+
42
+ if not self._cache_task_id(task_key):
43
+ DebugUtil.debug(f"Task with key {task_key} already exists. Skipping execution.")
44
+ return {"status": f"Task with key {task_key} already exists. Skipping execution."}
45
+
46
+ DebugUtil.debug(f"Task with key {task_key} does not exist. Proceeding with execution.")
47
+
48
+ # Call the original apply_async method to proceed with task execution
49
+ try:
50
+ return super().apply_async(args, kwargs, *other_args, **other_kwargs)
51
+ except Exception:
52
+ redis_client = get_redis_client()
53
+ if redis_client is not None:
54
+ redis_client.delete(task_key)
55
+ raise
56
+
57
+ @staticmethod
58
+ def _clear_cache():
59
+ """Clear the task cache."""
60
+ # clear_repo_cache()
61
+ # clear_service_cache()
62
+ ctxpool.clear()
63
+
64
+ @task_prerun.connect
65
+ def task_prerun_handler(task_id, task, args, kwargs, **extra_kwargs):
66
+ """Handle task execution before running."""
67
+ DebugUtil.debug(f"Task {task.name} started with task ID: {task_id}")
68
+ BaseTask._clear_cache()
69
+
70
+ @task_postrun.connect
71
+ def task_postrun_handler(sender: "BaseTask | None" = None, task_id=None, args=None, kwargs=None, **other_kwargs):
72
+ """Handle task completion after running."""
73
+ if sender is not None:
74
+ DebugUtil.debug(f"Task {sender.name} completed with task ID: {task_id}")
75
+ if task_id is not None:
76
+ task_key = BaseTask.generate_unique_task_id(sender.name, args, kwargs)
77
+ redis_client = get_redis_client()
78
+ if redis_client is not None:
79
+ DebugUtil.debug(f"Deleting task key {task_key} from Redis.")
80
+ redis_client.delete(task_key)
81
+ DebugUtil.debug("Closing repository manager sessions opened during the task.")
82
+ _close_sessions_sync()
83
+ BaseTask._clear_cache()
84
+
85
+ @task_failure.connect
86
+ def task_failure_handler(sender: "BaseTask | None" = None, exception=None, args=None, kwargs=None, **other_kwargs):
87
+ """Handle task failure."""
88
+ if sender is None:
89
+ return
90
+
91
+ # === Fallback call ===
92
+ try:
93
+ failed_method_sufix = "__fallback"
94
+ task_name = sender.run.__name__
95
+ failed_func_name = f"{task_name}{failed_method_sufix}"
96
+ mod = importlib.import_module(sender.__module__)
97
+ failed_func = getattr(mod, failed_func_name, None)
98
+ if callable(failed_func):
99
+ failed_func(*args, **kwargs)
100
+ else:
101
+ DebugUtil.debug(f"Fallback method {failed_func_name} not defined")
102
+ except Exception as e:
103
+ DebugUtil.debug(f"Fallback handler error: {e}")
104
+ DebugUtil.debug("Closing repository manager sessions opened during the task.")
105
+ _close_sessions_sync()
106
+ BaseTask._clear_cache()
@@ -0,0 +1,52 @@
1
+ from typing import ClassVar
2
+
3
+ from celery import Celery
4
+ from pydantic_settings import BaseSettings
5
+
6
+ from ..settings import CoreSettings, get_core_settings, init_core_settings
7
+
8
+
9
+ def get_celery_instance(settings: BaseSettings, *kwargs) -> Celery:
10
+ """Get the Celery instance with the core settings."""
11
+ core_settings: CoreSettings = init_core_settings(settings=settings)
12
+
13
+ class Config:
14
+ """Celery configuration class."""
15
+
16
+ broker_transport_options: ClassVar = {"visibility_timeout": core_settings.VISIBILITY_TIMEOUT}
17
+
18
+ return Celery(
19
+ core_settings.CELERY_MAIN_NAME,
20
+ broker=core_settings.CELERY_BROKER_URI,
21
+ backend=core_settings.CELERY_BACKEND_URI,
22
+ result_expires=core_settings.CELERY_RESULT_EXPIRES,
23
+ broker_connection_retry_on_startup=False,
24
+ config_source=Config,
25
+ **kwargs,
26
+ )
27
+
28
+
29
+ def run_celery_worker(settings: BaseSettings, argv=list[str]) -> Celery:
30
+ """Run the Celery worker."""
31
+ client = run_celery_client(settings)
32
+ _autodiscover_tasks(client)
33
+ client.worker_main(argv)
34
+
35
+ return client
36
+
37
+
38
+ def run_celery_client(settings: BaseSettings) -> Celery:
39
+ """Run the Celery client."""
40
+ return get_celery_instance(settings)
41
+
42
+
43
+ def _autodiscover_tasks(celery_app: Celery, force: bool = False) -> None:
44
+ """Autodiscover tasks in the specified folders.
45
+
46
+ Args:
47
+ celery_app (Celery, optional): The Celery app instance. Defaults to the global client.
48
+ force (bool, optional): Whether to force the autodiscovery. Defaults to False.
49
+
50
+ Created as wrapper for the original autodiscover_tasks function to allow for testing.
51
+ """
52
+ celery_app.autodiscover_tasks(get_core_settings().CELERY_TASK_FOLDERS, force=force)
@@ -0,0 +1,47 @@
1
+ """A Typer app whose async commands get repository managers scoped to the command's lifetime.
2
+
3
+ FastAPI's `Depends()`-based session lifecycle (open on request start, close on request end) has no
4
+ equivalent outside a request. `command_scope` provides that equivalent for CLI commands: repository
5
+ managers are opened lazily, on first use, by `load_repository_manager` (which caches them for the
6
+ duration of the command, so repeated calls within one command reuse the same manager/session instead
7
+ of each opening a fresh one); `command_scope` closes whatever ended up being opened once the command
8
+ finishes - whether it succeeded or raised.
9
+ """
10
+
11
+ import asyncio
12
+ import functools
13
+ import inspect
14
+ from collections.abc import Awaitable, Callable
15
+
16
+ import typer
17
+
18
+ from ..dependencies.repository_manager import repository_manager_scope
19
+
20
+
21
+ def command_scope[**P, R](fn: Callable[P, Awaitable[R]]) -> Callable[P, R]:
22
+ """Wrap an async Typer command, closing whatever repository manager sessions it opened."""
23
+
24
+ @functools.wraps(fn)
25
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
26
+ async def _main() -> R:
27
+ async with repository_manager_scope():
28
+ return await fn(*args, **kwargs)
29
+
30
+ return asyncio.run(_main())
31
+
32
+ return wrapper
33
+
34
+
35
+ class ScopedTyper(typer.Typer):
36
+ """Typer app that applies `command_scope` to every async command automatically."""
37
+
38
+ def command(self, *args, **kwargs):
39
+ """Register a command, wrapping async commands with `command_scope`."""
40
+ register = super().command(*args, **kwargs)
41
+
42
+ def decorator(fn):
43
+ if inspect.iscoroutinefunction(fn):
44
+ fn = command_scope(fn)
45
+ return register(fn)
46
+
47
+ return decorator