diff --git a/CLAUDE.md b/CLAUDE.md index 9f46b2b..51e40b1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -194,7 +194,11 @@ own (the client sends no `max_minutes`): the floored balance is reserved (it lands at zero) and the download's safety cap (`SOURCE_CAP_MINUTES`) is the probed length, not the reservation. Once per account: `metering.has_processed_before` (any reserved/committed - `process` row; a released one keeps the grant for the retry). The response + `process` row; a released one keeps the grant for the retry), and once per + client IP every `FIRST_VIDEO_IP_WINDOW_DAYS` (30): `first_video_grants` + holds an HMAC of the IP (never the IP), is not tied to the user row so an + account deletion does not reset it, and only counts grants whose job + reservation is live. A blocked network gets the first-N-minutes cut. The response carries `first_video: true`; the dashboard says so and tracks `FirstVideoGrant`. - **Anything else:** `max_minutes` becomes the balance, so the job clips the diff --git a/app.py b/app.py index 1a70ea9..b94cfd3 100644 --- a/app.py +++ b/app.py @@ -432,8 +432,15 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes= # FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is # clipped to the first N minutes. Neither sees the wall. grant = None + ip_hash = "" if balance.get("plan") == "free" and minutes > balance["remaining"] and max_minutes is None: processed_before = await _metering.has_processed_before(user.id) + if not processed_before: + # One whole first video per network (FIRST_VIDEO_IP_WINDOW_DAYS), + # so a stack of Google accounts from one IP gets one, not many. + ip_hash = _metering.ip_fingerprint(request.client.host if request.client else "") + if await _metering.ip_had_first_video(ip_hash): + processed_before = True grant, max_minutes = free_overflow("free", minutes, balance["remaining"], max_minutes, processed_before) @@ -451,6 +458,11 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes= # first video is processed whole, so its cap is the probed length. request.state.reserved_minutes = minutes if grant is not None else reserve request.state.first_video = grant is not None + if grant is not None: + try: + await _metering.record_first_video(ip_hash, job_id) + except Exception as e: # the grant stands; only the IP memory is lost + print(f"⚠️ Could not record first-video grant: {e}") except _metering.QuotaExceeded as e: _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ diff --git a/cloud/config.py b/cloud/config.py index e49b9b5..7781ac1 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -98,6 +98,11 @@ PARTIAL_MIN_MINUTES = 5 # the first N minutes automatically instead of hitting the wall. # 0 disables the grant. FIRST_VIDEO_MAX_MINUTES = 60 +# ...and once per client IP in this many days, whatever the account: a pile of +# Google accounts from one network gets one whole first video, and the rest +# fall back to the first-N-minutes cut. The IP is kept only as an HMAC +# (cloud/metering.ip_fingerprint) and rows older than the window are deleted. +FIRST_VIDEO_IP_WINDOW_DAYS = 30 # Minute cap DURING the trial (across all plans). Kept for grandfathered # 'trialing' subscriptions; removable once no subscription has status diff --git a/cloud/database.py b/cloud/database.py index 46c95eb..4a691da 100644 --- a/cloud/database.py +++ b/cloud/database.py @@ -18,6 +18,8 @@ _ADDITIVE_COLUMNS = ( "marketing_opt_out BOOLEAN NOT NULL DEFAULT false", # Nullable, no default: a catalog-only change, no table rewrite. "ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)", + # The per-network first-video check joins first_video_grants on job_id. + "CREATE INDEX IF NOT EXISTS ix_usage_job_id ON usage_ledger (job_id)", ) diff --git a/cloud/metering.py b/cloud/metering.py index c543335..b453be5 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -29,7 +29,7 @@ from decimal import Decimal from sqlalchemy import select, update, func, and_ from . import config, database -from .models import User, Subscription, CreditTopup, UsageLedger +from .models import User, Subscription, CreditTopup, UsageLedger, FirstVideoGrant SWEEP_INTERVAL_SECONDS = 15 * 60 @@ -456,6 +456,47 @@ async def has_processed_before(user_id) -> bool: return row is not None +def ip_fingerprint(ip) -> str: + """HMAC of a client IP (keyed on the app secret), or "" when unknown.""" + import hashlib + import hmac + if not ip or ip == "unknown": + return "" + key = (config.settings.jwt_secret or "openshorts").encode() + return hmac.new(key, f"ip:{ip}".encode(), hashlib.sha256).hexdigest() + + +async def ip_had_first_video(ip_hash: str) -> bool: + """True when this network already got a live first-video grant inside + ``FIRST_VIDEO_IP_WINDOW_DAYS``.""" + if not ip_hash: + return False + since = _now() - timedelta(days=config.FIRST_VIDEO_IP_WINDOW_DAYS) + async with database.session() as session: + row = (await session.execute( + select(FirstVideoGrant.id) + .join(UsageLedger, UsageLedger.job_id == FirstVideoGrant.job_id) + .where(and_( + FirstVideoGrant.ip_hash == ip_hash, + FirstVideoGrant.created_at >= since, + UsageLedger.status.in_(("reserved", "committed")), + )).limit(1) + )).first() + return row is not None + + +async def record_first_video(ip_hash: str, job_id: str): + """Remember a first-video grant for this network; prune expired rows.""" + if not ip_hash: + return + from sqlalchemy import delete + since = _now() - timedelta(days=config.FIRST_VIDEO_IP_WINDOW_DAYS) + async with database.session() as session: + async with session.begin(): + await session.execute(delete(FirstVideoGrant).where(FirstVideoGrant.created_at < since)) + session.add(FirstVideoGrant(ip_hash=ip_hash, job_id=job_id)) + + async def _topups_fifo(session, user_id): return list((await session.execute( select(CreditTopup).where(CreditTopup.user_id == user_id) diff --git a/cloud/models.py b/cloud/models.py index e91f16d..4831e62 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -112,6 +112,7 @@ class UsageLedger(Base): __table_args__ = ( Index("ix_usage_user_status", "user_id", "status"), Index("ix_usage_user_period_status", "user_id", "period_end", "status"), + Index("ix_usage_job_id", "job_id"), ) @@ -410,3 +411,19 @@ class LifecycleEmail(Base): __table_args__ = ( UniqueConstraint("user_id", "kind", name="uq_lifecycle_user_kind"), ) + + +class FirstVideoGrant(Base): + """One free first video clipped whole (app.free_overflow), by client IP. + + Keyed on an HMAC of the IP, not the IP, and deliberately NOT tied to the + user row: deleting an account must not hand its network a fresh grant. + Rows past ``FIRST_VIDEO_IP_WINDOW_DAYS`` are deleted on the next grant. + A grant only counts while its job's reservation is live, so a first video + that fails does not use up the network's grant. + """ + __tablename__ = "first_video_grants" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + ip_hash = Column(String(64), nullable=False, index=True) + job_id = Column(Text, nullable=False) + created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True) diff --git a/tests/test_partial_processing.py b/tests/test_partial_processing.py index afefdfa..5c1b79a 100644 --- a/tests/test_partial_processing.py +++ b/tests/test_partial_processing.py @@ -242,3 +242,21 @@ class TestCapSourceDuration: main.cap_source_duration(path, 3) assert os.path.getsize(path) == before assert 149 <= self._seconds(path) <= 151 + + +class TestFirstVideoIpFingerprint: + """The per-network limit keys on an HMAC of the IP, never the IP.""" + + def test_stable_and_not_the_ip(self, monkeypatch): + from cloud import metering + monkeypatch.setenv("JWT_SECRET", "s3cret") + a = metering.ip_fingerprint("203.0.113.7") + assert a == metering.ip_fingerprint("203.0.113.7") + assert "203.0.113.7" not in a and len(a) == 64 + assert a != metering.ip_fingerprint("203.0.113.8") + + def test_unknown_ip_has_no_fingerprint(self): + from cloud import metering + assert metering.ip_fingerprint("") == "" + assert metering.ip_fingerprint("unknown") == "" + assert metering.ip_fingerprint(None) == ""