ummmar commited on
Commit
63e633b
Β·
verified Β·
1 Parent(s): 5303a92

Update keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +40 -19
keep_alive.py CHANGED
@@ -1,4 +1,4 @@
1
- import os, requests, json
2
 
3
  CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
4
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
@@ -13,37 +13,58 @@ if not SPACE_HOST.startswith("http"):
13
 
14
  WORKER_NAME = "opencode-keepalive"
15
  URL = f"{SPACE_HOST}/health"
16
-
17
- # Embed cron trigger IN the script metadata (no separate /schedules call needed)
18
- payload = {
19
- "script": f"""
20
  addEventListener('scheduled', event => {{
21
  event.waitUntil(fetch('{URL}').then(r => console.log('Ping:', r.status)));
22
  }});
23
- """,
24
- "bindings": [],
25
- "compatibility_date": "2024-01-01",
26
- "triggers": {
27
- "crons": ["*/10 * * * *"]
28
- }
29
  }
30
 
31
- headers = {
32
  "Authorization": f"Bearer {CF_TOKEN}",
33
  "Content-Type": "application/json"
34
  }
35
 
36
- print(f"πŸš€ Deploying Keep-Alive Worker with embedded cron for: {URL}")
37
 
 
38
  try:
39
  res = requests.put(
40
  f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}",
41
- headers=headers,
42
- json=payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
 
 
 
 
 
 
 
 
44
  res.raise_for_status()
45
- print("βœ… Worker deployed with cron trigger (every 10 mins).")
46
- except requests.exceptions.HTTPError as e:
47
- print(f"❌ Deploy failed: {e.response.text}")
48
  except Exception as e:
49
- print(f"❌ Deploy failed: {e}")
 
 
1
+ import os, requests, time
2
 
3
  CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
4
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
 
13
 
14
  WORKER_NAME = "opencode-keepalive"
15
  URL = f"{SPACE_HOST}/health"
16
+ SCRIPT = f"""
 
 
 
17
  addEventListener('scheduled', event => {{
18
  event.waitUntil(fetch('{URL}').then(r => console.log('Ping:', r.status)));
19
  }});
20
+ """
21
+
22
+ headers_js = {
23
+ "Authorization": f"Bearer {CF_TOKEN}",
24
+ "Content-Type": "application/javascript"
 
25
  }
26
 
27
+ headers_json = {
28
  "Authorization": f"Bearer {CF_TOKEN}",
29
  "Content-Type": "application/json"
30
  }
31
 
32
+ print(f"πŸš€ Deploying Keep-Alive Worker for: {URL}")
33
 
34
+ # Step 1: Upload script as application/javascript
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_js,
39
+ data=SCRIPT
40
+ )
41
+ res.raise_for_status()
42
+ print("βœ… Worker script deployed.")
43
+ except Exception as e:
44
+ print(f"❌ Script deploy failed: {e}")
45
+ exit(0)
46
+
47
+ # Step 2: Wait for propagation
48
+ time.sleep(3)
49
+
50
+ # Step 3: Set cron trigger via /settings endpoint
51
+ cron_payload = {"crons": ["*/10 * * * *"]}
52
+ try:
53
+ res = requests.put(
54
+ f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/settings",
55
+ headers=headers_json,
56
+ json=cron_payload
57
  )
58
+ if res.status_code == 400:
59
+ print("⚠️ Cron settings returned 400. Retrying in 5s...")
60
+ time.sleep(5)
61
+ res = requests.put(
62
+ f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/settings",
63
+ headers=headers_json,
64
+ json=cron_payload
65
+ )
66
  res.raise_for_status()
67
+ print("βœ… Cron trigger set (every 10 mins).")
 
 
68
  except Exception as e:
69
+ print(f"⚠️ Cron setup failed (non-critical): {e}")
70
+ print(" Worker is live but may not auto-ping. Check CF Dashboard.")