Source code for fleetmesh_node.protocols.atproto.metering

"""Bilateral budgeting, rate limiting, and Cashu NUT-24 paid fetch for ATProto.

Standard library only. Manages:
- Token-bucket rate limiting per client IP or authenticated DID.
- Cashu NUT-18 / NUT-24 402 Payment Required challenges for heavy sync requests
  (getRepo, getBlob, subscribeRepos).
- Token deposit parsing and validation via fleetmesh_core.accounting.cashu.
- Bilateral peering capacity tracking between federating nodes.
"""
from __future__ import annotations

import time
from typing import Mapping, Optional

from fleetmesh_core.accounting import cashu
from fleetmesh_core.conformance.errors import FleetmeshError

__all__ = [
    'MeteringError',
    'TokenBucket',
    'AtprotoMetering',
]


[docs]class MeteringError(FleetmeshError): """Base error for ATProto metering and payment checks."""
[docs]class TokenBucket: """Standard token-bucket rate limiter.""" __slots__ = ('capacity', 'refill_rate', 'tokens', 'last_refill')
[docs] def __init__(self, capacity: float, refill_rate: float): self.capacity = float(capacity) self.refill_rate = float(refill_rate) self.tokens = float(capacity) self.last_refill = time.time()
[docs] def consume(self, amount: float = 1.0) -> bool: """Attempt to consume tokens. Returns True if allowed, False if dry.""" now = time.time() elapsed = now - self.last_refill self.last_refill = now self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate) if self.tokens >= amount: self.tokens -= amount return True return False
[docs]class AtprotoMetering: """Enforces rate limits and ecash settlement over XRPC and Firehose edges."""
[docs] def __init__( self, rate_limit_per_minute: int = 60, burst: int = 15, price_per_fetch_sat: int = 1, mint_url: Optional[str] = None, require_payment: bool = False, ): self.rate_limit_per_minute = rate_limit_per_minute self.burst = burst self.price_per_fetch_sat = price_per_fetch_sat if require_payment and not mint_url: raise ValueError('atproto metering: require_payment needs a mint_url') self.mint_url: Optional[str] = mint_url.rstrip('/') if mint_url else None self.require_payment = require_payment self._buckets: dict[str, TokenBucket] = {} self._balances_sat: dict[str, int] = {} self._paid_endpoints: set[str] = { 'com.atproto.sync.getRepo', 'com.atproto.sync.getBlob', 'com.atproto.sync.subscribeRepos', }
def _get_bucket(self, client_id: str) -> TokenBucket: if client_id not in self._buckets: refill_per_sec = self.rate_limit_per_minute / 60.0 self._buckets[client_id] = TokenBucket(capacity=self.burst, refill_rate=refill_per_sec) return self._buckets[client_id]
[docs] def deposit_cashu_token(self, client_id: str, token_str: str) -> int: """Parse and credit a Cashu V3 (cashuA) or V4 (cashuB) token to client's balance.""" token_str = token_str.strip() total_sat = 0 if token_str.startswith(cashu.TOKEN_V4_PREFIX): try: tok = cashu.decode_token_v4(token_str) total_sat = sum(p.get('amount', 0) for p in tok.get('proofs', [])) except Exception as e: raise MeteringError(f"invalid Cashu V4 token: {e}") from e elif token_str.startswith('cashuA'): try: import base64 import json raw_json = base64.urlsafe_b64decode(token_str[6:] + '==').decode('utf-8') tok = json.loads(raw_json) for entry in tok.get('token', []): for p in entry.get('proofs', []): total_sat += p.get('amount', 0) except Exception as e: raise MeteringError(f"invalid Cashu V3 token: {e}") from e else: raise MeteringError("unsupported Cashu token format") if total_sat <= 0: raise MeteringError("token carries zero satoshis") self._balances_sat[client_id] = self._balances_sat.get(client_id, 0) + total_sat return total_sat
[docs] def get_balance(self, client_id: str) -> int: """Return the current satoshi balance for a client.""" return self._balances_sat.get(client_id, 0)
[docs] def check_request( self, client_id: str, nsid: str, headers: Mapping[str, str], ) -> tuple[bool, int, dict[str, str], Optional[bytes]]: """Evaluate rate limits and payment requirements for an incoming request. Returns (allowed, status_code, response_headers, response_body). """ # 1. Process in-band ecash payment header if present (X-Cashu or Authorization) token_header = headers.get('x-cashu') or headers.get('X-Cashu') if not token_header and 'authorization' in headers: auth_val = headers['authorization'] if auth_val.startswith('Bearer cashu'): token_header = auth_val[len('Bearer '):].strip() if token_header: try: self.deposit_cashu_token(client_id, token_header) except Exception: pass # 2. Token-bucket rate limiting check bucket = self._get_bucket(client_id) if not bucket.consume(1.0): body = b'{"error":"RateLimitExceeded","message":"Too many requests"}' return False, 429, {'Retry-After': '10', 'Content-Type': 'application/json'}, body # 3. Paid fetch check for designated endpoints if self.require_payment and nsid in self._paid_endpoints: current_bal = self.get_balance(client_id) if current_bal >= self.price_per_fetch_sat: # Deduct payment self._balances_sat[client_id] = current_bal - self.price_per_fetch_sat return True, 200, {}, None # Insufficient funds: produce HTTP 402 challenge pay_req = f"creqA_{self.mint_url}_{self.price_per_fetch_sat}sat" resp_hdrs = { 'X-Cashu': pay_req, 'Content-Type': 'application/json', } body = b'{"error":"PaymentRequired","message":"Resource requires Cashu ecash payment"}' return False, 402, resp_hdrs, body return True, 200, {}, None