fast-billing-sdk 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ from .client import AsyncBillingClient, PreparedEvent, ReportResult, ResultStatus
2
+
3
+ __all__ = ["AsyncBillingClient", "PreparedEvent", "ReportResult", "ResultStatus"]
@@ -0,0 +1,232 @@
1
+ import asyncio
2
+ import json
3
+ import math
4
+ import platform
5
+ import re
6
+ import time
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass
9
+ from decimal import Decimal
10
+ from enum import StrEnum
11
+ from importlib.metadata import version
12
+ from urllib.parse import urlsplit
13
+ from uuid import uuid4
14
+
15
+ import aiohttp
16
+
17
+ SDK_VERSION = version("fast-billing-sdk")
18
+ RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
19
+ IDENTIFIER = re.compile(r"[A-Za-z0-9_-]{1,64}")
20
+ PRODUCT_CODE = re.compile(r"[a-z0-9_]{1,64}")
21
+ SOURCE_LABEL = re.compile(r"[A-Za-z0-9_.-]{1,64}")
22
+ POINT_CODE = re.compile(r"[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+")
23
+ QUANTITY = re.compile(r"[0-9]{1,14}(?:\.[0-9]{1,6})?")
24
+ SECRET_KEYS = {
25
+ "authorization", "cookie", "setcookie", "password", "passwd", "secret", "apikey",
26
+ "accesstoken", "refreshtoken", "token", "privatekey", "secretkey", "clientsecret",
27
+ "databaseurl", "mysqlurl", "rabbitmqurl", "redisurl", "mongodburl", "dsn", "connectionstring",
28
+ }
29
+ CREDENTIAL_URL = re.compile(r"://[^\s/@]+:[^\s/@]+@")
30
+
31
+
32
+ def _identifier(value):
33
+ return isinstance(value, str) and 0 < len(value) <= 128 and value.strip() == value and not any(
34
+ ord(char) < 32 for char in value
35
+ )
36
+
37
+
38
+ def _correlation(value):
39
+ return isinstance(value, str) and IDENTIFIER.fullmatch(value) is not None
40
+
41
+
42
+ def _check_metadata(value):
43
+ if isinstance(value, dict):
44
+ for key, child in value.items():
45
+ if not isinstance(key, str) or re.sub(r"[^a-z0-9]", "", key.lower()) in SECRET_KEYS:
46
+ raise ValueError("元数据含不允许的字段")
47
+ _check_metadata(child)
48
+ elif isinstance(value, (tuple, list)):
49
+ for child in value:
50
+ _check_metadata(child)
51
+ elif isinstance(value, str) and CREDENTIAL_URL.search(value):
52
+ raise ValueError("元数据含连接凭据")
53
+
54
+
55
+ def _quantity(value):
56
+ if type(value) is int and 0 < value < 100_000_000_000_000:
57
+ value = str(value)
58
+ if isinstance(value, Decimal) and value.is_finite() and value.adjusted() <= 13 and value.as_tuple().exponent >= -6:
59
+ value = format(value, "f")
60
+ if not isinstance(value, str) or not QUANTITY.fullmatch(value) or Decimal(value) <= 0:
61
+ raise ValueError("quantity 须为正十进制数,最多 14 位整数和 6 位小数")
62
+ return value
63
+
64
+
65
+ class ResultStatus(StrEnum):
66
+ SUCCESS = "SUCCESS"
67
+ FAILED = "FAILED"
68
+ UNKNOWN = "UNKNOWN"
69
+
70
+
71
+ @dataclass(frozen=True, slots=True)
72
+ class ReportResult:
73
+ status: ResultStatus
74
+ attempts: int = 0
75
+ request_no: str | None = None
76
+ trace_id: str | None = None
77
+ receipt_id: str | None = None
78
+ processing_status: str | None = None
79
+ error_code: str | None = None
80
+
81
+ @property
82
+ def retryable(self):
83
+ return self.status is ResultStatus.UNKNOWN
84
+
85
+
86
+ @dataclass(frozen=True, slots=True, init=False)
87
+ class PreparedEvent:
88
+ _body: bytes
89
+ request_no: str
90
+ trace_id: str
91
+
92
+ def __init__(self, payload: str | bytes):
93
+ data = json.loads(payload)
94
+ if not isinstance(data, dict) or data.get("schema_version") != 1:
95
+ raise ValueError("冻结上报协议无效")
96
+ if not _correlation(data.get("request_no")) or not _correlation(data.get("trace_id")):
97
+ raise ValueError("冻结上报缺少有效编号")
98
+ _check_metadata(data)
99
+ object.__setattr__(self, "_body", payload.encode("utf-8") if isinstance(payload, str) else payload)
100
+ object.__setattr__(self, "request_no", data["request_no"])
101
+ object.__setattr__(self, "trace_id", data["trace_id"])
102
+
103
+ def to_json(self):
104
+ return self._body.decode("utf-8")
105
+
106
+
107
+ class AsyncBillingClient:
108
+ def __init__(self, base_url: str, *, product_code: str, source_system: str, source_env: str,
109
+ max_attempts: int = 3, timeout: float = 7.0, retry_delay: float = 0.25):
110
+ url = urlsplit(base_url)
111
+ if url.scheme not in {"http", "https"} or not url.hostname or url.username is not None or url.query or url.fragment:
112
+ raise ValueError("base_url 须为无凭据的 HTTP(S) 地址")
113
+ if not PRODUCT_CODE.fullmatch(product_code) or not all(SOURCE_LABEL.fullmatch(v) for v in (source_system, source_env)):
114
+ raise ValueError("产品或来源配置无效")
115
+ if type(max_attempts) is not int or max_attempts < 1 or not math.isfinite(timeout) or timeout <= 0:
116
+ raise ValueError("超时或重试次数无效")
117
+ if not math.isfinite(retry_delay) or retry_delay < 0:
118
+ raise ValueError("重试间隔无效")
119
+ self._endpoint = base_url.rstrip("/") + "/v1/events/report"
120
+ self._product_code = product_code
121
+ self._source_system = source_system
122
+ self._source_env = source_env
123
+ self._max_attempts = max_attempts
124
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
125
+ self._retry_delay = retry_delay
126
+ self._session: aiohttp.ClientSession | None = None
127
+
128
+ def prepare_event(self, event: Mapping[str, object]):
129
+ required = {"task_id", "completed_at", "source", "team_id", "usage"}
130
+ optional = {"user_id", "app_id", "ext", "client_context", "request_no", "trace_id"}
131
+ if not isinstance(event, Mapping) or not required <= event.keys() or event.keys() - required - optional:
132
+ raise ValueError("业务字典字段无效")
133
+ source = event["source"]
134
+ owner_field = {"web": "user_id", "api": "app_id"}.get(source) if isinstance(source, str) else None
135
+ if not owner_field or not _identifier(event.get(owner_field)) or event.get(
136
+ "app_id" if owner_field == "user_id" else "user_id"
137
+ ) is not None:
138
+ raise ValueError("业务来源与归属字段不匹配")
139
+ if not _identifier(event["team_id"]) or not _identifier(event["task_id"]):
140
+ raise ValueError("团队 ID 或任务 ID 无效")
141
+ completed = event["completed_at"]
142
+ if type(completed) is not int or not 1_000_000_000 <= completed <= 9_999_999_999:
143
+ raise ValueError("completed_at 须为 Unix 秒时间戳")
144
+ usage = event["usage"]
145
+ if not isinstance(usage, (list, tuple)) or not 1 <= len(usage) <= 100:
146
+ raise ValueError("usage 须包含 1 至 100 条用量")
147
+ items = []
148
+ codes = set()
149
+ for item in usage:
150
+ if not isinstance(item, Mapping) or item.keys() != {"code", "quantity"}:
151
+ raise ValueError("用量明细须包含 code 和 quantity")
152
+ code = item["code"]
153
+ if not isinstance(code, str) or len(code) > 160 or not POINT_CODE.fullmatch(code) or not code.startswith(
154
+ self._product_code + ":"
155
+ ) or code in codes:
156
+ raise ValueError("计费点无效或重复")
157
+ codes.add(code)
158
+ items.append({"code": code, "quantity": _quantity(item["quantity"])})
159
+ for key in ("ext", "client_context"):
160
+ content = event.get(key)
161
+ if content is not None:
162
+ if not isinstance(content, dict):
163
+ raise ValueError("元数据须为字典")
164
+ _check_metadata(content)
165
+ if len(json.dumps(content, ensure_ascii=False, allow_nan=False).encode()) > 16 * 1024:
166
+ raise ValueError("元数据超过 16 KiB")
167
+ payload = {
168
+ "schema_version": 1, "request_no": event.get("request_no") or uuid4().hex,
169
+ "trace_id": event.get("trace_id") or uuid4().hex,
170
+ "product_code": self._product_code, "team_id": event["team_id"], owner_field: event[owner_field],
171
+ "biz_id": event["task_id"], "occurrence_no": 1, "source": source,
172
+ "source_system": self._source_system, "source_env": self._source_env,
173
+ "consume_time": completed, "report_time": int(time.time()), "sdk_version": SDK_VERSION,
174
+ "sdk_context": {"python_version": platform.python_version(), "sdk_version": SDK_VERSION},
175
+ "items": items, "ext": event.get("ext"), "client_context": event.get("client_context"),
176
+ }
177
+ return PreparedEvent(json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
178
+
179
+ async def report(self, event: PreparedEvent | Mapping[str, object]) -> ReportResult:
180
+ try:
181
+ prepared = event if isinstance(event, PreparedEvent) else self.prepare_event(event)
182
+ except (ValueError, TypeError, RecursionError):
183
+ return ReportResult(ResultStatus.FAILED, error_code="INVALID_EVENT")
184
+ if self._session is None or self._session.closed:
185
+ self._session = aiohttp.ClientSession(
186
+ timeout=self._timeout, cookie_jar=aiohttp.DummyCookieJar(),
187
+ headers={"Content-Type": "application/json", "User-Agent": f"fast-billing-sdk/{SDK_VERSION}"},
188
+ )
189
+ for attempt in range(1, self._max_attempts + 1):
190
+ fields = {"attempts": attempt, "request_no": prepared.request_no, "trace_id": prepared.trace_id}
191
+ try:
192
+ async with self._session.post(self._endpoint, data=prepared._body, allow_redirects=False) as response:
193
+ try:
194
+ data = await response.json(content_type=None)
195
+ except (ValueError, UnicodeError):
196
+ data = None
197
+ result = self._result(response.status, data, fields)
198
+ except (aiohttp.ClientError, TimeoutError):
199
+ result = ReportResult(ResultStatus.UNKNOWN, error_code="NETWORK_ERROR", **fields)
200
+ if not result.retryable or attempt == self._max_attempts:
201
+ return result
202
+ await asyncio.sleep(min(5, self._retry_delay * 2 ** min(attempt - 1, 8)))
203
+ raise AssertionError("max_attempts must be positive")
204
+
205
+ @staticmethod
206
+ def _result(status, data, fields):
207
+ data = data if isinstance(data, dict) else {}
208
+ if status == 200:
209
+ receipt = data.get("data")
210
+ if data.get("code") == "OK" and isinstance(receipt, dict):
211
+ kind = receipt.get("status")
212
+ processing = receipt.get("processing_status")
213
+ receipt_id = receipt.get("receipt_id")
214
+ if isinstance(receipt_id, str) and receipt_id and processing in ("accepted", "processed", "failed") and (
215
+ kind == "duplicate" or kind == "accepted" and receipt.get("request_no") == fields["request_no"]
216
+ ):
217
+ return ReportResult(ResultStatus.SUCCESS, receipt_id=receipt_id, processing_status=processing, **fields)
218
+ return ReportResult(ResultStatus.UNKNOWN, error_code="INVALID_RECEIPT", **fields)
219
+ code = data.get("code")
220
+ code = code if isinstance(code, str) else f"HTTP_{status}"
221
+ outcome = ResultStatus.FAILED if 400 <= status < 500 and status not in RETRYABLE_STATUS else ResultStatus.UNKNOWN
222
+ return ReportResult(outcome, error_code=code, **fields)
223
+
224
+ async def aclose(self):
225
+ if self._session is not None:
226
+ await self._session.close()
227
+
228
+ async def __aenter__(self):
229
+ return self
230
+
231
+ async def __aexit__(self, *_exc):
232
+ await self.aclose()
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: fast-billing-sdk
3
+ Version: 1.0.0
4
+ Summary: Python client for reporting completed business tasks to Seabase Billing
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: Programming Language :: Python :: 3.11
7
+ Classifier: Programming Language :: Python :: 3.12
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: aiohttp<4,>=3.10
11
+
12
+ # Fast Billing SDK
13
+
14
+ Async Python 3.11+ client for reporting completed business tasks.
15
+
16
+ ```bash
17
+ python -m pip install fast-billing-sdk==1.0.0
18
+ ```
19
+
20
+ ```python
21
+ import os
22
+
23
+ from fast_billing_sdk import AsyncBillingClient
24
+
25
+
26
+ async def report_completed_task(event):
27
+ async with AsyncBillingClient(
28
+ base_url=os.environ["BILLING_API_URL"],
29
+ product_code=os.environ["BILLING_PRODUCT_CODE"],
30
+ source_system=os.environ["BILLING_SOURCE_SYSTEM"],
31
+ source_env=os.environ["BILLING_SOURCE_ENV"],
32
+ ) as billing:
33
+ return await billing.report(event)
34
+ ```
35
+
36
+ A task dictionary contains `task_id`, `completed_at` (Unix seconds), `source`, `team_id`, and `usage`. Web tasks supply `user_id`, and open API tasks supply `app_id`. Each usage entry contains a billing point `code` and a positive `quantity`. Optional `ext` carries business metadata. The client sends one report for the entire task.
37
+
38
+ For durable retries, create a prepared event with `billing.prepare_event(event)`, persist the result of `to_json()`, then send it via `await billing.report(prepared_event)`. Use `PreparedEvent(saved_json)` to restore that exact payload. A `SUCCESS` result confirms API receipt. `processing_status` reflects asynchronous processing. Reuse the saved payload after an `UNKNOWN` result.
@@ -0,0 +1,6 @@
1
+ fast_billing_sdk/__init__.py,sha256=SoROg-981ltXlD3r1Jkf0ve1NwzLEADEHU-lpmMlY2Q,165
2
+ fast_billing_sdk/client.py,sha256=blcr3PAiaEMUZQV2Oi8ZvV1qnmXxVw6D12GBxGpfC3g,11134
3
+ fast_billing_sdk-1.0.0.dist-info/METADATA,sha256=WF4RfKlnbfxgSQGLHZCl_bWBozU6e5_45styYOs2d1A,1719
4
+ fast_billing_sdk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ fast_billing_sdk-1.0.0.dist-info/top_level.txt,sha256=bF7X0CVT3pC2jSTXq_QXnY9H8fDtN1nx0w9NJhdRK1c,17
6
+ fast_billing_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ fast_billing_sdk