Coverage for core / src / sensorkit / core / entity.py: 95%
255 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 functools
7from abc import ABC, abstractmethod
8from typing import TYPE_CHECKING, Annotated, Literal, Self, overload
10from loguru import logger
11from pydantic import (
12 BaseModel,
13 Field,
14 PlainSerializer,
15 PlainValidator,
16 StringConstraints,
17 ValidationError,
18 model_validator,
19)
21from sensorkit.backend.base import Entity, KeyNotFound
22from sensorkit.backend.event import Event, EventMultiplexer, EventStreamConsumer
23from sensorkit.backend.request import (
24 Call,
25 RequestBase,
26 RequestHandlerFunc,
27)
28from sensorkit.common.aio import AsyncObserver
29from sensorkit.common.keyword import (
30 Keyword,
31 declare_keyword,
32 get_keyword_info,
33 validate_keyword_json,
34)
35from sensorkit.core.trait import Archetype, get_trait, match_traits
36from sensorkit.data.graph import DataGraph
38if TYPE_CHECKING:
39 from sensorkit.core.client import SensorKit
41type EntityType = Literal["generic", "device", "controller", "program"]
44class EntityDetails(BaseModel):
45 """Capabilities advertised by an entity."""
47 published_keywords: frozenset[str] = frozenset()
48 """Identifiers of keywords this entity can publish."""
51class DeviceDetails(EntityDetails):
52 """Device identity and advertised capabilities."""
54 archetype: str | None = None
55 """Declared principal archetype, or None when omitted."""
57 supported_commands: frozenset[str]
58 """Identifiers of each command supported by this device."""
60 def get_archetype(self) -> Archetype | None:
61 """Return the declared archetype if registered locally, otherwise None."""
62 archetype = get_trait(self.archetype) if self.archetype is not None else None
63 return archetype if isinstance(archetype, Archetype) else None
65 @functools.cached_property
66 def traits(self):
67 return match_traits(self)
70@declare_keyword(key="Instrument")
71class InstrumentInfo(BaseModel):
72 """Controller instrument metadata, available in capture context as `Instrument`."""
74 name: str = Field(min_length=1)
75 """Case-sensitive name used to select this instrument in controller tasks."""
76 devices: tuple[str, ...] = ()
77 """Optional opaque device IDs. Their order has no meaning."""
79 def get_fits_cards(self):
80 """Yield the controller instrument name as INSTRUME."""
81 yield "INSTRUME", (self.name, "Instrument name")
84class ControllerDetails(EntityDetails):
85 """Controller info."""
87 supported_tasks: list[str]
88 """Identifiers of each task supported by this controller."""
89 controlled_devices: list[str]
90 """Names of each device commanded by this controller."""
91 instruments: tuple[InstrumentInfo, ...] = ()
92 """Instruments available for task selection."""
94 @model_validator(mode="after")
95 def _check_instruments(self) -> Self:
96 names = {instrument.name for instrument in self.instruments}
98 if len(names) != len(self.instruments):
99 raise ValueError("Instrument names must be unique")
101 return self
104@declare_keyword
105class EntityInfo(BaseModel):
106 """Keyword describing an entity's type and capability details, stored in the KV backend."""
108 entity_type: EntityType
109 details: DeviceDetails | ControllerDetails | EntityDetails | None
112class EntityBase:
113 """Base object that represents an entity exposed via a backend."""
115 def __init__(self, sensorkit: SensorKit, entity: Entity):
116 self._sensorkit = sensorkit
117 self.backend = sensorkit.backend
118 self.entity = entity
120 def sensorkit(self) -> SensorKit:
121 """Return the SensorKit instance backing this entity."""
122 return self._sensorkit
124 @functools.cached_property
125 def _request(self):
126 return self.backend.request(self.entity)
128 @functools.cached_property
129 def _stream(self):
130 return self.backend.stream(self.entity)
132 @functools.cached_property
133 def _kv(self):
134 return self.backend.key_value(self.entity)
136 async def kv_put_model(self, model: BaseModel):
137 """Serialize model to JSON and write it to the KV store under its class name."""
138 await self._kv.update(
139 key=model.__class__.__name__,
140 value=model.model_dump_json().encode(),
141 )
143 async def kv_get_model[M: BaseModel](self, model_type: type[M]) -> M:
144 """Fetch and deserialize a model from the KV store by its class name."""
145 entry = await self._kv.get(model_type.__name__)
146 return model_type.model_validate_json(entry.value)
148 async def kv_monitor_model[M: BaseModel](self, model_type: type[M], *, strict: bool = False):
149 """Monitor changes to a model in the KV store by its class name.
151 Yields the current model, if any, then each update. Deletions are skipped.
152 Closing the generator releases its subscription.
154 Args:
155 model_type: The model stored under its class name.
156 strict: Whether invalid entries raise rather than being skipped.
158 Raises:
159 ValidationError: If `strict` is set and an entry is invalid.
160 """
161 stream = await self._kv.monitor(model_type.__name__)
163 async with contextlib.aclosing(stream):
164 async for entry in stream:
165 if entry.deleted():
166 continue
168 try:
169 model = model_type.model_validate_json(entry.value)
170 except ValidationError:
171 if strict:
172 raise
174 continue
176 yield model
179class EntityClient(EntityBase):
180 """Object that exposes client-side functionality of an entity."""
182 def __init__(self, sensorkit: SensorKit, entity: Entity):
183 super().__init__(sensorkit, entity)
184 self._online_monitor: asyncio.Task | None = None
185 self._online_observer = AsyncObserver(False)
186 self._event_mux = EventStreamConsumer(self._stream)
188 async def get_details(self) -> EntityDetails:
189 """Fetch the entity's current advertised details.
191 Raises:
192 KeyNotFound: The entity has no stored metadata.
193 ValueError: The metadata has no entity details.
194 """
195 info = await self.kv_get_model(EntityInfo)
197 if info.details is None:
198 raise ValueError(f"Entity '{self.entity}' has no advertised details")
200 return info.details
202 async def _monitor_online_state(self):
203 stream = await self._kv.monitor("EntityLease")
205 async for entry in stream:
206 online = not entry.deleted()
208 if self._online_observer.value != online:
209 logger.debug(f"{self.entity} is now {'offline' if entry.deleted() else 'online'}")
210 self._online_observer.notify(online)
212 def observe_online_state(self):
213 """Return an async generator that yields True/False as the entity comes online or goes offline."""
214 if not self._online_monitor:
215 self._online_monitor = asyncio.create_task(self._monitor_online_state())
217 return self._online_observer.consume(initial_value=True)
219 async def is_online(self) -> bool:
220 """Return whether the entity currently holds its lease."""
221 try:
222 entry = await self._kv.get("EntityLease")
223 except KeyNotFound:
224 return False
226 return not entry.deleted()
228 def get_event_mux(self) -> EventMultiplexer:
229 """Return the shared event consumer object for this entity."""
230 return self._event_mux
232 async def subscribe_events(self):
233 """Wait until the entity's shared event subscription is live, starting it if needed.
235 Once this returns, `monitor_event_nowait` and long-running calls attach to the entity's
236 events without suspending, so no event published after attaching is missed. The
237 subscription stays live for the life of the client.
239 Raises:
240 BackendError: If the subscription failed to start.
241 """
242 await self._event_mux.wait_ready()
244 @staticmethod
245 async def _monitor_receive[M: Event](queue: asyncio.Queue[M], context: contextlib.ExitStack):
246 with context:
247 while True:
248 yield await queue.get()
249 queue.task_done()
251 async def _await_event_consumer(self, context: contextlib.ExitStack):
252 """Wait until the entity's event subscription is live, releasing the queue on failure."""
253 try:
254 await self._event_mux.wait_ready()
255 except BaseException:
256 context.close()
257 raise
259 async def monitor_event[M: Event](self, event_type: type[M]):
260 """Return an async generator yielding events of the specified type from the entity's stream."""
261 consumer = self._event_mux
262 context = contextlib.ExitStack()
263 queue: asyncio.Queue[M] = context.enter_context(consumer.event_queue(event_type))
265 await self._await_event_consumer(context)
267 return self._monitor_receive(queue, context)
269 def monitor_event_nowait[M: Event](self, event_type: type[M]):
270 """Return an async generator yielding events of the specified type from the entity's stream.
272 Attaches without suspending, so the caller misses no event published after this returns.
274 Raises:
275 EventsNotSubscribed: If `subscribe_events` has not completed.
276 BackendError: If the subscription failed to start.
277 """
278 if not self._event_mux.ready():
279 raise EventsNotSubscribed(f"{self.entity} events are not subscribed")
281 context = contextlib.ExitStack()
282 queue: asyncio.Queue[M] = context.enter_context(self._event_mux.event_queue(event_type))
284 return self._monitor_receive(queue, context)
286 async def monitor_all_events(self):
287 """Return an async generator yielding all events from the entity's stream."""
288 consumer = self._event_mux
289 context = contextlib.ExitStack()
290 queue = context.enter_context(consumer.all_events())
292 await self._await_event_consumer(context)
294 return self._monitor_receive(queue, context)
296 async def monitor[M: Keyword | BaseModel](self, model_type: type[M]):
297 """Return an async generator yielding (subject, model) tuples for the given keyword or model type.
299 The subscription is live when this returns. Closing a started generator releases it.
300 """
301 key = info.key if (info := get_keyword_info(model_type)) else None
303 if key is not None:
304 validate_func = functools.partial(validate_keyword_json, key)
305 else:
306 validate_func = model_type.model_validate_json
308 consumer = await self._stream.consume(key, include_latest=True)
310 async def receive_data():
311 async with contextlib.aclosing(consumer):
312 async for msg in consumer:
313 try:
314 model: M = validate_func(msg.data)
315 yield msg.subject, model
316 except ValidationError:
317 logger.exception("Data validation failed")
318 except Exception:
319 logger.exception("Error while monitoring")
321 return receive_data()
323 async def monitor_all(self):
324 """Return an async generator yielding (subject, model) tuples for all keyword updates on this entity."""
325 consumer = await self._stream.consume(include_latest=True)
327 async def receive_data():
328 async for msg in consumer:
329 try:
330 model = validate_keyword_json(msg.subject.prop, msg.data)
331 except ValidationError:
332 logger.exception("Data validation failed")
333 continue
335 try:
336 yield msg.subject, model
337 except Exception:
338 logger.exception("Error while monitoring")
340 return receive_data()
342 async def request[M: BaseModel](self, name: str, data: BaseModel, response_type: type[M]) -> M:
343 """Send a named raw request and return the deserialised response."""
344 received = await self._request.invoke(
345 name=name,
346 payload=data.model_dump_json().encode(),
347 )
348 return response_type.model_validate_json(received)
350 @overload
351 def call[R: BaseModel | None, V: BaseModel | None](
352 self,
353 request: RequestBase[None, R, V],
354 ) -> Call[R, V]:
355 """Invoke a request that takes no message."""
357 @overload
358 def call[P: BaseModel, R: BaseModel | None, V: BaseModel | None](
359 self,
360 request: RequestBase[P, R, V],
361 data: P,
362 ) -> Call[R, V]:
363 """Invoke a request, sending it the given message."""
365 def call(self, request, data = None) -> Call:
366 """Invoke a request."""
367 return request.create_call(self._request, data, self._event_mux)
370class EventsNotSubscribed(Exception):
371 """Raised when attaching to an entity's events without suspending before they are subscribed."""
374class EntityRef[T: EntityClient = EntityClient]:
375 """A serializable reference to an entity client.
377 Model fields accept a nonempty name or a named instance of the declared class.
378 Optional fields also accept `None`. Existing instances retain their resolved client.
379 """
381 name: str | None
383 def __init__(self, name: str | None = None):
384 """Create a reference from an entity name.
386 Args:
387 name: the serialized entity name, or `None` for an unset reference.
388 """
389 self.name = name
390 self._client: T | None = None
392 def _get_client(self, kit: SensorKit) -> T:
393 """Return the client of the appropriate type for this reference."""
394 return kit.entity(self.name)
396 def resolve(self, kit: SensorKit) -> None:
397 """Resolve this reference against a SensorKit instance.
399 If `name` is set, caches the corresponding entity client for later access via
400 `get`, `require`, or `__call__`.
401 """
402 if self.name is not None:
403 self._client = self._get_client(kit)
405 def get(self) -> T | None:
406 """Return the resolved client, or `None` if the reference is unset.
408 Raises:
409 RuntimeError: if the reference has a name but has not yet been resolved.
410 """
411 if self.name is not None and self._client is None:
412 raise RuntimeError("Entity reference not resolved")
413 return self._client
415 def require(self) -> T:
416 """Return the resolved client, requiring that the reference be usable.
418 Raises:
419 RuntimeError: if the reference is unset or has not been resolved.
420 """
421 obj = self.get()
422 if obj is None:
423 raise RuntimeError("Required entity reference was not defined")
424 return obj
426 def __call__(self) -> T | None:
427 """Convenience accessor for `get`."""
428 return self.get()
430 def __eq__(self, other: object) -> bool:
431 """Compare references by the entity they name."""
432 return isinstance(other, EntityRef) and self.name == other.name
434 def __hash__(self) -> int:
435 return hash(self.name)
437 def __repr__(self) -> str:
438 return f"{type(self).__name__}({self.name!r})"
440 @classmethod
441 def __get_pydantic_core_schema__(cls, _source_type, handler):
442 def validate_ref(obj):
443 match obj:
444 case str() if obj:
445 return cls(name=obj)
446 case cls(name=str(name)) if name:
447 return obj
448 case str() | cls() | None:
449 raise ValueError("A nonempty entity name is required")
450 case _:
451 raise ValueError(f"Expected an entity name or {cls.__name__}")
453 name_type = Annotated[str, StringConstraints(min_length=1)]
454 return handler(
455 Annotated[
456 str,
457 PlainValidator(validate_ref, json_schema_input_type=name_type),
458 PlainSerializer(lambda obj: obj.name, return_type=name_type),
459 ]
460 )
463class EntityInterface(ABC):
464 """Interface describing an implementation of an entity."""
466 @abstractmethod
467 def sensorkit(self) -> SensorKit:
468 """Return the SensorKit instance backing this entity."""
469 ...
471 @abstractmethod
472 def declare_published_keyword(self, keyword_id: str) -> None:
473 """Declare a keyword this entity can publish.
475 After attachment, call `publish_entity_info()` to advertise changes.
476 """
477 ...
479 @property
480 @abstractmethod
481 def task_group(self) -> asyncio.TaskGroup:
482 """Return the TaskGroup used for background tasks on this entity."""
483 ...
485 @abstractmethod
486 async def kv_put_model(self, model: BaseModel):
487 """Serialize model and write it to the KV store."""
488 ...
490 @abstractmethod
491 async def kv_get_model[M: BaseModel](self, model_type: type[M]) -> M:
492 """Fetch and deserialize a model from the KV store."""
493 ...
495 @abstractmethod
496 async def emit_event(self, event: Event):
497 """Publish an event to the entity's event stream."""
498 ...
500 @abstractmethod
501 async def publish(self, model: Keyword):
502 """Publish a keyword model to the entity's data stream."""
503 ...
505 @abstractmethod
506 async def handle_request[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None](
507 self,
508 request: RequestBase[P, R, V],
509 func: RequestHandlerFunc[P, R, V],
510 ):
511 """Register a handler for the given Request declaration."""
512 ...
514 @abstractmethod
515 async def data_graph(self) -> DataGraph:
516 """Return the DataGraph for this entity, creating it if necessary."""
517 ...
519 @abstractmethod
520 async def publish_entity_info(self) -> EntityInfo:
521 """Build and publish EntityInfo to the KV store."""
522 ...