File size: 3,942 Bytes
c6262df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
HF Storage Bucket persistence (decision D9).

Pattern: SQLite lives on the Space's fast local disk (reliable locking); this
module mirrors it to an HF Storage Bucket so state survives restart/sleep.

  • restore_on_boot() — sync the DB snapshot from the bucket into DB_PATH before
                        the app opens the DB. No bucket/snapshot → no-op (fresh).
  • sync_worker()     — periodically push the DB to the bucket, and once more on
                        shutdown, so a reboot resumes from the last state.

Config (env): HF_TOKEN (write secret) + CRE_BUCKET ('owner/bucket-name'). If either
is missing, persistence is disabled and CRE runs ephemerally (still fully works).

Uses huggingface_hub `sync_bucket` (rsync-style, dir↔dir over hf:// paths). The DB
is staged in a dedicated dir so we never sync unrelated files; WAL is checkpointed
before each push so the single .db file is self-contained.
"""
from __future__ import annotations
import asyncio
import os
import shutil
import sqlite3
import time

import config

HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
CRE_BUCKET = os.getenv("CRE_BUCKET", "").strip()       # 'owner/bucket-name'
ENABLED = bool(HF_TOKEN and CRE_BUCKET)
SYNC_INTERVAL_SEC = int(os.getenv("CRE_SYNC_INTERVAL_SEC", "300"))

_STAGE_DIR = os.getenv("CRE_STAGE_DIR", "./.cre_sync")
_DB_NAME = "cre.db"
_REMOTE = f"hf://buckets/{CRE_BUCKET}/cre" if CRE_BUCKET else ""


def _checkpoint() -> None:
    """Fold the WAL back into the main .db file so the snapshot is complete."""
    try:
        c = sqlite3.connect(config.DB_PATH)
        c.execute("PRAGMA wal_checkpoint(TRUNCATE);")
        c.close()
    except Exception as e:
        print(f"[sync] checkpoint warning: {type(e).__name__}: {e}", flush=True)


def restore_on_boot() -> bool:
    """Sync the DB snapshot from the bucket into DB_PATH. Returns True if a
    snapshot was restored. Call BEFORE store.db.init()."""
    if not ENABLED:
        print("[sync] persistence disabled (no HF_TOKEN/CRE_BUCKET) — ephemeral mode", flush=True)
        return False
    try:
        from huggingface_hub import sync_bucket
        os.makedirs(_STAGE_DIR, exist_ok=True)
        sync_bucket(_REMOTE, _STAGE_DIR, token=HF_TOKEN)
        staged = os.path.join(_STAGE_DIR, _DB_NAME)
        if os.path.exists(staged):
            os.makedirs(os.path.dirname(config.DB_PATH) or ".", exist_ok=True)
            shutil.copyfile(staged, config.DB_PATH)
            print("[sync] restored DB snapshot from bucket", flush=True)
            return True
        print("[sync] bucket has no snapshot yet — fresh start", flush=True)
        return False
    except Exception as e:
        print(f"[sync] restore skipped ({type(e).__name__}: {e}) — fresh start", flush=True)
        return False


def push() -> bool:
    """Upload the current DB to the bucket (rsync, only if changed). True on success."""
    if not ENABLED or not os.path.exists(config.DB_PATH):
        return False
    try:
        from huggingface_hub import sync_bucket
        _checkpoint()
        os.makedirs(_STAGE_DIR, exist_ok=True)
        shutil.copyfile(config.DB_PATH, os.path.join(_STAGE_DIR, _DB_NAME))
        sync_bucket(_STAGE_DIR, _REMOTE, token=HF_TOKEN)
        return True
    except Exception as e:
        print(f"[sync] push failed: {type(e).__name__}: {e}", flush=True)
        return False


async def sync_worker(stop: asyncio.Event) -> None:
    """Periodically push the DB to the bucket; final push on shutdown."""
    if not ENABLED:
        return
    while not stop.is_set():
        try:
            await asyncio.wait_for(stop.wait(), timeout=SYNC_INTERVAL_SEC)
        except asyncio.TimeoutError:
            pass
        if await asyncio.to_thread(push):
            print(f"[sync] DB pushed to bucket @ {int(time.time())}", flush=True)
    await asyncio.to_thread(push)
    print("[sync] final DB snapshot pushed on shutdown", flush=True)