Sdm0 commited on
Commit
d6dc43a
·
verified ·
1 Parent(s): d8101d2

feat: use Supabase Postgres for durable jobs

Browse files
Files changed (1) hide show
  1. api.py +49 -1
api.py CHANGED
@@ -34,7 +34,30 @@ _jobs: dict[str, dict[str, Any]] = {}
34
  _lock = threading.Lock()
35
  _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
36
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def _init_jobs() -> None:
 
 
 
 
 
 
 
 
 
 
 
38
  with sqlite3.connect(DB_PATH) as conn:
39
  conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
40
  conn.commit()
@@ -45,16 +68,41 @@ def _save_job(job: dict[str, Any]) -> None:
45
  payload = {k: v for k, v in job.items() if k not in {"future"}}
46
  if "config" in payload:
47
  payload["config"] = {"configurable": payload["config"].get("configurable", {})}
 
 
 
 
 
 
 
 
 
 
 
48
  with sqlite3.connect(DB_PATH) as conn:
49
  conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
50
  conn.commit()
51
 
52
  def _load_job(job_id: str) -> dict[str, Any] | None:
 
 
 
 
 
 
 
53
  with sqlite3.connect(DB_PATH) as conn:
54
  row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
55
  return json.loads(row[0]) if row else None
56
 
57
  def _load_jobs() -> list[dict[str, Any]]:
 
 
 
 
 
 
 
58
  with sqlite3.connect(DB_PATH) as conn:
59
  rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
60
  return [json.loads(row[0]) for row in rows]
@@ -188,7 +236,7 @@ def health() -> dict[str, Any]:
188
  "status": "ok",
189
  "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
190
  "authentication": "required" if require_auth else "optional",
191
- "persistence": "configured_path" if os.getenv("OPENCODEREVIEW_DB_PATH") else "local_default_path",
192
  "local_embeddings": False,
193
  }
194
 
 
34
  _lock = threading.Lock()
35
  _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
36
 
37
+
38
+ def _postgres_connect():
39
+ """Return a Supabase Postgres connection when configured, else None."""
40
+ url = os.getenv("SUPABASE_DB_URL", "").strip()
41
+ if not url:
42
+ return None
43
+ try:
44
+ import psycopg
45
+ return psycopg.connect(url)
46
+ except Exception:
47
+ return None
48
+
49
  def _init_jobs() -> None:
50
+ pg = _postgres_connect()
51
+ if pg is not None:
52
+ with pg:
53
+ with pg.cursor() as cur:
54
+ cur.execute("""create table if not exists public.review_jobs (
55
+ id uuid primary key, repo text not null, pr_number integer not null,
56
+ endpoint text, status text not null, payload jsonb not null,
57
+ created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
58
+ cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
59
+ pg.close()
60
+ return
61
  with sqlite3.connect(DB_PATH) as conn:
62
  conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
63
  conn.commit()
 
68
  payload = {k: v for k, v in job.items() if k not in {"future"}}
69
  if "config" in payload:
70
  payload["config"] = {"configurable": payload["config"].get("configurable", {})}
71
+ pg = _postgres_connect()
72
+ if pg is not None:
73
+ with pg:
74
+ with pg.cursor() as cur:
75
+ cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
76
+ values (%s, %s, %s, %s, %s, %s::jsonb, now())
77
+ on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
78
+ endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
79
+ (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
80
+ pg.close()
81
+ return
82
  with sqlite3.connect(DB_PATH) as conn:
83
  conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
84
  conn.commit()
85
 
86
  def _load_job(job_id: str) -> dict[str, Any] | None:
87
+ pg = _postgres_connect()
88
+ if pg is not None:
89
+ with pg.cursor() as cur:
90
+ cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
91
+ row = cur.fetchone()
92
+ pg.close()
93
+ return json.loads(row[0]) if row else None
94
  with sqlite3.connect(DB_PATH) as conn:
95
  row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
96
  return json.loads(row[0]) if row else None
97
 
98
  def _load_jobs() -> list[dict[str, Any]]:
99
+ pg = _postgres_connect()
100
+ if pg is not None:
101
+ with pg.cursor() as cur:
102
+ cur.execute("select payload from public.review_jobs")
103
+ rows = cur.fetchall()
104
+ pg.close()
105
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
106
  with sqlite3.connect(DB_PATH) as conn:
107
  rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
108
  return [json.loads(row[0]) for row in rows]
 
236
  "status": "ok",
237
  "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
238
  "authentication": "required" if require_auth else "optional",
239
+ "persistence": "supabase_postgres" if os.getenv("SUPABASE_DB_URL") else ("configured_path" if os.getenv("OPENCODEREVIEW_DB_PATH") else "local_default_path"),
240
  "local_embeddings": False,
241
  }
242