|
| 1 | +import logging |
| 2 | +import time |
| 3 | +from datetime import datetime, timezone |
| 4 | + |
| 5 | +from fastapi import BackgroundTasks, FastAPI, HTTPException |
| 6 | +from fastapi.middleware.cors import CORSMiddleware |
| 7 | +from fastapi.responses import RedirectResponse |
| 8 | +from fastapi.staticfiles import StaticFiles |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | +import config |
| 12 | +from sync import SyncEngine |
| 13 | + |
| 14 | +logging.basicConfig( |
| 15 | + level=logging.INFO, |
| 16 | + format="%(asctime)s %(name)s %(levelname)s %(message)s", |
| 17 | +) |
| 18 | +logger = logging.getLogger("cloud-sync") |
| 19 | + |
| 20 | +app = FastAPI(title="WFR Cloud Sync") |
| 21 | +app.add_middleware( |
| 22 | + CORSMiddleware, |
| 23 | + allow_origins=["*"], |
| 24 | + allow_methods=["*"], |
| 25 | + allow_headers=["*"], |
| 26 | +) |
| 27 | +app.mount("/static", StaticFiles(directory="static"), name="static") |
| 28 | + |
| 29 | +engine = SyncEngine() |
| 30 | + |
| 31 | +# ── Sync state (module-level, single process) ───────────────────────────────── |
| 32 | + |
| 33 | +_sync_state: dict = { |
| 34 | + "running": False, |
| 35 | + "rows_done": 0, |
| 36 | + "rows_total": 0, |
| 37 | + "last_sync_iso": None, # ISO timestamp of last completed sync |
| 38 | + "last_sync_rows": None, # row count of last completed sync |
| 39 | + "last_sync_elapsed": None, # seconds |
| 40 | + "last_error": None, |
| 41 | + # cached from last status call so /api/status is fast |
| 42 | + "_cloud_cursor": None, |
| 43 | + "_unsynced_count": None, |
| 44 | + "_unsynced_ts": 0.0, # monotonic time of last unsynced_count fetch |
| 45 | +} |
| 46 | + |
| 47 | +_UNSYNCED_CACHE_TTL = 30.0 # seconds |
| 48 | + |
| 49 | + |
| 50 | +@app.get("/") |
| 51 | +def root(): |
| 52 | + return RedirectResponse(url="/static/index.html") |
| 53 | + |
| 54 | + |
| 55 | +@app.get("/api/status") |
| 56 | +def status(): |
| 57 | + # Local count — always fresh (fast local query) |
| 58 | + try: |
| 59 | + local_count = engine.get_local_count() |
| 60 | + except Exception as e: |
| 61 | + local_count = None |
| 62 | + logger.warning(f"get_local_count failed: {e}") |
| 63 | + |
| 64 | + # Unsynced count — cached with TTL to avoid hammering cloud on every poll |
| 65 | + now = time.monotonic() |
| 66 | + if now - _sync_state["_unsynced_ts"] > _UNSYNCED_CACHE_TTL and not _sync_state["running"]: |
| 67 | + try: |
| 68 | + cursor = engine.get_cloud_cursor() |
| 69 | + _sync_state["_cloud_cursor"] = cursor.isoformat() if cursor else None |
| 70 | + _sync_state["_unsynced_count"] = engine.get_unsynced_count(cursor) |
| 71 | + _sync_state["_unsynced_ts"] = now |
| 72 | + except Exception as e: |
| 73 | + logger.warning(f"unsynced_count fetch failed: {e}") |
| 74 | + |
| 75 | + cloud_configured = bool(config.CLOUD_POSTGRES_DSN) |
| 76 | + |
| 77 | + return { |
| 78 | + "local_count": local_count, |
| 79 | + "local_table": config.LOCAL_TABLE, |
| 80 | + "cloud_table": engine.cloud_table, |
| 81 | + "cloud_configured": cloud_configured, |
| 82 | + "cloud_cursor": _sync_state["_cloud_cursor"], |
| 83 | + "unsynced_count": _sync_state["_unsynced_count"], |
| 84 | + "last_sync_iso": _sync_state["last_sync_iso"], |
| 85 | + "last_sync_rows": _sync_state["last_sync_rows"], |
| 86 | + "last_sync_elapsed": _sync_state["last_sync_elapsed"], |
| 87 | + "last_error": _sync_state["last_error"], |
| 88 | + "sync_running": _sync_state["running"], |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +@app.post("/api/check-cloud") |
| 93 | +def check_cloud(): |
| 94 | + result = engine.check_cloud_connection() |
| 95 | + return result |
| 96 | + |
| 97 | + |
| 98 | +@app.post("/api/sync") |
| 99 | +def trigger_sync(background_tasks: BackgroundTasks): |
| 100 | + if _sync_state["running"]: |
| 101 | + raise HTTPException(status_code=409, detail="Sync already in progress") |
| 102 | + |
| 103 | + if not config.CLOUD_POSTGRES_DSN: |
| 104 | + raise HTTPException(status_code=400, detail="CLOUD_POSTGRES_DSN not configured") |
| 105 | + |
| 106 | + _sync_state["running"] = True |
| 107 | + _sync_state["rows_done"] = 0 |
| 108 | + _sync_state["rows_total"] = 0 |
| 109 | + _sync_state["last_error"] = None |
| 110 | + |
| 111 | + background_tasks.add_task(_run_sync) |
| 112 | + return {"status": "started"} |
| 113 | + |
| 114 | + |
| 115 | +@app.get("/api/sync-status") |
| 116 | +def sync_status(): |
| 117 | + return { |
| 118 | + "running": _sync_state["running"], |
| 119 | + "rows_done": _sync_state["rows_done"], |
| 120 | + "rows_total": _sync_state["rows_total"], |
| 121 | + "last_sync_iso": _sync_state["last_sync_iso"], |
| 122 | + "last_sync_rows": _sync_state["last_sync_rows"], |
| 123 | + "last_sync_elapsed": _sync_state["last_sync_elapsed"], |
| 124 | + "last_error": _sync_state["last_error"], |
| 125 | + } |
| 126 | + |
| 127 | + |
| 128 | +def _progress_cb(rows_done: int, rows_total: int) -> None: |
| 129 | + _sync_state["rows_done"] = rows_done |
| 130 | + _sync_state["rows_total"] = rows_total |
| 131 | + |
| 132 | + |
| 133 | +class SelectTablePayload(BaseModel): |
| 134 | + table: str |
| 135 | + |
| 136 | + |
| 137 | +class CreateTablePayload(BaseModel): |
| 138 | + table: str |
| 139 | + |
| 140 | + |
| 141 | +@app.get("/api/local-tables") |
| 142 | +def list_local_tables(): |
| 143 | + """List existing local tables (tables matching ^wfr[0-9] on the local DB).""" |
| 144 | + tables = engine.list_local_tables() |
| 145 | + return {"tables": tables, "current": engine.local_table} |
| 146 | + |
| 147 | + |
| 148 | +@app.post("/api/select-local-table") |
| 149 | +def select_local_table(payload: SelectTablePayload): |
| 150 | + """Switch the active local source table for the next sync.""" |
| 151 | + if _sync_state["running"]: |
| 152 | + raise HTTPException(status_code=409, detail="Cannot change table while sync is running") |
| 153 | + name = payload.table.lower().strip() |
| 154 | + if not name: |
| 155 | + raise HTTPException(status_code=400, detail="Table name is required") |
| 156 | + engine.local_table = name |
| 157 | + # Invalidate unsynced cache |
| 158 | + _sync_state["_unsynced_ts"] = 0.0 |
| 159 | + _sync_state["_unsynced_count"] = None |
| 160 | + _sync_state["_cloud_cursor"] = None |
| 161 | + return {"selected": name} |
| 162 | + |
| 163 | + |
| 164 | +@app.get("/api/cloud-tables") |
| 165 | +def list_cloud_tables(): |
| 166 | + """List existing cloud tables (tables matching ^wfr[0-9] on the cloud DB).""" |
| 167 | + tables = engine.list_cloud_tables() |
| 168 | + return {"tables": tables, "current": engine.cloud_table} |
| 169 | + |
| 170 | + |
| 171 | +@app.post("/api/cloud-tables") |
| 172 | +def create_cloud_table(payload: CreateTablePayload): |
| 173 | + """Create a new cloud hypertable.""" |
| 174 | + name = payload.table.lower().strip() |
| 175 | + if not name: |
| 176 | + raise HTTPException(status_code=400, detail="Table name is required") |
| 177 | + try: |
| 178 | + engine.create_cloud_table(name) |
| 179 | + except Exception as e: |
| 180 | + raise HTTPException(status_code=500, detail=str(e)) |
| 181 | + # Invalidate unsynced cache |
| 182 | + _sync_state["_unsynced_ts"] = 0.0 |
| 183 | + return {"created": name} |
| 184 | + |
| 185 | + |
| 186 | +@app.post("/api/select-table") |
| 187 | +def select_table(payload: SelectTablePayload): |
| 188 | + """Switch the active cloud table for the next sync.""" |
| 189 | + if _sync_state["running"]: |
| 190 | + raise HTTPException(status_code=409, detail="Cannot change table while sync is running") |
| 191 | + name = payload.table.lower().strip() |
| 192 | + if not name: |
| 193 | + raise HTTPException(status_code=400, detail="Table name is required") |
| 194 | + engine.cloud_table = name |
| 195 | + # Invalidate unsynced cache so next /api/status recalculates |
| 196 | + _sync_state["_unsynced_ts"] = 0.0 |
| 197 | + _sync_state["_unsynced_count"] = None |
| 198 | + _sync_state["_cloud_cursor"] = None |
| 199 | + return {"selected": name} |
| 200 | + |
| 201 | + |
| 202 | +def _run_sync() -> None: |
| 203 | + try: |
| 204 | + result = engine.sync(progress_cb=_progress_cb) |
| 205 | + _sync_state["last_sync_iso"] = datetime.now(timezone.utc).isoformat() |
| 206 | + _sync_state["last_sync_rows"] = result["rows_synced"] |
| 207 | + _sync_state["last_sync_elapsed"] = result["elapsed_s"] |
| 208 | + _sync_state["last_error"] = None |
| 209 | + # Invalidate unsynced cache |
| 210 | + _sync_state["_unsynced_ts"] = 0.0 |
| 211 | + except Exception as e: |
| 212 | + logger.error(f"Sync failed: {e}") |
| 213 | + _sync_state["last_error"] = str(e) |
| 214 | + finally: |
| 215 | + _sync_state["running"] = False |
0 commit comments