techindro commited on
Commit
6f62011
·
verified ·
1 Parent(s): 8eb9cf4

Upload 2 files

Browse files
Files changed (2) hide show
  1. config.py +52 -0
  2. main.py +425 -0
config.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Papaya configuration.
2
+
3
+ All PayPal credentials come from environment variables. Nothing secret is
4
+ stored in the code base. Papaya talks to the PayPal *Sandbox* only.
5
+
6
+ Required environment variables
7
+ PAYPAL_CLIENT_ID Sandbox app client id
8
+ PAYPAL_CLIENT_SECRET Sandbox app secret
9
+
10
+ Optional environment variables
11
+ PAYPAL_VAULT_ID Vaulted PayPal payment token. When set, orders are
12
+ created against this stored payment source so no
13
+ buyer approval page is needed.
14
+ PAPAYA_API_KEY If set, POST /pay requires an `X-API-Key` header.
15
+ PAPAYA_MAX_CHARGE Hard cap per charge (default 5.00).
16
+ PAPAYA_CURRENCY ISO currency code (default USD).
17
+ """
18
+
19
+ import os
20
+ from decimal import Decimal
21
+ from pathlib import Path
22
+
23
+ # --- PayPal (Sandbox only) -------------------------------------------------
24
+ PAYPAL_BASE_URL = "https://api-m.sandbox.paypal.com"
25
+ PAYPAL_CLIENT_ID = os.getenv("PAYPAL_CLIENT_ID", "")
26
+ PAYPAL_CLIENT_SECRET = os.getenv("PAYPAL_CLIENT_SECRET", "")
27
+ PAYPAL_VAULT_ID = os.getenv("PAYPAL_VAULT_ID", "")
28
+
29
+ # --- Networking ------------------------------------------------------------
30
+ REQUEST_TIMEOUT_SECONDS = 10
31
+ TOKEN_REFRESH_MARGIN_SECONDS = 60 # refresh the token this long before expiry
32
+
33
+ # --- Pricing (all values in CURRENCY) --------------------------------------
34
+ CURRENCY = os.getenv("PAPAYA_CURRENCY", "USD")
35
+ CPU_RATE_PER_SECOND = Decimal("0.002") # price of 100% CPU for one second
36
+ TOKEN_RATE_PER_1K = Decimal("0.01") # price per 1,000 data tokens
37
+ MIN_CHARGE = Decimal("0.01") # PayPal minimum is 0.01
38
+ MAX_CHARGE = Decimal(os.getenv("PAPAYA_MAX_CHARGE", "5.00"))
39
+
40
+ # --- Access control --------------------------------------------------------
41
+ PAPAYA_API_KEY = os.getenv("PAPAYA_API_KEY", "")
42
+
43
+ # --- Logs and history ------------------------------------------------------
44
+ LOG_DIR = Path(os.getenv("PAPAYA_LOG_DIR", "logs"))
45
+ LOG_FILE = LOG_DIR / "node_logs.txt"
46
+ MAX_LOG_LINES = 500
47
+ MAX_TRANSACTIONS = 500
48
+
49
+
50
+ def paypal_configured() -> bool:
51
+ """True when both Sandbox credentials are present."""
52
+ return bool(PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET)
main.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Papaya backend (FastAPI).
2
+
3
+ Flow: telemetry -> validation -> pricing -> OAuth token -> PayPal Sandbox
4
+ order -> capture -> log.
5
+
6
+ Run from the project root:
7
+ uvicorn backend.main:app --reload
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hmac
13
+ import threading
14
+ import time
15
+ import uuid
16
+ from collections import deque
17
+ from datetime import datetime, timezone
18
+ from decimal import ROUND_HALF_UP, Decimal
19
+ from typing import Any
20
+
21
+ import numpy as np
22
+ import psutil
23
+ import requests
24
+ from fastapi import Depends, FastAPI, Header, HTTPException, Query
25
+ from pydantic import BaseModel, Field
26
+
27
+ from backend import config
28
+
29
+ app = FastAPI(
30
+ title="Papaya",
31
+ description="Automated payment layer for servers and AI nodes (PayPal Sandbox).",
32
+ version="1.0.0",
33
+ )
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Data models (Pydantic rejects broken or unexpected input)
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ class TelemetryPayload(BaseModel):
41
+ """Workload reported by one node for one billing window."""
42
+
43
+ model_config = {"extra": "forbid"}
44
+
45
+ node_id: str = Field(..., pattern=r"^[A-Za-z0-9_.-]{1,64}$")
46
+ cpu_percent: float = Field(..., ge=0, le=100)
47
+ tokens: int = Field(0, ge=0, le=10_000_000)
48
+ duration_seconds: float = Field(..., gt=0, le=3600)
49
+ memory_percent: float | None = Field(None, ge=0, le=100)
50
+
51
+
52
+ class PriceBreakdown(BaseModel):
53
+ cpu_cost: str
54
+ token_cost: str
55
+ total: str
56
+ currency: str
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # In-memory history + text logs ("Sovereign Node Logs")
61
+ # ---------------------------------------------------------------------------
62
+
63
+ _lock = threading.Lock()
64
+ _logs: deque[str] = deque(maxlen=config.MAX_LOG_LINES)
65
+ _transactions: deque[dict[str, Any]] = deque(maxlen=config.MAX_TRANSACTIONS)
66
+
67
+
68
+ def _now() -> str:
69
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
70
+
71
+
72
+ def log(level: str, message: str) -> None:
73
+ """Append a line to the in-memory log and (best effort) to a text file.
74
+
75
+ Never pass secrets or tokens into this function.
76
+ """
77
+ line = f"[{_now()}] {level.upper():<7} {message}"
78
+ with _lock:
79
+ _logs.append(line)
80
+ try:
81
+ config.LOG_DIR.mkdir(parents=True, exist_ok=True)
82
+ with config.LOG_FILE.open("a", encoding="utf-8") as fh:
83
+ fh.write(line + "\n")
84
+ except OSError:
85
+ pass # logging must never break the request
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Analytical Modeler (pricing)
90
+ # ---------------------------------------------------------------------------
91
+
92
+
93
+ def _money(value: Decimal) -> Decimal:
94
+ return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
95
+
96
+
97
+ def price_workload(p: TelemetryPayload) -> tuple[Decimal, PriceBreakdown]:
98
+ """Turn CPU load, time and data tokens into a price."""
99
+ cpu_cost = (
100
+ Decimal(str(p.cpu_percent)) / Decimal(100)
101
+ * Decimal(str(p.duration_seconds))
102
+ * config.CPU_RATE_PER_SECOND
103
+ )
104
+ token_cost = Decimal(p.tokens) / Decimal(1000) * config.TOKEN_RATE_PER_1K
105
+ total = max(_money(cpu_cost + token_cost), config.MIN_CHARGE)
106
+ breakdown = PriceBreakdown(
107
+ cpu_cost=f"{cpu_cost:.6f}",
108
+ token_cost=f"{token_cost:.6f}",
109
+ total=f"{total:.2f}",
110
+ currency=config.CURRENCY,
111
+ )
112
+ return total, breakdown
113
+
114
+
115
+ # ---------------------------------------------------------------------------
116
+ # PayPal Sandbox client (OAuth 2.0 + Orders v2)
117
+ # ---------------------------------------------------------------------------
118
+
119
+
120
+ class PayPalUnavailable(Exception):
121
+ """Network problem: timeout, DNS failure, connection refused..."""
122
+
123
+
124
+ class PayPalError(Exception):
125
+ """PayPal answered with an error status."""
126
+
127
+ def __init__(self, status_code: int, message: str) -> None:
128
+ super().__init__(message)
129
+ self.status_code = status_code
130
+ self.message = message
131
+
132
+
133
+ def _error_message(resp: requests.Response) -> str:
134
+ try:
135
+ data = resp.json()
136
+ return str(data.get("message") or data.get("error_description") or data)[:300]
137
+ except ValueError:
138
+ return resp.text[:300]
139
+
140
+
141
+ class _TokenCache:
142
+ """Caches the OAuth token and refreshes it shortly before it expires."""
143
+
144
+ def __init__(self) -> None:
145
+ self._lock = threading.Lock()
146
+ self._token: str | None = None
147
+ self._expires_at = 0.0
148
+
149
+ def get(self, force: bool = False) -> str:
150
+ with self._lock:
151
+ stale = time.time() >= self._expires_at - config.TOKEN_REFRESH_MARGIN_SECONDS
152
+ if force or not self._token or stale:
153
+ self._fetch()
154
+ assert self._token is not None
155
+ return self._token
156
+
157
+ def _fetch(self) -> None:
158
+ try:
159
+ resp = requests.post(
160
+ f"{config.PAYPAL_BASE_URL}/v1/oauth2/token",
161
+ auth=(config.PAYPAL_CLIENT_ID, config.PAYPAL_CLIENT_SECRET),
162
+ data={"grant_type": "client_credentials"},
163
+ headers={"Accept": "application/json"},
164
+ timeout=config.REQUEST_TIMEOUT_SECONDS,
165
+ )
166
+ except requests.RequestException as exc:
167
+ raise PayPalUnavailable(f"token request failed: {exc}") from exc
168
+ if resp.status_code >= 400:
169
+ raise PayPalError(resp.status_code, f"token request rejected: {_error_message(resp)}")
170
+ data = resp.json()
171
+ self._token = data["access_token"]
172
+ self._expires_at = time.time() + int(data.get("expires_in", 300))
173
+ log("info", "PayPal access token refreshed")
174
+
175
+ def clear(self) -> None:
176
+ with self._lock:
177
+ self._token = None
178
+ self._expires_at = 0.0
179
+
180
+
181
+ _tokens = _TokenCache()
182
+
183
+
184
+ def _paypal_call(
185
+ method: str, path: str, payload: dict | None = None, request_id: str | None = None
186
+ ) -> dict:
187
+ """Call PayPal. Retries once with a fresh token if the old one was rejected."""
188
+ resp: requests.Response | None = None
189
+ for attempt in (0, 1):
190
+ token = _tokens.get(force=attempt == 1)
191
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
192
+ if request_id:
193
+ headers["PayPal-Request-Id"] = request_id # idempotency key
194
+ try:
195
+ resp = requests.request(
196
+ method,
197
+ f"{config.PAYPAL_BASE_URL}{path}",
198
+ json=payload,
199
+ headers=headers,
200
+ timeout=config.REQUEST_TIMEOUT_SECONDS,
201
+ )
202
+ except requests.RequestException as exc:
203
+ raise PayPalUnavailable(f"{method} {path} failed: {exc}") from exc
204
+ if resp.status_code == 401 and attempt == 0:
205
+ continue
206
+ break
207
+ assert resp is not None
208
+ if resp.status_code >= 400:
209
+ raise PayPalError(resp.status_code, _error_message(resp))
210
+ return resp.json() if resp.content else {}
211
+
212
+
213
+ def _create_order(node_id: str, amount: Decimal, request_id: str) -> dict:
214
+ body: dict[str, Any] = {
215
+ "intent": "CAPTURE",
216
+ "purchase_units": [
217
+ {
218
+ "reference_id": node_id,
219
+ "description": f"Papaya compute usage for node {node_id}",
220
+ "amount": {"currency_code": config.CURRENCY, "value": f"{amount:.2f}"},
221
+ }
222
+ ],
223
+ }
224
+ if config.PAYPAL_VAULT_ID:
225
+ # Stored payment source: lets the merchant charge without a buyer page.
226
+ body["payment_source"] = {
227
+ "paypal": {
228
+ "vault_id": config.PAYPAL_VAULT_ID,
229
+ "stored_credential": {
230
+ "payment_initiator": "MERCHANT",
231
+ "payment_type": "UNSCHEDULED",
232
+ "usage": "SUBSEQUENT",
233
+ },
234
+ }
235
+ }
236
+ return _paypal_call("POST", "/v2/checkout/orders", body, request_id)
237
+
238
+
239
+ def _capture_order(order_id: str, request_id: str) -> dict:
240
+ return _paypal_call("POST", f"/v2/checkout/orders/{order_id}/capture", {}, request_id)
241
+
242
+
243
+ def _capture_id(order: dict) -> str | None:
244
+ try:
245
+ return order["purchase_units"][0]["payments"]["captures"][0]["id"]
246
+ except (KeyError, IndexError, TypeError):
247
+ return None
248
+
249
+
250
+ def _approval_url(order: dict) -> str | None:
251
+ for link in order.get("links", []):
252
+ if link.get("rel") in ("payer-action", "approve"):
253
+ return link.get("href")
254
+ return None
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # Payment orchestration
259
+ # ---------------------------------------------------------------------------
260
+
261
+
262
+ def process_payment(payload: TelemetryPayload) -> dict[str, Any]:
263
+ """Price the workload, then try to pay it. Never raises on network errors."""
264
+ amount, breakdown = price_workload(payload)
265
+ record: dict[str, Any] = {
266
+ "id": uuid.uuid4().hex[:12],
267
+ "timestamp": _now(),
268
+ "node_id": payload.node_id,
269
+ "cpu_percent": payload.cpu_percent,
270
+ "tokens": payload.tokens,
271
+ "duration_seconds": payload.duration_seconds,
272
+ "amount": f"{amount:.2f}",
273
+ "currency": config.CURRENCY,
274
+ "breakdown": breakdown.model_dump(),
275
+ "mode": "paypal_sandbox",
276
+ "status": "PENDING",
277
+ "order_id": None,
278
+ "capture_id": None,
279
+ "approval_url": None,
280
+ "detail": "",
281
+ }
282
+
283
+ if amount > config.MAX_CHARGE:
284
+ record.update(
285
+ mode="none",
286
+ status="REJECTED",
287
+ detail=f"Charge {amount:.2f} exceeds the per-call cap of {config.MAX_CHARGE:.2f}",
288
+ )
289
+ log("warning", f"node={payload.node_id} rejected: {record['detail']}")
290
+ return _store(record)
291
+
292
+ if not config.paypal_configured():
293
+ record.update(
294
+ mode="local_fallback",
295
+ status="LOCAL_ONLY",
296
+ detail="PayPal credentials not set; price calculated locally, no payment made",
297
+ )
298
+ log("warning", f"node={payload.node_id} local fallback amount={record['amount']}")
299
+ return _store(record)
300
+
301
+ request_id = uuid.uuid4().hex
302
+ try:
303
+ order = _create_order(payload.node_id, amount, request_id)
304
+ record["order_id"] = order.get("id")
305
+ status = order.get("status", "UNKNOWN")
306
+ log("info", f"node={payload.node_id} order {record['order_id']} status={status}")
307
+
308
+ if status == "APPROVED":
309
+ order = _capture_order(order["id"], request_id + "-cap")
310
+ status = order.get("status", "UNKNOWN")
311
+
312
+ record["status"] = status
313
+ record["capture_id"] = _capture_id(order)
314
+ if status == "COMPLETED":
315
+ record["detail"] = "Payment captured"
316
+ log("info", f"node={payload.node_id} captured {record['amount']} {config.CURRENCY}")
317
+ else:
318
+ record["approval_url"] = _approval_url(order)
319
+ record["detail"] = (
320
+ "Order created but the payment source has not approved it yet. "
321
+ "Set PAYPAL_VAULT_ID to charge a stored payment source without a buyer page."
322
+ )
323
+ log("warning", f"node={payload.node_id} order not completed (status={status})")
324
+ except PayPalUnavailable as exc:
325
+ record.update(
326
+ mode="local_fallback",
327
+ status="LOCAL_ONLY",
328
+ detail=f"PayPal unreachable; price calculated locally ({exc})",
329
+ )
330
+ log("error", f"node={payload.node_id} PayPal unreachable, using local fallback")
331
+ except PayPalError as exc:
332
+ record.update(status="FAILED", detail=f"PayPal error {exc.status_code}: {exc.message}")
333
+ log("error", f"node={payload.node_id} PayPal error {exc.status_code}")
334
+ return _store(record)
335
+
336
+
337
+ def _store(record: dict[str, Any]) -> dict[str, Any]:
338
+ with _lock:
339
+ _transactions.append(record)
340
+ return record
341
+
342
+
343
+ # ---------------------------------------------------------------------------
344
+ # Telemetry Sensor
345
+ # ---------------------------------------------------------------------------
346
+
347
+
348
+ def sample_local_telemetry(node_id: str, window_seconds: float) -> dict[str, Any]:
349
+ """Read the real CPU/memory of this machine.
350
+
351
+ Data tokens are *simulated* (Poisson noise scaled by CPU load) so the demo
352
+ works on any laptop. Real nodes should send their own token counts.
353
+ """
354
+ cpu = float(psutil.cpu_percent(interval=0.5))
355
+ mem = float(psutil.virtual_memory().percent)
356
+ rng = np.random.default_rng()
357
+ tokens = int(rng.poisson(lam=200 + cpu * 20))
358
+ return {
359
+ "node_id": node_id,
360
+ "cpu_percent": round(cpu, 1),
361
+ "memory_percent": round(mem, 1),
362
+ "tokens": tokens,
363
+ "duration_seconds": window_seconds,
364
+ }
365
+
366
+
367
+ # ---------------------------------------------------------------------------
368
+ # API routes
369
+ # ---------------------------------------------------------------------------
370
+
371
+
372
+ def require_api_key(x_api_key: str | None = Header(default=None)) -> None:
373
+ """Protects spending endpoints when PAPAYA_API_KEY is set."""
374
+ if config.PAPAYA_API_KEY and not hmac.compare_digest(
375
+ x_api_key or "", config.PAPAYA_API_KEY
376
+ ):
377
+ raise HTTPException(status_code=401, detail="Invalid or missing X-API-Key")
378
+
379
+
380
+ @app.get("/")
381
+ def root() -> dict[str, str]:
382
+ return {"name": "Papaya", "docs": "/docs", "health": "/health"}
383
+
384
+
385
+ @app.get("/health")
386
+ def health() -> dict[str, Any]:
387
+ return {
388
+ "status": "ok",
389
+ "paypal_configured": config.paypal_configured(),
390
+ "vault_configured": bool(config.PAYPAL_VAULT_ID),
391
+ "api_key_required": bool(config.PAPAYA_API_KEY),
392
+ "currency": config.CURRENCY,
393
+ }
394
+
395
+
396
+ @app.get("/telemetry/sample")
397
+ def telemetry_sample(
398
+ node_id: str = Query("local-node", pattern=r"^[A-Za-z0-9_.-]{1,64}$"),
399
+ window_seconds: float = Query(5.0, gt=0, le=3600),
400
+ ) -> dict[str, Any]:
401
+ return sample_local_telemetry(node_id, window_seconds)
402
+
403
+
404
+ @app.post("/price", response_model=PriceBreakdown)
405
+ def price(payload: TelemetryPayload) -> PriceBreakdown:
406
+ """Price a workload without paying for it."""
407
+ return price_workload(payload)[1]
408
+
409
+
410
+ @app.post("/pay", dependencies=[Depends(require_api_key)])
411
+ def pay(payload: TelemetryPayload) -> dict[str, Any]:
412
+ """Price a workload and pay it through the PayPal Sandbox."""
413
+ return process_payment(payload)
414
+
415
+
416
+ @app.get("/transactions")
417
+ def transactions(limit: int = Query(50, ge=1, le=500)) -> list[dict[str, Any]]:
418
+ with _lock:
419
+ return list(_transactions)[-limit:][::-1]
420
+
421
+
422
+ @app.get("/logs")
423
+ def logs(limit: int = Query(100, ge=1, le=500)) -> dict[str, list[str]]:
424
+ with _lock:
425
+ return {"lines": list(_logs)[-limit:]}