davixlabs-h2i 1.2.1__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.
@@ -0,0 +1,10 @@
1
+ Davix H2I SDK License
2
+
3
+ Copyright (c) 2026 Davix Labs. All rights reserved.
4
+
5
+ You may install, copy and use this software, and include it unchanged or modified in your own applications, in order to
6
+ use the Davix H2I API with a Davix H2I account, under the Davix H2I terms of service (https://h2i.davixlabs.io/terms/).
7
+ You may not sell this software on its own, or use it to build or offer a service that competes with Davix H2I.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS,
10
+ DAVIX LABS IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: davixlabs-h2i
3
+ Version: 1.2.1
4
+ Summary: Official Python SDK for the Davix H2I API: images, PDFs, documents, data and AI tools.
5
+ Author-email: Davix Labs <h2i-support@davixlabs.io>
6
+ License: Davix H2I SDK License
7
+
8
+ Copyright (c) 2026 Davix Labs. All rights reserved.
9
+
10
+ You may install, copy and use this software, and include it unchanged or modified in your own applications, in order to
11
+ use the Davix H2I API with a Davix H2I account, under the Davix H2I terms of service (https://h2i.davixlabs.io/terms/).
12
+ You may not sell this software on its own, or use it to build or offer a service that competes with Davix H2I.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS,
15
+ DAVIX LABS IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
16
+
17
+ Project-URL: Homepage, https://h2i.davixlabs.io
18
+ Project-URL: Documentation, https://h2i.davixlabs.io/developers/
19
+ Keywords: davix,h2i,pdf,image,api,sdk
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: License :: Other/Proprietary License
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # Davix H2I Python SDK (`davixlabs-h2i`)
29
+
30
+ Official client for the [Davix H2I](https://h2i.davixlabs.io) API: images, PDFs, documents, data and AI tools.
31
+ Every method, field list, enum and error code is generated from the same API contract as the server.
32
+
33
+ ## Install
34
+
35
+ Python 3.8 or newer, no other packages.
36
+
37
+ ```bash
38
+ pip install davixlabs-h2i
39
+ ```
40
+
41
+ ## Use
42
+
43
+ ```python
44
+ import os
45
+ from davix_h2i import H2I, ErrorCodes, DavixH2IError
46
+
47
+ h2i = H2I(os.environ["DAVIX_H2I_API_KEY"])
48
+ try:
49
+ result = h2i.images.resize({"images": "photo.jpg", "width": 800})
50
+ h2i.download(result.files()[0], dest="photo-800.jpg")
51
+ except DavixH2IError as error:
52
+ print(error.code, error.hint, error.request_id)
53
+ ```
54
+
55
+ ## What it does for you
56
+
57
+ * **Key safety:** the API key is only sent as a header, is never printed, and never follows a redirect or goes to a download address.
58
+ * **Retries:** only failures that are safe to repeat; one Idempotency-Key per call, reused by its retries, so a retry never bills twice.
59
+ * **Errors:** every error carries the API's code, status, hint, details and request id.
60
+ * **Files:** a plain text value is read from disk only for a field the API defines as a file.
61
+ * **New endpoints:** the generic request method reaches public `/v1/` paths this version does not know yet.
62
+ * **Metadata:** each endpoint's schema (types, limits, defaults, allowed values) with an optional check before sending.
63
+
64
+ Options of one call are keyword arguments: `h2i.images.resize(params, idempotency_key="order-42", timeout=120)`.
65
+ Tests: `python -m unittest discover -s tests`.
66
+
67
+ ## Help
68
+
69
+ [Developer guide](https://h2i.davixlabs.io/developers/) · h2i-support@davixlabs.io
@@ -0,0 +1,42 @@
1
+ # Davix H2I Python SDK (`davixlabs-h2i`)
2
+
3
+ Official client for the [Davix H2I](https://h2i.davixlabs.io) API: images, PDFs, documents, data and AI tools.
4
+ Every method, field list, enum and error code is generated from the same API contract as the server.
5
+
6
+ ## Install
7
+
8
+ Python 3.8 or newer, no other packages.
9
+
10
+ ```bash
11
+ pip install davixlabs-h2i
12
+ ```
13
+
14
+ ## Use
15
+
16
+ ```python
17
+ import os
18
+ from davix_h2i import H2I, ErrorCodes, DavixH2IError
19
+
20
+ h2i = H2I(os.environ["DAVIX_H2I_API_KEY"])
21
+ try:
22
+ result = h2i.images.resize({"images": "photo.jpg", "width": 800})
23
+ h2i.download(result.files()[0], dest="photo-800.jpg")
24
+ except DavixH2IError as error:
25
+ print(error.code, error.hint, error.request_id)
26
+ ```
27
+
28
+ ## What it does for you
29
+
30
+ * **Key safety:** the API key is only sent as a header, is never printed, and never follows a redirect or goes to a download address.
31
+ * **Retries:** only failures that are safe to repeat; one Idempotency-Key per call, reused by its retries, so a retry never bills twice.
32
+ * **Errors:** every error carries the API's code, status, hint, details and request id.
33
+ * **Files:** a plain text value is read from disk only for a field the API defines as a file.
34
+ * **New endpoints:** the generic request method reaches public `/v1/` paths this version does not know yet.
35
+ * **Metadata:** each endpoint's schema (types, limits, defaults, allowed values) with an optional check before sending.
36
+
37
+ Options of one call are keyword arguments: `h2i.images.resize(params, idempotency_key="order-42", timeout=120)`.
38
+ Tests: `python -m unittest discover -s tests`.
39
+
40
+ ## Help
41
+
42
+ [Developer guide](https://h2i.davixlabs.io/developers/) · h2i-support@davixlabs.io
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "davixlabs-h2i"
7
+ version = "1.2.1"
8
+ description = "Official Python SDK for the Davix H2I API: images, PDFs, documents, data and AI tools."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { file = "LICENSE" }
12
+ authors = [{ name = "Davix Labs", email = "h2i-support@davixlabs.io" }]
13
+ keywords = ["davix", "h2i", "pdf", "image", "api", "sdk"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent", "License :: Other/Proprietary License"]
15
+ dependencies = []
16
+
17
+ [project.urls]
18
+ Homepage = "https://h2i.davixlabs.io"
19
+ Documentation = "https://h2i.davixlabs.io/developers/"
20
+
21
+ [tool.setuptools.packages.find]
22
+ where = ["src"]
23
+
24
+ [tool.setuptools.package-data]
25
+ davix_h2i = ["contract.json", "py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ """Official Python SDK for the Davix H2I API.
2
+
3
+ from davix_h2i import H2I
4
+ h2i = H2I(api_key=os.environ["DAVIX_H2I_API_KEY"])
5
+ result = h2i.images.resize({"images": "photo.jpg", "width": 800})
6
+ print(result.files())
7
+ """
8
+ from ._client import DEFAULT_BASE_URL, ENUM_VALUES, H2I
9
+ from ._contract import bundled_contract
10
+ from ._errors import (AiError, ApiError, AuthenticationError, ConfigError, ConflictError, DavixH2IError, JobError, KeyManagementError,
11
+ NetworkError, NotFoundError, PlanError, ProcessingError, QuotaError, RateLimitError, ServerError, SignedUrlError,
12
+ TimeoutError, UploadError, ValidationError)
13
+ from ._generated import enums
14
+ from ._generated.error_codes import ErrorCodes
15
+ from ._multipart import FileInput
16
+ from ._response import Response
17
+ from ._schema import FieldSchema, Schema
18
+ from ._version import VERSION as __version__
19
+
20
+ __all__ = [
21
+ "H2I", "Response", "FileInput", "Schema", "FieldSchema", "ErrorCodes", "enums", "ENUM_VALUES", "bundled_contract", "DEFAULT_BASE_URL",
22
+ "DavixH2IError", "ApiError", "ValidationError", "UploadError", "AuthenticationError", "PlanError", "QuotaError", "RateLimitError",
23
+ "ProcessingError", "ServerError", "NotFoundError", "ConflictError", "AiError", "KeyManagementError", "JobError", "SignedUrlError",
24
+ "NetworkError", "TimeoutError", "ConfigError", "__version__",
25
+ ]
@@ -0,0 +1,297 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import re
7
+ import time
8
+ import uuid
9
+ from typing import Any, Dict, Mapping, Optional
10
+ from urllib.parse import urlencode, urljoin, urlsplit
11
+
12
+ from . import _errors as errors
13
+ from . import _transport
14
+ from ._contract import Capabilities, ContractView
15
+ from ._generated.api import Namespaces
16
+ from ._generated.enums import ALL as _ENUMS
17
+ from ._multipart import build_form, to_text
18
+ from ._paths import assert_public_path, expand_path, match_template
19
+ from ._response import Response
20
+ from ._schema import Schema
21
+ from ._version import VERSION
22
+
23
+ DEFAULT_BASE_URL = "https://app.h2i.davixlabs.io"
24
+ _SCHEMA_MAJOR = 1
25
+ _REPEATABLE = {"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}
26
+ _OPTIONS = {"idempotency_key", "headers", "timeout", "max_retries", "retry", "validate", "strict"}
27
+
28
+
29
+ def _origin(url: str):
30
+ parts = urlsplit(url)
31
+ return parts.scheme.lower(), (parts.hostname or "").lower(), parts.port or (443 if parts.scheme == "https" else 80)
32
+
33
+
34
+ class _Enums:
35
+ def __getattr__(self, name: str) -> Any:
36
+ from ._generated import enums
37
+ return getattr(enums, name)
38
+
39
+
40
+ class H2I(Namespaces):
41
+ """The Davix H2I client.
42
+
43
+ h2i = H2I(api_key=os.environ["DAVIX_H2I_API_KEY"])
44
+ result = h2i.images.resize({"images": "photo.jpg", "width": 800})
45
+ """
46
+
47
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, *, timeout: float = 60.0, max_retries: int = 2,
48
+ max_retry_delay: float = 30.0, auth_scheme: str = "x-api-key", auto_idempotency_key: bool = True,
49
+ validate: bool = False, allow_insecure: bool = False, user_agent_suffix: Optional[str] = None) -> None:
50
+ if not isinstance(api_key, str) or not api_key.strip():
51
+ raise errors.ConfigError("Davix H2I: api_key is required.")
52
+ if re.search(r"[\r\n]", api_key):
53
+ raise errors.ConfigError("Davix H2I: api_key contains invalid characters.")
54
+ parts = urlsplit(base_url or DEFAULT_BASE_URL)
55
+ host = (parts.hostname or "").lower()
56
+ local = host in ("localhost", "127.0.0.1", "::1") or host.endswith(".localhost")
57
+ if not host or not (parts.scheme == "https" or (parts.scheme == "http" and (local or allow_insecure))):
58
+ raise errors.ConfigError("Davix H2I: base_url must use https:// (http:// is only allowed for localhost, or with allow_insecure).")
59
+ if parts.username or parts.password:
60
+ raise errors.ConfigError("Davix H2I: credentials in base_url are not allowed.")
61
+ if auth_scheme not in ("x-api-key", "bearer"):
62
+ raise errors.ConfigError('Davix H2I: auth_scheme must be "x-api-key" or "bearer".')
63
+ self.__api_key = api_key.strip()
64
+ self.base_url = "%s://%s%s" % (parts.scheme, parts.netloc, parts.path.rstrip("/"))
65
+ self.timeout = timeout
66
+ self.max_retries = max_retries
67
+ self.max_retry_delay = max_retry_delay
68
+ self.auth_scheme = auth_scheme
69
+ self.auto_idempotency_key = auto_idempotency_key
70
+ self.validate_params = validate
71
+ self.user_agent = "davix-h2i-python/%s%s" % (VERSION, " " + user_agent_suffix if user_agent_suffix else "")
72
+ self.contract = ContractView(self)
73
+ self.capabilities = Capabilities(self)
74
+ self.enums = _Enums()
75
+ self._schemas: Dict[str, Schema] = {}
76
+ self._create_namespaces()
77
+
78
+ def __repr__(self) -> str: # never shows the key
79
+ return "<H2I %s>" % self.base_url
80
+
81
+ def __getstate__(self) -> None:
82
+ raise TypeError("The client holds your API key and cannot be pickled.")
83
+
84
+ # ---------------------------------------------------------------- metadata
85
+ def schema(self, endpoint_id: str) -> Schema:
86
+ found = self._schemas.get(endpoint_id)
87
+ if found is None:
88
+ endpoints = self.contract.active["endpoints"]
89
+ endpoint = next((e for e in endpoints if e["id"] == endpoint_id), None) or next(
90
+ (e for e in endpoints if "%s.%s" % (".".join(e["sdk"]["namespace"]), e["sdk"]["method"]) == endpoint_id), None)
91
+ if endpoint is None:
92
+ raise errors.ConfigError('Unknown endpoint "%s".' % endpoint_id)
93
+ found = self._schemas[endpoint_id] = Schema(endpoint)
94
+ return found
95
+
96
+ def _use_contract(self, contract: Optional[Dict[str, Any]]) -> None:
97
+ if contract is not None:
98
+ if not isinstance(contract, dict) or not isinstance(contract.get("endpoints"), list):
99
+ raise errors.ConfigError("The live contract is malformed.")
100
+ if int(contract.get("metadataSchemaVersion", 0)) != _SCHEMA_MAJOR:
101
+ raise errors.ConfigError("The live contract uses metadata schema %s, which this SDK version (%s) does not understand. Upgrade the SDK."
102
+ % (contract.get("metadataSchemaVersion"), VERSION))
103
+ self.contract.live = contract
104
+ self._schemas = {}
105
+
106
+ # ---------------------------------------------------------------- calls
107
+ def call(self, endpoint_id: str, params: Optional[Mapping[str, Any]] = None, **options: Any) -> Response:
108
+ """Calls an endpoint by its id. Options: idempotency_key, headers, timeout, max_retries, retry, validate, strict."""
109
+ self._check_options(options)
110
+ schema = self.schema(endpoint_id)
111
+ endpoint = schema.endpoint
112
+ params = {} if params is None else params
113
+ if not isinstance(params, Mapping):
114
+ raise errors.ConfigError("%s: params must be a dict." % endpoint_id)
115
+ if options.get("validate", self.validate_params):
116
+ result = schema.validate(params)
117
+ if not result["valid"]:
118
+ raise errors.ConfigError("%s: invalid parameters: %s" % (endpoint_id, " ".join(e["message"] for e in result["errors"])),
119
+ code="sdk_validation_failed", details={"errors": result["errors"]})
120
+ fields = {f["name"]: f for f in endpoint["request"]["fields"]}
121
+ if options.get("strict"):
122
+ unknown = [k for k in params if k not in fields]
123
+ if unknown:
124
+ raise errors.ConfigError("%s: unknown parameter(s): %s." % (endpoint_id, ", ".join(unknown)))
125
+ path_values: Dict[str, Any] = {}
126
+ query: Dict[str, Any] = {}
127
+ headers: Dict[str, str] = {}
128
+ body: Dict[str, Any] = {}
129
+ for name, value in params.items(): # your order is kept; unknown names (a newer server) go in the body
130
+ field = fields.get(name)
131
+ location = field.get("location") if field else None
132
+ if field and location == "header" and field.get("standard"):
133
+ continue # e.g. Idempotency-Key: use idempotency_key=
134
+ if location == "path":
135
+ path_values[name] = value
136
+ elif value is None:
137
+ continue
138
+ elif location == "query":
139
+ query[name] = value
140
+ elif location == "header":
141
+ headers[name] = str(value)
142
+ else:
143
+ body[name] = value
144
+ url_path = expand_path(endpoint["path"], path_values)
145
+ content = endpoint["request"].get("contentType")
146
+ payload, content_type = None, None
147
+ if content == "multipart/form-data":
148
+ payload, content_type = build_form([f for f in fields.values() if f.get("location") == "form"], body)
149
+ elif body:
150
+ payload, content_type = json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8"), "application/json"
151
+ eligible = endpoint["method"] == "POST" and schema.idempotent
152
+ return self._send(endpoint["method"], url_path, query=query, headers=headers, payload=payload, content_type=content_type,
153
+ eligible=eligible, options=options)
154
+
155
+ def request(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, json_body: Any = None,
156
+ form: Optional[Mapping[str, Any]] = None, **options: Any) -> Response:
157
+ """For endpoints this version does not know yet. Only the public API (/v1/...) can be reached."""
158
+ self._check_options(options)
159
+ contract = self.contract.active
160
+ method = str(method).upper()
161
+ if method not in ("GET", "POST", "PUT", "PATCH", "DELETE"):
162
+ raise errors.ConfigError('request(): unsupported method "%s".' % method)
163
+ assert_public_path(path, contract["requestPolicy"])
164
+ endpoint = next((e for e in contract["endpoints"] if e["method"] == method and match_template(e["path"], path)), None)
165
+ if json_body is not None and form is not None:
166
+ raise errors.ConfigError("request(): pass either json_body or form, not both.")
167
+ payload, content_type = None, None
168
+ if json_body is not None:
169
+ payload, content_type = json.dumps(json_body, separators=(",", ":"), ensure_ascii=False).encode("utf-8"), "application/json"
170
+ elif form is not None:
171
+ known = [f for f in endpoint["request"]["fields"] if f.get("location") == "form"] if endpoint else None
172
+ payload, content_type = build_form(known, form)
173
+ eligible = method == "POST" and bool(endpoint and (endpoint.get("idempotency") or {}).get("supported"))
174
+ return self._send(method, path, query=query, payload=payload, content_type=content_type, eligible=eligible, options=options)
175
+
176
+ def download(self, url_or_result: Any, dest: Optional[str] = None, timeout: Optional[float] = None) -> Any:
177
+ """Fetches a signed result address of this server. The API key is NOT sent. Returns bytes, or the path when dest is given."""
178
+ raw = url_or_result if isinstance(url_or_result, str) else (url_or_result or {}).get("url")
179
+ if not isinstance(raw, str):
180
+ raise errors.ConfigError('download(): pass a URL string or a result with a "url".')
181
+ url = urljoin(self.base_url + "/", raw)
182
+ if _origin(url) != _origin(self.base_url):
183
+ raise errors.ConfigError("download(): refusing to fetch a URL that is not on the configured Davix H2I host.")
184
+ if not re.match(r"^/(render|image|pdf|ai|data|documents)/[^/\\]+$", urlsplit(url).path) or re.search(r"/(\.|%2e){1,2}(/|$)", urlsplit(url).path, re.I):
185
+ raise errors.ConfigError("download(): not a Davix H2I output URL.")
186
+ status, headers, data = _transport.send("GET", url, {"User-Agent": self.user_agent}, None, timeout or self.timeout)
187
+ if status >= 300:
188
+ raise self._api_error(status, self._parse(headers, data), headers)
189
+ if dest is None:
190
+ return data
191
+ folder = os.path.dirname(os.path.abspath(dest))
192
+ os.makedirs(folder, exist_ok=True)
193
+ with open(dest, "wb") as handle:
194
+ handle.write(data)
195
+ return dest
196
+
197
+ # ---------------------------------------------------------------- core
198
+ @staticmethod
199
+ def _check_options(options: Mapping[str, Any]) -> None:
200
+ unknown = set(options) - _OPTIONS
201
+ if unknown:
202
+ raise errors.ConfigError("Unknown option(s): %s. API parameters go in the params dict." % ", ".join(sorted(unknown)))
203
+
204
+ @staticmethod
205
+ def _parse(headers: Mapping[str, str], data: bytes) -> Any:
206
+ content_type = headers.get("content-type", "")
207
+ if "json" in content_type:
208
+ try:
209
+ return json.loads(data.decode("utf-8"))
210
+ except ValueError:
211
+ return None
212
+ if content_type.startswith("text/"):
213
+ return data.decode("utf-8", "replace")
214
+ return data or None
215
+
216
+ def _api_error(self, status: int, body: Any, headers: Mapping[str, str]) -> errors.DavixH2IError:
217
+ body_dict = body if isinstance(body, dict) else {}
218
+ error = body_dict.get("error") if isinstance(body_dict.get("error"), dict) else {}
219
+ code = error.get("code") or body_dict.get("code")
220
+ meta = next((e for e in self.contract.active["errors"] if e["code"] == code), None) if code else None
221
+ retry_after = None
222
+ for candidate in (headers.get("retry-after"), (error.get("details") or {}).get("retry_after_seconds") if isinstance(error.get("details"), dict) else None):
223
+ try:
224
+ retry_after = float(candidate)
225
+ break
226
+ except (TypeError, ValueError):
227
+ continue
228
+ cls = errors.class_for(status, meta.get("family") if meta else None)
229
+ return cls(error.get("message") or body_dict.get("message") or "Davix H2I API error (HTTP %d)" % status,
230
+ code=code, status=status, hint=error.get("hint"), details=error.get("details"),
231
+ request_id=headers.get("request-id") or body_dict.get("request_id"), renewal_url=error.get("renewal_url"),
232
+ retryable=meta["retryable"] if meta else status in (503, 504), retry_after=retry_after, body=body)
233
+
234
+ def _send(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, headers: Optional[Mapping[str, str]] = None,
235
+ payload: Optional[bytes] = None, content_type: Optional[str] = None, eligible: bool = False,
236
+ options: Optional[Mapping[str, Any]] = None, attach_key: bool = True) -> Response:
237
+ options = options or {}
238
+ url = self.base_url + path
239
+ if _origin(url) != _origin(self.base_url):
240
+ raise errors.ConfigError("Resolved URL left the configured Davix H2I host.")
241
+ pairs = []
242
+ for name, value in (query or {}).items():
243
+ pairs.extend((name, to_text(v)) for v in (value if isinstance(value, (list, tuple)) else [value]) if v is not None)
244
+ if pairs:
245
+ url += "?" + urlencode(pairs)
246
+ sent = {"accept": "application/json", "user-agent": self.user_agent}
247
+ if attach_key:
248
+ if self.auth_scheme == "bearer":
249
+ sent["authorization"] = "Bearer " + self.__api_key
250
+ else:
251
+ sent["x-api-key"] = self.__api_key
252
+ for name, value in {**(headers or {}), **(options.get("headers") or {})}.items():
253
+ lower = name.lower()
254
+ if lower in ("x-api-key", "authorization", "host"):
255
+ raise errors.ConfigError('Header "%s" is managed by the SDK and cannot be overridden.' % name)
256
+ sent[lower] = str(value)
257
+ if content_type:
258
+ sent["content-type"] = content_type
259
+ retries = 0 if options.get("retry") is False else options.get("max_retries", self.max_retries)
260
+ key = options.get("idempotency_key")
261
+ if key:
262
+ if not re.match(r"^[A-Za-z0-9._:-]{8,128}$", key):
263
+ raise errors.ConfigError("idempotency_key must be 8-128 characters from [A-Za-z0-9._:-].")
264
+ elif self.auto_idempotency_key and eligible and retries > 0:
265
+ key = "h2i-%s" % uuid.uuid4() # one key per call, reused by every retry, so a retry never bills twice
266
+ if key:
267
+ sent["idempotency-key"] = key
268
+ safe = method in _REPEATABLE or bool(key) # repeating cannot duplicate work
269
+ attempt = 0
270
+ while True:
271
+ attempt += 1
272
+ try:
273
+ status, answer_headers, data = _transport.send(method, url, sent, payload, options.get("timeout", self.timeout))
274
+ except errors.NetworkError:
275
+ if attempt <= retries and safe:
276
+ self._wait(attempt, None)
277
+ continue
278
+ raise
279
+ body = self._parse(answer_headers, data)
280
+ if 200 <= status < 300:
281
+ request_id = answer_headers.get("request-id") or (body.get("request_id") if isinstance(body, dict) else None)
282
+ return Response(status, answer_headers, body, request_id, key, attempt)
283
+ error = self._api_error(status, body, answer_headers)
284
+ again = (status == 429 and error.retryable) or (status in (503, 504) and error.retryable and safe)
285
+ if attempt <= retries and again:
286
+ self._wait(attempt, error.retry_after)
287
+ continue
288
+ raise error
289
+
290
+ def _wait(self, attempt: int, retry_after: Optional[float]) -> None:
291
+ delay = random.uniform(0, min(8.0, 0.5 * 2 ** (attempt - 1)))
292
+ if retry_after is not None:
293
+ delay = max(delay, retry_after)
294
+ time.sleep(min(delay, self.max_retry_delay))
295
+
296
+
297
+ ENUM_VALUES = _ENUMS
@@ -0,0 +1,116 @@
1
+ """The contract (bundled, or the live copy), and capabilities: what the contract guarantees, what this server offers, what your plan allows."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from typing import Any, Dict, Mapping, Optional
7
+
8
+ from ._errors import ConfigError
9
+ from ._response import Response
10
+
11
+ _bundled: Optional[Dict[str, Any]] = None
12
+
13
+
14
+ def bundled_contract() -> Dict[str, Any]:
15
+ global _bundled
16
+ if _bundled is None:
17
+ with open(os.path.join(os.path.dirname(__file__), "contract.json"), encoding="utf-8") as handle:
18
+ _bundled = json.load(handle)
19
+ return _bundled
20
+
21
+
22
+ class ContractView:
23
+ """h2i.contract: .bundled ships with this SDK, .live is set by refresh(). The other methods are one small live GET each."""
24
+
25
+ def __init__(self, client: Any) -> None:
26
+ self._client = client
27
+ self.live: Optional[Dict[str, Any]] = None
28
+
29
+ @property
30
+ def bundled(self) -> Dict[str, Any]:
31
+ return bundled_contract()
32
+
33
+ @property
34
+ def active(self) -> Dict[str, Any]:
35
+ return self.live or bundled_contract()
36
+
37
+ @property
38
+ def version(self) -> str:
39
+ return self.active["contractVersion"]
40
+
41
+ def fetch(self) -> Dict[str, Any]:
42
+ return self._client._send("GET", "/v1/contract", attach_key=False).data
43
+
44
+ def refresh(self) -> Dict[str, Any]:
45
+ contract = self.fetch()
46
+ self._client._use_contract(contract)
47
+ return contract
48
+
49
+ def reset(self) -> None:
50
+ self._client._use_contract(None)
51
+
52
+ def _slice(self, endpoint_id: str, **params: Any) -> Any:
53
+ return self._client.call(endpoint_id, params).data
54
+
55
+ def endpoints(self) -> Any:
56
+ return self._slice("contract.endpoints")
57
+
58
+ def endpoint(self, id: str) -> Any: # noqa: A002
59
+ return self._slice("contract.endpoints.{id}", id=id)
60
+
61
+ def fields(self, id: str) -> Any: # noqa: A002
62
+ return self._slice("contract.endpoints.{id}.fields", id=id)
63
+
64
+ def field(self, id: str, name: str) -> Any: # noqa: A002
65
+ return self._slice("contract.endpoints.{id}.fields.{name}", id=id, name=name)
66
+
67
+ def examples(self, id: str) -> Any: # noqa: A002
68
+ return self._slice("contract.endpoints.{id}.examples", id=id)
69
+
70
+ def categories(self) -> Any:
71
+ return self._slice("contract.categories")
72
+
73
+ def enums(self) -> Any:
74
+ return self._slice("contract.enums")
75
+
76
+ def error_codes(self) -> Any:
77
+ return self._slice("contract.errors")
78
+
79
+ def error(self, code: str) -> Any:
80
+ return self._slice("contract.errors.{code}", code=code)
81
+
82
+
83
+ class Capabilities:
84
+ """h2i.capabilities() asks this server; .static() reads the contract without a request; .account() is about your key."""
85
+
86
+ def __init__(self, client: Any) -> None:
87
+ self._client = client
88
+
89
+ def __call__(self, category: Optional[str] = None) -> Response:
90
+ answer = self._client.call("capabilities")
91
+ if category is None:
92
+ return answer
93
+ data = answer.data
94
+ if not isinstance(data, Mapping) or category not in data:
95
+ raise ConfigError('No runtime capability group "%s". Available: %s.' % (category, ", ".join(data or {})))
96
+ return Response(answer.status, answer.headers, data[category], answer.request_id, answer.idempotency_key, answer.attempts)
97
+
98
+ def static(self, category: Optional[str] = None) -> Any:
99
+ capabilities = self._client.contract.active["capabilities"]
100
+ if category is None:
101
+ return capabilities
102
+ if category not in capabilities["categories"]:
103
+ raise ConfigError('Unknown category "%s". Available: %s.' % (category, ", ".join(capabilities["categories"])))
104
+ return capabilities["categories"][category]
105
+
106
+ def account(self) -> Dict[str, Any]:
107
+ answers = {name: self._client.call(name) for name in ("subscription", "usage", "account")}
108
+ result: Dict[str, Any] = {name: a.data for name, a in answers.items()}
109
+ result["request_ids"] = [a.request_id for a in answers.values()]
110
+ return result
111
+
112
+ def section(self, name: str) -> Any:
113
+ return self._client.call("capabilities.{section}", {"section": name}).data
114
+
115
+ def feature(self, section: str, feature: str) -> Any:
116
+ return self._client.call("capabilities.{section}.{feature}", {"section": section, "feature": feature}).data