fix: change middleware to avoid Beanie init

This commit is contained in:
haolou 2025-10-23 13:36:03 +08:00
parent a936f89426
commit 1823a33d45

View File

@ -2,6 +2,7 @@ from fastapi import Request, status, HTTPException
from fastapi.responses import JSONResponse
from webapi.middleware.freeleaps_auth_middleware import request_context_var
from common.log.module_logger import ModuleLogger
from backend.models.base_doc import BaseDoc
class DatabaseMiddleware:
@ -39,41 +40,50 @@ class DatabaseMiddleware:
return await response(scope, receive, send)
if not product_id:
# Compatibility / public routes: use main database with tenant models initialized
# Compatibility / public routes: use main database
await self.module_logger.log_info(f"No product_id - using main database for path: {request.url.path}")
# Get main database with Beanie initialized for tenant models
# Get main database (no Beanie initialization needed with BaseDoc)
main_db_initialized = await tenant_cache.get_main_db_initialized()
request.state.db = main_db_initialized
request.state.product_id = None
await self.module_logger.log_info(f"Successfully initialized main database with tenant models")
# Set the database context for BaseDoc models
BaseDoc.set_tenant_database(main_db_initialized)
await self.module_logger.log_info(f"Successfully initialized main database")
return await self.app(scope, receive, send)
try:
# Get tenant-specific database with Beanie already initialized (cached)
# Get tenant-specific database (no Beanie initialization needed with BaseDoc)
await self.module_logger.log_info(f"Attempting to get tenant database for product_id: {product_id}")
tenant_db = await tenant_cache.get_initialized_db(product_id)
request.state.db = tenant_db
request.state.product_id = product_id
await self.module_logger.log_info(f"Successfully retrieved cached tenant database with Beanie for product_id: {product_id}")
except HTTPException as e:
# Handle tenant not found or inactive (HTTPException from TenantDBCache)
await self.module_logger.log_error(f"Tenant error for {product_id}: [{e.status_code}] {e.detail}")
# Set the database context for BaseDoc models
BaseDoc.set_tenant_database(tenant_db)
await self.module_logger.log_info(f"Successfully retrieved tenant database for product_id: {product_id}")
return await self.app(scope, receive, send)
except ValueError as e:
# Handle tenant not found or inactive (ValueError from TenantDBCache)
await self.module_logger.log_error(f"Tenant error for {product_id}: {str(e)}")
response = JSONResponse(
status_code=e.status_code,
content={"detail": e.detail}
status_code=status.HTTP_404_NOT_FOUND,
content={"detail": str(e)}
)
return await response(scope, receive, send)
except Exception as e:
await self.module_logger.log_error(f"Database error for tenant {product_id}: {str(e)}")
response = JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Database connection error"}
)
return await response(scope, receive, send)
return await self.app(scope, receive, send)