feat(B-RED): Zentraler Redis Pool — cache.py, monitoring.py, worker.py auf get_redis() umgestellt

B-RED: 5 direkte aioredis.from_url() Konstruktoren auf get_redis() umgestellt
- cache.py: get_cache() delegiert auf get_redis(), _cache_redis Singleton entfernt
- monitoring.py: check_redis() und check_worker() nutzen get_redis()
- worker.py: _acquire_cron_lock() und _release_cron_lock() nutzen get_redis()
- 0 verbleibende direkte aioredis.from_url() außerhalb auth.py

B-RED-TEST: 8 Tests in test_redis_pool.py — alle grün
- Singleton, get_cache delegation, SET/GET, parallel, reset, no-direct-from_url checks
This commit is contained in:
Agent Zero
2026-08-13 16:25:17 +02:00
parent e3ca3b3d28
commit e9164979b5
4 changed files with 125 additions and 41 deletions
+16 -21
View File
@@ -20,7 +20,6 @@ logger = logging.getLogger(__name__)
# on every replica. We use a short-lived Redis SET NX lock per cron call
# so only one replica actually executes the job.
import redis.asyncio as aioredis # noqa: E402
import uuid # noqa: E402
@@ -31,33 +30,29 @@ async def _acquire_cron_lock(job_name: str, ttl_seconds: int = 120) -> str | Non
replica already holds the lock. The lock auto-expires after
*ttl_seconds* to avoid deadlocks if a worker crashes mid-job.
"""
settings = get_settings()
client = aioredis.from_url(settings.redis_url)
from app.core.auth import get_redis
client = get_redis()
token = str(uuid.uuid4())
lock_key = f"leocrm:cron_lock:{job_name}"
try:
acquired = await client.set(lock_key, token, nx=True, ex=ttl_seconds)
return token if acquired else None
finally:
await client.aclose()
acquired = await client.set(lock_key, token, nx=True, ex=ttl_seconds)
return token if acquired else None
async def _release_cron_lock(job_name: str, token: str) -> None:
"""Release a previously acquired cron lock using a safe compare-and-delete."""
settings = get_settings()
client = aioredis.from_url(settings.redis_url)
from app.core.auth import get_redis
client = get_redis()
lock_key = f"leocrm:cron_lock:{job_name}"
try:
# Lua script ensures we only delete if the token matches (avoid
# releasing a lock that was already expired and re-acquired).
script = (
b"if redis.call('get', KEYS[1]) == ARGV[1] "
b"then return redis.call('del', KEYS[1]) "
b"else return 0 end"
)
await client.eval(script, 1, lock_key, token.encode())
finally:
await client.aclose()
# Lua script ensures we only delete if the token matches (avoid
# releasing a lock that was already expired and re-acquired).
script = (
b"if redis.call('get', KEYS[1]) == ARGV[1] "
b"then return redis.call('del', KEYS[1]) "
b"else return 0 end"
)
await client.eval(script, 1, lock_key, token.encode())
def _wrap_cron_with_lock(job_name: str, func: Any, ttl_seconds: int = 120) -> Any: