Repository navigation
Expand file tree
/
Copy pathgen_schema_reference.py
More file actions
394 lines (347 loc) · 14.9 KB
/
Copy pathgen_schema_reference.py
File metadata and controls
394 lines (347 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""
Generates schema reference for dstack models.
"""
import importlib
import inspect
import json
import logging
import re
from enum import Enum
from fnmatch import fnmatch
from typing import Optional
import mkdocs_gen_files
import yaml
from pydantic import BaseModel, RootModel
from pydantic_core import PydanticUndefined
from typing_extensions import Annotated, Any, Dict, Literal, Type, Union, get_args, get_origin
from dstack._internal.core.models.resources import Range
from mkdocs.structure.files import File
FILE_PATTERN = "docs/reference/**.md"
logger = logging.getLogger("mkdocs.plugins.dstack.schema")
logger.info("Generating schema reference...")
def _unwrap_optional(annotation: Any) -> Any:
"""The non-`None` member of an `Optional[...]`, or the annotation unchanged."""
if get_origin(annotation) is Union:
args = [a for a in get_args(annotation) if a is not type(None)]
if len(args) == 1:
return args[0]
return annotation
def _linkable_model(annotation: Any) -> Optional[type]:
"""
The `BaseModel` subclass a field links to in the reference, if any.
pydantic v2 strips `Annotated` off `FieldInfo.annotation`, so the shape this used to unwrap by
hand (`Annotated[Optional[SSHParams], Field(...)]`) now arrives as plain `Optional[SSHParams]`.
Recursing over the annotation covers both, and also catches a bare model field, which the old
`get_args(...)[0]` approach silently missed.
"""
origin = get_origin(annotation)
# The container cases come first: `get_origin(Annotated[X, ...])` is `Annotated`, which is
# itself a class, so testing `inspect.isclass` first would stop before ever unwrapping it.
if origin in (Annotated, Union, list):
for arg in get_args(annotation):
if arg is type(None):
continue
found = _linkable_model(arg)
if found is not None:
return found
return None
type_ = origin if origin is not None else annotation
if inspect.isclass(type_) and issubclass(type_, BaseModel) and not issubclass(type_, Range):
return type_
return None
# Scalar JSON Schema types, mapped to how the docs spell them. Deliberately an allowlist rather
# than a full mapping: `array` and `object` would only restate what the annotation already renders
# more precisely (`list[str]` gaining a bare `list`, `dict` gaining `object`), and merging anything
# into a bracketed type corrupts it, since `_enrich_type_from_schema` splits the rendered type on
# `" | "` — which `list["no-capacity" | "interruption"]` contains.
_ENRICHABLE = {"string": "str", "integer": "int", "boolean": "bool", "number": "float"}
def _shorthand_primitives(model: Type) -> list:
"""
The primitive types a model accepts in place of its object form, e.g. `8` or `arm:8` for
`CPUSpec`. Taken from the model's own validation JSON Schema, which is the same declaration
that produces the published `configuration.json`.
"""
try:
schema = model.model_json_schema(mode="validation")
except Exception:
return []
found = {
_ENRICHABLE[entry["type"]]
for entry in schema.get("anyOf", [])
if entry.get("type") in _ENRICHABLE
}
return sorted(found, key=_type_sort_key)
def _type_sort_key(t: str) -> tuple:
"""Sort key for type parts: primitives first, then literals, then compound types."""
order = {"bool": 0, "int": 1, "float": 2, "str": 3}
if t in order:
return (0, order[t])
if t.startswith('"'):
return (1, t)
if t.startswith("list"):
return (2, t)
if t == "dict":
return (3, "")
if t == "object":
return (4, "")
return (5, t)
def get_friendly_type(annotation: Any) -> str:
"""Get a user-friendly type string for documentation.
Produces types like: ``int | str``, ``"vscode" | "cursor"``, ``list[object]``.
"""
# Unwrap Annotated
if get_origin(annotation) is Annotated:
return get_friendly_type(get_args(annotation)[0])
# Handle Union (including Optional)
if get_origin(annotation) is Union:
args = [a for a in get_args(annotation) if a is not type(None)]
if not args:
return ""
parts: list = []
for arg in args:
friendly = get_friendly_type(arg)
# Split compound types (e.g., "int | str" from Range) to deduplicate,
# but avoid splitting types that contain brackets (e.g., list[...])
if "[" not in friendly:
for part in friendly.split(" | "):
if part and part not in parts:
parts.append(part)
else:
if friendly and friendly not in parts:
parts.append(friendly)
parts.sort(key=_type_sort_key)
return " | ".join(parts)
# Handle Literal — list values
if get_origin(annotation) is Literal:
values = [v.value if isinstance(v, Enum) else v for v in get_args(annotation)]
return " | ".join(f'"{v}"' for v in values)
# Handle list
if get_origin(annotation) is list:
args = get_args(annotation)
if args:
inner = get_friendly_type(args[0])
return f"list[{inner}]"
return "list"
# Handle dict
if get_origin(annotation) is dict:
return "dict"
# Handle concrete classes
if inspect.isclass(annotation):
# Enum — list values
if issubclass(annotation, Enum):
values = [e.value for e in annotation]
return " | ".join(f'"{v}"' for v in values)
# Range — depends on inner type parameter
if issubclass(annotation, Range):
min_field = annotation.model_fields.get("min")
inner = _unwrap_optional(min_field.annotation) if min_field else None
if inspect.isclass(inner):
# Range[Memory] → str, Range[int] → int | str
if issubclass(inner, float):
return "str"
return "int | str"
# Memory (float subclass that parses "8GB" strings)
from dstack._internal.core.models.resources import Memory as _Memory
if issubclass(annotation, _Memory):
return "str"
# BaseModel subclass (not Range)
if issubclass(annotation, BaseModel) and not issubclass(annotation, Range):
# Root models — resolve from the root type
if issubclass(annotation, RootModel):
return get_friendly_type(annotation.model_fields["root"].annotation)
# Models that define their own core schema also accept a shorthand. Read which
# primitives from the model's own JSON Schema rather than assuming `int | str`:
# `CPUSpec` takes both, but `FilePathMapping` and `RepoSpec` take only a string.
if "__get_pydantic_core_schema__" in annotation.__dict__:
shorthand = _shorthand_primitives(annotation)
if shorthand:
return " | ".join([*shorthand, "object"])
return "object"
# ComputeCapability (tuple subclass that parses "7.5" strings)
if annotation.__name__ == "ComputeCapability":
return "float | str"
# Constrained and primitive types — check MRO
# bool must come before int (bool is a subclass of int)
if issubclass(annotation, bool):
return "bool"
if issubclass(annotation, int):
# Duration (int subclass that parses "5m" strings)
if annotation.__name__ == "Duration":
return "int | str"
return "int"
if issubclass(annotation, float):
return "float"
if issubclass(annotation, str):
return "str"
if issubclass(annotation, (list, tuple)):
return "list"
if issubclass(annotation, dict):
return "dict"
return annotation.__name__
return str(annotation)
def _enrich_type_from_schema(friendly_type: str, prop_schema: Dict[str, Any]) -> str:
"""Enrich the friendly type with extra accepted types from the JSON schema.
A field's annotation is its *post-validation* type, so it does not show what a before-validator
also accepts — a duration typed ``int`` takes ``"5m"``, ``false`` and ``"off"`` as well. Those
come from the type's ``json_schema_input_type``, i.e. the same declaration that produces the
published schema.
"""
any_of = prop_schema.get("anyOf")
if not any_of:
return friendly_type
schema_types = set()
for entry in any_of:
# A single accepted value (`Literal["off"]`) is more useful spelled out than as `str`.
# Duplicates are removed below, so an annotation that already shows it is unaffected.
literals = [entry["const"]] if "const" in entry else entry.get("enum", [])
if literals:
schema_types.update(f'"{v}"' for v in literals if isinstance(v, str))
continue
mapped = _ENRICHABLE.get(entry.get("type", ""))
if mapped:
schema_types.add(mapped)
# Add any schema types not already present in the friendly type
current_parts = [p.strip() for p in friendly_type.split(" | ")]
new_parts = schema_types - set(current_parts)
if not new_parts:
return friendly_type
all_parts = list(set(current_parts) | new_parts)
all_parts.sort(key=_type_sort_key)
return " | ".join(all_parts)
def generate_schema_reference(
model_path: str,
*,
overrides: Optional[dict[str, dict[str, Any]]] = None,
prefix: str = "",
) -> str:
module, model_name = model_path.rsplit(".", maxsplit=1)
cls = getattr(importlib.import_module(module), model_name)
assert issubclass(cls, BaseModel)
rows = []
if (
not overrides
or "show_root_heading" not in overrides
or overrides.get("show_root_heading") is True
):
rows.extend(
[
prefix + f"### {cls.__name__}",
"",
]
)
# The schema says what a field *accepts*, which is wider than its annotation wherever a
# before-validator coerces. `mode="validation"` is pydantic's default, but state it: the
# serialization schema carries the narrow type and would defeat the whole point.
try:
schema_props = cls.model_json_schema(mode="validation").get("properties", {})
except Exception:
schema_props = {}
for name, field in cls.model_fields.items():
default = field.default
default_repr: Optional[str]
if default is None or default is PydanticUndefined:
default_repr = None
elif isinstance(default, (list, tuple, dict)) and len(default) == 0:
default_repr = None
elif isinstance(default, Enum):
default_repr = str(default.value)
elif isinstance(default, BaseModel):
default_repr = str(default)
elif isinstance(default, str):
default_repr = default
else:
default_repr = json.dumps(default)
friendly_type = get_friendly_type(field.annotation)
friendly_type = _enrich_type_from_schema(friendly_type, schema_props.get(name, {}))
values = dict(
name=name,
description=field.description,
type=friendly_type,
default=default_repr,
required=field.is_required(),
)
# TODO: If the field doesn't have description (e.g. BaseConfiguration.type), we could fallback to docstring
if values["description"]:
if overrides and name in overrides:
values.update(overrides[name])
field_type = _linkable_model(field.annotation)
base_model = field_type is not None
_defaults = (
f"Defaults to `{values['default']}`."
if not base_model and values.get("default")
else ""
)
_must_be = (
f"Must be `{values['default']}`."
if not base_model and values.get("default")
else ""
)
if overrides and "item_id_prefix" in overrides:
item_id_prefix = overrides["item_id_prefix"]
else:
item_id_prefix = ""
if hasattr(field_type, "__name__") and overrides and "item_id_mapping" in overrides:
link_name = overrides["item_id_mapping"].get(values["name"]) or values["name"]
else:
link_name = values["name"]
item_header = (
f"`{values['name']}`"
if not base_model
else f"[`{values['name']}`](#{item_id_prefix}{link_name})"
)
item_required_marker = "(Required)" if values["required"] else "(Optional)"
item_type_display = f"`{values['type']}`" if values.get("type") else ""
item_description = (values["description"]).replace("\n", "<br>") + "."
item_default = _defaults if not values["required"] else _must_be
item_id = f"#{values['name']}" if not base_model else f"#_{values['name']}"
item_toc_label = f"data-toc-label='{values['name']}'"
item_css_cass = "class='reference-item'"
parts = [
f"###### {item_header}",
"-",
item_required_marker,
item_type_display,
item_description,
item_default,
"{",
item_id,
item_toc_label,
item_css_cass,
"}",
]
rows.append(prefix + " ".join(p for p in parts if p))
return "\n".join(rows)
def sub_schema_reference(match: re.Match) -> str:
logger.debug("Generating schema reference for `%s`", match.group(2))
options = yaml.safe_load("\n".join(row[4:] for row in match.group(3).split("\n")))
logger.debug("Options: %s", options)
return (
generate_schema_reference(match.group(2), **(options or {}), prefix=match.group(1))
+ "\n\n"
)
def expand_schema_references(text: str) -> str:
"""Expand #SCHEMA# placeholders in markdown text. Used by hooks when gen-files is not used."""
return re.sub(
r"( *)#SCHEMA#\s+(dstack\.[.a-z_0-9A-Z]+)\s*((?:\n {4}[^\n]+)*)\n",
sub_schema_reference,
text,
)
def process_file(file: File):
if not fnmatch(file.src_uri, FILE_PATTERN):
return
logger.debug("Looking for schema references in `%s`", file.src_uri)
with mkdocs_gen_files.open(file.src_uri, "r") as f:
text = f.read()
# Pattern:
# #SCHEMA# dstack.<module>.<model>
# overrides:
# name:
# required: true
text = expand_schema_references(text)
with mkdocs_gen_files.open(file.src_uri, "w") as f:
f.write(text)
def main():
# Processing sequentially since there is no speed up with concurrent processing
for file in mkdocs_gen_files.files:
process_file(file)
main()