diff --git a/CLAUDE.md b/CLAUDE.md index 32bb05f..abb377b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -113,6 +113,7 @@ Async job queue with semaphore-based concurrency control. Configure via `MAX_CON - `MAX_CONCURRENT_JOBS` - Concurrent processing limit (default: 5) - `VITE_API_URL` - Production API URL override - `VITE_OPENPANEL_API_URL`, `VITE_OPENPANEL_CLIENT_ID` - Optional product analytics, read at **build** time. Unset (the default, including every self-hosted build) means no analytics is initialised and no third-party script is loaded. `dashboard/index.html` also gates reporting on an `ANALYTICS_HOSTS` allowlist, so a build carrying credentials stays inert on any other host. +- `OPENPANEL_CLIENT_ID`, `OPENPANEL_CLIENT_SECRET` - Optional **server-side** analytics (`cloud/analytics.py`), same opt-in rule: unset means a silent no-op. Reports job outcomes with the user's job index, which the browser cannot do reliably — a render finishes after the tab is often gone, and ad-blockers eat a share of client events. Needs a *write* client; the read client used for querying is a different credential. **Client-side (localStorage, encrypted):** - `GEMINI_API_KEY` - Google Gemini API key (required) diff --git a/app.py b/app.py index 641b868..07fb810 100644 --- a/app.py +++ b/app.py @@ -943,6 +943,46 @@ async def _record_job_alert(job_id): await _alerts.record_job_outcome(ok, err) except Exception as e: print(f"⚠️ Alert recording error for {job_id}: {e}") + await _track_job_outcome(job, ok, err) + + +async def _track_job_outcome(job, ok, err): + """Report the job to OpenPanel, with the user's job index. + + The index is what makes the retention question answerable: on 26-jul-2026, + 491 of 564 users who ever processed a video did it exactly once. Counting + distinct users at index 1 versus index >= 2 measures whether the clip + quality work moved that, which nothing in the stack could do before. + + Client-side analytics cannot cover this: a render finishes minutes later, + often after the tab is closed, and ad-blockers eat a share of the rest. + """ + try: + from cloud import analytics as _an + from sqlalchemy import text as _sa_text + from cloud import database as _db + user_id = job.get('user_id') + job_index = None + try: + async with _db.session() as s: + job_index = (await s.execute(_sa_text( + "select count(*) from usage_ledger " + "where user_id = :uid and job_type = 'process'"), + {"uid": user_id})).scalar() + except Exception: + pass # an index we cannot read is not worth failing a job over + clips = len(((job.get('result') or {}).get('clips')) or []) + _an.track( + "ClipsDelivered" if ok else "JobFailed", + user_id=user_id, + job_index=job_index, + clips=clips if ok else None, + plan=job.get('user_plan'), + source="url" if job.get('url') else "upload", + reason=(_alerts._classify_failure(err) if not ok and err else None), + ) + except Exception as e: + print(f"⚠️ Analytics error: {e}") async def _settle_reservation(job_id): diff --git a/cloud/analytics.py b/cloud/analytics.py new file mode 100644 index 0000000..3a77d23 --- /dev/null +++ b/cloud/analytics.py @@ -0,0 +1,77 @@ +"""Server-side product events to OpenPanel. + +The browser already reports the funnel (Signup, CheckoutStarted, Subscribed, +QuotaWall*, UpsellModal*). This module reports what the browser cannot be +trusted for: + +* **Job outcomes.** Ad-blockers eat a chunk of client-side analytics, and the + interesting moment — a render finishing minutes later — often happens after + the tab is gone. Server-side is the only place these are complete. +* **Repeat usage.** The one number that decides whether the product retains: + on 26-jul-2026, 491 of 564 users who ever processed a video did it exactly + once. Every clip-quality fix shipped that day (1080p, captions, loudness) was + aimed at that 87%, and nothing in the stack could measure whether it moved. + ``job_index`` on each event answers it directly: count distinct users at + index 1 versus index >= 2, before and after. + +Fire-and-forget by design. Analytics must never slow down or break a job, so +every failure is swallowed and every send runs in the background. +""" +import asyncio +import os + +import httpx + +_TIMEOUT = 5.0 + + +def _config(): + """(api_url, client_id, client_secret) or None when not configured. + + Absent config is the normal state for self-hosted installs, so this stays + silent rather than warning. + """ + client_id = os.environ.get("OPENPANEL_CLIENT_ID", "").strip() + if not client_id: + return None + api = (os.environ.get("OPENPANEL_API_URL", "").strip() + or "https://api.openpanel.fotoexamen.com").rstrip("/") + return api, client_id, os.environ.get("OPENPANEL_CLIENT_SECRET", "").strip() + + +async def _post(payload): + cfg = _config() + if not cfg: + return + api, client_id, secret = cfg + headers = {"openpanel-client-id": client_id, "Content-Type": "application/json"} + if secret: + headers["openpanel-client-secret"] = secret + try: + async with httpx.AsyncClient(timeout=_TIMEOUT) as c: + await c.post(f"{api}/track", json=payload, headers=headers) + except Exception: + pass # analytics must never surface into a job + + +def track(name: str, user_id=None, **props): + """Queue an event. Returns immediately; never raises. + + ``user_id`` becomes OpenPanel's profileId, which is what makes retention + and repeat-usage questions answerable per user. + """ + if not _config(): + return + payload = { + "type": "track", + "payload": { + "name": name, + "properties": {k: v for k, v in props.items() if v is not None}, + }, + } + if user_id is not None: + payload["payload"]["profileId"] = str(user_id) + try: + asyncio.get_running_loop().create_task(_post(payload)) + except RuntimeError: + pass # no loop (CLI/self-host path) — nothing to report to anyway