video-accessibility/backend/app/core/database.py
Vadym Samoilenko 31199f8705 chore: push all session changes — backend hardening, tests, apache config, deploy scripts
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 15:52:14 +01:00

82 lines
2.9 KiB
Python

from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from ..core.logging import get_logger
from .config import settings
logger = get_logger(__name__)
class MongoDB:
client: AsyncIOMotorClient = None
database: AsyncIOMotorDatabase = None
mongodb = MongoDB()
async def connect_to_mongo():
logger.info("Connecting to MongoDB...")
mongodb.client = AsyncIOMotorClient(settings.mongodb_uri)
mongodb.database = mongodb.client[settings.mongodb_db]
# Test connection
try:
await mongodb.client.admin.command('ping')
logger.info("Successfully connected to MongoDB")
except Exception as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise
async def close_mongo_connection():
logger.info("Closing MongoDB connection...")
if mongodb.client:
mongodb.client.close()
async def get_database() -> AsyncIOMotorDatabase:
return mongodb.database
async def create_indexes():
"""Create database indexes as specified in the development plan"""
db = mongodb.database
# Jobs collection indexes
await db.jobs.create_index([("status", 1), ("created_at", -1)])
await db.jobs.create_index([("client_id", 1)])
# Users collection indexes
await db.users.create_index([("email", 1)], unique=True)
# Audit logs collection indexes - comprehensive indexing for audit queries
await db.audit_logs.create_index([("timestamp", -1)]) # Primary sort field
await db.audit_logs.create_index([("action", 1), ("timestamp", -1)]) # Filter by action
await db.audit_logs.create_index([("user_id", 1), ("timestamp", -1)]) # User activity
await db.audit_logs.create_index([("severity", 1), ("timestamp", -1)]) # Security events
await db.audit_logs.create_index([("resource_type", 1), ("resource_id", 1)]) # Resource tracking
await db.audit_logs.create_index([("ip_address", 1), ("timestamp", -1)]) # IP-based analysis
await db.audit_logs.create_index([("success", 1), ("timestamp", -1)]) # Failed operations
# Text search index for description and details
await db.audit_logs.create_index([
("description", "text"),
("details", "text"),
("error_message", "text")
])
# Per-language QC assignment index — for linguist queue queries
await db.jobs.create_index([("qc_assignments.linguist_id", 1), ("qc_assignments.status", 1)])
# Review notes collection indexes
await db.review_notes.create_index([("job_id", 1), ("asset_key", 1)])
await db.review_notes.create_index([("job_id", 1), ("asset_key", 1), ("timestamp_seconds", 1)])
await db.review_notes.create_index([("user_id", 1)])
# VTT versions collection indexes
await db.vtt_versions.create_index(
[("job_id", 1), ("lang", 1), ("kind", 1), ("version", -1)],
unique=True,
)
await db.vtt_versions.create_index([("job_id", 1), ("created_at", -1)])
logger.info("Database indexes created successfully")