fractafrag/services/api/app/middleware/rate_limit.py
John Lightner 05d39fdda8 M0: Foundation scaffold — Docker Compose, DB schema, FastAPI app, all service stubs
Track A (Infrastructure & Data Layer):
- docker-compose.yml with all 7 services (nginx, frontend, api, mcp, renderer, worker, postgres, redis)
- docker-compose.override.yml for local dev (hot reload, port exposure)
- PostgreSQL init.sql with full schema (15 tables, pgvector indexes, creator economy stubs)
- .env.example with all required environment variables

Track A+B (API Layer):
- FastAPI app with 10 routers (auth, shaders, feed, votes, generate, desires, users, payments, mcp_keys, health)
- SQLAlchemy ORM models for all 15 tables
- Pydantic schemas for all request/response types
- JWT auth middleware (access + refresh tokens, Redis blocklist)
- Redis rate limiting middleware
- Celery worker config with job stubs (render, embed, generate, feed cache, expire bounties)
- Alembic migration framework

Service stubs:
- MCP server (health endpoint, 501 for all tools)
- Renderer service (Express + Puppeteer scaffold, 501 for /render)
- Frontend (package.json with React/Vite/Three.js/TanStack/Tailwind deps)
- Nginx reverse proxy config (/, /api, /mcp, /renders)

Project:
- DECISIONS.md with 11 recorded architectural decisions
- README.md with architecture overview
- Sample shader seed data (plasma, fractal noise, raymarched sphere)
2026-03-24 20:45:08 -05:00

59 lines
1.7 KiB
Python

"""Fractafrag — Redis-backed rate limiting middleware."""
import time
from fastapi import Request, HTTPException, status
from app.redis import get_redis
async def check_rate_limit(
key: str,
max_requests: int,
window_seconds: int = 60,
):
"""
Check and enforce rate limit.
Args:
key: Unique identifier (e.g., "ip:1.2.3.4" or "user:uuid")
max_requests: Maximum requests allowed in the window
window_seconds: Time window in seconds
Raises:
HTTPException 429 if rate limit exceeded
"""
redis = await get_redis()
redis_key = f"ratelimit:{key}"
pipe = redis.pipeline()
now = time.time()
window_start = now - window_seconds
# Remove old entries outside the window
pipe.zremrangebyscore(redis_key, 0, window_start)
# Count current entries
pipe.zcard(redis_key)
# Add current request
pipe.zadd(redis_key, {str(now): now})
# Set TTL on the key
pipe.expire(redis_key, window_seconds)
results = await pipe.execute()
current_count = results[1]
if current_count >= max_requests:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"Rate limit exceeded. Max {max_requests} requests per {window_seconds}s.",
headers={"Retry-After": str(window_seconds)},
)
async def rate_limit_ip(request: Request, max_requests: int = 100):
"""Rate limit by IP address. Default: 100 req/min."""
ip = request.client.host if request.client else "unknown"
await check_rate_limit(f"ip:{ip}", max_requests)
async def rate_limit_user(user_id: str, max_requests: int = 300):
"""Rate limit by user ID. Default: 300 req/min."""
await check_rate_limit(f"user:{user_id}", max_requests)