clipwright/cloud/database.py
juancarlos.cavero 05578c5456 feat: add hosted paid mode (managed keys, Stripe trial, metering)
Adds an optional cloud/paid mode behind a BILLING_ENABLED flag. With the flag
off the app is byte-identical to today's self-hosted BYOK build (regression-zero).

Backend (cloud/ package, only imported when BILLING_ENABLED):
- Auth: magic link (Resend) + Google OAuth (authlib) + JWT sessions
- Stripe: hosted Checkout with 3-day card trial, Customer Portal, idempotent
  order-safe webhooks; 3 plans (Starter/Creator/Pro) resolved by lookup_key
- Postgres + SQLAlchemy async; atomic minute metering (reserve/commit/release,
  plan->topup FIFO, restart-safe) with sweeper
- Managed keys: Gemini + Upload-Post server-side for entitled users; paid-only
  (BYOK core header ignored on hosted); Upload-Post white-label per-user profiles
- Metering wired into /api/process (probe->reserve->402, priority queue) and
  thumbnail image generation (3 min/batch)
- yt-dlp residential PROXY_URL support + 720p cap for hosted YouTube downloads

Frontend:
- AuthContext, LoginModal, PricingSection (3-day trial), AccountPage, UsageMeter,
  TopUpModal, TrialGate/AdvancedBanner
- Paid-only UI: hide BYOK core inputs, trial prompts per tool
- Included (Clip Generator, YouTube Studio) vs BYOK (AI Shorts/dubbing: fal.ai +
  ElevenLabs) clearly separated; ThumbnailStudio + SaaShortsTab managed-aware
- Landing: free-self-host vs paid-hosted messaging

Verified end-to-end against real Postgres + Stripe test mode.
2026-07-14 13:04:43 +02:00

49 lines
1.6 KiB
Python

"""Async SQLAlchemy engine + session management for cloud mode."""
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import declarative_base
from .config import settings
Base = declarative_base()
_engine = None
_sessionmaker = None
async def init_engine():
"""Create the async engine + sessionmaker and ensure the schema exists.
Uses ``create_all`` for zero-friction boot (additive-only schema in v1).
Alembic (see ``alembic/``) is available for controlled migrations later.
"""
global _engine, _sessionmaker
if _engine is not None:
return
# Import models so their tables register on Base.metadata before create_all.
from . import models # noqa: F401
_engine = create_async_engine(settings.database_url, pool_pre_ping=True)
_sessionmaker = async_sessionmaker(_engine, expire_on_commit=False, class_=AsyncSession)
async with _engine.begin() as conn:
# Case-insensitive email uniqueness.
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS citext"))
await conn.run_sync(Base.metadata.create_all)
def get_sessionmaker():
if _sessionmaker is None:
raise RuntimeError("Cloud DB engine not initialized — call init_engine() first.")
return _sessionmaker
def session():
"""Return a new AsyncSession context manager (for use outside FastAPI deps)."""
return get_sessionmaker()()
async def get_db():
"""FastAPI dependency yielding an AsyncSession."""
async with get_sessionmaker()() as s:
yield s