cloudcode / keep_alive.py
ummmar's picture
Update keep_alive.py
63e633b verified
Raw History Blame Contribute Delete
2.16 kB
import os, requests, time
CF_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
SPACE_HOST = os.getenv("SPACE_HOST") or os.getenv("CONTAINER_HOST")
if not all([CF_TOKEN, CF_ACCOUNT_ID, SPACE_HOST]):
print("⏭️ Keep-alive skipped: Missing credentials.")
exit(0)
if not SPACE_HOST.startswith("http"):
SPACE_HOST = f"https://{SPACE_HOST}"
WORKER_NAME = "opencode-keepalive"
URL = f"{SPACE_HOST}/health"
SCRIPT = f"""
addEventListener('scheduled', event => {{
event.waitUntil(fetch('{URL}').then(r => console.log('Ping:', r.status)));
}});
"""
headers_js = {
"Authorization": f"Bearer {CF_TOKEN}",
"Content-Type": "application/javascript"
}
headers_json = {
"Authorization": f"Bearer {CF_TOKEN}",
"Content-Type": "application/json"
}
print(f"🚀 Deploying Keep-Alive Worker for: {URL}")
# Step 1: Upload script as application/javascript
try:
res = requests.put(
f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}",
headers=headers_js,
data=SCRIPT
)
res.raise_for_status()
print("✅ Worker script deployed.")
except Exception as e:
print(f"❌ Script deploy failed: {e}")
exit(0)
# Step 2: Wait for propagation
time.sleep(3)
# Step 3: Set cron trigger via /settings endpoint
cron_payload = {"crons": ["*/10 * * * *"]}
try:
res = requests.put(
f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/settings",
headers=headers_json,
json=cron_payload
)
if res.status_code == 400:
print("⚠️ Cron settings returned 400. Retrying in 5s...")
time.sleep(5)
res = requests.put(
f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/workers/scripts/{WORKER_NAME}/settings",
headers=headers_json,
json=cron_payload
)
res.raise_for_status()
print("✅ Cron trigger set (every 10 mins).")
except Exception as e:
print(f"⚠️ Cron setup failed (non-critical): {e}")
print(" Worker is live but may not auto-ping. Check CF Dashboard.")