ummmar commited on
Commit
5303a92
·
verified ·
1 Parent(s): be83b46

Update keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +26 -39
keep_alive.py CHANGED
@@ -1,11 +1,11 @@
1
- import os, requests, time
2
 
3
  CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
4
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
5
  SPACE_HOST = os.getenv("SPACE_HOST") or os.getenv("CONTAINER_HOST")
6
 
7
- if not SPACE_HOST:
8
- print("⏭️ Keep-alive skipped: SPACE_HOST not detected.")
9
  exit(0)
10
 
11
  if not SPACE_HOST.startswith("http"):
@@ -13,50 +13,37 @@ if not SPACE_HOST.startswith("http"):
13
 
14
  WORKER_NAME = "opencode-keepalive"
15
  URL = f"{SPACE_HOST}/health"
16
- HEADERS = {"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/javascript"}
17
 
18
- print(f"🚀 Provisioning Keep-Alive Worker for: {URL}")
19
-
20
- # 1. Deploy Worker Script
21
- script = f"""
22
  addEventListener('scheduled', event => {{
23
- event.waitUntil(fetch('{URL}').then(r => console.log('Ping status:', r.status)));
24
  }});
25
- """
 
 
 
 
 
 
26
 
27
- try:
28
- res = requests.put(
29
- f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}",
30
- headers=HEADERS, data=script
31
- )
32
- res.raise_for_status()
33
- print("✅ Worker script deployed.")
34
- except Exception as e:
35
- print(f"❌ Worker deploy failed: {e}")
36
- # Do not exit here, let the space run without keep-alive if CF fails
37
- exit(0)
38
 
39
- # 2. Wait for propagation
40
- time.sleep(3)
41
 
42
- # 3. Set Cron Trigger
43
- cron_payload = {"schedules": [{"cron": "*/10 * * * *"}]}
44
  try:
45
  res = requests.put(
46
- f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/schedules",
47
- headers={"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/json"},
48
- json=cron_payload
49
  )
50
- if res.status_code == 400:
51
- print("⚠️ Cron setup returned 400. Retrying in 5 seconds...")
52
- time.sleep(5)
53
- res = requests.put(
54
- f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/schedules",
55
- headers={"Authorization": f"Bearer {CF_TOKEN}", "Content-Type": "application/json"},
56
- json=cron_payload
57
- )
58
  res.raise_for_status()
59
- print("✅ Cron trigger set (every 10 mins).")
 
 
60
  except Exception as e:
61
- print(f"⚠️ Cron setup failed (non-critical): {e}")
62
- print(" The worker is deployed but may not ping automatically. Check CF Dashboard.")
 
1
+ import os, requests, json
2
 
3
  CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
4
  CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
5
  SPACE_HOST = os.getenv("SPACE_HOST") or os.getenv("CONTAINER_HOST")
6
 
7
+ if not all([CF_TOKEN, CF_ACCOUNT_ID, SPACE_HOST]):
8
+ print("⏭️ Keep-alive skipped: Missing credentials.")
9
  exit(0)
10
 
11
  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}")