Coverage for core / src / sensorkit / core / impl / entity.py: 95%

134 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 

6from _contextvars import ContextVar 

7from typing import TYPE_CHECKING, Any, Callable, ClassVar, Iterable, Literal, Self, final, override 

8 

9from loguru import logger 

10from pydantic import BaseModel, TypeAdapter 

11 

12from sensorkit.backend.base import Entity, KVError, SpecialProperty 

13from sensorkit.backend.event import Event 

14from sensorkit.backend.request import HandlerError, RequestBase, RequestHandlerFunc 

15from sensorkit.common.keyword import Keyword, dump_keyword_json, get_keyword_info 

16from sensorkit.core.entity import EntityBase, EntityDetails, EntityInfo, EntityInterface 

17from sensorkit.data.graph import DataGraph 

18 

19if TYPE_CHECKING: 

20 from sensorkit.core.client import SensorKit, ServiceContext 

21 

22 

23class EntityImpl(EntityBase, EntityInterface): 

24 """Object that exposes implementation-side functionality of an entity.""" 

25 

26 current: ClassVar[ContextVar[EntityImpl | None]] = ContextVar("current_entity", default=None) 

27 """The instance in the current execution context, if any.""" 

28 

29 @classmethod 

30 def for_service_context(cls, context: ServiceContext, entity: str, **kwargs) -> Self: 

31 """Construct an entity implementation for the service context.""" 

32 return cls( 

33 sensorkit=context.sensorkit(), 

34 entity=Entity.at(entity), 

35 task_group=context.task_group, 

36 **kwargs, 

37 ) 

38 

39 def __init__(self, sensorkit: SensorKit, entity: Entity, *, task_group: asyncio.TaskGroup): 

40 super().__init__(sensorkit, entity) 

41 self._data_graph: DataGraph | None = None 

42 self._task_group = task_group 

43 self._attach_hooks: list[Callable] = [] 

44 self._detach_hooks: list[Callable] = [] 

45 self._requests: dict[str, RequestBase] = {} 

46 self._published_keywords: set[str] = set() 

47 

48 async def init_impl(self): 

49 """Implements initialization of the entity. 

50 

51 This method is called after the backend is up and available, but before `attach` is run. 

52 Implementations will typically retrieve configuration, restore persisted state, and 

53 perform any other initialization to prepare resources required by user `on_attach` hooks. 

54 """ 

55 pass 

56 

57 def on_attach(self, func: Callable): 

58 """Register a callback to run when this entity is being attached.""" 

59 self._attach_hooks.append(func) 

60 return func 

61 

62 @final 

63 async def attach(self): 

64 """Attach the entity implementation to the running service context. 

65 

66 Runs all attach hooks and publishes entity info. An exception raised in any attach hook 

67 is propagated as fatal. 

68 """ 

69 await self._call_with_context(self._attach_hooks, error_policy="raise") 

70 

71 with self.enter_context(): 

72 await self.attach_impl() 

73 

74 await self.publish_entity_info() 

75 

76 async def attach_impl(self): 

77 """Implements "attach". Runs after the user attach hooks.""" 

78 pass 

79 

80 def on_detach(self, func: Callable): 

81 """Register a callback to run when this entity is being detached.""" 

82 self._detach_hooks.append(func) 

83 return func 

84 

85 @final 

86 async def detach(self): 

87 """Detach the entity implementation from the running service context. 

88 

89 Runs all detach hooks. An exception raised in the internal detach hook (`detach_impl`) is 

90 propagated as fatal, while exceptions from user detach hooks are logged. 

91 """ 

92 with self.enter_context(): 

93 await self.detach_impl() 

94 

95 for result in await self._call_with_context(self._detach_hooks, error_policy="ignore"): 

96 match result: 

97 case asyncio.CancelledError(): 

98 logger.warning(f"Cancelled during {self.entity} detach") 

99 case Exception(): 

100 logger.warning(f"Error during {self.entity} detach ({type(result).__name__})") 

101 logger.opt(exception=result).debug("detach hook raised") 

102 case BaseException(): 

103 raise result 

104 

105 async def detach_impl(self): 

106 """Implements "detach". Runs before the user detach hooks.""" 

107 pass 

108 

109 @contextlib.contextmanager 

110 def enter_context(self): 

111 """Store a reference to this entity in the current execution context.""" 

112 var = type(self).current 

113 token = var.set(self) 

114 

115 # Also set the base EntityImpl.current so sk.entity() resolves for all entity types. 

116 base_var = EntityImpl.current 

117 base_token = base_var.set(self) if var is not base_var else None 

118 

119 try: 

120 yield 

121 finally: 

122 var.reset(token) 

123 

124 if base_token is not None: 

125 base_var.reset(base_token) 

126 

127 @override 

128 def declare_published_keyword(self, keyword_id: str) -> None: 

129 """Declare a keyword this entity can publish.""" 

130 self._published_keywords.add(keyword_id) 

131 

132 @override 

133 @property 

134 def task_group(self): 

135 return self._task_group 

136 

137 @override 

138 async def emit_event(self, event: Event): 

139 """Serialize and publish the event to the entity's event stream subject.""" 

140 await self._stream.publish( 

141 SpecialProperty.EVENTS, 

142 event.model_dump_json().encode(), 

143 ) 

144 

145 @override 

146 async def publish(self, model: Keyword): 

147 """Serialize and publish a keyword model to the entity's data stream.""" 

148 if info := get_keyword_info(model): 

149 await self._stream.publish( 

150 info.key, 

151 dump_keyword_json(model), 

152 ) 

153 else: 

154 await self._stream.publish( 

155 model.__class__.__name__, 

156 model.model_dump_json().encode() 

157 if isinstance(model, BaseModel) 

158 else TypeAdapter(model).dump_json(model), 

159 ) 

160 

161 @override 

162 async def handle_request[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None]( 

163 self, 

164 request: RequestBase[P, R, V], 

165 func: RequestHandlerFunc[P, R, V], 

166 ): 

167 """Register a handler for the given Request declaration on the backend. 

168 

169 Raises: 

170 HandlerError: if this entity already serves a request under the same name. 

171 """ 

172 # A request name is only unique within one entity, since it becomes the last token of the 

173 # backend subject the handler binds. 

174 if request.name in self._requests: 

175 raise HandlerError(f"Entity {self.entity} already handles request '{request.name}'") 

176 

177 callback = request.create_handler(func, self._stream) 

178 

179 # Reserve the name before yielding, so concurrent attach hooks cannot both get past the 

180 # check and race to bind the same subject. 

181 self._requests[request.name] = request 

182 

183 try: 

184 await self._request.handle_request(request.name, callback) 

185 except BaseException: 

186 del self._requests[request.name] 

187 raise 

188 

189 @override 

190 async def data_graph(self): 

191 """Return this entity's configured data graph, creating it on first use.""" 

192 if not self._data_graph: 

193 with contextlib.suppress(KVError): 

194 dg = await self.kv_get_model(DataGraph) 

195 

196 # Make sure a concurrent call does not result in two graphs. 

197 if not self._data_graph: 

198 self._data_graph = dg 

199 self._data_graph.start(task_group=self.task_group) 

200 logger.info(f"Started DataGraph with {len(self._data_graph.nodes)} ops") 

201 

202 return self._data_graph 

203 

204 def entity_info(self) -> EntityInfo: 

205 """Build this entity's info record from its current state.""" 

206 return EntityInfo( 

207 entity_type="generic", 

208 details=EntityDetails( 

209 published_keywords=frozenset(self._published_keywords), 

210 ), 

211 ) 

212 

213 @override 

214 async def publish_entity_info(self) -> EntityInfo: 

215 """Publish this entity's EntityInfo entry to the KV store.""" 

216 info = self.entity_info() 

217 await self.kv_put_model(info) 

218 return info 

219 

220 async def _call_with_context( 

221 self, 

222 funcs: Iterable[Callable], 

223 args: tuple[Any, ...] = (), 

224 kwargs: dict[str, Any] | None = None, 

225 *, 

226 error_policy: Literal["raise", "log", "ignore"] = "log", 

227 ) -> list[Any]: 

228 """Invoke hooks concurrently within this entity's execution context.""" 

229 call_kwargs = kwargs if kwargs is not None else {} 

230 

231 async def invoke(func: Callable): 

232 aw = func(*args, **call_kwargs) 

233 return await aw if asyncio.iscoroutine(aw) else aw 

234 

235 with self.enter_context(): 

236 tasks = [asyncio.ensure_future(invoke(func)) for func in funcs] 

237 

238 if error_policy == "raise": 

239 # Fail fast: propagate the first hook exception immediately, cancelling any 

240 # still-running siblings so none are left orphaned on the loop. 

241 try: 

242 return await asyncio.gather(*tasks) 

243 finally: 

244 for task in tasks: 

245 task.cancel() 

246 await asyncio.gather(*tasks, return_exceptions=True) 

247 

248 results = await asyncio.gather(*tasks, return_exceptions=True) 

249 

250 if error_policy == "log": 

251 for result in results: 

252 match result: 

253 case Exception(): 

254 logger.opt(exception=result).debug("error in callback") 

255 case BaseException(): 

256 logger.debug(f"error in callback ({type(result).__name__})") 

257 

258 return results