mpesa-daraja-core 0.9.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 (29) hide show
  1. mpesa_daraja_core-0.9.0/MANIFEST.in +5 -0
  2. mpesa_daraja_core-0.9.0/PKG-INFO +125 -0
  3. mpesa_daraja_core-0.9.0/README.md +85 -0
  4. mpesa_daraja_core-0.9.0/mpesa/__init__.py +133 -0
  5. mpesa_daraja_core-0.9.0/mpesa/_limits.py +183 -0
  6. mpesa_daraja_core-0.9.0/mpesa/auth.py +527 -0
  7. mpesa_daraja_core-0.9.0/mpesa/callback_token.py +64 -0
  8. mpesa_daraja_core-0.9.0/mpesa/callbacks.py +245 -0
  9. mpesa_daraja_core-0.9.0/mpesa/classification.py +104 -0
  10. mpesa_daraja_core-0.9.0/mpesa/client.py +958 -0
  11. mpesa_daraja_core-0.9.0/mpesa/coercion.py +357 -0
  12. mpesa_daraja_core-0.9.0/mpesa/config.py +203 -0
  13. mpesa_daraja_core-0.9.0/mpesa/enums.py +179 -0
  14. mpesa_daraja_core-0.9.0/mpesa/exceptions.py +250 -0
  15. mpesa_daraja_core-0.9.0/mpesa/helpers.py +182 -0
  16. mpesa_daraja_core-0.9.0/mpesa/limits.py +227 -0
  17. mpesa_daraja_core-0.9.0/mpesa/py.typed +0 -0
  18. mpesa_daraja_core-0.9.0/mpesa/requests_async.py +585 -0
  19. mpesa_daraja_core-0.9.0/mpesa/requests_sync.py +990 -0
  20. mpesa_daraja_core-0.9.0/mpesa/responses.py +388 -0
  21. mpesa_daraja_core-0.9.0/mpesa/responses_models.py +29 -0
  22. mpesa_daraja_core-0.9.0/mpesa/results.py +301 -0
  23. mpesa_daraja_core-0.9.0/mpesa_daraja_core.egg-info/PKG-INFO +125 -0
  24. mpesa_daraja_core-0.9.0/mpesa_daraja_core.egg-info/SOURCES.txt +27 -0
  25. mpesa_daraja_core-0.9.0/mpesa_daraja_core.egg-info/dependency_links.txt +1 -0
  26. mpesa_daraja_core-0.9.0/mpesa_daraja_core.egg-info/requires.txt +6 -0
  27. mpesa_daraja_core-0.9.0/mpesa_daraja_core.egg-info/top_level.txt +1 -0
  28. mpesa_daraja_core-0.9.0/setup.cfg +4 -0
  29. mpesa_daraja_core-0.9.0/setup.py +72 -0
@@ -0,0 +1,5 @@
1
+ include LICENSE
2
+ include README.md
3
+ include CHANGES.md
4
+ recursive-include mpesa *.py py.typed
5
+ recursive-exclude tests *
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: mpesa-daraja-core
3
+ Version: 0.9.0
4
+ Summary: M-Pesa Daraja SDK for Python — one hardened core shared with Go and TypeScript under a single executable wire contract.
5
+ Home-page: https://github.com/anthrodjear/mpesa-sdk
6
+ Author: mpesa-sdk maintainers
7
+ License: MIT
8
+ Project-URL: Source, https://github.com/anthrodjear/mpesa-sdk
9
+ Project-URL: Issues, https://github.com/anthrodjear/mpesa-sdk/issues
10
+ Project-URL: Changelog, https://github.com/anthrodjear/mpesa-sdk/blob/main/CHANGES.md
11
+ Keywords: mpesa,daraja,safaricom,stk-push,payments,mobile-money,kenya
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Office/Business :: Financial
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: requests<3,>=2.32.4
24
+ Requires-Dist: cryptography<51,>=48.0.1
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8; extra == "dev"
27
+ Requires-Dist: pytest-cov>=6; extra == "dev"
28
+ Dynamic: author
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: description-content-type
32
+ Dynamic: home-page
33
+ Dynamic: keywords
34
+ Dynamic: license
35
+ Dynamic: project-url
36
+ Dynamic: provides-extra
37
+ Dynamic: requires-dist
38
+ Dynamic: requires-python
39
+ Dynamic: summary
40
+
41
+ # mpesa-daraja-core
42
+
43
+ [![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python)](https://pypi.org/project/mpesa-daraja-core/)
44
+
45
+ Python SDK for the Safaricom M-Pesa Daraja API. Zero-config first call: four environment variables and one client.
46
+
47
+ ## Install
48
+
49
+ ```sh
50
+ pip install mpesa-daraja-core
51
+ ```
52
+
53
+ ## Quick start
54
+
55
+ ```python
56
+ from mpesa import MpesaClient, STKPushRequest, TransactionType
57
+
58
+ client = MpesaClient.from_env() # reads MPESA_*; sandbox by default
59
+
60
+ resp = client.stk_push(STKPushRequest(
61
+ transaction_type=TransactionType.CUSTOMER_PAY_BILL_ONLINE,
62
+ amount=100,
63
+ party_a="254712345678",
64
+ phone_number="254712345678",
65
+ call_back_url="https://example.com/stk/callback",
66
+ account_reference="Order42",
67
+ transaction_desc="test",
68
+ ))
69
+ print(resp.response_code, resp.checkout_request_id)
70
+ ```
71
+
72
+ `from_env()` reads `MPESA_CONSUMER_KEY`, `MPESA_CONSUMER_SECRET`, `MPESA_SHORTCODE` and `MPESA_PASSKEY`. A missing variable raises `ValueError` naming it. `MPESA_ENVIRONMENT` accepts `sandbox` (default), `production` or `prod`; `MpesaClient.from_env("prod")` overrides the variable.
73
+
74
+ > Accepted ≠ paid. `response_code == "0"` means the prompt was queued. Settle only after an `stk_query` bound to your stored `checkout_request_id`, and require `result.verify_amount(order_amount)`.
75
+
76
+ > **Money is whole KES.** Amounts are integers, never floats; inbound callback amounts are validated against a canonical grammar with no rounding or fractional KES. A callback amount is advisory until checked against your stored order.
77
+
78
+ One hardened core is implemented in Go, Python and TypeScript against one executable wire contract; a shared fixture corpus pins identical wire behaviour across all three engines. Go and TypeScript have no runtime dependencies; Python uses `requests` and `cryptography`.
79
+
80
+ ## Receiving callbacks
81
+
82
+ `token_on_file`, `repo`, `client`, `mark_paid` and `mark_pending_reconcile` are application code.
83
+
84
+ Daraja callbacks are unsigned; the query round-trip and stored-amount check are the settlement controls. Indeterminate results are never auto-failed — reconcile them.
85
+
86
+ A valid token proves only that the caller knows the URL; it authenticates nothing about the body or the payment. This example returns 200 for a token mismatch — a deliberate per-engine difference, not a weaker control. Malformed bodies are ACKed 200 rather than returning 5xx. Framework-level body limits (Flask MAX_CONTENT_LENGTH, express.raw() default) can still return 413 before the handler — configure them to match your policy.
87
+
88
+ ```python
89
+ from flask import Flask, request
90
+ from mpesa import ResultClass, STKQueryRequest, StkCallbackResult, callback_token_equal
91
+
92
+ app = Flask(__name__)
93
+ app.config["MAX_CONTENT_LENGTH"] = 1 << 20
94
+
95
+
96
+ @app.post("/mpesa/callback/<token>")
97
+ def stk_callback(token: str):
98
+ if not callback_token_equal(token_on_file, token):
99
+ return "", 200
100
+ try:
101
+ result = StkCallbackResult.from_json(request.get_data())
102
+ except ValueError:
103
+ return "", 200 # malformed: ACK, never a 5xx
104
+ order = repo.by_checkout(result.checkout_request_id)
105
+ if order is None:
106
+ return "", 200
107
+ paid = False
108
+ if result.classify() is ResultClass.SUCCESS:
109
+ resp = client.stk_query(STKQueryRequest(
110
+ checkout_request_id=result.checkout_request_id))
111
+ if resp.result_code == "0" and result.verify_amount(order.amount):
112
+ mark_paid(order)
113
+ paid = True
114
+ if not paid:
115
+ mark_pending_reconcile(order)
116
+ return "", 200
117
+ ```
118
+
119
+ ## What is covered
120
+
121
+ STK Push/Query, B2C, C2B register/simulate, Transaction Status, Reversal, Account Balance, Dynamic QR, B2B, Tax Remittance and Bill Manager — plus typed callbacks, token refresh with `401.003.01` retry-once, and redacted credential rendering.
122
+
123
+ ## Documentation
124
+
125
+ Full guide and cross-engine contract: [the repository README](https://github.com/anthrodjear/mpesa-sdk#readme).
@@ -0,0 +1,85 @@
1
+ # mpesa-daraja-core
2
+
3
+ [![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python)](https://pypi.org/project/mpesa-daraja-core/)
4
+
5
+ Python SDK for the Safaricom M-Pesa Daraja API. Zero-config first call: four environment variables and one client.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install mpesa-daraja-core
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```python
16
+ from mpesa import MpesaClient, STKPushRequest, TransactionType
17
+
18
+ client = MpesaClient.from_env() # reads MPESA_*; sandbox by default
19
+
20
+ resp = client.stk_push(STKPushRequest(
21
+ transaction_type=TransactionType.CUSTOMER_PAY_BILL_ONLINE,
22
+ amount=100,
23
+ party_a="254712345678",
24
+ phone_number="254712345678",
25
+ call_back_url="https://example.com/stk/callback",
26
+ account_reference="Order42",
27
+ transaction_desc="test",
28
+ ))
29
+ print(resp.response_code, resp.checkout_request_id)
30
+ ```
31
+
32
+ `from_env()` reads `MPESA_CONSUMER_KEY`, `MPESA_CONSUMER_SECRET`, `MPESA_SHORTCODE` and `MPESA_PASSKEY`. A missing variable raises `ValueError` naming it. `MPESA_ENVIRONMENT` accepts `sandbox` (default), `production` or `prod`; `MpesaClient.from_env("prod")` overrides the variable.
33
+
34
+ > Accepted ≠ paid. `response_code == "0"` means the prompt was queued. Settle only after an `stk_query` bound to your stored `checkout_request_id`, and require `result.verify_amount(order_amount)`.
35
+
36
+ > **Money is whole KES.** Amounts are integers, never floats; inbound callback amounts are validated against a canonical grammar with no rounding or fractional KES. A callback amount is advisory until checked against your stored order.
37
+
38
+ One hardened core is implemented in Go, Python and TypeScript against one executable wire contract; a shared fixture corpus pins identical wire behaviour across all three engines. Go and TypeScript have no runtime dependencies; Python uses `requests` and `cryptography`.
39
+
40
+ ## Receiving callbacks
41
+
42
+ `token_on_file`, `repo`, `client`, `mark_paid` and `mark_pending_reconcile` are application code.
43
+
44
+ Daraja callbacks are unsigned; the query round-trip and stored-amount check are the settlement controls. Indeterminate results are never auto-failed — reconcile them.
45
+
46
+ A valid token proves only that the caller knows the URL; it authenticates nothing about the body or the payment. This example returns 200 for a token mismatch — a deliberate per-engine difference, not a weaker control. Malformed bodies are ACKed 200 rather than returning 5xx. Framework-level body limits (Flask MAX_CONTENT_LENGTH, express.raw() default) can still return 413 before the handler — configure them to match your policy.
47
+
48
+ ```python
49
+ from flask import Flask, request
50
+ from mpesa import ResultClass, STKQueryRequest, StkCallbackResult, callback_token_equal
51
+
52
+ app = Flask(__name__)
53
+ app.config["MAX_CONTENT_LENGTH"] = 1 << 20
54
+
55
+
56
+ @app.post("/mpesa/callback/<token>")
57
+ def stk_callback(token: str):
58
+ if not callback_token_equal(token_on_file, token):
59
+ return "", 200
60
+ try:
61
+ result = StkCallbackResult.from_json(request.get_data())
62
+ except ValueError:
63
+ return "", 200 # malformed: ACK, never a 5xx
64
+ order = repo.by_checkout(result.checkout_request_id)
65
+ if order is None:
66
+ return "", 200
67
+ paid = False
68
+ if result.classify() is ResultClass.SUCCESS:
69
+ resp = client.stk_query(STKQueryRequest(
70
+ checkout_request_id=result.checkout_request_id))
71
+ if resp.result_code == "0" and result.verify_amount(order.amount):
72
+ mark_paid(order)
73
+ paid = True
74
+ if not paid:
75
+ mark_pending_reconcile(order)
76
+ return "", 200
77
+ ```
78
+
79
+ ## What is covered
80
+
81
+ STK Push/Query, B2C, C2B register/simulate, Transaction Status, Reversal, Account Balance, Dynamic QR, B2B, Tax Remittance and Bill Manager — plus typed callbacks, token refresh with `401.003.01` retry-once, and redacted credential rendering.
82
+
83
+ ## Documentation
84
+
85
+ Full guide and cross-engine contract: [the repository README](https://github.com/anthrodjear/mpesa-sdk#readme).
@@ -0,0 +1,133 @@
1
+ """M-Pesa Daraja SDK -- public API surface.
2
+
3
+ Covers all twelve business endpoints of the Safaricom Daraja platform
4
+ (STK Push/Query, B2B payout, B2C payout, Tax Remittance, Transaction
5
+ Status, Reversal, Account Balance, C2B register/simulate, Dynamic QR,
6
+ Bill Manager register/query/update/delete -- contracts in docs/apis/).
7
+ Quickstart (credentials via env vars, per client.py convention)::
8
+
9
+ import os
10
+ from mpesa import Config, Environment, MpesaClient
11
+ from mpesa.requests_sync import STKPushRequest
12
+ from mpesa.enums import TransactionType
13
+
14
+ cfg = Config(consumer_key=os.environ["MPESA_CONSUMER_KEY"],
15
+ consumer_secret=os.environ["MPESA_CONSUMER_SECRET"],
16
+ shortcode=os.environ["MPESA_SHORTCODE"],
17
+ passkey=os.environ["MPESA_PASSKEY"],
18
+ environment=Environment.from_config(
19
+ os.environ.get("MPESA_ENVIRONMENT")))
20
+ client = MpesaClient(cfg)
21
+ resp = client.stk_push(STKPushRequest(...))
22
+
23
+ Safety notes: INDETERMINATE results may still settle minutes later --
24
+ never auto-fail/auto-refund them; callbacks are UNSIGNED -- settle only
25
+ via stk_query bound to YOUR CheckoutRequestID record (binding dedups
26
+ duplicate deliveries, it does not authenticate origin); secrets/tokens
27
+ are redacted from every repr.
28
+ """
29
+
30
+ from .auth import TokenManager
31
+ from .callback_token import callback_token_equal, new_callback_token
32
+ from .callbacks import MetadataItem, StkCallbackResult
33
+ from .classification import ResultClass, classify_result_code
34
+ from .client import MpesaClient
35
+ from .config import Config
36
+ from .enums import (
37
+ ORGANIZATION_SHORTCODE,
38
+ RECEIVER_IDENTIFIER_ORG,
39
+ CommandID,
40
+ Environment,
41
+ QRTrxCode,
42
+ ResponseType,
43
+ TransactionType,
44
+ )
45
+ from .exceptions import InvalidTokenError, MpesaError, RefreshRateLimitedError
46
+ from .helpers import generate_password, normalize_phone, security_credential
47
+ from .limits import DEFAULT_TRANSACTION_LIMITS, ServiceLimits, TransactionLimits
48
+ from .requests_async import (
49
+ AccountBalanceRequest,
50
+ B2BRequest,
51
+ B2CPayoutRequest,
52
+ ReversalRequest,
53
+ TaxRemittanceRequest,
54
+ TransactionStatusRequest,
55
+ )
56
+ from .requests_sync import (
57
+ BillDeleteRequest,
58
+ BillQueryRequest,
59
+ BillRegisterRequest,
60
+ BillUpdateRequest,
61
+ C2BRegisterRequest,
62
+ C2BSimulateRequest,
63
+ QRCodeRequest,
64
+ STKPushRequest,
65
+ STKQueryRequest,
66
+ )
67
+ from .responses import (
68
+ B2CResponse,
69
+ BillAckResponse,
70
+ C2BAckResponse,
71
+ ConversationResponse,
72
+ OAuthToken,
73
+ QRCodeResponse,
74
+ STKPushResponse,
75
+ STKQueryResponse,
76
+ )
77
+ from .results import AsyncResult, BalanceSegment, parse_balance_segments
78
+
79
+ __version__ = "0.9.0"
80
+
81
+ __all__ = [
82
+ "AccountBalanceRequest",
83
+ "AsyncResult",
84
+ "B2BRequest",
85
+ "B2CPayoutRequest",
86
+ "B2CResponse",
87
+ "BalanceSegment",
88
+ "BillAckResponse",
89
+ "BillDeleteRequest",
90
+ "BillQueryRequest",
91
+ "BillRegisterRequest",
92
+ "BillUpdateRequest",
93
+ "C2BAckResponse",
94
+ "C2BRegisterRequest",
95
+ "C2BSimulateRequest",
96
+ "CommandID",
97
+ "Config",
98
+ "ConversationResponse",
99
+ "DEFAULT_TRANSACTION_LIMITS",
100
+ "Environment",
101
+ "InvalidTokenError",
102
+ "MetadataItem",
103
+ "MpesaClient",
104
+ "MpesaError",
105
+ "OAuthToken",
106
+ "ORGANIZATION_SHORTCODE",
107
+ "QRCodeRequest",
108
+ "QRCodeResponse",
109
+ "QRTrxCode",
110
+ "RECEIVER_IDENTIFIER_ORG",
111
+ "RefreshRateLimitedError",
112
+ "ResponseType",
113
+ "ResultClass",
114
+ "ReversalRequest",
115
+ "STKPushRequest",
116
+ "STKPushResponse",
117
+ "STKQueryRequest",
118
+ "STKQueryResponse",
119
+ "ServiceLimits",
120
+ "StkCallbackResult",
121
+ "TaxRemittanceRequest",
122
+ "TokenManager",
123
+ "TransactionLimits",
124
+ "TransactionStatusRequest",
125
+ "TransactionType",
126
+ "callback_token_equal",
127
+ "classify_result_code",
128
+ "generate_password",
129
+ "new_callback_token",
130
+ "normalize_phone",
131
+ "parse_balance_segments",
132
+ "security_credential",
133
+ ]
@@ -0,0 +1,183 @@
1
+ """Shared ingestion and streaming guards (single source of truth).
2
+
3
+ This is the BYTE-CAP module: it bounds how many bytes a wire body may carry
4
+ before any decode. Per-merchant amount ceilings (``max_per_transaction`` /
5
+ ``max_per_day``, KES rather than bytes) live in the separate
6
+ ``mpesa/limits.py`` module -- different name, different subject, and the two
7
+ are never consulted together.
8
+
9
+ Every Daraja-facing reader in this package enforces the SAME 1 MiB bound
10
+ (Go ``maxResponseLen`` / TS ``MAX_RESPONSE_LEN`` parity):
11
+
12
+ * :data:`MAX_BODY_BYTES` -- the cap, measured in BYTES, not characters.
13
+ A ``str`` body of 1M CJK characters is ~3 MiB on the wire and must not
14
+ bypass a char-count check, so :func:`check_body_size` measures ``str``
15
+ input as ``len(data.encode("utf-8"))`` while ``bytes``/``bytearray``
16
+ input is measured directly.
17
+ * :func:`check_body_size` -- pre-parse gate used by the callback, result
18
+ and sync-response models before ``json.loads``.
19
+ * :func:`read_capped` (alias :func:`_read_capped`) -- bounded streaming
20
+ reader shared by ``auth.TokenManager._refresh`` and
21
+ ``client.MpesaClient._send`` (previously near-identical ``iter_content``
22
+ cap loops in both places). Reads at most ``MAX_BODY_BYTES + 1`` bytes
23
+ via ``iter_content`` -- Go ``LimitReader`` parity -- so a gzip bomb
24
+ aborts mid-stream instead of being fully materialised by a pre-read
25
+ ``.content`` access. An optional monotonic ``deadline`` bounds the TOTAL
26
+ read time (slowloris defence): the socket's per-read timeout only caps
27
+ each chunk, a deadline caps the whole body. The socket is released in
28
+ ``finally`` so abort paths never leak connections.
29
+
30
+ Usage::
31
+
32
+ from ._limits import MAX_BODY_BYTES, check_body_size, read_capped
33
+
34
+ check_body_size(raw, "callback body") # raises ValueError when over cap
35
+ body = read_capped(response, "oauth/v1/generate response")
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import threading
41
+ import time
42
+ from typing import Any
43
+
44
+ __all__ = ["MAX_BODY_BYTES", "check_body_size", "read_capped", "_read_capped"]
45
+
46
+ #: Ingestion cap in BYTES (Go maxResponseLen / TS MAX_RESPONSE_LEN parity).
47
+ MAX_BODY_BYTES = 1_048_576
48
+
49
+
50
+ def check_body_size(data: "bytes | bytearray | str",
51
+ label: str = "response body") -> None:
52
+ """Reject bodies over :data:`MAX_BODY_BYTES`, measured in UTF-8 bytes.
53
+
54
+ ``bytes``/``bytearray`` input is measured directly; ``str`` input is
55
+ measured as ``len(data.encode("utf-8"))`` so multi-byte payloads
56
+ (e.g. 400k CJK chars ~= 1.2 MiB) cannot smuggle up to 4x the intended
57
+ bound past a char-count check. Anything else (already-decoded dicts)
58
+ is unchecked -- the gate only applies to raw wire bodies.
59
+
60
+ Args:
61
+ data: Raw wire body (bytes, bytearray or str).
62
+ label: Human context interpolated into the error, e.g.
63
+ ``"callback body"`` or ``"STKPushResponse response"``.
64
+
65
+ Raises:
66
+ ValueError: if the byte size exceeds :data:`MAX_BODY_BYTES`.
67
+
68
+ Example::
69
+
70
+ check_body_size(raw, "callback body")
71
+ """
72
+ if isinstance(data, (bytes, bytearray)):
73
+ size = len(data)
74
+ elif isinstance(data, str):
75
+ size = len(data.encode("utf-8"))
76
+ else: # decoded dicts carry no wire size: nothing to gate.
77
+ return
78
+ if size > MAX_BODY_BYTES:
79
+ raise ValueError(
80
+ f"mpesa: {label} exceeds {MAX_BODY_BYTES} bytes")
81
+
82
+
83
+ def read_capped(response: Any, label: str,
84
+ deadline: "float | None" = None) -> bytes:
85
+ """Stream at most ``MAX_BODY_BYTES + 1`` bytes from *response*.
86
+
87
+ The shared bounded reader for the OAuth leg (auth.py) and the
88
+ business leg (client.py): accumulates ``iter_content`` chunks,
89
+ aborts with ``ValueError`` the moment the total passes the cap
90
+ (BEFORE any ``json`` parse, so oversize bodies never reach the
91
+ decoder), and always releases the connection via ``response.close()``
92
+ in ``finally`` -- including the abort path.
93
+
94
+ An optional monotonic *deadline* (an absolute ``time.monotonic()``
95
+ instant) adds a REAL total read budget on top of the byte cap. The
96
+ socket's per-read timeout bounds ONE chunk only: a slowloris peer that
97
+ trickles sub-timeout bytes can otherwise hold a blocking ``iter_content``
98
+ call open indefinitely while staying under the byte cap. A watchdog
99
+ timer closes the response at the deadline, which INTERRUPTS the blocked
100
+ read; the expired flag is then checked before/after the stream and on
101
+ any transport exception. ``TimeoutError`` is distinct from the oversize
102
+ ``ValueError`` so callers never mislabel a timeout as a big body.
103
+
104
+ Plain ``bytes`` are returned instead of the ``Response`` because
105
+ ``requests.Response.content`` is a getter-only property; callers must
106
+ read status/headers off *response* themselves (safe after close --
107
+ they are already materialised).
108
+
109
+ Args:
110
+ response: Streamed HTTP response exposing ``iter_content`` and
111
+ ``close`` (real ``requests.Response`` or a duck-typed fake).
112
+ label: Endpoint context for the oversize/timeout error, e.g.
113
+ ``"oauth/v1/generate response"`` or ``"/mpesa/stkpush/..."``.
114
+ deadline: Absolute ``time.monotonic()`` instant by which the read
115
+ must finish, or ``None`` (default) to keep the historic
116
+ byte-cap-only behaviour. Optional so existing callers and
117
+ tests that pass just ``(response, label)`` keep working.
118
+
119
+ Raises:
120
+ ValueError: if the streamed body exceeds :data:`MAX_BODY_BYTES`.
121
+ TimeoutError: if the deadline passes before the body is fully read.
122
+
123
+ Example::
124
+
125
+ deadline = time.monotonic() + 30.0
126
+ body = read_capped(response, "oauth/v1/generate response",
127
+ deadline=deadline)
128
+ """
129
+ chunks: list[bytes] = []
130
+ total = 0
131
+ expired = False
132
+ timer: "threading.Timer | None" = None
133
+
134
+ def _expire() -> None:
135
+ # Runs on the watchdog thread. Closing the response releases the
136
+ # socket so a blocked iter_content() read returns/raises promptly.
137
+ nonlocal expired
138
+ expired = True
139
+ try:
140
+ response.close()
141
+ except Exception:
142
+ pass
143
+
144
+ def _check_deadline() -> None:
145
+ if expired or (deadline is not None and time.monotonic() >= deadline):
146
+ raise TimeoutError(f"mpesa: {label} exceeded request deadline")
147
+
148
+ try:
149
+ _check_deadline()
150
+ if deadline is not None:
151
+ remaining = deadline - time.monotonic()
152
+ if remaining <= 0:
153
+ raise TimeoutError(f"mpesa: {label} exceeded request deadline")
154
+ timer = threading.Timer(remaining, _expire)
155
+ timer.daemon = True
156
+ timer.start()
157
+ try:
158
+ # Bounded chunks keep byte accounting responsive; the watchdog
159
+ # is what actually interrupts a trickle that blocks one read.
160
+ for chunk in response.iter_content(min(MAX_BODY_BYTES + 1, 65536)):
161
+ _check_deadline()
162
+ chunks.append(chunk)
163
+ total += len(chunk)
164
+ if total > MAX_BODY_BYTES:
165
+ raise ValueError(
166
+ f"mpesa: {label} exceeds {MAX_BODY_BYTES} bytes")
167
+ _check_deadline()
168
+ except TimeoutError:
169
+ raise
170
+ except Exception as exc:
171
+ if expired:
172
+ raise TimeoutError(
173
+ f"mpesa: {label} exceeded request deadline") from exc
174
+ raise
175
+ finally:
176
+ if timer is not None:
177
+ timer.cancel()
178
+ response.close()
179
+ return b"".join(chunks)
180
+
181
+
182
+ #: Back-compat alias: the task-level name for the shared streaming reader.
183
+ _read_capped = read_capped