ummmar commited on
Commit
74c6e7a
·
verified ·
1 Parent(s): 82fb16e

Create keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +34 -0
keep_alive.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)