| import os |
| import httpx |
| import asyncio |
|
|
| SUPABASE_URL = os.environ.get("SUPABASE_URL", "") |
| SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "") |
|
|
| HEADERS = { |
| "apikey": SUPABASE_KEY, |
| "Authorization": f"Bearer {SUPABASE_KEY}", |
| "Content-Type": "application/json", |
| "Prefer": "return=minimal" |
| } |
|
|
| async def insert(table: str, data: dict): |
| """Insert data ke Supabase""" |
| if not SUPABASE_URL or not SUPABASE_KEY: |
| return False |
| try: |
| async with httpx.AsyncClient(timeout=10) as client: |
| response = await client.post( |
| f"{SUPABASE_URL}/rest/v1/{table}", |
| headers=HEADERS, |
| json=data |
| ) |
| return response.status_code in [200, 201] |
| except Exception: |
| return False |
|
|
| async def fetch(table: str, limit: int = 50) -> list: |
| """Fetch data dari Supabase""" |
| if not SUPABASE_URL or not SUPABASE_KEY: |
| return [] |
| try: |
| async with httpx.AsyncClient(timeout=10) as client: |
| response = await client.get( |
| f"{SUPABASE_URL}/rest/v1/{table}", |
| headers={**HEADERS, "Prefer": "return=representation"}, |
| params={"order": "created_at.desc", "limit": limit} |
| ) |
| if response.status_code == 200: |
| return response.json() |
| except Exception: |
| pass |
| return [] |
|
|
| async def log_activity(action: str, details: str = ""): |
| """Simpan activity log ke Supabase""" |
| await insert("activity_log", {"action": action, "details": details}) |
|
|
| async def log_chat(role: str, message: str, provider: str = ""): |
| """Simpan chat history ke Supabase""" |
| await insert("chat_history", {"role": role, "message": message, "provider": provider}) |
|
|
| async def log_module_output(module_name: str, topic: str, output: str, provider: str = ""): |
| """Simpan output modul ke Supabase""" |
| await insert("module_output", { |
| "module_name": module_name, |
| "topic": topic, |
| "output": output, |
| "provider": provider |
| }) |
|
|
| async def keepalive_ping(): |
| """Ping untuk keepalive log""" |
| await insert("keepalive_log", {"status": "alive"}) |
|
|
| async def start_keepalive(space_url: str = ""): |
| """Auto ping setiap 5 menit biar Space tidak sleep""" |
| while True: |
| try: |
| |
| await keepalive_ping() |
| |
| if space_url: |
| async with httpx.AsyncClient(timeout=10) as client: |
| await client.get(space_url) |
| except Exception: |
| pass |
| await asyncio.sleep(300) |