File size: 11,762 Bytes
4561114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""
api.py β€” Async FastAPI Inference Service

Endpoints:
  POST /classify          β€” Single log
  POST /classify/batch    β€” Batch of logs (up to 512)
  GET  /health            β€” Liveness check
  GET  /ready             β€” Readiness check (model loaded?)
  GET  /metrics           β€” Request counts, throughput, latency stats

Features:
  - Async request handling (non-blocking)
  - Worker pool via asyncio semaphore (bounded concurrency)
  - Structured JSON logs with request_id
  - Rate limiting (configurable)
  - Request ID tracing
  - Batch queue aggregation for small requests

Run:
  uvicorn api:app --host 0.0.0.0 --port 8000 --workers 1

Example:
  curl -X POST http://localhost:8000/classify \
       -H "Content-Type: application/json" \
       -d '{"source": "ModernCRM", "log_message": "User User123 logged in."}'
"""
from __future__ import annotations
import asyncio
import logging
import os
import time
import uuid
import statistics
from collections import deque
from contextlib import asynccontextmanager
from typing import Optional

from fastapi import FastAPI, HTTPException, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, field_validator

# ── Logging setup ─────────────────────────────────────────────────────────────
logging.basicConfig(
    level=logging.INFO,
    format='{"time":"%(asctime)s","level":"%(levelname)s","logger":"%(name)s","msg":"%(message)s"}'
)
logger = logging.getLogger("log-classifier-api")

# ── Config ─────────────────────────────────────────────────────────────────────
MAX_BATCH_SIZE      = int(os.getenv("MAX_BATCH_SIZE", "512"))
MAX_CONCURRENT      = int(os.getenv("MAX_CONCURRENT", "4"))   # concurrency cap
RATE_LIMIT_PER_MIN  = int(os.getenv("RATE_LIMIT_PER_MIN", "1000"))
LOG_MAX_CHARS       = 2048   # truncate huge logs before classify

# ── Global state ───────────────────────────────────────────────────────────────
_semaphore: asyncio.Semaphore = None   # type: ignore
_model_ready: bool = False

# Metrics ring buffer (last 1000 requests)
_latencies_ms: deque = deque(maxlen=1000)
_request_count = 0
_error_count   = 0
_start_time    = time.time()

# Rate limiter (simple sliding window per process)
_rate_window: deque = deque(maxlen=RATE_LIMIT_PER_MIN)


# ── Lifespan: load models on startup ──────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
    global _semaphore, _model_ready

    logger.info("Starting up β€” loading models…")
    _semaphore = asyncio.Semaphore(MAX_CONCURRENT)

    # Load models in a thread pool (blocking I/O, don't block event loop)
    loop = asyncio.get_event_loop()
    try:
        await loop.run_in_executor(None, _load_models_blocking)
        _model_ready = True
        logger.info("βœ… Models loaded β€” API ready")
    except Exception as e:
        logger.error(f"❌ Model load failed: {e}")
        # Service starts but /ready will return 503

    yield

    logger.info("Shutting down")


def _load_models_blocking():
    """Load BERT + classifier (blocks β€” run in executor)."""
    from processor_bert import classify_batch as _
    logger.info("BERT model loaded")


# ── App factory ────────────────────────────────────────────────────────────────
app = FastAPI(
    title="Log Classification API",
    description="3-tier hybrid pipeline: Regex β†’ BERT β†’ LLM",
    version="3.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# ── Request / Response schemas ─────────────────────────────────────────────────
class LogRequest(BaseModel):
    source:      str = Field(..., example="ModernCRM")
    log_message: str = Field(..., example="User User123 logged in.", min_length=1)

    @field_validator("log_message")
    @classmethod
    def truncate_long_logs(cls, v: str) -> str:
        return v[:LOG_MAX_CHARS]


class LogResponse(BaseModel):
    request_id:  str
    label:       str
    tier:        str
    confidence:  Optional[float]
    latency_ms:  float
    cached:      bool = False


class BatchRequest(BaseModel):
    logs: list[LogRequest] = Field(..., max_length=MAX_BATCH_SIZE)


class BatchResponse(BaseModel):
    request_id:   str
    total:        int
    elapsed_ms:   float
    throughput:   float
    results:      list[LogResponse]


class HealthResponse(BaseModel):
    status:    str
    uptime_s:  float


class MetricsResponse(BaseModel):
    total_requests:  int
    total_errors:    int
    uptime_s:        float
    requests_per_min: float
    latency_p50_ms:  Optional[float]
    latency_p95_ms:  Optional[float]
    latency_p99_ms:  Optional[float]


# ── Rate limiter ───────────────────────────────────────────────────────────────
def _check_rate_limit() -> None:
    now = time.time()
    _rate_window.append(now)
    # Window = last 60 seconds
    recent = [t for t in _rate_window if now - t < 60]
    if len(recent) > RATE_LIMIT_PER_MIN:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail=f"Rate limit exceeded: {RATE_LIMIT_PER_MIN} req/min",
        )


# ── Middleware: request logging ────────────────────────────────────────────────
@app.middleware("http")
async def log_requests(request: Request, call_next):
    rid = request.headers.get("X-Request-ID", str(uuid.uuid4())[:8])
    request.state.request_id = rid
    t0 = time.perf_counter()
    response = await call_next(request)
    elapsed = (time.perf_counter() - t0) * 1000
    logger.info(
        f"method={request.method} path={request.url.path} "
        f"status={response.status_code} latency={elapsed:.1f}ms rid={rid}"
    )
    response.headers["X-Request-ID"] = rid
    return response


# ── Health & readiness ─────────────────────────────────────────────────────────
@app.get("/health", response_model=HealthResponse, tags=["ops"])
async def health():
    return {"status": "ok", "uptime_s": round(time.time() - _start_time, 1)}


@app.get("/ready", tags=["ops"])
async def ready():
    if not _model_ready:
        raise HTTPException(status_code=503, detail="Models not yet loaded")
    return {"status": "ready"}


# ── Metrics ────────────────────────────────────────────────────────────────────
@app.get("/metrics", response_model=MetricsResponse, tags=["ops"])
async def metrics():
    uptime = time.time() - _start_time
    lats   = sorted(_latencies_ms) if _latencies_ms else []
    n      = len(lats)

    def pct(p):
        return round(lats[min(int(n * p), n - 1)], 2) if n else None

    return {
        "total_requests":  _request_count,
        "total_errors":    _error_count,
        "uptime_s":        round(uptime, 1),
        "requests_per_min": round(_request_count / max(uptime / 60, 1), 1),
        "latency_p50_ms":  pct(0.50),
        "latency_p95_ms":  pct(0.95),
        "latency_p99_ms":  pct(0.99),
    }


# ── Classify single ────────────────────────────────────────────────────────────
@app.post("/classify", response_model=LogResponse, tags=["inference"])
async def classify_single(req: LogRequest, request: Request):
    global _request_count, _error_count
    _check_rate_limit()
    _request_count += 1
    rid = getattr(request.state, "request_id", str(uuid.uuid4())[:8])

    async with _semaphore:
        loop = asyncio.get_event_loop()
        t0   = time.perf_counter()
        try:
            result = await loop.run_in_executor(
                None, _classify_blocking, req.source, req.log_message
            )
        except Exception as e:
            _error_count += 1
            logger.error(f"rid={rid} classify error: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    latency = (time.perf_counter() - t0) * 1000
    _latencies_ms.append(latency)

    return LogResponse(
        request_id = rid,
        label      = result["label"],
        tier       = result["tier"],
        confidence = result.get("confidence"),
        latency_ms = round(latency, 2),
    )


def _classify_blocking(source: str, log_message: str) -> dict:
    from classify import classify_log
    return classify_log(source, log_message)


# ── Classify batch ─────────────────────────────────────────────────────────────
@app.post("/classify/batch", response_model=BatchResponse, tags=["inference"])
async def classify_batch_endpoint(req: BatchRequest, request: Request):
    global _request_count, _error_count
    _check_rate_limit()
    _request_count += 1
    rid = getattr(request.state, "request_id", str(uuid.uuid4())[:8])

    log_pairs = [(r.source, r.log_message) for r in req.logs]

    async with _semaphore:
        loop = asyncio.get_event_loop()
        t0   = time.perf_counter()
        try:
            results = await loop.run_in_executor(
                None, _classify_batch_blocking, log_pairs
            )
        except Exception as e:
            _error_count += 1
            logger.error(f"rid={rid} batch error: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    elapsed_ms = (time.perf_counter() - t0) * 1000
    throughput = round(len(log_pairs) / (elapsed_ms / 1000), 1)
    _latencies_ms.extend([elapsed_ms / len(log_pairs)] * len(log_pairs))

    return BatchResponse(
        request_id = rid,
        total      = len(log_pairs),
        elapsed_ms = round(elapsed_ms, 2),
        throughput = throughput,
        results    = [
            LogResponse(
                request_id = rid,
                label      = r["label"],
                tier       = r["tier"],
                confidence = r.get("confidence"),
                latency_ms = round(elapsed_ms / len(log_pairs), 2),
            )
            for r in results
        ],
    )


def _classify_batch_blocking(log_pairs: list[tuple[str, str]]) -> list[dict]:
    from classify import classify_logs
    return classify_logs(log_pairs)


# ── Dev runner ──────────────────────────────────────────────────────────────────
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=False, workers=1)