57 lines
1.4 KiB
Python
57 lines
1.4 KiB
Python
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 in application.state.tasks.values():
|
|
try:
|
|
task.cancel()
|
|
except asyncio.CancelledError:
|
|
pass
|
|
await asyncio.gather(*application.state.tasks.values(), return_exceptions=True)
|
|
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)
|