feat(free-plan): one whole first video per network every 30 days
A stack of Google accounts from one IP used to get a 60-minute first video each. first_video_grants keeps an HMAC of the client IP (never the IP), not tied to the user row, counting only grants whose reservation is live; a network that already had one gets the first-N-minutes cut instead.
This commit is contained in:
parent
c7dab3dbf4
commit
9837228365
7 changed files with 101 additions and 2 deletions
|
|
@ -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
|
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
|
cap (`SOURCE_CAP_MINUTES`) is the probed length, not the reservation. Once
|
||||||
per account: `metering.has_processed_before` (any reserved/committed
|
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
|
carries `first_video: true`; the dashboard says so and tracks
|
||||||
`FirstVideoGrant`.
|
`FirstVideoGrant`.
|
||||||
- **Anything else:** `max_minutes` becomes the balance, so the job clips the
|
- **Anything else:** `max_minutes` becomes the balance, so the job clips the
|
||||||
|
|
|
||||||
12
app.py
12
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
|
# FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is
|
||||||
# clipped to the first N minutes. Neither sees the wall.
|
# clipped to the first N minutes. Neither sees the wall.
|
||||||
grant = None
|
grant = None
|
||||||
|
ip_hash = ""
|
||||||
if balance.get("plan") == "free" and minutes > balance["remaining"] and max_minutes is None:
|
if balance.get("plan") == "free" and minutes > balance["remaining"] and max_minutes is None:
|
||||||
processed_before = await _metering.has_processed_before(user.id)
|
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"],
|
grant, max_minutes = free_overflow("free", minutes, balance["remaining"],
|
||||||
max_minutes, processed_before)
|
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.
|
# 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.reserved_minutes = minutes if grant is not None else reserve
|
||||||
request.state.first_video = grant is not None
|
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:
|
except _metering.QuotaExceeded as e:
|
||||||
_maybe_send_quota_email(user)
|
_maybe_send_quota_email(user)
|
||||||
raise HTTPException(status_code=402, detail={
|
raise HTTPException(status_code=402, detail={
|
||||||
|
|
|
||||||
|
|
@ -98,6 +98,11 @@ PARTIAL_MIN_MINUTES = 5
|
||||||
# the first N minutes automatically instead of hitting the wall.
|
# the first N minutes automatically instead of hitting the wall.
|
||||||
# 0 disables the grant.
|
# 0 disables the grant.
|
||||||
FIRST_VIDEO_MAX_MINUTES = 60
|
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
|
# Minute cap DURING the trial (across all plans). Kept for grandfathered
|
||||||
# 'trialing' subscriptions; removable once no subscription has status
|
# 'trialing' subscriptions; removable once no subscription has status
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,8 @@ _ADDITIVE_COLUMNS = (
|
||||||
"marketing_opt_out BOOLEAN NOT NULL DEFAULT false",
|
"marketing_opt_out BOOLEAN NOT NULL DEFAULT false",
|
||||||
# Nullable, no default: a catalog-only change, no table rewrite.
|
# Nullable, no default: a catalog-only change, no table rewrite.
|
||||||
"ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)",
|
"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)",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ from decimal import Decimal
|
||||||
from sqlalchemy import select, update, func, and_
|
from sqlalchemy import select, update, func, and_
|
||||||
|
|
||||||
from . import config, database
|
from . import config, database
|
||||||
from .models import User, Subscription, CreditTopup, UsageLedger
|
from .models import User, Subscription, CreditTopup, UsageLedger, FirstVideoGrant
|
||||||
|
|
||||||
|
|
||||||
SWEEP_INTERVAL_SECONDS = 15 * 60
|
SWEEP_INTERVAL_SECONDS = 15 * 60
|
||||||
|
|
@ -456,6 +456,47 @@ async def has_processed_before(user_id) -> bool:
|
||||||
return row is not None
|
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):
|
async def _topups_fifo(session, user_id):
|
||||||
return list((await session.execute(
|
return list((await session.execute(
|
||||||
select(CreditTopup).where(CreditTopup.user_id == user_id)
|
select(CreditTopup).where(CreditTopup.user_id == user_id)
|
||||||
|
|
|
||||||
|
|
@ -112,6 +112,7 @@ class UsageLedger(Base):
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index("ix_usage_user_status", "user_id", "status"),
|
Index("ix_usage_user_status", "user_id", "status"),
|
||||||
Index("ix_usage_user_period_status", "user_id", "period_end", "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__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint("user_id", "kind", name="uq_lifecycle_user_kind"),
|
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)
|
||||||
|
|
|
||||||
|
|
@ -242,3 +242,21 @@ class TestCapSourceDuration:
|
||||||
main.cap_source_duration(path, 3)
|
main.cap_source_duration(path, 3)
|
||||||
assert os.path.getsize(path) == before
|
assert os.path.getsize(path) == before
|
||||||
assert 149 <= self._seconds(path) <= 151
|
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) == ""
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue