import asyncpg
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from contextlib import asynccontextmanager
DATABASE_URL = "postgresql+asyncpg://postgres:secret@localhost/analytics"
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
Base = declarative_base()
async def get_db():
async with AsyncSessionLocal() as session:
yield session
@asynccontextmanager
async def set_tenant_context(tenant_id: str, session):
await session.execute(asyncpg.execute, f"SET app.current_tenant = '{tenant_id}'")
try:
yield
finally:
await session.execute(asyncpg.execute, "RESET app.current_tenant")
app/models.py:
python
from sqlalchemy import Column, UUID, BigInteger, DateTime, String, func
from ..database import Base
import uuid
class Event(Base):
__tablename__ = "events"
id = Column(BigInteger, primary_key=True, index=True)
tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
user_id = Column(String, index=True)
revenue = Column(BigInteger)
timestamp = Column(DateTime(timezone=True), server_default=func.now())
RLS Setup (run once via migration or psql):
sql
-- Enable RLS on table
ALTER TABLE events ENABLE ROW LEVEL SECURITY;
-- Policy: Users can only see their tenant's rows
CREATE POLICY tenant_isolation ON events
USING (tenant_id = current_setting('app.current_tenant')::uuid);
Alembic Migration (alembic revision --autogenerate -m "init" then edit):
import aioredis
import hashlib
import json
import time
from typing import Dict, Any
redis = aioredis.from_url("redis://localhost:6379")
async def check_quota(tenant_id: str, quota_key: str = "queries_per_hour") -> bool:
"""Check if tenant has quota remaining. Returns True if OK."""
now = int(time.time() // 3600) # Hourly bucket
key = f"quota:{tenant_id}:{quota_key}:{now}"
# Tenant quotas (hardcoded; store in DB for prod)
limits = {"tenant_a": 100, "tenant_b": 1000} # UUIDs in prod
limit = limits.get(tenant_id, 10)
current = await redis.get(key)
if current and int(current) >= limit:
return False
return True
async def increment_quota(tenant_id: str, quota_key: str = "queries_per_hour"):
now = int(time.time() // 3600)
key = f"quota:{tenant_id}:{quota_key}:{now}"
await redis.incr(key)
await redis.expire(key, 3600) # Auto-expire
async def get_cache(tenant_id: str, query_json: str) -> Dict[Any, Any] | None:
key = f"cache:tenant:{tenant_id}:query:{hashlib.sha256(query_json.encode()).hexdigest()}"
data = await redis.get(key)
return json.loads(data) if data else None
async def set_cache(tenant_id: str, query_json: str, result: Dict[Any, Any], ttl: int = 3600):
key = f"cache:tenant:{tenant_id}:query:{hashlib.sha256(query_json.encode()).hexdigest()}"
await redis.set(key, json.dumps(result), ex=ttl)
5. Query Builder (app/query_builder.py)
python
from sqlalchemy import text, select, func
from sqlalchemy.sql import ColumnElement
from pydantic import BaseModel
from typing import List, Dict, Any
class AnalyticsQuery(BaseModel):
metrics: List[str] # e.g., ["revenue", "count"]
dimensions: List[str] = [] # e.g., ["user_id"]
filters: Dict[str, Any] = {} # e.g., {"timestamp": {"gte": "2023-01-01"}}
group_by: List[str] | None = None
limit: int = 1000
# Whitelist for security
WHITELISTED_COLUMNS = {
"metrics": {"revenue", "count(*)", "sum(revenue)"},
"dimensions": {"user_id", "timestamp"}
}
def build_sql(query: AnalyticsQuery):
# Simple builder: SELECT metrics, GROUP BY dimensions FROM events WHERE ...
# Prod: Use full SQL parser or Cube.js-like.
metrics_sql = ", ".join(query.metrics)
if "count" not in metrics_sql:
metrics_sql = f"{metrics_sql}, count(*) as count"
base = text(f"""
SELECT {metrics_sql}
FROM events
WHERE 1=1
""")
# Add filters (sanitize!)
for col, val in query.filters.items():
if col in WHITELISTED_COLUMNS["dimensions"]:
base = base + text(f" AND {col} >= '{val.get('gte', '')}'") # Escape properly in prod!
if query.dimensions:
dims = ", ".join(query.dimensions)
base = base + text(f" GROUP BY {dims}")
base = base.columns(limit=query.limit)
return base
6. Main App (app/main.py)
python
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer
from fastapi.middleware.base import BaseHTTPMiddleware
import jwt
from pydantic import BaseModel
from typing import Dict, Any
from sqlalchemy import select
from sqlalchemy.sql import text
import json
from .database import get_db, set_tenant_context
from .models import Event
from .redis import check_quota, increment_quota, get_cache, set_cache
from .query_builder import AnalyticsQuery, build_sql
app = FastAPI()
security = HTTPBearer()
class QueryRequest(BaseModel):
query: AnalyticsQuery
# Middleware: Set tenant from JWT
class TenantMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if "Authorization" in request.headers:
token = request.headers["Authorization"].replace("Bearer ", "")
try:
payload = jwt.decode(token, "secret", algorithms=["HS256"]) # Prod: RS256 + public key
request.state.tenant_id = payload["tenant_id"]
except:
pass
response = await call_next(request)
return response
app.add_middleware(TenantMiddleware)
@app.post("/analytics/query")
async def analytics_query(
req: QueryRequest,
token: str = Depends(security),
db = Depends(get_db)
):
tenant_id = getattr(token.credentials, 'tenant_id', None) # From middleware? Wait, use Depends
# Extract from token properly
payload = jwt.decode(token.credentials, "secret", algorithms=["HS256"])
tenant_id = payload["tenant_id"]
if not await check_quota(tenant_id):
raise HTTPException(status_code=429, detail="Quota exceeded")
query_json = req.query.model_dump_json()
# Check cache
cached = await get_cache(tenant_id, query_json)
if cached:
await increment_quota(tenant_id) # Count cached hits too?
return cached
# Build & execute query
async with set_tenant_context(tenant_id, db):
sql = build_sql(req.query)
result = await db.execute(sql)
data = result.fetchall()
response = [dict(row._mapping) for row in data] # Convert to dicts
# Cache & quota
await set_cache(tenant_id, query_json, response)
await increment_quota(tenant_id)
return {"data": response, "rows": len(response)}
# Sample data loader (for testing)
@app.post("/events")
async def add_event(events: list[Dict], token: str = Depends(security), db=Depends(get_db)):
payload = jwt.decode(token.credentials, "secret", algorithms=["HS256"])
tenant_id = payload["tenant_id"]
async with set_tenant_context(tenant_id, db):
for event in events:
event["tenant_id"] = tenant_id
db.add(Event(**event))
await db.commit()