Files
socaichat/backend/app/main.py
T
2026-04-08 19:15:19 +08:00

88 lines
2.3 KiB
Python

"""Litestar application entry point."""
from __future__ import annotations
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator
from dotenv import load_dotenv
# Load .env before anything else reads settings
load_dotenv()
from litestar import Litestar
from litestar.config.cors import CORSConfig
from app.api.chat import stream_chat
from app.api.conversations import (
create_conversation,
delete_conversation,
get_conversation,
list_conversations,
update_conversation,
)
from app.api.attachments import (
delete_attachment,
download_attachment,
get_attachment,
upload_attachment,
)
from app.api.health import health_check
from app.api.tickets import get_ticket, get_tickets_summary, list_tickets
from app.cache.redis import close_redis
from app.storage.blob import close_blob_client, ensure_container
from app.store.memory import close_checkpointer
from app.store.postgres import create_tables, dispose_engine
from app.tasks.bus import close_service_bus
cors_config = CORSConfig(
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=False,
)
@asynccontextmanager
async def lifespan(app: Litestar) -> AsyncGenerator[None, None]:
"""Application lifespan: create tables on startup, dispose engine on shutdown."""
import logging
await create_tables()
# Pre-create blob container (best-effort; skip if storage not configured)
try:
await ensure_container()
except Exception:
logging.getLogger(__name__).warning(
"Blob container init skipped (storage may not be configured)",
exc_info=True,
)
yield
await close_checkpointer()
await close_redis()
await close_blob_client()
await close_service_bus()
await dispose_engine()
app = Litestar(
route_handlers=[
health_check,
stream_chat,
list_conversations,
get_conversation,
create_conversation,
update_conversation,
delete_conversation,
get_tickets_summary,
list_tickets,
get_ticket,
upload_attachment,
get_attachment,
download_attachment,
delete_attachment,
],
cors_config=cors_config,
lifespan=[lifespan],
debug=False,
)