Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.git
.github
.venv
__pycache__
.pytest_cache
.pytest-tmp
.env
backups
data/streaming
docs/images
21 changes: 21 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copy to .env for local use. Never commit real secrets.
APP_ENV=development
APP_VERSION=4.0.0
LOG_LEVEL=INFO
LOG_JSON=true
REQUIRE_API_KEY=false
API_KEY=replace-with-at-least-16-random-characters
CORS_ORIGINS=http://localhost:8501
TRUSTED_HOSTS=localhost,127.0.0.1,testserver
METRICS_ENABLED=true
MAX_REQUEST_BODY_BYTES=1048576

# Enable these for the optional PostgreSQL warehouse.
POSTGRES_DB=project_rising
POSTGRES_USER=rising_user
POSTGRES_PASSWORD=replace-with-a-strong-password
DATABASE_URL=postgresql+psycopg2://rising_user:replace-with-a-strong-password@postgres:5432/project_rising
DATABASE_REQUIRED=false
DATABASE_CONNECT_TIMEOUT_SECONDS=5
DATABASE_MAX_RETRIES=3

26 changes: 23 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Project RISING Tests
name: Project RISING CI

on:
push:
Expand All @@ -9,7 +9,7 @@ permissions:

jobs:
test:
name: Pytest (Python 3.11)
name: Test and validate (Python 3.11)
runs-on: ubuntu-latest

steps:
Expand All @@ -28,4 +28,24 @@ jobs:
python -m pip install -r requirements.txt

- name: Run tests
run: python -m pytest -v
run: python -m pytest -q

- name: Compile Python modules
run: python -m compileall -q api config demo pipelines schemas streaming warehouse main.py

- name: Validate production configuration
env:
APP_ENV: production
REQUIRE_API_KEY: "true"
API_KEY: ci-only-api-key-000000000000
CORS_ORIGINS: https://pilot.example.org
TRUSTED_HOSTS: pilot.example.org
run: python -c "from config.config import get_settings; print(get_settings().environment)"

container:
name: Build container
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build pilot image
run: docker build --tag project-rising:${{ github.sha }} .
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@ __pycache__/
.pytest_cache/
.pytest-tmp/
data/streaming/
.env
.venv*/
.coverage
htmlcov/
*.log
backups/

.pytest-vscode/
22 changes: 22 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM python:3.11-slim AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PORT=8000

WORKDIR /app

RUN addgroup --system rising && adduser --system --ingroup rising rising

COPY requirements.txt .
RUN python -m pip install --upgrade pip && python -m pip install -r requirements.txt

COPY --chown=rising:rising . .
USER rising

EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"

CMD ["sh", "-c", "python -m uvicorn main:app --host 0.0.0.0 --port ${PORT} --proxy-headers --forwarded-allow-ips='*'"]
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ Open <http://127.0.0.1:8000/docs>, or get a real sample prediction:
curl http://127.0.0.1:8000/api/v1/disease-risk/sample
```

For a pilot-like local deployment, copy `.env.example` to `.env`, replace all
placeholder secrets, then run `docker compose up --build -d`. Liveness is at
`/health`, dependency readiness at `/ready`, and API-key-protected Prometheus
metrics at `/metrics`. See the [pilot deployment runbook](docs/operations/pilot_runbook.md).

Start the dashboard in a second terminal:

```bash
Expand Down Expand Up @@ -158,6 +163,8 @@ docker compose exec postgres psql -U rising_user -d project_rising -c "SELECT ev
| Method | Endpoint | Purpose |
|---|---|---|
| `GET` | `/health` | Service health check |
| `GET` | `/ready` | Required data and dependency readiness |
| `GET` | `/metrics` | Prometheus metrics (protected when API keys are enabled) |
| `GET` | `/api/v1/health-indicators` | Filter processed health indicators |
| `GET` | `/api/v1/climate-events` | Read accepted climate events when configured |
| `GET` | `/api/v1/pipeline/status` | Inspect pipeline readiness |
Expand Down
13 changes: 13 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Security Policy

Project RISING is a pilot decision-support prototype and does not accept
patient-level or other sensitive personal data. Report vulnerabilities
privately to the repository owner; do not include secrets or real health data
in an issue.

Production pilots must use HTTPS, API-key protection, explicit CORS and trusted
hosts, managed secrets, least-privilege database credentials, encrypted
backups, centralized logs, dependency scanning, and a documented key-rotation
procedure. The single shared API key is suitable only for a small controlled
pilot. Multi-user identity, roles, audit-grade access records, regulatory
review, and independent penetration testing are required before broader use.
45 changes: 45 additions & 0 deletions api/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from __future__ import annotations

import json
import logging
from datetime import datetime, timezone
from typing import Any


class JsonFormatter(logging.Formatter):
"""Emit one machine-readable JSON object per log record."""

def format(self, record: logging.LogRecord) -> str:
payload: dict[str, Any] = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
for field in (
"request_id",
"method",
"path",
"status_code",
"duration_ms",
"environment",
):
value = getattr(record, field, None)
if value is not None:
payload[field] = value
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, default=str)


def configure_logging(level: str = "INFO", json_logs: bool = True) -> None:
handler = logging.StreamHandler()
handler.setFormatter(
JsonFormatter()
if json_logs
else logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
)
root_logger = logging.getLogger()
root_logger.handlers.clear()
root_logger.addHandler(handler)
root_logger.setLevel(level)
49 changes: 49 additions & 0 deletions api/observability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from __future__ import annotations

import threading
from collections import Counter
from time import perf_counter


class Metrics:
"""Small dependency-free Prometheus metrics registry for pilot operation."""

def __init__(self) -> None:
self._lock = threading.Lock()
self._requests: Counter[tuple[str, str, int]] = Counter()
self._duration_seconds: Counter[tuple[str, str]] = Counter()
self._started = perf_counter()

def observe(self, method: str, path: str, status_code: int, duration: float) -> None:
normalized_path = path if not path.startswith("/api/v1/countries/") else "/api/v1/countries/{country}/risk"
with self._lock:
self._requests[(method, normalized_path, status_code)] += 1
self._duration_seconds[(method, normalized_path)] += duration

def render(self) -> str:
lines = [
"# HELP rising_uptime_seconds Process uptime in seconds.",
"# TYPE rising_uptime_seconds gauge",
f"rising_uptime_seconds {perf_counter() - self._started:.6f}",
"# HELP rising_http_requests_total HTTP requests by method, path, and status.",
"# TYPE rising_http_requests_total counter",
]
with self._lock:
for (method, path, status), count in sorted(self._requests.items()):
lines.append(
f'rising_http_requests_total{{method="{method}",path="{path}",status="{status}"}} {count}'
)
lines.extend(
[
"# HELP rising_http_request_duration_seconds_total Cumulative request duration.",
"# TYPE rising_http_request_duration_seconds_total counter",
]
)
for (method, path), duration in sorted(self._duration_seconds.items()):
lines.append(
f'rising_http_request_duration_seconds_total{{method="{method}",path="{path}"}} {duration:.6f}'
)
return "\n".join(lines) + "\n"


metrics = Metrics()
6 changes: 3 additions & 3 deletions api/routes/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

@router.get("")
def list_health_indicators(
country: str | None = Query(default=None),
indicator: str | None = Query(default=None),
country: str | None = Query(default=None, min_length=2, max_length=100),
indicator: str | None = Query(default=None, min_length=2, max_length=150),
year: int | None = Query(
default=None,
ge=1900,
Expand Down Expand Up @@ -90,4 +90,4 @@ def list_indicators() -> dict[str, Any]:
return {
"count": len(indicators),
"indicators": indicators,
}
}
6 changes: 4 additions & 2 deletions api/routes/pipeline.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
from typing import Any

from fastapi import APIRouter
from fastapi import APIRouter, Depends

from api.services.data_service import get_pipeline_status
from api.security import verify_api_key


router = APIRouter(
prefix="/pipeline",
tags=["Pipeline Monitoring"],
dependencies=[Depends(verify_api_key)],
)


@router.get("/status")
def pipeline_status() -> dict[str, Any]:
"""Return the current batch and streaming pipeline status."""

return get_pipeline_status()
return get_pipeline_status()
11 changes: 7 additions & 4 deletions api/routes/prediction.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import Any, Literal

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, ConfigDict, Field

from api.services.disease_risk_service import predict_disease_risk
from api.security import verify_api_key


router = APIRouter(
Expand All @@ -13,7 +14,9 @@


class DiseaseRiskRequest(BaseModel):
country: str = Field(examples=["Philippines"])
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

country: str = Field(min_length=2, max_length=100, examples=["Philippines"])
disease: Literal["dengue", "malaria", "mosquito_borne"] = "dengue"
temperature_c: float = Field(ge=-10, le=55, examples=[29.0])
rainfall_mm: float = Field(ge=0, le=2000, examples=[180.0])
Expand All @@ -31,7 +34,7 @@ def _predict(payload: DiseaseRiskRequest) -> dict[str, Any]:
raise HTTPException(status_code=503, detail=str(error)) from error


@router.post("/predict")
@router.post("/predict", dependencies=[Depends(verify_api_key)])
def disease_risk_prediction(payload: DiseaseRiskRequest) -> dict[str, Any]:
"""Predict explainable 14-day mosquito-borne disease risk."""

Expand Down
8 changes: 5 additions & 3 deletions api/routes/risk.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any

from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Path

from api.services.data_service import get_country_risk

Expand All @@ -12,7 +12,9 @@


@router.get("/{country}/risk")
def country_risk(country: str) -> dict[str, Any]:
def country_risk(
country: str = Path(min_length=2, max_length=100),
) -> dict[str, Any]:
"""Return a transparent comparative country-risk score."""

try:
Expand All @@ -31,4 +33,4 @@ def country_risk(country: str) -> dict[str, Any]:
raise HTTPException(
status_code=503,
detail=str(error),
) from error
) from error
27 changes: 27 additions & 0 deletions api/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from __future__ import annotations

import secrets

from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader

from config.config import get_settings


api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)


def verify_api_key(provided_key: str | None = Security(api_key_header)) -> None:
"""Require a configured API key for protected pilot operations."""

settings = get_settings()
if not settings.require_api_key:
return

expected = settings.api_key.get_secret_value() if settings.api_key else ""
if not provided_key or not secrets.compare_digest(provided_key, expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="A valid API key is required",
headers={"WWW-Authenticate": "ApiKey"},
)
Loading
Loading