Spaces:
Paused
Paused
feat: replace setup-uptimerobot.sh with a modular cloudflare-keepalive-setup.py for automated health check pinging.
Browse filesFiles changed (7)
- CHANGELOG.md+1-1
- Dockerfile+2-2
- README.md+3-3
- cloudflare-keepalive-setup.pyAdded+212
- cloudflare-proxy-setup.py+1-131
- setup-uptimerobot.shDeleted-73
- start.sh+5-5
5 unmodified lines67895 unmodified lines- Added HF Space dashboard, `/health`, `/status`, `/v1/*` proxy, and Telegram webhook proxy.- Added Cloudflare Worker setup for Telegram Bot API base URL proxying.- Added private HF Dataset backup and restore for Hermes state.- Added UptimeRobot monitor setup.5 unmodified lines67895 unmodified lines- Added HF Space dashboard, `/health`, `/status`, `/v1/*` proxy, and Telegram webhook proxy.- Added Cloudflare Worker setup for Telegram Bot API base URL proxying.- Added private HF Dataset backup and restore for Hermes state.- Added Cloudflare Keepalive Worker setup for automatic space keep-awake.
15 unmodified lines1617181920212223242526272815 unmodified linesCOPY --chown=hermes:hermes health-server.js /opt/huggingmess/health-server.jsCOPY --chown=hermes:hermes hermes-sync.py /opt/huggingmess/hermes-sync.pyCOPY --chown=hermes:hermes cloudflare-proxy-setup.py /opt/huggingmess/cloudflare-proxy-setup.pyCOPY --chown=hermes:hermes setup-uptimerobot.sh /opt/huggingmess/setup-uptimerobot.shRUN chmod +x \/opt/huggingmess/start.sh \/opt/huggingmess/hermes-sync.py \/opt/huggingmess/cloudflare-proxy-setup.py \/opt/huggingmess/setup-uptimerobot.shENV HERMES_HOME=/opt/data \HUGGINGMESS_APP_DIR=/opt/huggingmess \15 unmodified lines1617181920212223242526272815 unmodified linesCOPY --chown=hermes:hermes health-server.js /opt/huggingmess/health-server.jsCOPY --chown=hermes:hermes hermes-sync.py /opt/huggingmess/hermes-sync.pyCOPY --chown=hermes:hermes cloudflare-proxy-setup.py /opt/huggingmess/cloudflare-proxy-setup.pyCOPY --chown=hermes:hermes cloudflare-keepalive-setup.py /opt/huggingmess/cloudflare-keepalive-setup.pyRUN chmod +x \/opt/huggingmess/start.sh \/opt/huggingmess/hermes-sync.py \/opt/huggingmess/cloudflare-proxy-setup.py \/opt/huggingmess/cloudflare-keepalive-setup.pyENV HERMES_HOME=/opt/data \HUGGINGMESS_APP_DIR=/opt/huggingmess \
141 unmodified lines14214314414514614714811 unmodified lines160161162163164165166167141 unmodified lines### Keep AwakeWhen `CLOUDFLARE_WORKERS_TOKEN` and `SPACE_HOST` are present, HuggingMess creates a scheduled Worker that pings:```texthttps://your-space.hf.space/health11 unmodified lines| :--- | :--- | :--- || `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set `false` to skip keep-awake Worker setup || `CLOUDFLARE_KEEPALIVE_CRON` | `*/10 * * * *` | Cloudflare cron expression || `CLOUDFLARE_KEEPALIVE_URL` | `https://<SPACE_HOST>/health` | URL to ping || `CLOUDFLARE_KEEPALIVE_WORKER_NAME` | derived from `SPACE_HOST` | Custom Worker name |## Backup141 unmodified lines14214314414514614714811 unmodified lines160161162163164165166167141 unmodified lines### Keep AwakeWhen `CLOUDFLARE_WORKERS_TOKEN` is present, HuggingMess creates a scheduled Worker that pings your Space's `/health` route. It automatically detects your Space hostname:```texthttps://your-space.hf.space/health11 unmodified lines| :--- | :--- | :--- || `CLOUDFLARE_KEEPALIVE_ENABLED` | `true` | Set `false` to skip keep-awake Worker setup || `CLOUDFLARE_KEEPALIVE_CRON` | `*/10 * * * *` | Cloudflare cron expression || `CLOUDFLARE_KEEPALIVE_URL` | `https://<auto-detected-space-host>/health` | URL to ping || `CLOUDFLARE_KEEPALIVE_WORKER_NAME` | derived from space host | Custom Worker name |## Backup
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212#!/usr/bin/env python3from __future__ import annotations
"""Create or reuse a Cloudflare Worker for Space keep-awake."""
import jsonimport osimport reimport sysimport timeimport urllib.requestfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"KEEPALIVE_STATUS_FILE = Path("/tmp/huggingmess-cloudflare-keepalive-status.json")
def cf_request(method: str, path: str, token: str, body: bytes | None = None, content_type: str = "application/json"): req = urllib.request.Request( f"{API_BASE}{path}", data=body, method=method, headers={"Authorization": f"Bearer {token}", "Content-Type": content_type}, ) with urllib.request.urlopen(req, timeout=30) as response: payload = json.loads(response.read().decode("utf-8")) if not payload.get("success"): errors = payload.get("errors") or [{"message": "Unknown Cloudflare API error"}] raise RuntimeError(errors[0].get("message", "Unknown Cloudflare API error")) return payload["result"]
def slugify(value: str) -> str: cleaned = re.sub(r"[^a-z0-9-]+", "-", value.lower()).strip("-") cleaned = re.sub(r"-{2,}", "-", cleaned) return (cleaned or "huggingmess-proxy")[:63].rstrip("-")
def get_space_host() -> str: space_host = os.environ.get("SPACE_HOST", "").strip() if space_host: return space_host author = os.environ.get("SPACE_AUTHOR_NAME", "").strip() repo = os.environ.get("SPACE_REPO_NAME", "").strip() if author and repo: return f"{author}-{repo}.hf.space".lower() return ""
def derive_keepalive_worker_name() -> str: explicit = os.environ.get("CLOUDFLARE_KEEPALIVE_WORKER_NAME", "").strip() if explicit: return slugify(explicit) space_host = get_space_host() if space_host: return slugify(f"{space_host.replace('.hf.space', '')}-keepalive") return "huggingmess-keepalive"
def render_keepalive_worker(target_url: str) -> str: return f"""addEventListener("fetch", (event) => {{ event.respondWith(handleRequest(event.request));}});
addEventListener("scheduled", (event) => {{ event.waitUntil(ping("cron"));}});
const TARGET_URL = {json.dumps(target_url)};
async function ping(source) {{ const startedAt = new Date().toISOString(); try {{ const response = await fetch(TARGET_URL, {{ method: "GET", headers: {{ "user-agent": "HuggingMess Cloudflare KeepAlive", "cache-control": "no-cache" }}, cf: {{ cacheTtl: 0, cacheEverything: false }} }}); return {{ ok: response.ok, status: response.status, source, target: TARGET_URL, timestamp: startedAt }}; }} catch (error) {{ return {{ ok: false, status: 0, source, target: TARGET_URL, timestamp: startedAt, error: error.message }}; }}}}
async function handleRequest(request) {{ const url = new URL(request.url); if (url.pathname === "/" || url.pathname === "/health" || url.pathname === "/ping") {{ const result = await ping("manual"); return new Response(JSON.stringify(result, null, 2), {{ status: result.ok ? 200 : 502, headers: {{ "content-type": "application/json; charset=utf-8" }} }}); }} return new Response("Not found", {{ status: 404 }});}}"""
def write_keepalive_status(payload: dict) -> None: payload = { **payload, "timestamp": payload.get("timestamp") or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } KEEPALIVE_STATUS_FILE.write_text(json.dumps(payload), encoding="utf-8") try: KEEPALIVE_STATUS_FILE.chmod(0o600) except OSError: pass
def resolve_account_and_subdomain(api_token: str) -> tuple[str, str]: account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip() if not account_id: accounts = cf_request("GET", "/accounts", api_token) if not accounts: raise RuntimeError("No Cloudflare account is available for this token.") account_id = accounts[0]["id"]
subdomain_info = cf_request("GET", f"/accounts/{account_id}/workers/subdomain", api_token) subdomain = (subdomain_info or {}).get("subdomain", "").strip() if not subdomain: raise RuntimeError("Cloudflare Workers subdomain is not configured. Enable workers.dev first.") return account_id, subdomain
def setup_keepalive_worker(api_token: str, account_id: str, subdomain: str) -> None: enabled = os.environ.get("CLOUDFLARE_KEEPALIVE_ENABLED", "true").strip().lower() if enabled in {"0", "false", "no", "off"}: write_keepalive_status({"configured": False, "status": "disabled", "message": "Cloudflare keep-awake is disabled."}) return
space_host = get_space_host() if not space_host: write_keepalive_status({"configured": False, "status": "skipped", "message": "SPACE_HOST could not be determined."}) return
cron = os.environ.get("CLOUDFLARE_KEEPALIVE_CRON", "*/10 * * * *").strip() space_host = space_host.removeprefix("https://").removeprefix("http://").split("/")[0] target_url = os.environ.get("CLOUDFLARE_KEEPALIVE_URL", f"https://{space_host}/health").strip() worker_name = derive_keepalive_worker_name() worker_source = render_keepalive_worker(target_url)
cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}", api_token, body=worker_source.encode("utf-8"), content_type="application/javascript", ) cf_request( "POST", f"/accounts/{account_id}/workers/scripts/{worker_name}/subdomain", api_token, body=json.dumps({"enabled": True, "previews_enabled": True}).encode("utf-8"), ) cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}/schedules", api_token, body=json.dumps([{"cron": cron}]).encode("utf-8"), )
worker_url = f"https://{worker_name}.{subdomain}.workers.dev" write_keepalive_status( { "configured": True, "status": "configured", "workerName": worker_name, "workerUrl": worker_url, "targetUrl": target_url, "cron": cron, "message": f"Cloudflare Worker cron pings {target_url} on {cron}.", } )
def main() -> int: api_token = os.environ.get("CLOUDFLARE_WORKERS_TOKEN", "").strip()
if not api_token: return 0
try: account_id, subdomain = resolve_account_and_subdomain(api_token) setup_keepalive_worker(api_token, account_id, subdomain) return 0 except Exception as exc: print(f"Cloudflare keepalive setup failed: {exc}", file=sys.stderr) write_keepalive_status({"configured": False, "status": "error", "message": str(exc)}) return 1
if __name__ == "__main__": raise SystemExit(main())13 unmodified lines1415161718192044 unmodified lines6566676869707172737475767778798060 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012 unmodified lines2042052062072082092102112122132142152162172182192202219 unmodified lines23123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628731 unmodified lines31932032132232332432532632732832913 unmodified linesAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingmess-cloudflare-proxy.env")KEEPALIVE_STATUS_FILE = Path("/tmp/huggingmess-cloudflare-keepalive-status.json")DEFAULT_ALLOWED = ["api.telegram.org","discord.com",44 unmodified linesreturn "huggingmess-proxy"def derive_keepalive_worker_name() -> str:explicit = os.environ.get("CLOUDFLARE_KEEPALIVE_WORKER_NAME", "").strip()if explicit:return slugify(explicit)space_host = os.environ.get("SPACE_HOST", "").strip()if space_host:return slugify(f"{space_host.replace('.hf.space', '')}-keepalive")return "huggingmess-keepalive"def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str:return f"""addEventListener("fetch", (event) => {{event.respondWith(handleRequest(event.request));60 unmodified lines"""def render_keepalive_worker(target_url: str) -> str:return f"""addEventListener("fetch", (event) => {{event.respondWith(handleRequest(event.request));}});addEventListener("scheduled", (event) => {{event.waitUntil(ping("cron"));}});const TARGET_URL = {json.dumps(target_url)};async function ping(source) {{const startedAt = new Date().toISOString();try {{const response = await fetch(TARGET_URL, {{method: "GET",headers: {{"user-agent": "HuggingMess Cloudflare KeepAlive","cache-control": "no-cache"}},cf: {{ cacheTtl: 0, cacheEverything: false }}}});return {{ok: response.ok,status: response.status,source,target: TARGET_URL,timestamp: startedAt}};}} catch (error) {{return {{ok: false,status: 0,source,target: TARGET_URL,timestamp: startedAt,error: error.message}};}}}}async function handleRequest(request) {{const url = new URL(request.url);if (url.pathname === "/" || url.pathname === "/health" || url.pathname === "/ping") {{const result = await ping("manual");return new Response(JSON.stringify(result, null, 2), {{status: result.ok ? 200 : 502,headers: {{ "content-type": "application/json; charset=utf-8" }}}});}}return new Response("Not found", {{ status: 404 }});}}"""def write_env(proxy_url: str, proxy_secret: str) -> None:ENV_FILE.write_text(f'export CLOUDFLARE_PROXY_URL="{proxy_url}"\nexport CLOUDFLARE_PROXY_SECRET="{proxy_secret}"\n',2 unmodified linesENV_FILE.chmod(0o600)def write_keepalive_status(payload: dict) -> None:payload = {**payload,"timestamp": payload.get("timestamp") or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),}KEEPALIVE_STATUS_FILE.write_text(json.dumps(payload), encoding="utf-8")try:KEEPALIVE_STATUS_FILE.chmod(0o600)except OSError:passdef resolve_account_and_subdomain(api_token: str) -> tuple[str, str]:account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()if not account_id:9 unmodified linesreturn account_id, subdomaindef setup_keepalive_worker(api_token: str, account_id: str, subdomain: str) -> None:enabled = os.environ.get("CLOUDFLARE_KEEPALIVE_ENABLED", "true").strip().lower()if enabled in {"0", "false", "no", "off"}:write_keepalive_status({"configured": False, "status": "disabled", "message": "Cloudflare keep-awake is disabled."})returnspace_host = os.environ.get("SPACE_HOST", "").strip()if not space_host:write_keepalive_status({"configured": False, "status": "skipped", "message": "SPACE_HOST is not set."})returncron = os.environ.get("CLOUDFLARE_KEEPALIVE_CRON", "*/10 * * * *").strip()space_host = space_host.removeprefix("https://").removeprefix("http://").split("/")[0]target_url = os.environ.get("CLOUDFLARE_KEEPALIVE_URL", f"https://{space_host}/health").strip()worker_name = derive_keepalive_worker_name()worker_source = render_keepalive_worker(target_url)cf_request("PUT",f"/accounts/{account_id}/workers/scripts/{worker_name}",api_token,body=worker_source.encode("utf-8"),content_type="application/javascript",)cf_request("POST",f"/accounts/{account_id}/workers/scripts/{worker_name}/subdomain",api_token,body=json.dumps({"enabled": True, "previews_enabled": True}).encode("utf-8"),)cf_request("PUT",f"/accounts/{account_id}/workers/scripts/{worker_name}/schedules",api_token,body=json.dumps([{"cron": cron}]).encode("utf-8"),)worker_url = f"https://{worker_name}.{subdomain}.workers.dev"write_keepalive_status({"configured": True,"status": "configured","workerName": worker_name,"workerUrl": worker_url,"targetUrl": target_url,"cron": cron,"message": f"Cloudflare Worker cron pings {target_url} on {cron}.",})def main() -> int:existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip()existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip()31 unmodified lines)write_env(f"https://{worker_name}.{subdomain}.workers.dev", proxy_secret)setup_keepalive_worker(api_token, account_id, subdomain)return 0except Exception as exc:print(f"Cloudflare proxy setup failed: {exc}", file=sys.stderr)write_keepalive_status({"configured": False, "status": "error", "message": str(exc)})return 113 unmodified lines1415161718192044 unmodified lines65666768697060 unmodified lines1311321331341351362 unmodified lines1391401411421431449 unmodified lines15415515615715815931 unmodified lines19119219319419519619719819913 unmodified linesAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingmess-cloudflare-proxy.env")ENV_FILE = Path("/tmp/huggingmess-cloudflare-proxy.env")DEFAULT_ALLOWED = ["api.telegram.org","discord.com",44 unmodified linesreturn "huggingmess-proxy"def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str:return f"""addEventListener("fetch", (event) => {{event.respondWith(handleRequest(event.request));60 unmodified lines"""def write_env(proxy_url: str, proxy_secret: str) -> None:ENV_FILE.write_text(f'export CLOUDFLARE_PROXY_URL="{proxy_url}"\nexport CLOUDFLARE_PROXY_SECRET="{proxy_secret}"\n',2 unmodified linesENV_FILE.chmod(0o600)def resolve_account_and_subdomain(api_token: str) -> tuple[str, str]:account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()if not account_id:9 unmodified linesreturn account_id, subdomaindef main() -> int:existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip()existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip()31 unmodified lines)write_env(f"https://{worker_name}.{subdomain}.workers.dev", proxy_secret)return 0except Exception as exc:print(f"Cloudflare proxy setup failed: {exc}", file=sys.stderr)return 1
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/bin/bashset -euo pipefail
API_URL="https://api.uptimerobot.com/v2"API_KEY="${UPTIMEROBOT_API_KEY:-}"SPACE_HOST_INPUT="${1:-${SPACE_HOST:-}}"STATUS_FILE="/tmp/huggingmess-uptimerobot-status.json"
if [ -z "$API_KEY" ]; then echo "Missing UPTIMEROBOT_API_KEY." exit 1fi
if [ -z "$SPACE_HOST_INPUT" ]; then echo "Missing Space host." exit 1fi
SPACE_HOST_CLEAN="${SPACE_HOST_INPUT#https://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN#http://}"SPACE_HOST_CLEAN="${SPACE_HOST_CLEAN%%/*}"MONITOR_URL="https://${SPACE_HOST_CLEAN}/health"MONITOR_NAME="${UPTIMEROBOT_MONITOR_NAME:-HuggingMess ${SPACE_HOST_CLEAN}}"INTERVAL="${UPTIMEROBOT_INTERVAL:-300}"
MONITORS_RESPONSE=$(curl -sS -X POST "${API_URL}/getMonitors" \ -d "api_key=${API_KEY}" \ -d "format=json" \ -d "logs=0" \ -d "response_times=0" \ -d "response_times_limit=1")
MONITOR_ID=$(printf '%s' "$MONITORS_RESPONSE" | jq -r --arg url "$MONITOR_URL" ' (.monitors // []) | map(select(.url == $url)) | first | .id // empty')
if [ -n "$MONITOR_ID" ]; then printf '{"configured":true,"monitorId":"%s","url":"%s","alreadyExisted":true,"timestamp":"%s"}\n' \ "$MONITOR_ID" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE" echo "UptimeRobot monitor already exists for ${MONITOR_URL}" exit 0fi
CURL_ARGS=( -sS -X POST "${API_URL}/newMonitor" -d "api_key=${API_KEY}" -d "format=json" -d "type=1" -d "friendly_name=${MONITOR_NAME}" -d "url=${MONITOR_URL}" -d "interval=${INTERVAL}")
if [ -n "${UPTIMEROBOT_ALERT_CONTACTS:-}" ]; then CURL_ARGS+=(-d "alert_contacts=${UPTIMEROBOT_ALERT_CONTACTS}")fi
CREATE_RESPONSE=$(curl "${CURL_ARGS[@]}")CREATE_STATUS=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.stat // "fail"')
if [ "$CREATE_STATUS" != "ok" ]; then printf '{"configured":false,"error":"creation failed","timestamp":"%s"}\n' \ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE" echo "Failed to create UptimeRobot monitor." printf '%s\n' "$CREATE_RESPONSE" exit 1fi
NEW_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.monitor.id // empty')printf '{"configured":true,"monitorId":"%s","url":"%s","timestamp":"%s"}\n' \ "${NEW_ID:-}" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE"echo "Created UptimeRobot monitor ${NEW_ID:-"(id unavailable)"} for ${MONITOR_URL}"59 unmodified lines606162636465212 unmodified lines27827928028128228328428528628728859 unmodified linesfifiif [ -n "${TELEGRAM_USER_IDS:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; thenexport TELEGRAM_ALLOWED_USERS="$TELEGRAM_USER_IDS"elif [ -n "${TELEGRAM_USER_ID:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; then212 unmodified linesnode "$APP_DIR/health-server.js" &HEALTH_PID=$!if [ "${UPTIMEROBOT_ENABLED:-false}" = "true" ] && [ -n "${UPTIMEROBOT_API_KEY:-}" ] && [ -n "${SPACE_HOST:-}" ]; thenecho "Setting up UptimeRobot monitor..."bash "$APP_DIR/setup-uptimerobot.sh" "${SPACE_HOST}" || truefiif [ -n "${WEBHOOK_URL:-}" ]; thenpython - <<'PY' >/dev/null 2>&1 &import json, os, urllib.request59 unmodified lines6061626364656667686970212 unmodified lines28328428528628728859 unmodified linesfifiif [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; thenecho "Preparing Cloudflare Keepalive worker..."python "$APP_DIR/cloudflare-keepalive-setup.py" || truefiif [ -n "${TELEGRAM_USER_IDS:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; thenexport TELEGRAM_ALLOWED_USERS="$TELEGRAM_USER_IDS"elif [ -n "${TELEGRAM_USER_ID:-}" ] && [ -z "${TELEGRAM_ALLOWED_USERS:-}" ]; then212 unmodified linesnode "$APP_DIR/health-server.js" &HEALTH_PID=$!if [ -n "${WEBHOOK_URL:-}" ]; thenpython - <<'PY' >/dev/null 2>&1 &import json, os, urllib.request
CHANGELOG.md+1-1
Dockerfile+2-2
README.md+3-3
cloudflare-keepalive-setup.pyAdded+212
cloudflare-proxy-setup.py+1-131
setup-uptimerobot.shDeleted-73
start.sh+5-5