Coverage for core / src / sensorkit / backend / base.py: 99%

213 statements  

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

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import asyncio 

5import contextlib 

6import traceback 

7from abc import ABC, abstractmethod 

8from collections.abc import AsyncGenerator, AsyncIterator, Callable, Coroutine 

9from dataclasses import dataclass 

10from datetime import datetime 

11from enum import StrEnum 

12from typing import Any, ClassVar, Self 

13 

14from loguru import logger 

15from pydantic import BaseModel 

16 

17 

18class Backend: 

19 """Exposes a system backend implementation.""" 

20 

21 REPLY_TIMEOUT: ClassVar[float] = 1.0 

22 """Seconds a caller waits for the reply to a request. 

23 

24 Callers cannot extend it, so an unresponsive peer surfaces as an error rather than a longer 

25 wait. Work that takes longer belongs in a long-running request, whose progress events show 

26 that the handler is alive. 

27 """ 

28 

29 # TODO: Measure transit time and peer clock offset in the backend rather than assuming a margin. 

30 REPLY_MARGIN: ClassVar[float] = 0.1 

31 """Seconds of the reply budget reserved for reply transit and peer clock disagreement.""" 

32 

33 def __init__(self, impl: BackendImpl): 

34 self.impl = impl 

35 

36 async def register_service(self, info: ServiceInfo): 

37 """Announce a service session to the backend.""" 

38 return await self.impl.register_service(info) 

39 

40 async def shutdown_request_listeners(self): 

41 """Remove all registered request listeners from the backend.""" 

42 return await self.impl.request_purge_listeners() 

43 

44 def request(self, entity: Entity | None = None) -> RequestResponseContext: 

45 """Return a request-response context scoped to the given entity.""" 

46 return RequestResponseContext(self.impl, entity or Entity()) 

47 

48 def stream(self, entity: Entity | None = None) -> StreamContext: 

49 """Return a stream context scoped to the given entity.""" 

50 return StreamContext(self.impl, entity or Entity()) 

51 

52 def key_value(self, entity: Entity | None = None) -> KeyValueContext: 

53 """Return a key-value context scoped to the given entity.""" 

54 return KeyValueContext(self.impl, entity or Entity()) 

55 

56 

57class SpecialProperty(StrEnum): 

58 """Well-known subject property tokens used to address groups of keys or event streams.""" 

59 

60 ALL_PROPERTIES = "$ALL$" 

61 ALL_DESCENDANTS = "$WILDCARD$" 

62 EVENTS = "$EVENT$" 

63 NONE = "$NONE$" 

64 

65 

66@dataclass(slots=True, frozen=True, eq=True) 

67class Entity: 

68 """An addressable entity identified by a tuple of path segments.""" 

69 

70 path: tuple[str, ...] = () 

71 

72 @classmethod 

73 def at(cls, *path: str) -> Self: 

74 """Construct an Entity from individual path segments.""" 

75 return cls(path=path) 

76 

77 def subject(self, name: str) -> Subject: 

78 """Return a Subject for the named property on this entity.""" 

79 return Subject(self.path, name) 

80 

81 def __str__(self): 

82 return ".".join(self.path) 

83 

84 def __repr__(self): 

85 return f"Entity({repr(self.path)})" 

86 

87 

88@dataclass(slots=True, frozen=True, eq=True) 

89class Subject(Entity): 

90 """An entity path combined with a named property, forming a fully-qualified address.""" 

91 

92 prop: str | SpecialProperty = SpecialProperty.NONE 

93 

94 def full_path(self): 

95 """Return the complete path tuple including the property segment.""" 

96 return self.path + (self.prop,) 

97 

98 def entity(self): 

99 """Return the parent Entity, stripping the property segment.""" 

100 return Entity(self.path) 

101 

102 def __str__(self): 

103 return f"{".".join(self.path)}.{self.prop}" 

104 

105 def __repr__(self): 

106 return f"Subject({repr(self.path)}, {repr(self.prop)})" 

107 

108 

109# FIXME: This *Context class hierarchy should be collapsed so that only one need exist per entity. 

110# Differentiation between stream, kv, etc., operations can be achieved via Protocols. 

111@dataclass(slots=True, frozen=True) 

112class BaseContext(ABC): 

113 impl: BackendImpl 

114 entity: Entity 

115 

116 

117type RequestCallback = Callable[[bytes], Coroutine[Any, Any, bytes]] 

118 

119 

120class BackendError(Exception): 

121 """Indicates a backend communication error.""" 

122 

123 

124class ReplyTimeout(BackendError, TimeoutError): 

125 """Raised when the reply to a request does not arrive within the reply budget. 

126 

127 The handler may still have received and run the request. 

128 

129 Args: 

130 subject: The request subject. 

131 elapsed: Seconds the caller actually waited. 

132 """ 

133 

134 def __init__(self, subject: Subject, elapsed: float): 

135 super().__init__( 

136 f"no reply from {subject} within {Backend.REPLY_TIMEOUT} s (waited {elapsed:.1f} s)" 

137 ) 

138 self.elapsed = elapsed 

139 """Seconds the caller actually waited. Well past the budget, the caller itself stalled.""" 

140 

141 

142class RemoteRequestError(BackendError): 

143 """Indicates an error raised in the remote request handler.""" 

144 MAGIC: ClassVar[bytes] = b"ERR\0" 

145 

146 def __init__(self, *args, details: str | None = None): 

147 super().__init__(*args) 

148 self.details = details 

149 

150 @classmethod 

151 def parse(cls, name: str, data: bytes) -> Self | None: 

152 """Parse a response payload and return a RemoteRequestError if it contains the error magic prefix.""" 

153 if data.startswith(cls.MAGIC): 

154 _, message, *details = data.split(b"\0", maxsplit=2) 

155 decoded = message.decode("utf-8", errors="replace") 

156 return cls( 

157 f"Remote '{name}' request error: {decoded}", 

158 details=details[0].decode("utf-8", errors="replace") if details else None, 

159 ) 

160 

161 return None 

162 

163 @classmethod 

164 def from_exception(cls, err: BaseException) -> Self: 

165 """Construct a RemoteRequestError from an exception, capturing its traceback as details.""" 

166 return cls( 

167 f"{type(err).__name__}: {err}", 

168 details="".join(traceback.format_exception(type(err), err, err.__traceback__)), 

169 ) 

170 

171 def encode(self) -> bytes: 

172 """Encode this error into a wire-format bytes payload prefixed with the error magic.""" 

173 return ( 

174 self.MAGIC 

175 + str(self).replace("\0", "\ufffd").encode("utf-8", errors="replace") 

176 + (b"\0" + self.details.encode("utf-8", errors="replace") if self.details else b"") 

177 ) 

178 

179 

180class UnregisteredResponder(BackendError): 

181 """Raised when a request is made to a subject with no registered handler.""" 

182 

183 def __init__(self, subject: Subject): 

184 super().__init__(f"Remote `{subject.prop}` request error: responder for {subject} not registered") 

185 

186 

187@dataclass(slots=True, frozen=True) 

188class RequestResponseContext(BaseContext): 

189 """Exposes request-response methods of a backend implementation.""" 

190 

191 async def invoke(self, name: str, payload: bytes): 

192 """Send a request to the named subject and return the response bytes. 

193 

194 Raises: 

195 RemoteRequestError: if the remote handler returned an encoded error. 

196 ReplyTimeout: if no reply arrives within the reply budget. 

197 """ 

198 subject = self.entity.subject(name) 

199 loop = asyncio.get_running_loop() 

200 start = loop.time() 

201 

202 try: 

203 res = await self.impl.request_invoke(subject, payload, Backend.REPLY_TIMEOUT) 

204 except TimeoutError as e: 

205 raise ReplyTimeout(subject, loop.time() - start) from e 

206 

207 if err := RemoteRequestError.parse(name, res): 

208 logger.opt(lazy=True).debug( 

209 f"{err}{{details}}", 

210 details=lambda: "\n\t".join(["", *err.details.split("\n")] if err.details else []), 

211 ) 

212 raise err 

213 

214 return res 

215 

216 async def handle_request(self, name: str, callback: RequestCallback): 

217 """Register a callback to handle incoming requests for the named subject. 

218 

219 Errors raised by the callback are caught and returned to the caller as encoded 

220 RemoteRequestError payloads. 

221 """ 

222 async def _request_wrapper(payload: bytes): 

223 try: 

224 res = await callback(payload) 

225 except asyncio.CancelledError: 

226 logger.debug(f"dropping request {self.entity}.{name} due to cancellation") 

227 raise 

228 except Exception as e: 

229 logger.opt(exception=e).debug(f"error in {self.entity}.{name} request callback") 

230 res = RemoteRequestError.from_exception(e).encode() 

231 

232 return res 

233 

234 return await self.impl.request_listen(self.entity.subject(name), _request_wrapper) 

235 

236 

237@dataclass(slots=True, frozen=True) 

238class StreamContext(BaseContext): 

239 """Exposes stream methods of a backend implementation.""" 

240 

241 async def list_keys(self): 

242 """Return a coroutine that resolves to the list of stream subject keys for this entity.""" 

243 return await self.impl.stream_list(self.entity) 

244 

245 async def consume( 

246 self, 

247 key: str | None = None, 

248 *, 

249 durable_name: str | None = None, 

250 from_sequence: int | None = None, 

251 from_time: datetime | None = None, 

252 include_latest: bool = False, 

253 ): 

254 """Return a coroutine that resolves to an async iterator of StreamMessages. 

255 

256 If key is None, all properties for the entity are consumed. 

257 """ 

258 return await self.impl.stream_consume( 

259 self.entity.subject(key if key else SpecialProperty.ALL_PROPERTIES), 

260 durable_name=durable_name, 

261 start_at=from_time or from_sequence, 

262 include_latest=include_latest, 

263 ) 

264 

265 async def publish(self, key: str, payload: bytes): 

266 """Return a coroutine that publishes payload to the named stream subject.""" 

267 return await self.impl.stream_publish(self.entity.subject(key), payload) 

268 

269 async def publish_event(self, payload: bytes): 

270 """Return a coroutine that publishes payload to the entity's event stream subject.""" 

271 return await self.impl.stream_publish(self.entity.subject(SpecialProperty.EVENTS), payload) 

272 

273 

274@dataclass(slots=True, frozen=True) 

275class KeyValueContext(BaseContext): 

276 """Exposes key-value store methods of a backend implementation.""" 

277 

278 async def monitor_all(self, *, deep=False): 

279 """Return an async generator that yields KVEntry objects as keys are created or updated. 

280 

281 With deep=True, monitors all descendants rather than direct properties only. 

282 """ 

283 if deep: 

284 # FIXME: This option is expeditious at the moment, but can lead to a lot of duplicative 

285 # messages. In general, this backend code needs a major iteration to use multi- 

286 # plexing. Use of ALL_DESCENDANTS is generally problematic. Perhaps a client- 

287 # scoped option: set up a single "firehose" subscription and use a global multi- 

288 # plexer, or, disallow use of ALL_DESCENDANTS and use shared subscriptions per 

289 # entity, possibly via AsyncObserver. In the latter case, calling this method 

290 # with deep=True would raise. 

291 logger.debug("warning: monitor_all(deep=True) may cause excess traffic") 

292 

293 prop = SpecialProperty.ALL_DESCENDANTS if deep else SpecialProperty.ALL_PROPERTIES 

294 monitor = await self.impl.kv_monitor(self.entity.subject(prop)) 

295 

296 async def key_value_monitor(): 

297 async for batch in monitor: 

298 for entry in batch: 

299 yield entry 

300 

301 return key_value_monitor() 

302 

303 async def monitor(self, key: str): 

304 """Return an async generator that yields KVEntry objects for changes to the named key. 

305 

306 After iteration begins, closing the generator releases the backend subscription. 

307 """ 

308 monitor = await self.impl.kv_monitor(self.entity.subject(key)) 

309 

310 async def key_value_monitor(): 

311 async with contextlib.aclosing(monitor): 

312 async for batch in monitor: 

313 for entry in batch: 

314 yield entry 

315 

316 return key_value_monitor() 

317 

318 async def get_all(self, *, deep=False) -> list[KVEntry]: 

319 """Return all current (non-deleted) KV entries for this entity. 

320 

321 With deep=True, includes entries from descendant entities as well. 

322 """ 

323 prop = SpecialProperty.ALL_DESCENDANTS if deep else SpecialProperty.ALL_PROPERTIES 

324 subject = self.entity.subject(prop) 

325 out = [] 

326 

327 # Monitor for a single batch, which are the current values. 

328 async for batch in await self.impl.kv_monitor(subject): 

329 for entry in batch: 

330 if not entry.deleted(): 

331 out.append(entry) 

332 

333 break 

334 

335 return out 

336 

337 async def get(self, key: str): 

338 """Fetch the current KVEntry for the named key.""" 

339 return await self.impl.kv_get(self.entity.subject(key)) 

340 

341 async def create( 

342 self, 

343 key: str, 

344 value: bytes, 

345 *, 

346 ttl: float | None = None, 

347 ): 

348 """Create a new KV entry. Raises if the key already exists.""" 

349 return await self.impl.kv_create(self.entity.subject(key), value, ttl) 

350 

351 async def update( 

352 self, 

353 key: str, 

354 value: bytes, 

355 *, 

356 revision: int | None = None, 

357 ttl: float | None = None, 

358 ): 

359 """Update an existing KV entry, optionally requiring a specific revision.""" 

360 return await self.impl.kv_update(self.entity.subject(key), value, revision, ttl) 

361 

362 async def delete( 

363 self, 

364 key: str, 

365 *, 

366 revision: int | None = None, 

367 ): 

368 """Delete the KV entry for the named key, optionally requiring a specific revision.""" 

369 await self.impl.kv_delete(self.entity.subject(key), revision) 

370 

371 

372@dataclass(slots=True, frozen=True, eq=True) 

373class KVEntry: 

374 """A single key-value store entry.""" 

375 key: Subject 

376 value: bytes 

377 revision: int 

378 

379 DELETE_MARKER: ClassVar[bytes] = b"DELETED" 

380 """Sentinel value denoting a deleted KV entry.""" 

381 

382 def deleted(self): 

383 """Return True if this entry has been marked as deleted.""" 

384 return self.value is KVEntry.DELETE_MARKER 

385 

386 

387class KVError(BackendError): 

388 """Base class for key-value store errors.""" 

389 

390 

391class RevisionError(KVError): 

392 """Raised when a KV update or delete is rejected due to a revision mismatch.""" 

393 

394 

395class KeyNotFound(KVError): 

396 """Raised when a requested KV key does not exist.""" 

397 

398 def __init__(self, subject: Subject, *, deleted: bool): 

399 super().__init__(f"key for `{subject}` not found") 

400 self.deleted = deleted 

401 

402 

403class ServiceInfo(BaseModel): 

404 """Information about a service.""" 

405 name: str 

406 version: str 

407 

408 

409@dataclass(slots=True, frozen=True, eq=True) 

410class StreamMessage: 

411 """A message read from a stream, including its subject, sequence number, timestamp, and payload.""" 

412 

413 subject: Subject 

414 sequence: int 

415 timestamp: datetime 

416 data: bytes 

417 

418 

419class BackendImpl(ABC): 

420 """Interface providing access to a backend.""" 

421 

422 @classmethod 

423 @abstractmethod 

424 async def create(cls, *args, **kwargs) -> BackendImpl: 

425 """Factory to create a BackendImpl instance.""" 

426 

427 async def register_service(self, info: ServiceInfo): 

428 """Notify the backend of a new service session. Optional method.""" 

429 

430 @abstractmethod 

431 async def request_invoke(self, target: Subject, payload: bytes, timeout: float) -> bytes: 

432 """Invoke a request. 

433 

434 Raises: 

435 TimeoutError: if no reply arrives within timeout seconds. The handler keeps running. 

436 """ 

437 

438 @abstractmethod 

439 async def request_listen(self, target: Subject, coro: RequestCallback): 

440 """Listen for requests.""" 

441 

442 @abstractmethod 

443 async def request_purge_listeners(self): 

444 """Remove all request listeners.""" 

445 

446 @abstractmethod 

447 async def stream_list(self, entity: Entity) -> list[Subject]: 

448 """List defined stream subjects for an entity.""" 

449 

450 @abstractmethod 

451 async def stream_publish(self, target: Subject, payload: bytes): 

452 """Publish to a stream subject.""" 

453 

454 @abstractmethod 

455 async def stream_consume( 

456 self, 

457 target: Subject, 

458 *, 

459 durable_name: str | None = None, 

460 start_at: int | datetime | None = None, 

461 include_latest: bool = False, 

462 ) -> AsyncIterator[StreamMessage]: 

463 """Consume a stream subject.""" 

464 

465 @abstractmethod 

466 async def kv_monitor(self, target: Subject) -> AsyncGenerator[list[KVEntry]]: 

467 """Subscribe to KV modifications for the given entity. 

468 

469 The first batch holds the current entries. 

470 After iteration begins, closing the generator releases the subscription. 

471 """ 

472 

473 @abstractmethod 

474 async def kv_get(self, target: Subject) -> KVEntry: 

475 """Return the value associated with a key.""" 

476 

477 @abstractmethod 

478 async def kv_create( 

479 self, 

480 target: Subject, 

481 payload: bytes, 

482 ttl: float | None = None, 

483 ) -> KVEntry: 

484 """Create a KV record.""" 

485 

486 @abstractmethod 

487 async def kv_update( 

488 self, 

489 target: Subject, 

490 payload: bytes, 

491 revision: int | None = None, 

492 ttl: float | None = None, 

493 ) -> KVEntry: 

494 """Update a KV record.""" 

495 

496 @abstractmethod 

497 async def kv_delete(self, target: Subject, revision: int | None = None): 

498 """Delete a KV record."""