ummmar commited on
Commit
796ba89
·
verified ·
1 Parent(s): 3921d81

Update keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +39 -16
keep_alive.py CHANGED
@@ -1,34 +1,57 @@
1
- import os, requests, json, time
2
 
3
- CF_TOKEN = os.getenv("CLOUDFLARE_WORKERS_TOKEN")
 
 
 
 
 
 
 
 
4
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
5
- SPACE_HOST = os.getenv("SPACE_HOST")
6
 
7
  if not all([CF_TOKEN, CF_ACCOUNT_ID, SPACE_HOST]):
8
- print("Keep-alive skipped: Missing CF credentials or SPACE_HOST.")
 
9
  exit(0)
10
 
 
 
 
 
11
  WORKER_NAME = "opencode-keepalive"
12
- URL = f"https://{SPACE_HOST}/health"
13
  HEADERS = {"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/javascript"}
14
 
 
 
15
  # 1. Deploy Worker Script
16
  script = f"""
17
  addEventListener('scheduled', event => {{
18
  event.waitUntil(fetch('{URL}').then(r => console.log('Ping status:', r.status)));
19
  }});
20
  """
21
- res = requests.put(
22
- f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}",
23
- headers=HEADERS, data=script
24
- )
25
- print("Worker deploy:", res.status_code)
 
 
 
 
 
26
 
27
  # 2. Set Cron Trigger (Every 10 mins)
28
  cron_payload = {"schedules": [{"cron": "*/10 * * * *"}]}
29
- res = requests.put(
30
- f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/schedules",
31
- headers={"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/json"},
32
- json=cron_payload
33
- )
34
- print("Cron setup:", res.status_code)
 
 
 
 
 
1
+ import os, requests, json
2
 
3
+ # 1. Auto-detect SPACE_HOST from Hugging Face environment
4
+ # HF Spaces usually provide SPACE_HOST or CONTAINER_HOST
5
+ SPACE_HOST = os.getenv("SPACE_HOST") or os.getenv("CONTAINER_HOST")
6
+
7
+ # If still missing, check if we have a custom override
8
+ if not SPACE_HOST:
9
+ SPACE_HOST = os.getenv("CUSTOM_SPACE_HOST") # Optional fallback secret
10
+
11
+ CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN") # Unified token
12
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
 
13
 
14
  if not all([CF_TOKEN, CF_ACCOUNT_ID, SPACE_HOST]):
15
+ print("⏭️ Keep-alive skipped: Missing CF credentials or SPACE_HOST.")
16
+ print(f" DEBUG: SPACE_HOST={SPACE_HOST}, CF_TOKEN={'Set' if CF_TOKEN else 'Missing'}, CF_ACCOUNT_ID={'Set' if CF_ACCOUNT_ID else 'Missing'}")
17
  exit(0)
18
 
19
+ # Ensure https:// prefix
20
+ if not SPACE_HOST.startswith("http"):
21
+ SPACE_HOST = f"https://{SPACE_HOST}"
22
+
23
  WORKER_NAME = "opencode-keepalive"
24
+ URL = f"{SPACE_HOST}/health"
25
  HEADERS = {"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/javascript"}
26
 
27
+ print(f"🚀 Provisioning Keep-Alive Worker for: {URL}")
28
+
29
  # 1. Deploy Worker Script
30
  script = f"""
31
  addEventListener('scheduled', event => {{
32
  event.waitUntil(fetch('{URL}').then(r => console.log('Ping status:', r.status)));
33
  }});
34
  """
35
+ try:
36
+ res = requests.put(
37
+ f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}",
38
+ headers=HEADERS, data=script
39
+ )
40
+ res.raise_for_status()
41
+ print("✅ Worker deployed successfully.")
42
+ except Exception as e:
43
+ print(f"❌ Worker deploy failed: {e}")
44
+ exit(1)
45
 
46
  # 2. Set Cron Trigger (Every 10 mins)
47
  cron_payload = {"schedules": [{"cron": "*/10 * * * *"}]}
48
+ try:
49
+ res = requests.put(
50
+ f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/schedules",
51
+ headers={"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/json"},
52
+ json=cron_payload
53
+ )
54
+ res.raise_for_status()
55
+ print("✅ Cron trigger set (every 10 mins).")
56
+ except Exception as e:
57
+ print(f"❌ Cron setup failed: {e}")