Coverage for core / src / sensorkit / common / aio.py: 98%

189 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Async utilities: scoped futures, periodic loops, value latches, and observer queues.""" 

3 

4from __future__ import annotations 

5 

6import asyncio 

7import contextlib 

8from collections.abc import AsyncGenerator, Awaitable, Callable, Collection 

9from typing import AsyncContextManager, ClassVar, Literal, Self, get_args, overload 

10 

11from sensorkit.common.logging import limited_logger 

12 

13type OverflowPolicy = Literal["drop_oldest", "close"] 

14"""Overflow handling for observer queues.""" 

15 

16 

17def scoped_waiter[T](aw: Awaitable[T]) -> AsyncContextManager[asyncio.Future[T]]: 

18 """Create an async context manager wrapping an awaitable in a scoped `asyncio.Future`. 

19 

20 The future is cancelled if it has not completed before the `async with` block 

21 exits or if an exception propagates out of the block. 

22 

23 Important: 

24 Any exceptions raised by the awaitable are silently discarded. This makes 

25 `scoped_waiter` suitable only for "waiter" type tasks where exceptions either 

26 won't occur or are not meaningful to handle (e.g. background monitoring tasks, 

27 optional notifications, or advisory operations). 

28 

29 Args: 

30 aw: The awaitable object to be wrapped in an `asyncio.Future`. 

31 

32 Returns: 

33 An async context manager that yields the `asyncio.Future` for the awaitable. 

34 """ 

35 return _scoped_waiter(aw) 

36 

37 

38@overload 

39def cleanup_future(fut: asyncio.Task): ... 

40 

41@overload 

42def cleanup_future(fut: asyncio.Future): ... 

43 

44def cleanup_future(fut: asyncio.Future | asyncio.Task): 

45 """Safely clean up a Future or an already-completed Task. 

46 

47 Args: 

48 fut: The asyncio.Future to clean up. 

49 """ 

50 if not fut.done(): 

51 fut.cancel() 

52 elif not fut.cancelled(): 

53 fut.exception() 

54 

55 

56async def defer_cancellation[T](aw: Awaitable[T]) -> T: 

57 """Finish an awaitable before propagating caller cancellation. 

58 

59 Repeated caller cancellation leaves the operation running and waits for it to finish. 

60 Operation failures, including cancellation of the operation itself, take precedence 

61 over caller cancellation. 

62 

63 Args: 

64 aw: The operation, as a coroutine, task, or future. 

65 

66 Returns: 

67 The operation's result if the caller was not canceled while waiting. 

68 

69 Raises: 

70 asyncio.CancelledError: If the caller or the operation was canceled. 

71 """ 

72 fut = asyncio.ensure_future(aw) 

73 cancelled = False 

74 

75 while not fut.done(): 

76 try: 

77 await asyncio.shield(fut) 

78 except asyncio.CancelledError: 

79 cancelled = True 

80 

81 result = fut.result() 

82 

83 if cancelled: 

84 raise asyncio.CancelledError() 

85 

86 return result 

87 

88 

89async def interruptible_wait( 

90 futures: Collection[asyncio.Future], 

91 *, 

92 timeout: float | None = None, 

93 interrupt: asyncio.Event | None = None, 

94) -> set[asyncio.Future]: 

95 """Wait until all futures finish, the timeout expires, or interrupt is set. 

96 

97 Timeout, interruption, and caller cancellation leave the supplied futures running. 

98 Results and exceptions are left for the caller to retrieve. 

99 

100 Returns: 

101 The futures that have not finished. 

102 """ 

103 loop = asyncio.get_running_loop() 

104 deadline = None if timeout is None else loop.time() + timeout 

105 pending = {future for future in futures if not future.done()} 

106 waiter = None if interrupt is None else asyncio.ensure_future(interrupt.wait()) 

107 

108 try: 

109 while pending and not (interrupt is not None and interrupt.is_set()): 

110 remaining = None if deadline is None else deadline - loop.time() 

111 

112 if remaining is not None and remaining <= 0: 

113 break 

114 

115 _, pending = await asyncio.wait( 

116 pending if waiter is None else {*pending, waiter}, 

117 timeout=remaining, 

118 return_when=asyncio.FIRST_COMPLETED, 

119 ) 

120 pending.discard(waiter) 

121 finally: 

122 if waiter is not None: 

123 waiter.cancel() 

124 await asyncio.wait((waiter,)) 

125 

126 return pending 

127 

128 

129@contextlib.asynccontextmanager 

130async def _scoped_waiter(aw: Awaitable) -> AsyncGenerator[asyncio.Task]: 

131 fut = asyncio.ensure_future(aw) 

132 

133 try: 

134 yield fut 

135 finally: 

136 if not fut.done(): 

137 fut.cancel() 

138 with contextlib.suppress(asyncio.CancelledError): 

139 await fut 

140 else: 

141 with contextlib.suppress(asyncio.CancelledError): 

142 fut.exception() 

143 

144 

145class AsyncValueLatch[T]: 

146 """Stores a value and stages pending changes.""" 

147 

148 def __init__(self, initial_value: T): 

149 self.value: T = initial_value 

150 self.pending_value: T = initial_value 

151 self._pending = asyncio.Event() 

152 

153 def update(self, value: T, only_if_different=True): 

154 """Flag a pending value change and set that pending value.""" 

155 if only_if_different and value == self.pending_value: 

156 return False 

157 

158 self.pending_value = value 

159 self._pending.set() 

160 return True 

161 

162 def pending_change(self): 

163 """Return True if there is a pending value change.""" 

164 return self._pending.is_set() 

165 

166 async def wait_until_pending(self): 

167 """Wait until there is a pending value change.""" 

168 await self._pending.wait() 

169 

170 def apply(self): 

171 """Apply the pending value if there is one and return the current value.""" 

172 if self._pending.is_set(): 

173 self._pending.clear() 

174 self.value = self.pending_value 

175 

176 return self.value 

177 

178 

179class AsyncObserver[T]: 

180 """Fan out notified values to independent, bounded subscriber queues. 

181 

182 Each subscriber receives values notified after it subscribes, in order. With 

183 `initial_value=True`, it first receives the current value, if one has been set. 

184 Each subscriber chooses what happens when its queue is full. By default its oldest 

185 pending value is discarded. 

186 

187 Closing the observer shuts down every subscriber queue and ends notification. 

188 """ 

189 

190 NOT_SET: ClassVar[object] = object() 

191 DEFAULT_MAXSIZE: ClassVar[int] = 1024 

192 

193 def __init__(self, initial_value: T = NOT_SET): 

194 self._observers: dict[asyncio.Queue[T], OverflowPolicy] = {} 

195 self._value = initial_value 

196 self._dropped = 0 

197 self._closed = False 

198 

199 def subscribe( 

200 self, 

201 *, 

202 initial_value: bool = False, 

203 maxsize: int = DEFAULT_MAXSIZE, 

204 overflow: OverflowPolicy = "drop_oldest", 

205 ): 

206 """Create and return a new observer queue. 

207 

208 Args: 

209 initial_value: Whether to seed the queue with the current value, if one is set. 

210 maxsize: Bound on values queued for this subscriber. 

211 overflow: What to do when the queue is full. `drop_oldest` discards the oldest 

212 pending value. `close` unsubscribes the queue and shuts it down immediately, 

213 discarding its pending values. 

214 

215 Raises: 

216 RuntimeError: If the observer is closed. 

217 ValueError: If `maxsize` is not positive, which would leave the queue unbounded, 

218 or if `overflow` is not a known policy. 

219 """ 

220 if self._closed: 

221 raise RuntimeError("Cannot subscribe to a closed observer") 

222 

223 if maxsize < 1: 

224 raise ValueError(f"maxsize must be positive, got {maxsize}") 

225 

226 if overflow not in get_args(OverflowPolicy.__value__): 

227 raise ValueError(f"unknown overflow policy {overflow!r}") 

228 

229 queue: asyncio.Queue[T] = asyncio.Queue(maxsize) 

230 self._observers[queue] = overflow 

231 

232 if initial_value and self._value is not self.NOT_SET: 

233 queue.put_nowait(self._value) 

234 

235 return queue 

236 

237 def unsubscribe(self, queue: asyncio.Queue[T]): 

238 """Remove an observer queue, leaving its pending values readable.""" 

239 self._observers.pop(queue, None) 

240 queue.shutdown() 

241 

242 @contextlib.contextmanager 

243 def subscription( 

244 self, 

245 *, 

246 initial_value: bool = False, 

247 maxsize: int = DEFAULT_MAXSIZE, 

248 overflow: OverflowPolicy = "drop_oldest", 

249 ): 

250 """Context manager that provides a subscriber queue and unsubscribes it on exit.""" 

251 queue = self.subscribe(initial_value=initial_value, maxsize=maxsize, overflow=overflow) 

252 

253 try: 

254 yield queue 

255 finally: 

256 self.unsubscribe(queue) 

257 

258 def notify(self, value: T): 

259 """Update the current value and notify all observers. 

260 

261 Delivery never blocks on a subscriber. A subscriber whose queue is full is handled 

262 by its overflow policy. 

263 

264 Raises: 

265 RuntimeError: If the observer is closed. 

266 """ 

267 if self._closed: 

268 raise RuntimeError("Cannot notify a closed observer") 

269 

270 self._value = value 

271 

272 # Closing an overflowing queue removes its subscription. 

273 for queue, overflow in list(self._observers.items()): 

274 try: 

275 queue.put_nowait(value) 

276 except asyncio.QueueFull: 

277 match overflow: 

278 case "drop_oldest": 

279 queue.get_nowait() 

280 queue.task_done() 

281 queue.put_nowait(value) 

282 self._dropped += 1 

283 

284 # A single-value queue keeps only the latest value by design. 

285 if queue.maxsize > 1: 

286 limited_logger().warning( 

287 f"observer queue full at {queue.maxsize}; dropping oldest value" 

288 ) 

289 case "close": 

290 del self._observers[queue] 

291 self._dropped += queue.qsize() + 1 

292 queue.shutdown(immediate=True) 

293 

294 limited_logger().warning( 

295 f"observer queue full at {queue.maxsize}; closing subscriber" 

296 ) 

297 

298 def close(self): 

299 """Permanently close the observer. 

300 

301 Discard pending values and wake subscribers with `asyncio.QueueShutDown`. 

302 The current value stays readable. Closing again has no effect. 

303 """ 

304 self._closed = True 

305 queues = list(self._observers) 

306 self._observers.clear() 

307 

308 for queue in queues: 

309 queue.shutdown(immediate=True) 

310 

311 @property 

312 def value(self) -> T: 

313 """Get the current value.""" 

314 if self._value is self.NOT_SET: 

315 raise RuntimeError("Observed value must be set prior to access") 

316 

317 return self._value 

318 

319 @property 

320 def subscriber_count(self) -> int: 

321 """The number of queues currently subscribed.""" 

322 return len(self._observers) 

323 

324 @property 

325 def dropped(self) -> int: 

326 """Values lost to overflow, including pending values discarded on overflow closure.""" 

327 return self._dropped 

328 

329 @property 

330 def closed(self) -> bool: 

331 """Whether the observer has been closed.""" 

332 return self._closed 

333 

334 async def consume( 

335 self, 

336 *, 

337 initial_value: bool = False, 

338 maxsize: int = DEFAULT_MAXSIZE, 

339 overflow: OverflowPolicy = "drop_oldest", 

340 ): 

341 """Yield successive values as an async generator, unsubscribing automatically on exit. 

342 

343 By default, iteration ends when the observer closes. With `overflow="close"`, 

344 queue shutdown raises `asyncio.QueueShutDown`. The `closed` property reports 

345 whether the observer itself has closed. 

346 """ 

347 queue = self.subscribe(initial_value=initial_value, maxsize=maxsize, overflow=overflow) 

348 

349 try: 

350 while True: 

351 item = await queue.get() 

352 

353 try: 

354 yield item 

355 finally: 

356 queue.task_done() 

357 except asyncio.QueueShutDown: 

358 if overflow == "close": 

359 raise 

360 finally: 

361 self.unsubscribe(queue) 

362 

363 

364class AsyncLoop: 

365 """Runs a function repeatedly on a fixed interval. 

366 

367 The interval is a plain attribute, so assigning to it retunes a running loop from 

368 its next sleep onward. 

369 """ 

370 

371 def __init__( 

372 self, 

373 func: Callable[[], Awaitable[None] | None], 

374 *, 

375 interval: float, 

376 log: bool = False, 

377 label: str | None = None, 

378 ): 

379 """Initialize the loop without starting it. 

380 

381 Args: 

382 func: Called once per iteration. Takes no arguments. 

383 interval: Seconds to sleep between iterations. 

384 log: Whether to log exceptions raised by `func`. 

385 label: Optional label for logging. 

386 """ 

387 self.func = func 

388 self.interval = interval 

389 self._log = log 

390 self._label = label or getattr(func, "__qualname__", str(func)) 

391 self._task: asyncio.Task | None = None 

392 

393 @property 

394 def active(self) -> bool: 

395 """Report whether the loop is currently running.""" 

396 return self._task is not None and not self._task.done() 

397 

398 def start(self) -> Self: 

399 """Start the loop, returning self. 

400 

401 Does nothing if the loop is already running, so callers that cannot easily 

402 tell may start it unconditionally. 

403 """ 

404 if not self.active: 

405 self._task = asyncio.create_task(self._run()) 

406 

407 return self 

408 

409 async def stop(self): 

410 """Cancel the loop and wait for it to unwind. 

411 

412 Safe to call on a loop that was never started, and on one already stopped. 

413 """ 

414 if self._task is None: 

415 return 

416 

417 task = self._task 

418 task.cancel() 

419 self._task = None 

420 

421 with contextlib.suppress(asyncio.CancelledError): 

422 await task 

423 

424 async def _run(self): 

425 while True: 

426 try: 

427 if coro := self.func(): 

428 await coro 

429 except Exception as e: 

430 if self._log: 

431 from loguru import logger 

432 

433 msg = f": {e}" if str(e) else "" 

434 logger.exception(f"{type(e).__name__} in {self._label} loop{msg}") 

435 

436 await asyncio.sleep(self.interval)