mitulabs-payments 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. mitulabs_payments-0.1.0/.gitignore +8 -0
  2. mitulabs_payments-0.1.0/CHANGELOG.md +5 -0
  3. mitulabs_payments-0.1.0/LICENSE +21 -0
  4. mitulabs_payments-0.1.0/PKG-INFO +173 -0
  5. mitulabs_payments-0.1.0/README.md +147 -0
  6. mitulabs_payments-0.1.0/pyproject.toml +60 -0
  7. mitulabs_payments-0.1.0/src/mitulabs_payments/__init__.py +17 -0
  8. mitulabs_payments-0.1.0/src/mitulabs_payments/_version.py +1 -0
  9. mitulabs_payments-0.1.0/src/mitulabs_payments/amounts.py +39 -0
  10. mitulabs_payments-0.1.0/src/mitulabs_payments/api.py +126 -0
  11. mitulabs_payments-0.1.0/src/mitulabs_payments/charge.py +243 -0
  12. mitulabs_payments-0.1.0/src/mitulabs_payments/credentials.py +87 -0
  13. mitulabs_payments-0.1.0/src/mitulabs_payments/environment.py +50 -0
  14. mitulabs_payments-0.1.0/src/mitulabs_payments/errors.py +18 -0
  15. mitulabs_payments-0.1.0/src/mitulabs_payments/frameworks/__init__.py +41 -0
  16. mitulabs_payments-0.1.0/src/mitulabs_payments/frameworks/django.py +31 -0
  17. mitulabs_payments-0.1.0/src/mitulabs_payments/frameworks/fastapi.py +38 -0
  18. mitulabs_payments-0.1.0/src/mitulabs_payments/frameworks/flask.py +31 -0
  19. mitulabs_payments-0.1.0/src/mitulabs_payments/mitu.py +152 -0
  20. mitulabs_payments-0.1.0/src/mitulabs_payments/models.py +49 -0
  21. mitulabs_payments-0.1.0/src/mitulabs_payments/py.typed +0 -0
  22. mitulabs_payments-0.1.0/tests/conformance/.gitkeep +0 -0
  23. mitulabs_payments-0.1.0/tests/integration/.gitkeep +0 -0
  24. mitulabs_payments-0.1.0/tests/unit/.gitkeep +0 -0
  25. mitulabs_payments-0.1.0/tests/unit/conftest.py +27 -0
  26. mitulabs_payments-0.1.0/tests/unit/fake_mitu.py +149 -0
  27. mitulabs_payments-0.1.0/tests/unit/test_config.py +88 -0
  28. mitulabs_payments-0.1.0/tests/unit/test_credentials.py +92 -0
  29. mitulabs_payments-0.1.0/tests/unit/test_django.py +92 -0
  30. mitulabs_payments-0.1.0/tests/unit/test_fastapi.py +125 -0
  31. mitulabs_payments-0.1.0/tests/unit/test_flask.py +429 -0
  32. mitulabs_payments-0.1.0/tests/unit/wire.py +47 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ .pytest_cache/
8
+ .env
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mitu Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.5
2
+ Name: mitulabs-payments
3
+ Version: 0.1.0
4
+ Summary: Charge AI agents for API routes through Mitu, with standard MPP and x402 payments.
5
+ Project-URL: Homepage, https://github.com/Mitulabs/payments/tree/main/python
6
+ Project-URL: Issues, https://github.com/Mitulabs/payments/issues
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: httpx<1,>=0.27
11
+ Provides-Extra: dev
12
+ Requires-Dist: django==6.1.3; extra == 'dev'
13
+ Requires-Dist: fastapi==0.165.0; extra == 'dev'
14
+ Requires-Dist: flask==3.1.3; extra == 'dev'
15
+ Requires-Dist: mypy==2.4.1; extra == 'dev'
16
+ Requires-Dist: pip-audit==2.10.1; extra == 'dev'
17
+ Requires-Dist: pytest==9.2.0; extra == 'dev'
18
+ Requires-Dist: ruff==0.17.6; extra == 'dev'
19
+ Provides-Extra: django
20
+ Requires-Dist: django>=5; extra == 'django'
21
+ Provides-Extra: fastapi
22
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
23
+ Provides-Extra: flask
24
+ Requires-Dist: flask>=3; extra == 'flask'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # mitulabs-payments
28
+
29
+ Python SDK for charging AI agents per request on HTTP APIs. It places Mitu's payment flow in front of a route:
30
+ agents pay through the [Machine Payments Protocol](https://mpp.dev) (MPP) or [x402](https://x402.org), and Mitu
31
+ issues the payment challenges, settles each payment on chain, and delivers the `payment.completed` webhook.
32
+
33
+ The SDK does not verify payments, hold receiving addresses, or convert currencies. For each request it creates a
34
+ payment through the Mitu API, confirms that the payment an agent presents belongs to the route and price being
35
+ requested, and serves the route once Mitu has settled it. Prices in local currencies are converted at the rate
36
+ Mitu locks when the payment is created.
37
+
38
+ ## Requirements
39
+
40
+ - Python 3.12 or later
41
+ - FastAPI, Flask or Django
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install "mitulabs-payments[fastapi]" # or [flask], [django]
47
+ ```
48
+
49
+ ## Configuration
50
+
51
+ ```python
52
+ import os
53
+
54
+ from mitulabs_payments import Mitu
55
+
56
+ mitu = Mitu(os.environ["MITU_API_KEY"])
57
+ ```
58
+
59
+ | Option | Default | Description |
60
+ | --- | --- | --- |
61
+ | `api_key` | required | Mitu secret key. `sk_test_` selects the sandbox, `sk_live_` production. |
62
+ | `default_currency` | `"USD"` | Currency code for prices that do not specify one. |
63
+ | `base_url` | Mitu API for the key's environment | API origin override, for testing. Must use HTTPS unless it is `localhost`. |
64
+ | `transport` | — | An `httpx` transport, for testing. |
65
+
66
+ The API key is sent only to the Mitu API, as `x-api-key`. It is never forwarded to an agent payment URL, logged,
67
+ or included in an error message.
68
+
69
+ ## Usage
70
+
71
+ Decorate a route with `@mitu.charge`. The decorator sits below the framework's route decorator.
72
+
73
+ ### FastAPI
74
+
75
+ ```python
76
+ from fastapi import FastAPI, Request
77
+
78
+ app = FastAPI()
79
+
80
+
81
+ @app.get("/v1/search")
82
+ @mitu.charge(amount="0.01", currency="USD", description="Search")
83
+ async def search(request: Request):
84
+ return run_search(request.query_params, request.state.mitu_payment)
85
+ ```
86
+
87
+ Charged FastAPI routes accept `request: Request`. Both `async def` and `def` routes are supported.
88
+
89
+ ### Flask
90
+
91
+ ```python
92
+ from flask import g, request
93
+
94
+
95
+ @app.get("/v1/search")
96
+ @mitu.charge(amount="0.01", currency="USD")
97
+ def search():
98
+ return run_search(request.args, g.mitu_payment)
99
+ ```
100
+
101
+ ### Django
102
+
103
+ ```python
104
+ @mitu.charge(amount="0.01", currency="USD")
105
+ def search(request):
106
+ return JsonResponse(run_search(request.GET, request.mitu_payment))
107
+ ```
108
+
109
+ Sync and async Django views are supported.
110
+
111
+ ### Shutdown
112
+
113
+ Call `await mitu.close()` (or `mitu.close_sync()` in sync applications) at shutdown to release HTTP connections.
114
+
115
+ ## Request flow
116
+
117
+ 1. **No payment credential.** The SDK creates a payment for the route's price, with a 15-minute expiry and the
118
+ route's method and path in its metadata, and returns Mitu's `402 Payment Required` response, including the MPP
119
+ `WWW-Authenticate` and x402 `PAYMENT-REQUIRED` challenges.
120
+ 2. **Payment credential present.** The SDK reads the Mitu payment id from the MPP or x402 credential, retrieves the
121
+ payment, and checks that its amount, currency, method and path match the route. A credential for any other
122
+ route or price receives a new `402`.
123
+ 3. **Settlement.** The SDK forwards only the payment headers to the payment's `agent_url`. When Mitu confirms
124
+ settlement, the view runs and the response carries Mitu's receipt header (`Payment-Receipt` or
125
+ `PAYMENT-RESPONSE`). Any other answer from Mitu, such as a replayed or expired payment, is returned to the agent
126
+ unchanged, and the view does not run.
127
+
128
+ Every response that carries payment state includes `Cache-Control: no-store`. If Mitu cannot be reached, or
129
+ answers with a server error, the route responds `503 Service Unavailable` with `Retry-After: 5` and is not served.
130
+
131
+ ## Pricing
132
+
133
+ `amount` is a decimal string greater than zero with at most two decimal places, such as `"0.01"` or `"1500"`. It
134
+ can also be a function of the request that returns such a string, or `None` to serve that request without payment.
135
+ On async views the function may be async. The function is evaluated on the initial request and on the paid retry,
136
+ and must return the same price for both. Derive prices from server-side state, never from the request body.
137
+
138
+ ## Payments
139
+
140
+ The view receives a `Payment` with:
141
+
142
+ | Field | Description |
143
+ | --- | --- |
144
+ | `payment_id` | The Mitu payment id (`pmt_...`). |
145
+ | `reference` | The payment reference the SDK generated. |
146
+ | `tx_hash` | The settlement transaction hash, where the payment method has one. |
147
+ | `amount_paid` | The amount the agent paid, as a `Decimal`. |
148
+ | `currency` | The currency the agent paid in. |
149
+ | `network` | The network the payment settled on. |
150
+ | `payment_method` | The payment method used. |
151
+
152
+ The payment is final when the view runs. If the view fails afterwards, retry the operation or refund the payment.
153
+ Free requests receive `None`.
154
+
155
+ ## Error handling
156
+
157
+ | Error | Raised when |
158
+ | --- | --- |
159
+ | `MituConfigError` | The API key, base URL, currency, price or description is invalid, or a view has no request. |
160
+ | `MituApiError` | The Mitu API refuses a request in a way a retry will not fix, such as an invalid API key. Exposes `status`. |
161
+
162
+ Both derive from `MituError`.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
168
+ ruff check . && ruff format --check . && mypy --strict src && pytest
169
+ ```
170
+
171
+ ## License
172
+
173
+ [MIT](LICENSE)
@@ -0,0 +1,147 @@
1
+ # mitulabs-payments
2
+
3
+ Python SDK for charging AI agents per request on HTTP APIs. It places Mitu's payment flow in front of a route:
4
+ agents pay through the [Machine Payments Protocol](https://mpp.dev) (MPP) or [x402](https://x402.org), and Mitu
5
+ issues the payment challenges, settles each payment on chain, and delivers the `payment.completed` webhook.
6
+
7
+ The SDK does not verify payments, hold receiving addresses, or convert currencies. For each request it creates a
8
+ payment through the Mitu API, confirms that the payment an agent presents belongs to the route and price being
9
+ requested, and serves the route once Mitu has settled it. Prices in local currencies are converted at the rate
10
+ Mitu locks when the payment is created.
11
+
12
+ ## Requirements
13
+
14
+ - Python 3.12 or later
15
+ - FastAPI, Flask or Django
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install "mitulabs-payments[fastapi]" # or [flask], [django]
21
+ ```
22
+
23
+ ## Configuration
24
+
25
+ ```python
26
+ import os
27
+
28
+ from mitulabs_payments import Mitu
29
+
30
+ mitu = Mitu(os.environ["MITU_API_KEY"])
31
+ ```
32
+
33
+ | Option | Default | Description |
34
+ | --- | --- | --- |
35
+ | `api_key` | required | Mitu secret key. `sk_test_` selects the sandbox, `sk_live_` production. |
36
+ | `default_currency` | `"USD"` | Currency code for prices that do not specify one. |
37
+ | `base_url` | Mitu API for the key's environment | API origin override, for testing. Must use HTTPS unless it is `localhost`. |
38
+ | `transport` | — | An `httpx` transport, for testing. |
39
+
40
+ The API key is sent only to the Mitu API, as `x-api-key`. It is never forwarded to an agent payment URL, logged,
41
+ or included in an error message.
42
+
43
+ ## Usage
44
+
45
+ Decorate a route with `@mitu.charge`. The decorator sits below the framework's route decorator.
46
+
47
+ ### FastAPI
48
+
49
+ ```python
50
+ from fastapi import FastAPI, Request
51
+
52
+ app = FastAPI()
53
+
54
+
55
+ @app.get("/v1/search")
56
+ @mitu.charge(amount="0.01", currency="USD", description="Search")
57
+ async def search(request: Request):
58
+ return run_search(request.query_params, request.state.mitu_payment)
59
+ ```
60
+
61
+ Charged FastAPI routes accept `request: Request`. Both `async def` and `def` routes are supported.
62
+
63
+ ### Flask
64
+
65
+ ```python
66
+ from flask import g, request
67
+
68
+
69
+ @app.get("/v1/search")
70
+ @mitu.charge(amount="0.01", currency="USD")
71
+ def search():
72
+ return run_search(request.args, g.mitu_payment)
73
+ ```
74
+
75
+ ### Django
76
+
77
+ ```python
78
+ @mitu.charge(amount="0.01", currency="USD")
79
+ def search(request):
80
+ return JsonResponse(run_search(request.GET, request.mitu_payment))
81
+ ```
82
+
83
+ Sync and async Django views are supported.
84
+
85
+ ### Shutdown
86
+
87
+ Call `await mitu.close()` (or `mitu.close_sync()` in sync applications) at shutdown to release HTTP connections.
88
+
89
+ ## Request flow
90
+
91
+ 1. **No payment credential.** The SDK creates a payment for the route's price, with a 15-minute expiry and the
92
+ route's method and path in its metadata, and returns Mitu's `402 Payment Required` response, including the MPP
93
+ `WWW-Authenticate` and x402 `PAYMENT-REQUIRED` challenges.
94
+ 2. **Payment credential present.** The SDK reads the Mitu payment id from the MPP or x402 credential, retrieves the
95
+ payment, and checks that its amount, currency, method and path match the route. A credential for any other
96
+ route or price receives a new `402`.
97
+ 3. **Settlement.** The SDK forwards only the payment headers to the payment's `agent_url`. When Mitu confirms
98
+ settlement, the view runs and the response carries Mitu's receipt header (`Payment-Receipt` or
99
+ `PAYMENT-RESPONSE`). Any other answer from Mitu, such as a replayed or expired payment, is returned to the agent
100
+ unchanged, and the view does not run.
101
+
102
+ Every response that carries payment state includes `Cache-Control: no-store`. If Mitu cannot be reached, or
103
+ answers with a server error, the route responds `503 Service Unavailable` with `Retry-After: 5` and is not served.
104
+
105
+ ## Pricing
106
+
107
+ `amount` is a decimal string greater than zero with at most two decimal places, such as `"0.01"` or `"1500"`. It
108
+ can also be a function of the request that returns such a string, or `None` to serve that request without payment.
109
+ On async views the function may be async. The function is evaluated on the initial request and on the paid retry,
110
+ and must return the same price for both. Derive prices from server-side state, never from the request body.
111
+
112
+ ## Payments
113
+
114
+ The view receives a `Payment` with:
115
+
116
+ | Field | Description |
117
+ | --- | --- |
118
+ | `payment_id` | The Mitu payment id (`pmt_...`). |
119
+ | `reference` | The payment reference the SDK generated. |
120
+ | `tx_hash` | The settlement transaction hash, where the payment method has one. |
121
+ | `amount_paid` | The amount the agent paid, as a `Decimal`. |
122
+ | `currency` | The currency the agent paid in. |
123
+ | `network` | The network the payment settled on. |
124
+ | `payment_method` | The payment method used. |
125
+
126
+ The payment is final when the view runs. If the view fails afterwards, retry the operation or refund the payment.
127
+ Free requests receive `None`.
128
+
129
+ ## Error handling
130
+
131
+ | Error | Raised when |
132
+ | --- | --- |
133
+ | `MituConfigError` | The API key, base URL, currency, price or description is invalid, or a view has no request. |
134
+ | `MituApiError` | The Mitu API refuses a request in a way a retry will not fix, such as an invalid API key. Exposes `status`. |
135
+
136
+ Both derive from `MituError`.
137
+
138
+ ## Development
139
+
140
+ ```bash
141
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
142
+ ruff check . && ruff format --check . && mypy --strict src && pytest
143
+ ```
144
+
145
+ ## License
146
+
147
+ [MIT](LICENSE)
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mitulabs-payments"
7
+ dynamic = ["version"]
8
+ description = "Charge AI agents for API routes through Mitu, with standard MPP and x402 payments."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ dependencies = [
13
+ "httpx>=0.27,<1",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ fastapi = ["fastapi>=0.110"]
18
+ flask = ["flask>=3"]
19
+ django = ["django>=5"]
20
+ dev = [
21
+ "fastapi==0.165.0",
22
+ "flask==3.1.3",
23
+ "django==6.1.3",
24
+ "pytest==9.2.0",
25
+ "mypy==2.4.1",
26
+ "ruff==0.17.6",
27
+ "pip-audit==2.10.1",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/Mitulabs/payments/tree/main/python"
32
+ Issues = "https://github.com/Mitulabs/payments/issues"
33
+
34
+ [tool.hatch.version]
35
+ path = "src/mitulabs_payments/_version.py"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/mitulabs_payments"]
39
+
40
+ [tool.ruff]
41
+ line-length = 100
42
+ [tool.ruff.lint]
43
+ select = ["E", "F", "I", "B", "S", "UP", "T20"] # S = bandit security checks, T20 = no print()
44
+ [tool.ruff.lint.per-file-ignores]
45
+ "tests/**" = ["S101", "S105", "S106"] # asserts and fixture keys are expected in tests
46
+
47
+ [tool.mypy]
48
+ strict = true
49
+
50
+ [[tool.mypy.overrides]]
51
+ module = ["django.*"]
52
+ ignore_missing_imports = true
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests/unit"]
56
+ filterwarnings = [
57
+ "error",
58
+ # Starlette's TestClient prefers httpx2; this package and its tests use httpx.
59
+ "ignore:Using `httpx` with `starlette.testclient` is deprecated",
60
+ ]
@@ -0,0 +1,17 @@
1
+ import logging
2
+
3
+ from ._version import __version__
4
+ from .errors import MituApiError, MituConfigError, MituError
5
+ from .mitu import Mitu
6
+ from .models import Payment
7
+
8
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
9
+
10
+ __all__ = [
11
+ "Mitu",
12
+ "MituApiError",
13
+ "MituConfigError",
14
+ "MituError",
15
+ "Payment",
16
+ "__version__",
17
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,39 @@
1
+ import re
2
+ from decimal import Decimal
3
+
4
+ from .errors import MituConfigError
5
+
6
+ _AMOUNT = re.compile(r"[0-9]+(?:\.[0-9]{1,2})?")
7
+ _CURRENCY = re.compile(r"[A-Za-z]{2,10}")
8
+ MAX_DESCRIPTION_LENGTH = 500
9
+
10
+
11
+ def parse_price(value: object) -> Decimal:
12
+ """Parses a price such as ``"5000"`` or ``"12.50"``: positive, at most two decimal places."""
13
+ if not (isinstance(value, str) and _AMOUNT.fullmatch(value)):
14
+ raise MituConfigError(
15
+ f"amount must be a decimal string with at most 2 decimal places, got {value!r}"
16
+ )
17
+ amount = Decimal(value)
18
+ if not amount:
19
+ raise MituConfigError("amount must be greater than 0; return None to serve free")
20
+ # Mitu reads the amount as a JSON number, so it must survive the trip through a float.
21
+ if Decimal(repr(float(amount))) != amount:
22
+ raise MituConfigError(f"amount {value} is too precise to send to Mitu")
23
+ return amount
24
+
25
+
26
+ def parse_currency(value: object) -> str:
27
+ if not (isinstance(value, str) and _CURRENCY.fullmatch(value)):
28
+ raise MituConfigError(f"currency must be a currency code such as USD, got {value!r}")
29
+ return value.upper()
30
+
31
+
32
+ def parse_description(value: object) -> str | None:
33
+ if value is None:
34
+ return None
35
+ if not isinstance(value, str) or len(value) > MAX_DESCRIPTION_LENGTH:
36
+ raise MituConfigError(
37
+ f"description must be a string of at most {MAX_DESCRIPTION_LENGTH} characters"
38
+ )
39
+ return value or None
@@ -0,0 +1,126 @@
1
+ import asyncio
2
+ import os
3
+ import threading
4
+ import weakref
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Final
7
+
8
+ import httpx
9
+
10
+ from ._version import __version__
11
+ from .errors import MituConfigError
12
+
13
+ TIMEOUT_SECONDS: Final = 10.0
14
+ PAYMENTS_PATH: Final = "/v1/public/payments"
15
+
16
+ _USER_AGENT: Final = f"mitulabs-payments-python/{__version__}"
17
+
18
+ Transport = httpx.BaseTransport | httpx.AsyncBaseTransport
19
+
20
+
21
+ class MituApi:
22
+ """Builds and sends the requests of the payment flow, from sync and async code alike.
23
+
24
+ Only requests to the Mitu API carry ``x-api-key``; requests to an ``agent_url`` carry the
25
+ agent's payment headers and nothing else. Redirects are never followed.
26
+ """
27
+
28
+ def __init__(self, api_key: str, base_url: str, *, transport: Transport | None = None) -> None:
29
+ self._api_key = api_key
30
+ self._payments_url = f"{base_url}{PAYMENTS_PATH}"
31
+ self._transport = transport
32
+ self._timeout = httpx.Timeout(TIMEOUT_SECONDS).as_dict()
33
+ self._lock = threading.Lock()
34
+ self._client: httpx.Client | None = None
35
+ # One per event loop: pooled connections cannot move between loops, and Django runs
36
+ # each async view of a WSGI app on a loop of its own.
37
+ self._async_clients: weakref.WeakKeyDictionary[
38
+ asyncio.AbstractEventLoop, httpx.AsyncClient
39
+ ] = weakref.WeakKeyDictionary()
40
+ _after_fork_in_child(self._forget_clients)
41
+
42
+ def create_payment(self, body: Mapping[str, object]) -> httpx.Request:
43
+ return self._request("POST", self._payments_url, self._api_headers(), json=body)
44
+
45
+ def get_payment(self, payment_id: str) -> httpx.Request:
46
+ return self._request("GET", f"{self._payments_url}/{payment_id}", self._api_headers())
47
+
48
+ def agent(self, url: str, payment_headers: Mapping[str, str]) -> httpx.Request:
49
+ return self._request("GET", url, {**self._base_headers(), **payment_headers})
50
+
51
+ def send(self, request: httpx.Request) -> httpx.Response:
52
+ with self._lock:
53
+ if self._client is None:
54
+ self._client = httpx.Client(
55
+ follow_redirects=False, transport=self._typed(httpx.BaseTransport)
56
+ )
57
+ client = self._client
58
+ return client.send(request)
59
+
60
+ async def asend(self, request: httpx.Request) -> httpx.Response:
61
+ loop = asyncio.get_running_loop()
62
+ with self._lock:
63
+ if not (client := self._async_clients.get(loop)):
64
+ client = self._async_clients[loop] = httpx.AsyncClient(
65
+ follow_redirects=False, transport=self._typed(httpx.AsyncBaseTransport)
66
+ )
67
+ return await client.send(request)
68
+
69
+ def close(self) -> None:
70
+ with self._lock:
71
+ client, self._client = self._client, None
72
+ if client:
73
+ client.close()
74
+
75
+ async def aclose(self) -> None:
76
+ with self._lock:
77
+ client = self._async_clients.pop(asyncio.get_running_loop(), None)
78
+ self._async_clients.clear()
79
+ if client:
80
+ await client.aclose()
81
+ self.close()
82
+
83
+ def _request(
84
+ self,
85
+ method: str,
86
+ url: str,
87
+ headers: Mapping[str, str],
88
+ *,
89
+ json: Mapping[str, object] | None = None,
90
+ ) -> httpx.Request:
91
+ return httpx.Request(
92
+ method, url, headers=headers, json=json, extensions={"timeout": self._timeout}
93
+ )
94
+
95
+ def _base_headers(self) -> dict[str, str]:
96
+ return {"accept": "application/json", "user-agent": _USER_AGENT}
97
+
98
+ def _api_headers(self) -> dict[str, str]:
99
+ return {**self._base_headers(), "x-api-key": self._api_key}
100
+
101
+ def _typed[T: Transport](self, kind: type[T]) -> T | None:
102
+ match self._transport:
103
+ case None:
104
+ return None
105
+ case transport if isinstance(transport, kind):
106
+ return transport
107
+ raise MituConfigError(f"transport must be an {kind.__name__} for this view")
108
+
109
+ def _forget_clients(self) -> None:
110
+ # Not closed: the parent process still owns those pooled sockets.
111
+ self._client = None
112
+ self._async_clients = weakref.WeakKeyDictionary()
113
+
114
+
115
+ def _after_fork_in_child(method: Callable[[], None]) -> None:
116
+ # Pooled sockets must not be shared with the parent (Gunicorn --preload). The weak
117
+ # reference keeps the hook from holding the client alive.
118
+ if not hasattr(os, "register_at_fork"):
119
+ return
120
+ ref = weakref.WeakMethod(method)
121
+
122
+ def run() -> None:
123
+ if bound := ref():
124
+ bound()
125
+
126
+ os.register_at_fork(after_in_child=run)