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
« 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
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
14from loguru import logger
15from pydantic import BaseModel
18class Backend:
19 """Exposes a system backend implementation."""
21 REPLY_TIMEOUT: ClassVar[float] = 1.0
22 """Seconds a caller waits for the reply to a request.
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 """
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."""
33 def __init__(self, impl: BackendImpl):
34 self.impl = impl
36 async def register_service(self, info: ServiceInfo):
37 """Announce a service session to the backend."""
38 return await self.impl.register_service(info)
40 async def shutdown_request_listeners(self):
41 """Remove all registered request listeners from the backend."""
42 return await self.impl.request_purge_listeners()
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())
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())
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())
57class SpecialProperty(StrEnum):
58 """Well-known subject property tokens used to address groups of keys or event streams."""
60 ALL_PROPERTIES = "$ALL$"
61 ALL_DESCENDANTS = "$WILDCARD$"
62 EVENTS = "$EVENT$"
63 NONE = "$NONE$"
66@dataclass(slots=True, frozen=True, eq=True)
67class Entity:
68 """An addressable entity identified by a tuple of path segments."""
70 path: tuple[str, ...] = ()
72 @classmethod
73 def at(cls, *path: str) -> Self:
74 """Construct an Entity from individual path segments."""
75 return cls(path=path)
77 def subject(self, name: str) -> Subject:
78 """Return a Subject for the named property on this entity."""
79 return Subject(self.path, name)
81 def __str__(self):
82 return ".".join(self.path)
84 def __repr__(self):
85 return f"Entity({repr(self.path)})"
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."""
92 prop: str | SpecialProperty = SpecialProperty.NONE
94 def full_path(self):
95 """Return the complete path tuple including the property segment."""
96 return self.path + (self.prop,)
98 def entity(self):
99 """Return the parent Entity, stripping the property segment."""
100 return Entity(self.path)
102 def __str__(self):
103 return f"{".".join(self.path)}.{self.prop}"
105 def __repr__(self):
106 return f"Subject({repr(self.path)}, {repr(self.prop)})"
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
117type RequestCallback = Callable[[bytes], Coroutine[Any, Any, bytes]]
120class BackendError(Exception):
121 """Indicates a backend communication error."""
124class ReplyTimeout(BackendError, TimeoutError):
125 """Raised when the reply to a request does not arrive within the reply budget.
127 The handler may still have received and run the request.
129 Args:
130 subject: The request subject.
131 elapsed: Seconds the caller actually waited.
132 """
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."""
142class RemoteRequestError(BackendError):
143 """Indicates an error raised in the remote request handler."""
144 MAGIC: ClassVar[bytes] = b"ERR\0"
146 def __init__(self, *args, details: str | None = None):
147 super().__init__(*args)
148 self.details = details
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 )
161 return None
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 )
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 )
180class UnregisteredResponder(BackendError):
181 """Raised when a request is made to a subject with no registered handler."""
183 def __init__(self, subject: Subject):
184 super().__init__(f"Remote `{subject.prop}` request error: responder for {subject} not registered")
187@dataclass(slots=True, frozen=True)
188class RequestResponseContext(BaseContext):
189 """Exposes request-response methods of a backend implementation."""
191 async def invoke(self, name: str, payload: bytes):
192 """Send a request to the named subject and return the response bytes.
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()
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
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
214 return res
216 async def handle_request(self, name: str, callback: RequestCallback):
217 """Register a callback to handle incoming requests for the named subject.
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()
232 return res
234 return await self.impl.request_listen(self.entity.subject(name), _request_wrapper)
237@dataclass(slots=True, frozen=True)
238class StreamContext(BaseContext):
239 """Exposes stream methods of a backend implementation."""
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)
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.
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 )
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)
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)
274@dataclass(slots=True, frozen=True)
275class KeyValueContext(BaseContext):
276 """Exposes key-value store methods of a backend implementation."""
278 async def monitor_all(self, *, deep=False):
279 """Return an async generator that yields KVEntry objects as keys are created or updated.
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")
293 prop = SpecialProperty.ALL_DESCENDANTS if deep else SpecialProperty.ALL_PROPERTIES
294 monitor = await self.impl.kv_monitor(self.entity.subject(prop))
296 async def key_value_monitor():
297 async for batch in monitor:
298 for entry in batch:
299 yield entry
301 return key_value_monitor()
303 async def monitor(self, key: str):
304 """Return an async generator that yields KVEntry objects for changes to the named key.
306 After iteration begins, closing the generator releases the backend subscription.
307 """
308 monitor = await self.impl.kv_monitor(self.entity.subject(key))
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
316 return key_value_monitor()
318 async def get_all(self, *, deep=False) -> list[KVEntry]:
319 """Return all current (non-deleted) KV entries for this entity.
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 = []
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)
333 break
335 return out
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))
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)
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)
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)
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
379 DELETE_MARKER: ClassVar[bytes] = b"DELETED"
380 """Sentinel value denoting a deleted KV entry."""
382 def deleted(self):
383 """Return True if this entry has been marked as deleted."""
384 return self.value is KVEntry.DELETE_MARKER
387class KVError(BackendError):
388 """Base class for key-value store errors."""
391class RevisionError(KVError):
392 """Raised when a KV update or delete is rejected due to a revision mismatch."""
395class KeyNotFound(KVError):
396 """Raised when a requested KV key does not exist."""
398 def __init__(self, subject: Subject, *, deleted: bool):
399 super().__init__(f"key for `{subject}` not found")
400 self.deleted = deleted
403class ServiceInfo(BaseModel):
404 """Information about a service."""
405 name: str
406 version: str
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."""
413 subject: Subject
414 sequence: int
415 timestamp: datetime
416 data: bytes
419class BackendImpl(ABC):
420 """Interface providing access to a backend."""
422 @classmethod
423 @abstractmethod
424 async def create(cls, *args, **kwargs) -> BackendImpl:
425 """Factory to create a BackendImpl instance."""
427 async def register_service(self, info: ServiceInfo):
428 """Notify the backend of a new service session. Optional method."""
430 @abstractmethod
431 async def request_invoke(self, target: Subject, payload: bytes, timeout: float) -> bytes:
432 """Invoke a request.
434 Raises:
435 TimeoutError: if no reply arrives within timeout seconds. The handler keeps running.
436 """
438 @abstractmethod
439 async def request_listen(self, target: Subject, coro: RequestCallback):
440 """Listen for requests."""
442 @abstractmethod
443 async def request_purge_listeners(self):
444 """Remove all request listeners."""
446 @abstractmethod
447 async def stream_list(self, entity: Entity) -> list[Subject]:
448 """List defined stream subjects for an entity."""
450 @abstractmethod
451 async def stream_publish(self, target: Subject, payload: bytes):
452 """Publish to a stream subject."""
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."""
465 @abstractmethod
466 async def kv_monitor(self, target: Subject) -> AsyncGenerator[list[KVEntry]]:
467 """Subscribe to KV modifications for the given entity.
469 The first batch holds the current entries.
470 After iteration begins, closing the generator releases the subscription.
471 """
473 @abstractmethod
474 async def kv_get(self, target: Subject) -> KVEntry:
475 """Return the value associated with a key."""
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."""
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."""
496 @abstractmethod
497 async def kv_delete(self, target: Subject, revision: int | None = None):
498 """Delete a KV record."""