File size: 2,162 Bytes
63e633b 74c6e7a 25e813a 796ba89 5303a92 74c6e7a 796ba89 74c6e7a 796ba89 63e633b 74c6e7a 5303a92 74c6e7a 63e633b 5303a92 25e813a 63e633b 5303a92 74c6e7a 63e633b 25e813a 63e633b 796ba89 5303a92 63e633b 796ba89 63e633b 796ba89 63e633b 796ba89 63e633b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 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.") |