Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changelog/runtime-sync-http.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pympp: minor
---

Added an owned-loop payment runtime and synchronous HTTPX payment transport.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,22 @@ If a credential is sent but its outcome cannot be confirmed, matching attempts
raise `mpp.errors.PaymentOutcomeUnknownError`. Reconcile them externally before
calling `runtime.reset_unknown_outcomes(reconciled=True)`.

Synchronous and mixed sync/async integrations use an explicit owned asyncio loop
runtime:

```python
import httpx
from mpp.client import SyncPaymentTransport
from mpp.runtime import OwnedPaymentRuntime

with OwnedPaymentRuntime([method]) as runtime:
with httpx.Client(transport=SyncPaymentTransport(runtime=runtime)) as client:
response = client.get("https://api.example.com/paid")
```

For loop-bound resources, pass async-context-manager factories with
`method_factories=` so they are created and closed on the owned loop.

## Examples

| Example | Description |
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ description = "Python SDK for the Machine Payments Protocol (MPP)"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"anyio>=4,<5",
"httpx>=0.27",
]
authors = [
Expand Down
1 change: 1 addition & 0 deletions src/mpp/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""

from mpp import _expires as Expires
from mpp.client.sync_transport import SyncPaymentTransport
from mpp.client.transport import Client, PaymentTransport, get, post, request
from mpp.events import (
CHALLENGE_RECEIVED,
Expand Down
74 changes: 59 additions & 15 deletions src/mpp/client/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import hashlib
import re
import threading
from dataclasses import dataclass
from datetime import UTC, datetime
from http.cookies import CookieError, SimpleCookie
Expand All @@ -20,7 +21,7 @@
if TYPE_CHECKING:
from collections.abc import Sequence

from mpp.runtime import Method, PaymentRuntime
from mpp.runtime import Method, OwnedPaymentRuntime, PaymentRuntime

_COOKIE_ESCAPE = re.compile(r"%[0-9a-fA-F]{2}")
_PAYMENT_MARKER = "mpp.payment_attempt"
Expand Down Expand Up @@ -80,8 +81,13 @@ def __init__(self) -> None:
self._unreconciled_count = 0
self._circuit: _UnknownOutcome | None = None
self._reconciliation = _Reconciliation()
self._lock = threading.RLock()

def begin(self, challenge: Challenge, request: httpx.Request) -> _HttpPaymentAttempt:
with self._lock:
return self._begin(challenge, request)

def _begin(self, challenge: Challenge, request: httpx.Request) -> _HttpPaymentAttempt:
marker = request.extensions.get(_PAYMENT_MARKER)
if isinstance(marker, _HttpPaymentAttempt):
raise _outcome_error(marker)
Expand Down Expand Up @@ -112,6 +118,10 @@ def begin(self, challenge: Challenge, request: httpx.Request) -> _HttpPaymentAtt
return attempt

def mark_sent(self, attempt: _HttpPaymentAttempt, request: httpx.Request) -> None:
with self._lock:
self._mark_sent(attempt, request)

def _mark_sent(self, attempt: _HttpPaymentAttempt, request: httpx.Request) -> None:
if self._circuit is not None:
self.discard(attempt)
raise _outcome_error(self._circuit)
Expand All @@ -128,6 +138,14 @@ def mark_unknown(
self,
attempt: _HttpPaymentAttempt,
cause: BaseException,
) -> _UnknownOutcome:
with self._lock:
return self._mark_unknown(attempt, cause)

def _mark_unknown(
self,
attempt: _HttpPaymentAttempt,
cause: BaseException,
) -> _UnknownOutcome:
if attempt.unknown_outcome is not None:
return attempt.unknown_outcome
Expand Down Expand Up @@ -155,6 +173,10 @@ def mark_unknown(
return outcome

def complete(self, attempt: _HttpPaymentAttempt) -> None:
with self._lock:
self._complete(attempt)

def _complete(self, attempt: _HttpPaymentAttempt) -> None:
if attempt.completed or attempt.unknown_outcome is not None:
return
attempt.completed = True
Expand All @@ -164,21 +186,25 @@ def complete(self, attempt: _HttpPaymentAttempt) -> None:
request.extensions.pop(_PAYMENT_MARKER, None)

def discard(self, attempt: _HttpPaymentAttempt) -> None:
if not attempt.sent:
self.complete(attempt)
with self._lock:
if not attempt.sent:
self._complete(attempt)

def reset(self, *, reconciled: bool) -> None:
if not reconciled:
raise ValueError("Unknown payment outcomes must be externally reconciled before reset")
self._reconciliation.reconciled = True
self._reconciliation = _Reconciliation()
self._entries = {
key: entry
for key, entry in self._entries.items()
if isinstance(entry, _HttpPaymentAttempt)
}
self._unreconciled_count = 0
self._circuit = None
with self._lock:
if not reconciled:
raise ValueError(
"Unknown payment outcomes must be externally reconciled before reset"
)
self._reconciliation.reconciled = True
self._reconciliation = _Reconciliation()
self._entries = {
key: entry
for key, entry in self._entries.items()
if isinstance(entry, _HttpPaymentAttempt)
}
self._unreconciled_count = 0
self._circuit = None

def _remove(self, attempt: _HttpPaymentAttempt) -> None:
for key in attempt.keys:
Expand Down Expand Up @@ -242,6 +268,24 @@ def retry_request(self, authorization: str) -> httpx.Request:
return retry


def _settle_http_payment(
attempt: _HttpPaymentAttempt,
payment: _HttpPayment,
response: httpx.Response,
) -> PaymentOutcomeUnknownError | None:
if response.status_code < 400:
attempt.complete()
return None
detail = (
"Server returned another payment challenge after receiving a credential"
if response.status_code == 402
else f"Credentialed request returned HTTP {response.status_code}"
)
cause = RuntimeError(detail)
attempt.unknown(cause)
return payment.unknown(cause)


class _AllowedOrigins:
def __init__(self, allowed: Sequence[str] | None) -> None:
self._allow_all = allowed is None
Expand Down Expand Up @@ -326,7 +370,7 @@ def _challenge_is_expired(challenge: Challenge) -> bool:


def _match_http_challenge(
runtime: PaymentRuntime,
runtime: PaymentRuntime | OwnedPaymentRuntime,
challenges: list[Challenge],
) -> tuple[Challenge | None, Method | None]:
try:
Expand Down
Loading