"""Read-only loader for the centralized user-profile schema TOML.:func:`load_user_profile_schema` reads the bundled schema TOML into a:class:`ProfileSchemaDefinition` and raises :class:`UserProfileSchemaLoadError`when the file cannot be read or validated."""from__future__importannotationsfromfunctoolsimportlru_cachefrompathlibimportPathfrompydanticimportValidationErrorfrom...coreimportfreeze_toml,read_tomlfrom...core.resourcesimportbundled_pathfrom._errorsimportUserProfileSchemaLoadErrorfrom._schemaimportProfileSchemaDefinition
[docs]defload_user_profile_schema(path:Path|None=None)->ProfileSchemaDefinition:"""Load the centralized user-profile schema. Args: path: TOML schema path. Defaults to the bundled registry schema. Returns: A strict, frozen :class:`ProfileSchemaDefinition`. Raises: :class:`UserProfileSchemaLoadError`: If the schema file cannot be stated, parsed, or validated into :class:`ProfileSchemaDefinition`. """target=pathifpathisnotNoneelsebundled_path("registry","aeat","user_profile","schema.toml")resolved=target.resolve()try:stat=resolved.stat()exceptOSErrorasexc:raise_schema_load_error(resolved,"cannot stat user-profile schema",operation="stat")fromexcreturn_load_user_profile_schema_cached(str(resolved),stat.st_size,stat.st_mtime_ns)
@lru_cache(maxsize=16)def_load_user_profile_schema_cached(path:str,byte_count:int,modified_ns:int)->ProfileSchemaDefinition:delbyte_count,modified_nssource_path=Path(path)data=freeze_toml(read_toml(source_path,error_factory=lambdamessage:_schema_load_error(source_path,message,operation="read"),),)raw_schema=data.get("schema")ifnotisinstance(raw_schema,dict):raise_schema_load_error(source_path,"missing [schema] table",operation="validate")raw_sections=data.get("sections")ifnotisinstance(raw_sections,tuple)ornotraw_sections:raise_schema_load_error(source_path,"missing [[sections]] tables",operation="validate")try:returnProfileSchemaDefinition.model_validate({**raw_schema,"sections":raw_sections})exceptValidationErrorasexc:raise_schema_load_error(source_path,f"invalid user-profile schema: {exc}",operation="validate")fromexcdef_schema_load_error(path:Path,message:str,*,operation:str)->UserProfileSchemaLoadError:"""Build a structured schema-load error without leaking raw OS exceptions."""returnUserProfileSchemaLoadError(f"{path}: {message}",context={"operation":operation,"path":str(path),"schema":"user_profile",},)