Coverage for core / src / sensorkit / api / entrypoint.py: 91%

158 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2import asyncio 

3import concurrent.futures 

4import contextlib 

5import os 

6import signal 

7import time 

8from collections.abc import Callable, Coroutine, Mapping 

9from random import random 

10from typing import Any 

11 

12from loguru import logger 

13 

14from sensorkit.api.declarative import Service 

15from sensorkit.common.aio import cleanup_future, scoped_waiter 

16from sensorkit.common.importutil import obj_from_spec 

17 

18type ServiceEntrypointFunc = Callable[[Service], Coroutine[Any, Any, None]] 

19 

20FORCE_QUIT_INTERRUPTS = 3 

21 

22 

23class ServiceEntrypoint: 

24 """Proxy for a service entrypoint function.""" 

25 

26 @classmethod 

27 def from_spec(cls, spec: str, load_file: bool = False): 

28 """Finds a service entrypoint in a module or python file.""" 

29 return obj_from_spec(spec=spec, base=ServiceEntrypoint, load_file=load_file) 

30 

31 def __init__(self, func: ServiceEntrypointFunc, version: str): 

32 self._func = func 

33 self._version = version 

34 

35 async def run(self, name: str): 

36 """Start the service with *name* and return `(service, task)` once it is running.""" 

37 # Invoke the user entrypoint function passing in a new Service instance. 

38 service = Service(name, self._version) 

39 task = asyncio.create_task(self._func(service)) 

40 

41 try: 

42 # Wait for the service to start up or for the task to fail. 

43 await asyncio.wait( 

44 [service.running, task], 

45 return_when=asyncio.FIRST_COMPLETED, 

46 ) 

47 

48 if not service.running.done(): 

49 if e := task.exception(): 

50 logger.debug(f"Service '{name}' failed to start: {type(e).__name__}: {e}") 

51 raise e 

52 else: 

53 raise RuntimeError(f"Entrypoint '{self._func.__name__}' did not start the service!") 

54 

55 # If the service raised, propagate the exception. 

56 await service.running 

57 

58 return service, task 

59 except asyncio.CancelledError: 

60 task.cancel() 

61 

62 try: 

63 await task 

64 except asyncio.CancelledError: 

65 pass 

66 except Exception as e: 

67 logger.opt(exception=e).debug("exception during service shutdown") 

68 

69 for fut in (service.running, service.shutdown): 

70 cleanup_future(fut) 

71 

72 raise 

73 

74 def __call__(self, *args, **kwargs): 

75 raise RuntimeError("Service entrypoint cannot be called directly") 

76 

77 

78def service_entrypoint(*, version: str): 

79 """Returns a decorator for defining a service entrypoint.""" 

80 def decorator(func: ServiceEntrypointFunc): 

81 return ServiceEntrypoint(func, version=version) 

82 

83 return decorator 

84 

85 

86class ShutdownSignal(Exception): 

87 """Raised to signal an orderly service shutdown across threads.""" 

88 

89 

90class ServiceExit(Exception): 

91 """A service failure caused by a worker-thread exit. 

92 

93 The original exception is preserved as the cause. 

94 """ 

95 

96 def __init__(self, name: str, cause: BaseException): 

97 super().__init__(f"Service {name} raised {type(cause).__name__}") 

98 self.__cause__ = cause 

99 

100 

101async def run_services( 

102 entrypoints: Mapping[str, ServiceEntrypoint], 

103 trap_signals: bool = True, 

104 **kwargs, 

105): 

106 """Run a set of service entrypoints.""" 

107 interrupt_count = 0 

108 

109 # We have to use a `concurrent.futures.Future` here so it can be used by different event loops 

110 # running on different threads. 

111 shutdown = concurrent.futures.Future() 

112 

113 def signal_shutdown(sig=None, _frame=None): 

114 nonlocal interrupt_count 

115 

116 match sig: 

117 case signal.SIGTERM: 

118 logger.info("Service process received shutdown signal") 

119 case signal.SIGINT: 

120 interrupt_count += 1 

121 remaining = FORCE_QUIT_INTERRUPTS - interrupt_count 

122 

123 if interrupt_count == 1: 

124 logger.warning("Service process received interrupt signal") 

125 elif remaining > 0: 

126 times = "one more time" if remaining == 1 else f"{remaining} more times" 

127 logger.warning(f"Interrupt {times} to force exit") 

128 else: 

129 logger.error("Forced exit") 

130 os._exit(130) 

131 

132 if not shutdown.done(): 

133 shutdown.set_exception(ShutdownSignal()) 

134 

135 if trap_signals: 

136 signal.signal(signal.SIGINT, signal_shutdown) 

137 signal.signal(signal.SIGTERM, signal_shutdown) 

138 

139 # Run all services, each in its own thread with its own event loop per invocation. 

140 loops = [ 

141 asyncio.create_task(asyncio.to_thread(_service_loop, name, entrypoint, shutdown, **kwargs)) 

142 for name, entrypoint in entrypoints.items() 

143 ] 

144 

145 try: 

146 # Keep service tasks alive until their threads finish shutting down. 

147 await asyncio.gather( 

148 asyncio.shield(asyncio.wrap_future(shutdown)), 

149 *(asyncio.shield(task) for task in loops), 

150 ) 

151 finally: 

152 # Shut down other services and wait for their teardown. 

153 signal_shutdown() 

154 await asyncio.gather(*loops, return_exceptions=True) 

155 

156 

157def _restart_loop( 

158 wait_fn: Callable[[float], bool], 

159 *, 

160 max_restarts: int | None = None, 

161 startup_failure_threshold: float = 30.0, 

162 restart_backoff_min: float = 5.0, 

163 restart_backoff_max: float = 300.0, 

164 restart_backoff_random: float = 5.0, 

165 restart_backoff_factor: float = 1.8, 

166): 

167 """Restart loop generator. Yields once per iteration; caller runs the service body. 

168 

169 wait_fn(seconds) must return True to continue or False for graceful shutdown, and 

170 raise to signal an abnormal stop. 

171 """ 

172 restarts = 0 

173 backoff = 0.0 

174 

175 while max_restarts is None or restarts <= max_restarts: 

176 if not wait_fn(backoff): 

177 return 

178 

179 start = time.monotonic() 

180 yield 

181 elapsed = time.monotonic() - start 

182 

183 if elapsed < startup_failure_threshold: 

184 restarts += 1 

185 backoff = backoff * restart_backoff_factor + random() * restart_backoff_random 

186 backoff = min(max(backoff, restart_backoff_min), restart_backoff_max) 

187 else: 

188 restarts = 1 

189 backoff = 0.0 

190 

191 

192def _service_loop( 

193 name: str, 

194 entrypoint: ServiceEntrypoint, 

195 shutdown_signal: concurrent.futures.Future, 

196 startup_timeout: float = 300.0, 

197 shutdown_timeout: float = 5.0, 

198 **kwargs, 

199): 

200 last_err: Exception | None = None 

201 

202 def _wait_for_shutdown(timeout: float) -> bool: 

203 if timeout > 0.0 and not shutdown_signal.done(): 

204 logger.info(f"Waiting {timeout:1.0f} sec before restarting {name} ...") 

205 try: 

206 shutdown_signal.result(timeout=timeout) 

207 return False 

208 except concurrent.futures.TimeoutError: 

209 return True 

210 

211 try: 

212 for _ in _restart_loop(_wait_for_shutdown, **kwargs): 

213 logger.info(f"Starting {name}") 

214 last_err = None 

215 

216 try: 

217 asyncio.run( 

218 _service_proc( 

219 name, entrypoint, shutdown_signal, startup_timeout, shutdown_timeout 

220 ) 

221 ) 

222 except Exception as e: 

223 logger.error(f"Service {name} exited due to {type(e).__name__}") 

224 last_err = e 

225 except BaseException as e: 

226 # Wrap worker-thread exits so exhausted restarts cannot stop the main loop. 

227 logger.error(f"Service {name} exited due to {type(e).__name__}") 

228 last_err = ServiceExit(name, e) 

229 except ShutdownSignal as e: 

230 last_err = e 

231 except Exception as e: 

232 logger.error(f"Terminating {name} service loop due to {type(e).__name__}") 

233 last_err = e 

234 finally: 

235 logger.debug(f"service loop for {name} exiting (last_err is {type(last_err).__name__}))") 

236 

237 # Make sure all other services exit, too. 

238 if not shutdown_signal.done(): 

239 shutdown_signal.set_result(None) 

240 

241 if last_err: 

242 raise last_err 

243 

244 

245async def _service_proc( 

246 name: str, 

247 entrypoint: ServiceEntrypoint, 

248 shutdown_signal: concurrent.futures.Future, 

249 startup_timeout: float, 

250 shutdown_timeout: float, 

251): 

252 service: Service | None = None 

253 service_task: asyncio.Task | None = None 

254 

255 # Bind the cross-thread shutdown signal to this event loop. 

256 shutdown = asyncio.wrap_future(shutdown_signal) 

257 

258 try: 

259 async with scoped_waiter(asyncio.shield(shutdown)) as shutdown_wait: 

260 startup = asyncio.create_task(entrypoint.run(name)) 

261 

262 await asyncio.wait( 

263 [startup, shutdown_wait], 

264 return_when=asyncio.FIRST_COMPLETED, 

265 timeout=startup_timeout, 

266 ) 

267 

268 if shutdown_wait.done(): 

269 startup.cancel() 

270 

271 with contextlib.suppress(asyncio.CancelledError): 

272 await startup 

273 

274 return 

275 

276 if not startup.done(): 

277 raise TimeoutError(f"Service failed to start within {startup_timeout:.0f} seconds") 

278 

279 service, service_task = startup.result() 

280 

281 await asyncio.wait( 

282 [service_task, shutdown_wait], 

283 return_when=asyncio.FIRST_COMPLETED, 

284 ) 

285 

286 if not shutdown_wait.done(): 

287 await service_task 

288 finally: 

289 if service and not service.shutdown.done(): 

290 logger.info(f"Shutting down {name}") 

291 

292 # Try an orderly shutdown first. 

293 with contextlib.suppress(Exception): 

294 async with asyncio.timeout(shutdown_timeout): 

295 await service.stop() 

296 

297 # Kill the user entrypoint task. 

298 if service_task and not service_task.done(): 

299 service_task.cancel() 

300 

301 with contextlib.suppress(asyncio.CancelledError): 

302 await service_task