Spaces:
Running
Running
File size: 6,655 Bytes
79dca2e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | """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,
}
|