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

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import asyncio 

5import builtins 

6from datetime import UTC, datetime 

7from types import MappingProxyType 

8from typing import TYPE_CHECKING, Any, Unpack, overload, override 

9 

10from pydantic import BaseModel 

11 

12from sensorkit.common.keyword import CompositeKeyword, KeywordDict, get_keyword_type 

13from sensorkit.core.trait import trait_keyword_ids 

14 

15if TYPE_CHECKING: 

16 from sensorkit.core.entity import DeviceDetails, EntityClient 

17 

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} 

31 

32_EVAL_GLOBALS = {"__builtins__": _SAFE_BUILTINS, "datetime": datetime, "UTC": UTC} 

33_MISSING = object() 

34_FSTRING_OPENERS = ('f"', "f'", 'F"', "F'") 

35 

36 

37def _raw_fstring_source(value: str) -> str: 

38 """Build source that evaluates `value` as a raw f-string template. 

39 

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. 

46 

47 Args: 

48 value: Template text containing one or more `{...}` fields. 

49 

50 Returns: 

51 Python source that evaluates to the rendered string. 

52 """ 

53 end = len(value) 

54 

55 while end and value[end - 1] in '\\"': 

56 end -= 1 

57 

58 source = f'rf"""{value[:end]}"""' 

59 

60 if end < len(value): 

61 source += f" + {value[end:]!r}" 

62 

63 return source 

64 

65 

66class Context(KeywordDict): 

67 """A `KeywordDict` read view that expands composite keywords. 

68 

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. 

76 

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 """ 

81 

82 def __init__( 

83 self, 

84 arg: Any = None, 

85 *objs: Unpack[tuple[object, ...]], 

86 ): 

87 super().__init__(arg, *objs) 

88 

89 if not isinstance(arg, Context): 

90 self._expand_all() 

91 

92 @override 

93 def update(self, other): 

94 super().update(other) 

95 

96 # Expand only what `other` just contributed. 

97 if not isinstance(other, Context): 

98 self._expand_values(other.values()) 

99 

100 @override 

101 def set_keyword(self, obj): 

102 if isinstance(obj, CompositeKeyword): 

103 self._expand(obj, {id(obj)}) 

104 

105 super().set_keyword(obj) 

106 

107 def _expand_all(self): 

108 self._expand_values(self.values()) 

109 

110 def _expand_values(self, values): 

111 for value in list(values): 

112 if isinstance(value, CompositeKeyword): 

113 self._expand(value, {id(value)}) 

114 

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 

121 

122 visited.add(id(composed)) 

123 

124 if isinstance(composed, CompositeKeyword): 

125 self._expand(composed, visited) 

126 

127 super().set_keyword(composed) 

128 

129 def eval(self, expr: str, *, default: object = _MISSING): 

130 """Evaluate a Python expression with this Context as the namespace. 

131 

132 Names in the expression resolve against this Context's keys. 

133 

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. 

140 

141 Returns: 

142 The expression result, keeping its native type. 

143 

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 

152 

153 return default 

154 

155 @overload 

156 def resolve[T](self, value: str | None, *, as_type: type[T], default: T = ...) -> T: ... 

157 

158 @overload 

159 def resolve(self, value: str | None, *, default: object = ...) -> object: ... 

160 

161 def resolve(self, value: str | None, *, as_type = _MISSING, default = _MISSING): 

162 r"""Resolve a config string against this Context. 

163 

164 The form of `value` selects how it is interpreted: 

165 

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`. 

174 

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. 

180 

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. 

184 

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") 

191 

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) 

199 

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__}") 

202 

203 return value 

204 

205 

206def merge_contexts(*contexts: KeywordDict | None) -> Context: 

207 """A fresh context holding each given one in turn. 

208 

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. 

212 

213 Args: 

214 *contexts: What to merge, lowest precedence first. 

215 

216 Returns: 

217 A new context. 

218 """ 

219 merged = Context() 

220 

221 for context in contexts: 

222 if context is not None: 

223 merged.update(context) 

224 

225 return merged 

226 

227 

228class ContextSubscription: 

229 """Subscribe to device keyword updates and produce Context snapshots. 

230 

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. 

234 

235 The cached keyword models are stored as-is in the context, preserving 

236 the strict typing afforded by Keywords. 

237 

238 Example usage:: 

239 

240 sub = ContextSubscription(mount_client) 

241 sub.add(AltAzPointing) 

242 sub.add(RADecPointing) 

243 

244 await sub.start() 

245 ctx = sub.snapshot(execution.context) 

246 await sub.stop() 

247 """ 

248 

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) 

257 

258 def add(self, keyword_type: type[BaseModel]): 

259 """Register a keyword subscription. 

260 

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) 

266 

267 def add_trait_keywords(self, details: DeviceDetails): 

268 """Register a subscription for each keyword required by a trait the device satisfies. 

269 

270 Args: 

271 details: The device details to match against registered traits. 

272 

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") 

279 

280 self.add(keyword_type) 

281 

282 async def _subscription_adder(self): 

283 while True: 

284 keyword = await self._add_queue.get() 

285 

286 if self._add_queue.empty(): 

287 self._ready.set() 

288 

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))) 

291 

292 async def _consumer(self, keyword: type[BaseModel]): 

293 stream = await self._client.monitor(keyword) 

294 

295 async for _, data in stream: 

296 self._cache.set(data) 

297 

298 async def start(self): 

299 """Start all subscriptions.""" 

300 if self._add_task: 

301 raise RuntimeError("ContextSubscription is already running") 

302 

303 self._add_task = asyncio.create_task(self._subscription_adder()) 

304 

305 if self._add_queue.empty(): 

306 self._ready.set() 

307 else: 

308 await self._ready.wait() 

309 

310 async def stop(self): 

311 """Cancel all background monitor tasks.""" 

312 if not self._add_task: 

313 return 

314 

315 self._add_task.cancel() 

316 

317 for task in self._consumers: 

318 task.cancel() 

319 

320 await asyncio.gather(self._add_task, *self._consumers, return_exceptions=True) 

321 

322 self._add_task = None 

323 self._consumers.clear() 

324 

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() 

329 

330 into.update(self._cache) 

331 return into