Skip to content

Commit b1d605c

Browse files
author
Tarek Mahmoud Sayed
committed
[OptionsValidator] Support async-only validators (IAsyncValidateOptions<T> without IValidateOptions<T>)
Union model discovery over both the sync and async validate interfaces so a validator that implements only IAsyncValidateOptions<T> is picked up. A new GenerateValidateMethod flag gates emission of the synchronous Validate method; it stays true for sync-capable and synthesized child validators, so their output is unchanged, and is false only for top-level async-only validators (which would otherwise emit a dead public Validate). Adds two runtime tests covering async-only generation and nested async failure aggregation.
1 parent c0dd533 commit b1d605c

4 files changed

Lines changed: 121 additions & 13 deletions

File tree

‎src/libraries/Microsoft.Extensions.Options/gen/Emitter.cs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,23 @@ private void GenValidatorType(ValidatorType vt, ref Dictionary<string, StaticFie
129129
{
130130
var modelToValidate = vt.ModelsToValidate[i];
131131

132-
GenModelValidationMethod(modelToValidate, vt.IsSynthetic, ref staticValidationAttributesDict, ref staticValidatorsDict);
132+
// Emit the synchronous Validate method only for models reached through IValidateOptions<T>.
133+
// Synthesized validators always emit it, since the asynchronous fallback path invokes Validate
134+
// for nested validators that don't themselves emit ValidateAsync.
135+
if (modelToValidate.GenerateValidateMethod)
136+
{
137+
GenModelValidationMethod(modelToValidate, vt.IsSynthetic, ref staticValidationAttributesDict, ref staticValidatorsDict);
138+
}
133139

134140
// Only emit the async validation method when the validator type explicitly implements
135141
// IAsyncValidateOptions<T> for this model and the required async validation symbols are available (.NET 11+).
136142
if (modelToValidate.GenerateAsyncValidateMethod && _symbolHolder.AsyncValidateOptionsSymbol is not null && _symbolHolder.IAsyncValidatableObjectSymbol is not null)
137143
{
138-
OutLn();
144+
if (modelToValidate.GenerateValidateMethod)
145+
{
146+
OutLn();
147+
}
148+
139149
GenAsyncModelValidationMethod(modelToValidate, vt.IsSynthetic, ref staticValidationAttributesDict, ref staticValidatorsDict);
140150
}
141151
}

‎src/libraries/Microsoft.Extensions.Options/gen/Model/ValidatedModel.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ internal sealed record class ValidatedModel(
1010
string SimpleName,
1111
bool SelfValidates,
1212
bool SelfValidatesAsync,
13+
bool GenerateValidateMethod,
1314
bool GenerateAsyncValidateMethod,
1415
List<ValidatedMember> MembersToValidate);
1516
}

‎src/libraries/Microsoft.Extensions.Options/gen/Parser.cs‎

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -95,21 +95,27 @@ public IReadOnlyList<ValidatorType> GetValidatorTypes(IEnumerable<(TypeDeclarati
9595
_ = _visitedModelTypes.Add(modelType.WithNullableAnnotation(NullableAnnotation.None));
9696
}
9797

98-
if (AlreadyImplementsValidateMethod(validatorType, modelType))
98+
// A validator can opt into synchronous validation (IValidateOptions<T>), asynchronous
99+
// validation (IAsyncValidateOptions<T>), or both, on a per-model basis. We emit Validate
100+
// only for models reached through the synchronous interface and ValidateAsync only for
101+
// models reached through the asynchronous interface. If the user already hand-wrote a
102+
// matching method, we skip generating that one to avoid emitting a duplicate member.
103+
bool generateSync = CanValidate(validatorType, modelType);
104+
bool generateAsync = ValidatorImplementsAsyncInterfaceFor(validatorType, modelType)
105+
&& !AlreadyImplementsValidateAsyncMethod(validatorType, modelType);
106+
107+
if (generateSync && AlreadyImplementsValidateMethod(validatorType, modelType))
99108
{
100109
// this type already implements a validation function, we can't auto-generate a new one
101110
Diag(DiagDescriptors.AlreadyImplementsValidateMethod, syntax.GetLocation(), validatorType.Name);
102111
continue;
103112
}
104113

105-
// Decide, per model, whether we additionally emit a ValidateAsync method. We do so when the
106-
// validator type explicitly implements IAsyncValidateOptions<T> for this specific model (and the
107-
// async symbols are available). A multi-model validator therefore only gets async validation for
108-
// the models it opted into. If the user already hand-wrote a matching ValidateAsync, we skip
109-
// generation to avoid emitting a duplicate member. The async requirement is propagated to any
110-
// synthesized child validators reached from this model.
111-
bool generateAsync = ValidatorImplementsAsyncInterfaceFor(validatorType, modelType)
112-
&& !AlreadyImplementsValidateAsyncMethod(validatorType, modelType);
114+
if (!generateSync && !generateAsync)
115+
{
116+
// nothing to generate: an async-only validator that already hand-wrote ValidateAsync
117+
continue;
118+
}
113119

114120
Location? modelTypeLocation = modelType.GetLocation();
115121
Location lowerLocationInCompilation = modelTypeLocation is not null && modelTypeLocation.SourceTree is not null && _compilation.ContainsSyntaxTree(modelTypeLocation.SourceTree)
@@ -131,6 +137,7 @@ public IReadOnlyList<ValidatorType> GetValidatorTypes(IEnumerable<(TypeDeclarati
131137
modelType.Name,
132138
selfValidate,
133139
selfValidateAsync,
140+
generateSync,
134141
generateAsync,
135142
membersToValidate));
136143
}
@@ -759,6 +766,7 @@ private void TrackRangeAttributeForSubstitution(AttributeData attribute, ITypeSy
759766
mt.Name,
760767
selfValidate,
761768
selfValidateAsync,
769+
true,
762770
isAsync,
763771
membersToValidate);
764772

@@ -839,11 +847,20 @@ private bool ValidatorImplementsAsyncInterfaceFor(ITypeSymbol validatorType, ITy
839847
private List<ITypeSymbol> GetModelTypes(ITypeSymbol validatorType)
840848
{
841849
var result = new List<ITypeSymbol>();
850+
var seen = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default);
842851
foreach (var implementingInterface in validatorType.AllInterfaces)
843852
{
844-
if (SymbolEqualityComparer.Default.Equals(implementingInterface.OriginalDefinition, _symbolHolder.ValidateOptionsSymbol))
853+
bool isSync = SymbolEqualityComparer.Default.Equals(implementingInterface.OriginalDefinition, _symbolHolder.ValidateOptionsSymbol);
854+
bool isAsync = _symbolHolder.AsyncValidateOptionsSymbol is not null
855+
&& SymbolEqualityComparer.Default.Equals(implementingInterface.OriginalDefinition, _symbolHolder.AsyncValidateOptionsSymbol);
856+
857+
if (isSync || isAsync)
845858
{
846-
result.Add(implementingInterface.TypeArguments.First());
859+
var model = implementingInterface.TypeArguments.First();
860+
if (seen.Add(model.WithNullableAnnotation(NullableAnnotation.None)))
861+
{
862+
result.Add(model);
863+
}
847864
}
848865
}
849866

‎src/libraries/Microsoft.Extensions.Options/tests/SourceGeneration.Unit.Tests/OptionsRuntimeTests.cs‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,51 @@ public async Task TestManualValidateAsyncIsNotOverwritten()
546546
Assert.True(result.Failed);
547547
Assert.Contains("Manual ValidateAsync invoked.", result.Failures);
548548
}
549+
550+
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
551+
public async Task TestAsyncOnlyValidatorGeneratesValidateAsyncOnly()
552+
{
553+
// The validator implements only IAsyncValidateOptions<T>. The generator must discover the model through
554+
// the asynchronous interface, emit ValidateAsync, and must not emit a synchronous Validate (the type does
555+
// not implement IValidateOptions<T>, so emitting Validate would be a dead public method).
556+
Assert.True(typeof(IAsyncValidateOptions<AsyncOnlyOptions>).IsAssignableFrom(typeof(AsyncOnlyOptionsValidator)));
557+
Assert.False(typeof(IValidateOptions<AsyncOnlyOptions>).IsAssignableFrom(typeof(AsyncOnlyOptionsValidator)));
558+
Assert.Null(typeof(AsyncOnlyOptionsValidator).GetMethod("Validate"));
559+
560+
AsyncOnlyOptions valid = new()
561+
{
562+
Name = "Valid",
563+
Age = 30,
564+
Nested = new() { Level = 5, Id = "1", Children = new() { new AsyncChildOptions { Name = "C1" } } }
565+
};
566+
567+
ValidateOptionsResult result = await new AsyncOnlyOptionsValidator().ValidateAsync("AsyncOnly", valid, default);
568+
Assert.True(result.Succeeded);
569+
}
570+
571+
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
572+
public async Task TestAsyncOnlyValidatorReportsAllFailures()
573+
{
574+
AsyncOnlyOptions invalid = new()
575+
{
576+
Name = "Invalid", // trips the root async-only self-validation
577+
Age = 0, // out of [Range(1, 100)]
578+
Nested = new() { Level = 50, Id = "trigger-async", Children = new() { new AsyncChildOptions { Name = null } } }
579+
};
580+
581+
ValidateOptionsResult result = await new AsyncOnlyOptionsValidator().ValidateAsync("AsyncOnly", invalid, default);
582+
Assert.True(result.Failed);
583+
584+
// A member attribute failure, a nested member attribute failure, an enumerated-item failure, the nested
585+
// async self-validation, and the root async-only self-validation are all surfaced. This proves nested async
586+
// validation runs from an async-only root and that the async pipeline is fully wired without a synchronous
587+
// Validate method.
588+
Assert.Contains("Age: The field AsyncOnly.Age must be between 1 and 100.", result.Failures);
589+
Assert.Contains("Level: The field AsyncOnly.Nested.Level must be between 0 and 10.", result.Failures);
590+
Assert.Contains("Name: The AsyncOnly.Nested.Children[0].Name field is required.", result.Failures);
591+
Assert.Contains("Nested async self-validation failed.", result.Failures);
592+
Assert.Contains("Async-only self-validation failed.", result.Failures);
593+
}
549594
#endif // NET
550595
}
551596

@@ -856,6 +901,41 @@ public partial class SyncRootReusingNestedOptionsValidator : IValidateOptions<Sy
856901
{
857902
}
858903

904+
public class AsyncOnlyOptions : IAsyncValidatableObject
905+
{
906+
[Required]
907+
public string? Name { get; set; }
908+
909+
[Range(1, 100)]
910+
public int Age { get; set; }
911+
912+
[ValidateObjectMembers]
913+
public AsyncNestedOptions? Nested { get; set; }
914+
915+
public async IAsyncEnumerable<ValidationResult> ValidateAsync(
916+
ValidationContext validationContext,
917+
[global::System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
918+
{
919+
await Task.Yield();
920+
if (Name == "Invalid")
921+
{
922+
yield return new ValidationResult("Async-only self-validation failed.");
923+
}
924+
}
925+
926+
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
927+
{
928+
yield break;
929+
}
930+
}
931+
932+
// Option A: the validator opts into asynchronous validation only. Model discovery goes through
933+
// IAsyncValidateOptions<T>, the generator emits ValidateAsync, and it must not emit a synchronous Validate.
934+
[OptionsValidator]
935+
public partial class AsyncOnlyOptionsValidator : IAsyncValidateOptions<AsyncOnlyOptions>
936+
{
937+
}
938+
859939
public class ManualAsyncOptions
860940
{
861941
[Required]

0 commit comments

Comments
 (0)