msgspecerror 0.21.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.
- msgspecerror/__init__.py +12 -0
- msgspecerror/const.py +425 -0
- msgspecerror/parse_anno.py +125 -0
- msgspecerror/parse_ctx.py +216 -0
- msgspecerror/parse_error.py +293 -0
- msgspecerror/parse_msgpack.py +452 -0
- msgspecerror/parse_path.py +178 -0
- msgspecerror/parse_struct.py +180 -0
- msgspecerror/parse_type.py +324 -0
- msgspecerror/repair.py +558 -0
- msgspecerror/repair_unicode.py +83 -0
- msgspecerror-0.21.1.0.dist-info/METADATA +551 -0
- msgspecerror-0.21.1.0.dist-info/RECORD +15 -0
- msgspecerror-0.21.1.0.dist-info/WHEEL +5 -0
- msgspecerror-0.21.1.0.dist-info/top_level.txt +1 -0
msgspecerror/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .const import ErrorType, DECODE_ERRORS, ENCODE_ERRORS
|
|
2
|
+
from .parse_anno import (get_class_annotation, get_class_annotation_dict,
|
|
3
|
+
get_msgspec_annotation, get_msgspec_annotation_dict)
|
|
4
|
+
from .parse_ctx import ErrorCtx
|
|
5
|
+
from .parse_error import MsgspecError, parse_msgspec_error
|
|
6
|
+
from .parse_struct import get_field_default, get_field_name, get_field_typehint
|
|
7
|
+
from .parse_type import get_default
|
|
8
|
+
from .repair import load_json_with_default, load_msgpack_with_default
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
__version__ = version = '0.21.1.0'
|
|
12
|
+
__version_tuple__ = version_tuple = (0, 21, 1, 0)
|
msgspecerror/const.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
from msgspec import ValidationError, DecodeError, EncodeError
|
|
5
|
+
|
|
6
|
+
DECODE_ERRORS = (ValidationError, DecodeError, UnicodeDecodeError)
|
|
7
|
+
ENCODE_ERRORS = (EncodeError, UnicodeEncodeError)
|
|
8
|
+
MAXIMUM_REPAIR = 100
|
|
9
|
+
|
|
10
|
+
# Shared utf8_error type for public repair API
|
|
11
|
+
T_utf8_error = Literal['strict', 'replace', 'ignore']
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# StrEnum is introduced in py3.11
|
|
15
|
+
class ErrorType(str, Enum):
|
|
16
|
+
"""
|
|
17
|
+
An enumeration of all possible `ValidationError` forms from msgspec,
|
|
18
|
+
grouped by the literal error message format.
|
|
19
|
+
|
|
20
|
+
Each member documents the error format, provides an example, and explains
|
|
21
|
+
the various conditions that can trigger it. The placeholder `<Path>`
|
|
22
|
+
represents a JSONPath-like string (e.g., "$.field") indicating the
|
|
23
|
+
error's location.
|
|
24
|
+
|
|
25
|
+
Note that when extracting error formats from msgspec source code, it must
|
|
26
|
+
be exactly matched, e.g. there might be error message like:
|
|
27
|
+
"Expected str ..." and "Expected `str`"
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __repr__(self):
|
|
31
|
+
return f'<{self.__class__.__name__}.{self.name}>'
|
|
32
|
+
|
|
33
|
+
# ======================================================================
|
|
34
|
+
# Group 1: Type Mismatch Errors
|
|
35
|
+
# ======================================================================
|
|
36
|
+
|
|
37
|
+
TYPE_MISMATCH = "TYPE_MISMATCH"
|
|
38
|
+
"""
|
|
39
|
+
Format: "Expected `<A>`, got `<B>` - at <Path>"
|
|
40
|
+
|
|
41
|
+
This is the most common category of error, triggered when a decoded value's
|
|
42
|
+
type is incompatible with the expected schema type.
|
|
43
|
+
Note that if <path> is root, " - at <path>" won't be shown
|
|
44
|
+
|
|
45
|
+
Examples:
|
|
46
|
+
- "Expected `int`, got `str` - at `$.age`"
|
|
47
|
+
- "Expected `str`, got `int` - at $.name"
|
|
48
|
+
- "Expected `MyCustomClass`, got `str` - at `$.custom_field`"
|
|
49
|
+
- "Expected `int`, got `str` - at `$.type`" (for tagged unions)
|
|
50
|
+
|
|
51
|
+
Triggered by:
|
|
52
|
+
1. **General Mismatch**: A decoded value's basic type (str, int, list, etc.)
|
|
53
|
+
doesn't match the target Python type.
|
|
54
|
+
2. **MsgPack-Specific Mismatch**: A msgpack-encoded value (e.g., a msgpack int)
|
|
55
|
+
cannot be coerced into the target Python type (e.g., str).
|
|
56
|
+
3. **Custom Type Mismatch**: A `dec_hook` returns an object that is not an
|
|
57
|
+
instance of the expected custom type.
|
|
58
|
+
4. **Tag Type Mismatch**: The tag field in a tagged union has an incorrect
|
|
59
|
+
type (e.g., an `int` was found when a `str` was expected).
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
TOKEN_TYPE_MISMATCH = "TOKEN_TYPE_MISMATCH"
|
|
63
|
+
"""
|
|
64
|
+
Format: "Expected `<type>` - at <Path>"
|
|
65
|
+
|
|
66
|
+
A type mismatch where the decoder encounters a syntactically valid JSON
|
|
67
|
+
token of the wrong type at the current decode position, but the actual
|
|
68
|
+
token type cannot be included in the error message because the token was
|
|
69
|
+
skipped (via ``json_skip``) rather than fully decoded. This always lacks
|
|
70
|
+
the ", got `<B>`" portion that distinguishes it from TYPE_MISMATCH.
|
|
71
|
+
|
|
72
|
+
Examples:
|
|
73
|
+
- "Expected `str` - at `$.kind`" (JSON: tag field value is non-string)
|
|
74
|
+
- "Expected `int` - at `$.kind`" (JSON: tag field value is non-int)
|
|
75
|
+
- "Expected `str` - at `key` in `$`" (convert: dict key is non-string)
|
|
76
|
+
|
|
77
|
+
Triggered by:
|
|
78
|
+
1. **Tag Value Mismatch** (JSON): The tag field value in a tagged union
|
|
79
|
+
has the wrong JSON token type (e.g., a number where a string tag
|
|
80
|
+
is expected, or vice versa).
|
|
81
|
+
2. **Map Key Mismatch** (convert): A dict key in `msgspec.convert()` or
|
|
82
|
+
equivalent path is not a string — the target type (Struct, TypedDict,
|
|
83
|
+
or dataclass) only has string field names, so non-string keys cannot
|
|
84
|
+
be matched.
|
|
85
|
+
3. **Token Type Mismatch** (JSON): The decoder expects an ``int`` or
|
|
86
|
+
``str`` at the current JSON decode position, but the next JSON token
|
|
87
|
+
has a different type. The token is identified by peeking its first
|
|
88
|
+
character and skipped with ``json_skip`` before the error is raised.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
# ======================================================================
|
|
92
|
+
# Group 2: Structural Errors (Format: "Object ... <field_name> ...")
|
|
93
|
+
# ======================================================================
|
|
94
|
+
|
|
95
|
+
MISSING_FIELD = "MISSING_FIELD"
|
|
96
|
+
"""
|
|
97
|
+
Format: "Object missing required field `<field_name>` - at `<Path>`"
|
|
98
|
+
Example: "Object missing required field `id`"
|
|
99
|
+
Triggered by: A Struct, TypedDict, or dataclass is missing a required field
|
|
100
|
+
that has no default value.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
UNKNOWN_FIELD = "UNKNOWN_FIELD"
|
|
104
|
+
"""
|
|
105
|
+
Format: "Object contains unknown field `<field_name>` - at `<Path>`"
|
|
106
|
+
Example: "Object contains unknown field 'favorite_color' - at `$`"
|
|
107
|
+
Triggered by: Decoding a Struct with `forbid_unknown_fields=True` and encountering
|
|
108
|
+
a field in the message that is not defined on the struct.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
# ======================================================================
|
|
112
|
+
# Group 3: Constraint and Length Errors
|
|
113
|
+
# ======================================================================
|
|
114
|
+
|
|
115
|
+
ARRAY_LENGTH_CONSTRAINT = "ARRAY_LENGTH_CONSTRAINT"
|
|
116
|
+
"""
|
|
117
|
+
Format: "Expected `array` of at (least|most) length <expected>, got <actual>[ - at <Path>]"
|
|
118
|
+
"Expected `array` of length <min> to <max>, got <actual>[ - at <Path>]"
|
|
119
|
+
"Expected `array` of length <expected>[ - at <Path>]"
|
|
120
|
+
Example: "Expected `array` of length 2, got 3 - at $.coordinates"
|
|
121
|
+
Triggered by: Decoding a fixed-size tuple (e.g., tuple[int, int]) or a NamedTuple,
|
|
122
|
+
and the array in the message has a different number of elements.
|
|
123
|
+
|
|
124
|
+
=== Added in 0.19.0 ===
|
|
125
|
+
Format: "Expected `array` of at most length <expected>" (without path suffix)
|
|
126
|
+
Example: "Expected `array` of at most length 2" (msgspec bug: path suffix omitted)
|
|
127
|
+
Triggered by:
|
|
128
|
+
Note: the variant without "- at <Path>" is a known msgspec bug
|
|
129
|
+
(missing %U format specifier) where the error location is lost.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
OBJECT_LENGTH_CONSTRAINT = "OBJECT_LENGTH_CONSTRAINT"
|
|
133
|
+
"""
|
|
134
|
+
Format: "Expected `object` of length <op> <value> - at <Path>"
|
|
135
|
+
Example: "Expected `object` of length >= 1 - at $.metadata"
|
|
136
|
+
Triggered by: A dictionary-like object (`dict`, `TypedDict`, `Struct`) violates
|
|
137
|
+
a `min_length` or `max_length` constraint defined in a `Meta` object.
|
|
138
|
+
Note: "object" here is JSON/MsgPack terminology for a key-value map.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
LENGTH_CONSTRAINT = "LENGTH_CONSTRAINT"
|
|
142
|
+
"""
|
|
143
|
+
Format: "Expected `<type>` of length <op> <value> - at <Path>"
|
|
144
|
+
Example: "Expected `str` of length <= 32 - at $.name"
|
|
145
|
+
Triggered by: A variable-length sequence (`list`, `set`, `frozenset`) or a sized
|
|
146
|
+
scalar (`str`, `bytes`) violates a `min_length` or `max_length`
|
|
147
|
+
constraint defined in a `Meta` object.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
PATTERN_CONSTRAINT = "PATTERN_CONSTRAINT"
|
|
151
|
+
"""
|
|
152
|
+
Format: "Expected `str` matching regex <pattern> - at <Path>"
|
|
153
|
+
Example: "Expected `str` matching regex '\\d{4}-\\d{2}-\\d{2}' - at $.date_str"
|
|
154
|
+
Triggered by: A string value does not match the regex `pattern` constraint from
|
|
155
|
+
a `Meta` object.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
NUMERIC_CONSTRAINT = "NUMERIC_CONSTRAINT"
|
|
159
|
+
"""
|
|
160
|
+
Format: "Expected `<type>` <op> <value> - at <Path>"
|
|
161
|
+
"Expected `<type>` that's a multiple of <value> - at <Path>"
|
|
162
|
+
Example: "Expected `int` >= 0 - at $.age"
|
|
163
|
+
"Expected `int` that's a multiple of 6"
|
|
164
|
+
Triggered by: A numeric value violates a constraint from a `Meta` object (e.g.,
|
|
165
|
+
ge, lt, multiple_of).
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
TIMEZONE_CONSTRAINT = "TIMEZONE_CONSTRAINT"
|
|
169
|
+
"""
|
|
170
|
+
Format: "Expected `datetime` with (a|no) timezone component - at <Path>"
|
|
171
|
+
"Expected `time` with (a|no) timezone component - at <Path>"
|
|
172
|
+
Triggered by: A datetime/time object does not satisfy the `tz=True` (aware) or
|
|
173
|
+
`tz=False` (naive) constraint from a `Meta` object.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
# ======================================================================
|
|
177
|
+
# Group 4: Invalid Value Errors
|
|
178
|
+
# ======================================================================
|
|
179
|
+
|
|
180
|
+
INVALID_ENUM_VALUE = "INVALID_ENUM_VALUE"
|
|
181
|
+
"""
|
|
182
|
+
Format: "Invalid enum value <value> - at <Path>"
|
|
183
|
+
Example: "Invalid enum value 'admin' - at $.role"
|
|
184
|
+
Triggered by: A value that is not a valid member of the target `Enum` or
|
|
185
|
+
`Literal` type.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
INVALID_TAG_VALUE = "INVALID_TAG_VALUE"
|
|
189
|
+
"""
|
|
190
|
+
Format: "Invalid value <value>" or "Invalid value `<value>`" - at <Path>
|
|
191
|
+
Example: "Invalid value 3 - at $.type"
|
|
192
|
+
Triggered by: (Tagged Unions) The tag field's type is correct (e.g., str, int),
|
|
193
|
+
but its specific value does not match any of the expected tag
|
|
194
|
+
values for the types in the union.
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
INVALID_DATETIME = "INVALID_DATETIME"
|
|
198
|
+
"""
|
|
199
|
+
Format: "Invalid RFC3339 encoded datetime - at <Path>"
|
|
200
|
+
Example: "Invalid RFC3339 encoded datetime - at $.timestamp"
|
|
201
|
+
Triggered by: A string intended for a `datetime.datetime` type is malformed.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
INVALID_DATE = "INVALID_DATE"
|
|
205
|
+
"""
|
|
206
|
+
Format: "Invalid RFC3339 encoded date - at <Path>"
|
|
207
|
+
Example: "Invalid RFC3339 encoded date - at $.birth_date"
|
|
208
|
+
Triggered by: A string intended for a `datetime.date` type is malformed.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
INVALID_TIME = "INVALID_TIME"
|
|
212
|
+
"""
|
|
213
|
+
Format: "Invalid RFC3339 encoded time - at <Path>"
|
|
214
|
+
Example: "Invalid RFC3339 encoded time - at $.event_time"
|
|
215
|
+
Triggered by: A string intended for a `datetime.time` type is malformed.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
INVALID_DURATION = "INVALID_DURATION"
|
|
219
|
+
"""
|
|
220
|
+
Format: "Invalid ISO8601 duration - at <Path>"
|
|
221
|
+
Example: "Invalid ISO8601 duration - at $.period"
|
|
222
|
+
Triggered by: A string intended for a `datetime.timedelta` type is malformed.
|
|
223
|
+
"""
|
|
224
|
+
|
|
225
|
+
UNSUPPORTED_DURATION_UNITS = "UNSUPPORTED_DURATION_UNITS"
|
|
226
|
+
"""
|
|
227
|
+
Format: "Only units 'D', 'H', 'M', and 'S' are supported when parsing ISO8601 durations - at <Path>"
|
|
228
|
+
Triggered by: An ISO8601 duration string contains unsupported units like
|
|
229
|
+
'W' (weeks) or 'Y' (years).
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
INVALID_MSGPACK_TIMESTAMP = "INVALID_MSGPACK_TIMESTAMP"
|
|
233
|
+
"""
|
|
234
|
+
Format: "Invalid MessagePack timestamp[: nanoseconds out of range] - at <Path>"
|
|
235
|
+
Triggered by: (MsgPack only) A MessagePack extension with type code -1
|
|
236
|
+
(timestamp) is malformed due to incorrect data length or an
|
|
237
|
+
out-of-bounds nanosecond value.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
INVALID_UUID = "INVALID_UUID"
|
|
241
|
+
"""
|
|
242
|
+
Format: "Invalid UUID - at <Path>"
|
|
243
|
+
"Invalid UUID bytes - at <Path>"
|
|
244
|
+
Triggered by: A string or byte sequence intended for a UUID type is malformed.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
INVALID_BASE64_STRING = "INVALID_BASE64_STRING"
|
|
248
|
+
"""
|
|
249
|
+
Format: "Invalid base64 encoded string - at <Path>"
|
|
250
|
+
Triggered by: A string intended for a bytes/bytearray/memoryview type is not
|
|
251
|
+
valid base64.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
INVALID_DECIMAL_STRING = "INVALID_DECIMAL_STRING"
|
|
255
|
+
"""
|
|
256
|
+
Format: "Invalid decimal string - at <Path>"
|
|
257
|
+
Triggered by: A string intended for a `decimal.Decimal` type cannot be parsed.
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
INVALID_EPOCH_TIMESTAMP = "INVALID_EPOCH_TIMESTAMP"
|
|
261
|
+
"""
|
|
262
|
+
Format: "Invalid epoch timestamp - at <Path>"
|
|
263
|
+
Triggered by: A non-finite float (inf, -inf, nan) is being decoded as
|
|
264
|
+
a datetime object.
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
# ======================================================================
|
|
268
|
+
# Group 5: Out of Range Errors
|
|
269
|
+
# ======================================================================
|
|
270
|
+
|
|
271
|
+
TIMESTAMP_OUT_OF_RANGE = "TIMESTAMP_OUT_OF_RANGE"
|
|
272
|
+
"""
|
|
273
|
+
Format: "Timestamp is out of range - at <Path>"
|
|
274
|
+
Triggered by: A numeric or string value that represents a datetime outside the
|
|
275
|
+
range supported by Python's `datetime` object.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
DURATION_OUT_OF_RANGE = "DURATION_OUT_OF_RANGE"
|
|
279
|
+
"""
|
|
280
|
+
Format: "Duration is out of range - at <Path>"
|
|
281
|
+
Triggered by: A numeric or string value that represents a duration outside the
|
|
282
|
+
range supported by Python's `timedelta` object.
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
INTEGER_OUT_OF_RANGE = "INTEGER_OUT_OF_RANGE"
|
|
286
|
+
"""
|
|
287
|
+
Format: "Integer value out of range - at <Path>"
|
|
288
|
+
Triggered by: A string representing an integer is too large to be processed
|
|
289
|
+
(e.g., has more than 4300 digits).
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
NUMBER_OUT_OF_RANGE = "NUMBER_OUT_OF_RANGE"
|
|
293
|
+
"""
|
|
294
|
+
Format: "Number out of range - at <Path>"
|
|
295
|
+
Triggered by: A string representing a number (int or float) is outside the
|
|
296
|
+
range of a `double` precision float.
|
|
297
|
+
"""
|
|
298
|
+
|
|
299
|
+
# ======================================================================
|
|
300
|
+
# Group 6: Wrapped Errors
|
|
301
|
+
# ======================================================================
|
|
302
|
+
|
|
303
|
+
WRAPPED_ERROR = "WRAPPED_ERROR"
|
|
304
|
+
"""
|
|
305
|
+
Format: "<Original Error Message> - at <Path>"
|
|
306
|
+
Example: "passwords cannot be the same - at $"
|
|
307
|
+
Triggered by: `msgspec` catches a `TypeError` or `ValueError` from user code
|
|
308
|
+
(e.g., in a `dec_hook`, `__post_init__`, or a custom type's
|
|
309
|
+
`__init__`) and wraps it in a `ValidationError`.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
UNICODE_DECODE_ERROR = 'UNICODE_DECODE_ERROR'
|
|
313
|
+
"""
|
|
314
|
+
Our custom error type to wrap UnicodeDecodeError.
|
|
315
|
+
Format: '<codec>' codec can't decode byte <byte>...
|
|
316
|
+
Example:
|
|
317
|
+
- 'utf-8' codec can't decode byte {byte} in position {position}: invalid start byte
|
|
318
|
+
- 'utf-8' codec can't decode byte {byte} in position {position}: invalid continuation byte
|
|
319
|
+
- 'utf-8' codec can't decode bytes in position {position1}-{position2}: unexpected end of data
|
|
320
|
+
- 'utf-8' codec can't decode bytes in position {position1}-{position2}: surrogates not allowed
|
|
321
|
+
Triggered by: Invalid unicode in bytes
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
JSON_MALFORMED = "JSON_MALFORMED"
|
|
325
|
+
"""
|
|
326
|
+
Format: "JSON is malformed: <reason> (byte <pos>)"
|
|
327
|
+
|
|
328
|
+
Raised as `DecodeError` when the input is syntactically invalid JSON.
|
|
329
|
+
The `<reason>` is one of the error messages below; `<pos>` is the
|
|
330
|
+
byte offset where the error was detected.
|
|
331
|
+
|
|
332
|
+
Reasons:
|
|
333
|
+
- invalid character
|
|
334
|
+
- trailing characters
|
|
335
|
+
- expected ',' or ']'
|
|
336
|
+
- expected ',' or '}'
|
|
337
|
+
- expected ':'
|
|
338
|
+
- expected '"'
|
|
339
|
+
- trailing comma in array
|
|
340
|
+
- trailing comma in object
|
|
341
|
+
- object keys must be strings
|
|
342
|
+
- invalid number
|
|
343
|
+
- invalid escape character in string
|
|
344
|
+
- invalid character in unicode escape
|
|
345
|
+
- invalid utf-16 surrogate pair
|
|
346
|
+
- unexpected end of hex escape
|
|
347
|
+
- unexpected end of escaped utf-16 surrogate pair
|
|
348
|
+
- invalid escaped character
|
|
349
|
+
|
|
350
|
+
Triggered by: Any JSON text that does not conform to the JSON grammar.
|
|
351
|
+
"""
|
|
352
|
+
|
|
353
|
+
MSGPACK_MALFORMED = "MSGPACK_MALFORMED"
|
|
354
|
+
"""
|
|
355
|
+
Format: "MessagePack data is malformed: <reason> (byte <pos>)"
|
|
356
|
+
|
|
357
|
+
Raised as `DecodeError` when the input is syntactically invalid MsgPack.
|
|
358
|
+
|
|
359
|
+
Reasons:
|
|
360
|
+
- trailing characters (byte <pos>)
|
|
361
|
+
- invalid opcode '\\x<XX>' (byte <pos>)
|
|
362
|
+
|
|
363
|
+
Triggered by: Any MsgPack data that does not conform to the MessagePack
|
|
364
|
+
binary format, e.g. trailing bytes after a complete message
|
|
365
|
+
or an unrecognized opcode.
|
|
366
|
+
"""
|
|
367
|
+
|
|
368
|
+
DATA_TRUNCATED = "DATA_TRUNCATED"
|
|
369
|
+
"""
|
|
370
|
+
Format: "Input data was truncated"
|
|
371
|
+
|
|
372
|
+
Raised as `DecodeError` when the input ends unexpectedly before
|
|
373
|
+
the full message can be parsed. Both JSON and MessagePack decoders
|
|
374
|
+
can produce this error, and the message is identical for both.
|
|
375
|
+
|
|
376
|
+
Example:
|
|
377
|
+
- JSON: ``msgspec.json.decode(b'{"a": 1', type=object)``
|
|
378
|
+
- MsgPack: ``msgspec.msgpack.decode(b'\\xda\\x00\\x05', type=object)``
|
|
379
|
+
|
|
380
|
+
Triggered by:
|
|
381
|
+
1. JSON input that ends mid-token (unclosed braces/brackets/strings).
|
|
382
|
+
2. MessagePack input with an incomplete opcode or payload.
|
|
383
|
+
"""
|
|
384
|
+
|
|
385
|
+
ENCODE_ERROR = "ENCODE_ERROR"
|
|
386
|
+
"""
|
|
387
|
+
Format: "Can't encode <obj> longer than 2**32 - 1"
|
|
388
|
+
|
|
389
|
+
Raised as `EncodeError` when an object is too large to be encoded
|
|
390
|
+
in the MessagePack format (MsgPack's 32-bit length limit).
|
|
391
|
+
|
|
392
|
+
Examples:
|
|
393
|
+
- "Can't encode strings longer than 2**32 - 1"
|
|
394
|
+
- "Can't encode bytes-like objects longer than 2**32 - 1"
|
|
395
|
+
- "Can't encode arrays longer than 2**32 - 1"
|
|
396
|
+
- "Can't encode maps longer than 2**32 - 1"
|
|
397
|
+
- "Can't encode Ext objects with data longer than 2**32 - 1"
|
|
398
|
+
|
|
399
|
+
Triggered by: Encoding a string, bytes, array, map, or Ext object
|
|
400
|
+
whose length exceeds 2**32 - 1 (MsgPack 32-bit limit).
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
INPUT_REJECTED = "INPUT_REJECTED"
|
|
404
|
+
"""
|
|
405
|
+
Internal error type used by ``msgspecerror`` — never raised by msgspec
|
|
406
|
+
itself.
|
|
407
|
+
|
|
408
|
+
Emitted by the repair loop when a single input requires more than 100
|
|
409
|
+
repair attempts. This cap prevents server resource exhaustion from
|
|
410
|
+
maliciously crafted inputs that repeatedly trigger new errors after
|
|
411
|
+
each repair cycle.
|
|
412
|
+
|
|
413
|
+
Note:
|
|
414
|
+
This is an ``msgspecerror``-internal type. It does not correspond
|
|
415
|
+
to any msgspec ``ValidationError`` message.
|
|
416
|
+
|
|
417
|
+
Format: "Input rejected: too many repair cycles"
|
|
418
|
+
Triggered by: input repaired >100 times, but still fails
|
|
419
|
+
|
|
420
|
+
Format: "Input rejected: validation failed on struct defaults"
|
|
421
|
+
Triggered by: Usually because struct definition mistake:
|
|
422
|
+
__post_init__, dec_hook, etc, have conflicts with field defaults.
|
|
423
|
+
e.g. field struct writes `amount: int = 0`,
|
|
424
|
+
but __post_init__ checks `if self.amount < 1: raise ValueError`
|
|
425
|
+
"""
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from typing import Dict, Any
|
|
2
|
+
|
|
3
|
+
from msgspec import NODEFAULT, UNSET
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_class_annotation_dict(cls: type) -> Dict[str, Any]:
|
|
7
|
+
"""
|
|
8
|
+
Safely get __annotations__ of a class and its parent classes
|
|
9
|
+
A simpler version of `typing.get_type_hints`, that won't do _eval_type() just leave annotation as it is
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
cls (type): A class
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
dict[str, Any]: {name: annotation}, annotation can be typehint or string
|
|
16
|
+
"""
|
|
17
|
+
out = {}
|
|
18
|
+
try:
|
|
19
|
+
mro = cls.__mro__
|
|
20
|
+
except AttributeError:
|
|
21
|
+
raise TypeError(f'Input must be a class, got {cls}')
|
|
22
|
+
|
|
23
|
+
for base in reversed(mro):
|
|
24
|
+
annotations = getattr(base, '__annotations__', None)
|
|
25
|
+
if annotations:
|
|
26
|
+
out.update(annotations)
|
|
27
|
+
|
|
28
|
+
return out
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_msgspec_annotation_dict(cls: type) -> Dict[str, Any]:
|
|
32
|
+
"""
|
|
33
|
+
Safely get __annotations__ of a class and its parent classes, with special support for msgspec.
|
|
34
|
+
A simpler version of `typing.get_type_hints`, as we don't call _eval_type() just leave annotation as it is
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
cls (type): A class
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
dict[str, Any]: {name: annotation}, annotation can be typehint or string
|
|
41
|
+
"""
|
|
42
|
+
out = {}
|
|
43
|
+
try:
|
|
44
|
+
mro = cls.__mro__
|
|
45
|
+
except AttributeError:
|
|
46
|
+
raise TypeError(f'Input must be a class, got {cls}')
|
|
47
|
+
|
|
48
|
+
for base in reversed(mro):
|
|
49
|
+
annotations = getattr(base, '__annotations__', None)
|
|
50
|
+
if not annotations:
|
|
51
|
+
continue
|
|
52
|
+
for name, anno in annotations.items():
|
|
53
|
+
# get value
|
|
54
|
+
value = getattr(cls, name, NODEFAULT)
|
|
55
|
+
# ignore UNSET
|
|
56
|
+
if value == UNSET:
|
|
57
|
+
continue
|
|
58
|
+
out[name] = anno
|
|
59
|
+
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def get_class_annotation(cls: type, key: str):
|
|
64
|
+
"""
|
|
65
|
+
Get the annotation for a specific key from a class and its MRO in sequential order.
|
|
66
|
+
|
|
67
|
+
Iterates the MRO in sequential order (most-derived class first) and returns the
|
|
68
|
+
annotation for the given key from the first class that defines it.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
cls (type): A class
|
|
72
|
+
key (str): The annotation name to look up
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
Any: The annotation for the given key
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
AttributeError: If the key is not found in any class in the MRO
|
|
79
|
+
"""
|
|
80
|
+
try:
|
|
81
|
+
mro = cls.__mro__
|
|
82
|
+
except AttributeError:
|
|
83
|
+
raise TypeError(f'Input must be a class, got {cls}')
|
|
84
|
+
|
|
85
|
+
for base in mro:
|
|
86
|
+
annotations = getattr(base, '__annotations__', None)
|
|
87
|
+
if annotations and key in annotations:
|
|
88
|
+
return annotations[key]
|
|
89
|
+
|
|
90
|
+
raise AttributeError(f"'{cls.__name__}' has no annotation '{key}'")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_msgspec_annotation(cls: type, key: str):
|
|
94
|
+
"""
|
|
95
|
+
Get the annotation for a specific key from a class and its MRO, with msgspec UNSET support.
|
|
96
|
+
|
|
97
|
+
Iterates the MRO in sequential order (most-derived class first) and returns the
|
|
98
|
+
annotation for the given key from the first class that defines it, skipping any
|
|
99
|
+
field whose value is msgspec.UNSET.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
cls (type): A class
|
|
103
|
+
key (str): The annotation name to look up
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
Any: The annotation for the given key
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
AttributeError: If the key is not found (or is UNSET) in any class in the MRO
|
|
110
|
+
"""
|
|
111
|
+
try:
|
|
112
|
+
mro = cls.__mro__
|
|
113
|
+
except AttributeError:
|
|
114
|
+
raise TypeError(f'Input must be a class, got {cls}')
|
|
115
|
+
|
|
116
|
+
for base in mro:
|
|
117
|
+
annotations = getattr(base, '__annotations__', None)
|
|
118
|
+
if annotations and key in annotations:
|
|
119
|
+
# Check if the field is marked UNSET
|
|
120
|
+
value = getattr(cls, key, NODEFAULT)
|
|
121
|
+
if value == UNSET:
|
|
122
|
+
raise AttributeError(f"'{cls.__name__}' has no annotation '{key}'")
|
|
123
|
+
return annotations[key]
|
|
124
|
+
|
|
125
|
+
raise AttributeError(f"'{cls.__name__}' has no annotation '{key}'")
|