msgspec-fastapi 0.1.0__cp311-abi3-win_arm64.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.
- msgspec_fastapi/__init__.py +4 -0
- msgspec_fastapi/_defaults.pyd +0 -0
- msgspec_fastapi/_defaults.pyi +50 -0
- msgspec_fastapi/body_errors.py +506 -0
- msgspec_fastapi/defaults.py +342 -0
- msgspec_fastapi/py.typed +0 -0
- msgspec_fastapi/responses.py +40 -0
- msgspec_fastapi/router.py +1236 -0
- msgspec_fastapi/validation.py +595 -0
- msgspec_fastapi-0.1.0.dist-info/METADATA +282 -0
- msgspec_fastapi-0.1.0.dist-info/RECORD +14 -0
- msgspec_fastapi-0.1.0.dist-info/WHEEL +5 -0
- msgspec_fastapi-0.1.0.dist-info/licenses/LICENSE +29 -0
- msgspec_fastapi-0.1.0.dist-info/top_level.txt +1 -0
|
Binary file
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from types import ModuleType
|
|
3
|
+
from typing import Any, final
|
|
4
|
+
|
|
5
|
+
@final
|
|
6
|
+
class _Guard:
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
fallback: Callable[[Any], None],
|
|
10
|
+
registry: dict[type[Any], Any],
|
|
11
|
+
trusted_union_reducer: Any,
|
|
12
|
+
union_type: type[Any],
|
|
13
|
+
function_type: type[Any],
|
|
14
|
+
builtin_function_type: type[Any],
|
|
15
|
+
getset_descriptor_type: type[Any],
|
|
16
|
+
member_descriptor_type: type[Any],
|
|
17
|
+
method_descriptor_type: type[Any],
|
|
18
|
+
wrapper_descriptor_type: type[Any],
|
|
19
|
+
struct_type: type[Any],
|
|
20
|
+
enum_type: type[Any],
|
|
21
|
+
atomic_ids: set[int],
|
|
22
|
+
reference_ids: set[int],
|
|
23
|
+
model_brands: tuple[str, ...],
|
|
24
|
+
native_state_methods: tuple[tuple[str, tuple[Any, ...]], ...],
|
|
25
|
+
state_names: tuple[str, ...],
|
|
26
|
+
enum_namespace: Any,
|
|
27
|
+
missing: Any,
|
|
28
|
+
mro_descriptor: Any,
|
|
29
|
+
dict_descriptor: Any,
|
|
30
|
+
name_descriptor: Any,
|
|
31
|
+
) -> None: ...
|
|
32
|
+
def check(self, value: Any, /) -> None: ...
|
|
33
|
+
def class_info(self, cls: type[Any], /) -> tuple[str, Any, tuple[Any, ...]]: ...
|
|
34
|
+
|
|
35
|
+
@final
|
|
36
|
+
class _Copier:
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
copy_module: ModuleType,
|
|
40
|
+
deepcopy: Callable[..., Any],
|
|
41
|
+
list_copier: Callable[..., Any],
|
|
42
|
+
dict_copier: Callable[..., Any],
|
|
43
|
+
tuple_copier: Callable[..., Any],
|
|
44
|
+
atomic_copier: Callable[..., Any] | None,
|
|
45
|
+
reconstruct: Callable[..., Any],
|
|
46
|
+
atomic_first: bool,
|
|
47
|
+
memo_sentinel: object,
|
|
48
|
+
) -> None: ...
|
|
49
|
+
def __call__(self, value: Any, memo: dict[int, Any] | None = None, /) -> Any: ...
|
|
50
|
+
def deepcopy(self, value: Any, memo: dict[int, Any] | None = None, /) -> Any: ...
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
"""Error-only JSON traversal; successful requests retain typed msgspec decoding."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import datetime
|
|
7
|
+
import decimal
|
|
8
|
+
import enum
|
|
9
|
+
import inspect
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from types import UnionType
|
|
13
|
+
from typing import (
|
|
14
|
+
Annotated,
|
|
15
|
+
Any,
|
|
16
|
+
Literal,
|
|
17
|
+
NamedTuple,
|
|
18
|
+
Tuple,
|
|
19
|
+
Union,
|
|
20
|
+
get_args,
|
|
21
|
+
get_origin,
|
|
22
|
+
get_type_hints,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
import msgspec
|
|
26
|
+
from typing_extensions import NotRequired, Required, is_typeddict
|
|
27
|
+
|
|
28
|
+
from .validation import base_type, pattern_validator
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _Unsupported(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Node(NamedTuple):
|
|
36
|
+
target: Any
|
|
37
|
+
origin: Any
|
|
38
|
+
args: tuple[Any, ...]
|
|
39
|
+
cls: Any
|
|
40
|
+
metadata: tuple[Any, ...]
|
|
41
|
+
check_patterns: Callable[..., list[dict[str, Any]]] | None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_TYPE_MRO = type.__dict__['__mro__'].__get__
|
|
45
|
+
_TYPE_DICT = type.__dict__['__dict__'].__get__
|
|
46
|
+
_ENUM_METHODS = tuple(
|
|
47
|
+
(name, tuple(inspect.getattr_static(base, name) for base in bases))
|
|
48
|
+
for name, bases in (
|
|
49
|
+
('_missing_', (enum.Enum,)),
|
|
50
|
+
('__hash__', (enum.Enum, object, int, str)),
|
|
51
|
+
('__eq__', (enum.Enum, object, int, str)),
|
|
52
|
+
('__getattribute__', (enum.Enum, object, int, str)),
|
|
53
|
+
)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _type_guard(watched: list[tuple[type, tuple[str, ...]]]) -> Callable[[], bool]:
|
|
58
|
+
sentinel = object()
|
|
59
|
+
namespaces = []
|
|
60
|
+
mros = []
|
|
61
|
+
seen: set[tuple[int, str]] = set()
|
|
62
|
+
classes: set[int] = set()
|
|
63
|
+
for cls, names in watched:
|
|
64
|
+
mro = _TYPE_MRO(cls)
|
|
65
|
+
if id(cls) not in classes:
|
|
66
|
+
classes.add(id(cls))
|
|
67
|
+
mros.append((cls, mro))
|
|
68
|
+
for base in mro:
|
|
69
|
+
mapping = _TYPE_DICT(base)
|
|
70
|
+
for name in names:
|
|
71
|
+
key = (id(base), name)
|
|
72
|
+
if key not in seen:
|
|
73
|
+
seen.add(key)
|
|
74
|
+
namespaces.append((mapping, name, mapping.get(name, sentinel)))
|
|
75
|
+
|
|
76
|
+
def unchanged() -> bool:
|
|
77
|
+
return all(_TYPE_MRO(cls) is before for cls, before in mros) and all(
|
|
78
|
+
mapping.get(name, sentinel) is before for mapping, name, before in namespaces
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return unchanged
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _fields(annotation: Any) -> tuple[list[tuple[str | int, Any, bool]], Any]:
|
|
85
|
+
cls = get_origin(annotation) or annotation
|
|
86
|
+
if isinstance(cls, type) and issubclass(cls, msgspec.Struct):
|
|
87
|
+
config = cls.__struct_config__
|
|
88
|
+
offset = int(config.array_like and config.tag is not None)
|
|
89
|
+
fields = [
|
|
90
|
+
(index + offset if config.array_like else field.encode_name, field.type, field.required)
|
|
91
|
+
for index, field in enumerate(msgspec.structs.fields(annotation))
|
|
92
|
+
]
|
|
93
|
+
return fields, config
|
|
94
|
+
if is_typeddict(cls):
|
|
95
|
+
if get_origin(annotation) is not None:
|
|
96
|
+
raise _Unsupported
|
|
97
|
+
hints = get_type_hints(cls, include_extras=True)
|
|
98
|
+
fields = []
|
|
99
|
+
for name, target in hints.items():
|
|
100
|
+
required = name in cls.__required_keys__
|
|
101
|
+
if get_origin(target) in (Required, NotRequired):
|
|
102
|
+
required = get_origin(target) is Required
|
|
103
|
+
target = get_args(target)[0]
|
|
104
|
+
fields.append((name, target, required))
|
|
105
|
+
return fields, None
|
|
106
|
+
if isinstance(cls, type) and dataclasses.is_dataclass(cls):
|
|
107
|
+
if get_origin(annotation) is not None:
|
|
108
|
+
raise _Unsupported
|
|
109
|
+
hints = get_type_hints(cls, include_extras=True)
|
|
110
|
+
return [
|
|
111
|
+
(
|
|
112
|
+
field.name,
|
|
113
|
+
hints[field.name],
|
|
114
|
+
field.default is dataclasses.MISSING
|
|
115
|
+
and field.default_factory is dataclasses.MISSING,
|
|
116
|
+
)
|
|
117
|
+
for field in dataclasses.fields(cls)
|
|
118
|
+
], None
|
|
119
|
+
raise _Unsupported
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _safe(annotation: Any, seen: set[Any], field_cache: dict[Any, Any], plain: set[Any]) -> bool:
|
|
123
|
+
"""Check hooks and identify types decoded without constructing models."""
|
|
124
|
+
annotation = base_type(annotation)
|
|
125
|
+
origin = get_origin(annotation)
|
|
126
|
+
cls = origin or annotation
|
|
127
|
+
if origin is None and not isinstance(cls, type) and annotation is not Any:
|
|
128
|
+
raise _Unsupported
|
|
129
|
+
if isinstance(cls, type) and issubclass(cls, tuple) and hasattr(cls, '_fields'):
|
|
130
|
+
raise _Unsupported
|
|
131
|
+
if isinstance(cls, type) and (
|
|
132
|
+
issubclass(cls, msgspec.Struct) or dataclasses.is_dataclass(cls) or is_typeddict(cls)
|
|
133
|
+
):
|
|
134
|
+
if annotation in seen:
|
|
135
|
+
return False
|
|
136
|
+
seen.add(annotation)
|
|
137
|
+
if getattr(cls, '__post_init__', None) is not None:
|
|
138
|
+
raise _Unsupported
|
|
139
|
+
field_cache[annotation] = _fields(annotation)
|
|
140
|
+
fields, _ = field_cache[annotation]
|
|
141
|
+
for _, child, _ in fields:
|
|
142
|
+
_safe(child, seen, field_cache, plain)
|
|
143
|
+
return False
|
|
144
|
+
if origin in (list, tuple, set, frozenset, dict, Union, UnionType):
|
|
145
|
+
children = [
|
|
146
|
+
_safe(arg, seen, field_cache, plain)
|
|
147
|
+
for arg in get_args(annotation)
|
|
148
|
+
if arg is not Ellipsis
|
|
149
|
+
]
|
|
150
|
+
decodable = all(children)
|
|
151
|
+
elif origin is Literal or annotation is Any:
|
|
152
|
+
decodable = True
|
|
153
|
+
elif isinstance(cls, type) and issubclass(cls, enum.Enum):
|
|
154
|
+
for name, defaults in _ENUM_METHODS:
|
|
155
|
+
method = inspect.getattr_static(cls, name)
|
|
156
|
+
if not any(method is default for default in defaults):
|
|
157
|
+
raise _Unsupported
|
|
158
|
+
decodable = True
|
|
159
|
+
elif cls in (
|
|
160
|
+
type(None),
|
|
161
|
+
bool,
|
|
162
|
+
int,
|
|
163
|
+
float,
|
|
164
|
+
str,
|
|
165
|
+
bytes,
|
|
166
|
+
bytearray,
|
|
167
|
+
memoryview,
|
|
168
|
+
datetime.datetime,
|
|
169
|
+
datetime.date,
|
|
170
|
+
datetime.time,
|
|
171
|
+
datetime.timedelta,
|
|
172
|
+
decimal.Decimal,
|
|
173
|
+
uuid.UUID,
|
|
174
|
+
msgspec.Raw,
|
|
175
|
+
):
|
|
176
|
+
decodable = True
|
|
177
|
+
else:
|
|
178
|
+
raise _Unsupported
|
|
179
|
+
if decodable:
|
|
180
|
+
plain.add(annotation)
|
|
181
|
+
return decodable
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _error(
|
|
185
|
+
loc: tuple[str | int, ...], message: str, kind: str = 'value_error.msgspec'
|
|
186
|
+
) -> dict[str, Any]:
|
|
187
|
+
return {'loc': loc, 'msg': message, 'type': kind}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _convert_errors(
|
|
191
|
+
value: Any, target: Any, loc: tuple[str | int, ...], nodes: dict[Any, _Node]
|
|
192
|
+
) -> list[dict[str, Any]]:
|
|
193
|
+
try:
|
|
194
|
+
msgspec.json.decode(msgspec.json.encode(value), type=target)
|
|
195
|
+
except msgspec.ValidationError as exc:
|
|
196
|
+
return [_error(loc, str(exc))]
|
|
197
|
+
check = nodes[target].check_patterns
|
|
198
|
+
return check(value, loc) if check is not None else []
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _walk(
|
|
202
|
+
value: Any,
|
|
203
|
+
annotation: Any,
|
|
204
|
+
loc: tuple[str | int, ...],
|
|
205
|
+
field_cache: dict[Any, Any],
|
|
206
|
+
plain: set[Any],
|
|
207
|
+
nodes: dict[Any, _Node],
|
|
208
|
+
) -> list[dict[str, Any]]:
|
|
209
|
+
target, origin, args, cls, metadata, _ = nodes[annotation]
|
|
210
|
+
if target in plain:
|
|
211
|
+
errors = _convert_errors(value, annotation, loc, nodes)
|
|
212
|
+
if not errors or origin not in (list, tuple, set, frozenset, dict):
|
|
213
|
+
return errors
|
|
214
|
+
if origin is Union or origin is UnionType:
|
|
215
|
+
if Any in args:
|
|
216
|
+
return []
|
|
217
|
+
if value is None and type(None) in args:
|
|
218
|
+
return []
|
|
219
|
+
structured = []
|
|
220
|
+
for child in args:
|
|
221
|
+
child_cls = get_origin(base_type(child)) or base_type(child)
|
|
222
|
+
if isinstance(child_cls, type) and (
|
|
223
|
+
issubclass(child_cls, msgspec.Struct)
|
|
224
|
+
or dataclasses.is_dataclass(child_cls)
|
|
225
|
+
or is_typeddict(child_cls)
|
|
226
|
+
):
|
|
227
|
+
config = (
|
|
228
|
+
child_cls.__struct_config__ if issubclass(child_cls, msgspec.Struct) else None
|
|
229
|
+
)
|
|
230
|
+
if isinstance(value, dict) and not (config and config.array_like):
|
|
231
|
+
structured.append(child)
|
|
232
|
+
elif isinstance(value, list) and config and config.array_like:
|
|
233
|
+
structured.append(child)
|
|
234
|
+
if len(structured) == 1:
|
|
235
|
+
return _walk(value, structured[0], loc, field_cache, plain, nodes)
|
|
236
|
+
if structured:
|
|
237
|
+
for child in structured:
|
|
238
|
+
config = (get_origin(base_type(child)) or base_type(child)).__struct_config__
|
|
239
|
+
key = 0 if config.array_like else config.tag_field
|
|
240
|
+
if isinstance(value, dict):
|
|
241
|
+
tag = value.get(key, msgspec.NODEFAULT)
|
|
242
|
+
else:
|
|
243
|
+
tag = value[0] if value else msgspec.NODEFAULT
|
|
244
|
+
if type(tag) is type(config.tag) and tag == config.tag:
|
|
245
|
+
return _walk(value, child, loc, field_cache, plain, nodes)
|
|
246
|
+
key = (
|
|
247
|
+
0
|
|
248
|
+
if isinstance(value, list)
|
|
249
|
+
else (
|
|
250
|
+
get_origin(base_type(structured[0])) or base_type(structured[0])
|
|
251
|
+
).__struct_config__.tag_field
|
|
252
|
+
)
|
|
253
|
+
return [_error(loc + (key,), 'Invalid or missing type tag')]
|
|
254
|
+
if target not in plain:
|
|
255
|
+
raise _Unsupported
|
|
256
|
+
return _convert_errors(value, annotation, loc, nodes)
|
|
257
|
+
|
|
258
|
+
if isinstance(cls, type) and (
|
|
259
|
+
issubclass(cls, msgspec.Struct) or dataclasses.is_dataclass(cls) or is_typeddict(cls)
|
|
260
|
+
):
|
|
261
|
+
fields, config = field_cache[target]
|
|
262
|
+
array = bool(config and config.array_like)
|
|
263
|
+
if not isinstance(value, list if array else dict):
|
|
264
|
+
if type(value) is int and not -(1 << 63) <= value < (1 << 64):
|
|
265
|
+
return _convert_errors(value, annotation, loc, nodes)
|
|
266
|
+
try:
|
|
267
|
+
msgspec.convert(value, type=annotation)
|
|
268
|
+
except msgspec.ValidationError as exc:
|
|
269
|
+
return [_error(loc, str(exc))]
|
|
270
|
+
raise _Unsupported
|
|
271
|
+
errors = []
|
|
272
|
+
if config and config.tag is not None:
|
|
273
|
+
key = 0 if array else config.tag_field
|
|
274
|
+
present = len(value) > 0 if array else key in value
|
|
275
|
+
if present and (type(value[key]) is not type(config.tag) or value[key] != config.tag):
|
|
276
|
+
errors.append(_error(loc + (key,), 'Invalid type tag'))
|
|
277
|
+
for key, child, required in fields:
|
|
278
|
+
if array:
|
|
279
|
+
assert isinstance(value, list) and isinstance(key, int)
|
|
280
|
+
present = key < len(value)
|
|
281
|
+
else:
|
|
282
|
+
assert isinstance(value, dict)
|
|
283
|
+
present = key in value
|
|
284
|
+
if present:
|
|
285
|
+
errors.extend(_walk(value[key], child, loc + (key,), field_cache, plain, nodes))
|
|
286
|
+
elif required:
|
|
287
|
+
errors.append(_error(loc + (key,), 'Field required', 'missing'))
|
|
288
|
+
if config and config.forbid_unknown_fields:
|
|
289
|
+
known = {key for key, _, _ in fields}
|
|
290
|
+
if config.tag is not None:
|
|
291
|
+
known.add(0 if array else config.tag_field)
|
|
292
|
+
for key in range(len(value)) if array else value:
|
|
293
|
+
if key not in known:
|
|
294
|
+
errors.append(_error(loc + (key,), 'Unexpected field', 'extra_forbidden'))
|
|
295
|
+
return errors
|
|
296
|
+
|
|
297
|
+
if origin in (list, tuple, set, frozenset, dict):
|
|
298
|
+
if target in (tuple[()], Tuple[()]):
|
|
299
|
+
raise _Unsupported
|
|
300
|
+
if (
|
|
301
|
+
origin in (set, frozenset)
|
|
302
|
+
or (origin is dict and args and base_type(args[0]) not in (str, Any))
|
|
303
|
+
) and any(
|
|
304
|
+
isinstance(item, msgspec.Meta)
|
|
305
|
+
and (item.min_length is not None or item.max_length is not None)
|
|
306
|
+
for item in metadata
|
|
307
|
+
):
|
|
308
|
+
raise _Unsupported
|
|
309
|
+
if not isinstance(value, dict if origin is dict else list):
|
|
310
|
+
return _convert_errors(value, annotation, loc, nodes)
|
|
311
|
+
relaxed: Any
|
|
312
|
+
if origin is dict:
|
|
313
|
+
relaxed = dict[Any, Any]
|
|
314
|
+
elif origin is tuple and args and args[-1] is not Ellipsis:
|
|
315
|
+
relaxed = origin[tuple(Any for _ in args)]
|
|
316
|
+
else:
|
|
317
|
+
relaxed = origin[Any] if origin is not tuple else tuple[Any, ...]
|
|
318
|
+
if metadata:
|
|
319
|
+
relaxed = Annotated[relaxed, *metadata]
|
|
320
|
+
errors = []
|
|
321
|
+
try:
|
|
322
|
+
msgspec.convert(value, type=relaxed)
|
|
323
|
+
except msgspec.ValidationError as exc:
|
|
324
|
+
errors.append(_error(loc, str(exc)))
|
|
325
|
+
except TypeError as exc:
|
|
326
|
+
raise _Unsupported from exc
|
|
327
|
+
if origin is dict:
|
|
328
|
+
assert isinstance(value, dict)
|
|
329
|
+
key_type, child_type = args or (Any, Any)
|
|
330
|
+
for key, item in value.items():
|
|
331
|
+
try:
|
|
332
|
+
msgspec.json.decode(
|
|
333
|
+
msgspec.json.encode({key: None}), type=origin[key_type, Any]
|
|
334
|
+
)
|
|
335
|
+
except msgspec.ValidationError as exc:
|
|
336
|
+
errors.append(_error(loc + (key, '[key]'), str(exc)))
|
|
337
|
+
check = nodes[key_type].check_patterns
|
|
338
|
+
if check is not None:
|
|
339
|
+
errors.extend(check(key, loc + (key, '[key]')))
|
|
340
|
+
errors.extend(_walk(item, child_type, loc + (key,), field_cache, plain, nodes))
|
|
341
|
+
else:
|
|
342
|
+
for index, item in enumerate(value):
|
|
343
|
+
if origin is tuple and args and args[-1] is not Ellipsis:
|
|
344
|
+
if index >= len(args):
|
|
345
|
+
continue
|
|
346
|
+
child = args[index]
|
|
347
|
+
else:
|
|
348
|
+
child = args[0] if args else Any
|
|
349
|
+
errors.extend(_walk(item, child, loc + (index,), field_cache, plain, nodes))
|
|
350
|
+
return errors
|
|
351
|
+
return _convert_errors(value, annotation, loc, nodes)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def compile_body_errors(annotation: Any) -> Callable[..., list[dict[str, Any]]]:
|
|
355
|
+
"""Prepare immutable schema metadata; keep error lists local to each call."""
|
|
356
|
+
try:
|
|
357
|
+
field_cache: dict[Any, Any] = {}
|
|
358
|
+
plain: set[Any] = set()
|
|
359
|
+
_safe(annotation, set(), field_cache, plain)
|
|
360
|
+
nodes: dict[Any, _Node] = {}
|
|
361
|
+
pending = [annotation]
|
|
362
|
+
while pending:
|
|
363
|
+
current = pending.pop()
|
|
364
|
+
if current in nodes:
|
|
365
|
+
continue
|
|
366
|
+
target = base_type(current)
|
|
367
|
+
origin, args = get_origin(target), get_args(target)
|
|
368
|
+
metadata = get_args(current)[1:] if get_origin(current) is Annotated else ()
|
|
369
|
+
nodes[current] = _Node(
|
|
370
|
+
target, origin, args, origin or target, metadata, pattern_validator(current)
|
|
371
|
+
)
|
|
372
|
+
if target in field_cache:
|
|
373
|
+
pending.extend(child for _, child, _ in field_cache[target][0])
|
|
374
|
+
if origin is not Literal:
|
|
375
|
+
pending.extend(arg for arg in args if arg is not Ellipsis)
|
|
376
|
+
watched: list[tuple[type, tuple[str, ...]]] = []
|
|
377
|
+
for node in nodes.values():
|
|
378
|
+
if node.target in field_cache:
|
|
379
|
+
watched.append((node.cls, ('__post_init__',)))
|
|
380
|
+
elif isinstance(node.cls, type) and issubclass(node.cls, enum.Enum):
|
|
381
|
+
watched.append((node.cls, tuple(name for name, _ in _ENUM_METHODS)))
|
|
382
|
+
unchanged = _type_guard(watched)
|
|
383
|
+
except (_Unsupported, TypeError, NameError, RecursionError):
|
|
384
|
+
return lambda value, loc=('body',): []
|
|
385
|
+
|
|
386
|
+
def diagnose(value: Any, loc: tuple[str | int, ...] = ('body',)) -> list[dict[str, Any]]:
|
|
387
|
+
if not unchanged():
|
|
388
|
+
return []
|
|
389
|
+
try:
|
|
390
|
+
return _walk(value, annotation, loc, field_cache, plain, nodes)
|
|
391
|
+
except (_Unsupported, TypeError, NameError, RecursionError):
|
|
392
|
+
return []
|
|
393
|
+
|
|
394
|
+
return diagnose
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def body_errors(
|
|
398
|
+
value: Any, annotation: Any, loc: tuple[str | int, ...] = ('body',)
|
|
399
|
+
) -> list[dict[str, Any]]:
|
|
400
|
+
return compile_body_errors(annotation)(value, loc)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _raw_pure(annotation: Any) -> bool:
|
|
404
|
+
if get_origin(annotation) is Annotated:
|
|
405
|
+
if any(not isinstance(m, msgspec.Meta) for m in get_args(annotation)[1:]):
|
|
406
|
+
return False
|
|
407
|
+
annotation = get_args(annotation)[0]
|
|
408
|
+
if any(annotation is t for t in (str, int, float, bool, type(None))):
|
|
409
|
+
return True
|
|
410
|
+
origin, args = get_origin(annotation), get_args(annotation)
|
|
411
|
+
if any(origin is t for t in (list, set, frozenset)):
|
|
412
|
+
return len(args) == 1 and _raw_pure(args[0])
|
|
413
|
+
if origin is dict:
|
|
414
|
+
return len(args) == 2 and all(_raw_pure(a) for a in args)
|
|
415
|
+
if origin is tuple:
|
|
416
|
+
return bool(args) and all(_raw_pure(a) for a in args if a is not Ellipsis)
|
|
417
|
+
if origin is Union or origin is UnionType:
|
|
418
|
+
return bool(args) and all(_raw_pure(a) for a in args)
|
|
419
|
+
return False
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _compile_raw_list_errors(
|
|
423
|
+
annotation: Any, full_walk: Callable[..., list[dict[str, Any]]]
|
|
424
|
+
) -> Callable[..., list[dict[str, Any]]] | None:
|
|
425
|
+
root = base_type(annotation)
|
|
426
|
+
args = get_args(root)
|
|
427
|
+
if get_origin(root) is not list or len(args) != 1 or pattern_validator(annotation) is not None:
|
|
428
|
+
return None
|
|
429
|
+
child = args[0]
|
|
430
|
+
cls = get_origin(base_type(child)) or base_type(child)
|
|
431
|
+
if not isinstance(cls, type) or not issubclass(cls, msgspec.Struct):
|
|
432
|
+
return None
|
|
433
|
+
try:
|
|
434
|
+
_safe(annotation, set(), {}, set())
|
|
435
|
+
fields = msgspec.structs.fields(child)
|
|
436
|
+
if not all(_raw_pure(f.type) for f in fields):
|
|
437
|
+
return None
|
|
438
|
+
config = cls.__struct_config__
|
|
439
|
+
specs = [
|
|
440
|
+
(f'_field_{index}', f.type, msgspec.field(name=f.encode_name))
|
|
441
|
+
if f.required
|
|
442
|
+
else (f'_field_{index}', f.type, msgspec.field(name=f.encode_name, default=None))
|
|
443
|
+
for index, f in enumerate(fields)
|
|
444
|
+
]
|
|
445
|
+
# JSON-only fields and inert defaults cannot form cycles in this transient model.
|
|
446
|
+
wire = msgspec.defstruct(
|
|
447
|
+
'_DiagnosticWire',
|
|
448
|
+
specs,
|
|
449
|
+
kw_only=True,
|
|
450
|
+
gc=False,
|
|
451
|
+
tag=config.tag,
|
|
452
|
+
tag_field=config.tag_field or 'type',
|
|
453
|
+
array_like=config.array_like,
|
|
454
|
+
forbid_unknown_fields=True,
|
|
455
|
+
)
|
|
456
|
+
wire_decoder = msgspec.json.Decoder(type=wire)
|
|
457
|
+
raw_decoder = msgspec.json.Decoder(type=list[msgspec.Raw])
|
|
458
|
+
any_decoder = msgspec.json.Decoder()
|
|
459
|
+
child_walk = compile_body_errors(child)
|
|
460
|
+
metadata = get_args(annotation)[1:] if get_origin(annotation) is Annotated else ()
|
|
461
|
+
relaxed = Annotated[list[Any], *metadata] if metadata else None
|
|
462
|
+
unchanged = _type_guard([(cls, ('__post_init__',))])
|
|
463
|
+
decode_piece = wire_decoder.decode
|
|
464
|
+
except (_Unsupported, TypeError, NameError, RecursionError):
|
|
465
|
+
return None
|
|
466
|
+
|
|
467
|
+
def diagnose(raw: bytes, loc: tuple[str | int, ...] = ('body',)) -> list[dict[str, Any]]:
|
|
468
|
+
if not unchanged() or (not config.array_like and b'{' not in raw):
|
|
469
|
+
return full_walk(any_decoder.decode(raw), loc)
|
|
470
|
+
try:
|
|
471
|
+
pieces = raw_decoder.decode(raw)
|
|
472
|
+
except (msgspec.DecodeError, UnicodeError):
|
|
473
|
+
return full_walk(any_decoder.decode(raw), loc)
|
|
474
|
+
errors = []
|
|
475
|
+
if relaxed is not None:
|
|
476
|
+
try:
|
|
477
|
+
msgspec.convert(pieces, type=relaxed)
|
|
478
|
+
except msgspec.ValidationError as exc:
|
|
479
|
+
errors.append(_error(loc, str(exc)))
|
|
480
|
+
for index, piece in enumerate(pieces):
|
|
481
|
+
try:
|
|
482
|
+
decode_piece(piece)
|
|
483
|
+
except (msgspec.DecodeError, UnicodeError):
|
|
484
|
+
# Validate complete failed/unknown pieces. Full fallback preserves
|
|
485
|
+
# original syntax-error text and first-invalid-value ordering.
|
|
486
|
+
try:
|
|
487
|
+
value = any_decoder.decode(piece)
|
|
488
|
+
except (msgspec.DecodeError, UnicodeError):
|
|
489
|
+
return full_walk(any_decoder.decode(raw), loc)
|
|
490
|
+
errors.extend(child_walk(value, loc + (index,)))
|
|
491
|
+
return errors
|
|
492
|
+
|
|
493
|
+
return diagnose
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def compile_json_body_errors(annotation: Any) -> Callable[..., list[dict[str, Any]]]:
|
|
497
|
+
"""Use original JSON slices when safe, otherwise retain the structural traversal."""
|
|
498
|
+
walk = compile_body_errors(annotation)
|
|
499
|
+
raw_walk = _compile_raw_list_errors(annotation, walk)
|
|
500
|
+
if raw_walk is not None:
|
|
501
|
+
return raw_walk
|
|
502
|
+
|
|
503
|
+
def diagnose(raw: bytes, loc: tuple[str | int, ...] = ('body',)) -> list[dict[str, Any]]:
|
|
504
|
+
return walk(msgspec.json.decode(raw), loc)
|
|
505
|
+
|
|
506
|
+
return diagnose
|