"""Traffic switch for merchant code: send a payment to the incumbent provider or to Knox. Assignment is sticky: the same key (customer id or order id) always gets the same arm for a given ramp salt and share. When an expired ramp cannot be read, new payments go to the incumbent; existing attempts retain their owner. Outcomes from both arms are reported to Knox in batches so the arms are compared with the same measurements. switch = KnoxSwitch(api_base="https://meta.knoxapi.com", secret_key=os.environ["KNOX_SECRET_KEY"]) arm = switch.arm_for(customer_id) # "knox" or "incumbent" started = time.monotonic() ...charge through that arm... switch.record(arm, "authorized", started, amount=2000, currency="usd") """ import hashlib import math import threading import time import httpx BUCKETS = 10_000 MAX_BATCH = 500 # Meta observation API limit def bucket(salt: str, key: str) -> int: return int.from_bytes(hashlib.sha256(f"{salt}:{key}".encode()).digest()[:8], "big") % BUCKETS def assign(salt: str, key: str, share_percent: float) -> str: return "knox" if bucket(salt, key) < round(share_percent * BUCKETS / 100) else "incumbent" class KnoxSwitch: def __init__(self, api_base: str, secret_key: str, ramp_ttl: float = 60.0, batch_size: int = 50, http: httpx.Client | None = None, control_prefix: str = "/v1", timeout: float = 5.0): self.api_base = api_base.rstrip("/") + "/" + control_prefix.strip("/") self.http = http or httpx.Client(timeout=5) self._headers = {"Authorization": f"Bearer {secret_key}"} self.timeout = timeout self.ramp_ttl, self.batch_size = ramp_ttl, batch_size self._ramp: dict | None = None self._fetched_at: float | None = None self._pending: list[dict] = [] self._lock = threading.Lock() self._ramp_lock = threading.Lock() def ramp(self) -> dict | None: with self._ramp_lock: if self._fetched_at is None or time.monotonic() - self._fetched_at >= self.ramp_ttl: try: response = self.http.get(f"{self.api_base}/traffic/ramp", headers=self._headers, timeout=self.timeout) response.raise_for_status() ramp = response.json() share = ramp.get("share_percent") if isinstance(ramp, dict) else None if (not isinstance(ramp, dict) or ramp.get("state") not in ("running", "paused") or not isinstance(ramp.get("salt"), str) or not ramp["salt"] or type(share) not in (int, float) or not math.isfinite(share) or not 0 <= share <= 100): raise ValueError("Invalid migration control state") self._ramp = ramp except (httpx.HTTPError, ValueError, TypeError): self._ramp = None # an expired running ramp cannot authorize new assignments self._fetched_at = time.monotonic() return self._ramp def arm_for(self, key: str, existing_arm: str | None = None) -> str: if existing_arm is not None: if existing_arm not in ("incumbent", "knox"): raise ValueError("Unknown existing payment owner") return existing_arm # caller persists this with the payment attempt, before its provider call ramp = self.ramp() if ramp is None or ramp.get("state") != "running": return "incumbent" return assign(ramp["salt"], key, ramp["share_percent"]) def record(self, arm: str, outcome: str, started_monotonic: float, decline_code: str | None = None, amount: int | None = None, currency: str | None = None) -> None: observation = {"arm": arm, "outcome": outcome, "latency_ms": int((time.monotonic() - started_monotonic) * 1000), "observed_at": int(time.time()), "decline_code": decline_code, "amount": amount, "currency": currency} with self._lock: self._pending.append(observation) ready = len(self._pending) >= self.batch_size if ready: self.flush() def flush(self) -> int: with self._lock: batch, self._pending = self._pending[:MAX_BATCH], self._pending[MAX_BATCH:] if not batch: return 0 try: self.http.post(f"{self.api_base}/traffic/observations", headers=self._headers, json={"observations": batch}, timeout=self.timeout).raise_for_status() except httpx.HTTPError: with self._lock: self._pending = batch + self._pending # retry on the next flush return 0 return len(batch)