Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.5" />
<PackageVersion Include="Microsoft.Bcl.HashCode" Version="6.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.5" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.5" />
<PackageVersion Include="Microsoft.Extensions.Primitives" Version="10.0.5" />
Expand Down
6 changes: 6 additions & 0 deletions Light.PortableResults.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@
<File Path="ai-plans\0040-4-native-aot-compatibility-for-built-in-validation-contracts.md" />
<File Path="ai-plans\0040-5-openapi-exhaustive.md" />
<File Path="ai-plans\0040-6-plan-deviations.md" />
<File Path="ai-plans\0043-0-openapi-source-generation.md" />
<File Path="ai-plans\0043-1-improve-documentation-hints.md" />
<File Path="ai-plans\0043-2-openapi-example-messages.md" />
<File Path="ai-plans\0043-3-plan-deviations.md" />
<File Path="ai-plans\AGENTS.md" />
</Folder>
<Folder Name="/benchmarks/">
Expand All @@ -81,6 +85,7 @@
<File Path="src\Directory.Build.props" />
<Project Path="src\Light.PortableResults.AspNetCore.Mvc\Light.PortableResults.AspNetCore.Mvc.csproj" />
<Project Path="src/Light.PortableResults.Validation/Light.PortableResults.Validation.csproj" />
<Project Path="src/Light.PortableResults.Validation.OpenApi.SourceGeneration/Light.PortableResults.Validation.OpenApi.SourceGeneration.csproj" />
<Project Path="src\Light.PortableResults.AspNetCore.MinimalApis\Light.PortableResults.AspNetCore.MinimalApis.csproj" />
<Project Path="src\Light.PortableResults.AspNetCore.OpenApi\Light.PortableResults.AspNetCore.OpenApi.csproj" />
<Project Path="src\Light.PortableResults.AspNetCore.Shared\Light.PortableResults.AspNetCore.Shared.csproj" />
Expand All @@ -92,6 +97,7 @@
<Project Path="tests\Light.PortableResults.AspNetCore.Mvc.Tests\Light.PortableResults.AspNetCore.Mvc.Tests.csproj" />
<Project Path="tests\Light.PortableResults.AspNetCore.OpenApi.Tests\Light.PortableResults.AspNetCore.OpenApi.Tests.csproj" />
<Project Path="tests\Light.PortableResults.Validation.OpenApi.Tests\Light.PortableResults.Validation.OpenApi.Tests.csproj" />
<Project Path="tests/Light.PortableResults.Validation.OpenApi.SourceGeneration.Tests/Light.PortableResults.Validation.OpenApi.SourceGeneration.Tests.csproj" />
<Project Path="tests/Light.PortableResults.Validation.Tests/Light.PortableResults.Validation.Tests.csproj" />
<Project Path="tests\Light.PortableResults.AspNetCore.MinimalApis.Tests\Light.PortableResults.AspNetCore.MinimalApis.Tests.csproj" />
<Project Path="tests\Light.PortableResults.AspNetCore.Shared.Tests\Light.PortableResults.AspNetCore.Shared.Tests.csproj" />
Expand Down
89 changes: 81 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public sealed class MovieRatingValidator : Validator<MovieRatingDto>
dto.Comment = context.Check(dto.Comment).HasLengthIn(10, 1000);
dto.UserName = context.Check(dto.UserName).IsNotNullOrWhiteSpace();

context.Check(dto.Rating).IsInBetween(1, 5);
context.Check(dto.Rating).IsInRange(1, 5);

// Use the checkpoint to determine if validation errors were attached to
// to the ValidationContext during this method call. The checkpoint will
Expand Down Expand Up @@ -813,7 +813,7 @@ public sealed class LightPortableResultsMovieRatingDtoValidator : Validator<Movi
{
context.Check(dto.Id).IsNotEmpty();
dto.Comment = context.Check(dto.Comment).IsNotNullOrWhiteSpace().HasLengthIn(10, 1000);
context.Check(dto.Rating).IsInBetween(1, 5);
context.Check(dto.Rating).IsInRange(1, 5);
return checkpoint.ToValidatedValue(dto);
}
}
Expand Down Expand Up @@ -929,7 +929,7 @@ public sealed class CreateMovieValidator : Validator<CreateMovieDto, Movie>
)
{
var title = context.Check(dto.Title).IsNotNullOrWhiteSpace();
context.Check(dto.ReleaseYear).IsInBetween(1888, DateTime.UtcNow.Year);
context.Check(dto.ReleaseYear).IsInRange(1888, DateTime.UtcNow.Year);
var directorName = context.Check(dto.DirectorName).IsNotNullOrWhiteSpace();

if (checkpoint.HasNewErrors)
Expand Down Expand Up @@ -995,7 +995,7 @@ public sealed class AddMovieRatingValidator : AsyncValidator<MovieRatingDto>
context.Check(dto.MovieId).IsNotEmpty();
dto.UserName = context.Check(dto.UserName).IsNotNullOrWhiteSpace();
dto.Comment = context.Check(dto.Comment).HasLengthIn(10, 1000);
context.Check(dto.Rating).IsInBetween(1, 5);
context.Check(dto.Rating).IsInRange(1, 5);

// Only hit the database if the synchronous checks passed
if (!checkpoint.HasNewErrors)
Expand Down Expand Up @@ -1075,7 +1075,7 @@ public sealed class MovieSearchService
var context = _contextFactory.CreateValidationContext();
var normalizedQuery = context.Check(query).IsNotNullOrWhiteSpace();
context.Check(page).IsGreaterThanOrEqualTo(1);
context.Check(pageSize).IsInBetween(1, 100);
context.Check(pageSize).IsInRange(1, 100);

if (context.HasErrors)
{
Expand Down Expand Up @@ -1129,7 +1129,7 @@ public sealed class AddMovieRatingValidator : AsyncValidator<MovieRatingDto>
context.Check(dto.MovieId).IsNotEmpty(shortCircuitOnError: true);
dto.UserName = context.Check(dto.UserName).IsNotNullOrWhiteSpace();
dto.Comment = context.Check(dto.Comment).HasLengthIn(10, 1000);
context.Check(dto.Rating).IsInBetween(1, 5);
context.Check(dto.Rating).IsInRange(1, 5);

if (!checkpoint.HasNewErrors)
{
Expand Down Expand Up @@ -1317,7 +1317,7 @@ public sealed class EmailSenderOptionsValidator : Validator<EmailSenderOptions>
)
{
context.Check(options.Host).IsNotNullOrWhiteSpace();
context.Check(options.Port).IsInBetween(1, 65535);
context.Check(options.Port).IsInRange(1, 65535);
context.Check(options.ApiKey).IsNotNullOrWhiteSpace();
return checkpoint.ToValidatedValue(options);
}
Expand Down Expand Up @@ -1429,7 +1429,80 @@ app.MapGet("/api/movies", GetMovies)
);
```

Comparison and range codes are polymorphic at the global code level, so the validation bridge also ships typed endpoint helpers: `WithEqualToError<T>()`, `WithNotEqualToError<T>()`, `WithGreaterThanError<T>()`, `WithGreaterThanOrEqualToError<T>()`, `WithLessThanError<T>()`, `WithLessThanOrEqualToError<T>()`, `WithInRangeError<T>()`, `WithNotInRangeError<T>()`, and `WithExclusiveRangeError<T>()`. These helpers use the existing inline metadata path, so an endpoint can document concrete metadata such as integer range boundaries for `IsInBetween(1, 5)` while still reusing global schemas for shape-fixed codes.
Comparison and range codes are polymorphic at the global code level, so the validation bridge also ships typed endpoint helpers: `WithEqualToError<T>()`, `WithNotEqualToError<T>()`, `WithGreaterThanError<T>()`, `WithGreaterThanOrEqualToError<T>()`, `WithLessThanError<T>()`, `WithLessThanOrEqualToError<T>()`, `WithInRangeError<T>()`, `WithNotInRangeError<T>()`, and `WithExclusiveRangeError<T>()`. These helpers use the existing inline metadata path, so an endpoint can document concrete metadata such as integer range boundaries for `IsInRange(1, 5)` while still reusing global schemas for shape-fixed codes.

### Validation OpenAPI source generation

`Light.PortableResults.Validation.OpenApi` also includes an opt-in source generator for Minimal API validation responses. Mark a synchronous validator with `[GeneratePortableValidationOpenApi]`, make it `partial`, and use `ProducesPortableValidationProblemFor<TValidator>(...)` on the endpoint:

```csharp
using Light.PortableResults.Validation;
using Light.PortableResults.Validation.OpenApi;

[GeneratePortableValidationOpenApi]
public sealed partial class AddMovieRatingValidator : Validator<MovieRatingDto>
{
protected override ValidatedValue<MovieRatingDto> PerformValidation(
ValidationContext context,
ValidationCheckpoint checkpoint,
MovieRatingDto dto
)
{
context.Check(dto.Id).IsNotEmpty();
context.Check(dto.Comment).HasLengthIn(10, 1000);
context.Check(dto.Rating).IsInRange(1, 5);
return checkpoint.ToValidatedValue(dto);
}
}

app.MapPut("/api/movieRatings", AddMovieRating)
.ProducesPortableValidationProblemFor<AddMovieRatingValidator>(
configure: x => x.UseFormat(ValidationProblemSerializationFormat.Rich)
);
```

The generated contract calls the same builder APIs you would write by hand, then the endpoint's `configure` callback runs afterward. This means you can still set the validation format, add manual metadata contracts, or call `AllowUnknownErrorCodes()` for errors that are outside the validator's documentable rules.

The generator analyzes top-level `context.Check(...).Rule(...)` chains in synchronous `Validator<T>` and `Validator<TSource, TValidated>` implementations. It supports built-in annotated rules, assignments that consume a checked value, explicit error hints via `[PortableValidationOpenApiErrorHint]`, and user-defined check methods annotated with `[ValidationRule]` plus optional `[ValidationErrorContract]` metadata definitions. Checks inside `if`, `switch`, loops, lambdas, local functions, `try`, or `using` blocks are skipped with a warning; lift the check to a top-level statement or add explicit hints when those errors must appear in the OpenAPI schema.

When metadata arguments are compile-time constants, such as `HasLengthIn(10, 1000)` or `IsInRange(1, 5)`, the generated contract also contributes a response-level OpenAPI example. Scalar and Swagger UI show these concrete values in the validation problem example body, including representative default messages such as `"comment must be between 10 and 1000 characters long"` and `"rating must be between 1 and 5"`. These messages are documentation examples based on the framework defaults; runtime responses can differ when applications configure validation templates, display names, target normalization, culture, or error overrides. Non-constant metadata arguments still get documented schemas and can still appear as code/target examples, but the generated message and concrete metadata values are omitted for that call site so the OpenAPI transformer uses the generic fallback message. Delegate-based `Must(...)`, `Custom(...)`, `ErrorOverrides`, async validators, source-null errors emitted before `PerformValidation`, child validators, and complex target inference are intentionally outside the first-generation analysis.

Use explicit hints when the validator emits known validation error contracts that the generator cannot infer. For an opaque `Custom(...)` path that only needs a code in the schema, add a code-only hint at the validator or `PerformValidation` method level:

```csharp
[GeneratePortableValidationOpenApi]
[PortableValidationOpenApiErrorHint("MovieAlreadyRated")]
public sealed partial class AddMovieRatingValidator : Validator<MovieRatingDto>
{
// ...
}
```

If the opaque path has endpoint-specific metadata, either point to a metadata type or declare the metadata schema inline:

```csharp
[PortableValidationOpenApiErrorHint("MovieAlreadyRated", typeof(MovieAlreadyRatedMetadata))]

[PortableValidationOpenApiErrorHint("RatingTooLow")]
[PortableValidationOpenApiErrorMetadataProperty("RatingTooLow", "lowerBoundary", typeof(int))]
[PortableValidationOpenApiErrorMetadataProperty("RatingTooLow", "upperBoundary", typeof(int))]
```

Hints compose with inferred rules. Matching schema shapes are deduplicated, while conflicting metadata shapes for the same code are reported by the generator because the emitted OpenAPI contract would otherwise be ambiguous. Hinting a code never makes the generated response non-exhaustive and never calls `AllowUnknownErrorCodes()` by itself.

You can also provide response-example entries for opaque paths. An example-only hint documents the code as code-only, so the common case does not need a separate `[PortableValidationOpenApiErrorHint]`. Use `Message` when the opaque path needs exact example text; otherwise the OpenAPI transformer writes `"Validation failed."`. Metadata values are compile-time constants declared with companion attributes:

```csharp
[PortableValidationOpenApiExampleHint(
"RatingTooLow",
Target = "rating",
Message = "rating must be at least 1"
)]
[PortableValidationOpenApiExampleMetadata("RatingTooLow", "lowerBoundary", 1)]
[PortableValidationOpenApiExampleMetadata("RatingTooLow", "upperBoundary", 5)]
```

Use `AllowUnknownErrorCodes()` only when the endpoint may emit additional codes that are not enumerable at build time. Explicit hints and `AllowUnknownErrorCodes()` compose: hints document the known contract, and the unknown-code opt-in keeps the generated schema non-exhaustive for the rest. Endpoint-level customization that is not validator-local, such as changing the validation problem format, documenting multiple example targets for the same code, or adding contracts decided outside the validator, still belongs in the endpoint `configure` callback.

Register reusable per-error-code metadata contracts once in DI by passing them to `AddPortableResultsOpenApi(...)`:

Expand Down
Loading
Loading