spec2py-runtime 0.1.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,193 @@
1
+ """Typed error hierarchy raised by generated clients.
2
+
3
+ ::
4
+
5
+ APIError
6
+ ├── APIConnectionError
7
+ │ └── APITimeoutError
8
+ ├── APIResponseValidationError
9
+ ├── PaginationOriginError
10
+ └── APIStatusError
11
+ ├── BadRequestError 400
12
+ ├── AuthenticationError 401
13
+ ├── PermissionDeniedError 403
14
+ ├── NotFoundError 404
15
+ ├── ConflictError 409
16
+ ├── UnprocessableEntityError 422
17
+ ├── RateLimitError 429
18
+ └── InternalServerError 5xx
19
+ """
20
+
21
+ from typing import override
22
+
23
+ import httpx2
24
+
25
+ __all__ = [
26
+ "APIConnectionError",
27
+ "APIError",
28
+ "APIResponseValidationError",
29
+ "APIStatusError",
30
+ "APITimeoutError",
31
+ "AuthenticationError",
32
+ "BadRequestError",
33
+ "ConflictError",
34
+ "InternalServerError",
35
+ "NotFoundError",
36
+ "PaginationOriginError",
37
+ "PermissionDeniedError",
38
+ "RateLimitError",
39
+ "UnprocessableEntityError",
40
+ "status_error_class",
41
+ ]
42
+
43
+
44
+ class APIError(Exception):
45
+ """Base class for every error a generated client raises."""
46
+
47
+ message: str
48
+ request: httpx2.Request
49
+
50
+ def __init__(self, message: str, request: httpx2.Request) -> None:
51
+ super().__init__(message)
52
+ self.message = message
53
+ self.request = request
54
+
55
+
56
+ class APIConnectionError(APIError):
57
+ """The request never produced a response (DNS, TCP, TLS or protocol failure)."""
58
+
59
+ def __init__(
60
+ self, request: httpx2.Request, message: str = "Connection error."
61
+ ) -> None:
62
+ super().__init__(message, request)
63
+
64
+
65
+ class APITimeoutError(APIConnectionError):
66
+ """The request timed out, after any retries."""
67
+
68
+ def __init__(self, request: httpx2.Request) -> None:
69
+ super().__init__(request, "Request timed out.")
70
+
71
+
72
+ class APIResponseValidationError(APIError):
73
+ """A 2xx response body did not match the declared schema at all."""
74
+
75
+ response: httpx2.Response
76
+ body: object
77
+
78
+ def __init__(
79
+ self, response: httpx2.Response, body: object, message: str | None = None
80
+ ) -> None:
81
+ super().__init__(
82
+ message or "Response body did not match the expected schema.",
83
+ response.request,
84
+ )
85
+ self.response = response
86
+ self.body = body
87
+
88
+
89
+ class PaginationOriginError(APIError):
90
+ """A next-page URL pointed at an origin other than ``base_url``.
91
+
92
+ Following it would send the client's credentials to that host. Pass
93
+ ``trusted_pagination_origins=["https://other.example"]`` to the client to
94
+ allow it. ``request`` is the request whose response held the URL.
95
+ """
96
+
97
+ url: str
98
+
99
+ def __init__(self, url: str, *, base_url: str, request: httpx2.Request) -> None:
100
+ super().__init__(
101
+ f"Refusing to follow next-page URL {url!r}: its origin differs from "
102
+ f"base_url {base_url!r}. Add the origin to trusted_pagination_origins "
103
+ "if this host should receive the client's credentials.",
104
+ request,
105
+ )
106
+ self.url = url
107
+
108
+
109
+ class APIStatusError(APIError):
110
+ """The server answered with a 4xx or 5xx status.
111
+
112
+ ``body`` is the decoded JSON (or text) body. ``parsed`` is that body parsed
113
+ into the error model the spec declares for this status, when one exists and
114
+ the body matches it.
115
+ """
116
+
117
+ response: httpx2.Response
118
+ status_code: int
119
+ body: object
120
+ parsed: object | None
121
+
122
+ def __init__(
123
+ self,
124
+ message: str,
125
+ *,
126
+ response: httpx2.Response,
127
+ body: object,
128
+ parsed: object | None = None,
129
+ ) -> None:
130
+ super().__init__(message, response.request)
131
+ self.response = response
132
+ self.status_code = response.status_code
133
+ self.body = body
134
+ self.parsed = parsed
135
+
136
+ @property
137
+ def request_id(self) -> str | None:
138
+ headers = self.response.headers
139
+ return headers.get("x-request-id") or headers.get("request-id")
140
+
141
+ @override
142
+ def __str__(self) -> str:
143
+ return f"{self.status_code} {self.message}"
144
+
145
+
146
+ class BadRequestError(APIStatusError):
147
+ pass
148
+
149
+
150
+ class AuthenticationError(APIStatusError):
151
+ pass
152
+
153
+
154
+ class PermissionDeniedError(APIStatusError):
155
+ pass
156
+
157
+
158
+ class NotFoundError(APIStatusError):
159
+ pass
160
+
161
+
162
+ class ConflictError(APIStatusError):
163
+ pass
164
+
165
+
166
+ class UnprocessableEntityError(APIStatusError):
167
+ pass
168
+
169
+
170
+ class RateLimitError(APIStatusError):
171
+ pass
172
+
173
+
174
+ class InternalServerError(APIStatusError):
175
+ pass
176
+
177
+
178
+ _BY_STATUS: dict[int, type[APIStatusError]] = {
179
+ 400: BadRequestError,
180
+ 401: AuthenticationError,
181
+ 403: PermissionDeniedError,
182
+ 404: NotFoundError,
183
+ 409: ConflictError,
184
+ 422: UnprocessableEntityError,
185
+ 429: RateLimitError,
186
+ }
187
+
188
+
189
+ def status_error_class(status_code: int) -> type[APIStatusError]:
190
+ """Pick the most specific :class:`APIStatusError` subclass for a status."""
191
+ if status_code >= 500:
192
+ return InternalServerError
193
+ return _BY_STATUS.get(status_code, APIStatusError)
@@ -0,0 +1,79 @@
1
+ """Multipart uploads from file objects, paths, bytes or ``(name, content)`` tuples."""
2
+
3
+ import json
4
+ import os
5
+ import pathlib
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import IO, Any, cast
8
+
9
+ from ._models import jsonable
10
+ from ._types import FileContent, FileTypes, NotGiven
11
+
12
+ __all__ = ["to_httpx_files", "to_multipart_data"]
13
+
14
+ type HttpxFile = (
15
+ tuple[str | None, IO[bytes] | bytes, str | None]
16
+ | tuple[str | None, IO[bytes] | bytes, str | None, Mapping[str, str]]
17
+ )
18
+
19
+
20
+ def _content(content: FileContent) -> tuple[str | None, IO[bytes] | bytes]:
21
+ if isinstance(content, os.PathLike):
22
+ path = pathlib.Path(content)
23
+ return path.name, path.read_bytes()
24
+ if isinstance(content, bytes):
25
+ return None, content
26
+ name = getattr(content, "name", None)
27
+ return (pathlib.Path(name).name if isinstance(name, str) else None), content
28
+
29
+
30
+ def _one(file: FileTypes) -> HttpxFile:
31
+ if isinstance(file, tuple):
32
+ parts = cast(tuple[Any, ...], file)
33
+ name, content = parts[0], parts[1]
34
+ default_name, body = _content(content)
35
+ content_type = parts[2] if len(parts) > 2 else None
36
+ filename = name if name is not None else default_name
37
+ if len(parts) > 3:
38
+ return (filename, body, content_type, parts[3])
39
+ return (filename, body, content_type)
40
+ default_name, body = _content(file)
41
+ return (default_name or "upload", body, None)
42
+
43
+
44
+ def to_httpx_files(
45
+ files: Mapping[str, FileTypes | Sequence[FileTypes] | NotGiven | None],
46
+ ) -> list[tuple[str, HttpxFile]]:
47
+ """Normalize generated-client file arguments into httpx2's ``files=`` shape.
48
+
49
+ ``None`` (an optional file left out) is dropped like ``NOT_GIVEN``.
50
+ """
51
+ out: list[tuple[str, HttpxFile]] = []
52
+ for field, value in files.items():
53
+ if isinstance(value, NotGiven) or value is None:
54
+ continue
55
+ if isinstance(value, list):
56
+ out.extend((field, _one(item)) for item in value)
57
+ else:
58
+ out.append((field, _one(cast(FileTypes, value))))
59
+ return out
60
+
61
+
62
+ def to_multipart_data(fields: Mapping[str, object]) -> dict[str, str | list[str]]:
63
+ """Encode non-file form fields: scalars as text, objects as JSON."""
64
+ data: dict[str, str | list[str]] = {}
65
+ for key, value in fields.items():
66
+ if isinstance(value, NotGiven) or value is None:
67
+ continue
68
+ if isinstance(value, bool):
69
+ data[key] = "true" if value else "false"
70
+ elif isinstance(value, str | int | float):
71
+ data[key] = str(value)
72
+ elif isinstance(value, list) and all(
73
+ isinstance(v, str | int | float) for v in cast(list[object], value)
74
+ ):
75
+ data[key] = [str(v) for v in cast(list[object], value)]
76
+ else:
77
+ encoded = jsonable(cast(object, value))
78
+ data[key] = encoded if isinstance(encoded, str) else json.dumps(encoded)
79
+ return data
@@ -0,0 +1,260 @@
1
+ """Model base class and the "lenient in, strict out" validation helpers.
2
+
3
+ Responses are parsed leniently: unknown fields are kept and unknown enum values
4
+ are tolerated, to tolerate additive server changes. Requests are
5
+ validated strictly before they are sent: wrong types fail locally, before a
6
+ round trip.
7
+ """
8
+
9
+ import functools
10
+ import logging
11
+ import sys
12
+ import types
13
+ import typing
14
+ from collections.abc import Mapping
15
+ from typing import Annotated, Any, Final, cast
16
+
17
+ import pydantic
18
+ import pydantic_core
19
+ from pydantic import TypeAdapter, ValidationError, ValidationInfo, WrapValidator
20
+
21
+ from ._types import NotGiven
22
+
23
+ __all__ = [
24
+ "BaseModel",
25
+ "Tolerant",
26
+ "build_body",
27
+ "jsonable",
28
+ "link_models",
29
+ "parse_value",
30
+ "validate_param",
31
+ ]
32
+
33
+ _STRICT_CONTEXT: Final = {"spec2py_strict": True}
34
+ logger = logging.getLogger("spec2py")
35
+
36
+
37
+ class BaseModel(pydantic.BaseModel):
38
+ """Base for generated models.
39
+
40
+ Keeps fields the schema doesn't declare (``extra="allow"``), accepts both
41
+ Python field names and wire aliases, and reads attribute docstrings as field
42
+ descriptions. Use ``model_fields_set`` to tell an absent field from one that
43
+ was explicitly ``null``. Validators are built lazily on first use, so
44
+ importing a client with thousands of models stays fast.
45
+ """
46
+
47
+ model_config = pydantic.ConfigDict(
48
+ extra="allow",
49
+ validate_by_name=True,
50
+ validate_by_alias=True,
51
+ serialize_by_alias=True,
52
+ use_attribute_docstrings=True,
53
+ arbitrary_types_allowed=True,
54
+ protected_namespaces=(),
55
+ defer_build=True,
56
+ revalidate_instances="always",
57
+ )
58
+
59
+ def to_dict(self) -> dict[str, Any]:
60
+ """Dump to a JSON-compatible dict using wire names, omitting unset fields."""
61
+ return self.model_dump(mode="json", by_alias=True, exclude_unset=True)
62
+
63
+ def to_json(self, *, indent: int | None = None) -> str:
64
+ """Dump to a JSON string using wire names, omitting unset fields."""
65
+ return self.model_dump_json(by_alias=True, exclude_unset=True, indent=indent)
66
+
67
+
68
+ def _tolerate(value: object, handler: Any, info: ValidationInfo) -> object:
69
+ try:
70
+ return handler(value)
71
+ except ValidationError:
72
+ if info.context and info.context.get("spec2py_strict"):
73
+ raise
74
+ return value
75
+
76
+
77
+ Tolerant: Final = WrapValidator(_tolerate)
78
+ """Annotation marker for closed sets (enums) that tolerate unknown values on responses.
79
+
80
+ ``Annotated[Literal["open", "paid"], Tolerant]`` type-checks as the literal, accepts
81
+ any value when parsing a response, and rejects unknown values when validating a
82
+ request.
83
+ """
84
+
85
+
86
+ @functools.cache
87
+ def _adapter(tp: Any) -> TypeAdapter[Any]:
88
+ return TypeAdapter(tp)
89
+
90
+
91
+ def parse_value[T](tp: type[T], data: object, *, strict: bool = True) -> T:
92
+ """Validate response ``data`` against ``tp``.
93
+
94
+ By default, malformed responses raise ``ValidationError``.
95
+ With ``strict=False`` a body that doesn't fully match is still
96
+ returned: every field that validates is typed, the rest keep their raw JSON
97
+ values, and a warning is logged. ``strict=True`` raises ``ValidationError``.
98
+ """
99
+ try:
100
+ return cast(T, _adapter(cast(Any, tp)).validate_python(data))
101
+ except ValidationError as exc:
102
+ if strict:
103
+ raise
104
+ logger.warning(
105
+ "Response did not match %s; returning a best-effort parse: %s",
106
+ getattr(tp, "__name__", tp),
107
+ exc.errors(include_url=False)[:3],
108
+ )
109
+ return cast(T, _best_effort(tp, data))
110
+
111
+
112
+ def _lenient(tp: Any, data: object) -> object:
113
+ try:
114
+ return _adapter(tp).validate_python(data)
115
+ except ValidationError:
116
+ return _best_effort(tp, data)
117
+
118
+
119
+ def _best_effort(tp: Any, data: object) -> object:
120
+ origin = typing.get_origin(tp)
121
+ if origin is Annotated:
122
+ return _best_effort(typing.get_args(tp)[0], data)
123
+ if isinstance(tp, typing.TypeAliasType):
124
+ return _best_effort(tp.__value__, data)
125
+ if origin in (list, set, tuple) and isinstance(data, list):
126
+ (item_type, *_) = typing.get_args(tp) or (Any,)
127
+ return [_lenient(item_type, item) for item in cast(list[object], data)]
128
+ if origin in (types.UnionType, typing.Union) and isinstance(data, dict):
129
+ for arg in typing.get_args(tp):
130
+ if isinstance(arg, type) and issubclass(arg, pydantic.BaseModel):
131
+ return _best_effort(arg, cast(object, data))
132
+ return cast(object, data)
133
+ if (
134
+ isinstance(tp, type)
135
+ and issubclass(tp, pydantic.BaseModel)
136
+ and isinstance(data, dict)
137
+ ):
138
+ raw = cast(dict[str, object], data)
139
+ _ensure_built(tp)
140
+ values: dict[str, object] = {}
141
+ consumed: set[str] = set()
142
+ for name, field in tp.model_fields.items():
143
+ key = field.alias if field.alias in raw else name
144
+ if key not in raw:
145
+ continue
146
+ consumed.add(key)
147
+ try:
148
+ values[name] = _field_adapter(tp, name).validate_python(raw[key])
149
+ except ValidationError:
150
+ values[name] = _best_effort(field.annotation, raw[key])
151
+ extras = {k: v for k, v in raw.items() if k not in consumed}
152
+ return tp.model_construct(_fields_set=set(values), **values, **extras)
153
+ return data
154
+
155
+
156
+ def _ensure_built(model: type[pydantic.BaseModel]) -> None:
157
+ """Build a deferred model so its field annotations are resolved types."""
158
+ if not model.__pydantic_complete__:
159
+ model.model_rebuild()
160
+
161
+
162
+ @functools.cache
163
+ def _field_adapter(model: type[pydantic.BaseModel], name: str) -> TypeAdapter[Any]:
164
+ _ensure_built(model)
165
+ field = model.model_fields[name]
166
+ annotation: Any = field.annotation
167
+ if field.metadata:
168
+ annotation = Annotated[annotation, *field.metadata]
169
+ return TypeAdapter(annotation)
170
+
171
+
172
+ def validate_param(tp: Any, value: object) -> object:
173
+ """Strictly validate one request value and return its JSON-compatible form."""
174
+ return _strict_dump(_adapter(tp), value)
175
+
176
+
177
+ def _strict_dump(adapter: TypeAdapter[Any], value: object) -> object:
178
+ """Validate a request value strictly and dump it to its wire form."""
179
+ validated = adapter.validate_python(value, strict=True, context=_STRICT_CONTEXT)
180
+ return adapter.dump_python(
181
+ validated, mode="json", by_alias=True, exclude_unset=True
182
+ )
183
+
184
+
185
+ def build_body(
186
+ model: type[pydantic.BaseModel],
187
+ fields: Mapping[str, object],
188
+ extra_body: Mapping[str, object] | None = None,
189
+ ) -> dict[str, object]:
190
+ """Build a JSON request body from flattened keyword arguments.
191
+
192
+ Each given field is validated strictly against its declared type on
193
+ ``model`` (so read-only required fields never get in the way) and dumped
194
+ under its wire alias. ``NOT_GIVEN`` values are dropped; ``None`` is kept and
195
+ sent as ``null``.
196
+ """
197
+ body: dict[str, object] = {}
198
+ for name, value in fields.items():
199
+ if isinstance(value, NotGiven):
200
+ continue
201
+ adapter = _field_adapter(model, name) # builds a deferred model first
202
+ try:
203
+ dumped = _strict_dump(adapter, value)
204
+ except ValidationError as exc:
205
+ raise _located(exc, model.__name__, name) from None
206
+ body[model.model_fields[name].alias or name] = dumped
207
+ if extra_body:
208
+ body.update(extra_body)
209
+ return body
210
+
211
+
212
+ def _located(exc: ValidationError, title: str, name: str) -> ValidationError:
213
+ """A field's validation error, re-located at its argument name."""
214
+ errors: list[Any] = [
215
+ {
216
+ "type": e["type"],
217
+ "loc": (name, *e["loc"]),
218
+ "input": e["input"],
219
+ **({"ctx": e["ctx"]} if "ctx" in e else {}),
220
+ }
221
+ for e in exc.errors(include_url=False)
222
+ ]
223
+ return ValidationError.from_exception_data(title, errors)
224
+
225
+
226
+ def jsonable(value: object) -> object:
227
+ """Convert models, containers and scalars to JSON-compatible Python values."""
228
+ match value:
229
+ case pydantic.BaseModel():
230
+ return value.model_dump(mode="json", by_alias=True, exclude_unset=True)
231
+ case NotGiven():
232
+ return None
233
+ case Mapping():
234
+ items = cast(Mapping[object, object], value).items()
235
+ return {
236
+ str(k): jsonable(v) for k, v in items if not isinstance(v, NotGiven)
237
+ }
238
+ case list() | tuple():
239
+ return [jsonable(v) for v in cast(list[object], value)]
240
+ case _:
241
+ return pydantic_core.to_jsonable_python(value)
242
+
243
+
244
+ def link_models(namespace: Mapping[str, object]) -> None:
245
+ """Make every model name resolvable from every module of a split models package.
246
+
247
+ Large specs split ``models`` into a package whose modules reference each
248
+ other only under ``TYPE_CHECKING`` (so imports stay acyclic). Called at the
249
+ bottom of ``models/__init__.py`` with ``globals()``, this adds the package's
250
+ exports to each submodule's namespace. Nothing is built here: models build
251
+ their validators lazily, on first use, which keeps importing a client with
252
+ thousands of models fast.
253
+ """
254
+ package = str(namespace.get("__name__"))
255
+ exported = cast(list[str], namespace.get("__all__", []))
256
+ names = {name: namespace[name] for name in exported if name in namespace}
257
+ for module_name, module in list(sys.modules.items()):
258
+ if module_name.startswith(package + "."):
259
+ for name, value in names.items():
260
+ module.__dict__.setdefault(name, value)