Spaces:
Sleeping

File size: 7,611 Bytes
69d639b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Final stage of the daily refresh: export Postgres β†’ SQLite β†’ gzip β†’ push
to the HF Space, and write a small status file the dashboard can surface.

This runs inside `scripts/daily_refresh.sh` (which has already loaded the
shell PATH and exported HF_TOKEN + DATABASE_URL).
"""

from __future__ import annotations

import gzip
import io
import json
import os
import shutil
import sqlite3
import subprocess
import sys
from datetime import UTC, datetime
from pathlib import Path

from huggingface_hub import CommitOperationAdd, HfApi

REPO = Path(__file__).resolve().parent.parent
SQLITE_PATH = REPO / "tracker_local.sqlite"
SEED_PATH = REPO / "tracker_seed.dat"
STATUS_PATH = REPO / "data" / "last_refresh.json"
HF_REPO = "fti-opportunity-tracker/app"

# Every push stores a new ~50 MB LFS blob for the seed. Superseded blobs keep
# counting against the Space's 1 GB repo cap until the history is squashed and
# HF garbage-collects them, so without this the push eventually 403s with
# "Repository storage limit reached" and the deployed data silently goes stale.
# Squash well below the cap: GC is not immediate (~100 min observed), so the
# remaining headroom has to cover several days of pushes in the meantime.
SQUASH_THRESHOLD_BYTES = 700_000_000


def export_postgres_to_sqlite() -> None:
    subprocess.run(
        ["uv", "run", "python", "scripts/export_to_sqlite.py"],
        cwd=REPO,
        check=True,
    )


def gzip_to_seed() -> None:
    if SEED_PATH.exists():
        SEED_PATH.unlink()
    # gzip in chunks to a temp path, then move.
    tmp = SEED_PATH.with_suffix(".dat.tmp")
    with SQLITE_PATH.open("rb") as src, gzip.open(tmp, "wb", compresslevel=9) as dst:
        shutil.copyfileobj(src, dst, length=1 << 20)
    tmp.replace(SEED_PATH)


def _hf_gitignore_without_seed() -> bytes:
    """Local .gitignore content with tracker_seed.dat removed.

    The local git repo ignores tracker_seed.dat (large binary, regenerated
    daily). But the HF Space git repo must track it for the Docker build.
    When create_commit finds a .gitignore in the operations it uses that
    content for the ignore check β€” so we include it here to allow the seed
    upload to go through.
    """
    lines = (REPO / ".gitignore").read_text().splitlines()
    filtered = [l for l in lines if l.strip() != "tracker_seed.dat"]
    return "\n".join(filtered).encode()


def push_to_hf(token: str) -> str:
    """Push the seed to HF Space. Retries up to 5 times on transient errors
    (DNS hiccups, closed-client, brief HF 5xx β€” all observed in the wild).

    Commits .gitignore alongside tracker_seed.dat so create_commit uses the
    included gitignore (which omits tracker_seed.dat) rather than the
    server-side .gitignore that blocks the upload.
    """
    import time

    last_exc: Exception | None = None
    hf_gitignore = _hf_gitignore_without_seed()
    for attempt in range(5):
        try:
            # Construct a fresh HfApi each attempt so a previous closed-client
            # doesn't poison the next try.
            api = HfApi(token=token)
            commit = api.create_commit(
                repo_id=HF_REPO,
                repo_type="space",
                operations=[
                    CommitOperationAdd(
                        path_in_repo=".gitignore",
                        path_or_fileobj=io.BytesIO(hf_gitignore),
                    ),
                    CommitOperationAdd(
                        path_in_repo="tracker_seed.dat",
                        path_or_fileobj=str(SEED_PATH),
                    ),
                ],
                commit_message=(
                    f"Daily refresh {datetime.now(UTC).strftime('%Y-%m-%d %H:%M UTC')}"
                ),
            )
            return str(commit).rsplit("/", 1)[-1]
        except Exception as exc:
            last_exc = exc
            wait_s = 5 + attempt * 10  # 5, 15, 25, 35, 45
            print(
                f"HF push attempt {attempt + 1}/5 failed: "
                f"{type(exc).__name__}: {exc}; retrying in {wait_s}s",
                flush=True,
            )
            time.sleep(wait_s)
    raise RuntimeError(f"HF push failed after 5 retries: {last_exc}") from last_exc


def reclaim_storage_if_needed(token: str) -> dict | None:
    """Squash the Space's git history when stored bytes approach the repo cap.

    Squashing makes every superseded seed blob unreferenced; HF's GC then
    reclaims them. Never fatal β€” if the check or the squash fails we still
    attempt the push, which is what actually matters.
    """
    try:
        api = HfApi(token=token)
        info = api.repo_info(HF_REPO, repo_type="space", expand=["usedStorage"])
        used = getattr(info, "used_storage", None)
        if used is None:
            print("storage: usedStorage unavailable β€” skipping squash", flush=True)
            return None
        if used < SQUASH_THRESHOLD_BYTES:
            print(f"storage: {used / 1e6:.0f} MB used β€” below squash threshold", flush=True)
            return {"used_bytes": used, "squashed": False}
        print(f"storage: {used / 1e6:.0f} MB used β€” squashing history", flush=True)
        api.super_squash_history(repo_id=HF_REPO, repo_type="space", branch="main")
        return {"used_bytes": used, "squashed": True}
    except Exception as exc:  # noqa: BLE001
        print(f"storage: squash check failed ({exc}) β€” continuing to push", flush=True)
        return {"error": f"{type(exc).__name__}: {exc}"}


def db_counts() -> dict[str, int]:
    out: dict[str, int] = {}
    with sqlite3.connect(SQLITE_PATH) as conn:
        cur = conn.cursor()
        out["opps"] = cur.execute("SELECT COUNT(*) FROM opportunities").fetchone()[0]
        out["enriched"] = cur.execute(
            "SELECT COUNT(*) FROM opportunities WHERE ai_enrichment_at IS NOT NULL"
        ).fetchone()[0]
        out["consulting"] = cur.execute(
            "SELECT COUNT(*) FROM opportunities WHERE is_consulting=1"
        ).fetchone()[0]
        out["non_consulting"] = cur.execute(
            "SELECT COUNT(*) FROM opportunities WHERE is_consulting=0"
        ).fetchone()[0]
        out["open_opps"] = cur.execute(
            "SELECT COUNT(*) FROM opportunities "
            "WHERE closing_date IS NULL OR closing_date >= date('now')"
        ).fetchone()[0]
    return out


def write_status(payload: dict) -> None:
    STATUS_PATH.parent.mkdir(parents=True, exist_ok=True)
    STATUS_PATH.write_text(json.dumps(payload, indent=2, default=str))


def main() -> int:
    payload: dict = {
        "started_at": datetime.now(UTC).isoformat(),
        "status": "running",
    }
    try:
        export_postgres_to_sqlite()
        payload.update(db_counts())
        gzip_to_seed()
        payload["seed_bytes"] = SEED_PATH.stat().st_size
        token = os.environ.get("HF_TOKEN")
        if not token:
            raise RuntimeError("HF_TOKEN missing β€” refusing to skip the push silently")
        payload["storage"] = reclaim_storage_if_needed(token)
        payload["push_commit_sha"] = push_to_hf(token)
        payload["status"] = "ok"
    except Exception as exc:
        payload["status"] = "failed"
        payload["error"] = f"{type(exc).__name__}: {exc}"
        payload["finished_at"] = datetime.now(UTC).isoformat()
        write_status(payload)
        print(json.dumps(payload, indent=2, default=str))
        return 1
    payload["finished_at"] = datetime.now(UTC).isoformat()
    write_status(payload)
    print(json.dumps(payload, indent=2, default=str))
    return 0


if __name__ == "__main__":
    sys.exit(main())