import asyncio import logging import threading from collections import defaultdict from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from chain_service.logging import setup_logging from chain_service.controllers.__main__ import setup_controllers setup_logging() application = FastAPI() logging.basicConfig(level=logging.DEBUG) @application.on_event("startup") async def startup_event(): application.state.tasks = defaultdict(list) application.state.tasks_lock = asyncio.Lock() @application.on_event("shutdown") async def shutdown_event(): async with application.state.tasks_lock: for task_list in application.state.tasks.values(): for task in task_list: try: task.cancel() except asyncio.CancelledError: pass application.state.tasks.clear() # Subclass threading.Thread for logging class DebugThread(threading.Thread): def __init__(self, *args, **kwargs): logging.debug(f"Creating thread {args} {kwargs}") super().__init__(*args, **kwargs) def _delete(self): logging.debug(f"Deleting thread {self.name}") super()._delete() threading.Thread = DebugThread application.add_middleware( CORSMiddleware, allow_origins=["http://localhost:5173"], allow_methods=["*"], ) setup_controllers(application)