Debian Codegraph @

src/auth0/management/core/pydantic_utilities.py

raw symbols SCIP
1 # This file was auto-generated by Fern from our API Definition.
2
3 # nopycln: file
4 import datetime as dt
5 import inspect
6 import json
7 import logging
8 from collections import defaultdict
9 from dataclasses import asdict
10 from typing import (
11 TYPE_CHECKING,
12 Any,
13 Callable,
14 ClassVar,
15 Dict,
16 List,
17 Mapping,
18 Optional,
19 Set,
20 Tuple,
21 Type,
22 TypeVar,
23 Union,
24 cast,
25 )
26
27 import pydantic
28 import typing_extensions
29 from pydantic.fields import FieldInfo as _FieldInfo
30
31 _logger = logging.getLogger(__name__)
32
33 if TYPE_CHECKING:
34 from .http_sse._models import ServerSentEvent
35
36 IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
37
38 if IS_PYDANTIC_V2:
39 _datetime_adapter = pydantic.TypeAdapter(dt.datetime) # type: ignore[attr-defined]
40 _date_adapter = pydantic.TypeAdapter(dt.date) # type: ignore[attr-defined]
41
42 def parse_datetime(value: Any) -> dt.datetime: # type: ignore[misc]
43 if isinstance(value, dt.datetime):
44 return value
45 return _datetime_adapter.validate_python(value)
46
47 def parse_date(value: Any) -> dt.date: # type: ignore[misc]
48 if isinstance(value, dt.datetime):
49 return value.date()
50 if isinstance(value, dt.date):
51 return value
52 return _date_adapter.validate_python(value)
53
54 # Avoid importing from pydantic.v1 to maintain Python 3.14 compatibility.
55 from typing import get_args as get_args # type: ignore[assignment]
56 from typing import get_origin as get_origin # type: ignore[assignment]
57
58 def is_literal_type(tp: Optional[Type[Any]]) -> bool: # type: ignore[misc]
59 return typing_extensions.get_origin(tp) is typing_extensions.Literal
60
61 def is_union(tp: Optional[Type[Any]]) -> bool: # type: ignore[misc]
62 return tp is Union or typing_extensions.get_origin(tp) is Union # type: ignore[comparison-overlap]
63
64 # Inline encoders_by_type to avoid importing from pydantic.v1.json
65 import re as _re
66 from collections import deque as _deque
67 from decimal import Decimal as _Decimal
68 from enum import Enum as _Enum
69 from ipaddress import (
70 IPv4Address as _IPv4Address,
71 )
72 from ipaddress import (
73 IPv4Interface as _IPv4Interface,
74 )
75 from ipaddress import (
76 IPv4Network as _IPv4Network,
77 )
78 from ipaddress import (
79 IPv6Address as _IPv6Address,
80 )
81 from ipaddress import (
82 IPv6Interface as _IPv6Interface,
83 )
84 from ipaddress import (
85 IPv6Network as _IPv6Network,
86 )
87 from pathlib import Path as _Path
88 from types import GeneratorType as _GeneratorType
89 from uuid import UUID as _UUID
90
91 from pydantic.fields import FieldInfo as ModelField # type: ignore[no-redef, assignment]
92
93 def _decimal_encoder(dec_value: Any) -> Any:
94 if dec_value.as_tuple().exponent >= 0:
95 return int(dec_value)
96 return float(dec_value)
97
98 encoders_by_type: Dict[Type[Any], Callable[[Any], Any]] = { # type: ignore[no-redef]
99 bytes: lambda o: o.decode(),
100 dt.date: lambda o: o.isoformat(),
101 dt.datetime: lambda o: o.isoformat(),
102 dt.time: lambda o: o.isoformat(),
103 dt.timedelta: lambda td: td.total_seconds(),
104 _Decimal: _decimal_encoder,
105 _Enum: lambda o: o.value,
106 frozenset: list,
107 _deque: list,
108 _GeneratorType: list,
109 _IPv4Address: str,
110 _IPv4Interface: str,
111 _IPv4Network: str,
112 _IPv6Address: str,
113 _IPv6Interface: str,
114 _IPv6Network: str,
115 _Path: str,
116 _re.Pattern: lambda o: o.pattern,
117 set: list,
118 _UUID: str,
119 }
120 else:
121 from pydantic.datetime_parse import parse_date as parse_date # type: ignore[no-redef]
122 from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore[no-redef]
123 from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined, no-redef, assignment]
124 from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[no-redef]
125 from pydantic.typing import get_args as get_args # type: ignore[no-redef]
126 from pydantic.typing import get_origin as get_origin # type: ignore[no-redef]
127 from pydantic.typing import is_literal_type as is_literal_type # type: ignore[no-redef, assignment]
128 from pydantic.typing import is_union as is_union # type: ignore[no-redef]
129
130 from .datetime_utils import serialize_datetime
131 from .serialization import convert_and_respect_annotation_metadata
132 from typing_extensions import TypeAlias
133
134 T = TypeVar("T")
135 Model = TypeVar("Model", bound=pydantic.BaseModel)
136
137
138 def parse_sse_obj(sse: "ServerSentEvent", type_: Type[T]) -> T:
139 """
140 Parse a ServerSentEvent into the appropriate type.
141
142 This function handles data-level discrimination where the discriminator
143 (e.g., 'type') is inside the 'data' payload. It parses the SSE data field
144 as JSON and deserializes it into the target type.
145
146 Note: Protocol-level discrimination (where the discriminator comes from
147 the SSE event: field) is handled at code-generation time and does not
148 use this function.
149
150 Args:
151 sse: The ServerSentEvent object to parse
152 type_: The target type to deserialize into
153
154 Returns:
155 The parsed object of type T
156
157 Note:
158 This function is only available in SDK contexts where http_sse module exists.
159 """
160 sse_event = asdict(sse)
161 data_value = sse_event.get("data")
162 if isinstance(data_value, str) and data_value:
163 try:
164 parsed_data = json.loads(data_value)
165 return parse_obj_as(type_, parsed_data)
166 except json.JSONDecodeError as e:
167 _logger.warning(
168 "Failed to parse SSE data field as JSON: %s, data: %s",
169 e,
170 data_value[:100] if len(data_value) > 100 else data_value,
171 )
172 return parse_obj_as(type_, sse_event)
173
174
175 _type_adapter_cache: Dict[int, Any] = {}
176
177
178 def _get_type_adapter(type_: Type[Any]) -> Any:
179 key = id(type_)
180 adapter = _type_adapter_cache.get(key)
181 if adapter is None:
182 adapter = pydantic.TypeAdapter(type_) # type: ignore[attr-defined]
183 _type_adapter_cache[key] = adapter
184 return adapter
185
186
187 def parse_obj_as(type_: Type[T], object_: Any) -> T:
188 # convert_and_respect_annotation_metadata is required for TypedDict aliasing.
189 #
190 # For Pydantic models, whether we should pre-dealias depends on how the model encodes aliasing:
191 # - If the model uses real Pydantic aliases (pydantic.Field(alias=...)), then we must pass wire keys through
192 # unchanged so Pydantic can validate them.
193 # - If the model encodes aliasing only via FieldMetadata annotations, then we MUST pre-dealias because Pydantic
194 # will not recognize those aliases during validation.
195 if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
196 has_pydantic_aliases = False
197 if IS_PYDANTIC_V2:
198 for field_name, field_info in getattr(type_, "model_fields", {}).items(): # type: ignore[attr-defined]
199 alias = getattr(field_info, "alias", None)
200 if alias is not None and alias != field_name:
201 has_pydantic_aliases = True
202 break
203 else:
204 for field in getattr(type_, "__fields__", {}).values():
205 alias = getattr(field, "alias", None)
206 name = getattr(field, "name", None)
207 if alias is not None and name is not None and alias != name:
208 has_pydantic_aliases = True
209 break
210
211 dealiased_object = (
212 object_
213 if has_pydantic_aliases
214 else convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
215 )
216 else:
217 dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
218 if IS_PYDANTIC_V2:
219 adapter = _get_type_adapter(type_)
220 return adapter.validate_python(dealiased_object) # type: ignore[no-any-return]
221 return pydantic.parse_obj_as(type_, dealiased_object)
222
223
224 def to_jsonable_with_fallback(obj: Any, fallback_serializer: Callable[[Any], Any]) -> Any:
225 if IS_PYDANTIC_V2:
226 from pydantic_core import to_jsonable_python
227
228 return to_jsonable_python(obj, fallback=fallback_serializer)
229 return fallback_serializer(obj)
230
231
232 class UniversalBaseModel(pydantic.BaseModel):
233 if IS_PYDANTIC_V2:
234 model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( # type: ignore[typeddict-unknown-key]
235 # Allow fields beginning with `model_` to be used in the model
236 protected_namespaces=(),
237 )
238
239 @pydantic.model_validator(mode="before") # type: ignore[attr-defined]
240 @classmethod
241 def _coerce_field_names_to_aliases(cls, data: Any) -> Any:
242 """
243 Accept Python field names in input by rewriting them to their Pydantic aliases,
244 while avoiding silent collisions when a key could refer to multiple fields.
245 """
246 if not isinstance(data, Mapping):
247 return data
248
249 fields = getattr(cls, "model_fields", {}) # type: ignore[attr-defined]
250 name_to_alias: Dict[str, str] = {}
251 alias_to_name: Dict[str, str] = {}
252
253 for name, field_info in fields.items():
254 alias = getattr(field_info, "alias", None) or name
255 name_to_alias[name] = alias
256 if alias != name:
257 alias_to_name[alias] = name
258
259 # Detect ambiguous keys: a key that is an alias for one field and a name for another.
260 ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys()))
261 for key in ambiguous_keys:
262 if key in data and name_to_alias[key] not in data:
263 raise ValueError(
264 f"Ambiguous input key '{key}': it is both a field name and an alias. "
265 "Provide the explicit alias key to disambiguate."
266 )
267
268 original_keys = set(data.keys())
269 rewritten: Dict[str, Any] = dict(data)
270 for name, alias in name_to_alias.items():
271 if alias != name and name in original_keys and alias not in rewritten:
272 rewritten[alias] = rewritten.pop(name)
273
274 return rewritten
275
276 @pydantic.model_serializer(mode="plain", when_used="json") # type: ignore[attr-defined]
277 def serialize_model(self) -> Any: # type: ignore[name-defined]
278 serialized = self.dict() # type: ignore[attr-defined]
279 data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()}
280 return data
281
282 else:
283
284 class Config:
285 smart_union = True
286 json_encoders = {dt.datetime: serialize_datetime}
287
288 @pydantic.root_validator(pre=True)
289 def _coerce_field_names_to_aliases(cls, values: Any) -> Any:
290 """
291 Pydantic v1 equivalent of _coerce_field_names_to_aliases.
292 """
293 if not isinstance(values, Mapping):
294 return values
295
296 fields = getattr(cls, "__fields__", {})
297 name_to_alias: Dict[str, str] = {}
298 alias_to_name: Dict[str, str] = {}
299
300 for name, field in fields.items():
301 alias = getattr(field, "alias", None) or name
302 name_to_alias[name] = alias
303 if alias != name:
304 alias_to_name[alias] = name
305
306 ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys()))
307 for key in ambiguous_keys:
308 if key in values and name_to_alias[key] not in values:
309 raise ValueError(
310 f"Ambiguous input key '{key}': it is both a field name and an alias. "
311 "Provide the explicit alias key to disambiguate."
312 )
313
314 original_keys = set(values.keys())
315 rewritten: Dict[str, Any] = dict(values)
316 for name, alias in name_to_alias.items():
317 if alias != name and name in original_keys and alias not in rewritten:
318 rewritten[alias] = rewritten.pop(name)
319
320 return rewritten
321
322 @classmethod
323 def model_construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
324 dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
325 return cls.construct(_fields_set, **dealiased_object)
326
327 @classmethod
328 def construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
329 dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
330 if IS_PYDANTIC_V2:
331 return super().model_construct(_fields_set, **dealiased_object) # type: ignore[misc]
332 return super().construct(_fields_set, **dealiased_object)
333
334 def json(self, **kwargs: Any) -> str:
335 kwargs_with_defaults = {
336 "by_alias": True,
337 "exclude_unset": True,
338 **kwargs,
339 }
340 if IS_PYDANTIC_V2:
341 return super().model_dump_json(**kwargs_with_defaults) # type: ignore[misc]
342 return super().json(**kwargs_with_defaults)
343
344 def dict(self, **kwargs: Any) -> Dict[str, Any]:
345 """
346 Override the default dict method to `exclude_unset` by default. This function patches
347 `exclude_unset` to work include fields within non-None default values.
348 """
349 # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2
350 # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice.
351 #
352 # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models
353 # that we have less control over, and this is less intrusive than custom serializers for now.
354 if IS_PYDANTIC_V2:
355 kwargs_with_defaults_exclude_unset = {
356 **kwargs,
357 "by_alias": True,
358 "exclude_unset": True,
359 "exclude_none": False,
360 }
361 kwargs_with_defaults_exclude_none = {
362 **kwargs,
363 "by_alias": True,
364 "exclude_none": True,
365 "exclude_unset": False,
366 }
367 dict_dump = deep_union_pydantic_dicts(
368 super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore[misc]
369 super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore[misc]
370 )
371
372 else:
373 _fields_set = self.__fields_set__.copy()
374
375 fields = _get_model_fields(self.__class__)
376 for name, field in fields.items():
377 if name not in _fields_set:
378 default = _get_field_default(field)
379
380 # If the default values are non-null act like they've been set
381 # This effectively allows exclude_unset to work like exclude_none where
382 # the latter passes through intentionally set none values.
383 if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]):
384 _fields_set.add(name)
385
386 if default is not None:
387 self.__fields_set__.add(name)
388
389 kwargs_with_defaults_exclude_unset_include_fields = {
390 "by_alias": True,
391 "exclude_unset": True,
392 "include": _fields_set,
393 **kwargs,
394 }
395
396 dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields)
397
398 return cast(
399 Dict[str, Any],
400 convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write"),
401 )
402
403
404 def _union_list_of_pydantic_dicts(source: List[Any], destination: List[Any]) -> List[Any]:
405 converted_list: List[Any] = []
406 for i, item in enumerate(source):
407 destination_value = destination[i]
408 if isinstance(item, dict):
409 converted_list.append(deep_union_pydantic_dicts(item, destination_value))
410 elif isinstance(item, list):
411 converted_list.append(_union_list_of_pydantic_dicts(item, destination_value))
412 else:
413 converted_list.append(item)
414 return converted_list
415
416
417 def deep_union_pydantic_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
418 for key, value in source.items():
419 node = destination.setdefault(key, {})
420 if isinstance(value, dict):
421 deep_union_pydantic_dicts(value, node)
422 # Note: we do not do this same processing for sets given we do not have sets of models
423 # and given the sets are unordered, the processing of the set and matching objects would
424 # be non-trivial.
425 elif isinstance(value, list):
426 destination[key] = _union_list_of_pydantic_dicts(value, node)
427 else:
428 destination[key] = value
429
430 return destination
431
432
433 if IS_PYDANTIC_V2:
434
435 class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore[misc, name-defined, type-arg]
436 pass
437
438 UniversalRootModel: TypeAlias = V2RootModel # type: ignore[misc]
439 else:
440 UniversalRootModel: TypeAlias = UniversalBaseModel # type: ignore[misc, no-redef]
441
442
443 def encode_by_type(o: Any) -> Any:
444 encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple)
445 for type_, encoder in encoders_by_type.items():
446 encoders_by_class_tuples[encoder] += (type_,)
447
448 if type(o) in encoders_by_type:
449 return encoders_by_type[type(o)](o)
450 for encoder, classes_tuple in encoders_by_class_tuples.items():
451 if isinstance(o, classes_tuple):
452 return encoder(o)
453
454
455 def update_forward_refs(model: Type["Model"], **localns: Any) -> None:
456 if IS_PYDANTIC_V2:
457 model.model_rebuild(raise_errors=False) # type: ignore[attr-defined]
458 else:
459 model.update_forward_refs(**localns)
460
461
462 # Mirrors Pydantic's internal typing
463 AnyCallable = Callable[..., Any]
464
465
466 def universal_root_validator(
467 pre: bool = False,
468 ) -> Callable[[AnyCallable], AnyCallable]:
469 def decorator(func: AnyCallable) -> AnyCallable:
470 if IS_PYDANTIC_V2:
471 # In Pydantic v2, for RootModel we always use "before" mode
472 # The custom validators transform the input value before the model is created
473 return cast(AnyCallable, pydantic.model_validator(mode="before")(func)) # type: ignore[attr-defined]
474 return cast(AnyCallable, pydantic.root_validator(pre=pre)(func)) # type: ignore[call-overload]
475
476 return decorator
477
478
479 def universal_field_validator(field_name: str, pre: bool = False) -> Callable[[AnyCallable], AnyCallable]:
480 def decorator(func: AnyCallable) -> AnyCallable:
481 if IS_PYDANTIC_V2:
482 return cast(AnyCallable, pydantic.field_validator(field_name, mode="before" if pre else "after")(func)) # type: ignore[attr-defined]
483 return cast(AnyCallable, pydantic.validator(field_name, pre=pre)(func))
484
485 return decorator
486
487
488 PydanticField = Union[ModelField, _FieldInfo]
489
490
491 def _get_model_fields(model: Type["Model"]) -> Mapping[str, PydanticField]:
492 if IS_PYDANTIC_V2:
493 return cast(Mapping[str, PydanticField], model.model_fields) # type: ignore[attr-defined]
494 return cast(Mapping[str, PydanticField], model.__fields__)
495
496
497 def _get_field_default(field: PydanticField) -> Any:
498 try:
499 value = field.get_default() # type: ignore[union-attr]
500 except:
501 value = field.default
502 if IS_PYDANTIC_V2:
503 from pydantic_core import PydanticUndefined
504
505 if value == PydanticUndefined:
506 return None
507 return value
508 return value