Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b595744e1 | |||
| 4877513bbf | |||
| 9e46bdc460 | |||
| 3860a5d061 | |||
| 7a7aaca064 | |||
| 76781ed238 | |||
| 2b20946ad7 |
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"mcpServers": {
|
|
||||||
"gitea": {
|
|
||||||
"type": "http",
|
|
||||||
"url": "https://git-mcp.farh.net/mcp",
|
|
||||||
"headers": {
|
|
||||||
"Authorization": "Bearer ${GITEA_TOKEN}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,8 +4,8 @@ import bcrypt
|
|||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
def hash_password(password: str) -> str:
|
||||||
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
return str(bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode())
|
||||||
|
|
||||||
|
|
||||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
return bool(bcrypt.checkpw(plain_password.encode(), hashed_password.encode()))
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ class CacheClient:
|
|||||||
return None
|
return None
|
||||||
if isinstance(value, bytes):
|
if isinstance(value, bytes):
|
||||||
return value.decode("utf-8", errors="replace")
|
return value.decode("utf-8", errors="replace")
|
||||||
return value
|
return str(value)
|
||||||
|
|
||||||
async def set(self, key: str, value: str, ttl_seconds: int = 300) -> None:
|
async def set(self, key: str, value: str, ttl_seconds: int = 300) -> None:
|
||||||
if not self._client:
|
if not self._client:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ def _build_engine_kwargs() -> dict:
|
|||||||
kwargs.update(
|
kwargs.update(
|
||||||
pool_size=10,
|
pool_size=10,
|
||||||
max_overflow=20,
|
max_overflow=20,
|
||||||
|
pool_timeout=30,
|
||||||
pool_pre_ping=True,
|
pool_pre_ping=True,
|
||||||
pool_recycle=3600,
|
pool_recycle=3600,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ from cartsnitch_api.routes.user import router as user_router
|
|||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
|
# Lazy import: keep `dispose_engine` out of the top-level imports so a
|
||||||
|
# stale or partially-built database.py never breaks module load on
|
||||||
|
# container start. The function is required for graceful pool cleanup
|
||||||
|
# on shutdown; if the import fails, the cache_client.close() that
|
||||||
|
# follows the yield would mask it. See CAR-1135 for the original
|
||||||
|
# ImportError that motivated this pattern.
|
||||||
from cartsnitch_api.database import dispose_engine
|
from cartsnitch_api.database import dispose_engine
|
||||||
|
|
||||||
await cache_client.initialize()
|
await cache_client.initialize()
|
||||||
|
|||||||
@@ -147,8 +147,8 @@ def _get_client_ip(request: Request) -> str:
|
|||||||
"""Extract client IP, respecting X-Forwarded-For behind a reverse proxy."""
|
"""Extract client IP, respecting X-Forwarded-For behind a reverse proxy."""
|
||||||
forwarded = request.headers.get("x-forwarded-for")
|
forwarded = request.headers.get("x-forwarded-for")
|
||||||
if forwarded:
|
if forwarded:
|
||||||
return forwarded.split(",")[0].strip()
|
return str(forwarded.split(",")[0].strip())
|
||||||
return request.client.host if request.client else "unknown"
|
return str(request.client.host) if request.client else "unknown"
|
||||||
|
|
||||||
|
|
||||||
def _get_rate_limit_key(request: Request) -> tuple[str, RateLimitBackend]:
|
def _get_rate_limit_key(request: Request) -> tuple[str, RateLimitBackend]:
|
||||||
|
|||||||
@@ -1,16 +1,40 @@
|
|||||||
"""Health check and error metrics endpoints."""
|
"""Health check and error metrics endpoints."""
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from cartsnitch_api.auth.dependencies import verify_service_key
|
from cartsnitch_api.auth.dependencies import verify_service_key
|
||||||
|
from cartsnitch_api.database import get_db
|
||||||
from cartsnitch_api.middleware.error_handler import get_error_monitor
|
from cartsnitch_api.middleware.error_handler import get_error_monitor
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(tags=["health"])
|
router = APIRouter(tags=["health"])
|
||||||
|
|
||||||
|
|
||||||
@router.get("/health")
|
@router.get("/health")
|
||||||
async def health():
|
async def health(db: AsyncSession = Depends(get_db)):
|
||||||
return {"status": "ok"}
|
"""Liveness + DB connectivity probe.
|
||||||
|
|
||||||
|
Returns HTTP 200 when the API process is responsive *and* the database
|
||||||
|
is reachable, so Kubernetes readiness probes can correctly route traffic
|
||||||
|
away from pods that have lost their database connection.
|
||||||
|
|
||||||
|
Returns HTTP 503 when the database is unreachable so K8s marks the pod
|
||||||
|
unhealthy and stops sending traffic to it.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await db.execute(text("SELECT 1"))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Health check failed: database unreachable")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail={"status": "unavailable", "database": "disconnected"},
|
||||||
|
) from exc
|
||||||
|
return {"status": "ok", "database": "connected"}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/internal/error-stats", dependencies=[Depends(verify_service_key)])
|
@router.get("/internal/error-stats", dependencies=[Depends(verify_service_key)])
|
||||||
|
|||||||
@@ -3,8 +3,22 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
from cartsnitch_api.database import dispose_engine
|
||||||
from cartsnitch_api.main import app
|
from cartsnitch_api.main import app
|
||||||
|
|
||||||
|
|
||||||
|
def test_dispose_engine_importable_from_database():
|
||||||
|
"""Regression for CAR-1135: api main.py used to import dispose_engine
|
||||||
|
at module level. A stale database.py (no dispose_engine) crashed the
|
||||||
|
container at import time with ImportError on line 9. The fix moved
|
||||||
|
the import inside the lifespan function, but `dispose_engine` must
|
||||||
|
still be importable from `cartsnitch_api.database` for the lifespan
|
||||||
|
teardown to actually close pooled connections.
|
||||||
|
"""
|
||||||
|
assert callable(dispose_engine)
|
||||||
|
assert dispose_engine.__name__ == "dispose_engine"
|
||||||
|
|
||||||
|
|
||||||
EXPECTED_ROUTES = [
|
EXPECTED_ROUTES = [
|
||||||
# Auth (3 — register/login/refresh are handled by Better-Auth service)
|
# Auth (3 — register/login/refresh are handled by Better-Auth service)
|
||||||
("get", "/auth/me"),
|
("get", "/auth/me"),
|
||||||
|
|||||||
Reference in New Issue
Block a user