Coverage for core / src / sensorkit / webapi / fastapi.py: 85%

406 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 contextlib 

4from collections.abc import AsyncGenerator 

5from typing import Annotated, Any, Callable, Iterable 

6 

7import uuid_utils.compat as uuid 

8import uvicorn 

9from fastapi import Body, Depends, FastAPI, HTTPException, Request, Response 

10from fastapi.middleware.cors import CORSMiddleware 

11from fastapi.sse import EventSourceResponse, ServerSentEvent 

12from loguru import logger 

13from pydantic import BaseModel, Field, RootModel, model_validator 

14 

15import sensorkit.api as sk 

16from sensorkit.auto.agent import AgentConfigureRequest, AgentState, agent_configure_request 

17from sensorkit.backend.base import ( 

18 BackendError, 

19 KeyNotFound, 

20 RemoteRequestError, 

21 ReplyTimeout, 

22 UnregisteredResponder, 

23) 

24from sensorkit.backend.request import Call 

25from sensorkit.core.controller import ControllerState 

26from sensorkit.core.device import DeviceState 

27from sensorkit.core.entity import DeviceDetails, EntityInfo 

28from sensorkit.core.program import ProgramState, TaskingError, TaskingStartupFailed 

29from sensorkit.webapi.forwarder import ( 

30 Forwarder, 

31 KeyValueForwarder, 

32 ProductForwarder, 

33 RecordQueueSet, 

34 SKRecord, 

35 StreamForwarder, 

36) 

37from sensorkit.webapi.preview import PreviewJPEG 

38from sensorkit.webapi.schema import add_sensorkit_schema 

39from sensorkit.webapi.security import ( 

40 LOOPBACK_HOSTS, 

41 AuthConfig, 

42 AuthMiddleware, 

43 CORSConfig, 

44 NoAuthConfig, 

45 SecurityHeadersMiddleware, 

46 TLSConfig, 

47) 

48from sensorkit.webapi.serve import ProductInfo, ServeDataConfig, ServeHandler 

49 

50PRODUCT_LISTING_TIMEOUT = 10.0 

51 

52 

53class WebAPIConfig(BaseModel): 

54 """Configuration for the WebAPI service.""" 

55 

56 port: int = 8000 

57 host: str = "127.0.0.1" 

58 agent: sk.EntityRef = sk.EntityRef("agent") 

59 serve_data_products: list[ServeDataConfig] = [] 

60 tls: TLSConfig | None = None 

61 auth: AuthConfig = NoAuthConfig() 

62 cors: CORSConfig = CORSConfig() 

63 expose_docs: bool = False 

64 max_stream_clients: int = 32 

65 stream_queue_size: int = 4096 

66 

67 

68class RawPayload(RootModel[Any]): 

69 """Request data carried through the web API as unvalidated JSON.""" 

70 

71 

72class AgentOverrideRequest(BaseModel): 

73 """Request body for controller demand override.""" 

74 

75 state: bool | None 

76 

77 

78class EntityListing(EntityInfo): 

79 """Entity listing response.""" 

80 

81 name: str 

82 online: bool 

83 

84 

85class DeviceListing(EntityInfo): 

86 """Device listing response.""" 

87 

88 name: str 

89 online: bool 

90 archetype: str | None = None 

91 traits: list[str] = Field(default_factory=list) 

92 

93 @model_validator(mode="after") 

94 def _populate_from_details(self): 

95 if isinstance(self.details, DeviceDetails): 

96 self.archetype = self.details.archetype 

97 self.traits = [trait.name for trait in self.details.traits] 

98 

99 return self 

100 

101 

102def _status_ok(**kwargs) -> dict[str, Any]: 

103 return {"status": "ok", **kwargs} 

104 

105 

106@contextlib.contextmanager 

107def _error_handler(): 

108 try: 

109 yield 

110 except KeyNotFound as err: 

111 raise HTTPException(status_code=404, detail="Requested entity not found") from err 

112 except RemoteRequestError as err: 

113 raise HTTPException(status_code=500, detail="Remote exception occurred") from err 

114 except UnregisteredResponder as err: 

115 raise HTTPException(status_code=503, detail="Endpoint unavailable") from err 

116 except ReplyTimeout as err: 

117 raise HTTPException(status_code=504, detail="Request timed out") from err 

118 except BackendError as err: 

119 raise HTTPException(status_code=503, detail="Backend not available") from err 

120 except TaskingStartupFailed as err: 

121 raise HTTPException(status_code=409, detail=str(err)) from err 

122 except TaskingError as err: 

123 match err.__cause__: 

124 case TimeoutError(): 

125 raise HTTPException(status_code=504, detail="Request timed out") from err 

126 case _: 

127 raise HTTPException( 

128 status_code=503, 

129 detail="Program tasking startup could not be confirmed", 

130 ) from err 

131 except sk.CallError as err: 

132 raise HTTPException(status_code=409, detail=str(err)) from err 

133 except TimeoutError as err: 

134 raise HTTPException(status_code=504, detail="Request timed out") from err 

135 

136 

137def _snapshot(forwarders: Iterable[Forwarder], entity_id: str | None = None) -> list[SKRecord]: 

138 """Return the cached records of the given forwarders, optionally for a single entity.""" 

139 return [record for forwarder in forwarders for record in forwarder.snapshot(entity_id)] 

140 

141 

142class WebAPI: 

143 """ 

144 FastAPI-based web service for SensorKit. 

145 

146 Provides REST API endpoints for interacting with devices, controllers, programs, 

147 and agents, as well as Server-Sent Events (SSE) for real-time state updates. 

148 """ 

149 

150 def __init__(self, kit: sk.SensorKit, config: WebAPIConfig): 

151 self.kit = kit 

152 self.config = config 

153 self.client_queues: RecordQueueSet = set() 

154 self.kv_forwarder = KeyValueForwarder(kit, targets=self.client_queues) 

155 self.stream_forwarder = StreamForwarder(kit, targets=self.client_queues) 

156 self._serve_handlers: list[ServeHandler] = [] 

157 self._product_forwarders: list[ProductForwarder] = [] 

158 self.authenticator = config.auth.create_authenticator() 

159 self._stopped = asyncio.Event() 

160 self._stopped.set() 

161 

162 ssl_options = config.tls.uvicorn_options() if config.tls else {} 

163 

164 self.app = self._create_fastapi_app() 

165 self.server = uvicorn.Server( 

166 uvicorn.Config( 

167 self.app, 

168 host=self.config.host, 

169 port=self.config.port, 

170 log_level="info", 

171 **ssl_options, 

172 ) 

173 ) 

174 

175 # Resolve the configured agent entity reference. 

176 self.config.agent.resolve(kit) 

177 

178 @property 

179 def forwarders(self) -> tuple[Forwarder, ...]: 

180 """Every active forwarder: key-value, stream, and one per data-product handler.""" 

181 return self.kv_forwarder, self.stream_forwarder, *self._product_forwarders 

182 

183 async def _check_stream_capacity(self): 

184 """Reject a new subscriber once the concurrent stream limit is reached.""" 

185 if len(self.client_queues) >= self.config.max_stream_clients: 

186 raise HTTPException(status_code=503, detail="Too many concurrent stream subscribers") 

187 

188 async def _stream_records( 

189 self, 

190 request: Request, 

191 sources: Iterable[Forwarder], 

192 match: Callable[[SKRecord], bool] = lambda _: True, 

193 ) -> AsyncGenerator[ServerSentEvent]: 

194 """Yield matching records as SSE: the snapshot of `sources`, then live updates. 

195 

196 Every forwarder feeds the same client queue, so live updates can only be selected 

197 by predicate; `sources` narrows the snapshot alone and `match` must cover both. 

198 """ 

199 request.state.is_sse = True 

200 queue: asyncio.Queue[SKRecord | None] = asyncio.Queue(self.config.stream_queue_size) 

201 self.client_queues.add(queue) 

202 

203 try: 

204 for record in filter(match, _snapshot(sources)): 

205 yield ServerSentEvent(raw_data=record.serialize()) 

206 

207 while True: 

208 record = await queue.get() 

209 

210 if record is None: 

211 break 

212 

213 try: 

214 if match(record): 

215 yield ServerSentEvent(raw_data=record.serialize()) 

216 finally: 

217 queue.task_done() 

218 except asyncio.CancelledError: 

219 host = request.client.host if request.client else "unknown" 

220 logger.debug(f"SSE client disconnected: {host}") 

221 finally: 

222 self.client_queues.discard(queue) 

223 

224 async def _product_listing(self) -> list[ProductInfo]: 

225 """Return every handler's product listing. 

226 

227 A handler's listing may not be ready immediately. Rather than report an empty 

228 listing — which would falsely imply there are no products — we wait up to 

229 PRODUCT_LISTING_TIMEOUT and raise 503 if it is still not available. 

230 """ 

231 try: 

232 async with asyncio.timeout(PRODUCT_LISTING_TIMEOUT): 

233 listings = [await handler.get_listing() for handler in self._serve_handlers] 

234 except TimeoutError as err: 

235 raise HTTPException( 

236 status_code=503, 

237 detail="Data product listing not yet available; try again shortly", 

238 ) from err 

239 

240 return [info for listing in listings for info in listing] 

241 

242 def _product_handler(self, controller_id: str, product_id: str) -> ServeHandler: 

243 """Return the handler serving a product, or raise 404 if none does.""" 

244 for handler in self._serve_handlers: 

245 if handler.has_product(controller_id, product_id): 

246 return handler 

247 

248 raise HTTPException(status_code=404, detail="Product not found") 

249 

250 async def _product_data(self, controller_id: str, product_id: str) -> bytes: 

251 """Return a product's raw bytes, or raise 404 if it is not being served. 

252 

253 A product can leave the handler's listing between the lookup and the read, so 

254 the miss is reported the same way an unknown product is. 

255 """ 

256 handler = self._product_handler(controller_id, product_id) 

257 

258 try: 

259 return await handler.get_data(controller_id, product_id) 

260 except KeyError as err: 

261 raise HTTPException(status_code=404, detail="Product not found") from err 

262 

263 def _product_metadata(self, controller_id: str, product_id: str) -> dict: 

264 """Return a product's cached metadata, or raise 404 if it is not being served.""" 

265 handler = self._product_handler(controller_id, product_id) 

266 

267 try: 

268 return handler.get_metadata(controller_id, product_id) 

269 except KeyError as err: 

270 raise HTTPException(status_code=404, detail="Product not found") from err 

271 

272 def _create_fastapi_app(self): 

273 hidden = {"docs_url": None, "redoc_url": None} 

274 app = FastAPI(title="SensorKit Web API", **({} if self.config.expose_docs else hidden)) 

275 

276 # CORS goes last so it answers preflight requests itself, which carry no credentials to 

277 # authorize. 

278 app.add_middleware(AuthMiddleware, authenticator=self.authenticator) 

279 app.add_middleware(SecurityHeadersMiddleware, hsts=self.config.tls is not None) 

280 app.add_middleware(CORSMiddleware, **self.config.cors.middleware_options()) 

281 

282 self._create_global_endpoints(app) 

283 self._create_entity_endpoints(app) 

284 self._create_device_endpoints(app) 

285 self._create_controller_endpoints(app) 

286 self._create_program_endpoints(app) 

287 self._create_agent_endpoints(app) 

288 self._finalize_openapi(app) 

289 

290 return app 

291 

292 def _finalize_openapi(self, app: FastAPI): 

293 """Generate the OpenAPI document and fold in the SensorKit and security schemas.""" 

294 app.openapi() 

295 schema = app.openapi_schema 

296 add_sensorkit_schema(schema["components"]["schemas"]) 

297 

298 if scheme := self.authenticator.openapi_scheme(): 

299 schema["components"]["securitySchemes"] = {"bearerAuth": scheme} 

300 schema["security"] = [{"bearerAuth": []}] 

301 

302 def _create_global_endpoints(self, app: FastAPI): 

303 @app.get( 

304 "/data/subscribe", 

305 tags=["Global"], 

306 response_class=EventSourceResponse, 

307 dependencies=[Depends(self._check_stream_capacity)], 

308 ) 

309 async def firehose_subscription(request: Request): 

310 """SSE endpoint for real-time updates.""" 

311 async with contextlib.aclosing(self._stream_records(request, self.forwarders)) as recs: 

312 async for event in recs: 

313 yield event 

314 

315 @app.get("/data/snapshot", tags=["Global"]) 

316 async def get_full_system_snapshot() -> list[SKRecord]: 

317 """Return the all cached data for all entities.""" 

318 return _snapshot(self.forwarders) 

319 

320 @app.get("/data/snapshot/{entity_id}", tags=["Global"]) 

321 async def get_entity_snapshot(entity_id: str) -> list[SKRecord]: 

322 """Return all cached data for a specific entity.""" 

323 return _snapshot(self.forwarders, entity_id) 

324 

325 @app.get("/entities", tags=["Global"]) 

326 async def get_entity_list() -> list[EntityListing | DeviceListing]: 

327 """Return a list of all entity IDs.""" 

328 output = [] 

329 cache = self.kv_forwarder.cache 

330 entities = tuple(cache.keys()) 

331 

332 for entity in entities: 

333 if record := cache[entity].get("EntityInfo"): 

334 if record.payload is None: 

335 continue 

336 

337 info = record.payload.copy() 

338 info["name"] = entity 

339 info["online"] = "EntityLease" in cache[entity] 

340 

341 output.append( 

342 DeviceListing.model_validate(info) 

343 if info["entity_type"] == "device" 

344 else EntityListing.model_validate(info) 

345 ) 

346 

347 return output 

348 

349 def _create_entity_endpoints(self, app: FastAPI): 

350 @app.post("/entity/{entity_id}/request/{request_name}", tags=["Entity"]) 

351 async def call_entity_request( 

352 entity_id: str, 

353 request_name: str, 

354 message: Annotated[dict[str, Any] | None, Body()] = None, 

355 ): 

356 """Call a request on an entity, passing the message and response through as JSON. 

357 

358 The caller supplies the request message and interprets the response itself. A request 

359 that declares no message takes an empty body, and one that responds with nothing 

360 answers 204. 

361 

362 Only simple requests are supported. A long-running request is still started by the 

363 entity, but answers 409 once its reply shows the call is long-running. 

364 """ 

365 context = self.kit.backend.request(sk.Entity.at(entity_id)) 

366 call = Call(context, request_name, message, RawPayload) 

367 

368 with _error_handler(): 

369 response = await call.invoke() 

370 

371 if response is None: 

372 return Response(status_code=204) 

373 

374 return Response(content=response.model_dump_json(), media_type="application/json") 

375 

376 def _create_device_endpoints(self, app: FastAPI): 

377 @app.get("/device/{device_id}/state", tags=["Device"]) 

378 async def get_device_state(device_id: str) -> DeviceState: 

379 """Return the current state of a device.""" 

380 with _error_handler(): 

381 return await self.kit.device(device_id).kv_get_model(DeviceState) 

382 

383 @app.post("/device/{device_id}/command", tags=["Device"]) 

384 async def run_device_command(device_id: str, command: sk.DeviceCommand): 

385 """Execute a command on a device.""" 

386 with _error_handler(): 

387 await self.kit.device(device_id).command(command) 

388 

389 return _status_ok() 

390 

391 def _create_controller_endpoints(self, app: FastAPI): 

392 @app.get("/controller/{controller_id}/state", tags=["Controller"]) 

393 async def get_controller_state(controller_id: str) -> ControllerState: 

394 """Return the current state of a controller.""" 

395 with _error_handler(): 

396 return await self.kit.controller(controller_id).kv_get_model(ControllerState) 

397 

398 @app.post("/controller/{controller_id}/execute", tags=["Controller"]) 

399 async def run_controller_task(controller_id: str, body: sk.TaskSubmission | sk.Task): 

400 """Execute a task on a controller. 

401 

402 The body may be a bare task or a `TaskSubmission` envelope. The envelope carries the 

403 client-supplied execution parameters (`context`, `expiry_time`) that the controller 

404 records on the minted `TaskExecution` — for example the file-naming keywords a caller 

405 needs threaded onto the execution. A bare task is equivalent to an envelope with no 

406 parameters. 

407 """ 

408 submission = body if isinstance(body, sk.TaskSubmission) else sk.TaskSubmission(task=body) 

409 

410 with _error_handler(): 

411 # The controller mints the task_id; learn it from the returned execution. 

412 execution = await self.kit.controller(controller_id).start_task( 

413 submission.task, 

414 context=submission.context, 

415 expiry_time=submission.expiry_time, 

416 ) 

417 await execution 

418 

419 return _status_ok(task_id=execution.task_id) 

420 

421 @app.post("/controller/{controller_id}/wait", tags=["Controller"]) 

422 async def wait_for_current_task(controller_id: str): 

423 """Wait for the currently executing task to complete on a controller.""" 

424 with _error_handler(): 

425 await self.kit.controller(controller_id).wait_for_task() 

426 

427 return _status_ok() 

428 

429 @app.post("/controller/{controller_id}/wait/{task_id}", tags=["Controller"]) 

430 async def wait_for_task(controller_id: str, task_id: uuid.UUID): 

431 """Wait for a task to complete on a controller.""" 

432 with _error_handler(): 

433 await self.kit.controller(controller_id).wait_for_task(task_id) 

434 

435 return _status_ok() 

436 

437 @app.post("/controller/{controller_id}/abort", tags=["Controller"]) 

438 async def abort_controller_task(controller_id: str, task_id: uuid.UUID | None = None): 

439 """Abort a specific task or the current task on a controller.""" 

440 with _error_handler(): 

441 await self.kit.controller(controller_id).abort_task(task_id) 

442 

443 return _status_ok() 

444 

445 @app.get("/controller/{controller_id}/products", tags=["Controller"]) 

446 async def list_controller_products(controller_id: str) -> list[ProductInfo]: 

447 """List data products associated with a controller.""" 

448 return [ 

449 info 

450 for info in await self._product_listing() 

451 if info.controller_id == controller_id 

452 ] 

453 

454 @app.get( 

455 "/controller/{controller_id}/products/subscribe", 

456 tags=["Controller"], 

457 response_class=EventSourceResponse, 

458 dependencies=[Depends(self._check_stream_capacity)], 

459 ) 

460 async def subscribe_controller_products(request: Request, controller_id: str): 

461 """SSE stream of product arrivals for a controller, including initial listing.""" 

462 

463 def is_controller_product(record: SKRecord) -> bool: 

464 return record.kind == "product" and str(record.subject.entity()) == controller_id 

465 

466 stream = self._stream_records(request, self._product_forwarders, is_controller_product) 

467 

468 async with contextlib.aclosing(stream) as recs: 

469 async for event in recs: 

470 yield event 

471 

472 @app.get("/controller/{controller_id}/product/{product_id}/data", tags=["Controller"]) 

473 async def get_controller_product_data(controller_id: str, product_id: str): 

474 """Return the raw FITS data for a product.""" 

475 raw_bytes = await self._product_data(controller_id, product_id) 

476 

477 return Response(content=raw_bytes, media_type="application/fits") 

478 

479 @app.get("/controller/{controller_id}/product/{product_id}/preview", tags=["Controller"]) 

480 async def get_controller_product_preview(controller_id: str, product_id: str): 

481 """Return a JPEG preview image generated from the FITS product data.""" 

482 data = await self._product_data(controller_id, product_id) 

483 

484 try: 

485 preview = await PreviewJPEG.from_fits(data) 

486 except Exception as err: 

487 logger.warning(f"Could not generate preview for {product_id}: {err}") 

488 raise HTTPException( 

489 status_code=422, detail="Could not generate preview" 

490 ) from err 

491 

492 return Response(content=preview.jpeg_bytes, media_type="image/jpeg") 

493 

494 @app.get("/controller/{controller_id}/product/{product_id}/metadata", tags=["Controller"]) 

495 async def get_controller_product_metadata(controller_id: str, product_id: str) -> dict: 

496 """Return the cached metadata for a product as a JSON object.""" 

497 metadata = self._product_metadata(controller_id, product_id) 

498 

499 if not metadata.get(ProductInfo): 

500 logger.warning(f"Product {product_id} has no ProductInfo keyword set") 

501 

502 return metadata 

503 

504 def _create_program_endpoints(self, app: FastAPI): 

505 @app.get("/program/{program_id}/state", tags=["Program"]) 

506 async def get_program_state(program_id: str) -> ProgramState: 

507 """Return the current state of a program.""" 

508 with _error_handler(): 

509 return await self.kit.program(program_id).kv_get_model(ProgramState) 

510 

511 @app.post("/program/{program_id}/enable", tags=["Program"]) 

512 async def enable_program(program_id: str, controller_id: str | None = None): 

513 """Enable a program.""" 

514 if controller_id is None: 

515 # TODO: When the program enable() method supports a None controller, i.e. leave 

516 # the associated controller unchanged, this part can be removed. 

517 with _error_handler(): 

518 state = await self.kit.program(program_id).kv_get_model(ProgramState) 

519 controller_id = state.enable_state.controller 

520 

521 if controller_id is None: 

522 raise HTTPException(status_code=422, detail="Controller ID is required") 

523 

524 with _error_handler(): 

525 await self.kit.program(program_id).enable(controller_id) 

526 

527 return _status_ok() 

528 

529 @app.post("/program/{program_id}/disable", tags=["Program"]) 

530 async def disable_program(program_id: str): 

531 """Disable a program.""" 

532 with _error_handler(): 

533 await self.kit.program(program_id).disable() 

534 

535 return _status_ok() 

536 

537 @app.post("/program/{program_id}/activate", tags=["Program"]) 

538 async def activate_program(program_id: str): 

539 """Start tasking for a program.""" 

540 with _error_handler(): 

541 activation = self.kit.program(program_id).start_tasking() 

542 

543 try: 

544 await activation 

545 finally: 

546 activation.close() 

547 

548 return _status_ok() 

549 

550 @app.post("/program/{program_id}/deactivate", tags=["Program"]) 

551 async def deactivate_program(program_id: str): 

552 """Stop tasking for a program.""" 

553 with _error_handler(): 

554 await self.kit.program(program_id).stop_tasking() 

555 

556 return _status_ok() 

557 

558 @app.post("/program/{program_id}/abort", tags=["Program"]) 

559 async def abort_program(program_id: str): 

560 """Abort program tasking immediately.""" 

561 with _error_handler(): 

562 await self.kit.program(program_id).abort_tasking() 

563 

564 return _status_ok() 

565 

566 def _create_agent_endpoints(self, app: FastAPI): 

567 @app.get("/agent/state", tags=["Agent"]) 

568 async def get_agent_state() -> AgentState: 

569 """Get the current status of the agent.""" 

570 with _error_handler(): 

571 return await self.config.agent.require().kv_get_model(AgentState) 

572 

573 @app.post("/agent/enable", tags=["Agent"]) 

574 async def enable_agent(): 

575 """Enable all agent control.""" 

576 with _error_handler(): 

577 await self.config.agent.require().call( 

578 agent_configure_request, AgentConfigureRequest(global_control_enabled=True) 

579 ) 

580 

581 return _status_ok() 

582 

583 @app.post("/agent/enable/{controller_id}", tags=["Agent"]) 

584 async def enable_controller(controller_id: str): 

585 """Enable agent control for a specific controller.""" 

586 with _error_handler(): 

587 await self.config.agent.require().call( 

588 agent_configure_request, 

589 AgentConfigureRequest(controller_control_enabled={controller_id: True}), 

590 ) 

591 

592 return _status_ok() 

593 

594 @app.post("/agent/disable", tags=["Agent"]) 

595 async def disable_agent(): 

596 """Disable all agent control.""" 

597 with _error_handler(): 

598 await self.config.agent.require().call( 

599 agent_configure_request, AgentConfigureRequest(global_control_enabled=False) 

600 ) 

601 

602 return _status_ok() 

603 

604 @app.post("/agent/disable/{controller_id}", tags=["Agent"]) 

605 async def disable_controller(controller_id: str): 

606 """Disable agent control for a specific controller.""" 

607 with _error_handler(): 

608 await self.config.agent.require().call( 

609 agent_configure_request, 

610 AgentConfigureRequest(controller_control_enabled={controller_id: False}), 

611 ) 

612 

613 return _status_ok() 

614 

615 @app.post("/agent/override/{controller_id}", tags=["Agent"]) 

616 async def override_controller(controller_id: str, req: AgentOverrideRequest): 

617 """Override controller demand.""" 

618 with _error_handler(): 

619 await self.config.agent.require().call( 

620 agent_configure_request, 

621 AgentConfigureRequest(controller_demand_override={controller_id: req.state}), 

622 ) 

623 

624 return _status_ok() 

625 

626 @app.post("/agent/scheduler/enable", tags=["Agent"]) 

627 async def enable_scheduler(): 

628 """Enable agent scheduling.""" 

629 with _error_handler(): 

630 await self.config.agent.require().call( 

631 agent_configure_request, 

632 AgentConfigureRequest(scheduling_enabled=True), 

633 ) 

634 

635 return _status_ok() 

636 

637 @app.post("/agent/scheduler/disable", tags=["Agent"]) 

638 async def disable_scheduler(): 

639 """Disable agent scheduling.""" 

640 with _error_handler(): 

641 await self.config.agent.require().call( 

642 agent_configure_request, 

643 AgentConfigureRequest(scheduling_enabled=False), 

644 ) 

645 

646 return _status_ok() 

647 

648 @app.post("/agent/scheduler/include/{program_id}", tags=["Agent"]) 

649 async def include_program(program_id: str): 

650 """Include a program for agent consideration.""" 

651 with _error_handler(): 

652 await self.config.agent.require().call( 

653 agent_configure_request, 

654 AgentConfigureRequest(remove_program_exclusions={program_id}), 

655 ) 

656 

657 return _status_ok() 

658 

659 @app.post("/agent/scheduler/exclude/{program_id}", tags=["Agent"]) 

660 async def exclude_program(program_id: str): 

661 """Exclude a program from agent consideration.""" 

662 with _error_handler(): 

663 await self.config.agent.require().call( 

664 agent_configure_request, 

665 AgentConfigureRequest(add_program_exclusions={program_id}), 

666 ) 

667 

668 return _status_ok() 

669 

670 async def _start_forwarders(self, *, task_group: asyncio.TaskGroup): 

671 """Start the KV/stream forwarders and any configured data-product handlers. 

672 

673 Split out from `serve` only so tests can drive it without running the uvicorn 

674 server. Not for use elsewhere: calling this and `serve` both would start two sets 

675 of forwarder tasks. 

676 """ 

677 await self.kv_forwarder.start(task_group=task_group) 

678 await self.stream_forwarder.start(task_group=task_group) 

679 

680 self._serve_handlers = [] 

681 self._product_forwarders = [] 

682 

683 for serve_config in self.config.serve_data_products: 

684 handler = serve_config.create_handler() 

685 forwarder = ProductForwarder(handler, targets=self.client_queues) 

686 

687 await forwarder.start(task_group=task_group) 

688 handler.start_monitor(task_group=task_group) 

689 

690 self._serve_handlers.append(handler) 

691 self._product_forwarders.append(forwarder) 

692 

693 def _warn_if_exposed(self): 

694 """Warn when the service is reachable off-host without TLS or authentication.""" 

695 if self.config.host in LOOPBACK_HOSTS: 

696 return 

697 

698 missing = [ 

699 name 

700 for name, present in ( 

701 ("TLS", self.config.tls is not None), 

702 ("authentication", self.authenticator.enabled), 

703 ) 

704 if not present 

705 ] 

706 

707 if missing: 

708 logger.warning( 

709 f"web API is bound to {self.config.host}:{self.config.port} with no " 

710 f"{' and no '.join(missing)}; anyone who can reach it can control this system" 

711 ) 

712 

713 async def serve(self, *, task_group: asyncio.TaskGroup): 

714 """Run the FastAPI server.""" 

715 # Already shut down or shutting down. 

716 if self.server.should_exit: 

717 return 

718 

719 self._stopped.clear() 

720 

721 try: 

722 await self._start_forwarders(task_group=task_group) 

723 

724 if self.config.tls is not None: 

725 # Loading the config is what builds the SSL context, and also what surfaces 

726 # an unreadable or mismatched certificate and key. 

727 self.server.config.load() 

728 

729 if (context := self.server.config.ssl) is not None: 

730 self.config.tls.apply_minimum_version(context) 

731 

732 self._warn_if_exposed() 

733 

734 await self.server.serve() 

735 finally: 

736 self._stopped.set() 

737 

738 async def shutdown(self): 

739 # Unblock any parked firehose generators so uvicorn's graceful shutdown 

740 # isn't stuck waiting on a never-ending SSE response. Snapshot the set 

741 # because each generator removes its own queue on exit. 

742 for queue in tuple(self.client_queues): 

743 if queue.full(): 

744 # Give up a record to make room for the sentinel. 

745 with contextlib.suppress(asyncio.QueueEmpty): 

746 queue.get_nowait() 

747 

748 queue.put_nowait(None) 

749 

750 # Signal a graceful shutdown to Uvicorn. Note that explicitly shutting down the server here 

751 # does not cause `serve` to return! 

752 self.server.should_exit = True 

753 await self._stopped.wait() 

754 

755 for handler in self._serve_handlers: 

756 await handler.stop_monitor() 

757 

758 for forwarder in self._product_forwarders: 

759 await forwarder.stop() 

760 

761 await self.kv_forwarder.stop() 

762 await self.stream_forwarder.stop()