feat(analytics): report job outcomes to OpenPanel, with the user's job index

The browser reports the funnel, but not what decides whether this product
retains: on 26-jul-2026, 491 of the 564 users who ever processed a video did it
exactly once. Every clip-quality fix that shipped that day — 1080p delivery,
captions by default, loudness normalisation — was aimed at that 87%, and
nothing in the stack could measure whether it moved.

Client-side cannot answer it. A render finishes minutes later, often after the
tab is gone, and ad-blockers eat a share of the rest. So the backend now emits
ClipsDelivered / JobFailed with the user's profileId and a `job_index` — the
count of process jobs that user has run. Counting distinct users at index 1
versus index >= 2, before and after today, answers the question directly.
Failures carry the same reason classification the Telegram alerts use, so the
"did it break or did they just not come back" split is visible too.

Fire-and-forget throughout: no config means a silent no-op (the normal state
for self-hosted), every send is a background task, and every failure is
swallowed. Analytics must never slow down or break a job.

Needs OPENPANEL_CLIENT_ID and OPENPANEL_CLIENT_SECRET in the environment — a
WRITE client, which is a different credential from the read/root client the MCP
needs. Verified against the live instance: the write path returns 200 and the
module no-ops cleanly when unconfigured.
This commit is contained in:
juancarlos.cavero 2026-07-28 15:52:42 +02:00
parent 4fcc1cd5ed
commit 51aafb5290
3 changed files with 118 additions and 0 deletions

View file

@ -113,6 +113,7 @@ Async job queue with semaphore-based concurrency control. Configure via `MAX_CON
- `MAX_CONCURRENT_JOBS` - Concurrent processing limit (default: 5) - `MAX_CONCURRENT_JOBS` - Concurrent processing limit (default: 5)
- `VITE_API_URL` - Production API URL override - `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. - `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):** **Client-side (localStorage, encrypted):**
- `GEMINI_API_KEY` - Google Gemini API key (required) - `GEMINI_API_KEY` - Google Gemini API key (required)

40
app.py
View file

@ -943,6 +943,46 @@ async def _record_job_alert(job_id):
await _alerts.record_job_outcome(ok, err) await _alerts.record_job_outcome(ok, err)
except Exception as e: except Exception as e:
print(f"⚠️ Alert recording error for {job_id}: {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): async def _settle_reservation(job_id):

77
cloud/analytics.py Normal file
View file

@ -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