douyinWEB/backend/app/pb_sync.py
eric a360eec2ba Document slots/covers/PB ops UX and sync feature pass to main.
Ship zombie reconcile, S3 covers, session end/drill-down, rooms ops, and refresh README for production.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 20:07:15 -05:00

346 lines
12 KiB
Python

"""
PocketBase sync — canonical admin datastore for rooms/sessions.
Monitor still uses SQLite as the hot-path worker DB; every mutation dual-writes here.
Media binaries live on SeaweedFS S3; only URLs are stored in PB/SQLite.
"""
from __future__ import annotations
import hashlib
import time
from typing import Any, Optional
import httpx
from .config import settings
_token: str = ""
_token_expire: float = 0
def _pb_id(sqlite_id: str) -> str:
"""PocketBase record id: 15-char [a-z0-9]."""
return hashlib.md5(str(sqlite_id).encode("utf-8")).hexdigest()[:15]
async def _client() -> httpx.AsyncClient:
return httpx.AsyncClient(
base_url=settings.pb_url.rstrip("/"),
timeout=20.0,
trust_env=False,
)
async def ensure_admin() -> None:
global _token, _token_expire
async with await _client() as client:
try:
resp = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if resp.status_code == 200:
data = resp.json()
_token = data.get("token") or ""
_token_expire = time.time() + 3600
return
except Exception:
pass
try:
resp = await client.post(
"/api/collections/_superusers/records",
json={
"email": settings.pb_admin_email,
"password": settings.pb_admin_password,
"passwordConfirm": settings.pb_admin_password,
},
)
if resp.status_code in (200, 201):
login = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if login.status_code == 200:
_token = login.json().get("token") or ""
_token_expire = time.time() + 3600
except Exception:
pass
async def _auth_headers() -> dict[str, str]:
global _token, _token_expire
if not _token or time.time() > _token_expire - 60:
await ensure_admin()
return {"Authorization": _token} if _token else {}
COLLECTION_DEFS: list[dict[str, Any]] = [
{
"name": "dy_rooms",
"type": "base",
"fields": [
{"name": "url", "type": "url", "required": True},
{"name": "room_id", "type": "text", "required": True},
{"name": "note", "type": "text"},
{"name": "tags", "type": "text"},
{"name": "enabled", "type": "bool"},
{"name": "last_status", "type": "text"},
{"name": "last_anchor", "type": "text"},
{"name": "last_title", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_blacklist",
"type": "base",
"fields": [
{"name": "value", "type": "text", "required": True},
{"name": "room_id", "type": "text"},
{"name": "reason", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_sessions",
"type": "base",
"fields": [
{"name": "room_id", "type": "text"},
{"name": "room_pk", "type": "text"},
{"name": "source_url", "type": "url"},
{"name": "anchor_name", "type": "text"},
{"name": "title", "type": "text"},
{"name": "started_at", "type": "number"},
{"name": "ended_at", "type": "number"},
{"name": "duration_seconds", "type": "number"},
{"name": "push_date", "type": "text"},
{"name": "status", "type": "text"},
{"name": "end_reason", "type": "text"},
{"name": "cover_url", "type": "url"},
{"name": "cover_path", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_events",
"type": "base",
"fields": [
{"name": "ts", "type": "number"},
{"name": "kind", "type": "text"},
{"name": "level", "type": "text"},
{"name": "message", "type": "text"},
{"name": "room_id", "type": "text"},
{"name": "session_id", "type": "text"},
{"name": "anchor_name", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
]
def _field_names(col_json: dict[str, Any]) -> set[str]:
names: set[str] = set()
for f in col_json.get("fields") or col_json.get("schema") or []:
n = f.get("name")
if n:
names.add(n)
return names
async def _ensure_fields(client: httpx.AsyncClient, headers: dict[str, str], col_def: dict[str, Any]) -> list[str]:
"""Add missing fields onto an existing PocketBase collection."""
name = col_def["name"]
resp = await client.get(f"/api/collections/{name}", headers=headers)
if resp.status_code != 200:
return [f"{name}: fetch {resp.status_code}"]
col = resp.json()
existing = _field_names(col)
missing = [f for f in col_def["fields"] if f["name"] not in existing]
if not missing:
return []
# PocketBase 0.22+ uses "fields"
fields = list(col.get("fields") or [])
if not fields and col.get("schema"):
fields = list(col.get("schema") or [])
for f in missing:
fields.append(dict(f))
payload = {"fields": fields}
patch = await client.patch(f"/api/collections/{name}", headers=headers, json=payload)
if patch.status_code not in (200, 204):
return [f"{name}: patch fields {patch.status_code} {patch.text[:180]}"]
return []
async def ensure_collections() -> dict[str, Any]:
await ensure_admin()
headers = await _auth_headers()
created: list[str] = []
updated: list[str] = []
skipped: list[str] = []
errors: list[str] = []
async with await _client() as client:
existing = await client.get("/api/collections", headers=headers)
by_name: dict[str, Any] = {}
if existing.status_code == 200:
for item in existing.json().get("items") or []:
by_name[item.get("name")] = item
for col in COLLECTION_DEFS:
if col["name"] in by_name:
field_errs = await _ensure_fields(client, headers, col)
if field_errs:
errors.extend(field_errs)
else:
updated.append(col["name"])
continue
payload = {
"name": col["name"],
"type": col["type"],
"fields": [
{"name": "id", "type": "text", "primaryKey": True, "system": True},
*col["fields"],
{"name": "created", "type": "autodate", "onCreate": True, "onUpdate": False},
{"name": "updated", "type": "autodate", "onCreate": True, "onUpdate": True},
],
}
resp = await client.post("/api/collections", headers=headers, json=payload)
if resp.status_code in (200, 201):
created.append(col["name"])
else:
errors.append(f"{col['name']}: {resp.status_code} {resp.text[:200]}")
return {
"created": created,
"updated": updated,
"skipped": skipped,
"errors": errors,
"ok": not errors,
}
async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]:
headers = await _auth_headers()
if not headers:
return None
async with await _client() as client:
filt = f'sqlite_id="{sqlite_id}"'
found = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
body = {**data, "sqlite_id": sqlite_id}
if found.status_code == 200 and (found.json().get("items") or []):
rid = found.json()["items"][0]["id"]
resp = await client.patch(
f"/api/collections/{collection}/records/{rid}",
headers=headers,
json=body,
)
if resp.status_code in (200, 204):
return rid
return None
# PocketBase text PK collections require explicit id on create
body["id"] = _pb_id(sqlite_id)
resp = await client.post(
f"/api/collections/{collection}/records",
headers=headers,
json=body,
)
if resp.status_code in (200, 201):
return resp.json().get("id") or body["id"]
# conflict: try fetch again / patch
if resp.status_code in (400, 409):
found2 = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
if found2.status_code == 200 and (found2.json().get("items") or []):
rid = found2.json()["items"][0]["id"]
await client.patch(
f"/api/collections/{collection}/records/{rid}",
headers=headers,
json={k: v for k, v in body.items() if k != "id"},
)
return rid
return None
def _session_cover_url(session: dict[str, Any]) -> str:
"""Only absolute http(s) URLs belong in PocketBase url field (S3 public)."""
raw = str(session.get("cover_path") or "").strip()
if raw.startswith("http://") or raw.startswith("https://"):
return raw
return ""
async def sync_room(room: dict[str, Any]) -> None:
await upsert_record(
"dy_rooms",
room["id"],
{
"url": room.get("url") or "",
"room_id": room.get("room_id") or "",
"note": room.get("note") or "",
"tags": room.get("tags") or "",
"enabled": bool(room.get("enabled")),
"last_status": room.get("last_status") or "",
"last_anchor": room.get("last_anchor") or "",
"last_title": room.get("last_title") or "",
},
)
async def sync_session(session: dict[str, Any]) -> None:
cover = _session_cover_url(session)
payload: dict[str, Any] = {
"room_id": session.get("room_id") or "",
"room_pk": session.get("room_pk") or "",
"source_url": session.get("source_url") or "",
"anchor_name": session.get("anchor_name") or "",
"title": session.get("title") or "",
"started_at": session.get("started_at") or 0,
"ended_at": session.get("ended_at") or 0,
"duration_seconds": session.get("duration_seconds") or 0,
"push_date": session.get("push_date") or "",
"status": session.get("status") or "",
"end_reason": session.get("end_reason") or "",
"cover_path": session.get("cover_path") or "",
}
if cover:
payload["cover_url"] = cover
await upsert_record("dy_sessions", session["id"], payload)
async def sync_event(event: dict[str, Any]) -> None:
eid = str(event.get("id") or "")
if not eid:
return
await upsert_record(
"dy_events",
eid,
{
"ts": event.get("ts") or 0,
"kind": event.get("kind") or "",
"level": event.get("level") or "",
"message": event.get("message") or "",
"room_id": event.get("room_id") or "",
"session_id": event.get("session_id") or "",
"anchor_name": event.get("anchor_name") or "",
},
)
async def health() -> dict[str, Any]:
try:
async with await _client() as client:
resp = await client.get("/api/health")
ok = resp.status_code == 200
body: Any
try:
body = resp.json()
except Exception:
body = resp.text[:200]
return {"ok": ok, "status_code": resp.status_code, "body": body}
except Exception as exc:
return {"ok": False, "error": str(exc)}