Sdm0 commited on
Commit
2b7edd7
·
verified ·
1 Parent(s): 104cdc4

Deploy dab7981f

Browse files
Files changed (1) hide show
  1. api.py +34 -0
api.py CHANGED
@@ -7,6 +7,8 @@ the process-local registry with a durable store and queue.
7
  from __future__ import annotations
8
 
9
  import os
 
 
10
  import threading
11
  import uuid
12
  from concurrent.futures import ThreadPoolExecutor
@@ -31,6 +33,26 @@ _jobs: dict[str, dict[str, Any]] = {}
31
  _lock = threading.Lock()
32
  _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  class ReviewRequest(BaseModel):
36
  repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
@@ -71,15 +93,18 @@ def _run_job(job_id: str, request: ReviewRequest) -> None:
71
  with _lock:
72
  if job_id in _jobs:
73
  _jobs[job_id]["status"] = "processing"
 
74
  try:
75
  state, config, cost, ragas = _build_and_stream(request.repo, request.pr_number, _normalize_endpoint_name(request.endpoint), ragas_background=True)
76
  verdict: Verdict | None = state.values.get("verdict")
77
  findings: list[Finding] = state.values.get("final_findings", [])
78
  with _lock:
79
  _jobs[job_id].update(status="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, ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None)
 
80
  except Exception as exc:
81
  with _lock:
82
  _jobs[job_id].update(status="failed", error=str(exc)[:500])
 
83
 
84
 
85
  @app.get("/api/health")
@@ -94,6 +119,7 @@ def create_review(request: ReviewRequest, x_api_key: str | None = Header(default
94
  job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
95
  with _lock:
96
  _jobs[job_id] = job
 
97
  job["future"] = _executor.submit(_run_job, job_id, request)
98
  return _with_ragas(job)
99
 
@@ -103,6 +129,8 @@ def get_review(job_id: str, x_api_key: str | None = Header(default=None)) -> dic
103
  _authorize(x_api_key)
104
  with _lock:
105
  job = _jobs.get(job_id)
 
 
106
  if not job:
107
  raise HTTPException(status_code=404, detail="Review not found")
108
  return _with_ragas(job)
@@ -113,15 +141,19 @@ def decide_review(job_id: str, request: DecisionRequest, x_api_key: str | None =
113
  _authorize(x_api_key)
114
  with _lock:
115
  job = _jobs.get(job_id)
 
 
116
  if not job:
117
  raise HTTPException(status_code=404, detail="Review not found")
118
  if job.get("status") != "awaiting_approval":
119
  raise HTTPException(status_code=409, detail="Review is not awaiting approval")
120
  config = job["config"]
121
  job["status"] = "processing_decision"
 
122
  if request.action == "reject":
123
  with _lock:
124
  job.update(status="rejected", decision="reject")
 
125
  return _public_job(job)
126
  graph = build_graph(DB_PATH)
127
  try:
@@ -136,10 +168,12 @@ def decide_review(job_id: str, request: DecisionRequest, x_api_key: str | None =
136
  final_status = (posting_result or {}).get("status", "posted")
137
  with _lock:
138
  job.update(status=final_status, decision="approve", posting_result=posting_result)
 
139
  return _public_job(job)
140
  except Exception as exc:
141
  with _lock:
142
  job.update(status="failed", error=str(exc)[:500])
 
143
  raise HTTPException(status_code=500, detail="Decision processing failed") from exc
144
  finally:
145
  conn = getattr(graph, "_opencodereview_conn", None)
 
7
  from __future__ import annotations
8
 
9
  import os
10
+ import json
11
+ import sqlite3
12
  import threading
13
  import uuid
14
  from concurrent.futures import ThreadPoolExecutor
 
33
  _lock = threading.Lock()
34
  _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
35
 
36
+ def _init_jobs() -> None:
37
+ with sqlite3.connect(DB_PATH) as conn:
38
+ conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
39
+ conn.commit()
40
+
41
+ _init_jobs()
42
+
43
+ def _save_job(job: dict[str, Any]) -> None:
44
+ payload = {k: v for k, v in job.items() if k not in {"future"}}
45
+ if "config" in payload:
46
+ payload["config"] = {"configurable": payload["config"].get("configurable", {})}
47
+ with sqlite3.connect(DB_PATH) as conn:
48
+ conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
49
+ conn.commit()
50
+
51
+ def _load_job(job_id: str) -> dict[str, Any] | None:
52
+ with sqlite3.connect(DB_PATH) as conn:
53
+ row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
54
+ return json.loads(row[0]) if row else None
55
+
56
 
57
  class ReviewRequest(BaseModel):
58
  repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
 
93
  with _lock:
94
  if job_id in _jobs:
95
  _jobs[job_id]["status"] = "processing"
96
+ _save_job(_jobs[job_id])
97
  try:
98
  state, config, cost, ragas = _build_and_stream(request.repo, request.pr_number, _normalize_endpoint_name(request.endpoint), ragas_background=True)
99
  verdict: Verdict | None = state.values.get("verdict")
100
  findings: list[Finding] = state.values.get("final_findings", [])
101
  with _lock:
102
  _jobs[job_id].update(status="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, ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None)
103
+ _save_job(_jobs[job_id])
104
  except Exception as exc:
105
  with _lock:
106
  _jobs[job_id].update(status="failed", error=str(exc)[:500])
107
+ _save_job(_jobs[job_id])
108
 
109
 
110
  @app.get("/api/health")
 
119
  job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
120
  with _lock:
121
  _jobs[job_id] = job
122
+ _save_job(job)
123
  job["future"] = _executor.submit(_run_job, job_id, request)
124
  return _with_ragas(job)
125
 
 
129
  _authorize(x_api_key)
130
  with _lock:
131
  job = _jobs.get(job_id)
132
+ if not job:
133
+ job = _load_job(job_id)
134
  if not job:
135
  raise HTTPException(status_code=404, detail="Review not found")
136
  return _with_ragas(job)
 
141
  _authorize(x_api_key)
142
  with _lock:
143
  job = _jobs.get(job_id)
144
+ if not job:
145
+ job = _load_job(job_id)
146
  if not job:
147
  raise HTTPException(status_code=404, detail="Review not found")
148
  if job.get("status") != "awaiting_approval":
149
  raise HTTPException(status_code=409, detail="Review is not awaiting approval")
150
  config = job["config"]
151
  job["status"] = "processing_decision"
152
+ _save_job(job)
153
  if request.action == "reject":
154
  with _lock:
155
  job.update(status="rejected", decision="reject")
156
+ _save_job(job)
157
  return _public_job(job)
158
  graph = build_graph(DB_PATH)
159
  try:
 
168
  final_status = (posting_result or {}).get("status", "posted")
169
  with _lock:
170
  job.update(status=final_status, decision="approve", posting_result=posting_result)
171
+ _save_job(job)
172
  return _public_job(job)
173
  except Exception as exc:
174
  with _lock:
175
  job.update(status="failed", error=str(exc)[:500])
176
+ _save_job(job)
177
  raise HTTPException(status_code=500, detail="Decision processing failed") from exc
178
  finally:
179
  conn = getattr(graph, "_opencodereview_conn", None)