File size: 6,400 Bytes
fb6a24f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env bash
# Stage the deploy bundle under search/_deploy/ and (optionally) push to HF.
#
# Usage:
#   ./deploy.sh stage              # just prep the bundle for inspection
#   ./deploy.sh push <user>/<repo> # stage + create-if-missing + upload
#
# After `push` the Space rebuilds itself.

set -euo pipefail
cd "$(dirname "$0")"

STAGE=_deploy
SRC_AVATARS="../gamer2/static/user_avatar"
SRC_EMOJIS="../gamer2/static/gamer/forum_images"

# Color helpers (used by the push pipeline's final report).
red()    { printf '\033[31m%s\033[0m\n' "$*"; }
green()  { printf '\033[32m%s\033[0m\n' "$*"; }
yellow() { printf '\033[33m%s\033[0m\n' "$*"; }

stage() {
  echo "→ Staging $STAGE/"
  rm -rf "$STAGE"
  mkdir -p "$STAGE"

  # App
  cp server.py            "$STAGE/"
  cp requirements.txt     "$STAGE/"
  cp Dockerfile           "$STAGE/"
  cp README.md            "$STAGE/"
  cp -R static            "$STAGE/static"

  # Data — posts.db lives in a separate dataset repo (Space free-tier is
  # capped at 1 GB; the Dockerfile pulls posts.db from the dataset at
  # image-build time). Only the small static assets ride along.
  cp -R "$SRC_AVATARS"    "$STAGE/avatars"
  cp -R "$SRC_EMOJIS"     "$STAGE/forum_emojis"

  # Sanity
  echo
  echo "→ Bundle contents:"
  du -sh "$STAGE"/* | sort -h
  echo
  echo "→ Total bundle size:"
  du -sh "$STAGE"
}

push() {
  local repo="$1"
  : "${HF_TOKEN:?Set HF_TOKEN env var or `source search/.env`}"

  # Gate: refuse to push if smoke tests fail. predeploy.sh chmods posts.db
  # to 0444 (true read-only), boots a test server on port 8799, and hits
  # every endpoint — catches the "works on dev, breaks in prod" class
  # of bug (PRAGMA writes on RO mounts, WAL lock files, etc) that has
  # bitten us twice. Skip with PREDEPLOY_SKIP=1 only when truly needed.
  if [ "${PREDEPLOY_SKIP:-}" != "1" ]; then
    echo "→ Running predeploy smoke tests…"
    if ! "$(dirname "$0")/predeploy.sh"; then
      echo
      echo "✗ Predeploy gate FAILED — push aborted."
      echo "  Set PREDEPLOY_SKIP=1 to override (only when you really know)."
      exit 1
    fi
    echo
  else
    echo "→ Skipping predeploy gate (PREDEPLOY_SKIP=1)"
  fi

  stage

  echo "→ Creating Space if it doesn't exist: $repo"
  hf repos create "$repo" --type space --space-sdk docker --exist-ok

  # `hf upload-large-folder` has a bug where it always calls create_repo
  # without space_sdk, even when --type space is passed and the Space
  # already exists. Use plain `hf upload` instead; our slim bundle is
  # ~37MB so chunked uploads aren't needed. The big posts.db lives in
  # a dataset repo and is fetched at image-build time.
  local commit_msg="${COMMIT_MSG:-deploy}"
  local last_known_sha
  last_known_sha=$(
    curl -s -H "Authorization: Bearer $HF_TOKEN" \
      "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \
      | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])" 2>/dev/null \
      || echo ""
  )

  # Retry the upload up to 3× on HF flake (their commit API 500s
  # intermittently). After each attempt — failure or otherwise —
  # check the git log to see if the commit actually landed; sometimes
  # the client gets a 500 but the server-side commit succeeded, and
  # blindly retrying creates a no-op (or wastes time).
  local attempt
  local success=0
  for attempt in 1 2 3; do
    echo "→ Uploading bundle (attempt $attempt/3)…"
    if hf upload "$repo" "$STAGE" . --type space --commit-message "$commit_msg"; then
      success=1
      break
    fi
    echo "  upload exit was non-zero — checking if the commit actually landed…"
    sleep 3
    local current_sha
    current_sha=$(
      curl -s -H "Authorization: Bearer $HF_TOKEN" \
        "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \
        | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])" 2>/dev/null \
        || echo ""
    )
    if [ -n "$current_sha" ] && [ "$current_sha" != "$last_known_sha" ]; then
      echo "  commit landed despite client error: $current_sha"
      success=1
      break
    fi
    if [ "$attempt" -lt 3 ]; then
      local wait=$((attempt * 10))
      echo "  no new commit — retrying in ${wait}s…"
      sleep "$wait"
    fi
  done

  if [ "$success" -ne 1 ]; then
    red "✗ Upload failed after 3 attempts."
    echo "  Check https://status.huggingface.co/ — their commit API"
    echo "  has intermittent 5xx episodes."
    exit 1
  fi

  # Confirm the new commit and wait for HF to actually serve it.
  local new_sha
  new_sha=$(
    curl -s -H "Authorization: Bearer $HF_TOKEN" \
      "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \
      | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])"
  )
  echo "→ Latest commit: $new_sha"

  echo "→ Waiting for Space to build + serve this sha (timeout 12 min)…"
  local space_host="${repo//\//-}.hf.space"
  local deadline=$(( $(date +%s) + 720 ))
  local last_stage=""
  while [ "$(date +%s)" -lt "$deadline" ]; do
    local info_json
    info_json=$(curl -s -H "Authorization: Bearer $HF_TOKEN" \
      "https://huggingface.co/api/spaces/$repo" 2>/dev/null)
    local live_sha stage
    live_sha=$(echo "$info_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('sha',''))" 2>/dev/null || echo "")
    stage=$(echo "$info_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('runtime',{}).get('stage',''))" 2>/dev/null || echo "")
    if [ "$stage" != "$last_stage" ]; then
      echo "  stage: $stage  sha: ${live_sha:0:12}"
      last_stage="$stage"
    fi
    if [ "$stage" = "RUNNING" ] && [ "$live_sha" = "$new_sha" ]; then
      # Final liveness check: hit /api/stats and confirm JSON
      if curl -fs -m 10 "https://$space_host/api/stats" >/dev/null 2>&1; then
        green "✓ Live: https://$space_host  (sha ${new_sha:0:12})"
        return 0
      fi
      echo "  stage RUNNING but /api/stats not answering yet — waiting…"
    fi
    sleep 10
  done

  red "✗ Timed out waiting for Space to flip to RUNNING on the new sha."
  echo "  Build may still finish — check 'hf spaces info $repo' and runtime logs."
  exit 1
}

case "${1:-}" in
  stage)        stage ;;
  push)         shift; push "${1:?Usage: ./deploy.sh push <user>/<repo>}" ;;
  *)            echo "Usage: $0 stage | push <user>/<repo>"; exit 1 ;;
esac