sightbox/backend/billing/frappe_client.py

280 lines
11 KiB
Python

"""
frappe_client.py — the Frappe REST API wrapper, backend/'s one outbound
external dependency.
Authenticates as a single dedicated System Manager Frappe user via API
key/secret (env vars only, never hardcoded — see .env.example). Wraps every
call with a small inline CircuitBreaker per ENTERPRISE_STANDARDS.md's
resilience rule ("every external service call... gets a circuit breaker") —
kept inline here rather than in a separate utils/ module so backend/'s file
layout stays exactly the flat five files CLAUDE.md specifies; the class is
co-located with the one call site it protects.
"""
import json
import time
import requests
class FrappeAPIError(Exception):
"""Raised for any non-2xx response or network failure talking to Frappe. Never leaks raw response bodies upstream."""
def __init__(self, message, status_code=None):
super().__init__(message)
self.status_code = status_code
class CircuitOpenError(FrappeAPIError):
"""Raised when the circuit breaker is OPEN and a call is rejected without attempting the network."""
class _CircuitBreaker:
"""
Minimal three-state circuit breaker (CLOSED / OPEN / HALF_OPEN) guarding
calls to the Frappe API, per ENTERPRISE_STANDARDS.md's standard
thresholds: 3 consecutive failures opens the circuit, 60 second cooldown
before a half-open retry attempt.
"""
FAILURE_THRESHOLD = 3
COOLDOWN_SECONDS = 60
def __init__(self):
self._failure_count = 0
self._state = "CLOSED"
self._opened_at = None
def before_call(self):
"""Raises CircuitOpenError if calls are currently rejected; otherwise allows the call through (CLOSED or HALF_OPEN)."""
if self._state == "OPEN":
if time.monotonic() - self._opened_at >= self.COOLDOWN_SECONDS:
self._state = "HALF_OPEN"
else:
raise CircuitOpenError("Frappe API circuit breaker is open")
def on_success(self):
"""Resets the breaker to CLOSED after any successful call, including a HALF_OPEN probe."""
self._failure_count = 0
self._state = "CLOSED"
self._opened_at = None
def on_failure(self):
"""Counts a failure; opens the circuit once FAILURE_THRESHOLD consecutive failures are reached."""
self._failure_count += 1
if self._failure_count >= self.FAILURE_THRESHOLD:
self._state = "OPEN"
self._opened_at = time.monotonic()
@property
def state(self):
return self._state
LOCKOUT_ROLE = "Trial Expired"
"""
The Role billing.py swaps a User onto to lock them out. Deliberately not a
disabled account (enabled=0): a Role with desk_access unchecked still lets
someone log in, Frappe just refuses them Desk access and — via this Role's
home_page field — redirects them straight to the billing page instead of
any module. Confirmed live against this project's actual Frappe version:
frappe/core/doctype/user/user.py's has_desk_access() checks whether any of
a User's Roles have desk_access=1, and frappe/website/utils.py's
get_home_page() walks a user's Roles for the first non-empty home_page.
"""
class FrappeClient:
"""
Thin wrapper around the subset of Frappe's REST API billing.py needs:
finding lockable Users (with their current Roles) and swapping a
User's Roles to lock them out or restore them.
"""
def __init__(self, base_url, api_key, api_secret, timeout=10, circuit_breaker=None):
self.base_url = base_url.rstrip("/")
self._session = requests.Session()
self._session.headers.update(
{"Authorization": f"token {api_key}:{api_secret}"}
)
self._timeout = timeout
self._breaker = circuit_breaker or _CircuitBreaker()
self._own_username = None
def _request(self, method, path, **kwargs):
"""
Sends one HTTP request through the circuit breaker, translating any
failure into FrappeAPIError so callers never see a raw requests
exception or a raw response body.
Data flow:
method (str) — HTTP verb
path (str) — path relative to base_url
kwargs (dict) — passed through to requests (json, params, ...)
returns (dict) — parsed JSON body on success
Steps:
1. Reject immediately if the circuit is OPEN
2. Perform the request
3. Record success/failure on the breaker
4. Raise FrappeAPIError on any non-2xx status or network error
"""
# Step 1: circuit breaker gate
self._breaker.before_call()
url = f"{self.base_url}{path}"
try:
# Step 2: the actual network call
response = self._session.request(method, url, timeout=self._timeout, **kwargs)
except requests.RequestException as exc:
# Step 3/4: network-level failure counts against the breaker and surfaces as FrappeAPIError
self._breaker.on_failure()
raise FrappeAPIError(f"Frappe API request failed: {exc}") from exc
if response.status_code >= 400:
# Step 3/4: HTTP-level failure counts against the breaker and surfaces as FrappeAPIError
self._breaker.on_failure()
raise FrappeAPIError(
f"Frappe API returned {response.status_code} for {method} {path}",
status_code=response.status_code,
)
# Step 3: a clean response resets the breaker
self._breaker.on_success()
return response.json() if response.content else {}
def _get_own_username(self):
"""
Resolves and caches the Frappe username this client's own API
key/secret authenticates as, so list_enabled_users() can exclude it
the same way it excludes Administrator.
Why this matters: this client authenticates as one dedicated
System Manager User (per CLAUDE.md's billing design). If that
account is left out of nothing, disable_users() disables it along
with everyone else — which invalidates this client's own API
token mid-operation and turns every subsequent call in the same
request into a 401, cascading into a partial failure across the
rest of the list. Confirmed live during Stripe webhook testing:
exactly this happened before this exclusion existed.
"""
if self._own_username is None:
body = self._request("GET", "/api/method/frappe.auth.get_logged_user")
self._own_username = body["message"]
return self._own_username
def get_user_lock_state(self, username):
"""
Fetches everything about one User that lockout touches and restore
must put back exactly: their current Roles and default_workspace.
Why default_workspace matters as much as Roles: confirmed live and
the hard way — frappe/website/utils.py's get_home_page() computes
the right redirect from LOCKOUT_ROLE's home_page field, then
unconditionally *overwrites that result* if the User has a
default_workspace set (every staff User does, per Installation
Playbook Stage 8), sending a "locked-out" User straight back to
their old Desk workspace — which then 403s, since desk_access is
gone. Clearing default_workspace during lockout is what actually
makes the home_page redirect take effect; restoring it is what
gives the User their normal workspace back afterward.
Data flow:
username (str) — the Frappe User to read
returns (dict) — {"roles": [role, ...], "default_workspace": str | None}
"""
body = self._request("GET", f"/api/resource/User/{username}")
doc = body.get("data", {})
return {
"roles": [row["role"] for row in doc.get("roles", [])],
"default_workspace": doc.get("default_workspace") or None,
}
def lock_user(self, username):
"""
Locks one User out: swaps their Roles to just [LOCKOUT_ROLE] and
clears default_workspace, in one call — both are required for
LOCKOUT_ROLE's home_page redirect to actually take effect (see
get_user_lock_state's docstring).
Data flow:
username (str) — the Frappe User to lock out
returns (None)
"""
self._request(
"PUT",
f"/api/resource/User/{username}",
json={"roles": [{"role": LOCKOUT_ROLE}], "default_workspace": ""},
)
def restore_user(self, username, roles, default_workspace):
"""
Restores one User's exact pre-lockout Roles and default_workspace,
in one call.
Data flow:
username (str) — the Frappe User to restore
roles (list[str]) — their real Roles, from the stored snapshot
default_workspace (str|None) — their real default_workspace, from the snapshot
returns (None)
"""
self._request(
"PUT",
f"/api/resource/User/{username}",
json={
"roles": [{"role": role} for role in roles],
"default_workspace": default_workspace or "",
},
)
def list_lockable_users(self):
"""
Fetches every currently-enabled, not-already-locked-out User's
lock state (Roles + default_workspace), except Administrator and
this client's own service account.
Data flow:
returns (dict[str, dict]) — {username: {"roles": [...], "default_workspace": ...}},
exactly what billing.py needs to
snapshot before locking anyone out
Steps:
1. Resolve this client's own username (cached after first call)
2. GET /api/resource/User filtered to enabled=1, excluding
Administrator and this client's own account
3. Fetch each candidate's current lock state, skipping anyone
who already holds LOCKOUT_ROLE — already locked, and
including them here would overwrite their real stored state
with the lockout state they're currently wearing
"""
# Step 1: never lock out the account this client is authenticating as
own_username = self._get_own_username()
# Step 2: filter server-side so neither exclusion ever reaches the fetched list
params = {
"filters": json.dumps([["enabled", "=", 1], ["name", "not in", ["Administrator", own_username]]]),
"fields": '["name"]',
"limit_page_length": 0,
}
body = self._request("GET", "/api/resource/User", params=params)
usernames = [row["name"] for row in body.get("data", [])]
# Step 3: only users not already locked out are eligible to be (re-)snapshotted
lockable = {}
for username in usernames:
state = self.get_user_lock_state(username)
if LOCKOUT_ROLE not in state["roles"]:
lockable[username] = state
return lockable
def ping(self):
"""
Lightweight reachability check for GET /health. Returns True if the
Frappe API responded, False on any FrappeAPIError (including an open
circuit breaker) rather than raising.
"""
try:
self._request("GET", "/api/resource/User", params={"limit_page_length": 1})
return True
except FrappeAPIError:
return False