FastSpine 1.1.0__tar.gz → 1.2.0__tar.gz

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 (112) hide show
  1. {fastspine-1.1.0 → fastspine-1.2.0}/PKG-INFO +17 -15
  2. {fastspine-1.1.0 → fastspine-1.2.0}/README.md +15 -13
  3. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/celery.md +17 -10
  4. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/configuration.md +2 -2
  5. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/database.md +4 -4
  6. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/example.md +3 -9
  7. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/__init__.py +6 -1
  8. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/celery/base_task.py +22 -6
  9. fastspine-1.2.0/fastspine/celery/broker.py +15 -0
  10. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/celery/engine.py +6 -1
  11. fastspine-1.2.0/fastspine/dependencies/profiler.py +58 -0
  12. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/dependencies/services.py +21 -1
  13. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/celery_settings.py +6 -0
  14. {fastspine-1.1.0 → fastspine-1.2.0}/pyproject.toml +2 -2
  15. fastspine-1.2.0/tests/test_base_task.py +159 -0
  16. fastspine-1.2.0/tests/test_broker.py +18 -0
  17. {fastspine-1.1.0 → fastspine-1.2.0}/uv.lock +1 -1
  18. fastspine-1.1.0/fastspine/dependencies/profiler.py +0 -37
  19. fastspine-1.1.0/tests/test_base_task.py +0 -70
  20. {fastspine-1.1.0 → fastspine-1.2.0}/.github/workflows/publish.yml +0 -0
  21. {fastspine-1.1.0 → fastspine-1.2.0}/.gitignore +0 -0
  22. {fastspine-1.1.0 → fastspine-1.2.0}/.pre-commit-config.yaml +0 -0
  23. {fastspine-1.1.0 → fastspine-1.2.0}/.ruff.toml +0 -0
  24. {fastspine-1.1.0 → fastspine-1.2.0}/.vscode/extensions.json +0 -0
  25. {fastspine-1.1.0 → fastspine-1.2.0}/.vscode/launch.json +0 -0
  26. {fastspine-1.1.0 → fastspine-1.2.0}/.vscode/settings.json +0 -0
  27. {fastspine-1.1.0 → fastspine-1.2.0}/LICENSE +0 -0
  28. {fastspine-1.1.0 → fastspine-1.2.0}/Makefile +0 -0
  29. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/caching.md +0 -0
  30. {fastspine-1.1.0 → fastspine-1.2.0}/_docs/cli.md +0 -0
  31. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/abstract/owner_base.py +0 -0
  32. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/alembic/__init__.py +0 -0
  33. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/alembic/alembic.py +0 -0
  34. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/alembic/config.py +0 -0
  35. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/boostrap.py +0 -0
  36. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/cache_decorater.py +0 -0
  37. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/cache_encoder.py +0 -0
  38. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/cache_exception.py +0 -0
  39. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/cache_model.py +0 -0
  40. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/cache_service.py +0 -0
  41. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/key_builder.py +0 -0
  42. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cache/redis_cache.py +0 -0
  43. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/cli/scoped_typer.py +0 -0
  44. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/ctx/ctx_pool.py +0 -0
  45. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/database/engine.py +0 -0
  46. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/decorators/contextualize_decorator.py +0 -0
  47. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/decorators/retry_decorator.py +0 -0
  48. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/decorators/upsert_decorator.py +0 -0
  49. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/dependencies/database.py +0 -0
  50. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/dependencies/repository_manager.py +0 -0
  51. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/access_exception.py +0 -0
  52. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/action_not_allowed_exception.py +0 -0
  53. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/base_app_exception.py +0 -0
  54. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/exception_handler.py +0 -0
  55. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/not_found_exception.py +0 -0
  56. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/security_exception.py +0 -0
  57. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/exception/soft_delete_exception.py +0 -0
  58. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/lib/__init__.py +0 -0
  59. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/lib/contextualize.py +0 -0
  60. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/lib/profiler.py +0 -0
  61. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/mailer/mailer_service.py +0 -0
  62. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/middleware/request_middleware.py +0 -0
  63. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/middleware/session_middleware.py +0 -0
  64. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/mixins/__init__.py +0 -0
  65. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/mixins/representable.py +0 -0
  66. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/mixins/soft_delete.py +0 -0
  67. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/mixins/timestamps.py +0 -0
  68. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/models/base.py +0 -0
  69. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/redis/client.py +0 -0
  70. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/repositories/abstract_repository.py +0 -0
  71. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/repositories/base_repository.py +0 -0
  72. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/repositories/external_base_repository.py +0 -0
  73. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/repositories/repository_manager.py +0 -0
  74. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/schemas/pagination_model.py +0 -0
  75. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/services/api_service.py +0 -0
  76. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/services/base_service.py +0 -0
  77. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/__init__.py +0 -0
  78. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/app_settings.py +0 -0
  79. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/cache_settings.py +0 -0
  80. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/mailer_settings.py +0 -0
  81. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/settings/profiler_settings.py +0 -0
  82. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/types/__init__.py +0 -0
  83. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/types/types.py +0 -0
  84. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/class_util.py +0 -0
  85. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/conversion.py +0 -0
  86. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/dataframe_util.py +0 -0
  87. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/dates.py +0 -0
  88. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/debug_util.py +0 -0
  89. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/emails.py +0 -0
  90. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/files.py +0 -0
  91. {fastspine-1.1.0 → fastspine-1.2.0}/fastspine/util/math.py +0 -0
  92. {fastspine-1.1.0 → fastspine-1.2.0}/tests/__init__.py +0 -0
  93. {fastspine-1.1.0 → fastspine-1.2.0}/tests/conftest.py +0 -0
  94. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_base_repository.py +0 -0
  95. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_batch_decorater.py +0 -0
  96. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_cache_decorater.py +0 -0
  97. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_cache_service.py +0 -0
  98. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_class_util.py +0 -0
  99. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_contextualize_decorator.py +0 -0
  100. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_ctxpool.py +0 -0
  101. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_database_dependencies.py +0 -0
  102. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_emails.py +0 -0
  103. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_files.py +0 -0
  104. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_key_builder.py +0 -0
  105. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_math.py +0 -0
  106. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_redis_cache.py +0 -0
  107. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_repository_manager.py +0 -0
  108. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_repository_manager_dependencies.py +0 -0
  109. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_scoped_typer.py +0 -0
  110. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_services_dependencies.py +0 -0
  111. {fastspine-1.1.0 → fastspine-1.2.0}/tests/test_session_middleware.py +0 -0
  112. {fastspine-1.1.0 → fastspine-1.2.0}/uv.toml +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: FastSpine
3
- Version: 1.1.0
4
- Summary: FastAPI framework with a service-repository architecture, dependency injection, Redis caching and SQLAlchemy, Celery and Alembic integration.
3
+ Version: 1.2.0
4
+ Summary: Stop copy-pasting FastAPI + SQLAlchemy boilerplate - a repository/service layer, Redis caching, and Celery tasks that work the same way in your API, CLI, and workers.
5
5
  Author-email: Aleksandar Pavlovic <sleker@gmail.com>
6
6
  License-Expression: MIT
7
7
  License-File: LICENSE
@@ -50,9 +50,10 @@ Description-Content-Type: text/markdown
50
50
 
51
51
  # FastSpine
52
52
 
53
- FastSpine is a Python framework built on top of FastAPI that provides a service-repository
54
- architecture, dependency injection, caching, and supporting infrastructure (database sessions, Celery
55
- tasks, Alembic migrations, Redis, mailer) for building backend applications.
53
+ Stop copy-pasting the same FastAPI + SQLAlchemy boilerplate into every project. FastSpine gives
54
+ you a repository/service layer, Redis caching, and Celery tasks that are wired up the same way
55
+ everywhere - in your API, your CLI, and your background workers - so you write the business logic
56
+ once and reuse it across all three.
56
57
 
57
58
  ## Requirements
58
59
 
@@ -108,7 +109,9 @@ given integration does (e.g. `fastspine.celery.base_task` needs the `celery` ext
108
109
  FastSpine provides two parallel sets of dependency helpers for every layer:
109
110
 
110
111
  - `*_dep` / `get_*` factories (e.g. `service_dep`, `get_repository`, `get_repository_manager`) —
111
- build FastAPI `Depends()`-compatible callables for use inside request handlers.
112
+ build FastAPI `Depends()`-compatible callables for use inside request handlers. For services,
113
+ `Service[YourService]` is shorthand for `Annotated[YourService, Depends(service_dep(YourService))]`
114
+ — use it directly as a route parameter's type, no `Annotated`/`Depends` import needed.
112
115
  - `load_*` helpers (e.g. `load_service`, `load_repository`, `load_repository_manager`) — resolve the
113
116
  same dependency graph eagerly, for use outside of FastAPI's request lifecycle (CLI commands, Celery
114
117
  tasks, scripts).
@@ -310,22 +313,21 @@ class OrderSyncService(BaseService):
310
313
 
311
314
  ### 6. Use the service
312
315
 
313
- Inside a FastAPI route, inject it with `service_dep`:
316
+ Inside a FastAPI route, inject it with `Service[...]`:
314
317
 
315
318
  ```python
316
- from typing import Annotated
317
-
318
- from fastapi import Depends
319
-
320
- from fastspine import service_dep
321
-
322
- OrderSyncServiceDep = Annotated[OrderSyncService, Depends(service_dep(OrderSyncService))]
319
+ from fastspine import Service
323
320
 
324
321
  @app.post("/orders/sync")
325
- def sync_orders(service: OrderSyncServiceDep):
322
+ def sync_orders(service: Service[OrderSyncService]):
326
323
  service.sync()
327
324
  ```
328
325
 
326
+ `Service[OrderSyncService]` is shorthand for `Annotated[OrderSyncService,
327
+ Depends(service_dep(OrderSyncService))]` - use that longer form directly (`from fastspine import
328
+ service_dep`) if you want to build the `Annotated` alias yourself, e.g. to reuse it across several
329
+ routes under your own name.
330
+
329
331
  Outside of FastAPI's request lifecycle (CLI commands, Celery tasks), use `load_service` instead,
330
332
  which resolves the same dependency graph eagerly:
331
333
 
@@ -1,8 +1,9 @@
1
1
  # FastSpine
2
2
 
3
- FastSpine is a Python framework built on top of FastAPI that provides a service-repository
4
- architecture, dependency injection, caching, and supporting infrastructure (database sessions, Celery
5
- tasks, Alembic migrations, Redis, mailer) for building backend applications.
3
+ Stop copy-pasting the same FastAPI + SQLAlchemy boilerplate into every project. FastSpine gives
4
+ you a repository/service layer, Redis caching, and Celery tasks that are wired up the same way
5
+ everywhere - in your API, your CLI, and your background workers - so you write the business logic
6
+ once and reuse it across all three.
6
7
 
7
8
  ## Requirements
8
9
 
@@ -58,7 +59,9 @@ given integration does (e.g. `fastspine.celery.base_task` needs the `celery` ext
58
59
  FastSpine provides two parallel sets of dependency helpers for every layer:
59
60
 
60
61
  - `*_dep` / `get_*` factories (e.g. `service_dep`, `get_repository`, `get_repository_manager`) —
61
- build FastAPI `Depends()`-compatible callables for use inside request handlers.
62
+ build FastAPI `Depends()`-compatible callables for use inside request handlers. For services,
63
+ `Service[YourService]` is shorthand for `Annotated[YourService, Depends(service_dep(YourService))]`
64
+ — use it directly as a route parameter's type, no `Annotated`/`Depends` import needed.
62
65
  - `load_*` helpers (e.g. `load_service`, `load_repository`, `load_repository_manager`) — resolve the
63
66
  same dependency graph eagerly, for use outside of FastAPI's request lifecycle (CLI commands, Celery
64
67
  tasks, scripts).
@@ -260,22 +263,21 @@ class OrderSyncService(BaseService):
260
263
 
261
264
  ### 6. Use the service
262
265
 
263
- Inside a FastAPI route, inject it with `service_dep`:
266
+ Inside a FastAPI route, inject it with `Service[...]`:
264
267
 
265
268
  ```python
266
- from typing import Annotated
267
-
268
- from fastapi import Depends
269
-
270
- from fastspine import service_dep
271
-
272
- OrderSyncServiceDep = Annotated[OrderSyncService, Depends(service_dep(OrderSyncService))]
269
+ from fastspine import Service
273
270
 
274
271
  @app.post("/orders/sync")
275
- def sync_orders(service: OrderSyncServiceDep):
272
+ def sync_orders(service: Service[OrderSyncService]):
276
273
  service.sync()
277
274
  ```
278
275
 
276
+ `Service[OrderSyncService]` is shorthand for `Annotated[OrderSyncService,
277
+ Depends(service_dep(OrderSyncService))]` - use that longer form directly (`from fastspine import
278
+ service_dep`) if you want to build the `Annotated` alias yourself, e.g. to reuse it across several
279
+ routes under your own name.
280
+
279
281
  Outside of FastAPI's request lifecycle (CLI commands, Celery tasks), use `load_service` instead,
280
282
  which resolves the same dependency graph eagerly:
281
283
 
@@ -99,9 +99,20 @@ does not enqueue it twice. The key is cleared once the task finishes (success or
99
99
  off the result needs to handle that case (e.g. check `isinstance(result, dict)`) if dedup is
100
100
  enabled for that task.
101
101
 
102
- This needs a working Redis connection (same one caching uses - see [Caching](caching.md)); if
103
- `CACHE_ENABLED` is `False` or there's no Redis configured, `get_redis_client()` returns `None` and
104
- `_cache_task_id` is a no-op - dedup is simply skipped, every call goes through.
102
+ **This dedup logic only runs at all when `CELERY_BROKER_URI` is a Redis broker** (`redis://`/
103
+ `rediss://`, checked via `fastspine.celery.broker.is_redis_broker`). Redis has no built-in message
104
+ deduplication, which is why `BaseTask` implements it at the application level. Other brokers
105
+ (RabbitMQ, ...) typically have their own deduplication module/plugin at the transport level - for
106
+ those, `apply_async` skips this check entirely and forwards straight to Celery's own
107
+ `apply_async`, rather than requiring a working cache-Redis connection for something the broker
108
+ already handles. (This is also why `broker_transport_options`'s `visibility_timeout` - a
109
+ Redis/SQS-only transport option - is only set by `get_celery_instance` for a Redis broker too.)
110
+
111
+ When the broker *is* Redis, dedup storage itself uses the same cache-layer Redis connection as
112
+ [Caching](caching.md) (`CacheSettings`/`REDIS_HOST`/etc - not `CELERY_BROKER_URI` directly, despite
113
+ both being Redis in this case). If `CACHE_ENABLED` is `False` or that connection isn't reachable,
114
+ `get_redis_client()` returns `None` and `_cache_task_id` is a no-op - dedup is skipped, every call
115
+ goes through.
105
116
 
106
117
  ### Session cleanup on completion/failure
107
118
 
@@ -171,21 +182,17 @@ import, not a blanket rule.
171
182
 
172
183
  ```python
173
184
  # myapp/api/orders.py
174
- from typing import Annotated
185
+ from fastapi import APIRouter
175
186
 
176
- from fastapi import APIRouter, Depends
177
-
178
- from fastspine import service_dep
187
+ from fastspine import Service
179
188
 
180
189
  from myapp.services.sync_service import OrderSyncService
181
190
 
182
191
  router = APIRouter()
183
192
 
184
- OrderSyncServiceDep = Annotated[OrderSyncService, Depends(service_dep(OrderSyncService))]
185
-
186
193
 
187
194
  @router.post("/orders/sync")
188
- def trigger_sync(service: OrderSyncServiceDep):
195
+ def trigger_sync(service: Service[OrderSyncService]):
189
196
  service.trigger_sync()
190
197
  return {"status": "queued"}
191
198
  ```
@@ -88,13 +88,13 @@ your choice. If you only run one Redis instance for both, set `REDIS_HOST`/`REDI
88
88
 
89
89
  | Field | Type | Default | Description |
90
90
  |---|---|---|---|
91
- | `CELERY_BROKER_URI` | `str` | `""` | Celery broker connection URL. Only used by Celery (`fastspine.celery.engine`) - the cache layer connects via `CacheSettings.get_redis_url()`/`REDIS_*` (above) instead, not this field. Must be a `redis://`, `rediss://`, or `unix://` URL (empty string fails to parse). |
91
+ | `CELERY_BROKER_URI` | `str` | `""` | Celery broker connection URL. Only used by Celery (`fastspine.celery.engine`) - the cache layer connects via `CacheSettings.get_redis_url()`/`REDIS_*` (above) instead, not this field. Any broker Celery/Kombu supports works (`redis://`, `rediss://`, `amqp://` for RabbitMQ, ...); whether it's a Redis URL specifically also gates `VISIBILITY_TIMEOUT` and `BaseTask`'s dedup logic below. |
92
92
  | `CELERY_BACKEND_URI` | `str` | `"redis://localhost:6385/0"` | Celery result backend URL. |
93
93
  | `CELERY_RESULT_EXPIRES` | `int` | `604800` (7 days, in seconds) | How long Celery keeps task results around. |
94
94
  | `CELERY_MAIN_NAME` | `str` | `"_redis_main"` | Name of the main Celery app instance. |
95
95
  | `CELERY_TASK_FOLDERS` | `list[str]` | `[]` | Module paths Celery should autodiscover tasks from. |
96
96
  | `WORKERS_ON` | `bool` | `True` | Whether Celery workers are enabled for this deployment. |
97
- | `VISIBILITY_TIMEOUT` | `int` | `3600` | Default visibility timeout (seconds) for in-flight tasks. |
97
+ | `VISIBILITY_TIMEOUT` | `int` | `3600` | Default visibility timeout (seconds) for in-flight tasks - only applied when `CELERY_BROKER_URI` is a Redis broker (see [Celery](celery.md#deduplication)); ignored otherwise, since other brokers handle this at the transport level. |
98
98
 
99
99
  ## Profiler settings
100
100
 
@@ -179,7 +179,7 @@ A `RepositoryManager` instance is what actually holds a session. Call `.get(Repo
179
179
  repository bound to that same session, created lazily and cached for reuse:
180
180
 
181
181
  ```python
182
- primary = load_repository_manager(PrimaryRepositoryManager) # or injected via Depends/service_dep
182
+ primary = load_repository_manager(PrimaryRepositoryManager) # or injected via Service[...]/Depends
183
183
  order_repo = primary.get(OrderRepository) # db/profiler injected automatically
184
184
  ```
185
185
 
@@ -207,9 +207,9 @@ class OrderSyncService(BaseService):
207
207
  self.reporting.get(ReportingRepository).save(orders)
208
208
  ```
209
209
 
210
- Inject it into a FastAPI route with `Depends(service_dep(OrderSyncService))`, or build it eagerly
211
- outside a request (CLI, Celery) with `load_service(OrderSyncService)` - both resolve the same
212
- constructor dependencies, just at different times. See the
210
+ Inject it into a FastAPI route with `Service[OrderSyncService]` (`from fastspine import Service`),
211
+ or build it eagerly outside a request (CLI, Celery) with `load_service(OrderSyncService)` - both
212
+ resolve the same constructor dependencies, just at different times. See the
213
213
  [README](../README.md#6-use-the-service) for the full DI picture, and [CLI](cli.md) /
214
214
  `fastspine.celery.base_task.BaseTask` for how sessions opened this way get closed outside a
215
215
  FastAPI request.
@@ -180,28 +180,22 @@ never cached, and doesn't need to be - it writes, it doesn't read.
180
180
  # myapp/main.py
181
181
  import myapp.bootstrap # noqa: F401 (must run before any route uses OrderService)
182
182
 
183
- from typing import Annotated
184
-
185
- from fastapi import Depends
186
-
187
- from fastspine import FastSpineApp, service_dep
183
+ from fastspine import FastSpineApp, Service
188
184
 
189
185
  from myapp.settings import settings
190
186
  from myapp.services.order_service import OrderService
191
187
 
192
188
  app = FastSpineApp(settings=settings, title=settings.PROJECT_NAME)
193
189
 
194
- OrderServiceDep = Annotated[OrderService, Depends(service_dep(OrderService))]
195
-
196
190
 
197
191
  @app.post("/orders")
198
- async def create_order(customer_name: str, total_cents: int, service: OrderServiceDep):
192
+ async def create_order(customer_name: str, total_cents: int, service: Service[OrderService]):
199
193
  order_id = await service.create_order(customer_name, total_cents)
200
194
  return {"id": order_id}
201
195
 
202
196
 
203
197
  @app.get("/orders/{order_id}")
204
- async def get_order(order_id: int, service: OrderServiceDep):
198
+ async def get_order(order_id: int, service: Service[OrderService]):
205
199
  return await service.get_order(order_id)
206
200
  ```
207
201
 
@@ -1,8 +1,9 @@
1
1
  from .abstract.owner_base import OwnerBase
2
2
  from .boostrap import FastSpineApp, run_fast_core_app
3
- from .dependencies.profiler import load_profiler
3
+ from .dependencies.profiler import load_profiler, set_profiler_factory
4
4
  from .dependencies.repository_manager import get_repository_manager, load_repository_manager
5
5
  from .dependencies.services import (
6
+ Service,
6
7
  load_service,
7
8
  load_services,
8
9
  service_dep,
@@ -12,6 +13,7 @@ from .exception.action_not_allowed_exception import ActionNotAllowedError
12
13
  from .exception.base_app_exception import BaseAppError, BaseError
13
14
  from .exception.not_found_exception import NotFoundError
14
15
  from .exception.security_exception import SecurityAlertError
16
+ from .lib.profiler import Profiler
15
17
  from .repositories.base_repository import BaseRepository
16
18
  from .repositories.external_base_repository import ExternalBaseRepository
17
19
  from .repositories.repository_manager import RepositoryManager
@@ -27,11 +29,14 @@ __all__ = [
27
29
  "load_service",
28
30
  "load_services",
29
31
  "service_dep",
32
+ "Service",
30
33
  "RepositoryManager",
31
34
  "BaseService",
32
35
  "get_repository_manager",
33
36
  "load_repository_manager",
34
37
  "load_profiler",
38
+ "set_profiler_factory",
39
+ "Profiler",
35
40
  "BaseAppError",
36
41
  "BaseError",
37
42
  "AccessDeniedError",
@@ -7,14 +7,27 @@ from celery.signals import task_failure, task_postrun, task_prerun
7
7
 
8
8
  from ..ctx.ctx_pool import ctxpool
9
9
  from ..dependencies.repository_manager import _close_sessions_sync
10
- from ..redis.client import get_redis_client
10
+ from ..redis.client import get_sync_redis_client as get_redis_client
11
11
  from ..settings import get_core_settings
12
12
  from ..util.debug_util import DebugUtil
13
+ from .broker import is_redis_broker
13
14
 
14
15
 
15
16
  class BaseTask(Task):
16
17
  """A base task class that can be extended for custom behavior."""
17
18
 
19
+ @staticmethod
20
+ def _dedup_enabled() -> bool:
21
+ """Whether Redis-based task deduplication should run.
22
+
23
+ Only meaningful when the broker is Redis - Redis itself has no built-in message
24
+ deduplication, which is why this exists. Other brokers (RabbitMQ, ...) handle
25
+ deduplication at the transport level via their own module/plugin, so this app-level
26
+ check is skipped there rather than requiring a working cache-Redis connection for
27
+ something that broker already does.
28
+ """
29
+ return is_redis_broker(get_core_settings().CELERY_BROKER_URI)
30
+
18
31
  @staticmethod
19
32
  def generate_unique_task_id(task_name: str, args=None, kwargs=None):
20
33
  """Generate a unique task ID based on method name and arguments."""
@@ -36,6 +49,9 @@ class BaseTask(Task):
36
49
 
37
50
  def apply_async(self, args=None, kwargs=None, *other_args, **other_kwargs):
38
51
  """Override apply_async to generate a unique task ID before execution."""
52
+ if not self._dedup_enabled():
53
+ return super().apply_async(args, kwargs, *other_args, **other_kwargs)
54
+
39
55
  DebugUtil.debug(f"Applying task {self.name} with args: {args}, kwargs: {kwargs}")
40
56
  task_key = BaseTask.generate_unique_task_id(self.name, args, kwargs)
41
57
 
@@ -72,12 +88,12 @@ class BaseTask(Task):
72
88
  """Handle task completion after running."""
73
89
  if sender is not None:
74
90
  DebugUtil.debug(f"Task {sender.name} completed with task ID: {task_id}")
75
- if task_id is not None:
91
+ if task_id is not None and BaseTask._dedup_enabled():
76
92
  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)
93
+ redis_client = get_redis_client()
94
+ if redis_client is not None:
95
+ DebugUtil.debug(f"Deleting task key {task_key} from Redis.")
96
+ redis_client.delete(task_key)
81
97
  DebugUtil.debug("Closing repository manager sessions opened during the task.")
82
98
  _close_sessions_sync()
83
99
  BaseTask._clear_cache()
@@ -0,0 +1,15 @@
1
+ from urllib.parse import urlparse
2
+
3
+ _REDIS_BROKER_SCHEMES = {"redis", "rediss"}
4
+
5
+
6
+ def is_redis_broker(broker_uri: str) -> bool:
7
+ """Check whether a Celery broker URI points at Redis.
8
+
9
+ Shared between `engine.py` (whether to pass Redis-specific `broker_transport_options`) and
10
+ `base_task.py` (whether `BaseTask`'s own Redis-based deduplication should run at all - other
11
+ brokers like RabbitMQ have their own message-deduplication module/plugin handling this at the
12
+ transport level, so there's nothing for this app-level mechanism to add there, and no reason
13
+ to require a working cache-Redis connection for it).
14
+ """
15
+ return urlparse(broker_uri).scheme in _REDIS_BROKER_SCHEMES
@@ -4,6 +4,7 @@ from celery import Celery
4
4
  from pydantic_settings import BaseSettings
5
5
 
6
6
  from ..settings import CoreSettings, get_core_settings, init_core_settings
7
+ from .broker import is_redis_broker
7
8
 
8
9
 
9
10
  def get_celery_instance(settings: BaseSettings, *kwargs) -> Celery:
@@ -13,7 +14,11 @@ def get_celery_instance(settings: BaseSettings, *kwargs) -> Celery:
13
14
  class Config:
14
15
  """Celery configuration class."""
15
16
 
16
- broker_transport_options: ClassVar = {"visibility_timeout": core_settings.VISIBILITY_TIMEOUT}
17
+ broker_transport_options: ClassVar = (
18
+ {"visibility_timeout": core_settings.VISIBILITY_TIMEOUT}
19
+ if is_redis_broker(core_settings.CELERY_BROKER_URI)
20
+ else {}
21
+ )
17
22
 
18
23
  return Celery(
19
24
  core_settings.CELERY_MAIN_NAME,
@@ -0,0 +1,58 @@
1
+ from typing import Callable
2
+
3
+ from fastspine.lib.profiler import Profiler
4
+
5
+ from ..ctx.ctx_pool import ctxpool
6
+ from ..settings import get_core_settings
7
+
8
+ profiler_ctx = ctxpool.new("profiler_ctx", default=None)
9
+
10
+ _profiler_factory: Callable[[], Profiler] | None = None
11
+
12
+
13
+ def set_profiler_factory(factory: Callable[[], Profiler] | None) -> None:
14
+ """Register a factory for building this process's `Profiler` instance.
15
+
16
+ Call this once at process startup - same process-per-entrypoint discipline as
17
+ `register_sessions`/`init_core_settings` (a FastAPI app, a CLI command, a Celery worker each
18
+ need their own call, since each is a separate process) - before anything calls
19
+ `load_profiler()`/`fetch_profiler()`. The factory takes no arguments; read
20
+ `get_core_settings()` yourself inside it if your custom `Profiler` needs settings-driven
21
+ behavior. Pass `None` to restore the default (a plain `Profiler` built from
22
+ `PROFILER_NAME`/`PROFILER_TRACK_MEMORY`/`PROFILER_ENABLED`/`PROFILER_LOG_LEVEL`).
23
+
24
+ The factory must return a `Profiler` (subclass) instance - every place a `Profiler` gets
25
+ injected (`BaseService.profiler`, `BaseRepository.profiler`, the cache decorators) is typed
26
+ as plain `Profiler`, not whatever custom subclass you use, so override/extend its methods
27
+ rather than changing its public shape.
28
+ """
29
+ global _profiler_factory
30
+ _profiler_factory = factory
31
+
32
+
33
+ def _build_profiler() -> Profiler:
34
+ """Build a new `Profiler` instance, via the registered factory if one was set."""
35
+ if _profiler_factory is not None:
36
+ return _profiler_factory()
37
+
38
+ settings = get_core_settings()
39
+ return Profiler(
40
+ name=settings.PROFILER_NAME,
41
+ track_memory=settings.PROFILER_TRACK_MEMORY,
42
+ enabled=settings.PROFILER_ENABLED,
43
+ level=settings.PROFILER_LOG_LEVEL,
44
+ )
45
+
46
+
47
+ def load_profiler() -> Profiler:
48
+ """Return a Profiler instance outside FastApi lifecycle ie celery task."""
49
+ profiler = ctxpool.get("profiler_ctx", default=None)
50
+ if profiler is None:
51
+ profiler = _build_profiler()
52
+ profiler_ctx.set(profiler)
53
+ return profiler
54
+
55
+
56
+ def fetch_profiler():
57
+ """Fetch the Profiler instance inside Depends."""
58
+ return load_profiler()
@@ -1,7 +1,9 @@
1
1
  import inspect
2
- from typing import Any
2
+ from functools import cache
3
+ from typing import TYPE_CHECKING, Annotated, Any, TypeVar
3
4
 
4
5
  from fastapi import Depends
6
+ from fastapi.params import Depends as DependsParam
5
7
 
6
8
  from ..ctx.ctx_pool import ctxpool
7
9
  from ..dependencies.repository_manager import get_repository_manager, load_repository_manager
@@ -9,11 +11,29 @@ from ..repositories.repository_manager import RepositoryManager
9
11
  from ..services.base_service import BaseService
10
12
  from ..util.class_util import get_class_annotations
11
13
 
14
+ T = TypeVar("T")
12
15
  supported_params_type = [BaseService, RepositoryManager]
13
16
  # Track dependency resolution to detect circular dependencies
14
17
  _dependency_resolution_stack: set[type] = set()
15
18
 
16
19
 
20
+ @cache
21
+ def _dependency_for(cls: type) -> DependsParam:
22
+ return Depends(service_dep(cls))
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ Service = Annotated[T, "fastspine.service"]
27
+ else:
28
+
29
+ class Service:
30
+ """Type hint for service dependencies in FastAPI endpoints."""
31
+
32
+ def __class_getitem__(cls, item: type) -> object:
33
+ """Return a FastAPI dependency for the given service class."""
34
+ return Annotated[item, _dependency_for(item)]
35
+
36
+
17
37
  def clear_cache():
18
38
  """Clear service cache."""
19
39
  ctxpool.clear_one("_service_cache_var")
@@ -8,3 +8,9 @@ class CelerySettings:
8
8
  CELERY_TASK_FOLDERS: list[str] = []
9
9
  WORKERS_ON: bool = True # Whether workers are enabled
10
10
  VISIBILITY_TIMEOUT: int = 3600 # Default visibility timeout for tasks in seconds
11
+ CELERY_DEDUPLICATION_ENABLED: bool = True # Whether task deduplication is enabled
12
+
13
+ @property
14
+ def celery_deduplication_enabled(self) -> bool:
15
+ """Check if task deduplication is enabled."""
16
+ return self.CELERY_DEDUPLICATION_ENABLED
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "FastSpine"
3
- version = "1.1.0"
4
- description = "FastAPI framework with a service-repository architecture, dependency injection, Redis caching and SQLAlchemy, Celery and Alembic integration."
3
+ version = "1.2.0"
4
+ description = "Stop copy-pasting FastAPI + SQLAlchemy boilerplate - a repository/service layer, Redis caching, and Celery tasks that work the same way in your API, CLI, and workers."
5
5
  authors = [
6
6
  {name = "Aleksandar Pavlovic", email = "sleker@gmail.com"}
7
7
  ]
@@ -0,0 +1,159 @@
1
+ from types import SimpleNamespace
2
+ from unittest.mock import AsyncMock, Mock
3
+
4
+ from celery import Task
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+ from sqlalchemy.orm import Session
7
+
8
+ import fastspine.celery.base_task as base_task_module
9
+ from fastspine.celery.base_task import BaseTask
10
+ from fastspine.dependencies.repository_manager import _repo_manager_cache_var
11
+
12
+
13
+ class _FakeCeleryTask:
14
+ """Minimal stand-in for a Celery task instance, enough for the signal handlers under test."""
15
+
16
+ __module__ = __name__
17
+ name = "fake_task"
18
+
19
+ def run(self):
20
+ pass
21
+
22
+
23
+ class _DummyTask(BaseTask):
24
+ """A real `BaseTask` subclass, not bound to a Celery app - enough to exercise `apply_async`."""
25
+
26
+ name = "dummy_task"
27
+
28
+
29
+ def test_dedup_enabled_true_for_redis_broker(monkeypatch):
30
+ """Redis has no built-in message dedup, so BaseTask's own check applies there."""
31
+ monkeypatch.setattr(
32
+ base_task_module, "get_core_settings", lambda: SimpleNamespace(CELERY_BROKER_URI="redis://localhost:6379/0")
33
+ )
34
+ assert BaseTask._dedup_enabled() is True
35
+
36
+
37
+ def test_dedup_enabled_false_for_non_redis_broker(monkeypatch):
38
+ """RabbitMQ (and other non-Redis brokers) handle message dedup at the transport level."""
39
+ monkeypatch.setattr(
40
+ base_task_module, "get_core_settings", lambda: SimpleNamespace(CELERY_BROKER_URI="amqp://guest@localhost//")
41
+ )
42
+ assert BaseTask._dedup_enabled() is False
43
+
44
+
45
+ def test_apply_async_skips_dedup_entirely_for_non_redis_broker(monkeypatch):
46
+ """With a non-Redis broker, apply_async forwards straight through - no Redis touched at all."""
47
+ monkeypatch.setattr(
48
+ base_task_module, "get_core_settings", lambda: SimpleNamespace(CELERY_BROKER_URI="amqp://guest@localhost//")
49
+ )
50
+ redis_client = Mock()
51
+ monkeypatch.setattr(base_task_module, "get_redis_client", lambda: redis_client)
52
+ monkeypatch.setattr(Task, "apply_async", lambda self, args=None, kwargs=None, *a, **kw: "forwarded")
53
+
54
+ result = _DummyTask().apply_async(args=(1,), kwargs={"x": 1})
55
+
56
+ assert result == "forwarded"
57
+ redis_client.set.assert_not_called()
58
+
59
+
60
+ def test_apply_async_dedups_when_broker_is_redis(monkeypatch):
61
+ """With a Redis broker, a duplicate call (same args/kwargs) is skipped rather than re-sent."""
62
+ monkeypatch.setattr(
63
+ base_task_module,
64
+ "get_core_settings",
65
+ lambda: SimpleNamespace(CELERY_BROKER_URI="redis://localhost:6379/0", CACHE_KEY_PREFIX=""),
66
+ )
67
+ redis_client = Mock()
68
+ monkeypatch.setattr(base_task_module, "get_redis_client", lambda: redis_client)
69
+ monkeypatch.setattr(Task, "apply_async", lambda self, args=None, kwargs=None, *a, **kw: "forwarded")
70
+
71
+ redis_client.set.return_value = True # lock acquired - not a duplicate
72
+ first = _DummyTask().apply_async(args=(1,), kwargs={"x": 1})
73
+ assert first == "forwarded"
74
+
75
+ redis_client.set.return_value = False # key already exists - duplicate
76
+ second = _DummyTask().apply_async(args=(1,), kwargs={"x": 1})
77
+ assert isinstance(second, dict)
78
+ assert "already exists" in second["status"]
79
+
80
+
81
+ def test_task_prerun_handler_clears_stale_cache(sync_repo_manager_class):
82
+ """A sync worker reuses its process/thread across tasks, so prerun must wipe leftover state."""
83
+ manager = sync_repo_manager_class(db=Mock(spec=Session))
84
+ _repo_manager_cache_var.set({sync_repo_manager_class: manager})
85
+
86
+ BaseTask.task_prerun_handler(task_id="t-1", task=_FakeCeleryTask(), args=(), kwargs={})
87
+
88
+ assert _repo_manager_cache_var.get() is None
89
+
90
+
91
+ def test_task_postrun_handler_closes_sessions_and_clears_cache(sync_repo_manager_class):
92
+ """On successful completion, the task's repository manager session gets closed."""
93
+ manager = sync_repo_manager_class(db=Mock(spec=Session))
94
+ _repo_manager_cache_var.set({sync_repo_manager_class: manager})
95
+
96
+ BaseTask.task_postrun_handler(sender=None, task_id=None, args=None, kwargs=None)
97
+
98
+ manager.db.close.assert_called_once()
99
+ assert _repo_manager_cache_var.get() is None
100
+
101
+
102
+ def test_task_failure_handler_closes_sessions_and_clears_cache(sync_repo_manager_class):
103
+ """Regression test: the failure path used to skip session cleanup entirely, leaking the connection."""
104
+ manager = sync_repo_manager_class(db=Mock(spec=Session))
105
+ _repo_manager_cache_var.set({sync_repo_manager_class: manager})
106
+
107
+ BaseTask.task_failure_handler(sender=_FakeCeleryTask(), exception=Exception("boom"), args=(), kwargs={})
108
+
109
+ manager.db.close.assert_called_once()
110
+ assert _repo_manager_cache_var.get() is None
111
+
112
+
113
+ def test_task_failure_handler_does_nothing_without_a_sender(sync_repo_manager_class):
114
+ """Without a `sender`, the handler bails out before reaching the cleanup logic."""
115
+ manager = sync_repo_manager_class(db=Mock(spec=Session))
116
+ _repo_manager_cache_var.set({sync_repo_manager_class: manager})
117
+
118
+ BaseTask.task_failure_handler(sender=None, exception=Exception("boom"), args=(), kwargs={})
119
+
120
+ manager.db.close.assert_not_called()
121
+
122
+
123
+ def test_task_postrun_handler_deletes_dedup_key_when_broker_is_redis(monkeypatch):
124
+ """The dedup key written by apply_async gets cleaned up once the task finishes."""
125
+ monkeypatch.setattr(
126
+ base_task_module,
127
+ "get_core_settings",
128
+ lambda: SimpleNamespace(CELERY_BROKER_URI="redis://localhost:6379/0", CACHE_KEY_PREFIX=""),
129
+ )
130
+ redis_client = Mock()
131
+ monkeypatch.setattr(base_task_module, "get_redis_client", lambda: redis_client)
132
+
133
+ BaseTask.task_postrun_handler(sender=_FakeCeleryTask(), task_id="t-1", args=(), kwargs={})
134
+
135
+ redis_client.delete.assert_called_once()
136
+
137
+
138
+ def test_task_postrun_handler_skips_dedup_key_when_broker_is_not_redis(monkeypatch):
139
+ """No dedup key was ever written for a non-Redis broker, so there's nothing to delete here either."""
140
+ monkeypatch.setattr(
141
+ base_task_module, "get_core_settings", lambda: SimpleNamespace(CELERY_BROKER_URI="amqp://guest@localhost//")
142
+ )
143
+ redis_client = Mock()
144
+ monkeypatch.setattr(base_task_module, "get_redis_client", lambda: redis_client)
145
+
146
+ BaseTask.task_postrun_handler(sender=_FakeCeleryTask(), task_id="t-1", args=(), kwargs={})
147
+
148
+ redis_client.delete.assert_not_called()
149
+
150
+
151
+ def test_task_postrun_handler_closes_an_async_session_too(async_repo_manager_class):
152
+ """Sync Celery tasks can still have loaded an async-managed repository manager; must not crash."""
153
+ manager = async_repo_manager_class(db=AsyncMock(spec=AsyncSession))
154
+ _repo_manager_cache_var.set({async_repo_manager_class: manager})
155
+
156
+ BaseTask.task_postrun_handler(sender=None, task_id=None, args=None, kwargs=None)
157
+
158
+ manager.db.close.assert_not_called() # can't close an AsyncSession from this sync path - skipped, not crashed
159
+ assert _repo_manager_cache_var.get() is None
@@ -0,0 +1,18 @@
1
+ import pytest
2
+
3
+ from fastspine.celery.broker import is_redis_broker
4
+
5
+
6
+ @pytest.mark.parametrize(
7
+ ("broker_uri", "expected"),
8
+ [
9
+ ("redis://localhost:6379/0", True),
10
+ ("rediss://localhost:6379/0", True),
11
+ ("amqp://guest@localhost//", False),
12
+ ("kafka://localhost:9092", False),
13
+ ("", False),
14
+ ],
15
+ )
16
+ def test_is_redis_broker(broker_uri, expected):
17
+ """Only redis:// and rediss:// broker URIs count as a Redis broker."""
18
+ assert is_redis_broker(broker_uri) is expected
@@ -674,7 +674,7 @@ wheels = [
674
674
 
675
675
  [[package]]
676
676
  name = "fastspine"
677
- version = "1.1.0"
677
+ version = "1.2.0"
678
678
  source = { editable = "." }
679
679
  dependencies = [
680
680
  { name = "alembic" },
@@ -1,37 +0,0 @@
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()
@@ -1,70 +0,0 @@
1
- from unittest.mock import AsyncMock, Mock
2
-
3
- from sqlalchemy.ext.asyncio import AsyncSession
4
- from sqlalchemy.orm import Session
5
-
6
- from fastspine.celery.base_task import BaseTask
7
- from fastspine.dependencies.repository_manager import _repo_manager_cache_var
8
-
9
-
10
- class _FakeCeleryTask:
11
- """Minimal stand-in for a Celery task instance, enough for the signal handlers under test."""
12
-
13
- __module__ = __name__
14
- name = "fake_task"
15
-
16
- def run(self):
17
- pass
18
-
19
-
20
- def test_task_prerun_handler_clears_stale_cache(sync_repo_manager_class):
21
- """A sync worker reuses its process/thread across tasks, so prerun must wipe leftover state."""
22
- manager = sync_repo_manager_class(db=Mock(spec=Session))
23
- _repo_manager_cache_var.set({sync_repo_manager_class: manager})
24
-
25
- BaseTask.task_prerun_handler(task_id="t-1", task=_FakeCeleryTask(), args=(), kwargs={})
26
-
27
- assert _repo_manager_cache_var.get() is None
28
-
29
-
30
- def test_task_postrun_handler_closes_sessions_and_clears_cache(sync_repo_manager_class):
31
- """On successful completion, the task's repository manager session gets closed."""
32
- manager = sync_repo_manager_class(db=Mock(spec=Session))
33
- _repo_manager_cache_var.set({sync_repo_manager_class: manager})
34
-
35
- BaseTask.task_postrun_handler(sender=None, task_id=None, args=None, kwargs=None)
36
-
37
- manager.db.close.assert_called_once()
38
- assert _repo_manager_cache_var.get() is None
39
-
40
-
41
- def test_task_failure_handler_closes_sessions_and_clears_cache(sync_repo_manager_class):
42
- """Regression test: the failure path used to skip session cleanup entirely, leaking the connection."""
43
- manager = sync_repo_manager_class(db=Mock(spec=Session))
44
- _repo_manager_cache_var.set({sync_repo_manager_class: manager})
45
-
46
- BaseTask.task_failure_handler(sender=_FakeCeleryTask(), exception=Exception("boom"), args=(), kwargs={})
47
-
48
- manager.db.close.assert_called_once()
49
- assert _repo_manager_cache_var.get() is None
50
-
51
-
52
- def test_task_failure_handler_does_nothing_without_a_sender(sync_repo_manager_class):
53
- """Without a `sender`, the handler bails out before reaching the cleanup logic."""
54
- manager = sync_repo_manager_class(db=Mock(spec=Session))
55
- _repo_manager_cache_var.set({sync_repo_manager_class: manager})
56
-
57
- BaseTask.task_failure_handler(sender=None, exception=Exception("boom"), args=(), kwargs={})
58
-
59
- manager.db.close.assert_not_called()
60
-
61
-
62
- def test_task_postrun_handler_closes_an_async_session_too(async_repo_manager_class):
63
- """Sync Celery tasks can still have loaded an async-managed repository manager; must not crash."""
64
- manager = async_repo_manager_class(db=AsyncMock(spec=AsyncSession))
65
- _repo_manager_cache_var.set({async_repo_manager_class: manager})
66
-
67
- BaseTask.task_postrun_handler(sender=None, task_id=None, args=None, kwargs=None)
68
-
69
- manager.db.close.assert_not_called() # can't close an AsyncSession from this sync path - skipped, not crashed
70
- assert _repo_manager_cache_var.get() is None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes