Spaces:
Sleeping

PERDYPTO commited on
Commit
742c2d4
Β·
verified Β·
1 Parent(s): 1e28d9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -141
app.py CHANGED
@@ -2,50 +2,82 @@ import os
2
  import sqlite3
3
  import tempfile
4
  import threading
5
- from typing import Optional
6
-
7
- from fastapi import FastAPI, Query, HTTPException
 
 
 
 
 
 
 
8
  from huggingface_hub import download_bucket_files, batch_bucket_files
9
 
10
- TOKEN = os.environ.get("HF_TOKEN", "")
 
 
 
 
 
 
 
 
 
11
 
 
12
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
13
  DB_PATH_IN_BUCKET = "github_pipeline.db"
14
 
15
- app = FastAPI(title="GitHub Pipeline DB API")
16
-
17
- _status = {"state": "starting"}
18
- _lock = threading.Lock()
19
-
20
- # Persistent disk connection (shared across requests with check_same_thread=False)
21
  _conn: Optional[sqlite3.Connection] = None
22
  _local_db_file: Optional[str] = None
23
 
24
- # Columns that are safe to sort/filter by. Built dynamically from the actual
25
- # schema at load time so this stays correct even if the DB shape changes.
26
  _metadata_columns: list[str] = []
27
  _repo_ids_columns: list[str] = []
 
28
 
29
- # The "joined" view we expose to the API: repo_ids + metadata on repo_id.
30
  JOIN_SQL = """
31
  FROM repo_ids r
32
  LEFT JOIN metadata m ON m.repo_id = r.repo_id
33
  """
34
 
35
- # Whitelisted sortable/filterable fields -> actual SQL column expression.
36
- FIELD_MAP: dict[str, str] = {}
37
-
38
- # Fields that are boolean-ish (0/1) and get exposed as true/false filters.
39
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
40
 
41
-
42
- def build_field_map(conn: sqlite3.Connection):
43
- global _metadata_columns, _repo_ids_columns, FIELD_MAP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  cur = conn.cursor()
45
-
46
  cur.execute('PRAGMA table_info("repo_ids")')
47
  _repo_ids_columns = [c[1] for c in cur.fetchall()]
48
-
49
  cur.execute('PRAGMA table_info("metadata")')
50
  _metadata_columns = [c[1] for c in cur.fetchall()]
51
 
@@ -54,73 +86,141 @@ def build_field_map(conn: sqlite3.Connection):
54
  fmap[c] = f"r.{c}"
55
  for c in _metadata_columns:
56
  if c == "repo_id":
57
- continue # avoid clobbering r.repo_id
58
  fmap[c] = f"m.{c}"
59
  FIELD_MAP = fmap
60
 
 
 
 
 
 
 
61
 
62
- def refresh_db():
63
- """Download the db from HF bucket and open it in high-performance disk-backed read mode."""
64
- global _conn, _local_db_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
 
 
 
66
  workdir = tempfile.mkdtemp()
67
  local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
68
 
69
- print(f"[download] pulling hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
70
  download_bucket_files(
71
  SOURCE_BUCKET,
72
  [(DB_PATH_IN_BUCKET, local_db_path)],
73
  token=TOKEN,
74
  )
75
- print(f"[download] saved to {local_db_path}")
76
 
77
- # Open SQLite directly from disk with Read-Only URI mode & memory optimizations
78
- # This prevents OOM on 16GB RAM limits while keeping speeds near in-memory reads.
79
  db_uri = f"file:{local_db_path}?mode=ro"
80
  new_conn = sqlite3.connect(db_uri, uri=True, check_same_thread=False)
 
81
 
82
- # SQLite performance tuning for low-RAM disk reading
83
- new_conn.execute("PRAGMA cache_size = -64000") # Limit RAM cache to 64MB max
84
- new_conn.execute("PRAGMA temp_store = MEMORY")
85
- new_conn.execute("PRAGMA mmap_size = 30000000000") # Enable memory-mapped I/O
86
 
87
- build_field_map(new_conn)
 
 
88
 
89
- with _lock:
90
  if _conn:
91
  _conn.close()
92
  _conn = new_conn
93
  _local_db_file = local_db_path
94
 
95
- print("[load] DB ready and optimized for fast, low-memory reads.")
 
 
 
96
 
97
 
98
- def push_db_back():
99
- """Optional: upload local persistent db back to HF bucket."""
100
  if not _local_db_file or not os.path.exists(_local_db_file):
101
  raise HTTPException(400, "No local DB available to push")
102
-
103
- print(f"[upload] pushing db back to hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
104
  batch_bucket_files(
105
  SOURCE_BUCKET,
106
  add=[(_local_db_file, DB_PATH_IN_BUCKET)],
107
  token=TOKEN,
108
  )
109
- print("[upload] done")
110
 
111
 
112
- @app.on_event("startup")
113
- def on_startup():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  try:
115
- refresh_db()
116
- _status["state"] = "ready"
117
  except Exception as e:
118
  _status["state"] = f"error: {e}"
119
  print(f"[fatal] {e}")
 
 
 
 
120
 
 
 
121
 
122
- @app.get("/")
123
- def health():
 
 
 
 
 
 
 
 
 
 
 
124
  return {
125
  "status": _status,
126
  "endpoints": {
@@ -132,48 +232,46 @@ def health():
132
 
133
 
134
  @app.get("/api/schema")
135
- def schema():
136
  if _conn is None:
137
  raise HTTPException(503, "db not loaded yet")
138
- return {
139
  "repo_ids_columns": _repo_ids_columns,
140
  "metadata_columns": _metadata_columns,
141
  "queryable_fields": sorted(FIELD_MAP.keys()),
142
  "boolean_fields": sorted(BOOL_FIELDS & set(FIELD_MAP.keys())),
143
- }
144
-
145
-
146
- def _get_conn() -> sqlite3.Connection:
147
- if _conn is None:
148
- raise HTTPException(503, "db not loaded yet")
149
- return _conn
150
 
151
 
152
  @app.get("/api/query")
153
- def query(
154
- sort_by: str = Query("stars", description="Field to sort by, e.g. stars, forks_count, watchers_count, repo_id"),
155
- order: str = Query("desc", pattern="^(?i)(asc|desc)$", description="asc or desc"),
156
- limit: int = Query(10, ge=1, le=1000, description="Number of rows to return"),
157
  offset: int = Query(0, ge=0),
158
- language: Optional[str] = Query(None, description="Filter by primary_language, e.g. Python"),
159
- is_fork: Optional[bool] = Query(None, description="Filter forks: true/false"),
160
- archived: Optional[bool] = Query(None, description="Filter archived repos: true/false"),
161
- disabled: Optional[bool] = Query(None, description="Filter disabled repos: true/false"),
162
- is_template: Optional[bool] = Query(None, description="Filter template repos: true/false"),
163
- status: Optional[str] = Query(None, description="Filter by repo_ids.status"),
164
- min_stars: Optional[int] = Query(None, description="Minimum stars"),
165
- max_stars: Optional[int] = Query(None, description="Maximum stars"),
166
- search: Optional[str] = Query(None, description="Substring search in repo_path/description"),
167
  ):
168
- conn = _get_conn()
 
 
 
 
169
 
170
  if sort_by not in FIELD_MAP:
171
- raise HTTPException(400, f"invalid sort_by '{sort_by}'. See /api/schema for valid fields.")
172
 
173
  order_sql = "ASC" if order.lower() == "asc" else "DESC"
174
  sort_col = FIELD_MAP[sort_by]
175
 
176
- where = []
177
  params: list = []
178
 
179
  if language:
@@ -207,13 +305,8 @@ def query(
207
 
208
  where_sql = f"WHERE {' AND '.join(where)}" if where else ""
209
 
210
- select_cols = [f"r.{c}" for c in _repo_ids_columns] + [
211
- f"m.{c}" for c in _metadata_columns if c != "repo_id"
212
- ]
213
- select_sql = ", ".join(select_cols)
214
-
215
  sql = f"""
216
- SELECT {select_sql}
217
  {JOIN_SQL}
218
  {where_sql}
219
  ORDER BY {sort_col} {order_sql} NULLS LAST
@@ -221,90 +314,102 @@ def query(
221
  """
222
  params.extend([limit, offset])
223
 
224
- cur = conn.cursor()
225
- try:
226
- cur.execute(sql, params)
227
- except sqlite3.OperationalError:
228
- # Older sqlite may not support NULLS LAST; retry without it.
229
- sql = sql.replace("NULLS LAST", "")
230
- cur.execute(sql, params)
 
 
231
 
232
- col_names = [d[0] for d in cur.description]
233
- rows = [dict(zip(col_names, row)) for row in cur.fetchall()]
234
 
235
- return {
236
  "count": len(rows),
237
  "sort_by": sort_by,
238
  "order": order_sql,
239
  "filters": {
240
- "language": language,
241
- "is_fork": is_fork,
242
- "archived": archived,
243
- "disabled": disabled,
244
- "is_template": is_template,
245
- "status": status,
246
- "min_stars": min_stars,
247
- "max_stars": max_stars,
248
- "search": search,
249
  },
250
  "results": rows,
251
  }
 
 
252
 
253
 
254
  @app.get("/api/languages")
255
- def languages():
256
- """List distinct primary_language values with counts."""
257
- conn = _get_conn()
258
- cur = conn.cursor()
259
- cur.execute(
260
- """
261
- SELECT m.primary_language AS language, COUNT(*) AS count
262
- FROM metadata m
263
- WHERE m.primary_language IS NOT NULL AND m.primary_language != ''
264
- GROUP BY m.primary_language
265
- ORDER BY count DESC
266
- """
267
- )
268
- return {"languages": [{"language": r[0], "count": r[1]} for r in cur.fetchall()]}
 
 
 
 
 
 
 
269
 
270
 
271
  @app.get("/api/stats")
272
- def stats():
273
- conn = _get_conn()
274
- cur = conn.cursor()
275
- cur.execute("SELECT COUNT(*) FROM repo_ids")
276
- total_repos = cur.fetchone()[0]
277
- cur.execute("SELECT COUNT(*) FROM metadata")
278
- total_metadata = cur.fetchone()[0]
279
- cur.execute("SELECT COUNT(*) FROM metadata WHERE is_fork = 1")
280
- forks = cur.fetchone()[0]
281
- cur.execute("SELECT COUNT(*) FROM metadata WHERE archived = 1")
282
- archived = cur.fetchone()[0]
283
- return {
284
- "total_repos": total_repos,
285
- "total_metadata_rows": total_metadata,
286
- "forks": forks,
287
- "archived": archived,
288
- }
 
 
 
 
 
 
 
 
 
 
289
 
290
 
291
  @app.post("/api/refresh")
292
- def refresh():
293
- """Re-download the db from the bucket."""
294
- try:
295
- refresh_db()
296
- _status["state"] = "ready"
297
- return {"status": "ok", "state": _status["state"]}
298
- except Exception as e:
299
- _status["state"] = f"error: {e}"
300
- raise HTTPException(500, str(e))
301
 
302
 
303
  @app.post("/api/push")
304
- def push():
305
- """Persist local state back to HF bucket."""
306
  try:
307
- push_db_back()
308
  return {"status": "ok"}
309
  except Exception as e:
310
  raise HTTPException(500, str(e))
 
2
  import sqlite3
3
  import tempfile
4
  import threading
5
+ import asyncio
6
+ import time
7
+ from typing import Optional, Any
8
+ from functools import lru_cache
9
+ from contextlib import asynccontextmanager
10
+
11
+ from fastapi import FastAPI, Query, HTTPException, Request
12
+ from fastapi.middleware.gzip import GZipMiddleware
13
+ from fastapi.responses import HTMLResponse, JSONResponse
14
+ from fastapi.staticfiles import StaticFiles
15
  from huggingface_hub import download_bucket_files, batch_bucket_files
16
 
17
+ # ─── Optional ultra-fast JSON ───────────────────────────────────────────────
18
+ try:
19
+ import orjson
20
+ class ORJSONResponse(JSONResponse):
21
+ media_type = "application/json"
22
+ def render(self, content: Any) -> bytes:
23
+ return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)
24
+ json_response = ORJSONResponse
25
+ except ImportError:
26
+ json_response = JSONResponse
27
 
28
+ TOKEN = os.environ.get("HF_TOKEN", "")
29
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
30
  DB_PATH_IN_BUCKET = "github_pipeline.db"
31
 
32
+ # ─── State ──────────────────────────────────────────────────────────────────
33
+ _status = {"state": "starting", "last_refresh": None, "db_size_mb": 0}
34
+ _db_lock = threading.Lock() # for connection mutation
35
+ _async_lock = asyncio.Lock() # for async refresh coordination
 
 
36
  _conn: Optional[sqlite3.Connection] = None
37
  _local_db_file: Optional[str] = None
38
 
 
 
39
  _metadata_columns: list[str] = []
40
  _repo_ids_columns: list[str] = []
41
+ FIELD_MAP: dict[str, str] = {}
42
 
 
43
  JOIN_SQL = """
44
  FROM repo_ids r
45
  LEFT JOIN metadata m ON m.repo_id = r.repo_id
46
  """
47
 
 
 
 
 
48
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
49
 
50
+ # Simple TTL cache for query bursts (HF Spaces often gets repeated identical reqs)
51
+ _query_cache: dict[tuple, tuple[Any, float]] = {}
52
+ _CACHE_TTL_SEC = 8.0
53
+ _MAX_CACHE_ENTRIES = 200
54
+
55
+ # Pre-compiled select SQL (rebuilt on refresh)
56
+ _SELECT_SQL: str = ""
57
+
58
+ # ─── SQLite Optimizations ───────────────────────────────────────────────────
59
+ _READ_PRAGMAS = [
60
+ ("PRAGMA journal_mode = OFF", None), # No journal needed for RO
61
+ ("PRAGMA synchronous = OFF", None), # Faster, safe for read-only
62
+ ("PRAGMA cache_size = -262144", None), # 256 MB page cache
63
+ ("PRAGMA temp_store = MEMORY", None),
64
+ ("PRAGMA mmap_size = 30000000000", None), # 30 GB virtual mmap
65
+ ("PRAGMA query_only = ON", None),
66
+ ("PRAGMA threads = 4", None), # Allow background reads
67
+ ("PRAGMA read_uncommitted = 1", None), # Less locking overhead
68
+ ]
69
+
70
+ # ─── Helpers ────────────────────────────────────────────────────────────────
71
+ def _run_sync(fn, *args, **kwargs):
72
+ """Run blocking code in the default thread pool (avoids event-loop blocking)."""
73
+ return asyncio.get_event_loop().run_in_executor(None, lambda: fn(*args, **kwargs))
74
+
75
+
76
+ def _build_field_map(conn: sqlite3.Connection):
77
+ global _metadata_columns, _repo_ids_columns, FIELD_MAP, _SELECT_SQL
78
  cur = conn.cursor()
 
79
  cur.execute('PRAGMA table_info("repo_ids")')
80
  _repo_ids_columns = [c[1] for c in cur.fetchall()]
 
81
  cur.execute('PRAGMA table_info("metadata")')
82
  _metadata_columns = [c[1] for c in cur.fetchall()]
83
 
 
86
  fmap[c] = f"r.{c}"
87
  for c in _metadata_columns:
88
  if c == "repo_id":
89
+ continue
90
  fmap[c] = f"m.{c}"
91
  FIELD_MAP = fmap
92
 
93
+ # Pre-build the giant SELECT once
94
+ cols = [f"r.{c}" for c in _repo_ids_columns] + [
95
+ f"m.{c}" for c in _metadata_columns if c != "repo_id"
96
+ ]
97
+ _SELECT_SQL = ", ".join(cols)
98
+
99
 
100
+ def _ensure_indexes(conn: sqlite3.Connection):
101
+ """Create covering indexes if they don't exist β€” massive speed-up for filtering."""
102
+ cur = conn.cursor()
103
+ idx_stmts = [
104
+ "CREATE INDEX IF NOT EXISTS idx_meta_lang ON metadata(primary_language)",
105
+ "CREATE INDEX IF NOT EXISTS idx_meta_stars ON metadata(stars)",
106
+ "CREATE INDEX IF NOT EXISTS idx_meta_fork ON metadata(is_fork)",
107
+ "CREATE INDEX IF NOT EXISTS idx_meta_arch ON metadata(archived)",
108
+ "CREATE INDEX IF NOT EXISTS idx_meta_status ON repo_ids(status)",
109
+ "CREATE INDEX IF NOT EXISTS idx_meta_search ON metadata(repo_id, description)",
110
+ ]
111
+ for stmt in idx_stmts:
112
+ try:
113
+ cur.execute(stmt)
114
+ except sqlite3.OperationalError:
115
+ pass # may fail on read-only uri for repo_ids indexes; that's ok
116
+ conn.commit()
117
 
118
+
119
+ def _refresh_db_sync():
120
+ global _conn, _local_db_file, _status
121
  workdir = tempfile.mkdtemp()
122
  local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
123
 
 
124
  download_bucket_files(
125
  SOURCE_BUCKET,
126
  [(DB_PATH_IN_BUCKET, local_db_path)],
127
  token=TOKEN,
128
  )
 
129
 
 
 
130
  db_uri = f"file:{local_db_path}?mode=ro"
131
  new_conn = sqlite3.connect(db_uri, uri=True, check_same_thread=False)
132
+ new_conn.row_factory = sqlite3.Row # enables column-name access
133
 
134
+ for pragma, _ in _READ_PRAGMAS:
135
+ new_conn.execute(pragma)
 
 
136
 
137
+ # Try to create indexes (will silently fail on read-only if they exist)
138
+ _ensure_indexes(new_conn)
139
+ _build_field_map(new_conn)
140
 
141
+ with _db_lock:
142
  if _conn:
143
  _conn.close()
144
  _conn = new_conn
145
  _local_db_file = local_db_path
146
 
147
+ size_mb = round(os.path.getsize(local_db_path) / (1024 * 1024), 2)
148
+ _status.update({"state": "ready", "last_refresh": time.time(), "db_size_mb": size_mb})
149
+ _query_cache.clear() # invalidate on refresh
150
+ print(f"[load] DB ready ({size_mb} MB).")
151
 
152
 
153
+ def _push_db_sync():
 
154
  if not _local_db_file or not os.path.exists(_local_db_file):
155
  raise HTTPException(400, "No local DB available to push")
 
 
156
  batch_bucket_files(
157
  SOURCE_BUCKET,
158
  add=[(_local_db_file, DB_PATH_IN_BUCKET)],
159
  token=TOKEN,
160
  )
 
161
 
162
 
163
+ def _get_conn() -> sqlite3.Connection:
164
+ if _conn is None:
165
+ raise HTTPException(503, "db not loaded yet")
166
+ return _conn
167
+
168
+
169
+ # ─── Caching ────────────────────────────────────────────────────────────────
170
+ def _cache_key(*args, **kwargs) -> tuple:
171
+ return args + tuple(sorted(kwargs.items()))
172
+
173
+
174
+ def _get_cached(key: tuple):
175
+ entry = _query_cache.get(key)
176
+ if entry is None:
177
+ return None
178
+ data, ts = entry
179
+ if time.time() - ts > _CACHE_TTL_SEC:
180
+ del _query_cache[key]
181
+ return None
182
+ return data
183
+
184
+
185
+ def _set_cached(key: tuple, data: Any):
186
+ if len(_query_cache) >= _MAX_CACHE_ENTRIES:
187
+ # simple FIFO eviction
188
+ try:
189
+ _query_cache.pop(next(iter(_query_cache)))
190
+ except StopIteration:
191
+ pass
192
+ _query_cache[key] = (data, time.time())
193
+
194
+
195
+ # ─── Lifespan ───────────────────────────────────────────────────────────────
196
+ @asynccontextmanager
197
+ async def lifespan(app: FastAPI):
198
  try:
199
+ await _run_sync(_refresh_db_sync)
 
200
  except Exception as e:
201
  _status["state"] = f"error: {e}"
202
  print(f"[fatal] {e}")
203
+ yield
204
+ if _conn:
205
+ _conn.close()
206
+
207
 
208
+ app = FastAPI(title="GitHub Pipeline DB API", lifespan=lifespan)
209
+ app.add_middleware(GZipMiddleware, minimum_size=500) # compress responses >500B
210
 
211
+ # Serve the cosmic frontend
212
+ app.mount("/static", StaticFiles(directory="static"), name="static")
213
+
214
+
215
+ # ──�� Endpoints ──────────────────────────────────────────────────────────────
216
+ @app.get("/", response_class=HTMLResponse)
217
+ async def root():
218
+ with open("static/index.html", "r", encoding="utf-8") as f:
219
+ return f.read()
220
+
221
+
222
+ @app.get("/api/health")
223
+ async def health():
224
  return {
225
  "status": _status,
226
  "endpoints": {
 
232
 
233
 
234
  @app.get("/api/schema")
235
+ async def schema():
236
  if _conn is None:
237
  raise HTTPException(503, "db not loaded yet")
238
+ return json_response({
239
  "repo_ids_columns": _repo_ids_columns,
240
  "metadata_columns": _metadata_columns,
241
  "queryable_fields": sorted(FIELD_MAP.keys()),
242
  "boolean_fields": sorted(BOOL_FIELDS & set(FIELD_MAP.keys())),
243
+ })
 
 
 
 
 
 
244
 
245
 
246
  @app.get("/api/query")
247
+ async def query(
248
+ sort_by: str = Query("stars", description="Field to sort by"),
249
+ order: str = Query("desc", pattern="^(?i)(asc|desc)$"),
250
+ limit: int = Query(10, ge=1, le=1000),
251
  offset: int = Query(0, ge=0),
252
+ language: Optional[str] = Query(None),
253
+ is_fork: Optional[bool] = Query(None),
254
+ archived: Optional[bool] = Query(None),
255
+ disabled: Optional[bool] = Query(None),
256
+ is_template: Optional[bool] = Query(None),
257
+ status: Optional[str] = Query(None),
258
+ min_stars: Optional[int] = Query(None),
259
+ max_stars: Optional[int] = Query(None),
260
+ search: Optional[str] = Query(None),
261
  ):
262
+ cache_key = _cache_key("query", sort_by, order, limit, offset, language, is_fork,
263
+ archived, disabled, is_template, status, min_stars, max_stars, search)
264
+ cached = _get_cached(cache_key)
265
+ if cached is not None:
266
+ return json_response(cached)
267
 
268
  if sort_by not in FIELD_MAP:
269
+ raise HTTPException(400, f"invalid sort_by '{sort_by}'. See /api/schema.")
270
 
271
  order_sql = "ASC" if order.lower() == "asc" else "DESC"
272
  sort_col = FIELD_MAP[sort_by]
273
 
274
+ where: list[str] = []
275
  params: list = []
276
 
277
  if language:
 
305
 
306
  where_sql = f"WHERE {' AND '.join(where)}" if where else ""
307
 
 
 
 
 
 
308
  sql = f"""
309
+ SELECT {_SELECT_SQL}
310
  {JOIN_SQL}
311
  {where_sql}
312
  ORDER BY {sort_col} {order_sql} NULLS LAST
 
314
  """
315
  params.extend([limit, offset])
316
 
317
+ def _execute():
318
+ conn = _get_conn()
319
+ cur = conn.cursor()
320
+ try:
321
+ cur.execute(sql, params)
322
+ except sqlite3.OperationalError:
323
+ cur.execute(sql.replace("NULLS LAST", ""), params)
324
+ rows = [dict(r) for r in cur.fetchall()]
325
+ return rows
326
 
327
+ rows = await _run_sync(_execute)
 
328
 
329
+ payload = {
330
  "count": len(rows),
331
  "sort_by": sort_by,
332
  "order": order_sql,
333
  "filters": {
334
+ "language": language, "is_fork": is_fork, "archived": archived,
335
+ "disabled": disabled, "is_template": is_template, "status": status,
336
+ "min_stars": min_stars, "max_stars": max_stars, "search": search,
 
 
 
 
 
 
337
  },
338
  "results": rows,
339
  }
340
+ _set_cached(cache_key, payload)
341
+ return json_response(payload)
342
 
343
 
344
  @app.get("/api/languages")
345
+ async def languages():
346
+ cache_key = ("languages",)
347
+ cached = _get_cached(cache_key)
348
+ if cached is not None:
349
+ return json_response(cached)
350
+
351
+ def _execute():
352
+ conn = _get_conn()
353
+ cur = conn.cursor()
354
+ cur.execute("""
355
+ SELECT m.primary_language AS language, COUNT(*) AS count
356
+ FROM metadata m
357
+ WHERE m.primary_language IS NOT NULL AND m.primary_language != ''
358
+ GROUP BY m.primary_language
359
+ ORDER BY count DESC
360
+ """)
361
+ return {"languages": [{"language": r[0], "count": r[1]} for r in cur.fetchall()]}
362
+
363
+ data = await _run_sync(_execute)
364
+ _set_cached(cache_key, data)
365
+ return json_response(data)
366
 
367
 
368
  @app.get("/api/stats")
369
+ async def stats():
370
+ cache_key = ("stats",)
371
+ cached = _get_cached(cache_key)
372
+ if cached is not None:
373
+ return json_response(cached)
374
+
375
+ def _execute():
376
+ conn = _get_conn()
377
+ cur = conn.cursor()
378
+ cur.execute("SELECT COUNT(*) FROM repo_ids")
379
+ total_repos = cur.fetchone()[0]
380
+ cur.execute("SELECT COUNT(*) FROM metadata")
381
+ total_metadata = cur.fetchone()[0]
382
+ cur.execute("SELECT COUNT(*) FROM metadata WHERE is_fork = 1")
383
+ forks = cur.fetchone()[0]
384
+ cur.execute("SELECT COUNT(*) FROM metadata WHERE archived = 1")
385
+ archived = cur.fetchone()[0]
386
+ return {
387
+ "total_repos": total_repos,
388
+ "total_metadata_rows": total_metadata,
389
+ "forks": forks,
390
+ "archived": archived,
391
+ }
392
+
393
+ data = await _run_sync(_execute)
394
+ _set_cached(cache_key, data)
395
+ return json_response(data)
396
 
397
 
398
  @app.post("/api/refresh")
399
+ async def refresh():
400
+ async with _async_lock:
401
+ try:
402
+ await _run_sync(_refresh_db_sync)
403
+ return {"status": "ok", "state": _status["state"]}
404
+ except Exception as e:
405
+ _status["state"] = f"error: {e}"
406
+ raise HTTPException(500, str(e))
 
407
 
408
 
409
  @app.post("/api/push")
410
+ async def push():
 
411
  try:
412
+ await _run_sync(_push_db_sync)
413
  return {"status": "ok"}
414
  except Exception as e:
415
  raise HTTPException(500, str(e))