Coverage for core / src / sensorkit / data / context.py: 96%
125 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 builtins
6from datetime import UTC, datetime
7from types import MappingProxyType
8from typing import TYPE_CHECKING, Any, Unpack, overload, override
10from pydantic import BaseModel
12from sensorkit.common.keyword import CompositeKeyword, KeywordDict, get_keyword_type
13from sensorkit.core.trait import trait_keyword_ids
15if TYPE_CHECKING:
16 from sensorkit.core.entity import DeviceDetails, EntityClient
18_SAFE_BUILTINS = {
19 "__import__": builtins.__import__,
20 "format": format,
21 "str": str,
22 "int": int,
23 "float": float,
24 "bool": bool,
25 "round": round,
26 "len": len,
27 "min": min,
28 "max": max,
29 "abs": abs,
30}
32_EVAL_GLOBALS = {"__builtins__": _SAFE_BUILTINS, "datetime": datetime, "UTC": UTC}
33_MISSING = object()
34_FSTRING_OPENERS = ('f"', "f'", 'F"', "F'")
37def _raw_fstring_source(value: str) -> str:
38 """Build source that evaluates `value` as a raw f-string template.
40 The value is embedded in a triple-double-quoted raw f-string, so backslashes stay
41 literal while `{...}` still interpolates. Trailing backslashes or quotes cannot safely
42 abut the closing delimiter (a raw literal cannot end in an odd backslash run, and a
43 trailing quote would merge with it), so they are peeled off and re-appended verbatim
44 via concatenation. A triple-quote embedded mid-value is unsupported and surfaces as a
45 `SyntaxError` when the source is evaluated.
47 Args:
48 value: Template text containing one or more `{...}` fields.
50 Returns:
51 Python source that evaluates to the rendered string.
52 """
53 end = len(value)
55 while end and value[end - 1] in '\\"':
56 end -= 1
58 source = f'rf"""{value[:end]}"""'
60 if end < len(value):
61 source += f" + {value[end:]!r}"
63 return source
66class Context(KeywordDict):
67 """A `KeywordDict` read view that expands composite keywords.
69 A `KeywordDict` stores only what is explicitly set, so its serialized form stays minimal.
70 A `Context` is the resolvable view over that data: as keywords enter it, any
71 `CompositeKeyword` also makes its composed keywords available under their own keys, so a
72 consumer can look up (and `eval` against) a composed keyword without knowing which
73 composite carried it. Expansion happens eagerly on every write path — construction,
74 `set`, and `update` — because the data pipeline mutates a context in flight, so a
75 one-shot expand at construction would not hold.
77 A `Context` source is trusted to already be expanded; any other source (a bare
78 `KeywordDict`, an iterable of items from deserialization, keyword arguments) is expanded on
79 the way in.
80 """
82 def __init__(
83 self,
84 arg: Any = None,
85 *objs: Unpack[tuple[object, ...]],
86 ):
87 super().__init__(arg, *objs)
89 if not isinstance(arg, Context):
90 self._expand_all()
92 @override
93 def update(self, other):
94 super().update(other)
96 # Expand only what `other` just contributed.
97 if not isinstance(other, Context):
98 self._expand_values(other.values())
100 @override
101 def set_keyword(self, obj):
102 if isinstance(obj, CompositeKeyword):
103 self._expand(obj, {id(obj)})
105 super().set_keyword(obj)
107 def _expand_all(self):
108 self._expand_values(self.values())
110 def _expand_values(self, values):
111 for value in list(values):
112 if isinstance(value, CompositeKeyword):
113 self._expand(value, {id(value)})
115 def _expand(self, obj: CompositeKeyword, visited: set[int]):
116 # Traverse composed keywords, storing each under its own key. Calling the base
117 # setter avoids repeating expansion through this class's `set_keyword`.
118 for composed in obj.composed_keywords():
119 if id(composed) in visited:
120 continue
122 visited.add(id(composed))
124 if isinstance(composed, CompositeKeyword):
125 self._expand(composed, visited)
127 super().set_keyword(composed)
129 def eval(self, expr: str, *, default: object = _MISSING):
130 """Evaluate a Python expression with this Context as the namespace.
132 Names in the expression resolve against this Context's keys.
134 Args:
135 expr: The Python expression to evaluate.
136 default: Value returned if `expr` references a name absent from the Context.
137 If omitted, a missing name raises `NameError`. Only missing names are
138 caught; any other error (such as a bad format spec on a present value)
139 always propagates.
141 Returns:
142 The expression result, keeping its native type.
144 Raises:
145 NameError: A referenced name is absent and no `default` was given.
146 """
147 try:
148 return eval(expr, _EVAL_GLOBALS, self)
149 except NameError:
150 if default is _MISSING:
151 raise
153 return default
155 @overload
156 def resolve[T](self, value: str | None, *, as_type: type[T], default: T = ...) -> T: ...
158 @overload
159 def resolve(self, value: str | None, *, default: object = ...) -> object: ...
161 def resolve(self, value: str | None, *, as_type = _MISSING, default = _MISSING):
162 r"""Resolve a config string against this Context.
164 The form of `value` selects how it is interpreted:
166 - `=<expr>`: evaluate the remainder as a Python expression (see `eval`), keeping
167 its native type, e.g. `=File.path.name.upper()` or `=frame_num + 1`.
168 - `f"..."` or `F"..."`: evaluate as that f-string, yielding a string. Use this form
169 when escape sequences should be processed, e.g. `f"line\n{frame_num}"`.
170 - text containing `{...}`: evaluate as a raw f-string template, so fields
171 interpolate with full expression power while backslashes stay literal, e.g.
172 `C:\Temp\{frame_num}.fits`. Write `{{` or `}}` for a literal brace.
173 - anything else: literal text returned verbatim, e.g. `C:\Temp`.
175 Args:
176 value: The config string to resolve.
177 as_type: If given, raise TypeError if the resolved value is not of this type.
178 default: The resolved value if a referenced name is absent (see `eval`) or if
179 the input value is None.
181 Returns:
182 The resolved value: native type for `=<expr>`, a string for the f-string and
183 template forms, or the original text for a literal.
185 Raises:
186 TypeError: if `as_type` is given and the resolved value is not of that type.
187 """
188 if value is None:
189 if default is _MISSING:
190 raise TypeError("cannot resolve None without default")
192 value = default
193 elif value.startswith("="):
194 value = self.eval(value[1:], default=default)
195 elif value.startswith(_FSTRING_OPENERS):
196 value = self.eval(value, default=default)
197 elif "{" in value:
198 value = self.eval(_raw_fstring_source(value), default=default)
200 if as_type is not _MISSING and not isinstance(value, as_type):
201 raise TypeError(f"expected {as_type.__name__}, got {type(value).__name__}")
203 return value
206def merge_contexts(*contexts: KeywordDict | None) -> Context:
207 """A fresh context holding each given one in turn.
209 A later one wins where two set the same keyword, so contexts listed root
210 first along a chain of devices leave the deepest publisher's value. None is
211 passed over. Nothing given is modified, and none of them is the result.
213 Args:
214 *contexts: What to merge, lowest precedence first.
216 Returns:
217 A new context.
218 """
219 merged = Context()
221 for context in contexts:
222 if context is not None:
223 merged.update(context)
225 return merged
228class ContextSubscription:
229 """Subscribe to device keyword updates and produce Context snapshots.
231 Monitors one or more keyword types on EntityClients, caching the latest
232 value of each. A `snapshot` merges the cached keyword models with an
233 optional base context and additional key-value pairs.
235 The cached keyword models are stored as-is in the context, preserving
236 the strict typing afforded by Keywords.
238 Example usage::
240 sub = ContextSubscription(mount_client)
241 sub.add(AltAzPointing)
242 sub.add(RADecPointing)
244 await sub.start()
245 ctx = sub.snapshot(execution.context)
246 await sub.stop()
247 """
249 def __init__(self, client: EntityClient):
250 self._client = client
251 self._add_queue: asyncio.Queue[type[BaseModel]] = asyncio.Queue()
252 self._add_task: asyncio.Task | None = None
253 self._consumers: list[asyncio.Task] = []
254 self._ready = asyncio.Event()
255 self._cache = KeywordDict()
256 self.cache = MappingProxyType(self._cache)
258 def add(self, keyword_type: type[BaseModel]):
259 """Register a keyword subscription.
261 Args:
262 keyword_type: The keyword/model type to subscribe to.
263 """
264 self._ready.clear()
265 self._add_queue.put_nowait(keyword_type)
267 def add_trait_keywords(self, details: DeviceDetails):
268 """Register a subscription for each keyword required by a trait the device satisfies.
270 Args:
271 details: The device details to match against registered traits.
273 Raises:
274 ValueError: A matched trait requires a keyword that is not declared.
275 """
276 for keyword_id in sorted(trait_keyword_ids(details)):
277 if (keyword_type := get_keyword_type(keyword_id)) is None:
278 raise ValueError(f"trait keyword '{keyword_id}' is not a declared keyword")
280 self.add(keyword_type)
282 async def _subscription_adder(self):
283 while True:
284 keyword = await self._add_queue.get()
286 if self._add_queue.empty():
287 self._ready.set()
289 # TODO: Need a monitor variant that allows a Queue parameter, then we only need one.
290 self._consumers.append(asyncio.create_task(self._consumer(keyword)))
292 async def _consumer(self, keyword: type[BaseModel]):
293 stream = await self._client.monitor(keyword)
295 async for _, data in stream:
296 self._cache.set(data)
298 async def start(self):
299 """Start all subscriptions."""
300 if self._add_task:
301 raise RuntimeError("ContextSubscription is already running")
303 self._add_task = asyncio.create_task(self._subscription_adder())
305 if self._add_queue.empty():
306 self._ready.set()
307 else:
308 await self._ready.wait()
310 async def stop(self):
311 """Cancel all background monitor tasks."""
312 if not self._add_task:
313 return
315 self._add_task.cancel()
317 for task in self._consumers:
318 task.cancel()
320 await asyncio.gather(self._add_task, *self._consumers, return_exceptions=True)
322 self._add_task = None
323 self._consumers.clear()
325 def snapshot(self, into: KeywordDict | None = None) -> Context:
326 """Copy the cached Context into a target Context."""
327 if into is None:
328 into = Context()
330 into.update(self._cache)
331 return into