"""Read the tenant's durable monthly browser spend and enforce its limit.""" import datetime as dt from decimal import Decimal import re from core.logins import read_bucket KEY = "login_budget" LIMIT_USD = Decimal("25") class LoginBudgetUnavailable(RuntimeError): """The browser spend meter could not be read.""" class LoginBudgetExceeded(PermissionError): """The tenant has reached its monthly browser spend limit.""" def month_key(now=None): now = now or dt.datetime.now(dt.timezone.utc) if now.tzinfo is None: raise LoginBudgetUnavailable("The browser spend meter is unavailable.") return now.astimezone(dt.timezone.utc).strftime("%Y-%m") def report(rt, *, now=None): """Report validated monthly spend even after admission reaches the cap.""" try: month = month_key(now) bucket = read_bucket(rt, KEY) months, holds = _validated(bucket) spent = _decimal(months.get(month, "0")) held = sum((_decimal(row["remaining_usd"]) for row in holds.values() if row["month"] == month), Decimal(0)) except Exception: raise LoginBudgetUnavailable("The browser spend meter is unavailable.") from None return {"month": month, "spent_usd": float(spent), "limit_usd": float(LIMIT_USD), "held_usd": float(held), "remaining_usd": float(max(Decimal("0"), LIMIT_USD - spent - held))} def meter(rt, *, now=None, reservation_id=None): """Refuse a new run at $25 or when the strict spend read fails.""" reading = report(rt, now=now) if reservation_id is not None: _, holds = _validated(read_bucket(rt, KEY)) own = holds.get(reservation_id) if not own or own["month"] != reading["month"]: raise LoginBudgetUnavailable("budget_unavailable") reading["remaining_usd"] += float(_decimal(own["remaining_usd"])) if reading["remaining_usd"] <= 0: raise LoginBudgetExceeded("This tenant has reached its $25 monthly browser limit.") return reading def _decimal(value): if isinstance(value, bool) or not isinstance(value, (int, float, str, Decimal)): raise LoginBudgetUnavailable("budget_unavailable") try: amount = Decimal(str(value)) if not amount.is_finite() or amount < 0 or not Decimal(str(float(amount))).is_finite(): raise ValueError() return amount except Exception: raise LoginBudgetUnavailable("budget_unavailable") from None def _validated(bucket): if not isinstance(bucket, dict) or (bucket and "months" not in bucket): raise LoginBudgetUnavailable("budget_unavailable") months, holds = bucket.get("months", {}), bucket.get("holds", {}) if not isinstance(months, dict) or not isinstance(holds, dict): raise LoginBudgetUnavailable("budget_unavailable") for month, value in months.items(): if not isinstance(month, str) or not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", month): raise LoginBudgetUnavailable("budget_unavailable") _decimal(value) for hid, row in holds.items(): if (not isinstance(hid, str) or not re.fullmatch(r"login_run_[a-f0-9]{24}", hid) or not isinstance(row, dict) or set(row) != {"month", "bound_usd", "remaining_usd", "charges"} or not isinstance(row["month"], str) or not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", row["month"]) or not isinstance(row["charges"], dict)): raise LoginBudgetUnavailable("budget_unavailable") bound, remaining = _decimal(row["bound_usd"]), _decimal(row["remaining_usd"]) if bound <= 0 or bound > LIMIT_USD or remaining > bound: raise LoginBudgetUnavailable("budget_unavailable") for cid, cost in row["charges"].items(): if not isinstance(cid, str) or not re.fullmatch(r"charge_[a-f0-9]{24}", cid): raise LoginBudgetUnavailable("budget_unavailable") _decimal(cost) paid = sum((_decimal(cost) for cost in row["charges"].values()), Decimal(0)) if remaining != max(Decimal(0), bound - paid): raise LoginBudgetUnavailable("budget_unavailable") return months, holds def _update(rt, fn): try: _validated(read_bucket(rt, KEY)) return rt.update(KEY, fn, flush="sync") except (LoginBudgetExceeded, LoginBudgetUnavailable): raise except Exception: raise LoginBudgetUnavailable("budget_unavailable") from None def reserve(rt, reservation_id, bound_usd, *, now=None): """Atomically reserve a known run bound before browser or paid work.""" month, bound = month_key(now), _decimal(bound_usd) row = {"month": month, "bound_usd": str(bound), "remaining_usd": str(bound), "charges": {}} _validated({"months": {}, "holds": {reservation_id: row}}) def change(cur): months, holds = _validated(cur) if reservation_id in holds: if holds[reservation_id] == row: return cur raise LoginBudgetUnavailable("budget_unavailable") used = _decimal(months.get(month, "0")) used += sum((_decimal(h["remaining_usd"]) for h in holds.values() if h["month"] == month), Decimal(0)) if used + bound > LIMIT_USD: raise LoginBudgetExceeded("budget_exceeded") cur.setdefault("months", {}) cur.setdefault("holds", {})[reservation_id] = dict(row) return cur saved = _update(rt, change) if saved.get("holds", {}).get(reservation_id) != row: raise LoginBudgetUnavailable("budget_unavailable") def charge(rt, reservation_id, charge_id, measured_usd): """Book measured usage once and reduce the matching hold atomically.""" amount = _decimal(measured_usd) if not isinstance(charge_id, str) or not re.fullmatch(r"charge_[a-f0-9]{24}", charge_id): raise LoginBudgetUnavailable("budget_unavailable") def change(cur): months, holds = _validated(cur) row = holds.get(reservation_id) if not row: raise LoginBudgetUnavailable("budget_unavailable") if charge_id in row["charges"]: if _decimal(row["charges"][charge_id]) == amount: return cur raise LoginBudgetUnavailable("budget_unavailable") month = row["month"] months[month] = str(_decimal(months.get(month, "0")) + amount) row["charges"][charge_id] = str(amount) row["remaining_usd"] = str(max(Decimal(0), _decimal(row["remaining_usd"]) - amount)) return cur saved = _update(rt, change) if saved.get("holds", {}).get(reservation_id, {}).get("charges", {}).get(charge_id) != str(amount): raise LoginBudgetUnavailable("budget_unavailable") def release(rt, reservation_id): """Release unused admission credit without inventing measured spend.""" def change(cur): _, holds = _validated(cur) holds.pop(reservation_id, None) return cur saved = _update(rt, change) if reservation_id in saved.get("holds", {}): raise LoginBudgetUnavailable("budget_unavailable")