Spaces:
Paused
Paused
OpenCode Bot commited on
Commit ·
90dd1f4
1
Parent(s): a48c907
Update sync_auths.py: use auth_store table, multipart upload API
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Bidirectional auth file sync between HF Space and PostgreSQL (Aiven).Modes:backup - HF → PG: Read auth files from HF Space, upsert to auth_storerestore - PG → HF: Push auth files from auth_store to HF Spacesync - backup + restore (if HF empty) + delete stale PG recordscleanup - Delete PG records that no longer exist on HFRuns as GitHub Actions cron every 10 minutes (sync) and 15 minutes (cleanup)."""import os, sys, json, requestsimport psycopg2REPO_ID = "mansui52001/grok2api"HF_TOKEN = os.environ["HF_TOKEN"]PGSTORE_DSN = os.environ.get("PGSTORE_DSN", "")MANAGEMENT_PASSWORD = os.environ.get("REMOTE_MGMT_KEY", "")SPACE_URL = "https://mansui52001-grok2api.hf.space"# PG table used by CLIProxyAPI itselfTABLE = "auth_store"def get_pg_conn():if not PGSTORE_DSN:print("ERROR: PGSTORE_DSN not set")sys.exit(1)return psycopg2.connect(PGSTORE_DSN)def get_hf_auth_files():"""List and read all auth files from HF Space via Management API."""headers = {"Authorization": f"Bearer {MANAGEMENT_PASSWORD}","X-Management-Key": MANAGEMENT_PASSWORD,}try:r = requests.get(f"{SPACE_URL}/v0/management/auth-files", headers=headers, timeout=30)if r.status_code != 200:print(f"List auth files failed: {r.status_code} {r.text[:200]}")return {}data = r.json()file_list = data.get("files", [])except Exception as e:print(f"List auth files error: {e}")return {}auth_files = {}for f in file_list:name = f.get("name", f.get("id", ""))if not name:continuetry:r2 = requests.get(f"{SPACE_URL}/v0/management/auth-files/{name}",headers=headers, timeout=30)if r2.status_code == 200:auth_files[name] = r2.json()else:print(f" Read {name} failed: {r2.status_code}")except Exception as e:print(f" Read {name} error: {e}")return auth_filesdef backup_to_pg(conn, auth_files):"""Upsert auth files to PG auth_store table."""if not auth_files:print("No auth files on HF, skipping backup")returnwith conn.cursor() as cur:for name, content in auth_files.items():content_json = json.dumps(content)cur.execute(f"""INSERT INTO {TABLE} (id, content, updated_at)VALUES (%s, %s, NOW())ON CONFLICT (id)DO UPDATE SET content = EXCLUDED.content, updated_at = NOW()""", (name, content_json))conn.commit()print(f"Backed up {len(auth_files)} auth files to PG ({TABLE})")def delete_stale_from_pg(conn, hf_filenames):"""Delete PG records that no longer exist on HF."""if not hf_filenames:print("HF has 0 auth files, skipping PG cleanup to avoid accidental data loss")returnwith conn.cursor() as cur:cur.execute(f"SELECT id FROM {TABLE}")pg_filenames = {row[0] for row in cur.fetchall()}stale = pg_filenames - set(hf_filenames)if stale:with conn.cursor() as cur:cur.execute(f"DELETE FROM {TABLE} WHERE id = ANY(%s)", (list(stale),))conn.commit()print(f"Deleted {len(stale)} stale records from PG: {stale}")else:print("No stale records in PG")def restore_from_pg(conn):"""Push auth files from PG auth_store to HF Space."""with conn.cursor() as cur:cur.execute(f"SELECT id, content FROM {TABLE}")pg_files = {row[0]: row[1] for row in cur.fetchall()}if not pg_files:print("PG has no auth files to restore")returnheaders = {"Authorization": f"Bearer {MANAGEMENT_PASSWORD}","X-Management-Key": MANAGEMENT_PASSWORD,}restored = 0for name, content in pg_files.items():content_str = json.dumps(content, indent=2) if isinstance(content, dict) else str(content)files = {"file": (name, content_str, "application/json")}try:r = requests.post(f"{SPACE_URL}/v0/management/auth-files",headers=headers, files=files, timeout=30,)if r.status_code == 200:restored += 1else:print(f" Restore {name} failed: {r.status_code} {r.text[:200]}")except Exception as e:print(f" Restore {name} error: {e}")print(f"Restored {restored}/{len(pg_files)} auth files from PG to HF")def delete_hf_auth_file(name):"""Delete an auth file from HF Space."""headers = {"Authorization": f"Bearer {MANAGEMENT_PASSWORD}","X-Management-Key": MANAGEMENT_PASSWORD,}try:r = requests.delete(f"{SPACE_URL}/v0/management/auth-files",headers=headers, json={"name": name}, timeout=30,)return r.status_code == 200except Exception as e:print(f" Delete {name} error: {e}")return Falsedef cleanup_stale(conn):"""Delete PG records that no longer exist on HF (cleanup mode)."""hf_auth_files = get_hf_auth_files()print(f"HF Space has {len(hf_auth_files)} auth files")if not hf_auth_files:print("HF has 0 auth files, skipping cleanup to avoid accidental data loss")returndelete_stale_from_pg(conn, set(hf_auth_files.keys()))# Also check for stale files on HF that are not in PGwith conn.cursor() as cur:cur.execute(f"SELECT id FROM {TABLE}")pg_filenames = {row[0] for row in cur.fetchall()}stale_hf = set(hf_auth_files.keys()) - pg_filenamesif stale_hf:print(f"Found {len(stale_hf)} stale files on HF not in PG: {stale_hf}")for name in stale_hf:if delete_hf_auth_file(name):print(f" Deleted {name} from HF")else:print(f" Failed to delete {name} from HF")else:print("No stale files on HF")def main():mode = sys.argv[1] if len(sys.argv) > 1 else "sync"print(f"=== Auth Sync Mode: {mode} ===")conn = get_pg_conn()if mode in ("backup", "sync"):hf_auth_files = get_hf_auth_files()print(f"HF Space has {len(hf_auth_files)} auth files")backup_to_pg(conn, hf_auth_files)if mode in ("sync",):delete_stale_from_pg(conn, set(hf_auth_files.keys()))if mode in ("restore", "sync"):if mode == "restore":hf_auth_files = get_hf_auth_files()if len(hf_auth_files) == 0:print("HF has no auth files - restoring from PG...")restore_from_pg(conn)else:print(f"HF has {len(hf_auth_files)} files, no restore needed")if mode == "cleanup":cleanup_stale(conn)conn.close()print("=== Sync Complete ===")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Bidirectional auth file sync between HF Space and PostgreSQL (Aiven).Uses the 'auth_store' table (columns: id TEXT, content JSONB, created_at, updated_at).Modes:backup - HF -> PG: Read auth files from HF Space, upsert to PG auth_storerestore - PG -> HF: If HF has no auth files, push from PG auth_storesync - backup + restore + cleanup stale PG recordscleanup - Delete PG records that no longer exist on HFRuns as GitHub Actions cron (every 10 min for sync, every 15 min for cleanup).GitHub Actions can reach both HF Space API and Aiven PG; HF Space cannot reach Aiven."""import os, sys, json, requestsimport psycopg2SPACE_URL = "https://mansui52001-grok2api.hf.space"HF_TOKEN = os.environ.get("HF_TOKEN", "")PGSTORE_DSN = os.environ.get("PGSTORE_DSN", "")MGMT_PWD = os.environ.get("REMOTE_MGMT_KEY", "")TABLE = "auth_store"def get_pg_conn():if not PGSTORE_DSN:print("ERROR: PGSTORE_DSN not set")sys.exit(1)return psycopg2.connect(PGSTORE_DSN)def mgmt_headers():return {"Authorization": f"Bearer {MGMT_PWD}","X-Management-Key": MGMT_PWD,}def get_hf_auth_files():"""List all auth file names from HF Space via Management API."""headers = mgmt_headers()try:r = requests.get(f"{SPACE_URL}/v0/management/auth-files", headers=headers, timeout=30)if r.status_code != 200:print(f"List auth files failed: {r.status_code} {r.text[:200]}")return []data = r.json()files = data.get("files", [])names = [f.get("name", f.get("id", "")) for f in files]return [n for n in names if n]except Exception as e:print(f"List auth files error: {e}")return []def read_hf_auth_file(name):"""Read a single auth file content from HF Space."""headers = mgmt_headers()try:r = requests.get(f"{SPACE_URL}/v0/management/auth-files/{name}", headers=headers, timeout=30)if r.status_code == 200:return r.textreturn Noneexcept Exception as e:print(f" Read {name} error: {e}")return Nonedef upload_hf_auth_file(name, content_str):"""Upload an auth file to HF Space via multipart POST."""headers = mgmt_headers()files = {"file": (name, content_str, "application/json")}try:r = requests.post(f"{SPACE_URL}/v0/management/auth-files", headers=headers, files=files, timeout=30)return r.status_code == 200except Exception as e:print(f" Upload {name} error: {e}")return Falsedef delete_hf_auth_file(name):"""Delete an auth file from HF Space."""headers = mgmt_headers()try:r = requests.delete(f"{SPACE_URL}/v0/management/auth-files", headers=headers, json={"name": name}, timeout=30)return r.status_code == 200except Exception as e:print(f" Delete {name} error: {e}")return Falsedef backup_to_pg(conn):"""Read auth files from HF, upsert to PG auth_store."""hf_names = get_hf_auth_files()print(f"HF Space has {len(hf_names)} auth files")if not hf_names:print("No auth files on HF, skipping backup")return 0backed_up = 0with conn.cursor() as cur:for name in hf_names:content_str = read_hf_auth_file(name)if not content_str:continuetry:content_json = json.loads(content_str)except json.JSONDecodeError:print(f" {name}: invalid JSON, skipping")continuecur.execute(f"""INSERT INTO {TABLE} (id, content, updated_at)VALUES (%s, %s, NOW())ON CONFLICT (id)DO UPDATE SET content = EXCLUDED.content, updated_at = NOW()""",(name, json.dumps(content_json)),)backed_up += 1conn.commit()print(f"Backed up {backed_up} auth files to PG ({TABLE})")return backed_updef restore_from_pg(conn):"""Push auth files from PG to HF if HF has none."""hf_names = get_hf_auth_files()if hf_names:print(f"HF already has {len(hf_names)} files, no restore needed")return 0with conn.cursor() as cur:cur.execute(f"SELECT id, content FROM {TABLE}")rows = cur.fetchall()if not rows:print("PG has no auth files to restore")return 0print(f"Restoring {len(rows)} auth files from PG to HF...")restored = 0for name, content in rows:content_str = json.dumps(content, indent=2) if isinstance(content, dict) else str(content)if upload_hf_auth_file(name, content_str):restored += 1else:print(f" Failed to restore {name}")print(f"Restored {restored}/{len(rows)} auth files from PG to HF")return restoreddef cleanup_stale_pg(conn):"""Delete PG records that no longer exist on HF."""hf_names = set(get_hf_auth_files())print(f"HF Space has {len(hf_names)} auth files")if not hf_names:print("HF has 0 auth files, skipping cleanup to avoid accidental data loss")return 0with conn.cursor() as cur:cur.execute(f"SELECT id FROM {TABLE}")pg_names = {row[0] for row in cur.fetchall()}stale = pg_names - hf_namesif stale:with conn.cursor() as cur:cur.execute(f"DELETE FROM {TABLE} WHERE id = ANY(%s)", (list(stale),))conn.commit()print(f"Deleted {len(stale)} stale records from PG: {stale}")else:print("No stale records in PG")return len(stale)def main():mode = sys.argv[1] if len(sys.argv) > 1 else "sync"print(f"=== Auth Sync Mode: {mode} ===")print(f" PG table: {TABLE}")print(f" HF Space: {SPACE_URL}")conn = get_pg_conn()if mode in ("backup", "sync"):backup_to_pg(conn)if mode in ("sync",):cleanup_stale_pg(conn)if mode in ("restore", "sync"):restore_from_pg(conn)if mode == "cleanup":cleanup_stale_pg(conn)conn.close()print("=== Sync Complete ===")if __name__ == "__main__":main()
sync_auths.py+131-131