Coverage for src/robot_dispatch/infra/redis_lock.py: 100%
68 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 17:18 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 17:18 +0000
1from __future__ import annotations
3import asyncio
4import uuid
6import redis.asyncio as redis
8from robot_dispatch.logging_setup import get_logger
10logger = get_logger("lock")
12_RELEASE = """
13if redis.call('get', KEYS[1]) == ARGV[1] then
14 return redis.call('del', KEYS[1])
15else
16 return 0
17end
18"""
20_EXTEND = """
21if redis.call('get', KEYS[1]) == ARGV[1] then
22 return redis.call('pexpire', KEYS[1], ARGV[2])
23else
24 return 0
25end
26"""
29class RedisLock:
30 """Best-effort leader election for the dispatcher loop.
32 Correctness does not depend on this lock: `FOR UPDATE SKIP LOCKED` already
33 guarantees a task is handed out once. The lock only keeps several replicas
34 from spinning on the same empty queue, and it degrades to "no lock" when
35 Redis is unreachable.
36 """
38 def __init__(self, url: str, key: str = "robot-dispatch:dispatcher:leader", ttl_ms: int = 10_000) -> None:
39 self._url = url
40 self._key = key
41 self._ttl_ms = ttl_ms
42 self._client: redis.Redis | None = None
43 self._token = uuid.uuid4().hex
44 self._available = False
46 @property
47 def available(self) -> bool:
48 return self._available
50 async def connect(self) -> None:
51 try:
52 self._client = redis.from_url(self._url, decode_responses=True)
53 await self._client.ping()
54 self._available = True
55 except Exception as exc: # noqa: BLE001 - optional dependency
56 logger.warning("redis unavailable, running without leader lock", error=str(exc))
57 self._available = False
58 self._client = None
60 async def close(self) -> None:
61 client, self._client = self._client, None
62 if client is not None:
63 await client.aclose()
65 async def acquire(self) -> bool:
66 if self._client is None:
67 return True
68 try:
69 return bool(
70 await self._client.set(self._key, self._token, nx=True, px=self._ttl_ms)
71 )
72 except Exception as exc: # noqa: BLE001
73 logger.warning("redis lock acquire failed", error=str(exc))
74 return True
76 async def extend(self) -> bool:
77 if self._client is None:
78 return True
79 try:
80 return bool(await self._client.eval(_EXTEND, 1, self._key, self._token, self._ttl_ms))
81 except Exception: # noqa: BLE001
82 return True
84 async def release(self) -> None:
85 if self._client is None:
86 return
87 try:
88 await self._client.eval(_RELEASE, 1, self._key, self._token)
89 except Exception as exc: # noqa: BLE001
90 logger.warning("redis lock release failed", error=str(exc))
93class NullLock:
94 """Used when Redis is disabled entirely."""
96 available = False
98 async def connect(self) -> None:
99 return None
101 async def close(self) -> None:
102 return None
104 async def acquire(self) -> bool:
105 return True
107 async def extend(self) -> bool:
108 return True
110 async def release(self) -> None:
111 return None
114async def sleep_ms(milliseconds: float) -> None:
115 await asyncio.sleep(max(milliseconds, 0) / 1000)