Spaces:
Running
Running
Deploy fd090517
Browse files- api.py +646 -646
- frontend/api/provider-test.js +1 -1
- frontend/api/provider-test.test.js +12 -0
api.py
CHANGED
|
@@ -1,646 +1,646 @@
|
|
| 1 |
-
"""Small HTTP boundary for the React client.
|
| 2 |
-
|
| 3 |
-
The review engine remains in the existing LangGraph modules. This service only
|
| 4 |
-
owns job lifecycle and approval state; production deployments should replace
|
| 5 |
-
the process-local registry with a durable store and queue.
|
| 6 |
-
"""
|
| 7 |
-
from __future__ import annotations
|
| 8 |
-
|
| 9 |
-
import os
|
| 10 |
-
import hashlib
|
| 11 |
-
import time
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
import json
|
| 14 |
-
import secrets
|
| 15 |
-
import sqlite3
|
| 16 |
-
import threading
|
| 17 |
-
import uuid
|
| 18 |
-
import requests
|
| 19 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 20 |
-
from datetime import datetime, timezone
|
| 21 |
-
from typing import Any, Literal
|
| 22 |
-
|
| 23 |
-
from fastapi import FastAPI, Header, HTTPException, Request
|
| 24 |
-
from fastapi.responses import RedirectResponse
|
| 25 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
-
from langgraph.types import Command
|
| 27 |
-
from pydantic import BaseModel, Field
|
| 28 |
-
|
| 29 |
-
from app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
|
| 30 |
-
from graph import build_graph
|
| 31 |
-
from observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
|
| 32 |
-
from state import Finding, Verdict
|
| 33 |
-
from endpoints import register_endpoint, unregister_endpoint
|
| 34 |
-
|
| 35 |
-
app = FastAPI(title="OpenCodeReview API", version="0.1.0")
|
| 36 |
-
allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
|
| 37 |
-
app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
|
| 38 |
-
|
| 39 |
-
_jobs: dict[str, dict[str, Any]] = {}
|
| 40 |
-
_lock = threading.Lock()
|
| 41 |
-
_executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
|
| 42 |
-
_rate_lock = threading.Lock()
|
| 43 |
-
_rate_windows: dict[str, list[float]] = {}
|
| 44 |
-
_oauth_states: set[str] = set()
|
| 45 |
-
_sessions: dict[str, dict[str, Any]] = {}
|
| 46 |
-
|
| 47 |
-
def _rate_limit(request: Request) -> None:
|
| 48 |
-
limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
|
| 49 |
-
if limit <= 0:
|
| 50 |
-
return
|
| 51 |
-
now = datetime.now(timezone.utc).timestamp()
|
| 52 |
-
forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
|
| 53 |
-
key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
|
| 54 |
-
with _rate_lock:
|
| 55 |
-
window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
|
| 56 |
-
if len(window) >= limit:
|
| 57 |
-
raise HTTPException(status_code=429, detail="Rate limit exceeded")
|
| 58 |
-
window.append(now)
|
| 59 |
-
_rate_windows[key] = window
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _postgres_connect():
|
| 63 |
-
"""Return a Supabase Postgres connection when configured, else None."""
|
| 64 |
-
url = os.getenv("SUPABASE_DB_URL", "").strip()
|
| 65 |
-
if not url:
|
| 66 |
-
return None
|
| 67 |
-
try:
|
| 68 |
-
import psycopg
|
| 69 |
-
return psycopg.connect(url)
|
| 70 |
-
except Exception:
|
| 71 |
-
return None
|
| 72 |
-
|
| 73 |
-
def _init_jobs() -> None:
|
| 74 |
-
pg = _postgres_connect()
|
| 75 |
-
if pg is not None:
|
| 76 |
-
with pg:
|
| 77 |
-
with pg.cursor() as cur:
|
| 78 |
-
cur.execute("""create table if not exists public.review_jobs (
|
| 79 |
-
id uuid primary key, repo text not null, pr_number integer not null,
|
| 80 |
-
endpoint text, status text not null, payload jsonb not null,
|
| 81 |
-
created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
|
| 82 |
-
cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
|
| 83 |
-
pg.close()
|
| 84 |
-
return
|
| 85 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 86 |
-
conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
|
| 87 |
-
conn.commit()
|
| 88 |
-
|
| 89 |
-
_init_jobs()
|
| 90 |
-
|
| 91 |
-
def _save_job(job: dict[str, Any]) -> None:
|
| 92 |
-
payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
|
| 93 |
-
if "config" in payload:
|
| 94 |
-
payload["config"] = {"configurable": payload["config"].get("configurable", {})}
|
| 95 |
-
pg = _postgres_connect()
|
| 96 |
-
if pg is not None:
|
| 97 |
-
with pg:
|
| 98 |
-
with pg.cursor() as cur:
|
| 99 |
-
cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
|
| 100 |
-
values (%s, %s, %s, %s, %s, %s::jsonb, now())
|
| 101 |
-
on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
|
| 102 |
-
endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
|
| 103 |
-
(job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
|
| 104 |
-
pg.close()
|
| 105 |
-
return
|
| 106 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 107 |
-
conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
|
| 108 |
-
conn.commit()
|
| 109 |
-
|
| 110 |
-
def _load_job(job_id: str) -> dict[str, Any] | None:
|
| 111 |
-
pg = _postgres_connect()
|
| 112 |
-
if pg is not None:
|
| 113 |
-
with pg.cursor() as cur:
|
| 114 |
-
cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
|
| 115 |
-
row = cur.fetchone()
|
| 116 |
-
pg.close()
|
| 117 |
-
if not row:
|
| 118 |
-
return None
|
| 119 |
-
return json.loads(row[0]) if isinstance(row[0], str) else row[0]
|
| 120 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 121 |
-
row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
|
| 122 |
-
return json.loads(row[0]) if row else None
|
| 123 |
-
|
| 124 |
-
def _load_jobs() -> list[dict[str, Any]]:
|
| 125 |
-
pg = _postgres_connect()
|
| 126 |
-
if pg is not None:
|
| 127 |
-
with pg.cursor() as cur:
|
| 128 |
-
cur.execute("select payload from public.review_jobs")
|
| 129 |
-
rows = cur.fetchall()
|
| 130 |
-
pg.close()
|
| 131 |
-
return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
|
| 132 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 133 |
-
rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
|
| 134 |
-
return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
class ReviewRequest(BaseModel):
|
| 138 |
-
repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
|
| 139 |
-
pr_number: int = Field(gt=0)
|
| 140 |
-
endpoint: str | None = None
|
| 141 |
-
provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
|
| 142 |
-
model: str | None = None
|
| 143 |
-
api_key: str | None = None
|
| 144 |
-
base_url: str | None = None
|
| 145 |
-
review_mode: Literal["fast", "thorough"] = "thorough"
|
| 146 |
-
baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
class DecisionRequest(BaseModel):
|
| 150 |
-
action: Literal["approve", "reject"]
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
class FindingFeedbackRequest(BaseModel):
|
| 154 |
-
finding_index: int = Field(ge=0)
|
| 155 |
-
label: Literal['correct', 'incorrect', 'useful']
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
def _authorize(token: str | None) -> None:
|
| 159 |
-
expected = os.getenv("OCR_API_KEY", "").strip()
|
| 160 |
-
# Authentication is opt-in for local development, but deployments can
|
| 161 |
-
# require it explicitly. Never silently treat a missing production key
|
| 162 |
-
# as authenticated.
|
| 163 |
-
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 164 |
-
if require_auth and not expected:
|
| 165 |
-
raise HTTPException(status_code=503, detail="API authentication is not configured")
|
| 166 |
-
if expected and (not token or not secrets.compare_digest(token, expected)):
|
| 167 |
-
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 168 |
-
|
| 169 |
-
def _authorize_request(token: str | None, request: Request) -> None:
|
| 170 |
-
if _session(request):
|
| 171 |
-
return
|
| 172 |
-
_authorize(token)
|
| 173 |
-
|
| 174 |
-
def _session(request: Request) -> dict[str, Any] | None:
|
| 175 |
-
sid = request.cookies.get("ocr_session")
|
| 176 |
-
return _sessions.get(sid) if sid else None
|
| 177 |
-
|
| 178 |
-
@app.get("/api/auth/github/start")
|
| 179 |
-
def github_login() -> RedirectResponse:
|
| 180 |
-
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 181 |
-
if not client_id:
|
| 182 |
-
raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
|
| 183 |
-
state = secrets.token_urlsafe(32)
|
| 184 |
-
_oauth_states.add(state)
|
| 185 |
-
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 186 |
-
url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
|
| 187 |
-
return RedirectResponse(url)
|
| 188 |
-
|
| 189 |
-
@app.get("/api/auth/github/callback")
|
| 190 |
-
def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
|
| 191 |
-
if state not in _oauth_states:
|
| 192 |
-
raise HTTPException(status_code=400, detail="Invalid OAuth state")
|
| 193 |
-
_oauth_states.discard(state)
|
| 194 |
-
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 195 |
-
client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
|
| 196 |
-
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 197 |
-
token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
|
| 198 |
-
token_resp.raise_for_status()
|
| 199 |
-
access_token = token_resp.json().get("access_token")
|
| 200 |
-
if not access_token:
|
| 201 |
-
raise HTTPException(status_code=502, detail="GitHub did not return an access token")
|
| 202 |
-
user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
|
| 203 |
-
user_resp.raise_for_status()
|
| 204 |
-
user = user_resp.json()
|
| 205 |
-
sid = secrets.token_urlsafe(32)
|
| 206 |
-
_sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
|
| 207 |
-
frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
|
| 208 |
-
out = RedirectResponse(frontend)
|
| 209 |
-
out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
|
| 210 |
-
return out
|
| 211 |
-
|
| 212 |
-
@app.get("/api/auth/me")
|
| 213 |
-
def github_me(request: Request) -> dict[str, Any]:
|
| 214 |
-
session = _session(request)
|
| 215 |
-
if not session:
|
| 216 |
-
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 217 |
-
return {"github_id": session["github_id"], "login": session["login"]}
|
| 218 |
-
|
| 219 |
-
@app.post("/api/auth/logout")
|
| 220 |
-
def github_logout(request: Request) -> dict[str, str]:
|
| 221 |
-
sid = request.cookies.get("ocr_session")
|
| 222 |
-
if sid:
|
| 223 |
-
_sessions.pop(sid, None)
|
| 224 |
-
return {"status": "logged_out"}
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 228 |
-
result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
|
| 229 |
-
now = time.time()
|
| 230 |
-
result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
|
| 231 |
-
if job.get("status") == "queued":
|
| 232 |
-
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 233 |
-
return result
|
| 234 |
-
|
| 235 |
-
def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
|
| 236 |
-
result = _public_job(job)
|
| 237 |
-
task_id = result.get("ragas_task_id")
|
| 238 |
-
with _ragas_lock:
|
| 239 |
-
task = _ragas_tasks.get(task_id) if task_id else None
|
| 240 |
-
def finish():
|
| 241 |
-
metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
|
| 242 |
-
evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
|
| 243 |
-
result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
|
| 244 |
-
if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
|
| 245 |
-
result['ragas']['status'] = 'partial'
|
| 246 |
-
if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
|
| 247 |
-
with _lock:
|
| 248 |
-
live = _jobs.get(job.get('id'))
|
| 249 |
-
if live is not None:
|
| 250 |
-
live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
|
| 251 |
-
_save_job(live)
|
| 252 |
-
return result
|
| 253 |
-
if not task_id:
|
| 254 |
-
result["ragas"] = {
|
| 255 |
-
"status": "skipped",
|
| 256 |
-
"scores": result.get("ragas_scores") or {},
|
| 257 |
-
"reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
|
| 258 |
-
}
|
| 259 |
-
else:
|
| 260 |
-
if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
|
| 261 |
-
result["ragas"] = {
|
| 262 |
-
"status": job["ragas_status"],
|
| 263 |
-
"scores": job.get("ragas_scores") or {},
|
| 264 |
-
"error": job.get("ragas_error"),
|
| 265 |
-
}
|
| 266 |
-
return finish()
|
| 267 |
-
with _ragas_lock:
|
| 268 |
-
task = _ragas_tasks.get(task_id)
|
| 269 |
-
if not task:
|
| 270 |
-
# Task registries are process-local. A restart invalidates an
|
| 271 |
-
# in-flight task instead of making the client poll forever.
|
| 272 |
-
if result.get("ragas_scores"):
|
| 273 |
-
result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
|
| 274 |
-
else:
|
| 275 |
-
result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
|
| 276 |
-
with _lock:
|
| 277 |
-
live = _jobs.get(job.get("id"))
|
| 278 |
-
if live is not None:
|
| 279 |
-
live["ragas_status"] = "unavailable"
|
| 280 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 281 |
-
_save_job(live)
|
| 282 |
-
elif not task.get("done"):
|
| 283 |
-
timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
|
| 284 |
-
started = float(task.get("started", 0) or 0)
|
| 285 |
-
if started and datetime.now(timezone.utc).timestamp() - started > timeout:
|
| 286 |
-
result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
|
| 287 |
-
with _lock:
|
| 288 |
-
live = _jobs.get(job.get("id"))
|
| 289 |
-
if live is not None:
|
| 290 |
-
live["ragas_status"] = "failed"
|
| 291 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 292 |
-
_save_job(live)
|
| 293 |
-
else:
|
| 294 |
-
result["ragas"] = {"status": "pending"}
|
| 295 |
-
elif task.get("error"):
|
| 296 |
-
result["ragas"] = {"status": "failed", "error": task.get("error")}
|
| 297 |
-
with _lock:
|
| 298 |
-
live = _jobs.get(job.get("id"))
|
| 299 |
-
if live is not None:
|
| 300 |
-
live["ragas_status"] = "failed"
|
| 301 |
-
live["ragas_error"] = task.get("error")
|
| 302 |
-
_save_job(live)
|
| 303 |
-
else:
|
| 304 |
-
scores = task.get("scores") or {}
|
| 305 |
-
if scores:
|
| 306 |
-
result["ragas"] = {"status": "completed", "scores": scores}
|
| 307 |
-
if not job.get("ragas_scores"):
|
| 308 |
-
with _lock:
|
| 309 |
-
live = _jobs.get(job.get("id"))
|
| 310 |
-
if live is not None:
|
| 311 |
-
live["ragas_scores"] = scores
|
| 312 |
-
live["ragas_status"] = "completed"
|
| 313 |
-
_save_job(live)
|
| 314 |
-
else:
|
| 315 |
-
result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
|
| 316 |
-
with _lock:
|
| 317 |
-
live = _jobs.get(job.get("id"))
|
| 318 |
-
if live is not None:
|
| 319 |
-
live["ragas_status"] = "completed_no_scores"
|
| 320 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 321 |
-
_save_job(live)
|
| 322 |
-
return finish()
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 326 |
-
with _lock:
|
| 327 |
-
if _jobs.get(job_id, {}).get("status") == "cancelled":
|
| 328 |
-
return
|
| 329 |
-
if job_id in _jobs:
|
| 330 |
-
_jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
|
| 331 |
-
_save_job(_jobs[job_id])
|
| 332 |
-
try:
|
| 333 |
-
ephemeral_endpoint = None
|
| 334 |
-
ragas_started = False
|
| 335 |
-
endpoint_name = _normalize_endpoint_name(request.endpoint)
|
| 336 |
-
if request.api_key:
|
| 337 |
-
if not request.provider or not request.model:
|
| 338 |
-
raise ValueError("provider and model are required when supplying a user API key")
|
| 339 |
-
ephemeral_endpoint = f"user-{job_id}"
|
| 340 |
-
register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
|
| 341 |
-
endpoint_name = ephemeral_endpoint
|
| 342 |
-
def save_ragas(scores: dict, error: str | None) -> None:
|
| 343 |
-
try:
|
| 344 |
-
with _lock:
|
| 345 |
-
live = _jobs.get(job_id)
|
| 346 |
-
if live is None:
|
| 347 |
-
return
|
| 348 |
-
live["ragas_scores"] = scores or None
|
| 349 |
-
live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
|
| 350 |
-
live["ragas_error"] = error
|
| 351 |
-
_save_job(live)
|
| 352 |
-
finally:
|
| 353 |
-
# Custom providers are registered only for this job. Keep the
|
| 354 |
-
# endpoint alive until the background RAGAS task has finished;
|
| 355 |
-
# otherwise evaluation silently falls back to built-ins.
|
| 356 |
-
if ephemeral_endpoint:
|
| 357 |
-
unregister_endpoint(ephemeral_endpoint)
|
| 358 |
-
|
| 359 |
-
def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
|
| 360 |
-
with _lock:
|
| 361 |
-
live = _jobs[job_id]
|
| 362 |
-
if live.get("status") == "cancelled":
|
| 363 |
-
raise RuntimeError("Review cancelled")
|
| 364 |
-
completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
|
| 365 |
-
if stage not in completed:
|
| 366 |
-
completed.append(stage)
|
| 367 |
-
live["progress"]["stage"] = stage
|
| 368 |
-
live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
|
| 369 |
-
if isinstance(update, dict):
|
| 370 |
-
stages = update.get("review_stages", [])
|
| 371 |
-
if isinstance(stages, list):
|
| 372 |
-
live.setdefault("review_stages", []).extend(stages)
|
| 373 |
-
for key in ("findings",):
|
| 374 |
-
for finding in update.get(key, []) or []:
|
| 375 |
-
if hasattr(finding, "model_dump"):
|
| 376 |
-
finding = finding.model_dump(mode="json")
|
| 377 |
-
if isinstance(finding, dict):
|
| 378 |
-
live.setdefault("findings", []).append(finding)
|
| 379 |
-
_save_job(live)
|
| 380 |
-
|
| 381 |
-
state, config, cost, ragas, ragas_inputs = _build_and_stream(
|
| 382 |
-
request.repo,
|
| 383 |
-
request.pr_number,
|
| 384 |
-
endpoint_name,
|
| 385 |
-
ragas_background=True,
|
| 386 |
-
ragas_result_callback=save_ragas,
|
| 387 |
-
progress_callback=progress,
|
| 388 |
-
review_mode=request.review_mode,
|
| 389 |
-
baseline_sha=request.baseline_sha,
|
| 390 |
-
)
|
| 391 |
-
ragas_started = isinstance(ragas, str)
|
| 392 |
-
actual_head = state.values.get("head_sha")
|
| 393 |
-
verdict: Verdict | None = state.values.get("verdict")
|
| 394 |
-
findings: list[Finding] = state.values.get("final_findings", [])
|
| 395 |
-
with _lock:
|
| 396 |
-
if _jobs[job_id].get("status") == "cancelled":
|
| 397 |
-
return
|
| 398 |
-
if actual_head and _jobs[job_id].get("head_sha") != actual_head:
|
| 399 |
-
# The PR moved between metadata lookup and ingestion. The result
|
| 400 |
-
# can still be viewed, but must not satisfy the old cache key.
|
| 401 |
-
_jobs[job_id]["request_fingerprint"] = None
|
| 402 |
-
_jobs[job_id]["head_sha"] = actual_head
|
| 403 |
-
stages = state.values.get("review_stages", [])
|
| 404 |
-
incomplete = bool(verdict and verdict.recommendation == "incomplete")
|
| 405 |
-
_jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
|
| 406 |
-
_save_job(_jobs[job_id])
|
| 407 |
-
except Exception as exc:
|
| 408 |
-
with _lock:
|
| 409 |
-
if _jobs[job_id].get("status") != "cancelled":
|
| 410 |
-
_jobs[job_id].update(status="failed", error=str(exc)[:500])
|
| 411 |
-
_save_job(_jobs[job_id])
|
| 412 |
-
finally:
|
| 413 |
-
if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
|
| 414 |
-
unregister_endpoint(ephemeral_endpoint)
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
def _hydrate_jobs() -> None:
|
| 418 |
-
"""Restore persisted jobs after a process restart and resume interrupted work."""
|
| 419 |
-
for persisted in _load_jobs():
|
| 420 |
-
# Evaluation inputs may include an in-memory endpoint object. Never
|
| 421 |
-
# retain or expose that snapshot: it can contain a user's provider key.
|
| 422 |
-
if "ragas_inputs" in persisted:
|
| 423 |
-
persisted.pop("ragas_inputs", None)
|
| 424 |
-
_save_job(persisted)
|
| 425 |
-
job_id = persisted.get("id")
|
| 426 |
-
if not job_id:
|
| 427 |
-
continue
|
| 428 |
-
status = persisted.get("status")
|
| 429 |
-
_jobs[job_id] = persisted
|
| 430 |
-
if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
|
| 431 |
-
persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
|
| 432 |
-
_save_job(persisted)
|
| 433 |
-
if status in {"queued", "processing"} and persisted.get("custom_provider"):
|
| 434 |
-
persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
|
| 435 |
-
_save_job(persisted)
|
| 436 |
-
continue
|
| 437 |
-
if status in {"queued", "processing", "processing_decision"}:
|
| 438 |
-
# Decision processing cannot be safely replayed without an explicit
|
| 439 |
-
# user action; review execution can be resumed idempotently.
|
| 440 |
-
if status == "processing_decision":
|
| 441 |
-
_jobs[job_id]["status"] = "awaiting_approval"
|
| 442 |
-
_save_job(_jobs[job_id])
|
| 443 |
-
continue
|
| 444 |
-
try:
|
| 445 |
-
request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
|
| 446 |
-
except Exception:
|
| 447 |
-
_jobs[job_id].update(status="failed", error="Persisted job request is invalid")
|
| 448 |
-
_save_job(_jobs[job_id])
|
| 449 |
-
continue
|
| 450 |
-
_jobs[job_id]["status"] = "queued"
|
| 451 |
-
_save_job(_jobs[job_id])
|
| 452 |
-
_jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
_hydrate_jobs()
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
@app.get("/api/health")
|
| 459 |
-
def health() -> dict[str, Any]:
|
| 460 |
-
provider_configured = any(
|
| 461 |
-
os.getenv(name, "").strip()
|
| 462 |
-
for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
|
| 463 |
-
)
|
| 464 |
-
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 465 |
-
persistence = "local_default_path"
|
| 466 |
-
if os.getenv("SUPABASE_DB_URL"):
|
| 467 |
-
probe = _postgres_connect()
|
| 468 |
-
if probe is not None:
|
| 469 |
-
probe.close()
|
| 470 |
-
persistence = "supabase_postgres"
|
| 471 |
-
else:
|
| 472 |
-
persistence = "supabase_configured_unreachable"
|
| 473 |
-
elif os.getenv("OPENCODEREVIEW_DB_PATH"):
|
| 474 |
-
persistence = "configured_path"
|
| 475 |
-
return {
|
| 476 |
-
"status": "ok",
|
| 477 |
-
"inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
|
| 478 |
-
"authentication": "required" if require_auth else "optional",
|
| 479 |
-
"rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
|
| 480 |
-
"persistence": persistence,
|
| 481 |
-
"local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
|
| 482 |
-
in {"1", "true", "yes", "on"},
|
| 483 |
-
}
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
@app.post("/api/reviews", status_code=202)
|
| 487 |
-
def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
|
| 488 |
-
_authorize_request(x_api_key, http_request)
|
| 489 |
-
_rate_limit(http_request)
|
| 490 |
-
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 491 |
-
material = request.model_dump()
|
| 492 |
-
head_sha = base_sha = None
|
| 493 |
-
try:
|
| 494 |
-
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 495 |
-
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 496 |
-
if token:
|
| 497 |
-
headers["Authorization"] = f"Bearer {token}"
|
| 498 |
-
response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
|
| 499 |
-
response.raise_for_status()
|
| 500 |
-
pull = response.json()
|
| 501 |
-
head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
|
| 502 |
-
except (requests.RequestException, KeyError, ValueError):
|
| 503 |
-
pass # Active deduplication still works if GitHub metadata is unavailable.
|
| 504 |
-
prompt_hash = hashlib.sha256()
|
| 505 |
-
for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
|
| 506 |
-
prompt_hash.update(source.read_bytes())
|
| 507 |
-
for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
|
| 508 |
-
prompt_hash.update(source.read_bytes())
|
| 509 |
-
material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
|
| 510 |
-
fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
|
| 511 |
-
# Reuse completed previews only for an identical immutable diff and configuration.
|
| 512 |
-
with _lock:
|
| 513 |
-
existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
|
| 514 |
-
if existing is None:
|
| 515 |
-
job_id = str(uuid.uuid4())
|
| 516 |
-
job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
|
| 517 |
-
_jobs[job_id] = job
|
| 518 |
-
_save_job(job)
|
| 519 |
-
else:
|
| 520 |
-
job = existing
|
| 521 |
-
if existing is not None:
|
| 522 |
-
return {**_with_ragas(job), "reused": True}
|
| 523 |
-
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 524 |
-
return _with_ragas(job)
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
@app.post("/api/reviews/{job_id}/cancel")
|
| 528 |
-
def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 529 |
-
_authorize_request(x_api_key, request)
|
| 530 |
-
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 531 |
-
with _lock:
|
| 532 |
-
job = _jobs.get(job_id)
|
| 533 |
-
if not job or job.get("owner_id", "api-key") != owner:
|
| 534 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 535 |
-
if job.get("status") not in {"queued", "processing"}:
|
| 536 |
-
raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
|
| 537 |
-
future = job.get("future")
|
| 538 |
-
if future:
|
| 539 |
-
future.cancel()
|
| 540 |
-
job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
|
| 541 |
-
_save_job(job)
|
| 542 |
-
return _public_job(job)
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
@app.get("/api/reviews/{job_id}")
|
| 546 |
-
def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 547 |
-
# API-key authorization remains supported for polling; OAuth callers use the cookie path.
|
| 548 |
-
_authorize_request(x_api_key, request)
|
| 549 |
-
with _lock:
|
| 550 |
-
job = _jobs.get(job_id)
|
| 551 |
-
if not job:
|
| 552 |
-
job = _load_job(job_id)
|
| 553 |
-
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 554 |
-
if not job or job.get("owner_id", "api-key") != owner:
|
| 555 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 556 |
-
return _with_ragas(job)
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
@app.post('/api/reviews/{job_id}/feedback')
|
| 560 |
-
def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
|
| 561 |
-
x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 562 |
-
_authorize_request(x_api_key, request)
|
| 563 |
-
_rate_limit(request)
|
| 564 |
-
owner = str((_session(request) or {}).get('github_id') or 'api-key')
|
| 565 |
-
with _lock:
|
| 566 |
-
job = _jobs.get(job_id) or _load_job(job_id)
|
| 567 |
-
if not job or job.get('owner_id', 'api-key') != owner:
|
| 568 |
-
raise HTTPException(status_code=404, detail='Review not found')
|
| 569 |
-
if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
|
| 570 |
-
raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
|
| 571 |
-
if payload.finding_index >= len(job.get('findings') or []):
|
| 572 |
-
raise HTTPException(status_code=422, detail='Finding does not exist')
|
| 573 |
-
feedback = dict(job.get('feedback') or {})
|
| 574 |
-
feedback[str(payload.finding_index)] = payload.label
|
| 575 |
-
job['feedback'] = feedback
|
| 576 |
-
job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
|
| 577 |
-
_jobs[job_id] = job
|
| 578 |
-
_save_job(job)
|
| 579 |
-
return {'feedback': feedback}
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
@app.post("/api/reviews/{job_id}/decision")
|
| 583 |
-
def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 584 |
-
_authorize_request(x_api_key, http_request)
|
| 585 |
-
_rate_limit(http_request)
|
| 586 |
-
with _lock:
|
| 587 |
-
preview = _jobs.get(job_id) or _load_job(job_id)
|
| 588 |
-
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 589 |
-
if not preview or preview.get("owner_id", "api-key") != owner:
|
| 590 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 591 |
-
if request.action == "approve" and preview.get("baseline_sha"):
|
| 592 |
-
raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
|
| 593 |
-
if preview and request.action == "approve" and preview.get("head_sha"):
|
| 594 |
-
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 595 |
-
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 596 |
-
if token:
|
| 597 |
-
headers["Authorization"] = f"Bearer {token}"
|
| 598 |
-
try:
|
| 599 |
-
response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
|
| 600 |
-
response.raise_for_status()
|
| 601 |
-
current = response.json()
|
| 602 |
-
if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
|
| 603 |
-
raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
|
| 604 |
-
except (requests.RequestException, KeyError, ValueError) as exc:
|
| 605 |
-
raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
|
| 606 |
-
with _lock:
|
| 607 |
-
job = _jobs.get(job_id)
|
| 608 |
-
if not job:
|
| 609 |
-
job = _load_job(job_id)
|
| 610 |
-
if not job:
|
| 611 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 612 |
-
if job.get("status") != "awaiting_approval":
|
| 613 |
-
raise HTTPException(status_code=409, detail="Review is not awaiting approval")
|
| 614 |
-
config = job["config"]
|
| 615 |
-
job["status"] = "processing_decision"
|
| 616 |
-
_save_job(job)
|
| 617 |
-
if request.action == "reject":
|
| 618 |
-
with _lock:
|
| 619 |
-
job.update(status="rejected", decision="reject")
|
| 620 |
-
_save_job(job)
|
| 621 |
-
return _public_job(job)
|
| 622 |
-
graph = build_graph(DB_PATH)
|
| 623 |
-
try:
|
| 624 |
-
callbacks = [TokenCostCallback()]
|
| 625 |
-
handler = get_langfuse_handler()
|
| 626 |
-
if handler:
|
| 627 |
-
callbacks.append(handler)
|
| 628 |
-
config = dict(config)
|
| 629 |
-
config["callbacks"] = callbacks
|
| 630 |
-
result = graph.invoke(Command(resume={"action": "approve"}), config)
|
| 631 |
-
posting_result = result.get("posting_result") if isinstance(result, dict) else None
|
| 632 |
-
final_status = (posting_result or {}).get("status", "posted")
|
| 633 |
-
with _lock:
|
| 634 |
-
job.update(status=final_status, decision="approve", posting_result=posting_result)
|
| 635 |
-
_save_job(job)
|
| 636 |
-
return _public_job(job)
|
| 637 |
-
except Exception as exc:
|
| 638 |
-
with _lock:
|
| 639 |
-
job.update(status="failed", error=str(exc)[:500])
|
| 640 |
-
_save_job(job)
|
| 641 |
-
raise HTTPException(status_code=500, detail="Decision processing failed") from exc
|
| 642 |
-
finally:
|
| 643 |
-
conn = getattr(graph, "_opencodereview_conn", None)
|
| 644 |
-
if conn:
|
| 645 |
-
conn.close()
|
| 646 |
-
flush_langfuse()
|
|
|
|
| 1 |
+
"""Small HTTP boundary for the React client.
|
| 2 |
+
|
| 3 |
+
The review engine remains in the existing LangGraph modules. This service only
|
| 4 |
+
owns job lifecycle and approval state; production deployments should replace
|
| 5 |
+
the process-local registry with a durable store and queue.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import hashlib
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import json
|
| 14 |
+
import secrets
|
| 15 |
+
import sqlite3
|
| 16 |
+
import threading
|
| 17 |
+
import uuid
|
| 18 |
+
import requests
|
| 19 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
from typing import Any, Literal
|
| 22 |
+
|
| 23 |
+
from fastapi import FastAPI, Header, HTTPException, Request
|
| 24 |
+
from fastapi.responses import RedirectResponse
|
| 25 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
+
from langgraph.types import Command
|
| 27 |
+
from pydantic import BaseModel, Field
|
| 28 |
+
|
| 29 |
+
from app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
|
| 30 |
+
from graph import build_graph
|
| 31 |
+
from observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
|
| 32 |
+
from state import Finding, Verdict
|
| 33 |
+
from endpoints import register_endpoint, unregister_endpoint
|
| 34 |
+
|
| 35 |
+
app = FastAPI(title="OpenCodeReview API", version="0.1.0")
|
| 36 |
+
allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
|
| 37 |
+
app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
|
| 38 |
+
|
| 39 |
+
_jobs: dict[str, dict[str, Any]] = {}
|
| 40 |
+
_lock = threading.Lock()
|
| 41 |
+
_executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
|
| 42 |
+
_rate_lock = threading.Lock()
|
| 43 |
+
_rate_windows: dict[str, list[float]] = {}
|
| 44 |
+
_oauth_states: set[str] = set()
|
| 45 |
+
_sessions: dict[str, dict[str, Any]] = {}
|
| 46 |
+
|
| 47 |
+
def _rate_limit(request: Request) -> None:
|
| 48 |
+
limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
|
| 49 |
+
if limit <= 0:
|
| 50 |
+
return
|
| 51 |
+
now = datetime.now(timezone.utc).timestamp()
|
| 52 |
+
forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
|
| 53 |
+
key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
|
| 54 |
+
with _rate_lock:
|
| 55 |
+
window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
|
| 56 |
+
if len(window) >= limit:
|
| 57 |
+
raise HTTPException(status_code=429, detail="Rate limit exceeded")
|
| 58 |
+
window.append(now)
|
| 59 |
+
_rate_windows[key] = window
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _postgres_connect():
|
| 63 |
+
"""Return a Supabase Postgres connection when configured, else None."""
|
| 64 |
+
url = os.getenv("SUPABASE_DB_URL", "").strip()
|
| 65 |
+
if not url:
|
| 66 |
+
return None
|
| 67 |
+
try:
|
| 68 |
+
import psycopg
|
| 69 |
+
return psycopg.connect(url)
|
| 70 |
+
except Exception:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
def _init_jobs() -> None:
|
| 74 |
+
pg = _postgres_connect()
|
| 75 |
+
if pg is not None:
|
| 76 |
+
with pg:
|
| 77 |
+
with pg.cursor() as cur:
|
| 78 |
+
cur.execute("""create table if not exists public.review_jobs (
|
| 79 |
+
id uuid primary key, repo text not null, pr_number integer not null,
|
| 80 |
+
endpoint text, status text not null, payload jsonb not null,
|
| 81 |
+
created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
|
| 82 |
+
cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
|
| 83 |
+
pg.close()
|
| 84 |
+
return
|
| 85 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 86 |
+
conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
|
| 87 |
+
conn.commit()
|
| 88 |
+
|
| 89 |
+
_init_jobs()
|
| 90 |
+
|
| 91 |
+
def _save_job(job: dict[str, Any]) -> None:
|
| 92 |
+
payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
|
| 93 |
+
if "config" in payload:
|
| 94 |
+
payload["config"] = {"configurable": payload["config"].get("configurable", {})}
|
| 95 |
+
pg = _postgres_connect()
|
| 96 |
+
if pg is not None:
|
| 97 |
+
with pg:
|
| 98 |
+
with pg.cursor() as cur:
|
| 99 |
+
cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
|
| 100 |
+
values (%s, %s, %s, %s, %s, %s::jsonb, now())
|
| 101 |
+
on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
|
| 102 |
+
endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
|
| 103 |
+
(job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
|
| 104 |
+
pg.close()
|
| 105 |
+
return
|
| 106 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 107 |
+
conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
|
| 108 |
+
conn.commit()
|
| 109 |
+
|
| 110 |
+
def _load_job(job_id: str) -> dict[str, Any] | None:
|
| 111 |
+
pg = _postgres_connect()
|
| 112 |
+
if pg is not None:
|
| 113 |
+
with pg.cursor() as cur:
|
| 114 |
+
cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
|
| 115 |
+
row = cur.fetchone()
|
| 116 |
+
pg.close()
|
| 117 |
+
if not row:
|
| 118 |
+
return None
|
| 119 |
+
return json.loads(row[0]) if isinstance(row[0], str) else row[0]
|
| 120 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 121 |
+
row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
|
| 122 |
+
return json.loads(row[0]) if row else None
|
| 123 |
+
|
| 124 |
+
def _load_jobs() -> list[dict[str, Any]]:
|
| 125 |
+
pg = _postgres_connect()
|
| 126 |
+
if pg is not None:
|
| 127 |
+
with pg.cursor() as cur:
|
| 128 |
+
cur.execute("select payload from public.review_jobs")
|
| 129 |
+
rows = cur.fetchall()
|
| 130 |
+
pg.close()
|
| 131 |
+
return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
|
| 132 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 133 |
+
rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
|
| 134 |
+
return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class ReviewRequest(BaseModel):
|
| 138 |
+
repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
|
| 139 |
+
pr_number: int = Field(gt=0)
|
| 140 |
+
endpoint: str | None = None
|
| 141 |
+
provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
|
| 142 |
+
model: str | None = None
|
| 143 |
+
api_key: str | None = None
|
| 144 |
+
base_url: str | None = None
|
| 145 |
+
review_mode: Literal["fast", "thorough"] = "thorough"
|
| 146 |
+
baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class DecisionRequest(BaseModel):
|
| 150 |
+
action: Literal["approve", "reject"]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class FindingFeedbackRequest(BaseModel):
|
| 154 |
+
finding_index: int = Field(ge=0)
|
| 155 |
+
label: Literal['correct', 'incorrect', 'useful']
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _authorize(token: str | None) -> None:
|
| 159 |
+
expected = os.getenv("OCR_API_KEY", "").strip()
|
| 160 |
+
# Authentication is opt-in for local development, but deployments can
|
| 161 |
+
# require it explicitly. Never silently treat a missing production key
|
| 162 |
+
# as authenticated.
|
| 163 |
+
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 164 |
+
if require_auth and not expected:
|
| 165 |
+
raise HTTPException(status_code=503, detail="API authentication is not configured")
|
| 166 |
+
if expected and (not token or not secrets.compare_digest(token, expected)):
|
| 167 |
+
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 168 |
+
|
| 169 |
+
def _authorize_request(token: str | None, request: Request) -> None:
|
| 170 |
+
if _session(request):
|
| 171 |
+
return
|
| 172 |
+
_authorize(token)
|
| 173 |
+
|
| 174 |
+
def _session(request: Request) -> dict[str, Any] | None:
|
| 175 |
+
sid = request.cookies.get("ocr_session")
|
| 176 |
+
return _sessions.get(sid) if sid else None
|
| 177 |
+
|
| 178 |
+
@app.get("/api/auth/github/start")
|
| 179 |
+
def github_login() -> RedirectResponse:
|
| 180 |
+
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 181 |
+
if not client_id:
|
| 182 |
+
raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
|
| 183 |
+
state = secrets.token_urlsafe(32)
|
| 184 |
+
_oauth_states.add(state)
|
| 185 |
+
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 186 |
+
url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
|
| 187 |
+
return RedirectResponse(url)
|
| 188 |
+
|
| 189 |
+
@app.get("/api/auth/github/callback")
|
| 190 |
+
def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
|
| 191 |
+
if state not in _oauth_states:
|
| 192 |
+
raise HTTPException(status_code=400, detail="Invalid OAuth state")
|
| 193 |
+
_oauth_states.discard(state)
|
| 194 |
+
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 195 |
+
client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
|
| 196 |
+
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 197 |
+
token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
|
| 198 |
+
token_resp.raise_for_status()
|
| 199 |
+
access_token = token_resp.json().get("access_token")
|
| 200 |
+
if not access_token:
|
| 201 |
+
raise HTTPException(status_code=502, detail="GitHub did not return an access token")
|
| 202 |
+
user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
|
| 203 |
+
user_resp.raise_for_status()
|
| 204 |
+
user = user_resp.json()
|
| 205 |
+
sid = secrets.token_urlsafe(32)
|
| 206 |
+
_sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
|
| 207 |
+
frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
|
| 208 |
+
out = RedirectResponse(frontend)
|
| 209 |
+
out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
|
| 210 |
+
return out
|
| 211 |
+
|
| 212 |
+
@app.get("/api/auth/me")
|
| 213 |
+
def github_me(request: Request) -> dict[str, Any]:
|
| 214 |
+
session = _session(request)
|
| 215 |
+
if not session:
|
| 216 |
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 217 |
+
return {"github_id": session["github_id"], "login": session["login"]}
|
| 218 |
+
|
| 219 |
+
@app.post("/api/auth/logout")
|
| 220 |
+
def github_logout(request: Request) -> dict[str, str]:
|
| 221 |
+
sid = request.cookies.get("ocr_session")
|
| 222 |
+
if sid:
|
| 223 |
+
_sessions.pop(sid, None)
|
| 224 |
+
return {"status": "logged_out"}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 228 |
+
result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
|
| 229 |
+
now = time.time()
|
| 230 |
+
result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
|
| 231 |
+
if job.get("status") == "queued":
|
| 232 |
+
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 233 |
+
return result
|
| 234 |
+
|
| 235 |
+
def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
|
| 236 |
+
result = _public_job(job)
|
| 237 |
+
task_id = result.get("ragas_task_id")
|
| 238 |
+
with _ragas_lock:
|
| 239 |
+
task = _ragas_tasks.get(task_id) if task_id else None
|
| 240 |
+
def finish():
|
| 241 |
+
metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
|
| 242 |
+
evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
|
| 243 |
+
result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
|
| 244 |
+
if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
|
| 245 |
+
result['ragas']['status'] = 'partial'
|
| 246 |
+
if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
|
| 247 |
+
with _lock:
|
| 248 |
+
live = _jobs.get(job.get('id'))
|
| 249 |
+
if live is not None:
|
| 250 |
+
live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
|
| 251 |
+
_save_job(live)
|
| 252 |
+
return result
|
| 253 |
+
if not task_id:
|
| 254 |
+
result["ragas"] = {
|
| 255 |
+
"status": "skipped",
|
| 256 |
+
"scores": result.get("ragas_scores") or {},
|
| 257 |
+
"reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
|
| 258 |
+
}
|
| 259 |
+
else:
|
| 260 |
+
if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
|
| 261 |
+
result["ragas"] = {
|
| 262 |
+
"status": job["ragas_status"],
|
| 263 |
+
"scores": job.get("ragas_scores") or {},
|
| 264 |
+
"error": job.get("ragas_error"),
|
| 265 |
+
}
|
| 266 |
+
return finish()
|
| 267 |
+
with _ragas_lock:
|
| 268 |
+
task = _ragas_tasks.get(task_id)
|
| 269 |
+
if not task:
|
| 270 |
+
# Task registries are process-local. A restart invalidates an
|
| 271 |
+
# in-flight task instead of making the client poll forever.
|
| 272 |
+
if result.get("ragas_scores"):
|
| 273 |
+
result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
|
| 274 |
+
else:
|
| 275 |
+
result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
|
| 276 |
+
with _lock:
|
| 277 |
+
live = _jobs.get(job.get("id"))
|
| 278 |
+
if live is not None:
|
| 279 |
+
live["ragas_status"] = "unavailable"
|
| 280 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 281 |
+
_save_job(live)
|
| 282 |
+
elif not task.get("done"):
|
| 283 |
+
timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
|
| 284 |
+
started = float(task.get("started", 0) or 0)
|
| 285 |
+
if started and datetime.now(timezone.utc).timestamp() - started > timeout:
|
| 286 |
+
result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
|
| 287 |
+
with _lock:
|
| 288 |
+
live = _jobs.get(job.get("id"))
|
| 289 |
+
if live is not None:
|
| 290 |
+
live["ragas_status"] = "failed"
|
| 291 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 292 |
+
_save_job(live)
|
| 293 |
+
else:
|
| 294 |
+
result["ragas"] = {"status": "pending"}
|
| 295 |
+
elif task.get("error"):
|
| 296 |
+
result["ragas"] = {"status": "failed", "error": task.get("error")}
|
| 297 |
+
with _lock:
|
| 298 |
+
live = _jobs.get(job.get("id"))
|
| 299 |
+
if live is not None:
|
| 300 |
+
live["ragas_status"] = "failed"
|
| 301 |
+
live["ragas_error"] = task.get("error")
|
| 302 |
+
_save_job(live)
|
| 303 |
+
else:
|
| 304 |
+
scores = task.get("scores") or {}
|
| 305 |
+
if scores:
|
| 306 |
+
result["ragas"] = {"status": "completed", "scores": scores}
|
| 307 |
+
if not job.get("ragas_scores"):
|
| 308 |
+
with _lock:
|
| 309 |
+
live = _jobs.get(job.get("id"))
|
| 310 |
+
if live is not None:
|
| 311 |
+
live["ragas_scores"] = scores
|
| 312 |
+
live["ragas_status"] = "completed"
|
| 313 |
+
_save_job(live)
|
| 314 |
+
else:
|
| 315 |
+
result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
|
| 316 |
+
with _lock:
|
| 317 |
+
live = _jobs.get(job.get("id"))
|
| 318 |
+
if live is not None:
|
| 319 |
+
live["ragas_status"] = "completed_no_scores"
|
| 320 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 321 |
+
_save_job(live)
|
| 322 |
+
return finish()
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 326 |
+
with _lock:
|
| 327 |
+
if _jobs.get(job_id, {}).get("status") == "cancelled":
|
| 328 |
+
return
|
| 329 |
+
if job_id in _jobs:
|
| 330 |
+
_jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
|
| 331 |
+
_save_job(_jobs[job_id])
|
| 332 |
+
try:
|
| 333 |
+
ephemeral_endpoint = None
|
| 334 |
+
ragas_started = False
|
| 335 |
+
endpoint_name = _normalize_endpoint_name(request.endpoint)
|
| 336 |
+
if request.api_key:
|
| 337 |
+
if not request.provider or not request.model:
|
| 338 |
+
raise ValueError("provider and model are required when supplying a user API key")
|
| 339 |
+
ephemeral_endpoint = f"user-{job_id}"
|
| 340 |
+
register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
|
| 341 |
+
endpoint_name = ephemeral_endpoint
|
| 342 |
+
def save_ragas(scores: dict, error: str | None) -> None:
|
| 343 |
+
try:
|
| 344 |
+
with _lock:
|
| 345 |
+
live = _jobs.get(job_id)
|
| 346 |
+
if live is None:
|
| 347 |
+
return
|
| 348 |
+
live["ragas_scores"] = scores or None
|
| 349 |
+
live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
|
| 350 |
+
live["ragas_error"] = error
|
| 351 |
+
_save_job(live)
|
| 352 |
+
finally:
|
| 353 |
+
# Custom providers are registered only for this job. Keep the
|
| 354 |
+
# endpoint alive until the background RAGAS task has finished;
|
| 355 |
+
# otherwise evaluation silently falls back to built-ins.
|
| 356 |
+
if ephemeral_endpoint:
|
| 357 |
+
unregister_endpoint(ephemeral_endpoint)
|
| 358 |
+
|
| 359 |
+
def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
|
| 360 |
+
with _lock:
|
| 361 |
+
live = _jobs[job_id]
|
| 362 |
+
if live.get("status") == "cancelled":
|
| 363 |
+
raise RuntimeError("Review cancelled")
|
| 364 |
+
completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
|
| 365 |
+
if stage not in completed:
|
| 366 |
+
completed.append(stage)
|
| 367 |
+
live["progress"]["stage"] = stage
|
| 368 |
+
live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
|
| 369 |
+
if isinstance(update, dict):
|
| 370 |
+
stages = update.get("review_stages", [])
|
| 371 |
+
if isinstance(stages, list):
|
| 372 |
+
live.setdefault("review_stages", []).extend(stages)
|
| 373 |
+
for key in ("findings",):
|
| 374 |
+
for finding in update.get(key, []) or []:
|
| 375 |
+
if hasattr(finding, "model_dump"):
|
| 376 |
+
finding = finding.model_dump(mode="json")
|
| 377 |
+
if isinstance(finding, dict):
|
| 378 |
+
live.setdefault("findings", []).append(finding)
|
| 379 |
+
_save_job(live)
|
| 380 |
+
|
| 381 |
+
state, config, cost, ragas, ragas_inputs = _build_and_stream(
|
| 382 |
+
request.repo,
|
| 383 |
+
request.pr_number,
|
| 384 |
+
endpoint_name,
|
| 385 |
+
ragas_background=True,
|
| 386 |
+
ragas_result_callback=save_ragas,
|
| 387 |
+
progress_callback=progress,
|
| 388 |
+
review_mode=request.review_mode,
|
| 389 |
+
baseline_sha=request.baseline_sha,
|
| 390 |
+
)
|
| 391 |
+
ragas_started = isinstance(ragas, str)
|
| 392 |
+
actual_head = state.values.get("head_sha")
|
| 393 |
+
verdict: Verdict | None = state.values.get("verdict")
|
| 394 |
+
findings: list[Finding] = state.values.get("final_findings", [])
|
| 395 |
+
with _lock:
|
| 396 |
+
if _jobs[job_id].get("status") == "cancelled":
|
| 397 |
+
return
|
| 398 |
+
if actual_head and _jobs[job_id].get("head_sha") != actual_head:
|
| 399 |
+
# The PR moved between metadata lookup and ingestion. The result
|
| 400 |
+
# can still be viewed, but must not satisfy the old cache key.
|
| 401 |
+
_jobs[job_id]["request_fingerprint"] = None
|
| 402 |
+
_jobs[job_id]["head_sha"] = actual_head
|
| 403 |
+
stages = state.values.get("review_stages", [])
|
| 404 |
+
incomplete = bool(verdict and verdict.recommendation == "incomplete")
|
| 405 |
+
_jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
|
| 406 |
+
_save_job(_jobs[job_id])
|
| 407 |
+
except Exception as exc:
|
| 408 |
+
with _lock:
|
| 409 |
+
if _jobs[job_id].get("status") != "cancelled":
|
| 410 |
+
_jobs[job_id].update(status="failed", error=str(exc)[:500])
|
| 411 |
+
_save_job(_jobs[job_id])
|
| 412 |
+
finally:
|
| 413 |
+
if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
|
| 414 |
+
unregister_endpoint(ephemeral_endpoint)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _hydrate_jobs() -> None:
|
| 418 |
+
"""Restore persisted jobs after a process restart and resume interrupted work."""
|
| 419 |
+
for persisted in _load_jobs():
|
| 420 |
+
# Evaluation inputs may include an in-memory endpoint object. Never
|
| 421 |
+
# retain or expose that snapshot: it can contain a user's provider key.
|
| 422 |
+
if "ragas_inputs" in persisted:
|
| 423 |
+
persisted.pop("ragas_inputs", None)
|
| 424 |
+
_save_job(persisted)
|
| 425 |
+
job_id = persisted.get("id")
|
| 426 |
+
if not job_id:
|
| 427 |
+
continue
|
| 428 |
+
status = persisted.get("status")
|
| 429 |
+
_jobs[job_id] = persisted
|
| 430 |
+
if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
|
| 431 |
+
persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
|
| 432 |
+
_save_job(persisted)
|
| 433 |
+
if status in {"queued", "processing"} and persisted.get("custom_provider"):
|
| 434 |
+
persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
|
| 435 |
+
_save_job(persisted)
|
| 436 |
+
continue
|
| 437 |
+
if status in {"queued", "processing", "processing_decision"}:
|
| 438 |
+
# Decision processing cannot be safely replayed without an explicit
|
| 439 |
+
# user action; review execution can be resumed idempotently.
|
| 440 |
+
if status == "processing_decision":
|
| 441 |
+
_jobs[job_id]["status"] = "awaiting_approval"
|
| 442 |
+
_save_job(_jobs[job_id])
|
| 443 |
+
continue
|
| 444 |
+
try:
|
| 445 |
+
request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
|
| 446 |
+
except Exception:
|
| 447 |
+
_jobs[job_id].update(status="failed", error="Persisted job request is invalid")
|
| 448 |
+
_save_job(_jobs[job_id])
|
| 449 |
+
continue
|
| 450 |
+
_jobs[job_id]["status"] = "queued"
|
| 451 |
+
_save_job(_jobs[job_id])
|
| 452 |
+
_jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
_hydrate_jobs()
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
@app.get("/api/health")
|
| 459 |
+
def health() -> dict[str, Any]:
|
| 460 |
+
provider_configured = any(
|
| 461 |
+
os.getenv(name, "").strip()
|
| 462 |
+
for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
|
| 463 |
+
)
|
| 464 |
+
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 465 |
+
persistence = "local_default_path"
|
| 466 |
+
if os.getenv("SUPABASE_DB_URL"):
|
| 467 |
+
probe = _postgres_connect()
|
| 468 |
+
if probe is not None:
|
| 469 |
+
probe.close()
|
| 470 |
+
persistence = "supabase_postgres"
|
| 471 |
+
else:
|
| 472 |
+
persistence = "supabase_configured_unreachable"
|
| 473 |
+
elif os.getenv("OPENCODEREVIEW_DB_PATH"):
|
| 474 |
+
persistence = "configured_path"
|
| 475 |
+
return {
|
| 476 |
+
"status": "ok",
|
| 477 |
+
"inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
|
| 478 |
+
"authentication": "required" if require_auth else "optional",
|
| 479 |
+
"rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
|
| 480 |
+
"persistence": persistence,
|
| 481 |
+
"local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
|
| 482 |
+
in {"1", "true", "yes", "on"},
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@app.post("/api/reviews", status_code=202)
|
| 487 |
+
def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
|
| 488 |
+
_authorize_request(x_api_key, http_request)
|
| 489 |
+
_rate_limit(http_request)
|
| 490 |
+
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 491 |
+
material = request.model_dump()
|
| 492 |
+
head_sha = base_sha = None
|
| 493 |
+
try:
|
| 494 |
+
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 495 |
+
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 496 |
+
if token:
|
| 497 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 498 |
+
response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
|
| 499 |
+
response.raise_for_status()
|
| 500 |
+
pull = response.json()
|
| 501 |
+
head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
|
| 502 |
+
except (requests.RequestException, KeyError, ValueError):
|
| 503 |
+
pass # Active deduplication still works if GitHub metadata is unavailable.
|
| 504 |
+
prompt_hash = hashlib.sha256()
|
| 505 |
+
for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
|
| 506 |
+
prompt_hash.update(source.read_bytes())
|
| 507 |
+
for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
|
| 508 |
+
prompt_hash.update(source.read_bytes())
|
| 509 |
+
material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
|
| 510 |
+
fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
|
| 511 |
+
# Reuse completed previews only for an identical immutable diff and configuration.
|
| 512 |
+
with _lock:
|
| 513 |
+
existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
|
| 514 |
+
if existing is None:
|
| 515 |
+
job_id = str(uuid.uuid4())
|
| 516 |
+
job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
|
| 517 |
+
_jobs[job_id] = job
|
| 518 |
+
_save_job(job)
|
| 519 |
+
else:
|
| 520 |
+
job = existing
|
| 521 |
+
if existing is not None:
|
| 522 |
+
return {**_with_ragas(job), "reused": True}
|
| 523 |
+
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 524 |
+
return _with_ragas(job)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
@app.post("/api/reviews/{job_id}/cancel")
|
| 528 |
+
def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 529 |
+
_authorize_request(x_api_key, request)
|
| 530 |
+
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 531 |
+
with _lock:
|
| 532 |
+
job = _jobs.get(job_id)
|
| 533 |
+
if not job or job.get("owner_id", "api-key") != owner:
|
| 534 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 535 |
+
if job.get("status") not in {"queued", "processing"}:
|
| 536 |
+
raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
|
| 537 |
+
future = job.get("future")
|
| 538 |
+
if future:
|
| 539 |
+
future.cancel()
|
| 540 |
+
job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
|
| 541 |
+
_save_job(job)
|
| 542 |
+
return _public_job(job)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
@app.get("/api/reviews/{job_id}")
|
| 546 |
+
def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 547 |
+
# API-key authorization remains supported for polling; OAuth callers use the cookie path.
|
| 548 |
+
_authorize_request(x_api_key, request)
|
| 549 |
+
with _lock:
|
| 550 |
+
job = _jobs.get(job_id)
|
| 551 |
+
if not job:
|
| 552 |
+
job = _load_job(job_id)
|
| 553 |
+
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 554 |
+
if not job or job.get("owner_id", "api-key") != owner:
|
| 555 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 556 |
+
return _with_ragas(job)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
@app.post('/api/reviews/{job_id}/feedback')
|
| 560 |
+
def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
|
| 561 |
+
x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 562 |
+
_authorize_request(x_api_key, request)
|
| 563 |
+
_rate_limit(request)
|
| 564 |
+
owner = str((_session(request) or {}).get('github_id') or 'api-key')
|
| 565 |
+
with _lock:
|
| 566 |
+
job = _jobs.get(job_id) or _load_job(job_id)
|
| 567 |
+
if not job or job.get('owner_id', 'api-key') != owner:
|
| 568 |
+
raise HTTPException(status_code=404, detail='Review not found')
|
| 569 |
+
if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
|
| 570 |
+
raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
|
| 571 |
+
if payload.finding_index >= len(job.get('findings') or []):
|
| 572 |
+
raise HTTPException(status_code=422, detail='Finding does not exist')
|
| 573 |
+
feedback = dict(job.get('feedback') or {})
|
| 574 |
+
feedback[str(payload.finding_index)] = payload.label
|
| 575 |
+
job['feedback'] = feedback
|
| 576 |
+
job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
|
| 577 |
+
_jobs[job_id] = job
|
| 578 |
+
_save_job(job)
|
| 579 |
+
return {'feedback': feedback}
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
@app.post("/api/reviews/{job_id}/decision")
|
| 583 |
+
def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 584 |
+
_authorize_request(x_api_key, http_request)
|
| 585 |
+
_rate_limit(http_request)
|
| 586 |
+
with _lock:
|
| 587 |
+
preview = _jobs.get(job_id) or _load_job(job_id)
|
| 588 |
+
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 589 |
+
if not preview or preview.get("owner_id", "api-key") != owner:
|
| 590 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 591 |
+
if request.action == "approve" and preview.get("baseline_sha"):
|
| 592 |
+
raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
|
| 593 |
+
if preview and request.action == "approve" and preview.get("head_sha"):
|
| 594 |
+
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 595 |
+
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 596 |
+
if token:
|
| 597 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 598 |
+
try:
|
| 599 |
+
response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
|
| 600 |
+
response.raise_for_status()
|
| 601 |
+
current = response.json()
|
| 602 |
+
if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
|
| 603 |
+
raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
|
| 604 |
+
except (requests.RequestException, KeyError, ValueError) as exc:
|
| 605 |
+
raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
|
| 606 |
+
with _lock:
|
| 607 |
+
job = _jobs.get(job_id)
|
| 608 |
+
if not job:
|
| 609 |
+
job = _load_job(job_id)
|
| 610 |
+
if not job:
|
| 611 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 612 |
+
if job.get("status") != "awaiting_approval":
|
| 613 |
+
raise HTTPException(status_code=409, detail="Review is not awaiting approval")
|
| 614 |
+
config = job["config"]
|
| 615 |
+
job["status"] = "processing_decision"
|
| 616 |
+
_save_job(job)
|
| 617 |
+
if request.action == "reject":
|
| 618 |
+
with _lock:
|
| 619 |
+
job.update(status="rejected", decision="reject")
|
| 620 |
+
_save_job(job)
|
| 621 |
+
return _public_job(job)
|
| 622 |
+
graph = build_graph(DB_PATH)
|
| 623 |
+
try:
|
| 624 |
+
callbacks = [TokenCostCallback()]
|
| 625 |
+
handler = get_langfuse_handler()
|
| 626 |
+
if handler:
|
| 627 |
+
callbacks.append(handler)
|
| 628 |
+
config = dict(config)
|
| 629 |
+
config["callbacks"] = callbacks
|
| 630 |
+
result = graph.invoke(Command(resume={"action": "approve"}), config)
|
| 631 |
+
posting_result = result.get("posting_result") if isinstance(result, dict) else None
|
| 632 |
+
final_status = (posting_result or {}).get("status", "posted")
|
| 633 |
+
with _lock:
|
| 634 |
+
job.update(status=final_status, decision="approve", posting_result=posting_result)
|
| 635 |
+
_save_job(job)
|
| 636 |
+
return _public_job(job)
|
| 637 |
+
except Exception as exc:
|
| 638 |
+
with _lock:
|
| 639 |
+
job.update(status="failed", error=str(exc)[:500])
|
| 640 |
+
_save_job(job)
|
| 641 |
+
raise HTTPException(status_code=500, detail="Decision processing failed") from exc
|
| 642 |
+
finally:
|
| 643 |
+
conn = getattr(graph, "_opencodereview_conn", None)
|
| 644 |
+
if conn:
|
| 645 |
+
conn.close()
|
| 646 |
+
flush_langfuse()
|
frontend/api/provider-test.js
CHANGED
|
@@ -17,7 +17,7 @@ export default async function handler(req, res) {
|
|
| 17 |
body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
|
| 18 |
} else {
|
| 19 |
const base = new URL(baseUrl || 'https://api.openai.com/v1');
|
| 20 |
-
if (base.protocol !== 'https:' || !['openrouter.ai','api.openai.com','api.groq.com','api.deepseek.com'].includes(base.hostname) || base.port || base.username || base.password) return res.status(400).json({error:'Use an HTTPS API URL from OpenRouter, OpenAI, Groq, or
|
| 21 |
url = `${base.origin}${base.pathname.replace(/\/$/,'')}/chat/completions`;
|
| 22 |
headers = {Authorization:`Bearer ${apiKey}`};
|
| 23 |
body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
|
|
|
|
| 17 |
body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
|
| 18 |
} else {
|
| 19 |
const base = new URL(baseUrl || 'https://api.openai.com/v1');
|
| 20 |
+
if (base.protocol !== 'https:' || !['openrouter.ai','api.openai.com','api.groq.com','api.deepseek.com','tokenharbor.ai'].includes(base.hostname) || base.port || base.username || base.password) return res.status(400).json({error:'Use an HTTPS API URL from OpenRouter, OpenAI, Groq, DeepSeek, or TokenHarbor.'});
|
| 21 |
url = `${base.origin}${base.pathname.replace(/\/$/,'')}/chat/completions`;
|
| 22 |
headers = {Authorization:`Bearer ${apiKey}`};
|
| 23 |
body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
|
frontend/api/provider-test.test.js
CHANGED
|
@@ -48,3 +48,15 @@ test('MiniMax probe reserves reasoning budget consistently with review calls', a
|
|
| 48 |
await handler(req,res); assert.equal(res.code,200);
|
| 49 |
} finally { globalThis.fetch=original; }
|
| 50 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
await handler(req,res); assert.equal(res.code,200);
|
| 49 |
} finally { globalThis.fetch=original; }
|
| 50 |
});
|
| 51 |
+
|
| 52 |
+
test('TokenHarbor OpenAI-compatible URL is allowed', async () => {
|
| 53 |
+
const original = globalThis.fetch;
|
| 54 |
+
try {
|
| 55 |
+
globalThis.fetch = async (url) => {
|
| 56 |
+
assert.equal(url, 'https://tokenharbor.ai/v1/chat/completions');
|
| 57 |
+
return {ok:true,json:async()=>({choices:[{message:{content:'{"ok":true}'}}]})};
|
| 58 |
+
};
|
| 59 |
+
const req = request(), res = response(); req.body.baseUrl='https://tokenharbor.ai/v1';
|
| 60 |
+
await handler(req,res); assert.equal(res.code,200); assert.equal(res.body.json_object_valid,true);
|
| 61 |
+
} finally { globalThis.fetch = original; }
|
| 62 |
+
});
|