Metadata-Version: 2.4
Name: adapt-rate-limiter
Version: 1.0.1
Summary: AI-powered adaptive rate limiter with embedded monitoring dashboard for FastAPI
Author-email: "Jeremiah Caleb I.R" <jeremiahcaleb@mce.edu.in>
License: MIT
Keywords: rate-limiter,fastapi,redis,monitoring,ai,machine-learning,security
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.100.0
Requires-Dist: uvicorn[standard]>=0.22.0
Requires-Dist: redis>=4.5.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: joblib>=1.2.0
Requires-Dist: scikit-learn>=1.2.0
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: httpx; extra == "dev"
Dynamic: license-file

# Adaptive Rate Limiter

[![PyPI version](https://img.shields.io/pypi/v/adapt-rate-limiter)](https://pypi.org/project/adapt-rate-limiter/)
[![Python](https://img.shields.io/pypi/pyversions/adapt-rate-limiter)](https://pypi.org/project/adapt-rate-limiter/)

An **AI-powered adaptive rate limiter** for FastAPI with a fully embedded real-time monitoring dashboard. It uses machine learning (Isolation Forest) combined with statistical traffic analysis to dynamically adjust rate limits per IP.

---

## Features

- 🤖 **AI + Statistical Decision Engine** — Isolation Forest anomaly detection combined with entropy, burstiness, and interval analysis
- 📊 **Embedded Dashboard** — React SPA at `/limiter-dashboard` with live charts, no separate server needed
- 🛑 **Ban / Unban IPs** — One-click manual IP control directly from the dashboard
- ⏱️ **Auto-expiry** — IPs automatically vanish from the dashboard after configurable idle time
- 🌐 **Proxy-aware** — Reads `X-Forwarded-For` / `X-Real-IP` for correct IP tracking behind Nginx/Apache
- 📦 **pip installable** — Models and dashboard are bundled; works out-of-the-box after install
- 🔴 **Redis-backed** — All IP data persisted in Redis; survives server restarts

---

## Requirements

- Python ≥ 3.8
- Redis (any recent version)

---

## Installation

```bash
pip install adapt-rate-limiter
```

---

## Quick Start

### Option 1 — Integrate into your existing FastAPI app

```python
from fastapi import FastAPI
from adapt_rate_limiter import AdaptiveRateLimitMiddleware, mount_rate_limiter

app = FastAPI()

# 1. Mount the dashboard + wire Redis setup
mount_rate_limiter(
    app,
    redis_host="localhost",   # your Redis host
    redis_port=6379,
    window_size=60,           # sliding window (seconds)
    ip_ttl=300,               # IPs expire after 5 min of inactivity
)

# 2. Add Global API Protection! 
# This intercepts ALL requests globally and handles AI checks instantly.
app.add_middleware(AdaptiveRateLimitMiddleware)

# 3. Write your endpoints natively!
@app.get("/my-api")          # Automatically Protected!
async def endpoint():
    return {"message": "OK"}
```

Then visit **`http://yourserver/limiter-dashboard`** for the monitoring dashboard.

---

### Option 2 — Run the standalone server

If you just want the rate limiter as a standalone server:

```bash
pip install adapt-rate-limiter uvicorn
uvicorn adapt_rate_limiter.main:app --host 0.0.0.0 --port 8000
```

Endpoints:
| URL | Description |
|---|---|
| `GET /api` | Demo rate-limited endpoint |
| `GET /dashboard-data` | JSON metrics for all tracked IPs |
| `GET /limiter-dashboard` | Monitoring dashboard UI |
| `POST /ban-ip` | Ban an IP `{"ip": "1.2.3.4"}` |
| `POST /unban-ip` | Unban an IP `{"ip": "1.2.3.4"}` |

---

## Configuration

| Parameter | Default | Description |
|---|---|---|
| `redis_host` | `"localhost"` | Redis server hostname |
| `redis_port` | `6379` | Redis server port |
| `window_size` | `60` | Sliding window in seconds |
| `ip_ttl` | `600` | Seconds to keep idle IPs in dashboard |
| `enable_dashboard` | `True` | Set `False` to skip mounting the dashboard |

### Environment Variables

You can also configure via environment variables (useful for Docker/k8s):

```bash
REDIS_HOST=redis.internal
REDIS_PORT=6379
IP_SUMMARY_TTL=300
```

---

## Dashboard Features

- **Requests/min timeline** — Area chart of traffic over the last 10 minutes
- **Action distribution** — Donut chart (ALLOW / RESTRICT / BLOCK)
- **Risk distribution** — Donut chart (LOW / MEDIUM / HIGH)
- **Top 5 IPs** — Horizontal bar chart by request count
- **IP table** — Sortable, searchable, filterable by action and ban status
- **Ban / Unban** — Click the button in any IP row to instantly block or unblock
- **Auto-refresh** — Polls `/dashboard-data` every second

---

## Behind Nginx / Apache

Add the proxy headers configuration:

```nginx
location / {
    proxy_pass         http://127.0.0.1:8000;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   Host             $host;
}
```

The rate limiter automatically reads `X-Forwarded-For` and `X-Real-IP` to get the real client IP.

---

## Building the Dashboard (for contributors)

The React dashboard source lives in `dashboard-ui/`. After making changes:

```bash
cd dashboard-ui
npm install
npm run build   # outputs to adapt_rate_limiter/dashboard/static/
```

Then rebuild the Python package:

```bash
pip install build
python -m build
```

---
