| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import copy |
| 8 | import dataclasses |
| 9 | import datetime |
| 10 | import decimal |
| 11 | import enum |
| 12 | import ipaddress |
| 13 | import math |
| 14 | import re |
| 15 | import sys |
| 16 | import types |
| 17 | import typing |
| 18 | import uuid |
| 19 | from dataclasses import dataclass |
| 20 | from typing import Any, Dict, List, Literal, Optional, Tuple, Type, TypeVar, Union |
| 21 | |
| 22 | from .auxiliary import ( |
| 23 | Alias, |
| 24 | Annotated, |
| 25 | float32, |
| 26 | float64, |
| 27 | int16, |
| 28 | int32, |
| 29 | int64, |
| 30 | MaxLength, |
| 31 | Precision, |
| 32 | ) |
| 33 | from .core import JsonType, Schema |
| 34 | from .docstring import Docstring, DocstringParam |
| 35 | from .inspection import TypeLike |
| 36 | from .serialization import json_to_object, object_to_json |
| 37 | |
| 38 | T = TypeVar("T") |
| 39 | |
| 40 | |
| 41 | @dataclass |
| 42 | class JsonSchemaNode: |
| 43 | title: Optional[str] |
| 44 | description: Optional[str] |
| 45 | |
| 46 | |
| 47 | @dataclass |
| 48 | class JsonSchemaType(JsonSchemaNode): |
| 49 | type: str |
| 50 | format: Optional[str] |
| 51 | |
| 52 | |
| 53 | @dataclass |
| 54 | class JsonSchemaBoolean(JsonSchemaType): |
| 55 | type: Literal["boolean"] |
| 56 | const: Optional[bool] |
| 57 | default: Optional[bool] |
| 58 | examples: Optional[List[bool]] |
| 59 | |
| 60 | |
| 61 | @dataclass |
| 62 | class JsonSchemaInteger(JsonSchemaType): |
| 63 | type: Literal["integer"] |
| 64 | const: Optional[int] |
| 65 | default: Optional[int] |
| 66 | examples: Optional[List[int]] |
| 67 | enum: Optional[List[int]] |
| 68 | minimum: Optional[int] |
| 69 | maximum: Optional[int] |
| 70 | |
| 71 | |
| 72 | @dataclass |
| 73 | class JsonSchemaNumber(JsonSchemaType): |
| 74 | type: Literal["number"] |
| 75 | const: Optional[float] |
| 76 | default: Optional[float] |
| 77 | examples: Optional[List[float]] |
| 78 | minimum: Optional[float] |
| 79 | maximum: Optional[float] |
| 80 | exclusiveMinimum: Optional[float] |
| 81 | exclusiveMaximum: Optional[float] |
| 82 | multipleOf: Optional[float] |
| 83 | |
| 84 | |
| 85 | @dataclass |
| 86 | class JsonSchemaString(JsonSchemaType): |
| 87 | type: Literal["string"] |
| 88 | const: Optional[str] |
| 89 | default: Optional[str] |
| 90 | examples: Optional[List[str]] |
| 91 | enum: Optional[List[str]] |
| 92 | minLength: Optional[int] |
| 93 | maxLength: Optional[int] |
| 94 | |
| 95 | |
| 96 | @dataclass |
| 97 | class JsonSchemaArray(JsonSchemaType): |
| 98 | type: Literal["array"] |
| 99 | items: "JsonSchemaAny" |
| 100 | |
| 101 | |
| 102 | @dataclass |
| 103 | class JsonSchemaObject(JsonSchemaType): |
| 104 | type: Literal["object"] |
| 105 | properties: Optional[Dict[str, "JsonSchemaAny"]] |
| 106 | additionalProperties: Optional[bool] |
| 107 | required: Optional[List[str]] |
| 108 | |
| 109 | |
| 110 | @dataclass |
| 111 | class JsonSchemaRef(JsonSchemaNode): |
| 112 | ref: Annotated[str, Alias("$ref")] |
| 113 | |
| 114 | |
| 115 | @dataclass |
| 116 | class JsonSchemaAllOf(JsonSchemaNode): |
| 117 | allOf: List["JsonSchemaAny"] |
| 118 | |
| 119 | |
| 120 | @dataclass |
| 121 | class JsonSchemaAnyOf(JsonSchemaNode): |
| 122 | anyOf: List["JsonSchemaAny"] |
| 123 | |
| 124 | |
| 125 | @dataclass |
| 126 | class JsonSchemaOneOf(JsonSchemaNode): |
| 127 | oneOf: List["JsonSchemaAny"] |
| 128 | |
| 129 | |
| 130 | JsonSchemaAny = Union[ |
| 131 | JsonSchemaRef, |
| 132 | JsonSchemaBoolean, |
| 133 | JsonSchemaInteger, |
| 134 | JsonSchemaNumber, |
| 135 | JsonSchemaString, |
| 136 | JsonSchemaArray, |
| 137 | JsonSchemaObject, |
| 138 | JsonSchemaOneOf, |
| 139 | ] |
| 140 | |
| 141 | |
| 142 | @dataclass |
| 143 | class JsonSchemaTopLevelObject(JsonSchemaObject): |
| 144 | schema: Annotated[str, Alias("$schema")] |
| 145 | definitions: Optional[Dict[str, JsonSchemaAny]] |
| 146 | |
| 147 | |
| 148 | def integer_range_to_type(min_value: float, max_value: float) -> type: |
| 149 | if min_value >= -(2**15) and max_value < 2**15: |
| 150 | return int16 |
| 151 | elif min_value >= -(2**31) and max_value < 2**31: |
| 152 | return int32 |
| 153 | else: |
| 154 | return int64 |
| 155 | |
| 156 | |
| 157 | def enum_safe_name(name: str) -> str: |
| 158 | name = re.sub(r"\W", "_", name) |
| 159 | is_dunder = name.startswith("__") |
| 160 | is_sunder = name.startswith("_") and name.endswith("_") |
| 161 | if is_dunder or is_sunder: # provide an alternative for dunder and sunder names |
| 162 | name = f"v{name}" |
| 163 | return name |
| 164 | |
| 165 | |
| 166 | def enum_values_to_type( |
| 167 | module: types.ModuleType, |
| 168 | name: str, |
| 169 | values: Dict[str, Any], |
| 170 | title: Optional[str] = None, |
| 171 | description: Optional[str] = None, |
| 172 | ) -> Type[enum.Enum]: |
| 173 | enum_class: Type[enum.Enum] = enum.Enum(name, values) # type: ignore |
| 174 | |
| 175 | # assign the newly created type to the same module where the defining class is |
| 176 | enum_class.__module__ = module.__name__ |
| 177 | enum_class.__doc__ = str( |
| 178 | Docstring(short_description=title, long_description=description) |
| 179 | ) |
| 180 | setattr(module, name, enum_class) |
| 181 | |
| 182 | return enum.unique(enum_class) |
| 183 | |
| 184 | |
| 185 | def schema_to_type( |
| 186 | schema: Schema, *, module: types.ModuleType, class_name: str |
| 187 | ) -> TypeLike: |
| 188 | """ |
| 189 | Creates a Python type from a JSON schema. |
| 190 | |
| 191 | :param schema: The JSON schema that the types would correspond to. |
| 192 | :param module: The module in which to create the new types. |
| 193 | :param class_name: The name assigned to the top-level class. |
| 194 | """ |
| 195 | |
| 196 | top_node = typing.cast( |
| 197 | JsonSchemaTopLevelObject, json_to_object(JsonSchemaTopLevelObject, schema) |
| 198 | ) |
| 199 | if top_node.definitions is not None: |
| 200 | for type_name, type_node in top_node.definitions.items(): |
| 201 | type_def = node_to_typedef(module, type_name, type_node) |
| 202 | if type_def.default is not dataclasses.MISSING: |
| 203 | raise TypeError("disallowed: `default` for top-level type definitions") |
| 204 | |
| 205 | setattr(type_def.type, "__module__", module.__name__) |
| 206 | setattr(module, type_name, type_def.type) |
| 207 | |
| 208 | return node_to_typedef(module, class_name, top_node).type |
| 209 | |
| 210 | |
| 211 | @dataclass |
| 212 | class TypeDef: |
| 213 | type: TypeLike |
| 214 | default: Any = dataclasses.MISSING |
| 215 | |
| 216 | |
| 217 | def json_to_value(target_type: TypeLike, data: JsonType) -> Any: |
| 218 | if data is not None: |
| 219 | return json_to_object(target_type, data) |
| 220 | else: |
| 221 | return dataclasses.MISSING |
| 222 | |
| 223 | |
| 224 | def node_to_typedef( |
| 225 | module: types.ModuleType, context: str, node: JsonSchemaNode |
| 226 | ) -> TypeDef: |
| 227 | if isinstance(node, JsonSchemaRef): |
| 228 | match_obj = re.match(r"^#/definitions/(\w+)$", node.ref) |
| 229 | if not match_obj: |
| 230 | raise ValueError(f"invalid reference: {node.ref}") |
| 231 | |
| 232 | type_name = match_obj.group(1) |
| 233 | return TypeDef(getattr(module, type_name), dataclasses.MISSING) |
| 234 | |
| 235 | elif isinstance(node, JsonSchemaBoolean): |
| 236 | if node.const is not None: |
| 237 | return TypeDef(Literal[node.const], dataclasses.MISSING) |
| 238 | |
| 239 | default = json_to_value(bool, node.default) |
| 240 | return TypeDef(bool, default) |
| 241 | |
| 242 | elif isinstance(node, JsonSchemaInteger): |
| 243 | if node.const is not None: |
| 244 | return TypeDef(Literal[node.const], dataclasses.MISSING) |
| 245 | |
| 246 | integer_type: TypeLike |
| 247 | if node.format == "int16": |
| 248 | integer_type = int16 |
| 249 | elif node.format == "int32": |
| 250 | integer_type = int32 |
| 251 | elif node.format == "int64": |
| 252 | integer_type = int64 |
| 253 | else: |
| 254 | if node.enum is not None: |
| 255 | integer_type = integer_range_to_type(min(node.enum), max(node.enum)) |
| 256 | elif node.minimum is not None and node.maximum is not None: |
| 257 | integer_type = integer_range_to_type(node.minimum, node.maximum) |
| 258 | else: |
| 259 | integer_type = int |
| 260 | |
| 261 | default = json_to_value(integer_type, node.default) |
| 262 | return TypeDef(integer_type, default) |
| 263 | |
| 264 | elif isinstance(node, JsonSchemaNumber): |
| 265 | if node.const is not None: |
| 266 | return TypeDef(Literal[node.const], dataclasses.MISSING) |
| 267 | |
| 268 | number_type: TypeLike |
| 269 | if node.format == "float32": |
| 270 | number_type = float32 |
| 271 | elif node.format == "float64": |
| 272 | number_type = float64 |
| 273 | else: |
| 274 | if ( |
| 275 | node.exclusiveMinimum is not None |
| 276 | and node.exclusiveMaximum is not None |
| 277 | and node.exclusiveMinimum == -node.exclusiveMaximum |
| 278 | ): |
| 279 | integer_digits = round(math.log10(node.exclusiveMaximum)) |
| 280 | else: |
| 281 | integer_digits = None |
| 282 | |
| 283 | if node.multipleOf is not None: |
| 284 | decimal_digits = -round(math.log10(node.multipleOf)) |
| 285 | else: |
| 286 | decimal_digits = None |
| 287 | |
| 288 | if integer_digits is not None and decimal_digits is not None: |
| 289 | number_type = Annotated[ |
| 290 | decimal.Decimal, |
| 291 | Precision(integer_digits + decimal_digits, decimal_digits), |
| 292 | ] |
| 293 | else: |
| 294 | number_type = float |
| 295 | |
| 296 | default = json_to_value(number_type, node.default) |
| 297 | return TypeDef(number_type, default) |
| 298 | |
| 299 | elif isinstance(node, JsonSchemaString): |
| 300 | if node.const is not None: |
| 301 | return TypeDef(Literal[node.const], dataclasses.MISSING) |
| 302 | |
| 303 | string_type: TypeLike |
| 304 | if node.format == "date-time": |
| 305 | string_type = datetime.datetime |
| 306 | elif node.format == "uuid": |
| 307 | string_type = uuid.UUID |
| 308 | elif node.format == "ipv4": |
| 309 | string_type = ipaddress.IPv4Address |
| 310 | elif node.format == "ipv6": |
| 311 | string_type = ipaddress.IPv6Address |
| 312 | |
| 313 | elif node.enum is not None: |
| 314 | string_type = enum_values_to_type( |
| 315 | module, |
| 316 | context, |
| 317 | {enum_safe_name(e): e for e in node.enum}, |
| 318 | title=node.title, |
| 319 | description=node.description, |
| 320 | ) |
| 321 | |
| 322 | elif node.maxLength is not None: |
| 323 | string_type = Annotated[str, MaxLength(node.maxLength)] |
| 324 | else: |
| 325 | string_type = str |
| 326 | |
| 327 | default = json_to_value(string_type, node.default) |
| 328 | return TypeDef(string_type, default) |
| 329 | |
| 330 | elif isinstance(node, JsonSchemaArray): |
| 331 | type_def = node_to_typedef(module, context, node.items) |
| 332 | if type_def.default is not dataclasses.MISSING: |
| 333 | raise TypeError("disallowed: `default` for array element type") |
| 334 | list_type = List[(type_def.type,)] # type: ignore |
| 335 | return TypeDef(list_type, dataclasses.MISSING) |
| 336 | |
| 337 | elif isinstance(node, JsonSchemaObject): |
| 338 | if node.properties is None: |
| 339 | return TypeDef(JsonType, dataclasses.MISSING) |
| 340 | |
| 341 | if node.additionalProperties is None or node.additionalProperties is not False: |
| 342 | raise TypeError("expected: `additionalProperties` equals `false`") |
| 343 | |
| 344 | required = node.required if node.required is not None else [] |
| 345 | |
| 346 | class_name = context |
| 347 | |
| 348 | fields: List[Tuple[str, Any, dataclasses.Field]] = [] |
| 349 | params: Dict[str, DocstringParam] = {} |
| 350 | for prop_name, prop_node in node.properties.items(): |
| 351 | type_def = node_to_typedef(module, f"{class_name}__{prop_name}", prop_node) |
| 352 | if prop_name in required: |
| 353 | prop_type = type_def.type |
| 354 | else: |
| 355 | prop_type = Union[(None, type_def.type)] |
| 356 | fields.append( |
| 357 | (prop_name, prop_type, dataclasses.field(default=type_def.default)) |
| 358 | ) |
| 359 | prop_desc = prop_node.title or prop_node.description |
| 360 | if prop_desc is not None: |
| 361 | params[prop_name] = DocstringParam(prop_name, prop_desc) |
| 362 | |
| 363 | fields.sort(key=lambda t: t[2].default is not dataclasses.MISSING) |
| 364 | if sys.version_info >= (3, 12): |
| 365 | class_type = dataclasses.make_dataclass( |
| 366 | class_name, fields, module=module.__name__ |
| 367 | ) |
| 368 | else: |
| 369 | class_type = dataclasses.make_dataclass( |
| 370 | class_name, fields, namespace={"__module__": module.__name__} |
| 371 | ) |
| 372 | class_type.__doc__ = str( |
| 373 | Docstring( |
| 374 | short_description=node.title, |
| 375 | long_description=node.description, |
| 376 | params=params, |
| 377 | ) |
| 378 | ) |
| 379 | setattr(module, class_name, class_type) |
| 380 | return TypeDef(class_type, dataclasses.MISSING) |
| 381 | |
| 382 | elif isinstance(node, JsonSchemaOneOf): |
| 383 | union_defs = tuple(node_to_typedef(module, context, n) for n in node.oneOf) |
| 384 | if any(d.default is not dataclasses.MISSING for d in union_defs): |
| 385 | raise TypeError("disallowed: `default` for union member type") |
| 386 | union_types = tuple(d.type for d in union_defs) |
| 387 | return TypeDef(Union[union_types], dataclasses.MISSING) |
| 388 | |
| 389 | raise NotImplementedError() |
| 390 | |
| 391 | |
| 392 | @dataclass |
| 393 | class SchemaFlatteningOptions: |
| 394 | qualified_names: bool = False |
| 395 | recursive: bool = False |
| 396 | |
| 397 | |
| 398 | def flatten_schema( |
| 399 | schema: Schema, *, options: Optional[SchemaFlatteningOptions] = None |
| 400 | ) -> Schema: |
| 401 | top_node = typing.cast( |
| 402 | JsonSchemaTopLevelObject, json_to_object(JsonSchemaTopLevelObject, schema) |
| 403 | ) |
| 404 | flattener = SchemaFlattener(options) |
| 405 | obj = flattener.flatten(top_node) |
| 406 | return typing.cast(Schema, object_to_json(obj)) |
| 407 | |
| 408 | |
| 409 | class SchemaFlattener: |
| 410 | options: SchemaFlatteningOptions |
| 411 | |
| 412 | def __init__(self, options: Optional[SchemaFlatteningOptions] = None) -> None: |
| 413 | self.options = options or SchemaFlatteningOptions() |
| 414 | |
| 415 | def flatten(self, source_node: JsonSchemaObject) -> JsonSchemaObject: |
| 416 | if source_node.type != "object": |
| 417 | return source_node |
| 418 | |
| 419 | source_props = source_node.properties or {} |
| 420 | target_props: Dict[str, JsonSchemaAny] = {} |
| 421 | |
| 422 | source_reqs = source_node.required or [] |
| 423 | target_reqs: List[str] = [] |
| 424 | |
| 425 | for name, prop in source_props.items(): |
| 426 | if not isinstance(prop, JsonSchemaObject): |
| 427 | target_props[name] = prop |
| 428 | if name in source_reqs: |
| 429 | target_reqs.append(name) |
| 430 | continue |
| 431 | |
| 432 | if self.options.recursive: |
| 433 | obj = self.flatten(prop) |
| 434 | else: |
| 435 | obj = prop |
| 436 | if obj.properties is not None: |
| 437 | if self.options.qualified_names: |
| 438 | target_props.update( |
| 439 | (f"{name}.{n}", p) for n, p in obj.properties.items() |
| 440 | ) |
| 441 | else: |
| 442 | target_props.update(obj.properties.items()) |
| 443 | if obj.required is not None: |
| 444 | if self.options.qualified_names: |
| 445 | target_reqs.extend(f"{name}.{n}" for n in obj.required) |
| 446 | else: |
| 447 | target_reqs.extend(obj.required) |
| 448 | |
| 449 | target_node = copy.copy(source_node) |
| 450 | target_node.properties = target_props or None |
| 451 | target_node.additionalProperties = False |
| 452 | target_node.required = target_reqs or None |
| 453 | return target_node |