import asyncio
import hashlib
import json
import logging
import time
from collections import defaultdict, deque
from dataclasses import dataclass
from typing import Dict, Optional, Tuple
from urllib.parse import urljoin
import aiohttp
import yaml
from fastapi import FastAPI, Request, Response
from fastapi.responses import StreamingResponse
from prometheus_client import Counter, Gauge, Histogram, generate_latest
from rapidfuzz import fuzz # For semantic diff scoring
from dataclasses_json import dataclass_json
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="SSTF Proxy")
# Prometheus Metrics
shadow_requests = Counter('sstf_shadow_requests_total', 'Shadow requests')
diff_count = Counter('sstf_diffs_total', 'Response diffs', ['type'])
shadow_latency = Histogram('sstf_shadow_latency_seconds', 'Shadow latency')
diff_rate_gauge = Gauge('sstf_diff_rate_percent', 'Current diff rate %')
circuit_state = Gauge('sstf_circuit_state', 'Circuit: 1=closed, 0=open, -1=half-open')
@dataclass_json
@dataclass
class Config:
primary_url: str
shadow_url: str
sample_pct: float = 1.0 # 0-100
diff_threshold_pct: float = 5.0
latency_multiplier: float = 3.0
shadow_timeout: float = 5.0
window_size: int = 1000 # Sliding window for rates
config_file: str = "sstf.yaml"
config = Config(primary_url="http://primary:8080", shadow_url="http://shadow:8080")
# Load config
def load_config():
global config
with open(config.config_file, 'r') as f:
loaded = yaml.safe_load(f)
config = Config.from_dict(loaded)
logger.info(f"Loaded config: {config}")
load_config()
# State
stats = defaultdict(lambda: deque(maxlen=config.window_size))
circuit_open_until = 0.0 # Timestamp when circuit reopens
request_id = 0
class DiffEngine:
@staticmethod
def compute_diff(primary_resp: Dict, shadow_resp: Dict) -> Tuple[str, float]:
"""Compute diff type and score (0-1, higher=more different)."""
diffs = []
score = 0.0
# Status diff
if primary_resp['status'] != shadow_resp['status']:
diffs.append(f"status:{primary_resp['status']}->{shadow_resp['status']}")
score += 0.3
# Headers diff (key subset)
p_headers = {k.lower(): v for k, v in primary_resp['headers'].items()
if k.lower() in ['content-type', 'etag']}
s_headers = {k.lower(): v for k, v in shadow_resp['headers'].items()
if k.lower() in ['content-type', 'etag']}
if p_headers != s_headers:
diffs.append(f"headers:{p_headers}=>{s_headers}")
score += 0.2
# Body diff (hash + fuzzy for text)
p_body_hash = hashlib.md5(primary_resp['body'].encode()).hexdigest()
s_body_hash = hashlib.md5(shadow_resp['body'].encode()).hexdigest()
if p_body_hash != s_body_hash:
if primary_resp['content_type'].startswith('text/'):
fuzzy_score = fuzz.ratio(primary_resp['body'], shadow_resp['body']) / 100
score += (1 - fuzzy_score) * 0.5
else:
score += 0.5
diffs.append("body")
diff_type = ','.join(diffs) or 'none'
return diff_type, score
diff_engine = DiffEngine()
async def forward_request(session: aiohttp.ClientSession, url: str, method: str, headers: Dict,
body: Optional[bytes], timeout: float) -> Dict:
"""Forward request and capture response."""
start = time.time()
try:
async with session.request(method, url, headers=headers, data=body,
timeout=aiohttp.ClientTimeout(total=timeout)) as resp:
body_bytes = await resp.read()
return {
'status': resp.status,
'headers': dict(resp.headers),
'body': body_bytes.decode('utf-8', errors='ignore'),
'content_type': resp.headers.get('content-type', ''),
'latency': time.time() - start
}
except Exception as e:
logger.warning(f"Request failed to {url}: {e}")
return {'status': 500, 'headers': {}, 'body': str(e), 'content_type': '', 'latency': time.time() - start}
async def handle_shadow(request: Request) -> None:
"""Async shadow request + diff + stats."""
global request_id
request_id += 1
rid = request_id
method = request.method
url = urljoin(config.shadow_url, request.url.path) + '?' + request.url.query.decode()
headers = dict(request.headers)
body = await request.body()
async with aiohttp.ClientSession() as session:
shadow_resp = await forward_request(session, url, method, headers, body, config.shadow_timeout)
shadow_requests.inc()
shadow_latency.observe(shadow_resp['latency'])
# Only diff if primary succeeded (we'll get primary_resp from main handler)
stats[rid]['shadow'] = shadow_resp
async def check_abort(primary_resp: Dict, shadow_resp: Dict) -> bool:
"""Check if we should abort shadowing."""
if time.time() < circuit_open_until:
return True
diff_type, score = diff_engine.compute_diff(primary_resp, shadow_resp)
diff_count.labels(type=diff_type).inc()
# Update rates
window = list(stats['diffs']) if 'diffs' in stats else []
window.append(1 if score > 0 else 0)
stats['diffs'] = deque(window, maxlen=config.window_size)
diff_rate = (sum(window) / len(window)) * 100 if window else 0
diff_rate_gauge.set(diff_rate)
# Latency check
if shadow_resp['latency'] > primary_resp['latency'] * config.latency_multiplier:
logger.warning("Latency abort")
return True
# Diff score check (avg > threshold)
if diff_rate > config.diff_threshold_pct:
logger.warning(f"Diff rate abort: {diff_rate}%")
return True
return False
@app.middleware("http")
async def shadow_middleware(request: Request, call_next):
method = request.method
url = urljoin(config.primary_url, request.url.path) + '?' + request.url.query.decode()
headers = dict(request.headers)
body = await request.body()
primary_start = time.time()
primary_resp_data = None
async with aiohttp.ClientSession() as session:
# Primary request (blocking path)
primary_resp_data = await forward_request(session, url, method, headers, body,
config.shadow_timeout * 2) # Longer for primary
# Shadow if sampled and circuit closed
if (config.sample_pct / 100 > (request_id % 10000) / 10000 and
time.time() >= circuit_open_until):
asyncio.create_task(handle_shadow(request))
primary_latency = time.time() - primary_start
# Wait for shadow if in progress (simple poll for demo; use queues in prod)
shadow_resp_data = stats.get(request_id, {}).get('shadow')
if shadow_resp_data:
# Check abort
if check_abort(primary_resp_data, shadow_resp_data):
global circuit_open_until
circuit_open_until = time.time() + 60 # 1 min cooldown
circuit_state.set(0) # Open
# Cleanup
stats.pop(request_id, None)
# Return primary response
status = primary_resp_data['status']
headers_out = {k: v for k, v in primary_resp_data['headers'].items()
if k.lower() not in ['content-length']}
body_out = primary_resp_data['body'].encode()
primary_resp_data['latency'] = primary_latency # Override with measured
return Response(content=body_out, status_code=status, headers=headers_out)
@app.get("/metrics")
async def metrics():
return StreamingResponse(generate_latest(), media_type="text/plain")
@app.post("/config")
async def update_config(body: dict):
global config
config = Config.from_dict(body)
with open(config.config_file, 'w') as f:
yaml.dump(config.to_dict(), f)
load_config()
return {"status": "updated"}
@app.get("/circuit")
async def circuit_status():
state = "closed" if time.time() >= circuit_open_until else "open"
return {"state": state, "reopen_at": circuit_open_until}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)