fiscalbase 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.
- fiscalbase/__init__.py +14 -0
- fiscalbase/_transport.py +245 -0
- fiscalbase/api.py +1146 -0
- fiscalbase/client.py +148 -0
- fiscalbase/py.typed +0 -0
- fiscalbase/types.py +13289 -0
- fiscalbase/webhooks.py +68 -0
- fiscalbase-1.0.0.dist-info/METADATA +175 -0
- fiscalbase-1.0.0.dist-info/RECORD +11 -0
- fiscalbase-1.0.0.dist-info/WHEEL +4 -0
- fiscalbase-1.0.0.dist-info/licenses/LICENSE +201 -0
fiscalbase/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from ._transport import FiscalbaseError, Result
|
|
2
|
+
from .client import Document, DocumentFilters, Fiscalbase, QuoteFilters
|
|
3
|
+
from .types import CreateInvoice, Problem
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"CreateInvoice",
|
|
7
|
+
"Document",
|
|
8
|
+
"DocumentFilters",
|
|
9
|
+
"Fiscalbase",
|
|
10
|
+
"FiscalbaseError",
|
|
11
|
+
"Problem",
|
|
12
|
+
"QuoteFilters",
|
|
13
|
+
"Result",
|
|
14
|
+
]
|
fiscalbase/_transport.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import math
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import AsyncIterator, Mapping
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import Any, Generic, Literal, TypeVar, cast
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from .types import Problem
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Result(Generic[T]):
|
|
21
|
+
data: T
|
|
22
|
+
response: httpx.Response
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def request_id(self) -> str | None:
|
|
26
|
+
return cast(str | None, self.response.headers.get("x-request-id"))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class FiscalbaseError(Exception):
|
|
30
|
+
"""An HTTP refusal or unexpected response, with the original response for diagnostics."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, problem: Problem, response: httpx.Response):
|
|
33
|
+
self.problem = problem
|
|
34
|
+
self.response = response
|
|
35
|
+
self.request_id = response.headers.get("x-request-id") or problem.get("request_id")
|
|
36
|
+
super().__init__(f"HTTP {response.status_code}: {problem['title']}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def key(value: str | None, *, required: bool) -> str | None:
|
|
40
|
+
if value is None and not required:
|
|
41
|
+
return None
|
|
42
|
+
if not isinstance(value, str) or not 1 <= len(value) <= 255 or value.strip() != value:
|
|
43
|
+
raise ValueError("Expected a stable idempotency_key of 1–255 characters")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def segment(value: str) -> str:
|
|
48
|
+
if not isinstance(value, str) or value in {"", ".", ".."}:
|
|
49
|
+
raise ValueError("Expected a non-empty path segment")
|
|
50
|
+
return quote(value, safe="")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _params(query: Mapping[str, object] | None) -> httpx.QueryParams:
|
|
54
|
+
def text(value: object) -> str:
|
|
55
|
+
return str(value).lower() if isinstance(value, bool) else str(value)
|
|
56
|
+
|
|
57
|
+
pairs: list[tuple[str, str]] = []
|
|
58
|
+
for name, value in (query or {}).items():
|
|
59
|
+
if isinstance(value, Mapping):
|
|
60
|
+
pairs.extend((f"{name}[{k}]", text(v)) for k, v in value.items())
|
|
61
|
+
elif isinstance(value, list):
|
|
62
|
+
pairs.extend((name, text(item)) for item in value)
|
|
63
|
+
elif value is not None:
|
|
64
|
+
pairs.append((name, text(value)))
|
|
65
|
+
return httpx.QueryParams(tuple(pairs))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _json(response: httpx.Response) -> Any:
|
|
69
|
+
try:
|
|
70
|
+
return response.json()
|
|
71
|
+
except ValueError:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _failure(response: httpx.Response, kind: str, title: str) -> FiscalbaseError:
|
|
76
|
+
problem: Problem = {"type": kind, "title": title, "status": response.status_code}
|
|
77
|
+
if request_id := response.headers.get("x-request-id"):
|
|
78
|
+
problem["request_id"] = request_id
|
|
79
|
+
return FiscalbaseError(problem, response)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _check_status(response: httpx.Response) -> None:
|
|
83
|
+
if response.is_success:
|
|
84
|
+
return
|
|
85
|
+
value = _json(response)
|
|
86
|
+
if (
|
|
87
|
+
isinstance(value, dict)
|
|
88
|
+
and isinstance(value.get("type"), str)
|
|
89
|
+
and isinstance(value.get("title"), str)
|
|
90
|
+
and type(value.get("status")) is int
|
|
91
|
+
):
|
|
92
|
+
raise FiscalbaseError(cast(Problem, value), response)
|
|
93
|
+
raise _failure(response, "http_error", response.reason_phrase or f"HTTP {response.status_code}")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _transient(response: httpx.Response) -> bool:
|
|
97
|
+
if response.status_code == 409:
|
|
98
|
+
problem = _json(response)
|
|
99
|
+
return isinstance(problem, dict) and problem.get("code") == "idempotency_key_in_progress"
|
|
100
|
+
return response.status_code in {429, 500, 502, 503, 504}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _retry_after(response: httpx.Response) -> float:
|
|
104
|
+
value = response.headers.get("retry-after", "")
|
|
105
|
+
if not value:
|
|
106
|
+
return 0
|
|
107
|
+
if re.fullmatch(r"[0-9]+", value):
|
|
108
|
+
return float(value)
|
|
109
|
+
try:
|
|
110
|
+
return parsedate_to_datetime(value).timestamp() - time.time()
|
|
111
|
+
except (ValueError, TypeError, OverflowError):
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Transport:
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
api_key: str,
|
|
119
|
+
timeout: float,
|
|
120
|
+
max_retries: int,
|
|
121
|
+
transport: httpx.AsyncBaseTransport | None,
|
|
122
|
+
):
|
|
123
|
+
if not isinstance(api_key, str) or not re.fullmatch(r"fb_(sandbox|live|test)_\S+", api_key):
|
|
124
|
+
raise ValueError(
|
|
125
|
+
"Expected a Fiscalbase server API key (fb_sandbox_, fb_test_, or fb_live_)"
|
|
126
|
+
)
|
|
127
|
+
if (
|
|
128
|
+
isinstance(timeout, bool)
|
|
129
|
+
or not math.isfinite(timeout)
|
|
130
|
+
or not 0.001 <= timeout <= 2147483.647
|
|
131
|
+
):
|
|
132
|
+
raise ValueError("timeout must be between 0.001 and 2147483.647 seconds")
|
|
133
|
+
if type(max_retries) is not int or not 0 <= max_retries <= 5:
|
|
134
|
+
raise ValueError("max_retries must be an integer from 0 to 5")
|
|
135
|
+
origin = (
|
|
136
|
+
"https://api-sandbox.fiscalbase.io"
|
|
137
|
+
if api_key.startswith("fb_sandbox_")
|
|
138
|
+
else "https://api.fiscalbase.io"
|
|
139
|
+
)
|
|
140
|
+
self._http = httpx.AsyncClient(
|
|
141
|
+
base_url=origin,
|
|
142
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
143
|
+
timeout=timeout,
|
|
144
|
+
transport=transport,
|
|
145
|
+
follow_redirects=False,
|
|
146
|
+
)
|
|
147
|
+
self._timeout = timeout
|
|
148
|
+
self._max_retries = max_retries
|
|
149
|
+
|
|
150
|
+
async def aclose(self) -> None:
|
|
151
|
+
await self._http.aclose()
|
|
152
|
+
|
|
153
|
+
async def _send(
|
|
154
|
+
self,
|
|
155
|
+
method: str,
|
|
156
|
+
path: str,
|
|
157
|
+
*,
|
|
158
|
+
query: Mapping[str, object] | None,
|
|
159
|
+
headers: Mapping[str, str | None] | None,
|
|
160
|
+
body: object = None,
|
|
161
|
+
files: list[tuple[str, bytes]] | None = None,
|
|
162
|
+
stream: bool = False,
|
|
163
|
+
) -> httpx.Response:
|
|
164
|
+
if files is not None and (body is not None or not files):
|
|
165
|
+
raise ValueError("Pass either a JSON body or a non-empty list of files")
|
|
166
|
+
# Build once: retries replay the original headers, URL and serialized JSON bytes.
|
|
167
|
+
request = self._http.build_request(
|
|
168
|
+
method,
|
|
169
|
+
path,
|
|
170
|
+
params=_params(query),
|
|
171
|
+
json=body,
|
|
172
|
+
headers={k: v for k, v in (headers or {}).items() if v is not None},
|
|
173
|
+
files=[("file", file) for file in files] if files else None,
|
|
174
|
+
)
|
|
175
|
+
base = self._http.base_url
|
|
176
|
+
url = request.url
|
|
177
|
+
if (url.scheme, url.host, url.port) != (base.scheme, base.host, base.port):
|
|
178
|
+
raise ValueError("Request origin does not match the API key")
|
|
179
|
+
retryable = method == "GET" or (
|
|
180
|
+
method == "POST" and body is not None and "idempotency-key" in request.headers
|
|
181
|
+
)
|
|
182
|
+
retries = self._max_retries if retryable else 0
|
|
183
|
+
deadline = asyncio.get_running_loop().time() + self._timeout
|
|
184
|
+
async with asyncio.timeout_at(deadline):
|
|
185
|
+
for attempt in range(retries + 1):
|
|
186
|
+
delay = min(0.2 * 2**attempt, 2.0)
|
|
187
|
+
try:
|
|
188
|
+
response = await self._http.send(request, stream=stream)
|
|
189
|
+
if stream and not response.is_success:
|
|
190
|
+
try:
|
|
191
|
+
await response.aread()
|
|
192
|
+
finally:
|
|
193
|
+
await response.aclose()
|
|
194
|
+
except (httpx.NetworkError, httpx.RemoteProtocolError, httpx.TimeoutException):
|
|
195
|
+
if attempt == retries:
|
|
196
|
+
raise
|
|
197
|
+
else:
|
|
198
|
+
if attempt == retries or not _transient(response):
|
|
199
|
+
return response
|
|
200
|
+
delay = max(delay, _retry_after(response))
|
|
201
|
+
if delay >= deadline - asyncio.get_running_loop().time():
|
|
202
|
+
return response
|
|
203
|
+
await asyncio.sleep(delay)
|
|
204
|
+
raise AssertionError("unreachable")
|
|
205
|
+
|
|
206
|
+
async def request(
|
|
207
|
+
self,
|
|
208
|
+
method: str,
|
|
209
|
+
path: str,
|
|
210
|
+
*,
|
|
211
|
+
mode: Literal["json", "empty", "bytes", "text"],
|
|
212
|
+
body: object = None,
|
|
213
|
+
files: list[tuple[str, bytes]] | None = None,
|
|
214
|
+
headers: Mapping[str, str | None] | None = None,
|
|
215
|
+
query: Mapping[str, object] | None = None,
|
|
216
|
+
) -> Result[Any]:
|
|
217
|
+
response = await self._send(
|
|
218
|
+
method, path, body=body, files=files, headers=headers, query=query
|
|
219
|
+
)
|
|
220
|
+
_check_status(response)
|
|
221
|
+
if response.status_code == 204 and mode == "empty":
|
|
222
|
+
return Result(None, response)
|
|
223
|
+
if mode == "bytes" and response.content:
|
|
224
|
+
return Result(response.content, response)
|
|
225
|
+
if mode == "text" and response.content:
|
|
226
|
+
return Result(response.text, response)
|
|
227
|
+
if mode == "json" and (data := _json(response)) is not None:
|
|
228
|
+
return Result(data, response)
|
|
229
|
+
raise _failure(response, "protocol_error", "Unexpected response body from Fiscalbase")
|
|
230
|
+
|
|
231
|
+
@asynccontextmanager
|
|
232
|
+
async def stream(
|
|
233
|
+
self,
|
|
234
|
+
method: str,
|
|
235
|
+
path: str,
|
|
236
|
+
*,
|
|
237
|
+
headers: Mapping[str, str | None] | None = None,
|
|
238
|
+
query: Mapping[str, object] | None = None,
|
|
239
|
+
) -> AsyncIterator[httpx.Response]:
|
|
240
|
+
response = await self._send(method, path, headers=headers, query=query, stream=True)
|
|
241
|
+
try:
|
|
242
|
+
_check_status(response)
|
|
243
|
+
yield response
|
|
244
|
+
finally:
|
|
245
|
+
await response.aclose()
|