Files
aoc/backend/database.py
Tomas Kracmar 9271b4e461
Some checks failed
CI / lint-and-test (push) Has been cancelled
feat: implement Phase 2 stabilization
- Cache Graph API tokens with expiry-aware reuse in graph/auth.py
- Add tenacity-based retry/backoff wrapper (utils/http.py) and apply to all Graph/source API calls
- Add Pydantic request/response models (models/api.py) and FastAPI query constraints
- Add unit tests for event_model, auth and integration tests for API endpoints
- Configure ruff linter/formatter in pyproject.toml
- Add GitHub Actions CI pipeline (.github/workflows/ci.yml)
- Add requirements-dev.txt with pytest, mongomock, httpx, ruff
- Clean up typing imports and fix ruff linting across codebase
2026-04-14 12:02:28 +02:00

44 lines
1.7 KiB
Python

from contextlib import suppress
import structlog
from config import DB_NAME, MONGO_URI, RETENTION_DAYS
from pymongo import ASCENDING, DESCENDING, TEXT, MongoClient
client = MongoClient(MONGO_URI)
db = client[DB_NAME]
events_collection = db["events"]
logger = structlog.get_logger("aoc.database")
def setup_indexes(max_retries: int = 5, delay: float = 2.0):
"""Ensure MongoDB indexes exist. Retries on connection errors."""
from time import sleep
for attempt in range(1, max_retries + 1):
try:
events_collection.create_index("dedupe_key", unique=True, sparse=True)
events_collection.create_index([("timestamp", DESCENDING)])
events_collection.create_index([("service", ASCENDING), ("timestamp", DESCENDING)])
events_collection.create_index("id")
events_collection.create_index(
[("actor_display", TEXT), ("raw_text", TEXT), ("operation", TEXT)],
name="text_search_index",
)
if RETENTION_DAYS > 0:
events_collection.create_index(
[("timestamp", ASCENDING)],
expireAfterSeconds=RETENTION_DAYS * 24 * 60 * 60,
name="ttl_timestamp",
)
else:
with suppress(Exception):
events_collection.drop_index("ttl_timestamp")
logger.info("MongoDB indexes ensured")
return
except Exception as exc:
if attempt == max_retries:
logger.error("Failed to ensure MongoDB indexes", error=str(exc))
raise
logger.warning("MongoDB not ready, retrying...", attempt=attempt, error=str(exc))
sleep(delay)