|
8 | 8 | from __future__ import annotations |
9 | 9 |
|
10 | 10 | import asyncio |
11 | | -import contextlib |
12 | 11 | import logging |
13 | 12 | import random |
14 | 13 | import secrets |
@@ -152,31 +151,41 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]: |
152 | 151 | if not await self._redis.set(key, token, ex=self._ttl, nx=True): |
153 | 152 | raise LockAcquisitionError(table_name, "Redis lock unavailable") |
154 | 153 |
|
155 | | - holder_task = asyncio.current_task() |
156 | | - if holder_task is None: |
157 | | - raise RuntimeError("Could not determine current asyncio task") |
158 | | - |
159 | | - watchdog = asyncio.create_task( |
160 | | - self._renewal_watchdog(key, token, table_name, holder_task), |
161 | | - name=f"redis-lock-watchdog:{key}", |
162 | | - ) |
| 154 | + # From here on the key is held: any failure must release it rather than leak it until TTL. |
| 155 | + watchdog: asyncio.Task[None] | None = None |
163 | 156 | try: |
| 157 | + holder_task = asyncio.current_task() |
| 158 | + if holder_task is None: |
| 159 | + raise RuntimeError("Could not determine current asyncio task") |
| 160 | + |
| 161 | + watchdog = asyncio.create_task( |
| 162 | + self._renewal_watchdog(key, token, table_name, holder_task), |
| 163 | + name=f"redis-lock-watchdog:{key}", |
| 164 | + ) |
164 | 165 | yield |
165 | 166 | finally: |
166 | | - await self._cancel_watchdog(watchdog) |
167 | | - await asyncio.shield(self._release_safely(key, token, table_name)) |
| 167 | + try: |
| 168 | + if watchdog is not None: |
| 169 | + await self._cancel_watchdog(watchdog) |
| 170 | + finally: |
| 171 | + await asyncio.shield(self._release_safely(key, token, table_name)) |
168 | 172 |
|
169 | 173 | async def _respect_rate_limit(self, table_name: str) -> None: |
170 | | - """Sleep enough to enforce the configured min-interval between acquires.""" |
| 174 | + """Sleep enough to enforce the configured min-interval between acquires. |
| 175 | +
|
| 176 | + The per-table slot is reserved under the mutex; the sleep itself happens |
| 177 | + outside it so one table's owed delay never blocks acquires for other tables. |
| 178 | + """ |
171 | 179 | if self._acquire_min_interval <= 0: |
172 | 180 | return |
173 | 181 | async with self._rate_limit_lock: |
174 | 182 | now = time.monotonic() |
175 | | - last = self._last_acquire_time.get(table_name, 0.0) |
176 | | - delay = last + self._acquire_min_interval - now |
177 | | - if delay > 0: |
178 | | - await asyncio.sleep(delay) |
179 | | - self._last_acquire_time[table_name] = time.monotonic() |
| 183 | + last = self._last_acquire_time.get(table_name) |
| 184 | + slot = now if last is None else max(now, last + self._acquire_min_interval) |
| 185 | + self._last_acquire_time[table_name] = slot |
| 186 | + delay = slot - now |
| 187 | + if delay > 0: |
| 188 | + await asyncio.sleep(delay) |
180 | 189 |
|
181 | 190 | async def _renewal_watchdog( |
182 | 191 | self, |
@@ -230,10 +239,18 @@ def _fail_holder( |
230 | 239 | holder_task.cancel() |
231 | 240 |
|
232 | 241 | async def _cancel_watchdog(self, watchdog: asyncio.Task[None]) -> None: |
233 | | - """Cancel the renewal watchdog and absorb its CancelledError.""" |
| 242 | + """Cancel the renewal watchdog and absorb its CancelledError. |
| 243 | +
|
| 244 | + If the holder task itself is being cancelled while awaiting the watchdog |
| 245 | + (e.g. app shutdown calls ``task.cancel()``), the cancellation must |
| 246 | + propagate — only the watchdog's own cancellation is swallowed. |
| 247 | + """ |
234 | 248 | watchdog.cancel() |
235 | | - with contextlib.suppress(asyncio.CancelledError): |
| 249 | + try: |
236 | 250 | await watchdog |
| 251 | + except asyncio.CancelledError: |
| 252 | + if (cur := asyncio.current_task()) is not None and cur.cancelling() > 0: |
| 253 | + raise |
237 | 254 |
|
238 | 255 | async def _release_safely(self, key: str, token: str, table_name: str) -> None: |
239 | 256 | """Release the lock; failures are logged but do not propagate. |
|
0 commit comments