server-decorator 2.0.0__tar.gz → 2.0.20__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.
- server_decorator-2.0.20/.gitignore +57 -0
- server_decorator-2.0.20/PKG-INFO +243 -0
- server_decorator-2.0.20/README.md +189 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/pyproject.toml +9 -3
- server_decorator-2.0.20/scripts/check.sh +26 -0
- server_decorator-2.0.20/src/server_decorator/__init__.py +190 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/_contract.py +1 -1
- server_decorator-2.0.20/src/server_decorator/_version.py +1 -0
- server_decorator-2.0.20/src/server_decorator/adapters/__init__.py +1 -0
- server_decorator-2.0.20/src/server_decorator/adapters/fastapi.py +758 -0
- server_decorator-2.0.20/src/server_decorator/adapters/graphql.py +220 -0
- server_decorator-2.0.20/src/server_decorator/config.py +19 -0
- server_decorator-2.0.20/src/server_decorator/consumer/__init__.py +1 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapter.py +23 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapters/__init__.py +1 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapters/bullmq_consumer.py +49 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapters/kafka_consumer.py +84 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapters/rabbitmq_consumer.py +46 -0
- server_decorator-2.0.20/src/server_decorator/consumer/adapters/redis_consumer.py +87 -0
- server_decorator-2.0.20/src/server_decorator/consumer/inmemory.py +31 -0
- server_decorator-2.0.20/src/server_decorator/consumer/registry.py +161 -0
- server_decorator-2.0.20/src/server_decorator/consumer/validate.py +33 -0
- server_decorator-2.0.20/src/server_decorator/decorators/__init__.py +92 -0
- server_decorator-2.0.20/src/server_decorator/decorators/_cache_key.py +101 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/decorators/_class_apply.py +13 -2
- server_decorator-2.0.20/src/server_decorator/decorators/_receiver.py +109 -0
- server_decorator-2.0.20/src/server_decorator/decorators/_warn_once.py +21 -0
- server_decorator-2.0.20/src/server_decorator/decorators/cache.py +139 -0
- server_decorator-2.0.20/src/server_decorator/decorators/circuit_breaker.py +303 -0
- server_decorator-2.0.20/src/server_decorator/decorators/coalesce.py +632 -0
- server_decorator-2.0.20/src/server_decorator/decorators/distributed_lock.py +259 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/decorators/emit_on_success.py +78 -14
- server_decorator-2.0.20/src/server_decorator/decorators/on_event.py +26 -0
- server_decorator-2.0.20/src/server_decorator/decorators/rate_limit.py +181 -0
- server_decorator-2.0.20/src/server_decorator/decorators/retry.py +124 -0
- server_decorator-2.0.20/src/server_decorator/decorators/single_flight.py +86 -0
- server_decorator-2.0.20/src/server_decorator/decorators/trace.py +413 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/decorators/tracking.py +2 -0
- server_decorator-2.0.20/src/server_decorator/middleware/__init__.py +17 -0
- server_decorator-2.0.20/src/server_decorator/middleware/auth.py +321 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/message.py +3 -0
- server_decorator-2.0.20/src/server_decorator/sse.py +150 -0
- server_decorator-2.0.20/tests/conftest.py +16 -0
- server_decorator-2.0.20/tests/integration/conftest.py +21 -0
- server_decorator-2.0.20/tests/integration/test_bullmq_consumer.py +37 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/integration/test_emit_rabbitmq.py +2 -1
- server_decorator-2.0.20/tests/integration/test_kafka_consumer.py +40 -0
- server_decorator-2.0.20/tests/integration/test_rabbitmq_consumer.py +45 -0
- server_decorator-2.0.20/tests/integration/test_redis_consumer.py +131 -0
- server_decorator-2.0.20/tests/unit/test_adapter_coverage.py +52 -0
- server_decorator-2.0.20/tests/unit/test_adapters_graphql_coverage.py +394 -0
- server_decorator-2.0.20/tests/unit/test_auth_middleware.py +270 -0
- server_decorator-2.0.20/tests/unit/test_bullmq_consumer_coverage.py +147 -0
- server_decorator-2.0.20/tests/unit/test_bullmq_extra_declared.py +14 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/unit/test_cache.py +31 -0
- server_decorator-2.0.20/tests/unit/test_cache_coverage.py +449 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/unit/test_cache_key_parity.py +1 -1
- server_decorator-2.0.20/tests/unit/test_cache_regression.py +535 -0
- server_decorator-2.0.20/tests/unit/test_circuit_breaker.py +120 -0
- server_decorator-2.0.20/tests/unit/test_circuit_breaker_coverage.py +444 -0
- server_decorator-2.0.20/tests/unit/test_coalesce.py +364 -0
- server_decorator-2.0.20/tests/unit/test_coalesce_coverage.py +1046 -0
- server_decorator-2.0.20/tests/unit/test_coalesce_regressions.py +620 -0
- server_decorator-2.0.20/tests/unit/test_config.py +26 -0
- server_decorator-2.0.20/tests/unit/test_consumer_exports.py +12 -0
- server_decorator-2.0.20/tests/unit/test_consumer_registry.py +108 -0
- server_decorator-2.0.20/tests/unit/test_consumer_validate.py +57 -0
- server_decorator-2.0.20/tests/unit/test_distributed_lock.py +376 -0
- server_decorator-2.0.20/tests/unit/test_distributed_lock_coverage.py +660 -0
- server_decorator-2.0.20/tests/unit/test_emit_on_success_coverage.py +387 -0
- server_decorator-2.0.20/tests/unit/test_emit_queues_hardening.py +287 -0
- server_decorator-2.0.20/tests/unit/test_emit_service_prefix.py +77 -0
- server_decorator-2.0.20/tests/unit/test_emitter_coverage.py +140 -0
- server_decorator-2.0.20/tests/unit/test_fastapi_adapter.py +331 -0
- server_decorator-2.0.20/tests/unit/test_fastapi_conformance.py +195 -0
- server_decorator-2.0.20/tests/unit/test_fastapi_coverage.py +873 -0
- server_decorator-2.0.20/tests/unit/test_graphql_loader.py +128 -0
- server_decorator-2.0.20/tests/unit/test_graphql_loader_regressions.py +300 -0
- server_decorator-2.0.20/tests/unit/test_kafka_adapter_coverage.py +94 -0
- server_decorator-2.0.20/tests/unit/test_kafka_consumer_coverage.py +238 -0
- server_decorator-2.0.20/tests/unit/test_logger_coverage.py +98 -0
- server_decorator-2.0.20/tests/unit/test_middleware_auth_coverage.py +441 -0
- server_decorator-2.0.20/tests/unit/test_noop_coverage.py +33 -0
- server_decorator-2.0.20/tests/unit/test_on_event.py +72 -0
- server_decorator-2.0.20/tests/unit/test_property_wrapping.py +44 -0
- server_decorator-2.0.20/tests/unit/test_qualname_coverage.py +39 -0
- server_decorator-2.0.20/tests/unit/test_queue_message_parity.py +20 -0
- server_decorator-2.0.20/tests/unit/test_queue_registry_coverage.py +174 -0
- server_decorator-2.0.20/tests/unit/test_rabbitmq_adapter_coverage.py +97 -0
- server_decorator-2.0.20/tests/unit/test_rabbitmq_consumer_coverage.py +183 -0
- server_decorator-2.0.20/tests/unit/test_rate_limit.py +77 -0
- server_decorator-2.0.20/tests/unit/test_redis_adapter_coverage.py +94 -0
- server_decorator-2.0.20/tests/unit/test_redis_consumer_coverage.py +217 -0
- server_decorator-2.0.20/tests/unit/test_registry_coverage.py +444 -0
- server_decorator-2.0.20/tests/unit/test_resilience_regression.py +675 -0
- server_decorator-2.0.20/tests/unit/test_retry.py +96 -0
- server_decorator-2.0.20/tests/unit/test_single_flight.py +531 -0
- server_decorator-2.0.20/tests/unit/test_smoke.py +27 -0
- server_decorator-2.0.20/tests/unit/test_sse.py +159 -0
- server_decorator-2.0.20/tests/unit/test_sse_replay.py +55 -0
- server_decorator-2.0.20/tests/unit/test_trace.py +226 -0
- server_decorator-2.0.20/tests/unit/test_trace_coverage.py +357 -0
- server_decorator-2.0.20/tests/unit/test_trace_hardening.py +482 -0
- server_decorator-2.0.0/.gitignore +0 -29
- server_decorator-2.0.0/PKG-INFO +0 -109
- server_decorator-2.0.0/README.md +0 -67
- server_decorator-2.0.0/scripts/check.sh +0 -19
- server_decorator-2.0.0/src/server_decorator/__init__.py +0 -61
- server_decorator-2.0.0/src/server_decorator/_version.py +0 -1
- server_decorator-2.0.0/src/server_decorator/decorators/__init__.py +0 -1
- server_decorator-2.0.0/src/server_decorator/decorators/_cache_key.py +0 -35
- server_decorator-2.0.0/src/server_decorator/decorators/cache.py +0 -92
- server_decorator-2.0.0/tests/unit/test_smoke.py +0 -15
- server_decorator-2.0.0/uv.lock +0 -1568
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/decorators/_qualname.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/emitter.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/logger.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/__init__.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapter.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/__init__.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/inmemory.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/kafka_adapter.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/noop.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/rabbitmq_adapter.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/adapters/redis_adapter.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/queue/registry.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/src/server_decorator/tracker.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/__init__.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/integration/__init__.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/integration/test_emit_kafka.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/integration/test_emit_redis.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/unit/__init__.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/unit/test_emit_on_success.py +0 -0
- {server_decorator-2.0.0 → server_decorator-2.0.20}/tests/unit/test_tracking.py +0 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
.npmrc
|
|
2
|
+
dist
|
|
3
|
+
node_modules
|
|
4
|
+
.astro
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# GitHub Actions
|
|
8
|
+
.env
|
|
9
|
+
*.log
|
|
10
|
+
|
|
11
|
+
# Package managers
|
|
12
|
+
npm-debug.log*
|
|
13
|
+
yarn-debug.log*
|
|
14
|
+
yarn-error.log*
|
|
15
|
+
package-lock.json # Use pnpm-lock.yaml instead
|
|
16
|
+
yarn.lock # Use pnpm-lock.yaml instead
|
|
17
|
+
# uv is dev-only; do not commit the lockfile
|
|
18
|
+
python/uv.lock
|
|
19
|
+
|
|
20
|
+
# iCloud-style duplicate files (D-D)
|
|
21
|
+
* 2
|
|
22
|
+
* 2.*
|
|
23
|
+
* 3
|
|
24
|
+
* 3.*
|
|
25
|
+
|
|
26
|
+
# Python (added during polyglot migration)
|
|
27
|
+
__pycache__/
|
|
28
|
+
*.py[cod]
|
|
29
|
+
.venv/
|
|
30
|
+
*.egg-info/
|
|
31
|
+
.pytest_cache/
|
|
32
|
+
.mypy_cache/
|
|
33
|
+
.ruff_cache/
|
|
34
|
+
# ps-release-workflow (gitignored state)
|
|
35
|
+
.claude/state/
|
|
36
|
+
.claude/worktrees/
|
|
37
|
+
|
|
38
|
+
# Rendered design HTML — local view artifacts only (global rule)
|
|
39
|
+
docs/superpowers/**/*.html
|
|
40
|
+
research/**/*.html
|
|
41
|
+
|
|
42
|
+
# Nim (F-006): `nim c` drops binaries beside sources; `nim r`/`nimble test` do not, but be safe.
|
|
43
|
+
nimcache/
|
|
44
|
+
nim/tests/t_*
|
|
45
|
+
!nim/tests/t_*.nim
|
|
46
|
+
nim/examples/emit_*
|
|
47
|
+
!nim/examples/emit_*.nim
|
|
48
|
+
nim/examples/user
|
|
49
|
+
nim/nimble.lock
|
|
50
|
+
# ^ the package has zero dependencies (plan constraint) — this lockfile must never be committed.
|
|
51
|
+
|
|
52
|
+
# graft's local graph cache — regenerable, not committed (run `graft build`).
|
|
53
|
+
graft/
|
|
54
|
+
# Rust build artifacts
|
|
55
|
+
target/
|
|
56
|
+
rust/target/
|
|
57
|
+
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: server-decorator
|
|
3
|
+
Version: 2.0.20
|
|
4
|
+
Summary: Server-side decorators for caching, tracking, and queue emission. Polyglot sibling of the Node `server-decorator` npm package.
|
|
5
|
+
Project-URL: Homepage, https://github.com/your-username/server-decorator
|
|
6
|
+
Project-URL: Repository, https://github.com/your-username/server-decorator
|
|
7
|
+
Project-URL: Issues, https://github.com/your-username/server-decorator/issues
|
|
8
|
+
Author: server-decorator contributors
|
|
9
|
+
License: MIT
|
|
10
|
+
Keywords: caching,decorators,kafka,queue,rabbitmq,redis,tracking
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Provides-Extra: all
|
|
21
|
+
Requires-Dist: aio-pika>=9.4; extra == 'all'
|
|
22
|
+
Requires-Dist: aiokafka>=0.11; extra == 'all'
|
|
23
|
+
Requires-Dist: bullmq>=2.0; extra == 'all'
|
|
24
|
+
Requires-Dist: fastapi>=0.100.0; extra == 'all'
|
|
25
|
+
Requires-Dist: httpx>=0.25.0; extra == 'all'
|
|
26
|
+
Requires-Dist: redis>=5.0; extra == 'all'
|
|
27
|
+
Provides-Extra: bullmq
|
|
28
|
+
Requires-Dist: bullmq>=2.0; extra == 'bullmq'
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: aio-pika>=9.4; extra == 'dev'
|
|
31
|
+
Requires-Dist: aiokafka>=0.11; extra == 'dev'
|
|
32
|
+
Requires-Dist: bullmq>=2.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: fastapi>=0.100.0; extra == 'dev'
|
|
34
|
+
Requires-Dist: httpx>=0.25.0; extra == 'dev'
|
|
35
|
+
Requires-Dist: jsonschema>=4.21; extra == 'dev'
|
|
36
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
37
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
38
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
39
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
40
|
+
Requires-Dist: redis>=5.0; extra == 'dev'
|
|
41
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
42
|
+
Requires-Dist: testcontainers[kafka,rabbitmq,redis]>=4.7; extra == 'dev'
|
|
43
|
+
Requires-Dist: tomli>=2.0; (python_version < '3.11') and extra == 'dev'
|
|
44
|
+
Provides-Extra: fastapi
|
|
45
|
+
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
|
|
46
|
+
Requires-Dist: httpx>=0.25.0; extra == 'fastapi'
|
|
47
|
+
Provides-Extra: kafka
|
|
48
|
+
Requires-Dist: aiokafka>=0.11; extra == 'kafka'
|
|
49
|
+
Provides-Extra: rabbitmq
|
|
50
|
+
Requires-Dist: aio-pika>=9.4; extra == 'rabbitmq'
|
|
51
|
+
Provides-Extra: redis
|
|
52
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
53
|
+
Description-Content-Type: text/markdown
|
|
54
|
+
|
|
55
|
+
# server-decorator (Python)
|
|
56
|
+
|
|
57
|
+
Server-side decorators for caching, tracking, and queue emission. Polyglot sibling of the Node `server-decorator` npm package — both share the wire-format contracts in [`../../../contracts`](../../../contracts).
|
|
58
|
+
|
|
59
|
+
## Install
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install server-decorator # core
|
|
63
|
+
pip install server-decorator[redis] # + redis adapter
|
|
64
|
+
pip install server-decorator[rabbitmq] # + aio-pika adapter
|
|
65
|
+
pip install server-decorator[kafka] # + aiokafka adapter
|
|
66
|
+
pip install server-decorator[all] # all adapters
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Requires Python 3.10+. `asyncio` only — no `trio`/`anyio` (Decision #10).
|
|
70
|
+
|
|
71
|
+
## Quick start
|
|
72
|
+
|
|
73
|
+
### Method form
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from server_decorator import tracking, cache, emit_on_success, CACHE_MISS
|
|
77
|
+
|
|
78
|
+
class InMemoryCache:
|
|
79
|
+
def __init__(self): self._d = {}
|
|
80
|
+
def get(self, key): return self._d.get(key, CACHE_MISS)
|
|
81
|
+
def set(self, key, val, ttl): self._d[key] = val
|
|
82
|
+
|
|
83
|
+
class OrderService:
|
|
84
|
+
@tracking
|
|
85
|
+
@cache(InMemoryCache(), ttl=300)
|
|
86
|
+
@emit_on_success(use_events=True)
|
|
87
|
+
async def create_order(self, customer_id: str, total: float) -> dict:
|
|
88
|
+
return {"customer_id": customer_id, "total": total, "status": "pending"}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Class form (auto-wrap every public method)
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from server_decorator import tracking_class
|
|
95
|
+
|
|
96
|
+
@tracking_class()
|
|
97
|
+
class OrderService:
|
|
98
|
+
async def create_order(self, ...): ... # auto-wrapped
|
|
99
|
+
async def cancel_order(self, ...): ... # auto-wrapped
|
|
100
|
+
def _internal(self): ... # SKIPPED (leading underscore)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`tracking_class`, `cache_class`, and `emit_on_success_class` accept `include`, `exclude`, and `include_private` to override the default predicates.
|
|
104
|
+
|
|
105
|
+
## Sync vs async
|
|
106
|
+
|
|
107
|
+
Method-level decorators auto-detect coroutines via `inspect.iscoroutinefunction` and wrap accordingly (Decision #5). For `@emit_on_success(use_queue=True)` on a sync method called outside an event loop, the side effect runs on a single-worker `ThreadPoolExecutor` so the caller doesn't block (D-C). To drain in-flight emits at process exit:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import atexit
|
|
111
|
+
from server_decorator.decorators.emit_on_success import _EMIT_EXECUTOR
|
|
112
|
+
atexit.register(_EMIT_EXECUTOR.shutdown, wait=True)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Caching `None` / falsy values
|
|
116
|
+
|
|
117
|
+
`CacheAdapter.get` returns `CACHE_MISS` (a module-level sentinel) when a key is absent — `None`/`0`/`""`/`False` are valid cached values. See [`../../../contracts/rules/cache-adapter.md`](../../../contracts/rules/cache-adapter.md).
|
|
118
|
+
|
|
119
|
+
## Consuming events
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from server_decorator import ConsumerRegistry, on_event, RedisStreamConsumer
|
|
123
|
+
import redis.asyncio as redis
|
|
124
|
+
|
|
125
|
+
registry = ConsumerRegistry()
|
|
126
|
+
registry.register(
|
|
127
|
+
"orders",
|
|
128
|
+
RedisStreamConsumer(redis.from_url("redis://localhost:6379"), stream="orders", group="email-svc"),
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@on_event("OrderService.createOrder", consumer="orders")
|
|
132
|
+
async def send_email(payload, meta):
|
|
133
|
+
... # return -> ack; raise -> redelivered
|
|
134
|
+
|
|
135
|
+
await registry.start()
|
|
136
|
+
# ... app runs ...
|
|
137
|
+
await registry.stop()
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**Delivery is at-least-once.** A message can be delivered more than once (e.g. a
|
|
141
|
+
crash between handler success and ack). **Handlers must be idempotent.** Ordering
|
|
142
|
+
is not guaranteed under redelivery. Unparseable messages are acked + skipped;
|
|
143
|
+
only handler failures stay pending for retry.
|
|
144
|
+
|
|
145
|
+
### Available consumers
|
|
146
|
+
|
|
147
|
+
| Consumer | Dependency |
|
|
148
|
+
|----------|------------|
|
|
149
|
+
| `RedisStreamConsumer` | `pip install server-decorator[redis]` |
|
|
150
|
+
| `KafkaConsumer` | `[kafka]` |
|
|
151
|
+
| `RabbitMQConsumer` | `[rabbitmq]` |
|
|
152
|
+
| `BullMQConsumer` | `[bullmq]` |
|
|
153
|
+
|
|
154
|
+
All backends deliver **at-least-once**, so handlers must be idempotent; failed
|
|
155
|
+
messages stay pending/unacked (Redis/RabbitMQ) or are retried per attempts
|
|
156
|
+
(Kafka offset is not committed / BullMQ job `attempts`).
|
|
157
|
+
|
|
158
|
+
`KafkaConsumer` rewinds the partition to a failed offset after
|
|
159
|
+
`retry_backoff_ms` (default 1000 ms), so the record is redelivered before
|
|
160
|
+
anything later is committed. A record that always fails therefore blocks its
|
|
161
|
+
partition; route it to a dead-letter topic inside the handler if that is not
|
|
162
|
+
what you want.
|
|
163
|
+
|
|
164
|
+
A traced message is handled inside its own exported span, named
|
|
165
|
+
`consume <eventName>` (`span.kind = CONSUMER`), whose parent is the producer
|
|
166
|
+
span. Inside the handler `span_id` is that consumer span's id, and the caller's
|
|
167
|
+
previous trace context is restored after dispatch.
|
|
168
|
+
|
|
169
|
+
## Single-flight
|
|
170
|
+
|
|
171
|
+
`SingleFlight` runs one execution per key while it is in flight; callers that arrive
|
|
172
|
+
meanwhile share its outcome:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
from server_decorator import SingleFlight
|
|
176
|
+
|
|
177
|
+
flights: SingleFlight[tuple[str, str], list[Row]] = SingleFlight()
|
|
178
|
+
|
|
179
|
+
async def load(symbol: str, quarter: str) -> list[Row]:
|
|
180
|
+
return await flights.do((symbol, quarter), lambda: fetch_rows(symbol, quarter))
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- **Shared result.** Every caller receives the same object, not a copy; a caller that
|
|
184
|
+
mutates it changes what the others see.
|
|
185
|
+
- **Nothing is cached.** A `do` call that starts after the work finished calls `fn` again.
|
|
186
|
+
- **Shared work runs while callers wait.** Cancelling one caller raises `CancelledError`
|
|
187
|
+
in that caller only; the others still receive the result.
|
|
188
|
+
- **Shared work is cancelled when the last waiter leaves.** Once every waiting caller has
|
|
189
|
+
been cancelled, the work is cancelled and the key is forgotten.
|
|
190
|
+
- **One event loop.** An instance belongs to one event loop and is not safe across threads.
|
|
191
|
+
|
|
192
|
+
## Behaviour notes
|
|
193
|
+
|
|
194
|
+
- **Auto topic.** The auto-generated topic is always `ClassName.methodName`,
|
|
195
|
+
also when `event_name` is overridden (it used to follow the event name).
|
|
196
|
+
If you set `event_name` without `topic`, the topic changes, e.g.
|
|
197
|
+
`order.created` becomes `OrderService.create`: update consumer bindings or
|
|
198
|
+
pin `topic=`.
|
|
199
|
+
- **Emit never changes the method's outcome.** If `transform` raises, the error
|
|
200
|
+
is logged and both the event and the queue publish are skipped; the caller
|
|
201
|
+
still gets the method's result.
|
|
202
|
+
- **Sync emit outside an event loop** publishes on one long-lived loop on the
|
|
203
|
+
single emit worker thread (closed at exit) and carries the caller's
|
|
204
|
+
`traceparent` / `tracestate`.
|
|
205
|
+
- **Lost lock lease.** `@distributed_lock` raises `LockLostError` after the
|
|
206
|
+
method settles if the lease was lost while it ran (the method's own error, if
|
|
207
|
+
any, is its `__context__`). A renewal that errors is retried on the next tick;
|
|
208
|
+
the lease counts as lost on a definite refusal or after a full TTL with no
|
|
209
|
+
confirmed renewal. The token-guarded release is always attempted, and a
|
|
210
|
+
cancellation in flight is never replaced or swallowed.
|
|
211
|
+
`distributed_lock_class` wraps coroutine functions only; sync methods and
|
|
212
|
+
properties are left untouched.
|
|
213
|
+
- **Tracing.** A `traceparent` must be version `00` with lower-case hex;
|
|
214
|
+
anything else is ignored and a new trace starts. `@trace` on a generator or
|
|
215
|
+
async generator spans the whole iteration. A plain function (or callable object)
|
|
216
|
+
that returns a coroutine or an async-generator object keeps its span open until
|
|
217
|
+
that object is awaited / fully iterated, with the trace context active in the
|
|
218
|
+
body and failures recorded; if the returned object is never awaited no span is
|
|
219
|
+
exported. A returned `asyncio.Future`/`Task` or a plain generator object returned
|
|
220
|
+
from a non-generator function is not tracked (the span ends when the function
|
|
221
|
+
returns) - decorate the inner function instead. Cancellation and other
|
|
222
|
+
`BaseException`s export the span as `ERROR` and are re-raised unchanged.
|
|
223
|
+
- **Batch load receiver detection.**
|
|
224
|
+
- Name the receiver `self` or `cls`. Then it is always recognised.
|
|
225
|
+
- With another receiver name, the owner class is found by scanning the class for the decorated function through `__wrapped__` / `__func__`. A decorator stacked on top that sets neither hides it, and the instance is then treated as the key. The result is cached per class.
|
|
226
|
+
- A `@staticmethod` is never given a receiver.
|
|
227
|
+
- **Cache.** A failing adapter `set` is logged and the result is still
|
|
228
|
+
returned; a failing `get` propagates. Non-finite numbers are rejected in
|
|
229
|
+
plain JSON values, dict/list/tuple/set/frozenset/deque, dataclass instances,
|
|
230
|
+
Decimal and complex; any OTHER object is keyed by `str(obj)` without being
|
|
231
|
+
inspected, so give such objects a stable `__str__` or pass a plain value.
|
|
232
|
+
Set and frozenset arguments are keyed as a sorted list. Keys keep non-ASCII
|
|
233
|
+
text as UTF-8 (matching Node).
|
|
234
|
+
|
|
235
|
+
## Development
|
|
236
|
+
|
|
237
|
+
`bash scripts/check.sh` runs ruff, ruff format, mypy strict and the unit tests
|
|
238
|
+
with a coverage gate: it fails below `COV_MIN` line coverage (99; a ratchet,
|
|
239
|
+
raise it, never lower it). Integration-marked tests are excluded.
|
|
240
|
+
|
|
241
|
+
## License
|
|
242
|
+
|
|
243
|
+
MIT.
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# server-decorator (Python)
|
|
2
|
+
|
|
3
|
+
Server-side decorators for caching, tracking, and queue emission. Polyglot sibling of the Node `server-decorator` npm package — both share the wire-format contracts in [`../../../contracts`](../../../contracts).
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install server-decorator # core
|
|
9
|
+
pip install server-decorator[redis] # + redis adapter
|
|
10
|
+
pip install server-decorator[rabbitmq] # + aio-pika adapter
|
|
11
|
+
pip install server-decorator[kafka] # + aiokafka adapter
|
|
12
|
+
pip install server-decorator[all] # all adapters
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires Python 3.10+. `asyncio` only — no `trio`/`anyio` (Decision #10).
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
### Method form
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from server_decorator import tracking, cache, emit_on_success, CACHE_MISS
|
|
23
|
+
|
|
24
|
+
class InMemoryCache:
|
|
25
|
+
def __init__(self): self._d = {}
|
|
26
|
+
def get(self, key): return self._d.get(key, CACHE_MISS)
|
|
27
|
+
def set(self, key, val, ttl): self._d[key] = val
|
|
28
|
+
|
|
29
|
+
class OrderService:
|
|
30
|
+
@tracking
|
|
31
|
+
@cache(InMemoryCache(), ttl=300)
|
|
32
|
+
@emit_on_success(use_events=True)
|
|
33
|
+
async def create_order(self, customer_id: str, total: float) -> dict:
|
|
34
|
+
return {"customer_id": customer_id, "total": total, "status": "pending"}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Class form (auto-wrap every public method)
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from server_decorator import tracking_class
|
|
41
|
+
|
|
42
|
+
@tracking_class()
|
|
43
|
+
class OrderService:
|
|
44
|
+
async def create_order(self, ...): ... # auto-wrapped
|
|
45
|
+
async def cancel_order(self, ...): ... # auto-wrapped
|
|
46
|
+
def _internal(self): ... # SKIPPED (leading underscore)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`tracking_class`, `cache_class`, and `emit_on_success_class` accept `include`, `exclude`, and `include_private` to override the default predicates.
|
|
50
|
+
|
|
51
|
+
## Sync vs async
|
|
52
|
+
|
|
53
|
+
Method-level decorators auto-detect coroutines via `inspect.iscoroutinefunction` and wrap accordingly (Decision #5). For `@emit_on_success(use_queue=True)` on a sync method called outside an event loop, the side effect runs on a single-worker `ThreadPoolExecutor` so the caller doesn't block (D-C). To drain in-flight emits at process exit:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import atexit
|
|
57
|
+
from server_decorator.decorators.emit_on_success import _EMIT_EXECUTOR
|
|
58
|
+
atexit.register(_EMIT_EXECUTOR.shutdown, wait=True)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Caching `None` / falsy values
|
|
62
|
+
|
|
63
|
+
`CacheAdapter.get` returns `CACHE_MISS` (a module-level sentinel) when a key is absent — `None`/`0`/`""`/`False` are valid cached values. See [`../../../contracts/rules/cache-adapter.md`](../../../contracts/rules/cache-adapter.md).
|
|
64
|
+
|
|
65
|
+
## Consuming events
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from server_decorator import ConsumerRegistry, on_event, RedisStreamConsumer
|
|
69
|
+
import redis.asyncio as redis
|
|
70
|
+
|
|
71
|
+
registry = ConsumerRegistry()
|
|
72
|
+
registry.register(
|
|
73
|
+
"orders",
|
|
74
|
+
RedisStreamConsumer(redis.from_url("redis://localhost:6379"), stream="orders", group="email-svc"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
@on_event("OrderService.createOrder", consumer="orders")
|
|
78
|
+
async def send_email(payload, meta):
|
|
79
|
+
... # return -> ack; raise -> redelivered
|
|
80
|
+
|
|
81
|
+
await registry.start()
|
|
82
|
+
# ... app runs ...
|
|
83
|
+
await registry.stop()
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Delivery is at-least-once.** A message can be delivered more than once (e.g. a
|
|
87
|
+
crash between handler success and ack). **Handlers must be idempotent.** Ordering
|
|
88
|
+
is not guaranteed under redelivery. Unparseable messages are acked + skipped;
|
|
89
|
+
only handler failures stay pending for retry.
|
|
90
|
+
|
|
91
|
+
### Available consumers
|
|
92
|
+
|
|
93
|
+
| Consumer | Dependency |
|
|
94
|
+
|----------|------------|
|
|
95
|
+
| `RedisStreamConsumer` | `pip install server-decorator[redis]` |
|
|
96
|
+
| `KafkaConsumer` | `[kafka]` |
|
|
97
|
+
| `RabbitMQConsumer` | `[rabbitmq]` |
|
|
98
|
+
| `BullMQConsumer` | `[bullmq]` |
|
|
99
|
+
|
|
100
|
+
All backends deliver **at-least-once**, so handlers must be idempotent; failed
|
|
101
|
+
messages stay pending/unacked (Redis/RabbitMQ) or are retried per attempts
|
|
102
|
+
(Kafka offset is not committed / BullMQ job `attempts`).
|
|
103
|
+
|
|
104
|
+
`KafkaConsumer` rewinds the partition to a failed offset after
|
|
105
|
+
`retry_backoff_ms` (default 1000 ms), so the record is redelivered before
|
|
106
|
+
anything later is committed. A record that always fails therefore blocks its
|
|
107
|
+
partition; route it to a dead-letter topic inside the handler if that is not
|
|
108
|
+
what you want.
|
|
109
|
+
|
|
110
|
+
A traced message is handled inside its own exported span, named
|
|
111
|
+
`consume <eventName>` (`span.kind = CONSUMER`), whose parent is the producer
|
|
112
|
+
span. Inside the handler `span_id` is that consumer span's id, and the caller's
|
|
113
|
+
previous trace context is restored after dispatch.
|
|
114
|
+
|
|
115
|
+
## Single-flight
|
|
116
|
+
|
|
117
|
+
`SingleFlight` runs one execution per key while it is in flight; callers that arrive
|
|
118
|
+
meanwhile share its outcome:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from server_decorator import SingleFlight
|
|
122
|
+
|
|
123
|
+
flights: SingleFlight[tuple[str, str], list[Row]] = SingleFlight()
|
|
124
|
+
|
|
125
|
+
async def load(symbol: str, quarter: str) -> list[Row]:
|
|
126
|
+
return await flights.do((symbol, quarter), lambda: fetch_rows(symbol, quarter))
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
- **Shared result.** Every caller receives the same object, not a copy; a caller that
|
|
130
|
+
mutates it changes what the others see.
|
|
131
|
+
- **Nothing is cached.** A `do` call that starts after the work finished calls `fn` again.
|
|
132
|
+
- **Shared work runs while callers wait.** Cancelling one caller raises `CancelledError`
|
|
133
|
+
in that caller only; the others still receive the result.
|
|
134
|
+
- **Shared work is cancelled when the last waiter leaves.** Once every waiting caller has
|
|
135
|
+
been cancelled, the work is cancelled and the key is forgotten.
|
|
136
|
+
- **One event loop.** An instance belongs to one event loop and is not safe across threads.
|
|
137
|
+
|
|
138
|
+
## Behaviour notes
|
|
139
|
+
|
|
140
|
+
- **Auto topic.** The auto-generated topic is always `ClassName.methodName`,
|
|
141
|
+
also when `event_name` is overridden (it used to follow the event name).
|
|
142
|
+
If you set `event_name` without `topic`, the topic changes, e.g.
|
|
143
|
+
`order.created` becomes `OrderService.create`: update consumer bindings or
|
|
144
|
+
pin `topic=`.
|
|
145
|
+
- **Emit never changes the method's outcome.** If `transform` raises, the error
|
|
146
|
+
is logged and both the event and the queue publish are skipped; the caller
|
|
147
|
+
still gets the method's result.
|
|
148
|
+
- **Sync emit outside an event loop** publishes on one long-lived loop on the
|
|
149
|
+
single emit worker thread (closed at exit) and carries the caller's
|
|
150
|
+
`traceparent` / `tracestate`.
|
|
151
|
+
- **Lost lock lease.** `@distributed_lock` raises `LockLostError` after the
|
|
152
|
+
method settles if the lease was lost while it ran (the method's own error, if
|
|
153
|
+
any, is its `__context__`). A renewal that errors is retried on the next tick;
|
|
154
|
+
the lease counts as lost on a definite refusal or after a full TTL with no
|
|
155
|
+
confirmed renewal. The token-guarded release is always attempted, and a
|
|
156
|
+
cancellation in flight is never replaced or swallowed.
|
|
157
|
+
`distributed_lock_class` wraps coroutine functions only; sync methods and
|
|
158
|
+
properties are left untouched.
|
|
159
|
+
- **Tracing.** A `traceparent` must be version `00` with lower-case hex;
|
|
160
|
+
anything else is ignored and a new trace starts. `@trace` on a generator or
|
|
161
|
+
async generator spans the whole iteration. A plain function (or callable object)
|
|
162
|
+
that returns a coroutine or an async-generator object keeps its span open until
|
|
163
|
+
that object is awaited / fully iterated, with the trace context active in the
|
|
164
|
+
body and failures recorded; if the returned object is never awaited no span is
|
|
165
|
+
exported. A returned `asyncio.Future`/`Task` or a plain generator object returned
|
|
166
|
+
from a non-generator function is not tracked (the span ends when the function
|
|
167
|
+
returns) - decorate the inner function instead. Cancellation and other
|
|
168
|
+
`BaseException`s export the span as `ERROR` and are re-raised unchanged.
|
|
169
|
+
- **Batch load receiver detection.**
|
|
170
|
+
- Name the receiver `self` or `cls`. Then it is always recognised.
|
|
171
|
+
- With another receiver name, the owner class is found by scanning the class for the decorated function through `__wrapped__` / `__func__`. A decorator stacked on top that sets neither hides it, and the instance is then treated as the key. The result is cached per class.
|
|
172
|
+
- A `@staticmethod` is never given a receiver.
|
|
173
|
+
- **Cache.** A failing adapter `set` is logged and the result is still
|
|
174
|
+
returned; a failing `get` propagates. Non-finite numbers are rejected in
|
|
175
|
+
plain JSON values, dict/list/tuple/set/frozenset/deque, dataclass instances,
|
|
176
|
+
Decimal and complex; any OTHER object is keyed by `str(obj)` without being
|
|
177
|
+
inspected, so give such objects a stable `__str__` or pass a plain value.
|
|
178
|
+
Set and frozenset arguments are keyed as a sorted list. Keys keep non-ASCII
|
|
179
|
+
text as UTF-8 (matching Node).
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
`bash scripts/check.sh` runs ruff, ruff format, mypy strict and the unit tests
|
|
184
|
+
with a coverage gate: it fails below `COV_MIN` line coverage (99; a ratchet,
|
|
185
|
+
raise it, never lower it). Integration-marked tests are excluded.
|
|
186
|
+
|
|
187
|
+
## License
|
|
188
|
+
|
|
189
|
+
MIT.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "server-decorator"
|
|
3
|
-
version = "2.0.
|
|
3
|
+
version = "2.0.20"
|
|
4
4
|
description = "Server-side decorators for caching, tracking, and queue emission. Polyglot sibling of the Node `server-decorator` npm package."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.10"
|
|
@@ -23,7 +23,9 @@ dependencies = []
|
|
|
23
23
|
redis = ["redis>=5.0"]
|
|
24
24
|
rabbitmq = ["aio-pika>=9.4"]
|
|
25
25
|
kafka = ["aiokafka>=0.11"]
|
|
26
|
-
|
|
26
|
+
bullmq = ["bullmq>=2.0"]
|
|
27
|
+
fastapi = ["fastapi>=0.100.0", "httpx>=0.25.0"]
|
|
28
|
+
all = ["redis>=5.0", "aio-pika>=9.4", "aiokafka>=0.11", "bullmq>=2.0", "fastapi>=0.100.0", "httpx>=0.25.0"]
|
|
27
29
|
dev = [
|
|
28
30
|
"pytest>=8",
|
|
29
31
|
"pytest-asyncio>=0.23",
|
|
@@ -31,9 +33,13 @@ dev = [
|
|
|
31
33
|
"ruff>=0.5",
|
|
32
34
|
"mypy>=1.10",
|
|
33
35
|
"jsonschema>=4.21",
|
|
36
|
+
"tomli>=2.0; python_version < '3.11'",
|
|
34
37
|
"redis>=5.0",
|
|
35
38
|
"aio-pika>=9.4",
|
|
36
39
|
"aiokafka>=0.11",
|
|
40
|
+
"bullmq>=2.0",
|
|
41
|
+
"fastapi>=0.100.0",
|
|
42
|
+
"httpx>=0.25.0",
|
|
37
43
|
"testcontainers[redis,rabbitmq,kafka]>=4.7",
|
|
38
44
|
]
|
|
39
45
|
|
|
@@ -71,7 +77,7 @@ files = ["src/server_decorator"]
|
|
|
71
77
|
# strict-mode still passes; the adapter wrappers keep the public-facing types
|
|
72
78
|
# precise on the server-decorator side.
|
|
73
79
|
[[tool.mypy.overrides]]
|
|
74
|
-
module = ["aiokafka.*", "aio_pika.*", "redis.*", "redis.asyncio"]
|
|
80
|
+
module = ["aiokafka.*", "aio_pika.*", "redis.*", "redis.asyncio", "bullmq.*", "fastapi.*", "httpx.*", "starlette.*"]
|
|
75
81
|
# Make the optional adapter deps appear as Any. They don't ship `py.typed`,
|
|
76
82
|
# and we don't want to vendor stubs for one thin wrapper layer.
|
|
77
83
|
ignore_missing_imports = true
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# python/packages/core/scripts/check.sh — lint + type-check + unit tests.
|
|
3
|
+
# Assumes `uv` is installed; `pip install uv` if not.
|
|
4
|
+
set -euo pipefail
|
|
5
|
+
|
|
6
|
+
cd "$(dirname "$0")/.."
|
|
7
|
+
|
|
8
|
+
if command -v uv >/dev/null 2>&1; then
|
|
9
|
+
uv sync --extra dev >/dev/null
|
|
10
|
+
RUN="uv run"
|
|
11
|
+
else
|
|
12
|
+
echo "warning: uv not found; falling back to plain python+pytest. Install uv for the full dev experience." >&2
|
|
13
|
+
RUN=""
|
|
14
|
+
fi
|
|
15
|
+
|
|
16
|
+
$RUN ruff check src tests
|
|
17
|
+
$RUN ruff format --check src tests
|
|
18
|
+
$RUN mypy src
|
|
19
|
+
|
|
20
|
+
# Coverage gate (unit tests only; integration-marked tests are excluded).
|
|
21
|
+
# COV_MIN is a ratchet: achieved line+branch coverage (--cov-branch) rounded down,
|
|
22
|
+
# measured on Python 3.10, 3.12 and 3.14. Raise it, never lower it.
|
|
23
|
+
COV_MIN=${COV_MIN:-98}
|
|
24
|
+
export COVERAGE_FILE="${COVERAGE_FILE:-${TMPDIR:-/tmp}/server-decorator-core.coverage}"
|
|
25
|
+
$RUN pytest -q tests/unit -m "not integration" \
|
|
26
|
+
--cov=src --cov-branch --cov-report=term-missing:skip-covered --cov-fail-under="$COV_MIN"
|