Spaces:
Running
Running
Download server/hub_sync.py from bevisssssss/driver: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/spaces/bevisssssss/driver/resolve/main/server/hub_sync.py
- Command line
-
hf download hf://spaces/bevisssssss/driver/server/hub_sync.py
-
curl -L -o hub_sync.py https://huggingface.co/spaces/bevisssssss/driver/resolve/main/server/hub_sync.py
6.66 kB
| """Persist the SQLite DB to Hugging Face Hub across deployments/restarts. | |
| Primary target is a **dataset** repo (`HF_DB_REPO`), not the Space repo: | |
| uploading into the Space repo would trigger a rebuild on every commit and the | |
| runtime data would be baked into the image. A dataset stays independent, so | |
| writes are cheap and the Space never restarts because of them. | |
| Uploads are coalesced: a burst of writes (index sync issues ~150) results in a | |
| single upload a few seconds later. | |
| """ | |
| import os | |
| import time | |
| import logging | |
| import threading | |
| logger = logging.getLogger(__name__) | |
| _SPACE_ID = os.getenv("SPACE_ID") or os.getenv("HF_SPACE_ID") | |
| _DB_REPO = os.getenv("HF_DB_REPO", "").strip() | |
| _HF_TOKEN = os.getenv("HF_TOKEN", "").strip() | |
| _REPO_ID = _DB_REPO or _SPACE_ID or "" | |
| _REPO_TYPE = "dataset" if _DB_REPO else "space" | |
| _FILENAME = "drivers.db" | |
| _SEED_FILENAME = os.getenv("HF_DB_SEED_FILE", "seed.db") | |
| _COALESCE_SECONDS = float(os.getenv("HF_DB_SYNC_DELAY", "5")) | |
| _last_sync_time: float = 0.0 | |
| _last_sync_ok: bool = False | |
| _last_sync_error: str = "" | |
| _sync_lock = threading.Lock() | |
| _upload_lock = threading.Lock() | |
| _dirty = threading.Event() | |
| _worker: threading.Thread | None = None | |
| _local_path: str = "" | |
| def _enabled() -> bool: | |
| return bool(_HF_TOKEN and _REPO_ID) | |
| def _hub_error_text(exc: Exception) -> str: | |
| try: | |
| from huggingface_hub.errors import HfHubHTTPError | |
| if isinstance(exc, HfHubHTTPError): | |
| return f"HTTP {exc.response.status_code}: {str(exc)[:200]}" | |
| except Exception: | |
| pass | |
| return str(exc)[:300] | |
| def _fetch(filename: str, force: bool = False) -> str: | |
| from huggingface_hub import hf_hub_download | |
| return hf_hub_download( | |
| repo_id=_REPO_ID, | |
| filename=filename, | |
| repo_type=_REPO_TYPE, | |
| token=_HF_TOKEN, | |
| force_download=force, | |
| ) | |
| def _delete_from_repo(filename: str) -> bool: | |
| try: | |
| from huggingface_hub import HfApi | |
| HfApi(token=_HF_TOKEN).delete_file( | |
| path_in_repo=filename, | |
| repo_id=_REPO_ID, | |
| repo_type=_REPO_TYPE, | |
| commit_message=f"consume {filename}", | |
| ) | |
| logger.info("%s removed from Hub after seeding", filename) | |
| return True | |
| except Exception as e: | |
| logger.warning("Could not delete %s from Hub: %s", filename, _hub_error_text(e)) | |
| return False | |
| def download_db(local_path: str) -> bool: | |
| """Restore drivers.db from the Hub at startup. | |
| A one-shot `seed.db` wins over `drivers.db`. The seed is uploaded while the | |
| Space is still running its old code; the live container keeps rewriting | |
| drivers.db, so a plain overwrite would be lost within seconds. | |
| """ | |
| if not _enabled(): | |
| logger.info("Hub sync skipped: HF_TOKEN/HF_DB_REPO not set") | |
| return False | |
| for name, force in ((_SEED_FILENAME, True), (_FILENAME, False)): | |
| try: | |
| cached = _fetch(name, force=force) | |
| except Exception as e: | |
| text = _hub_error_text(e) | |
| if "404" in text or "EntryNotFound" in text: | |
| continue | |
| logger.warning("DB download of %s failed: %s", name, text) | |
| continue | |
| try: | |
| os.makedirs(os.path.dirname(local_path) or ".", exist_ok=True) | |
| with open(cached, "rb") as src, open(local_path, "wb") as dst: | |
| dst.write(src.read()) | |
| logger.info( | |
| "DB restored from Hub (%s, %d bytes)", name, os.path.getsize(local_path) | |
| ) | |
| if name == _SEED_FILENAME: | |
| _delete_from_repo(_SEED_FILENAME) | |
| return True | |
| except Exception as e: | |
| logger.warning("DB restore from %s failed: %s", name, e) | |
| continue | |
| logger.info("No existing DB on Hub (first deploy)") | |
| return False | |
| def upload_db(local_path: str) -> bool: | |
| """Upload drivers.db to the Hub. Returns True on success.""" | |
| global _last_sync_time, _last_sync_ok, _last_sync_error | |
| if not _enabled(): | |
| return False | |
| if not os.path.exists(local_path) or not os.path.getsize(local_path): | |
| return False | |
| with _sync_lock: | |
| if _upload_lock.locked(): | |
| return False | |
| _upload_lock.acquire() | |
| try: | |
| from huggingface_hub import HfApi | |
| HfApi(token=_HF_TOKEN).upload_file( | |
| path_or_fileobj=local_path, | |
| path_in_repo=_FILENAME, | |
| repo_id=_REPO_ID, | |
| repo_type=_REPO_TYPE, | |
| commit_message="sync drivers.db", | |
| ) | |
| with _sync_lock: | |
| _last_sync_time = time.time() | |
| _last_sync_ok = True | |
| _last_sync_error = "" | |
| logger.info("DB synced to Hub (%d bytes)", os.path.getsize(local_path)) | |
| return True | |
| except Exception as e: | |
| text = _hub_error_text(e) | |
| with _sync_lock: | |
| _last_sync_time = time.time() | |
| _last_sync_ok = False | |
| _last_sync_error = text | |
| logger.warning("DB upload failed: %s", text) | |
| return False | |
| finally: | |
| _upload_lock.release() | |
| def _worker_loop(): | |
| while True: | |
| _dirty.wait() | |
| time.sleep(_COALESCE_SECONDS) | |
| _dirty.clear() | |
| upload_db(_local_path) | |
| def mark_dirty(): | |
| """Schedule an upload; bursts are coalesced into one.""" | |
| if not _enabled() or not _local_path: | |
| return | |
| _dirty.set() | |
| def sync_now() -> dict: | |
| """Synchronous upload — returns result dict.""" | |
| if _enabled() and _local_path: | |
| upload_db(_local_path) | |
| return get_status() | |
| def start(local_path: str): | |
| """Start the background upload worker.""" | |
| global _local_path, _worker | |
| _local_path = local_path | |
| if not _enabled(): | |
| logger.info("Hub sync inactive — HF_TOKEN/HF_DB_REPO not set") | |
| return | |
| if _worker and _worker.is_alive(): | |
| return | |
| _worker = threading.Thread(target=_worker_loop, daemon=True, name="hub-sync") | |
| _worker.start() | |
| logger.info( | |
| "Hub sync active — repo=%s type=%s (coalesce %.0fs)", | |
| _REPO_ID, _REPO_TYPE, _COALESCE_SECONDS, | |
| ) | |
| def stop(): | |
| """Flush pending state before shutdown.""" | |
| if _dirty.is_set() and _enabled() and _local_path: | |
| _dirty.clear() | |
| upload_db(_local_path) | |
| def get_status() -> dict: | |
| with _sync_lock: | |
| return { | |
| "enabled": _enabled(), | |
| "repo_id": _REPO_ID, | |
| "space_id": _REPO_ID, | |
| "repo_type": _REPO_TYPE, | |
| "token_set": bool(_HF_TOKEN), | |
| "last_sync_time": _last_sync_time, | |
| "last_sync_ok": _last_sync_ok, | |
| "last_sync_error": _last_sync_error, | |
| } | |