533 lines
22 KiB
Python
533 lines
22 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from datetime import date, datetime
|
|
from decimal import Decimal, InvalidOperation
|
|
from pathlib import Path
|
|
from typing import Any, Mapping, Sequence
|
|
from uuid import UUID
|
|
|
|
from .models import AttributeDefinition, ModuleConfigEntry, ModuleContentMapping, ModuleManifest
|
|
|
|
|
|
class SeederError(Exception):
|
|
pass
|
|
|
|
|
|
class DefinitionValidationError(SeederError):
|
|
pass
|
|
|
|
|
|
class ContentValidationError(SeederError):
|
|
pass
|
|
|
|
|
|
class ModuleValidationError(SeederError):
|
|
pass
|
|
|
|
|
|
class PresentationValidationError(SeederError):
|
|
pass
|
|
|
|
|
|
class DefinitionNotFoundError(ContentValidationError):
|
|
pass
|
|
|
|
|
|
class DefinitionConflictError(SeederError):
|
|
pass
|
|
|
|
|
|
class UnknownAttributeError(ContentValidationError):
|
|
pass
|
|
|
|
|
|
class InvalidAttributeValueError(ContentValidationError):
|
|
pass
|
|
|
|
|
|
SUPPORTED_DATA_TYPES = {"text", "rich_text", "number", "boolean", "date", "json", "media"}
|
|
SUPPORTED_DEFINITION_KINDS = {"scalar", "object"}
|
|
SUPPORTED_MODULE_STATUSES = {"draft", "active", "inactive", "archived"}
|
|
SUPPORTED_PRESENTATION_MODES = {"collection", "single"}
|
|
SUPPORTED_EMPTY_BEHAVIORS = {"hide", "show"}
|
|
SUPPORTED_VISIBILITIES = {"show", "hide"}
|
|
RENDERER_CODE_RE = re.compile(r"^[a-z][a-z0-9_]{1,127}$")
|
|
CLIENT_TYPE_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
|
|
|
|
|
|
def load_json(path: Path) -> Any:
|
|
try:
|
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
except OSError as exc:
|
|
raise SeederError(f"Unable to read JSON file {path}: {exc}") from exc
|
|
except json.JSONDecodeError as exc:
|
|
raise SeederError(f"Invalid JSON in {path}: {exc}") from exc
|
|
|
|
|
|
def slugify(value: str) -> str:
|
|
value = re.sub(r"[^a-z0-9]+", "-", value.strip().lower())
|
|
return value.strip("-")
|
|
|
|
|
|
def build_source_key(*, template_code: str, source_code: str) -> str:
|
|
"""Build the canonical persisted content identity.
|
|
|
|
``source_code`` is the stable author-facing identity. ``source_key`` is a
|
|
derived database/runtime identity and must never be manually authored.
|
|
Both content rows and content references must call this function.
|
|
"""
|
|
normalized_template = require_non_empty_string(
|
|
template_code, "template_code"
|
|
).lower()
|
|
normalized_source_code = require_non_empty_string(
|
|
source_code, "source_code"
|
|
)
|
|
stable_component = slugify(normalized_source_code)
|
|
if not stable_component:
|
|
raise SeederError(
|
|
"source_code becomes empty after canonicalization"
|
|
)
|
|
return f"{normalized_template}:{stable_component}"
|
|
|
|
|
|
def require_non_empty_string(value: Any, field_name: str) -> str:
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise SeederError(f"{field_name} must be a non-empty string")
|
|
return value.strip()
|
|
|
|
|
|
def bool_field(raw: Mapping[str, Any], preferred: str, legacy: str, default: bool) -> bool:
|
|
if preferred in raw:
|
|
return bool(raw[preferred])
|
|
if legacy in raw:
|
|
return bool(raw[legacy])
|
|
return default
|
|
|
|
|
|
def validate_definition_document(document: Mapping[str, Any]) -> None:
|
|
for field in ("name", "code", "attribute_prefix_code", "attribute_prefix_name", "attribute_defs"):
|
|
if field not in document:
|
|
raise DefinitionValidationError(f"Missing required field: {field}")
|
|
|
|
require_non_empty_string(document["name"], "name")
|
|
require_non_empty_string(document["code"], "code")
|
|
require_non_empty_string(document["attribute_prefix_code"], "attribute_prefix_code")
|
|
require_non_empty_string(document["attribute_prefix_name"], "attribute_prefix_name")
|
|
|
|
# Template-level search participation is an explicit contract.
|
|
# There are intentionally no compatibility defaults.
|
|
for flag in ("is_searchable", "is_filterable"):
|
|
if flag not in document:
|
|
raise DefinitionValidationError(f"Missing required field: {flag}")
|
|
if not isinstance(document[flag], bool):
|
|
raise DefinitionValidationError(f"{flag} must be a boolean")
|
|
|
|
defs = document["attribute_defs"]
|
|
if not isinstance(defs, list) or not defs:
|
|
raise DefinitionValidationError("attribute_defs must be a non-empty array")
|
|
|
|
_validate_definition_level(defs, path="attribute_defs")
|
|
validate_presentation_contracts(document)
|
|
|
|
|
|
def _validate_definition_level(definitions: Sequence[Any], *, path: str) -> None:
|
|
seen_codes: set[str] = set()
|
|
|
|
for index, raw in enumerate(definitions):
|
|
item_path = f"{path}[{index}]"
|
|
if not isinstance(raw, Mapping):
|
|
raise DefinitionValidationError(f"{item_path} must be an object")
|
|
|
|
for field in ("name", "code"):
|
|
if field not in raw:
|
|
raise DefinitionValidationError(f"{item_path} is missing {field!r}")
|
|
|
|
code = require_non_empty_string(raw["code"], f"{item_path}.code")
|
|
require_non_empty_string(raw["name"], f"{item_path}.name")
|
|
|
|
if "." in code:
|
|
raise DefinitionValidationError(f"{item_path}.code cannot contain '.'")
|
|
if code in seen_codes:
|
|
raise DefinitionValidationError(f"Duplicate sibling attribute code {code!r} at {path}")
|
|
seen_codes.add(code)
|
|
|
|
definition_kind = str(raw.get("definition_kind", "scalar")).strip()
|
|
if raw.get("data_type") == "object" and "definition_kind" not in raw:
|
|
definition_kind = "object"
|
|
|
|
if definition_kind not in SUPPORTED_DEFINITION_KINDS:
|
|
raise DefinitionValidationError(f"Unsupported definition_kind {definition_kind!r} for {item_path}")
|
|
|
|
if definition_kind == "scalar":
|
|
if "data_type" not in raw:
|
|
raise DefinitionValidationError(f"{item_path}.data_type is required for scalar definitions")
|
|
data_type = require_non_empty_string(raw["data_type"], f"{item_path}.data_type")
|
|
if data_type not in SUPPORTED_DATA_TYPES:
|
|
raise DefinitionValidationError(f"Unsupported data_type {data_type!r} for {item_path}")
|
|
if raw.get("children"):
|
|
raise DefinitionValidationError(f"Scalar definition {item_path} cannot contain children")
|
|
else:
|
|
if raw.get("data_type") not in (None, "", "object"):
|
|
raise DefinitionValidationError(f"Object definition {item_path} must not define scalar data_type")
|
|
children = raw.get("children")
|
|
if not isinstance(children, list) or not children:
|
|
raise DefinitionValidationError(f"Object definition {item_path} requires non-empty children")
|
|
if raw.get("allowed_values") is not None:
|
|
raise DefinitionValidationError(f"Object definition {item_path} cannot define allowed_values")
|
|
_validate_definition_level(children, path=f"{item_path}.children")
|
|
|
|
allowed_values = raw.get("allowed_values")
|
|
if allowed_values is not None and not isinstance(allowed_values, list):
|
|
raise DefinitionValidationError(f"allowed_values for {code!r} must be an array")
|
|
|
|
is_multivalue = bool_field(raw, "is_multivalue", "multivalue", False)
|
|
if is_multivalue and "default" in raw and definition_kind == "scalar":
|
|
default_value = raw.get("default")
|
|
if default_value is not None and not isinstance(default_value, list):
|
|
raise DefinitionValidationError(f"Default for multivalue attribute {code!r} must be an array")
|
|
|
|
|
|
def _validate_renderer_code(value: Any, field_name: str) -> str:
|
|
renderer = require_non_empty_string(value, field_name)
|
|
if not RENDERER_CODE_RE.fullmatch(renderer):
|
|
raise PresentationValidationError(
|
|
f"{field_name}={renderer!r} is not a valid semantic renderer code"
|
|
)
|
|
return renderer
|
|
|
|
|
|
def validate_presentation_contracts(document: Mapping[str, Any]) -> tuple[dict[str, Any], ...]:
|
|
"""Validate and normalize optional top-level presentation_contracts.
|
|
|
|
Presentation contracts are deliberately NOT read from document.metadata.
|
|
A template may omit presentation_contracts while legacy templates are being
|
|
migrated; when supplied, every contract is validated strictly.
|
|
"""
|
|
raw_contracts = document.get("presentation_contracts")
|
|
if raw_contracts is None:
|
|
return ()
|
|
if not isinstance(raw_contracts, list):
|
|
raise PresentationValidationError("presentation_contracts must be an array")
|
|
|
|
normalized: list[dict[str, Any]] = []
|
|
seen_versions: set[tuple[str, int]] = set()
|
|
active_clients: set[str] = set()
|
|
|
|
for index, raw in enumerate(raw_contracts):
|
|
path = f"presentation_contracts[{index}]"
|
|
if not isinstance(raw, Mapping):
|
|
raise PresentationValidationError(f"{path} must be an object")
|
|
|
|
client_type = require_non_empty_string(raw.get("client_type", "mobile"), f"{path}.client_type").lower()
|
|
if not CLIENT_TYPE_RE.fullmatch(client_type):
|
|
raise PresentationValidationError(f"{path}.client_type={client_type!r} is invalid")
|
|
|
|
mode = require_non_empty_string(raw.get("mode"), f"{path}.mode").lower()
|
|
if mode not in SUPPORTED_PRESENTATION_MODES:
|
|
raise PresentationValidationError(
|
|
f"{path}.mode must be one of {sorted(SUPPORTED_PRESENTATION_MODES)}"
|
|
)
|
|
|
|
version_no = raw.get("version_no", 1)
|
|
if isinstance(version_no, bool) or not isinstance(version_no, int) or version_no <= 0:
|
|
raise PresentationValidationError(f"{path}.version_no must be a positive integer")
|
|
|
|
is_active = raw.get("is_active", True)
|
|
if not isinstance(is_active, bool):
|
|
raise PresentationValidationError(f"{path}.is_active must be boolean")
|
|
|
|
renderers = raw.get("renderers")
|
|
if not isinstance(renderers, Mapping):
|
|
raise PresentationValidationError(f"{path}.renderers must be an object")
|
|
|
|
detail = _validate_renderer_code(renderers.get("detail"), f"{path}.renderers.detail")
|
|
collection = None
|
|
collection_item = None
|
|
if mode == "collection":
|
|
collection = _validate_renderer_code(renderers.get("collection"), f"{path}.renderers.collection")
|
|
collection_item = _validate_renderer_code(renderers.get("collection_item"), f"{path}.renderers.collection_item")
|
|
else:
|
|
if renderers.get("collection") is not None or renderers.get("collection_item") is not None:
|
|
raise PresentationValidationError(
|
|
f"{path}: single mode must not define collection or collection_item renderers"
|
|
)
|
|
|
|
metadata = raw.get("metadata") or {}
|
|
if not isinstance(metadata, Mapping):
|
|
raise PresentationValidationError(f"{path}.metadata must be an object")
|
|
|
|
raw_attributes = raw.get("attributes") or []
|
|
if not isinstance(raw_attributes, list):
|
|
raise PresentationValidationError(f"{path}.attributes must be an array")
|
|
|
|
attributes: list[dict[str, Any]] = []
|
|
seen_attribute_keys: set[str] = set()
|
|
for attribute_index, attribute_raw in enumerate(raw_attributes):
|
|
attribute_path = f"{path}.attributes[{attribute_index}]"
|
|
if not isinstance(attribute_raw, Mapping):
|
|
raise PresentationValidationError(f"{attribute_path} must be an object")
|
|
|
|
attribute_key = require_non_empty_string(
|
|
attribute_raw.get("attribute_key"),
|
|
f"{attribute_path}.attribute_key",
|
|
)
|
|
if attribute_key in seen_attribute_keys:
|
|
raise PresentationValidationError(
|
|
f"Duplicate attribute_key {attribute_key!r} in {path}.attributes"
|
|
)
|
|
seen_attribute_keys.add(attribute_key)
|
|
|
|
visibility = require_non_empty_string(
|
|
attribute_raw.get("visibility", "show"),
|
|
f"{attribute_path}.visibility",
|
|
).lower()
|
|
if visibility not in SUPPORTED_VISIBILITIES:
|
|
raise PresentationValidationError(
|
|
f"{attribute_path}.visibility must be one of "
|
|
f"{sorted(SUPPORTED_VISIBILITIES)}"
|
|
)
|
|
|
|
empty_behavior = require_non_empty_string(
|
|
attribute_raw.get("empty_behavior", "hide"),
|
|
f"{attribute_path}.empty_behavior",
|
|
).lower()
|
|
if empty_behavior not in SUPPORTED_EMPTY_BEHAVIORS:
|
|
raise PresentationValidationError(
|
|
f"{attribute_path}.empty_behavior must be one of "
|
|
f"{sorted(SUPPORTED_EMPTY_BEHAVIORS)}"
|
|
)
|
|
|
|
empty_text_raw = attribute_raw.get("empty_text")
|
|
empty_text: str | None = None
|
|
if empty_text_raw is not None:
|
|
if not isinstance(empty_text_raw, str) or not empty_text_raw.strip():
|
|
raise PresentationValidationError(
|
|
f"{attribute_path}.empty_text must be null or a non-empty string"
|
|
)
|
|
empty_text = empty_text_raw.strip()
|
|
|
|
if empty_behavior == "hide" and empty_text is not None:
|
|
raise PresentationValidationError(
|
|
f"{attribute_path}.empty_text is only valid when empty_behavior='show'"
|
|
)
|
|
|
|
display_order_raw = attribute_raw.get("display_order")
|
|
display_order: int | None = None
|
|
if display_order_raw is not None:
|
|
if (
|
|
isinstance(display_order_raw, bool)
|
|
or not isinstance(display_order_raw, int)
|
|
or display_order_raw < 0
|
|
):
|
|
raise PresentationValidationError(
|
|
f"{attribute_path}.display_order must be null or a non-negative integer"
|
|
)
|
|
display_order = display_order_raw
|
|
|
|
attribute_metadata = attribute_raw.get("metadata") or {}
|
|
if not isinstance(attribute_metadata, Mapping):
|
|
raise PresentationValidationError(f"{attribute_path}.metadata must be an object")
|
|
|
|
attributes.append({
|
|
"attribute_key": attribute_key,
|
|
"visibility": visibility,
|
|
"empty_behavior": empty_behavior,
|
|
"empty_text": empty_text,
|
|
"display_order": display_order,
|
|
"metadata": dict(attribute_metadata),
|
|
})
|
|
|
|
key = (client_type, version_no)
|
|
if key in seen_versions:
|
|
raise PresentationValidationError(
|
|
f"Duplicate presentation contract for client_type={client_type!r}, version_no={version_no}"
|
|
)
|
|
seen_versions.add(key)
|
|
|
|
if is_active:
|
|
if client_type in active_clients:
|
|
raise PresentationValidationError(
|
|
f"Only one active presentation contract may be declared for client_type={client_type!r}"
|
|
)
|
|
active_clients.add(client_type)
|
|
|
|
normalized.append({
|
|
"client_type": client_type,
|
|
"mode": mode,
|
|
"version_no": version_no,
|
|
"is_active": is_active,
|
|
"renderers": {
|
|
"collection": collection,
|
|
"collection_item": collection_item,
|
|
"detail": detail,
|
|
},
|
|
"attributes": attributes,
|
|
"metadata": dict(metadata),
|
|
})
|
|
|
|
return tuple(normalized)
|
|
|
|
|
|
def validate_content_document(document: Mapping[str, Any]) -> list[Mapping[str, Any]]:
|
|
if "contents" not in document:
|
|
raise ContentValidationError("Content document requires 'contents'")
|
|
contents = document["contents"]
|
|
if not isinstance(contents, list):
|
|
raise ContentValidationError("'contents' must be an array")
|
|
for index, row in enumerate(contents):
|
|
if not isinstance(row, Mapping):
|
|
raise ContentValidationError(f"contents[{index}] must be an object")
|
|
return contents
|
|
|
|
|
|
def validate_object_input(*, definitions: Mapping[str, AttributeDefinition], content: Mapping[str, Any], reserved_fields: set[str] | None = None) -> None:
|
|
unknown = set(content.keys()) - set(definitions.keys()) - (reserved_fields or set())
|
|
if unknown:
|
|
raise UnknownAttributeError("Unknown content attributes: " + ", ".join(sorted(unknown)))
|
|
|
|
|
|
def convert_scalar_value(*, definition: AttributeDefinition, value: Any) -> Any:
|
|
if definition.definition_kind != "scalar":
|
|
raise InvalidAttributeValueError(f"Definition {definition.attribute_key!r} is not scalar")
|
|
if value is None:
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} cannot contain null")
|
|
|
|
data_type = definition.data_type
|
|
if data_type in {"text", "rich_text"}:
|
|
if not isinstance(value, str):
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} must be text")
|
|
converted: Any = value
|
|
elif data_type == "number":
|
|
if isinstance(value, bool):
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} must be numeric")
|
|
try:
|
|
converted = Decimal(str(value))
|
|
except (InvalidOperation, ValueError, TypeError) as exc:
|
|
raise InvalidAttributeValueError(f"Invalid numeric value for {definition.code!r}: {value!r}") from exc
|
|
elif data_type == "boolean":
|
|
if not isinstance(value, bool):
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} must be boolean")
|
|
converted = value
|
|
elif data_type == "date":
|
|
if isinstance(value, datetime):
|
|
converted = value.date()
|
|
elif isinstance(value, date):
|
|
converted = value
|
|
elif isinstance(value, str):
|
|
try:
|
|
converted = date.fromisoformat(value)
|
|
except ValueError as exc:
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} requires YYYY-MM-DD") from exc
|
|
else:
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} must be a date")
|
|
elif data_type == "json":
|
|
try:
|
|
json.dumps(value)
|
|
except (TypeError, ValueError) as exc:
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} contains invalid JSON") from exc
|
|
converted = value
|
|
elif data_type == "media":
|
|
try:
|
|
converted = UUID(str(value))
|
|
except (ValueError, TypeError) as exc:
|
|
raise InvalidAttributeValueError(f"Attribute {definition.code!r} requires a media UUID") from exc
|
|
else:
|
|
raise InvalidAttributeValueError(f"Unsupported data type {data_type!r} for {definition.code!r}")
|
|
|
|
if definition.allowed_values is not None and converted not in definition.allowed_values:
|
|
raise InvalidAttributeValueError(
|
|
f"Value {converted!r} is not allowed for {definition.code!r}; allowed={definition.allowed_values!r}"
|
|
)
|
|
return converted
|
|
|
|
|
|
def parse_config_document(document: Mapping[str, Any], *, modules_root: Path) -> tuple[ModuleConfigEntry, ...]:
|
|
raw_modules = document.get("modules")
|
|
if not isinstance(raw_modules, list):
|
|
raise ModuleValidationError("config.json requires a 'modules' array")
|
|
|
|
entries: list[ModuleConfigEntry] = []
|
|
seen_codes: set[str] = set()
|
|
|
|
for index, raw in enumerate(raw_modules):
|
|
if not isinstance(raw, Mapping):
|
|
raise ModuleValidationError(f"modules[{index}] must be an object")
|
|
|
|
name = require_non_empty_string(raw.get("name"), f"modules[{index}].name")
|
|
code = require_non_empty_string(raw.get("code"), f"modules[{index}].code").lower()
|
|
path_value = require_non_empty_string(raw.get("path"), f"modules[{index}].path")
|
|
status = require_non_empty_string(raw.get("status"), f"modules[{index}].status")
|
|
|
|
if status not in SUPPORTED_MODULE_STATUSES:
|
|
raise ModuleValidationError(f"modules[{index}].status={status!r} is invalid")
|
|
if code in seen_codes:
|
|
raise ModuleValidationError(f"Duplicate module code {code!r}")
|
|
seen_codes.add(code)
|
|
|
|
entries.append(ModuleConfigEntry(name=name, code=code, path=(modules_root / path_value).resolve(), status=status))
|
|
|
|
return tuple(entries)
|
|
|
|
|
|
def parse_module_manifest(document: Mapping[str, Any], *, module_dir: Path) -> ModuleManifest:
|
|
name = require_non_empty_string(document.get("name"), "module.name")
|
|
code = require_non_empty_string(document.get("code"), "module.code").lower()
|
|
|
|
raw_mapping = document.get("content_mapping")
|
|
if not isinstance(raw_mapping, list) or not raw_mapping:
|
|
raise ModuleValidationError(f"module {code!r} requires non-empty content_mapping")
|
|
|
|
mappings: list[ModuleContentMapping] = []
|
|
seen_codes: set[str] = set()
|
|
|
|
for index, raw in enumerate(raw_mapping):
|
|
if not isinstance(raw, Mapping):
|
|
raise ModuleValidationError(f"content_mapping[{index}] must be an object")
|
|
|
|
mapping_name = require_non_empty_string(raw.get("name"), f"content_mapping[{index}].name")
|
|
mapping_code = require_non_empty_string(raw.get("code"), f"content_mapping[{index}].code").lower()
|
|
data_path = require_non_empty_string(raw.get("data_path"), f"content_mapping[{index}].data_path")
|
|
template_path = require_non_empty_string(raw.get("template_path"), f"content_mapping[{index}].template_path")
|
|
|
|
if mapping_code in seen_codes:
|
|
raise ModuleValidationError(f"Duplicate content_mapping code {mapping_code!r}")
|
|
seen_codes.add(mapping_code)
|
|
|
|
mappings.append(ModuleContentMapping(
|
|
name=mapping_name,
|
|
code=mapping_code,
|
|
description=raw.get("description"),
|
|
data_path=(module_dir / data_path).resolve(),
|
|
template_path=(module_dir / template_path).resolve(),
|
|
))
|
|
|
|
default_template_code_raw = document.get("default_template_code")
|
|
default_template_code: str | None = None
|
|
if default_template_code_raw is not None:
|
|
default_template_code = require_non_empty_string(
|
|
default_template_code_raw,
|
|
"module.default_template_code",
|
|
).lower()
|
|
if default_template_code not in seen_codes:
|
|
raise ModuleValidationError(
|
|
f"module.default_template_code {default_template_code!r} must reference "
|
|
f"a code declared in module {code!r} content_mapping"
|
|
)
|
|
|
|
metadata = document.get("metadata") or {}
|
|
if not isinstance(metadata, Mapping):
|
|
raise ModuleValidationError("module.metadata must be an object")
|
|
|
|
return ModuleManifest(
|
|
name=name,
|
|
code=code,
|
|
description=document.get("description"),
|
|
short_description=document.get("short_description"),
|
|
kind=document.get("kind"),
|
|
default_template_code=default_template_code,
|
|
metadata=dict(metadata),
|
|
content_mapping=tuple(mappings),
|
|
)
|