Implement Phase 0b base project against the frozen test contract
All seven services (gateway, ledger, fraud, sanctions, insights, notifier, audit), db/schema.sql plus optional_indexes.sql, scripts/seed.py and smoke.py, the gateway-served frontend, and docker-compose.yml. Plain-text stdlib logging and a weak manual X-Request-Id only -- no observability yet, by design, per test_no_observability.py. Implements all 13 named chaos-flag pathologies from docs/PATHOLOGIES.md behind Redis-backed runtime flags. make smoke and make test-contract pass; make test-baseline and make test-pathology pass except for a handful of load-sensitive tests documented in tests/README.md rather than papered over.
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import asyncio
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.db import engine
|
||||
from common.logging_config import configure_logging
|
||||
from common.redis_client import redis_client
|
||||
|
||||
from . import chaos
|
||||
from .repository import is_match
|
||||
|
||||
SERVICE_NAME = "sanctions"
|
||||
logger = configure_logging(SERVICE_NAME)
|
||||
app = FastAPI(title=SERVICE_NAME)
|
||||
|
||||
|
||||
class LookupRequest(BaseModel):
|
||||
holder_name: str
|
||||
request_id: str = "unknown"
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"service": SERVICE_NAME, "version": "0.1.0"}
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
async def healthz(request: Request):
|
||||
if request.headers.get("X-Ledgerline-Probe") == "chatty-health":
|
||||
logger.info(f"received chatty-health healthz probe from gateway")
|
||||
return {"status": "ok", "service": SERVICE_NAME}
|
||||
|
||||
|
||||
@app.get("/readyz")
|
||||
async def readyz():
|
||||
try:
|
||||
async with engine.connect() as conn:
|
||||
await conn.exec_driver_sql("SELECT 1")
|
||||
except Exception as exc:
|
||||
logger.exception(f"readyz check failed: {exc}")
|
||||
return JSONResponse(status_code=503, content={"status": "unavailable"})
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/internal/lookup")
|
||||
async def lookup(body: LookupRequest):
|
||||
logger.info(f"lookup for holder_name={body.holder_name!r} request_id={body.request_id}")
|
||||
|
||||
if await chaos.sanctions_errors_enabled() and chaos.should_error():
|
||||
logger.info(f"sanctions_errors chaos triggered for request_id={body.request_id}")
|
||||
return JSONResponse(status_code=503, content={"error": "sanctions vendor unavailable"})
|
||||
|
||||
if await chaos.slow_sanctions_enabled():
|
||||
delay = chaos.sample_delay_seconds()
|
||||
logger.info(f"slow_sanctions chaos sleeping {delay:.3f}s for request_id={body.request_id}")
|
||||
await asyncio.sleep(delay)
|
||||
|
||||
match = await is_match(body.holder_name)
|
||||
if match:
|
||||
return {"matched": True, **match}
|
||||
return {"matched": False, "country": None, "list_source": None}
|
||||
@@ -0,0 +1,37 @@
|
||||
"""slow_sanctions and sanctions_errors -- phase-0-base-project-spec.md §7.
|
||||
|
||||
Both flags belong to `sanctions`, the fake third-party watchlist vendor.
|
||||
"""
|
||||
import math
|
||||
import random
|
||||
|
||||
from common.chaos_flags import is_enabled
|
||||
|
||||
_MEDIAN_SECONDS = 0.04
|
||||
_P99_SECONDS = 1.8
|
||||
_MU = math.log(_MEDIAN_SECONDS)
|
||||
_Z99 = 2.326347874
|
||||
_SIGMA = (math.log(_P99_SECONDS) - _MU) / _Z99
|
||||
_TIMEOUT_TRIGGER_PROBABILITY = 0.015
|
||||
_TIMEOUT_TRIGGER_SECONDS = 5.0
|
||||
_ERROR_PROBABILITY = 0.03
|
||||
|
||||
|
||||
async def slow_sanctions_enabled() -> bool:
|
||||
return await is_enabled("slow_sanctions")
|
||||
|
||||
|
||||
async def sanctions_errors_enabled() -> bool:
|
||||
return await is_enabled("sanctions_errors")
|
||||
|
||||
|
||||
def sample_delay_seconds() -> float:
|
||||
"""Log-normal delay: median ~40ms, p99 ~1.8s. 1.5% of calls sleep 5s,
|
||||
which exceeds the caller's 3s downstream timeout and surfaces as one."""
|
||||
if random.random() < _TIMEOUT_TRIGGER_PROBABILITY:
|
||||
return _TIMEOUT_TRIGGER_SECONDS
|
||||
return random.lognormvariate(_MU, _SIGMA)
|
||||
|
||||
|
||||
def should_error() -> bool:
|
||||
return random.random() < _ERROR_PROBABILITY
|
||||
@@ -0,0 +1,19 @@
|
||||
import sqlalchemy as sa
|
||||
|
||||
from common.db import Session
|
||||
|
||||
|
||||
async def is_match(holder_name: str) -> dict | None:
|
||||
"""Case-insensitive exact match against sanctions_entries.normalized_name."""
|
||||
async with Session() as session:
|
||||
result = await session.execute(
|
||||
sa.text(
|
||||
"SELECT country, list_source FROM sanctions_entries "
|
||||
"WHERE lower(normalized_name) = lower(:name) LIMIT 1"
|
||||
),
|
||||
{"name": holder_name},
|
||||
)
|
||||
row = result.first()
|
||||
if row is None:
|
||||
return None
|
||||
return {"country": row.country, "list_source": row.list_source}
|
||||
Reference in New Issue
Block a user