diff --git a/GFramework.Game.Tests/Config/GeneratedConfigConsumerIntegrationTests.cs b/GFramework.Game.Tests/Config/GeneratedConfigConsumerIntegrationTests.cs index b44a1cd5..9422aa75 100644 --- a/GFramework.Game.Tests/Config/GeneratedConfigConsumerIntegrationTests.cs +++ b/GFramework.Game.Tests/Config/GeneratedConfigConsumerIntegrationTests.cs @@ -1,6 +1,4 @@ -using System; using System.IO; -using System.Linq; using GFramework.Game.Config; using GFramework.Game.Config.Generated; @@ -13,6 +11,8 @@ namespace GFramework.Game.Tests.Config; [TestFixture] public class GeneratedConfigConsumerIntegrationTests { + private string _rootPath = null!; + /// /// 为每个端到端测试准备独立的配置根目录,避免编译期 schema 资产与运行时写入互相污染。 /// @@ -35,8 +35,6 @@ public class GeneratedConfigConsumerIntegrationTests } } - private string _rootPath = null!; - /// /// 验证生成器自动拾取消费者项目的 schema 后, /// 可以用生成的聚合注册辅助完成加载,并通过强类型表包装访问运行时数据与查询辅助。 @@ -88,7 +86,8 @@ public class GeneratedConfigConsumerIntegrationTests Assert.That(monsterTable.Get(1).Name, Is.EqualTo("Slime")); Assert.That(monsterTable.Get(2).Hp, Is.EqualTo(30)); Assert.That(monsterTable.FindByName("Slime").Select(static config => config.Id), Is.EqualTo(new[] { 1 })); - Assert.That(dungeonMonsters.Select(static config => config.Name), Is.EquivalentTo(new[] { "Slime", "Goblin" })); + Assert.That(dungeonMonsters.Select(static config => config.Name), + Is.EquivalentTo(new[] { "Slime", "Goblin" })); Assert.That(monsterTable.TryFindFirstByName("Goblin", out var goblin), Is.True); Assert.That(goblin, Is.Not.Null); Assert.That(goblin!.Id, Is.EqualTo(2)); @@ -154,10 +153,13 @@ public class GeneratedConfigConsumerIntegrationTests Is.EqualTo(new[] { MonsterConfigBindings.TableName })); Assert.That(GeneratedConfigCatalog.GetTablesForRegistration().Select(static metadata => metadata.TableName), Is.SupersetOf(new[] { ItemConfigBindings.TableName, MonsterConfigBindings.TableName })); - Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, monsterOnlyOptions), Is.True); + Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, monsterOnlyOptions), + Is.True); Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, monsterOnlyOptions), Is.False); - Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, predicateOnlyOptions), Is.True); - Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, predicateOnlyOptions), Is.False); + Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, predicateOnlyOptions), + Is.True); + Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, predicateOnlyOptions), + Is.False); Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, options: null), Is.True); }); } @@ -232,6 +234,61 @@ public class GeneratedConfigConsumerIntegrationTests }); } + /// + /// 验证生成绑定会同时暴露 YAML 序列化、schema 路径解析与文本校验入口。 + /// + [Test] + public async Task GeneratedBindings_Should_Expose_Serializer_And_Validator_Helpers() + { + CreateMonsterFiles(); + + var config = new MonsterConfig + { + Id = 3, + Name = "Bat", + Hp = 12, + Faction = "cave" + }; + + var yaml = MonsterConfigBindings.SerializeToYaml(config); + var schemaPath = MonsterConfigBindings.GetSchemaPath(_rootPath); + var configDirectoryPath = MonsterConfigBindings.GetConfigDirectoryPath(_rootPath); + + Assert.Multiple(() => + { + Assert.That(schemaPath, Is.EqualTo(Path.Combine(_rootPath, "schemas", "monster.schema.json"))); + Assert.That(configDirectoryPath, Is.EqualTo(Path.Combine(_rootPath, "monster"))); + Assert.That(yaml, Does.Contain("id: 3")); + Assert.That(yaml, Does.Contain("name: Bat")); + Assert.That(yaml, Does.Contain("hp: 12")); + Assert.That(yaml, Does.Contain("faction: cave")); + Assert.That(yaml.EndsWith(Environment.NewLine, StringComparison.Ordinal), Is.True); + }); + + Assert.DoesNotThrow(() => + MonsterConfigBindings.ValidateYaml(_rootPath, "monster/generated.yaml", yaml)); + + Assert.DoesNotThrowAsync(async () => + await MonsterConfigBindings.ValidateYamlAsync(_rootPath, "monster/generated.yaml", yaml)); + + var invalidYaml = """ + id: 3 + name: Bat + hp: 12 + unknownField: true + """; + + var exception = Assert.Throws(() => + MonsterConfigBindings.ValidateYaml(_rootPath, "monster/generated.yaml", invalidYaml)); + + Assert.Multiple(() => + { + Assert.That(exception, Is.Not.Null); + Assert.That(exception!.Diagnostic.SchemaPath, Is.EqualTo(schemaPath)); + Assert.That(exception.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.UnknownProperty)); + }); + } + /// /// 在临时消费者根目录中创建测试文件。 /// diff --git a/GFramework.Game.Tests/Config/YamlConfigTextValidatorTests.cs b/GFramework.Game.Tests/Config/YamlConfigTextValidatorTests.cs new file mode 100644 index 00000000..02403d75 --- /dev/null +++ b/GFramework.Game.Tests/Config/YamlConfigTextValidatorTests.cs @@ -0,0 +1,165 @@ +using System.IO; +using GFramework.Game.Config; + +namespace GFramework.Game.Tests.Config; + +/// +/// 验证公开的 YAML 文本校验入口可以在保存前复用运行时同一套 schema 规则。 +/// +[TestFixture] +public sealed class YamlConfigTextValidatorTests +{ + private string _rootPath = null!; + + /// + /// 为每个测试准备独立临时目录。 + /// + [SetUp] + public void SetUp() + { + _rootPath = Path.Combine(Path.GetTempPath(), "GFramework.TextValidatorTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_rootPath); + } + + /// + /// 清理测试临时目录。 + /// + [TearDown] + public void TearDown() + { + if (Directory.Exists(_rootPath)) + { + Directory.Delete(_rootPath, true); + } + } + + /// + /// 验证合法 YAML 文本会通过公开校验入口。 + /// + [Test] + public void Validate_Should_Succeed_When_Yaml_Matches_Schema() + { + var schemaPath = CreateSchemaFile( + "schemas/monster.schema.json", + """ + { + "type": "object", + "required": ["id", "name", "hp"], + "properties": { + "id": { "type": "integer" }, + "name": { "type": "string" }, + "hp": { "type": "integer" } + } + } + """); + + Assert.DoesNotThrow(() => + YamlConfigTextValidator.Validate( + "monster", + schemaPath, + "monster/generated.yaml", + """ + id: 1 + name: Slime + hp: 10 + """)); + } + + /// + /// 验证结构错误会继续通过稳定的配置异常类型暴露给宿主。 + /// + [Test] + public void Validate_Should_Throw_ConfigLoadException_When_Yaml_Contains_Unknown_Field() + { + var schemaPath = CreateSchemaFile( + "schemas/monster.schema.json", + """ + { + "type": "object", + "required": ["id", "name"], + "properties": { + "id": { "type": "integer" }, + "name": { "type": "string" } + } + } + """); + + var exception = Assert.Throws(() => + YamlConfigTextValidator.Validate( + "monster", + schemaPath, + "monster/generated.yaml", + """ + id: 1 + name: Slime + hp: 10 + """)); + + Assert.Multiple(() => + { + Assert.That(exception, Is.Not.Null); + Assert.That(exception!.Diagnostic.TableName, Is.EqualTo("monster")); + Assert.That(exception.Diagnostic.SchemaPath, Is.EqualTo(schemaPath)); + Assert.That(exception.Diagnostic.YamlPath, Is.EqualTo("monster/generated.yaml")); + Assert.That(exception.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.UnknownProperty)); + }); + } + + /// + /// 验证异步入口与同步入口共享相同校验语义。 + /// + [Test] + public async Task ValidateAsync_Should_Throw_ConfigLoadException_When_Required_Field_Is_Missing() + { + var schemaPath = CreateSchemaFile( + "schemas/monster.schema.json", + """ + { + "type": "object", + "required": ["id", "name"], + "properties": { + "id": { "type": "integer" }, + "name": { "type": "string" } + } + } + """); + + var exception = Assert.ThrowsAsync(async () => + await YamlConfigTextValidator.ValidateAsync( + "monster", + schemaPath, + "monster/generated.yaml", + """ + id: 1 + """)); + + Assert.Multiple(() => + { + Assert.That(exception, Is.Not.Null); + Assert.That(exception!.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.MissingRequiredProperty)); + Assert.That(exception.Diagnostic.SchemaPath, Is.EqualTo(schemaPath)); + Assert.That(exception.Diagnostic.YamlPath, Is.EqualTo("monster/generated.yaml")); + }); + } + + /// + /// 在临时目录中创建 schema 文件。 + /// + /// 相对根目录的路径。 + /// 文件内容。 + /// 写入后的绝对路径。 + private string CreateSchemaFile( + string relativePath, + string content) + { + var fullPath = Path.Combine(_rootPath, relativePath.Replace('/', Path.DirectorySeparatorChar)); + var directoryPath = Path.GetDirectoryName(fullPath); + if (!string.IsNullOrWhiteSpace(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + + File.WriteAllText(fullPath, content.Replace("\n", Environment.NewLine, StringComparison.Ordinal)); + return fullPath; + } +} diff --git a/GFramework.Game/Config/YamlConfigSchemaValidator.cs b/GFramework.Game/Config/YamlConfigSchemaValidator.cs index 3c86d649..4c689264 100644 --- a/GFramework.Game/Config/YamlConfigSchemaValidator.cs +++ b/GFramework.Game/Config/YamlConfigSchemaValidator.cs @@ -19,18 +19,23 @@ internal static class YamlConfigSchemaValidator // JS tooling so grouping and backreferences behave consistently across environments. private const RegexOptions SupportedPatternRegexOptions = RegexOptions.CultureInvariant; private const string SupportedStringFormatNames = "'date', 'date-time', 'email', 'uri', 'uuid'"; + private static readonly Regex ExactDecimalPattern = new( @"^(?[+-]?)(?:(?\d+)(?:\.(?\d*))?|\.(?\d+))(?:[eE](?[+-]?\d+))?$", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex SupportedEmailFormatRegex = new( @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex SupportedDateFormatRegex = new( @"^(?\d{4})-(?\d{2})-(?\d{2})$", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex SupportedDateTimeFormatRegex = new( @"^(?\d{4})-(?\d{2})-(?\d{2})T(?\d{2}):(?\d{2}):(?\d{2})(?\.\d+)?(?Z|[+-]\d{2}:\d{2})$", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex SupportedUriSchemeRegex = new( @"^[A-Za-z][A-Za-z0-9+\.-]*:", RegexOptions.CultureInvariant | RegexOptions.Compiled); @@ -84,34 +89,57 @@ internal static class YamlConfigSchemaValidator innerException: exception); } - try + return ParseLoadedSchema(tableName, schemaPath, schemaText); + } + + /// + /// 从磁盘同步加载并解析一个 JSON Schema 文件。 + /// + /// 所属配置表名称。 + /// Schema 文件路径。 + /// 解析后的 schema 模型。 + /// 为空时抛出。 + /// 为空时抛出。 + /// 当 schema 文件不存在或内容非法时抛出。 + internal static YamlConfigSchema Load( + string tableName, + string schemaPath) + { + if (string.IsNullOrWhiteSpace(tableName)) { - using var document = JsonDocument.Parse(schemaText); - var root = document.RootElement; - var rootNode = ParseNode(tableName, schemaPath, "", root, isRoot: true); - if (rootNode.NodeType != YamlConfigSchemaPropertyType.Object) - { - throw ConfigLoadExceptionFactory.Create( - ConfigLoadFailureKind.SchemaUnsupported, - tableName, - $"Schema file '{schemaPath}' must declare a root object schema.", - schemaPath: schemaPath); - } - - var referencedTableNames = new HashSet(StringComparer.Ordinal); - CollectReferencedTableNames(rootNode, referencedTableNames); - - return new YamlConfigSchema(schemaPath, rootNode, referencedTableNames.ToArray()); + throw new ArgumentException("Table name cannot be null or whitespace.", nameof(tableName)); } - catch (JsonException exception) + + if (string.IsNullOrWhiteSpace(schemaPath)) + { + throw new ArgumentException("Schema path cannot be null or whitespace.", nameof(schemaPath)); + } + + if (!File.Exists(schemaPath)) { throw ConfigLoadExceptionFactory.Create( - ConfigLoadFailureKind.SchemaInvalidJson, + ConfigLoadFailureKind.SchemaFileNotFound, tableName, - $"Schema file '{schemaPath}' contains invalid JSON.", + $"Schema file '{schemaPath}' was not found.", + schemaPath: schemaPath); + } + + string schemaText; + try + { + schemaText = File.ReadAllText(schemaPath); + } + catch (Exception exception) + { + throw ConfigLoadExceptionFactory.Create( + ConfigLoadFailureKind.SchemaReadFailed, + tableName, + $"Failed to read schema file '{schemaPath}'.", schemaPath: schemaPath, innerException: exception); } + + return ParseLoadedSchema(tableName, schemaPath, schemaText); } /// @@ -211,6 +239,48 @@ internal static class YamlConfigSchemaValidator ValidateNode(tableName, yamlPath, string.Empty, yamlStream.Documents[0].RootNode, schema.RootNode, references); } + /// + /// 解析已读取到内存中的 schema 文本,并构造运行时最小模型。 + /// + /// 所属配置表名称。 + /// Schema 文件路径,仅用于诊断信息。 + /// Schema 文本内容。 + /// 解析后的 schema 模型。 + private static YamlConfigSchema ParseLoadedSchema( + string tableName, + string schemaPath, + string schemaText) + { + try + { + using var document = JsonDocument.Parse(schemaText); + var root = document.RootElement; + var rootNode = ParseNode(tableName, schemaPath, "", root, isRoot: true); + if (rootNode.NodeType != YamlConfigSchemaPropertyType.Object) + { + throw ConfigLoadExceptionFactory.Create( + ConfigLoadFailureKind.SchemaUnsupported, + tableName, + $"Schema file '{schemaPath}' must declare a root object schema.", + schemaPath: schemaPath); + } + + var referencedTableNames = new HashSet(StringComparer.Ordinal); + CollectReferencedTableNames(rootNode, referencedTableNames); + + return new YamlConfigSchema(schemaPath, rootNode, referencedTableNames.ToArray()); + } + catch (JsonException exception) + { + throw ConfigLoadExceptionFactory.Create( + ConfigLoadFailureKind.SchemaInvalidJson, + tableName, + $"Schema file '{schemaPath}' contains invalid JSON.", + schemaPath: schemaPath, + innerException: exception); + } + } + /// /// 递归解析 schema 节点,使运行时只保留校验真正需要的最小结构信息。 /// @@ -662,7 +732,8 @@ internal static class YamlConfigSchemaValidator schemaPath: schemaNode.SchemaPathHint, displayPath: GetDiagnosticPath(displayPath), rawValue: rawValue, - detail: $"Minimum property count: {constraints.MinProperties.Value.ToString(CultureInfo.InvariantCulture)}."); + detail: + $"Minimum property count: {constraints.MinProperties.Value.ToString(CultureInfo.InvariantCulture)}."); } if (constraints.MaxProperties.HasValue && @@ -676,7 +747,8 @@ internal static class YamlConfigSchemaValidator schemaPath: schemaNode.SchemaPathHint, displayPath: GetDiagnosticPath(displayPath), rawValue: rawValue, - detail: $"Maximum property count: {constraints.MaxProperties.Value.ToString(CultureInfo.InvariantCulture)}."); + detail: + $"Maximum property count: {constraints.MaxProperties.Value.ToString(CultureInfo.InvariantCulture)}."); } } @@ -1017,7 +1089,7 @@ internal static class YamlConfigSchemaValidator } var properties = schemaNode.Properties - ?? throw new InvalidOperationException("Object schema nodes must expose declared properties."); + ?? throw new InvalidOperationException("Object schema nodes must expose declared properties."); var objectEntries = new List>(); foreach (var property in element.EnumerateObject()) { @@ -1087,19 +1159,18 @@ internal static class YamlConfigSchemaValidator return "[" + string.Join( ",", - element.EnumerateArray().Select( - (item, index) => - { - var comparableValue = BuildComparableConstantValue( - tableName, - schemaPath, - $"{propertyPath}[{index}]", - keywordName, - item, - schemaNode.ItemNode); - return - $"{comparableValue.Length.ToString(CultureInfo.InvariantCulture)}:{comparableValue}"; - })) + + element.EnumerateArray().Select((item, index) => + { + var comparableValue = BuildComparableConstantValue( + tableName, + schemaPath, + $"{propertyPath}[{index}]", + keywordName, + item, + schemaNode.ItemNode); + return + $"{comparableValue.Length.ToString(CultureInfo.InvariantCulture)}:{comparableValue}"; + })) + "]"; } @@ -1133,11 +1204,11 @@ internal static class YamlConfigSchemaValidator } /// -/// 解析标量字段支持的范围、长度与模式约束。 -/// 当前共享子集支持: -/// `integer/number` 上的 `minimum/maximum/exclusiveMinimum/exclusiveMaximum`, -/// 以及 `string` 上的 `minLength/maxLength/pattern/format`。 -/// + /// 解析标量字段支持的范围、长度与模式约束。 + /// 当前共享子集支持: + /// `integer/number` 上的 `minimum/maximum/exclusiveMinimum/exclusiveMaximum`, + /// 以及 `string` 上的 `minLength/maxLength/pattern/format`。 + /// /// 所属配置表名称。 /// Schema 文件路径。 /// 字段路径。 @@ -1420,7 +1491,8 @@ internal static class YamlConfigSchemaValidator JsonElement element, YamlConfigSchemaPropertyType nodeType) { - var multipleOf = TryParseNumericConstraint(tableName, schemaPath, propertyPath, element, nodeType, "multipleOf"); + var multipleOf = + TryParseNumericConstraint(tableName, schemaPath, propertyPath, element, nodeType, "multipleOf"); if (!multipleOf.HasValue) { return null; @@ -2060,7 +2132,8 @@ internal static class YamlConfigSchemaValidator schemaPath: schemaNode.SchemaPathHint, displayPath: GetDiagnosticPath(displayPath), rawValue: rawValue, - detail: $"Exclusive minimum allowed value: {constraints.ExclusiveMinimum.Value.ToString(CultureInfo.InvariantCulture)}."); + detail: + $"Exclusive minimum allowed value: {constraints.ExclusiveMinimum.Value.ToString(CultureInfo.InvariantCulture)}."); } if (constraints.Maximum.HasValue && numericValue > constraints.Maximum.Value) @@ -2086,7 +2159,8 @@ internal static class YamlConfigSchemaValidator schemaPath: schemaNode.SchemaPathHint, displayPath: GetDiagnosticPath(displayPath), rawValue: rawValue, - detail: $"Exclusive maximum allowed value: {constraints.ExclusiveMaximum.Value.ToString(CultureInfo.InvariantCulture)}."); + detail: + $"Exclusive maximum allowed value: {constraints.ExclusiveMaximum.Value.ToString(CultureInfo.InvariantCulture)}."); } if (constraints.MultipleOf.HasValue && @@ -2100,7 +2174,8 @@ internal static class YamlConfigSchemaValidator schemaPath: schemaNode.SchemaPathHint, displayPath: GetDiagnosticPath(displayPath), rawValue: rawValue, - detail: $"Required numeric step: {constraints.MultipleOf.Value.ToString(CultureInfo.InvariantCulture)}."); + detail: + $"Required numeric step: {constraints.MultipleOf.Value.ToString(CultureInfo.InvariantCulture)}."); } } @@ -2534,7 +2609,8 @@ internal static class YamlConfigSchemaValidator return true; } - catch (ConfigLoadException exception) when (exception.Diagnostic.FailureKind != ConfigLoadFailureKind.UnexpectedFailure) + catch (ConfigLoadException exception) when (exception.Diagnostic.FailureKind != + ConfigLoadFailureKind.UnexpectedFailure) { return false; } @@ -2577,7 +2653,8 @@ internal static class YamlConfigSchemaValidator } var properties = schemaNode.Properties - ?? throw new InvalidOperationException("Validated object nodes must expose declared properties."); + ?? throw new InvalidOperationException( + "Validated object nodes must expose declared properties."); var objectEntries = new List>(mappingNode.Children.Count); foreach (var entry in mappingNode.Children) { @@ -2619,12 +2696,11 @@ internal static class YamlConfigSchemaValidator return "[" + string.Join( ",", - sequenceNode.Children.Select( - item => - { - var comparableValue = BuildComparableNodeValue(item, schemaNode.ItemNode); - return $"{comparableValue.Length.ToString(CultureInfo.InvariantCulture)}:{comparableValue}"; - })) + + sequenceNode.Children.Select(item => + { + var comparableValue = BuildComparableNodeValue(item, schemaNode.ItemNode); + return $"{comparableValue.Length.ToString(CultureInfo.InvariantCulture)}:{comparableValue}"; + })) + "]"; } @@ -2644,7 +2720,8 @@ internal static class YamlConfigSchemaValidator } var normalizedScalar = NormalizeScalarValue(schemaNode.NodeType, scalarNode.Value); - return $"{schemaNode.NodeType}:{normalizedScalar.Length.ToString(CultureInfo.InvariantCulture)}:{normalizedScalar}"; + return + $"{schemaNode.NodeType}:{normalizedScalar.Length.ToString(CultureInfo.InvariantCulture)}:{normalizedScalar}"; } /// @@ -3119,87 +3196,6 @@ internal sealed class YamlConfigSchemaNode private readonly NodeChildren _children; private readonly NodeValidation _validation; - /// - /// 创建对象节点描述。 - /// - /// 对象属性集合。 - /// 对象必填属性集合。 - /// 对象属性数量约束。 - /// 用于错误信息的 schema 文件路径提示。 - /// 对象节点模型。 - public static YamlConfigSchemaNode CreateObject( - IReadOnlyDictionary? properties, - IReadOnlyCollection? requiredProperties, - YamlConfigObjectConstraints? objectConstraints, - string schemaPathHint) - { - return new YamlConfigSchemaNode( - YamlConfigSchemaPropertyType.Object, - new NodeChildren(properties, requiredProperties, itemNode: null), - new NodeValidation( - referenceTableName: null, - allowedValues: null, - constraints: null, - arrayConstraints: null, - objectConstraints, - constantValue: null), - schemaPathHint); - } - - /// - /// 创建数组节点描述。 - /// - /// 数组元素节点。 - /// 数组元素数量约束。 - /// 用于错误信息的 schema 文件路径提示。 - /// 数组节点模型。 - public static YamlConfigSchemaNode CreateArray( - YamlConfigSchemaNode itemNode, - YamlConfigArrayConstraints? arrayConstraints, - string schemaPathHint) - { - return new YamlConfigSchemaNode( - YamlConfigSchemaPropertyType.Array, - new NodeChildren(properties: null, requiredProperties: null, itemNode), - new NodeValidation( - referenceTableName: null, - allowedValues: null, - constraints: null, - arrayConstraints, - objectConstraints: null, - constantValue: null), - schemaPathHint); - } - - /// - /// 创建标量节点描述。 - /// - /// 标量节点类型。 - /// 目标引用表名称。 - /// 标量允许值集合。 - /// 标量范围与长度约束。 - /// 用于错误信息的 schema 文件路径提示。 - /// 标量节点模型。 - public static YamlConfigSchemaNode CreateScalar( - YamlConfigSchemaPropertyType nodeType, - string? referenceTableName, - IReadOnlyCollection? allowedValues, - YamlConfigScalarConstraints? constraints, - string schemaPathHint) - { - return new YamlConfigSchemaNode( - nodeType, - NodeChildren.None, - new NodeValidation( - referenceTableName, - allowedValues, - constraints, - arrayConstraints: null, - objectConstraints: null, - constantValue: null), - schemaPathHint); - } - private YamlConfigSchemaNode( YamlConfigSchemaPropertyType nodeType, NodeChildren children, @@ -3281,6 +3277,87 @@ internal sealed class YamlConfigSchemaNode /// public string SchemaPathHint { get; } + /// + /// 创建对象节点描述。 + /// + /// 对象属性集合。 + /// 对象必填属性集合。 + /// 对象属性数量约束。 + /// 用于错误信息的 schema 文件路径提示。 + /// 对象节点模型。 + public static YamlConfigSchemaNode CreateObject( + IReadOnlyDictionary? properties, + IReadOnlyCollection? requiredProperties, + YamlConfigObjectConstraints? objectConstraints, + string schemaPathHint) + { + return new YamlConfigSchemaNode( + YamlConfigSchemaPropertyType.Object, + new NodeChildren(properties, requiredProperties, itemNode: null), + new NodeValidation( + referenceTableName: null, + allowedValues: null, + constraints: null, + arrayConstraints: null, + objectConstraints, + constantValue: null), + schemaPathHint); + } + + /// + /// 创建数组节点描述。 + /// + /// 数组元素节点。 + /// 数组元素数量约束。 + /// 用于错误信息的 schema 文件路径提示。 + /// 数组节点模型。 + public static YamlConfigSchemaNode CreateArray( + YamlConfigSchemaNode itemNode, + YamlConfigArrayConstraints? arrayConstraints, + string schemaPathHint) + { + return new YamlConfigSchemaNode( + YamlConfigSchemaPropertyType.Array, + new NodeChildren(properties: null, requiredProperties: null, itemNode), + new NodeValidation( + referenceTableName: null, + allowedValues: null, + constraints: null, + arrayConstraints, + objectConstraints: null, + constantValue: null), + schemaPathHint); + } + + /// + /// 创建标量节点描述。 + /// + /// 标量节点类型。 + /// 目标引用表名称。 + /// 标量允许值集合。 + /// 标量范围与长度约束。 + /// 用于错误信息的 schema 文件路径提示。 + /// 标量节点模型。 + public static YamlConfigSchemaNode CreateScalar( + YamlConfigSchemaPropertyType nodeType, + string? referenceTableName, + IReadOnlyCollection? allowedValues, + YamlConfigScalarConstraints? constraints, + string schemaPathHint) + { + return new YamlConfigSchemaNode( + nodeType, + NodeChildren.None, + new NodeValidation( + referenceTableName, + allowedValues, + constraints, + arrayConstraints: null, + objectConstraints: null, + constantValue: null), + schemaPathHint); + } + /// /// 基于当前节点复制一个只替换引用表名称的新节点。 /// 该方法用于把数组级别的 ref-table 语义挂接到元素节点上。 @@ -3312,8 +3389,6 @@ internal sealed class YamlConfigSchemaNode private sealed class NodeChildren { - public static NodeChildren None { get; } = new(properties: null, requiredProperties: null, itemNode: null); - public NodeChildren( IReadOnlyDictionary? properties, IReadOnlyCollection? requiredProperties, @@ -3324,6 +3399,8 @@ internal sealed class YamlConfigSchemaNode ItemNode = itemNode; } + public static NodeChildren None { get; } = new(properties: null, requiredProperties: null, itemNode: null); + public IReadOnlyDictionary? Properties { get; } public IReadOnlyCollection? RequiredProperties { get; } @@ -3333,14 +3410,6 @@ internal sealed class YamlConfigSchemaNode private sealed class NodeValidation { - public static NodeValidation None { get; } = new( - referenceTableName: null, - allowedValues: null, - constraints: null, - arrayConstraints: null, - objectConstraints: null, - constantValue: null); - public NodeValidation( string? referenceTableName, IReadOnlyCollection? allowedValues, @@ -3357,6 +3426,14 @@ internal sealed class YamlConfigSchemaNode ConstantValue = constantValue; } + public static NodeValidation None { get; } = new( + referenceTableName: null, + allowedValues: null, + constraints: null, + arrayConstraints: null, + objectConstraints: null, + constantValue: null); + public string? ReferenceTableName { get; } public IReadOnlyCollection? AllowedValues { get; } @@ -3534,8 +3611,8 @@ internal sealed class YamlConfigNumericConstraints internal sealed class YamlConfigStringConstraints { /// -/// 初始化字符串约束模型。 -/// + /// 初始化字符串约束模型。 + /// /// 最小长度约束。 /// 最大长度约束。 /// 正则模式约束原文。 diff --git a/GFramework.Game/Config/YamlConfigTextSerializer.cs b/GFramework.Game/Config/YamlConfigTextSerializer.cs new file mode 100644 index 00000000..f8467220 --- /dev/null +++ b/GFramework.Game/Config/YamlConfigTextSerializer.cs @@ -0,0 +1,29 @@ +namespace GFramework.Game.Config; + +/// +/// 提供可复用的 YAML 文本序列化入口,供生成配置绑定与宿主写回流程共享。 +/// +public static class YamlConfigTextSerializer +{ + private static readonly ISerializer Serializer = new SerializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .DisableAliases() + .ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve) + .Build(); + + /// + /// 将配置对象序列化为 YAML 文本。 + /// + /// 配置对象类型。 + /// 要序列化的配置对象。 + /// 带尾随换行的 YAML 文本。 + public static string Serialize(TValue value) + { + ArgumentNullException.ThrowIfNull(value); + + var yaml = Serializer.Serialize(value); + return yaml.EndsWith('\n') + ? yaml + : $"{yaml}{Environment.NewLine}"; + } +} diff --git a/GFramework.Game/Config/YamlConfigTextValidator.cs b/GFramework.Game/Config/YamlConfigTextValidator.cs new file mode 100644 index 00000000..84747633 --- /dev/null +++ b/GFramework.Game/Config/YamlConfigTextValidator.cs @@ -0,0 +1,44 @@ +namespace GFramework.Game.Config; + +/// +/// 提供面向宿主的 YAML 文本校验入口,使保存前校验可以复用运行时同一套 schema 规则。 +/// +public static class YamlConfigTextValidator +{ + /// + /// 使用指定 schema 文件同步校验 YAML 文本。 + /// + /// 所属配置表名称。 + /// Schema 文件绝对路径。 + /// YAML 文件路径,仅用于诊断信息。 + /// 待校验的 YAML 文本。 + public static void Validate( + string tableName, + string schemaPath, + string yamlPath, + string yamlText) + { + var schema = YamlConfigSchemaValidator.Load(tableName, schemaPath); + YamlConfigSchemaValidator.Validate(tableName, schema, yamlPath, yamlText); + } + + /// + /// 使用指定 schema 文件异步校验 YAML 文本。 + /// + /// 所属配置表名称。 + /// Schema 文件绝对路径。 + /// YAML 文件路径,仅用于诊断信息。 + /// 待校验的 YAML 文本。 + /// 取消令牌。 + public static async Task ValidateAsync( + string tableName, + string schemaPath, + string yamlPath, + string yamlText, + CancellationToken cancellationToken = default) + { + var schema = await YamlConfigSchemaValidator.LoadAsync(tableName, schemaPath, cancellationToken) + .ConfigureAwait(false); + YamlConfigSchemaValidator.Validate(tableName, schema, yamlPath, yamlText); + } +} diff --git a/GFramework.SourceGenerators.Tests/Config/SchemaConfigGeneratorTests.cs b/GFramework.SourceGenerators.Tests/Config/SchemaConfigGeneratorTests.cs index 73ce4d4e..f325d87c 100644 --- a/GFramework.SourceGenerators.Tests/Config/SchemaConfigGeneratorTests.cs +++ b/GFramework.SourceGenerators.Tests/Config/SchemaConfigGeneratorTests.cs @@ -446,6 +446,14 @@ public class SchemaConfigGeneratorTests Assert.That(generatedSources["MonsterConfigBindings.g.cs"], Does.Contain("public const string ConfigRelativePath = \"config/monster\";")); Assert.That(generatedSources["MonsterConfigBindings.g.cs"], Does.Contain("Metadata.ConfigRelativePath,")); + Assert.That(generatedSources["MonsterConfigBindings.g.cs"], + Does.Contain("public static string SerializeToYaml(MonsterConfig config)")); + Assert.That(generatedSources["MonsterConfigBindings.g.cs"], + Does.Contain("public static string GetSchemaPath(string configRootPath)")); + Assert.That(generatedSources["MonsterConfigBindings.g.cs"], + Does.Contain("public static void ValidateYaml(string configRootPath, string yamlPath, string yamlText)")); + Assert.That(generatedSources["MonsterConfigBindings.g.cs"], + Does.Contain("public static global::System.Threading.Tasks.Task ValidateYamlAsync(")); Assert.That(generatedSources["GeneratedConfigCatalog.g.cs"], Does.Contain("MonsterConfigBindings.Metadata.ConfigRelativePath")); } diff --git a/GFramework.SourceGenerators.Tests/Config/snapshots/SchemaConfigGenerator/MonsterConfigBindings.g.txt b/GFramework.SourceGenerators.Tests/Config/snapshots/SchemaConfigGenerator/MonsterConfigBindings.g.txt index 66ea9bf9..e657c7ff 100644 --- a/GFramework.SourceGenerators.Tests/Config/snapshots/SchemaConfigGenerator/MonsterConfigBindings.g.txt +++ b/GFramework.SourceGenerators.Tests/Config/snapshots/SchemaConfigGenerator/MonsterConfigBindings.g.txt @@ -100,6 +100,89 @@ public static class MonsterConfigBindings /// public const string SchemaRelativePath = Metadata.SchemaRelativePath; + /// + /// Serializes one generated config instance to YAML text using the shared runtime naming convention. + /// + /// The generated config instance to serialize. + /// YAML text that preserves the shared camelCase field naming convention. + public static string SerializeToYaml(MonsterConfig config) + { + return global::GFramework.Game.Config.YamlConfigTextSerializer.Serialize(config); + } + + /// + /// Resolves the absolute config directory path by combining the caller-supplied config root with the generated relative directory. + /// + /// Absolute or workspace-local config root directory. + /// The absolute config directory path for the generated table. + public static string GetConfigDirectoryPath(string configRootPath) + { + return ResolveAbsolutePath(configRootPath, Metadata.ConfigRelativePath); + } + + /// + /// Resolves the absolute schema file path by combining the caller-supplied config root with the generated relative schema path. + /// + /// Absolute or workspace-local config root directory. + /// The absolute schema file path for the generated table. + public static string GetSchemaPath(string configRootPath) + { + return ResolveAbsolutePath(configRootPath, Metadata.SchemaRelativePath); + } + + /// + /// Validates YAML text against the generated schema file located under the supplied config root directory. + /// + /// Absolute or workspace-local config root directory. + /// Logical or absolute YAML path used for diagnostics. + /// YAML text to validate. + public static void ValidateYaml(string configRootPath, string yamlPath, string yamlText) + { + global::GFramework.Game.Config.YamlConfigTextValidator.Validate( + Metadata.TableName, + GetSchemaPath(configRootPath), + yamlPath, + yamlText); + } + + /// + /// Asynchronously validates YAML text against the generated schema file located under the supplied config root directory. + /// + /// Absolute or workspace-local config root directory. + /// Logical or absolute YAML path used for diagnostics. + /// YAML text to validate. + /// Cancellation token. + public static global::System.Threading.Tasks.Task ValidateYamlAsync( + string configRootPath, + string yamlPath, + string yamlText, + global::System.Threading.CancellationToken cancellationToken = default) + { + return global::GFramework.Game.Config.YamlConfigTextValidator.ValidateAsync( + Metadata.TableName, + GetSchemaPath(configRootPath), + yamlPath, + yamlText, + cancellationToken); + } + + private static string ResolveAbsolutePath(string configRootPath, string relativePath) + { + if (string.IsNullOrWhiteSpace(configRootPath)) + { + throw new global::System.ArgumentException("Config root path cannot be null or whitespace.", nameof(configRootPath)); + } + + if (relativePath is null) + { + throw new global::System.ArgumentNullException(nameof(relativePath)); + } + + var normalizedRelativePath = relativePath.Replace('/', global::System.IO.Path.DirectorySeparatorChar) + .Replace('\\', global::System.IO.Path.DirectorySeparatorChar); + return global::System.IO.Path.Combine(configRootPath, normalizedRelativePath); + } + /// /// Exposes generated metadata for schema properties that declare x-gframework-ref-table. /// diff --git a/GFramework.SourceGenerators/Config/SchemaConfigGenerator.cs b/GFramework.SourceGenerators/Config/SchemaConfigGenerator.cs index cec8282e..bb9e7f7b 100644 --- a/GFramework.SourceGenerators/Config/SchemaConfigGenerator.cs +++ b/GFramework.SourceGenerators/Config/SchemaConfigGenerator.cs @@ -17,14 +17,19 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator private const string ConfigPathMetadataKey = "x-gframework-config-path"; private const string LookupIndexMetadataKey = "x-gframework-index"; private const string GeneratedNamespace = "GFramework.Game.Config.Generated"; + private const string LookupIndexTopLevelScalarOnlyMessage = "Only top-level required non-key scalar properties can declare a generated lookup index."; + private const string LookupIndexRequiresRequiredScalarMessage = "Generated lookup indexes currently require a required scalar property so dictionary keys remain non-null."; + private const string LookupIndexPrimaryKeyMessage = "The primary key already has Get/TryGet lookup semantics and should not declare a generated lookup index."; + private const string LookupIndexReferencePropertyMessage = "Reference properties are excluded from generated lookup indexes because they already carry cross-table semantics."; + private const string SupportedStringFormatNames = "'date', 'date-time', 'email', 'uri', and 'uuid'"; /// @@ -434,7 +439,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator if (isIndexedLookup) { return ParsedPropertyResult.FromDiagnostic( - CreateInvalidLookupIndexDiagnostic(filePath, displayPath, LookupIndexTopLevelScalarOnlyMessage)); + CreateInvalidLookupIndexDiagnostic(filePath, displayPath, + LookupIndexTopLevelScalarOnlyMessage)); } if (!string.IsNullOrWhiteSpace(refTableName)) @@ -752,7 +758,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator } var itemType = itemTypeElement.GetString() ?? string.Empty; - if (!TryValidateStringFormatMetadata(filePath, $"{displayPath}[]", itemsElement, itemType, out var formatDiagnostic)) + if (!TryValidateStringFormatMetadata(filePath, $"{displayPath}[]", itemsElement, itemType, + out var formatDiagnostic)) { return ParsedPropertyResult.FromDiagnostic(formatDiagnostic!); } @@ -1128,6 +1135,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator builder.AppendLine(" /// "); builder.AppendLine(" public const string SchemaRelativePath = Metadata.SchemaRelativePath;"); builder.AppendLine(); + AppendYamlSerializationHelpers(builder, schema); + builder.AppendLine(); builder.AppendLine(" /// "); builder.AppendLine( " /// Exposes generated metadata for schema properties that declare x-gframework-ref-table."); @@ -1430,7 +1439,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator builder.AppendLine( " /// Resolves the generated table metadata entries that belong to the specified logical config domain."); builder.AppendLine(" /// "); - builder.AppendLine(" /// Logical config domain derived from the schema base name."); + builder.AppendLine( + " /// Logical config domain derived from the schema base name."); builder.AppendLine( " /// A deterministic metadata snapshot for the requested config domain, or an empty list when no generated table belongs to that domain."); builder.AppendLine( @@ -1665,6 +1675,117 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator return builder.ToString().TrimEnd(); } + /// + /// 为生成的绑定类输出 YAML 序列化与 schema 路径辅助。 + /// + /// 输出缓冲区。 + /// 生成器级 schema 模型。 + private static void AppendYamlSerializationHelpers( + StringBuilder builder, + SchemaFileSpec schema) + { + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Serializes one generated config instance to YAML text using the shared runtime naming convention."); + builder.AppendLine(" /// "); + builder.AppendLine(" /// The generated config instance to serialize."); + builder.AppendLine( + " /// YAML text that preserves the shared camelCase field naming convention."); + builder.AppendLine($" public static string SerializeToYaml({schema.ClassName} config)"); + builder.AppendLine(" {"); + builder.AppendLine(" return global::GFramework.Game.Config.YamlConfigTextSerializer.Serialize(config);"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Resolves the absolute config directory path by combining the caller-supplied config root with the generated relative directory."); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Absolute or workspace-local config root directory."); + builder.AppendLine(" /// The absolute config directory path for the generated table."); + builder.AppendLine(" public static string GetConfigDirectoryPath(string configRootPath)"); + builder.AppendLine(" {"); + builder.AppendLine(" return ResolveAbsolutePath(configRootPath, Metadata.ConfigRelativePath);"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Resolves the absolute schema file path by combining the caller-supplied config root with the generated relative schema path."); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Absolute or workspace-local config root directory."); + builder.AppendLine(" /// The absolute schema file path for the generated table."); + builder.AppendLine(" public static string GetSchemaPath(string configRootPath)"); + builder.AppendLine(" {"); + builder.AppendLine(" return ResolveAbsolutePath(configRootPath, Metadata.SchemaRelativePath);"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Validates YAML text against the generated schema file located under the supplied config root directory."); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Absolute or workspace-local config root directory."); + builder.AppendLine( + " /// Logical or absolute YAML path used for diagnostics."); + builder.AppendLine(" /// YAML text to validate."); + builder.AppendLine( + " public static void ValidateYaml(string configRootPath, string yamlPath, string yamlText)"); + builder.AppendLine(" {"); + builder.AppendLine(" global::GFramework.Game.Config.YamlConfigTextValidator.Validate("); + builder.AppendLine(" Metadata.TableName,"); + builder.AppendLine(" GetSchemaPath(configRootPath),"); + builder.AppendLine(" yamlPath,"); + builder.AppendLine(" yamlText);"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Asynchronously validates YAML text against the generated schema file located under the supplied config root directory."); + builder.AppendLine(" /// "); + builder.AppendLine( + " /// Absolute or workspace-local config root directory."); + builder.AppendLine( + " /// Logical or absolute YAML path used for diagnostics."); + builder.AppendLine(" /// YAML text to validate."); + builder.AppendLine(" /// Cancellation token."); + builder.AppendLine( + " public static global::System.Threading.Tasks.Task ValidateYamlAsync("); + builder.AppendLine(" string configRootPath,"); + builder.AppendLine(" string yamlPath,"); + builder.AppendLine(" string yamlText,"); + builder.AppendLine(" global::System.Threading.CancellationToken cancellationToken = default)"); + builder.AppendLine(" {"); + builder.AppendLine(" return global::GFramework.Game.Config.YamlConfigTextValidator.ValidateAsync("); + builder.AppendLine(" Metadata.TableName,"); + builder.AppendLine(" GetSchemaPath(configRootPath),"); + builder.AppendLine(" yamlPath,"); + builder.AppendLine(" yamlText,"); + builder.AppendLine(" cancellationToken);"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" private static string ResolveAbsolutePath(string configRootPath, string relativePath)"); + builder.AppendLine(" {"); + builder.AppendLine(" if (string.IsNullOrWhiteSpace(configRootPath))"); + builder.AppendLine(" {"); + builder.AppendLine( + " throw new global::System.ArgumentException(\"Config root path cannot be null or whitespace.\", nameof(configRootPath));"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine(" if (relativePath is null)"); + builder.AppendLine(" {"); + builder.AppendLine(" throw new global::System.ArgumentNullException(nameof(relativePath));"); + builder.AppendLine(" }"); + builder.AppendLine(); + builder.AppendLine( + " var normalizedRelativePath = relativePath.Replace('/', global::System.IO.Path.DirectorySeparatorChar)"); + builder.AppendLine( + " .Replace('\\\\', global::System.IO.Path.DirectorySeparatorChar);"); + builder.AppendLine( + " return global::System.IO.Path.Combine(configRootPath, normalizedRelativePath);"); + builder.AppendLine(" }"); + } + /// /// 收集 schema 中声明的跨表引用元数据,并为生成代码分配稳定成员名。 /// @@ -1778,8 +1899,10 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator " /// Materializes a read-only exact-match lookup index from the current table snapshot."); builder.AppendLine(" /// "); builder.AppendLine(" /// Indexed property type."); - builder.AppendLine(" /// Selects the indexed property from one config entry."); - builder.AppendLine(" /// A read-only dictionary whose values preserve snapshot iteration order."); + builder.AppendLine( + " /// Selects the indexed property from one config entry."); + builder.AppendLine( + " /// A read-only dictionary whose values preserve snapshot iteration order."); builder.AppendLine(" /// "); builder.AppendLine( " /// The generated index skips runtime null keys even though is constrained to notnull. Malformed YAML payloads can still deserialize missing indexed values to , and throwing from this lazy path would permanently poison the cached index for the current table wrapper instance."); @@ -1789,8 +1912,9 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator builder.AppendLine($" global::System.Func<{schema.ClassName}, TProperty> keySelector)"); builder.AppendLine(" where TProperty : notnull"); builder.AppendLine(" {"); - builder.AppendLine(" var buckets = new global::System.Collections.Generic.Dictionary>();"); + builder.AppendLine( + " var buckets = new global::System.Collections.Generic.Dictionary>();"); builder.AppendLine(); builder.AppendLine( " // Capture the current table snapshot once so indexed lookups stay deterministic for this wrapper instance."); @@ -1808,7 +1932,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator builder.AppendLine(); builder.AppendLine(" if (!buckets.TryGetValue(key, out var matches))"); builder.AppendLine(" {"); - builder.AppendLine($" matches = new global::System.Collections.Generic.List<{schema.ClassName}>();"); + builder.AppendLine( + $" matches = new global::System.Collections.Generic.List<{schema.ClassName}>();"); builder.AppendLine(" buckets.Add(key, matches);"); builder.AppendLine(" }"); builder.AppendLine(); @@ -2830,7 +2955,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator return schemaType switch { - "integer" when constElement.ValueKind == JsonValueKind.Number && constElement.TryGetInt64(out var intValue) => + "integer" when constElement.ValueKind == JsonValueKind.Number && + constElement.TryGetInt64(out var intValue) => intValue.ToString(CultureInfo.InvariantCulture), "number" when constElement.ValueKind == JsonValueKind.Number => constElement.GetDouble().ToString(CultureInfo.InvariantCulture),