diff --git a/AGENTS.md b/AGENTS.md index 86f6199c80..0ee2f1c5fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,8 +45,10 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th - A validator holds only the rules declared for its type. Each has a public rule method for every member with rules (`Ensure{Member}`, `Ensure_Value` for the whole value; static unless it takes a service), a `ValidateDeclared` that runs them, and is an `IValidateMembers` (one member at a time, which a form field needs). These methods and their `[GeneratedRule]` are the **rule manifest** the generator reads from referenced assemblies (`Model/LinkReader.cs`); `Model/Resolution.cs` decides, once every model of the compilation is in, which other validators each one runs. - The rules of a base class or an interface stay in that type's validator, and the validator of every type that derives from it calls its `ValidateDeclared`; a type with no rules of its own still gets a validator when something it derives from has one. `[InheritFrom]` and `Include()` carry rules member by member (LPAD3112 where a member's rules can't be carried), and the validator of a `[Mutable]` view model validates the whole value as `T` and one member with `T`'s rule methods. Which members `[InheritFrom]` and `[Mutable]` write is decided in `src/Shared/GeneratedMembers.cs`, linked into both analyzer assemblies: the validation generator can't see what those generators write. - A `Validate` function may declare rules for a type of another assembly. Its validator (`{Type}In{Assembly}GeneratedValidator`) runs the validators the referenced assemblies have for the type and then its own rules, and the registration replaces what is registered for the type with it; `[assembly: ContributedValidator]` tells the assemblies that reference this one. LPAD3113 is an error on an asynchronous rule added to a type its own assembly validates synchronously. - - Not written yet: validators for generic types (LPAD3101), and the integrations ([#3379](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3379)). `[Mutable]`'s generator still writes its ZeroAlloc.Validation validator until that library is removed ([#3380](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3380)). - - `test/Validation.Tests` runs the generator as an application does and proves what the validators do (`test/Validation.Tests.Contracts` is the library it reads rules from across an assembly boundary, and `SdkValidationTests` in `test/Sdk.Tests` does the same from packed packages); `test/Validation.Analyzers.Tests` has the snapshots of what the generator writes and reports. + - What a transport needs is in `src/Validation` too: `ValidationFailedException` (a result with errors, which `ValidationResult.ThrowIfInvalid()` throws), `ValidationNotices` (the warnings and information of the request being handled, which a transport begins and sends with the response), `ValidationJson` (failures as JSON, written by hand), `ValidationManifest` (each validator's rules as data, which the generator writes as its `Manifest` and the registration adds) and `ObjectValidator` (validation by a type known only at run time, registered for every validated type, so a form component uses no reflection). In the manifest `each` before a rule says it is about the items of a collection and `when` that it does not always reject the value. + - The integrations are packages of their own ([#3379](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3379)), each a joint that runs after its host package's and whose types live in that package's namespaces: `src/Validation.AspNetCore` (422 `ValidationFailedProblemDetails`, the `Validation-Notices` response header, and `ValidationOpenApiSchemaTransformer`, which states the rules of the manifests), `src/Validation.Grpc` (`InvalidArgument`, with the failures in the `validation-failures-bin` trailer and the notices in `validation-notices-bin`), `src/Validation.HotChocolate` (one `VALIDATION` error for each failure, and the notices as the `validationNotices` extension) and `src/Validation.Blazor` (`LaunchPadValidator`, on .NET 11's asynchronous form validation). Each turns a `ValidationFailedException` into its transport's error shape; none validates by itself. `src/Analyzers/Api/Core/SchemaRules.cs` reads LaunchPad's rule attributes as it reads ZeroAlloc.Validation's. + - Not written yet: validators for generic types (LPAD3101), and validation in the mediator pipeline, which waits for the mediator switch to land ([#3379](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3379)): until then nothing throws `ValidationFailedException` but an application's own code. The `src/ZeroAlloc.*` packages, the SDK's detection of them and `[Mutable]`'s ZeroAlloc.Validation validator stay until that library is removed ([#3380](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3380)). + - `test/Validation.Tests` runs the generator as an application does and proves what the validators do (`test/Validation.Tests.Contracts` is the library it reads rules from across an assembly boundary, and `SdkValidationTests` in `test/Sdk.Tests` does the same from packed packages); `test/Validation.Analyzers.Tests` has the snapshots of what the generator writes and reports; `test/Validation.{AspNetCore,Grpc,HotChocolate,Blazor}.Tests` prove the integrations. - `src/Sdks/LaunchPad` is the **LaunchPad SDK** (`Rocket.Surgery.LaunchPad.Sdk`), an MSBuild SDK an application applies with an `` element in each project (`#:sdk` in a file-based app) or once in its `Directory.Build.props`. It chains `Joinery.Dovetail.Sdk` (the version `Directory.Packages.props` pins for it) and adds LaunchPad packages from what Dovetail's host detection finds and from the project's direct `PackageReference`s; `LaunchPadEnable=false` opts out. Every LaunchPad SDK also chains the **Chirograph** SDK (OpenAPI clients from `OpenApiClient` items) through `src/Sdks/LaunchPad/Sdk/Rocket.Surgery.LaunchPad.Chirograph.targets`, after the project body, unless the project applies Chirograph itself or sets `LaunchPadEnableChirograph=false`; the repository's own test projects apply `` directly, at the version `global.json` pins, which must equal the `Chirograph` `PackageVersion`. The versions are written into `Sdk/Packages.props` when the SDK is packed. `src/Sdks/Console` is the **console SDK** (`Rocket.Surgery.LaunchPad.Sdk.Console`): the same SDK for ConsoleAppFramework applications, chaining `Joinery.Dovetail.Sdk.Console`. `src/Sdks/{Web,Worker,Razor,BlazorWebAssembly,WebAssembly,WindowsDesktop}` are the **mirrors** (`Rocket.Surgery.LaunchPad.Sdk.Web`, ...): each is the Microsoft SDK of the same name with LaunchPad, chains Dovetail's mirror (`Joinery.Dovetail.Sdk.Web`, ...) and then applies `src/Sdks/Mirror/Rocket.Surgery.LaunchPad.Mirror.props`, which skips LaunchPad when a `Directory.Build.props` already applied it. Every SDK but `Rocket.Surgery.LaunchPad.Sdk` packs the shared files of `src/Sdks/LaunchPad/Sdk` beside its own `Sdk.props`/`Sdk.targets`; `src/Sdks/Directory.Build.props`/`.targets` hold the package settings and generate each `Sdk/Packages.props` from `LaunchPadChainedSdk`. `test/Sdk.Tests` packs it and builds throwaway applications against it, and `sample/Sample.Sdk` consumes it from packed packages (`dotnet msbuild build/pack.proj` there first). Like an application outside the repository, that sample and the throwaway projects of the tests stand outside central package management and name their own versions. - An operation that can fail responds with a **union response** instead of throwing ([`docs/design/union-types.md`](docs/design/union-types.md), [ADR-0005](docs/adr/0005-portable-unions-shaped-like-csharp-unions.md), [ADR-0010](docs/adr/0010-net11-only-and-native-unions.md), [ADR-0006](docs/adr/0006-union-responses-over-every-transport.md)); the generated servers answer each error case in their transport's error shape. Unions are native C# 15 unions (`public union Result(RocketModel, NotFound);`), or hand-written custom unions; LaunchPad has no union generator and no polyfill ([ADR-0010](docs/adr/0010-net11-only-and-native-unions.md)). The standard error cases (`Problem`, `NotFound` and the rest) are in Foundation. Generators detect a union by name (`UnionAttribute` or `IUnion`), take its cases from its public one-parameter constructors (implicitly declared ones included) and read it through `Value`. - Every test project runs on TUnit with Microsoft.Testing.Platform, as moved by tickets [#3050](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3050) and [#3051](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3051); `test/Directory.Build.targets` adds the TUnit, Verify.TUnit, TUnit.Mocks and TUnit.Assertions.Should packages to each of them, and there is no xunit, FakeItEasy or Shouldly anywhere. Tests assert with the Should syntax (`await x.Should().BeEqualTo(y)`), falling back to `Assert.That` only where it has no equivalent, and mock with TUnit.Mocks. A test that resolves services from a populated service collection derives from `ContainerTest` (`test/Shared/ContainerTest.cs`, linked into the projects that use it). The same file gives every test project `Joinery.Dovetail` and Specular, so a test gets the joints and the Specular scan results of the projects it references. Shared test code (the web app fixtures and fake time) lives in the non-packable `test/TestSupport` project. A test creates scopes directly with `CreateScope()` / `CreateAsyncScope()`. diff --git a/LaunchPad.slnx b/LaunchPad.slnx index 71c2f1383a..837b5de7a6 100644 --- a/LaunchPad.slnx +++ b/LaunchPad.slnx @@ -90,6 +90,10 @@ + + + + @@ -144,6 +148,10 @@ + + + + diff --git a/Readme.md b/Readme.md index 350b2ef839..2e773d548b 100644 --- a/Readme.md +++ b/Readme.md @@ -90,10 +90,14 @@ lists what the SDK adds for each technology. ### Validation -| Package | NuGet | What it does | -| ----------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Rocket.Surgery.LaunchPad.Validation | not published yet | LaunchPad's own validation, in progress ([#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)): rule attributes and `System.ComponentModel.DataAnnotations` compiled into one generated validator per type | -| Rocket.Surgery.LaunchPad.Validation.Analyzers | not published yet | The validator generator, analyzers and code fixes Validation depends on | +| Package | NuGet | What it does | +| ------------------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Rocket.Surgery.LaunchPad.Validation | not published yet | LaunchPad's own validation, in progress ([#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)): rule attributes, `System.ComponentModel.DataAnnotations` and `Validate` functions compiled into one generated validator per type | +| Rocket.Surgery.LaunchPad.Validation.Analyzers | not published yet | The validator generator, analyzers and code fixes Validation depends on | +| Rocket.Surgery.LaunchPad.Validation.AspNetCore | not published yet | Validation failures as 422 problem details with codes and placeholder values, warnings in a response header, and the rules in OpenAPI | +| Rocket.Surgery.LaunchPad.Validation.Grpc | not published yet | Validation failures as `InvalidArgument` with the failures in a trailer, and warnings in a trailer of successful calls | +| Rocket.Surgery.LaunchPad.Validation.HotChocolate | not published yet | Validation failures as GraphQL `VALIDATION` errors, and warnings as an extension of the result | +| Rocket.Surgery.LaunchPad.Validation.Blazor | not published yet | A `LaunchPadValidator` component: a form's fields validated one at a time, asynchronously where a rule waits, and the whole model on submit | ## Contributing diff --git a/docs/design/validation.md b/docs/design/validation.md index 7c01e19a97..86b9c47c80 100644 --- a/docs/design/validation.md +++ b/docs/design/validation.md @@ -177,6 +177,13 @@ Where the code so far differs from the text above: - **Generic types** with rules are an error (LPAD3101) for now. - **LPAD3001** looks only at types that have rules themselves: a type with no rules and a member whose type has them is not reported. +- **A rejected value is an exception at the transport**: `ValidationFailedException`, which carries the result and which `ValidationResult.ThrowIfInvalid()` throws. Each integration turns it into its transport's error shape, as the ZeroAlloc packages did with that library's exception; none validates by itself. What throws it for a request is the mediator pipeline, which is not written: it waits for the mediator switch (phase 5, still open). +- **Failures on the wire** carry `path`, `code`, `message`, `severity` and `arguments`, the values of the message's placeholders as text (a number or a date in its invariant form, so a JSON context needs no entry for each type). Over HTTP: a 422 `ValidationFailedProblemDetails` with `errors` by path and `notices` for what came with them. Over gRPC: `InvalidArgument`, the errors in the status detail and every failure as JSON in the `validation-failures-bin` trailer (a path is not a valid metadata key, and a message need not be ASCII). In GraphQL: one `VALIDATION` error for each failure, with `propertyName`, `errorCode`, `severity` and `arguments` as extensions. +- **Warnings on successful responses** go through `ValidationNotices`: whatever validates a request adds what did not reject it, and the transport sends it. A transport begins the notices before the request is handled and they are ambient from there (an `AsyncLocal`), registered scoped as the ones of the request being handled: a GraphQL resolver runs in a scope of its own, and a scoped service alone would never reach the response. They travel as the `Validation-Notices` response header over HTTP (a JSON array), the `validation-notices-bin` trailer over gRPC, and the `validationNotices` extension of a GraphQL result. +- **OpenAPI at run time** reads `ValidationManifest`, the rules of each validated type as data: the generator writes one as the validator's `Manifest` (with the rules of what the type derives from) and the registration adds it. `ValidationOpenApiSchemaTransformer` states the rules of a schema property from the member System.Text.Json serializes it from, whichever way the rule was declared. In the manifest a rule under a condition, a warning, and a rule about a member of a collection's item start with `when` and are left out; a rule about the items of a collection starts with `each` and goes to the `items` schema. +- **OpenAPI at build time** (the API generators, `SchemaRules`) reads LaunchPad's rule attributes from the request's members, beside ZeroAlloc.Validation's until that goes. It can't read the manifest of a type in the same compilation, which another generator writes, so the rules of a `Validate` function reach the document only through the transformer above. +- **Blazor** uses the asynchronous form validation .NET 11 added: `LaunchPadValidator` validates a field that changes with `IValidateMembers`, at once when its rules are synchronous and otherwise as `EditContext.RegisterAsyncFieldValidator`, so `IsValidationPending` is the pending state and a later change cancels an earlier one; `EditContext.ValidateAsync` awaits the whole model, and `Validate` throws for a model with a rule that waits, as the form does for any asynchronous validator. The validator is found by the model's run-time type through `ObjectValidators`, which the generated registrations fill in, with no reflection. A failure of a nested member is shown on the path's field of the top model, so it is in the summary and not beside the nested input. + ## Tech stack - .NET 11, C# 15, `$(LaunchPadTargetFrameworks)`; the analyzer package targets `netstandard2.0`. diff --git a/src/Analyzers/Api/Core/SchemaRules.cs b/src/Analyzers/Api/Core/SchemaRules.cs index ad2e86e473..10d2bc75a3 100644 --- a/src/Analyzers/Api/Core/SchemaRules.cs +++ b/src/Analyzers/Api/Core/SchemaRules.cs @@ -5,8 +5,9 @@ namespace Rocket.Surgery.LaunchPad.Analyzers.Api.Core; /// -/// Reads a member's ZeroAlloc.Validation rules at compile time and says how its OpenAPI schema states them. The rules are attributes with -/// constant arguments, so no validator is looked up when the document is built. +/// Reads a member's validation rules at compile time and says how its OpenAPI schema states them: the rule attributes of LaunchPad's +/// validation (Rocket.Surgery.LaunchPad.Validation.Rules) and, until that library goes, of ZeroAlloc.Validation. The rules are +/// attributes with constant arguments, so no validator is looked up when the document is built. /// /// /// @@ -20,16 +21,33 @@ namespace Rocket.Surgery.LaunchPad.Analyzers.Api.Core; /// [Equal], [NotEqual], [Null], [Empty]), and any rule with When or Unless, which holds only /// sometimes. /// +/// +/// LaunchPad's attributes say the same, by the same names, and [Url] the uri format. Left out of those: a rule that is +/// a warning or information (Severity), which does not reject the value, and a comparison with another member +/// (Member). The rules a Validate function declares are not attributes: this generator can't see the validator +/// another generator writes, so they reach a document only through the schema transformer of +/// Rocket.Surgery.LaunchPad.Validation.AspNetCore, which reads the rule manifest at run time. +/// /// internal static class SchemaRules { private const string Namespace = "ZeroAlloc.Validation"; + private const string LaunchPadNamespace = "Rocket.Surgery.LaunchPad.Validation.Rules"; public static EquatableArray Read(ImmutableArray attributes) { var rules = new List(); foreach (var attribute in attributes) { + if (attribute.AttributeClass is { } rule && rule.ContainingNamespace?.ToDisplayString() == LaunchPadNamespace) + { + if (attribute.AttributeConstructor is null) continue; + // A warning doesn't reject the value, and a comparison with another member has no constant to state. + if (attribute.NamedArguments.Any(a => ( a.Key == "Severity" && a.Value.Value is int and not 0 ) || ( a.Key == "Member" && a.Value.Value is string ))) continue; + rules.AddRange(LaunchPadRules(rule.Name, attribute.ConstructorArguments)); + continue; + } + if (attribute.AttributeClass is not { } type || type.ContainingNamespace?.ToDisplayString() != Namespace) continue; // An attribute whose constructor didn't bind (ZeroAlloc.Validation not referenced) has no arguments to read. if (attribute.AttributeConstructor is null) continue; @@ -95,6 +113,31 @@ private static IEnumerable Rules(string name, ImmutableArray LaunchPadRules(string name, ImmutableArray arguments) + { + switch (name) + { + case "UrlAttribute": + yield return Rule("Format", "uri"); + break; + case "InclusiveBetweenAttribute" or "ExclusiveBetweenAttribute" when !IsNumber(arguments, 0) || !IsNumber(arguments, 1): + case "GreaterThanOrEqualToAttribute" or "GreaterThanAttribute" or "LessThanOrEqualToAttribute" or "LessThanAttribute" when !IsNumber(arguments, 0): + case "IsEnumNameAttribute": + break; + default: + foreach (var rule in Rules(name, arguments)) + { + yield return rule; + } + + break; + } + } + + private static bool IsNumber(ImmutableArray arguments, int index) => + arguments.Length > index && arguments[index] is { Kind: TypedConstantKind.Primitive, Value: not ( null or string or bool or char ) }; + private static SchemaRuleModel Rule(string method, params string[] arguments) => new(method, arguments.ToEquatableArray()); // Lengths are ints and bounds doubles; both are written as the invariant round-trip text the schema keeps (Microsoft.OpenApi stores bounds diff --git a/src/Validation.Analyzers/Model/FunctionReader.cs b/src/Validation.Analyzers/Model/FunctionReader.cs index 8d8e8b9e78..38a7fd4d73 100644 --- a/src/Validation.Analyzers/Model/FunctionReader.cs +++ b/src/Validation.Analyzers/Model/FunctionReader.cs @@ -89,6 +89,7 @@ private sealed class RuleBuilder public string Severity { get; set; } = "Error"; public List<(string Name, string Expression)> Placeholders { get; } = []; public List Conditions { get; } = []; + public string Manifest { get; set; } = ""; } private void Report(DiagnosticDescriptor descriptor, SyntaxNode? node, params string[] arguments) => @@ -416,7 +417,6 @@ private void ReadEach(ExpressionSyntax selector, ExpressionSyntax rules, Scope s ReadBody(lambda, new(itemBuilder, present, item, scope.Conditions, into, indent + " ")); Line(into, indent + " }"); WriteLoopEnd(into, indent, n); - into.Manifest.Add("EnsureEach"); } private string Local() @@ -496,10 +496,10 @@ private void ReadChain(string member, ITypeSymbol memberType, List 0 || scope.Conditions.Count > 0 || rule.Severity != "Error" || ( scope.Into is not null && member.Length > 0 ); + into.Manifest.Add(( forEach ? "each " : "" ) + ( sometimes ? "when " : "" ) + rule.Manifest); + } + Write(into, scope, member, displayName, each ? "" : member, value, functions, rules, stop, each, n, each ? ValueOf(member, scope) : ""); } @@ -718,8 +727,8 @@ string value } if (bound.IsAsync) into.IsAsync = true; + rule.Manifest = manifest.Count == 0 ? bound.Code : bound.Code + "(" + string.Join(", ", manifest) + ")"; rules.Add(rule); - into.Manifest.Add(manifest.Count == 0 ? bound.Code : bound.Code + "(" + string.Join(", ", manifest) + ")"); } private static string Arguments(RuleBuilder rule) => diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs index 4dc8dc4174..2defbb3085 100644 --- a/src/Validation.Analyzers/Model/RuleReader.cs +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -497,6 +497,9 @@ private static RuleModel Finish(AttributeData attribute, RuleModel rule, IReadOn rule = rule with { Severity = severity switch { 1 => "Warning", 2 => "Info", _ => "Error", }, }; } + // A warning doesn't reject the value: the manifest says so, and a schema leaves the rule out. + if (rule.Severity != "Error") rule = rule with { Manifest = "when " + rule.Manifest, }; + // A DataAnnotations message numbers its placeholders: the member's name, then the attribute's arguments. if (Named(attribute, "ErrorMessage") is { Value: string errorMessage }) { diff --git a/src/Validation.Analyzers/ValidatorEmitter.cs b/src/Validation.Analyzers/ValidatorEmitter.cs index 442b9e676a..eba4fa68b3 100644 --- a/src/Validation.Analyzers/ValidatorEmitter.cs +++ b/src/Validation.Analyzers/ValidatorEmitter.cs @@ -233,6 +233,7 @@ public static string Validator(MergedModel model, CompilationModel compilation) Line(" }"); WriteMembers(context, Line); + WriteManifest(model, Line); if (options) { @@ -312,6 +313,57 @@ private static string Call(string receiver, SourceMemberRef member, string insta : $"{method}({list}, ref sink);"; } + // The rules of each member as data, with those of everything the type is: what describes the type where nothing is validated. + private static void WriteManifest(MergedModel model, Action line) + { + var members = new List<(string Member, List Rules)>(); + void Add(string member, IEnumerable rules) + { + if (member.Length == 0) return; + foreach (var (Member, Rules) in members) + { + if (Member != member) continue; + Rules.AddRange(rules); + return; + } + + members.Add((member, [.. rules,])); + } + + foreach (var source in model.Sources) + { + foreach (var member in source.Members) + { + Add(member.Member, member.Rules); + } + } + + foreach (var call in model.MutableMembers.OrderBy(static z => z.Key, StringComparer.Ordinal).SelectMany(static z => z.Value)) + { + Add(call.Member.Member, call.Member.Rules); + } + + foreach (var member in model.Resolved) + { + Add(member.Name, member.Rules); + } + + line(""); + line(" /// "); + line(" /// The rules of each member, as data."); + line(" /// "); + line(" " + Never); + line($" public static {Runtime}.ValidationManifest Manifest {{ get; }} = new("); + line($" typeof({model.Target.Type}){( members.Count == 0 ? "" : "," )}"); + for (var i = 0; i < members.Count; i++) + { + var (member, rules) = members[i]; + line($" new {Runtime}.ValidatedMember({Literal(member)}{Literals(rules)}){( i == members.Count - 1 ? "" : "," )}"); + } + + line(" );"); + } + // IValidateMembers: the rules of one member, wherever they are declared. private static void WriteMembers(Context context, Action line) { @@ -700,6 +752,8 @@ public static string Registration(IReadOnlyList models, Compilation sb.AppendLine($" {registration}(services);"); } + sb.AppendLine($" {extensions}.TryAddSingleton<{Runtime}.ObjectValidators>(services);"); + foreach (var model in models) { var target = model.Target; @@ -743,6 +797,8 @@ public static string Registration(IReadOnlyList models, Compilation } sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateMembers<{target.Type}>>(services, static provider => ({Runtime}.IValidateMembers<{target.Type}>)provider.GetService(typeof({Runtime}.IValidateAsync<{target.Type}>))!);"); + sb.AppendLine($" global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, {validator}.Manifest);"); + sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<{Runtime}.ObjectValidator, {Runtime}.ObjectValidator<{target.Type}>>());"); if (!model.IsAsync && compilation.HasOptions && target.IsReferenceType && !model.IsScoped) { sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<{optionsOf}, {validator}>());"); @@ -758,6 +814,8 @@ public static string Registration(IReadOnlyList models, Compilation private static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true); + private static string Literals(List values) => string.Concat(values.Select(static z => ", " + Literal(z))); + private static string Arguments(RuleModel rule) => string.Concat(rule.Arguments.Select(static z => $", {Sink}.Argument({Literal(z.Name)}, {z.Expression})")); private static string Manifest(ContributedMemberModel member) => string.Concat(member.Manifest.Select(static z => ", " + Literal(z))); diff --git a/src/Validation.AspNetCore/Joints/ValidationOpenApiJoint.cs b/src/Validation.AspNetCore/Joints/ValidationOpenApiJoint.cs new file mode 100644 index 0000000000..1694768fe6 --- /dev/null +++ b/src/Validation.AspNetCore/Joints/ValidationOpenApiJoint.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.OpenApi; +using Microsoft.Extensions.DependencyInjection; + +using Rocket.Surgery.LaunchPad.AspNetCore.OpenApi; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Joints; + +/// +/// Adds the to every OpenAPI document, so the rules of LaunchPad's validators show +/// in the schemas. +/// Implements the +/// +/// +/// Runs after the , which registers the OpenAPI document generation. +/// +/// +/// +[PublicAPI] +[DovetailExport] +[AfterJoint] +[DovetailCategory(DovetailCategory.Application)] +public class ValidationOpenApiJoint : IServiceJoint +{ + /// + public void Register(IDovetailContext context, IServiceCollection services) => + services.ConfigureAll(options => options.AddSchemaTransformer()); +} diff --git a/src/Validation.AspNetCore/Joints/ValidationProblemDetailsJoint.cs b/src/Validation.AspNetCore/Joints/ValidationProblemDetailsJoint.cs new file mode 100644 index 0000000000..24fd6d15a3 --- /dev/null +++ b/src/Validation.AspNetCore/Joints/ValidationProblemDetailsJoint.cs @@ -0,0 +1,76 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; + +using Rocket.Surgery.LaunchPad.AspNetCore.Validation; +using Rocket.Surgery.LaunchPad.Foundation; +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Joints; + +/// +/// Turns a into a 422 with , for controllers and +/// for the exception handler alike, and sends the warnings of a request that was accepted () in a +/// header of its response. +/// Implements the +/// +/// +/// Runs after the , so the status code selector it configures is kept for every other exception. +/// +/// +/// +[PublicAPI] +[DovetailExport] +[AfterJoint] +[DovetailCategory(DovetailCategory.Application)] +public class ValidationProblemDetailsJoint : IServiceJoint +{ + /// + public void Register(IDovetailContext context, IServiceCollection services) + { + services.AddJsonTypeInfoResolver(ValidationFailedJsonContext.Default, JsonTypeInfoResolverRegistration.LibraryOrder); + services.AddExceptionHandler( + options => + { + var previous = options.StatusCodeSelector; + options.StatusCodeSelector = exception => exception is ValidationFailedException + ? StatusCodes.Status422UnprocessableEntity + : previous?.Invoke(exception) ?? StatusCodes.Status500InternalServerError; + } + ); + services.TryAddScoped(static _ => ValidationNotices.Current ?? new ValidationNotices()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.Configure(options => options.Filters.Insert(0, new ValidationFailedExceptionFilter())); + } + + internal sealed class ValidationFailedExceptionFilter : IExceptionFilter + { + public void OnException(ExceptionContext context) + { + if (context.Exception is not ValidationFailedException exception) return; + context.ExceptionHandled = true; + context.Result = new UnprocessableEntityObjectResult(ValidationFailedProblemDetails.From(exception)); + } + } + + internal sealed class ValidationFailedProblemDetailsWriter : IProblemDetailsWriter + { + public bool CanWrite(ProblemDetailsContext context) => context.Exception is ValidationFailedException; + + public ValueTask WriteAsync(ProblemDetailsContext context) + { + var details = ValidationFailedProblemDetails.From((ValidationFailedException)context.Exception!); + details.Instance = context.ProblemDetails.Instance; + details.Extensions = context.ProblemDetails.Extensions; + context.HttpContext.Response.StatusCode = StatusCodes.Status422UnprocessableEntity; + var options = context.HttpContext.RequestServices.GetRequiredService>().Value.SerializerOptions; + var typeInfo = options.GetTypeInfo(); + return new(context.HttpContext.Response.WriteAsJsonAsync(details, typeInfo, contentType: "application/problem+json")); + } + } +} diff --git a/src/Validation.AspNetCore/OpenApi/ValidationOpenApiSchemaTransformer.cs b/src/Validation.AspNetCore/OpenApi/ValidationOpenApiSchemaTransformer.cs new file mode 100644 index 0000000000..c0d4a8b41d --- /dev/null +++ b/src/Validation.AspNetCore/OpenApi/ValidationOpenApiSchemaTransformer.cs @@ -0,0 +1,177 @@ +using System.Globalization; +using System.Reflection; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; + +using Rocket.Surgery.LaunchPad.AspNetCore.Validation; +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.OpenApi; + +/// +/// Describes the rules of a type's members in its OpenAPI schema: required members, lengths, ranges, patterns, e-mail addresses and +/// URLs. It also marks the members of the problem details LaunchPad writes as required: the type and title, and the errors of a +/// validation problem. +/// +/// +/// The rules come from the the generator writes for every validated type, whichever way they were +/// declared: attributes, a Validate function, a base class, an interface, [InheritFrom]. A schema property is matched +/// to its member through the member System.Text.Json serializes it from. Rules a schema can't state (Must, a comparison with +/// another member, a rule under a condition, a warning) are left out. +/// +/// The manifests of the validated types, which the generated registrations add to the services. +[PublicAPI] +public sealed class ValidationOpenApiSchemaTransformer(IEnumerable manifests) : IOpenApiSchemaTransformer +{ + private readonly Dictionary _manifests = Index(manifests); + + /// + public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(schema); + ArgumentNullException.ThrowIfNull(context); + // Microsoft.OpenApi leaves the properties of a schema that has none (a scalar, an array) null. + if (schema.Properties is not { Count: > 0 } properties) return Task.CompletedTask; + + RequireProblemDetailsMembers(schema, context.JsonTypeInfo.Type); + if (!_manifests.TryGetValue(context.JsonTypeInfo.Type, out var manifest)) return Task.CompletedTask; + + foreach (var jsonProperty in context.JsonTypeInfo.Properties) + { + if (jsonProperty.AttributeProvider is not MemberInfo member) continue; + if (!properties.TryGetValue(jsonProperty.Name, out var value) || value is not OpenApiSchema property) continue; + foreach (var validated in manifest.Members) + { + if (validated.Name != member.Name) continue; + foreach (var rule in validated.Rules) + { + if (rule.IsConditional) continue; + if (!rule.ForEachItem) + { + Apply(schema, jsonProperty.Name, property, rule); + } + else if (property.Items is OpenApiSchema items) + { + Apply(null, jsonProperty.Name, items, rule); + } + } + } + } + + return Task.CompletedTask; + } + + private static Dictionary Index(IEnumerable manifests) + { + ArgumentNullException.ThrowIfNull(manifests); + var byType = new Dictionary(); + foreach (var manifest in manifests) + { + // The last one registered for a type is that of the assembly that composes the others. + byType[manifest.Type] = manifest; + } + + return byType; + } + + private static void Apply(OpenApiSchema? schema, string name, OpenApiSchema property, ValidatedRule rule) + { + var isArray = property.Type is { } type && type.HasFlag(JsonSchemaType.Array); + var isString = property.Type is { } stringType && stringType.HasFlag(JsonSchemaType.String); + switch (rule.Name) + { + case "NotNull": + Require(schema, name); + break; + case "NotEmpty": + Require(schema, name); + if (isArray) property.MinItems ??= 1; + else if (isString) property.MinLength ??= 1; + break; + case "MinLength" when rule.TryGetNumber(0, out var minimum): + SetMinimumLength(property, isArray, (int)minimum); + break; + case "MaxLength" when rule.TryGetNumber(0, out var maximum): + SetMaximumLength(property, isArray, (int)maximum); + break; + case "Length" when rule.TryGetNumber(0, out var shortest) && rule.TryGetNumber(1, out var longest): + SetMinimumLength(property, isArray, (int)shortest); + SetMaximumLength(property, isArray, (int)longest); + break; + case "InclusiveBetween" when rule.TryGetNumber(0, out var from) && rule.TryGetNumber(1, out var to): + property.Minimum = Number(from); + property.Maximum = Number(to); + break; + case "ExclusiveBetween" when rule.TryGetNumber(0, out var above) && rule.TryGetNumber(1, out var below): + property.ExclusiveMinimum = Number(above); + property.ExclusiveMaximum = Number(below); + break; + case "GreaterThanOrEqualTo" when rule.TryGetNumber(0, out var atLeast): + property.Minimum = Number(atLeast); + break; + case "GreaterThan" when rule.TryGetNumber(0, out var moreThan): + property.ExclusiveMinimum = Number(moreThan); + break; + case "LessThanOrEqualTo" when rule.TryGetNumber(0, out var atMost): + property.Maximum = Number(atMost); + break; + case "LessThan" when rule.TryGetNumber(0, out var lessThan): + property.ExclusiveMaximum = Number(lessThan); + break; + case "Matches" when rule.TryGetText(0, out var pattern): + property.Pattern = pattern; + break; + case "EmailAddress": + property.Format = "email"; + break; + case "Url": + property.Format = "uri"; + break; + default: + break; + } + } + + // The problem details LaunchPad writes always have a type and a title, and the validation ones their errors. + private static void RequireProblemDetailsMembers(OpenApiSchema schema, Type type) + { + if (!typeof(ProblemDetails).IsAssignableFrom(type)) return; + RequireIfPresent(schema, "type"); + RequireIfPresent(schema, "title"); + if (typeof(HttpValidationProblemDetails).IsAssignableFrom(type) || typeof(ValidationFailedProblemDetails).IsAssignableFrom(type)) + RequireIfPresent(schema, "errors"); + } + + private static void RequireIfPresent(OpenApiSchema schema, string name) + { + if (schema.Properties?.ContainsKey(name) == true) Require(schema, name); + } + + // The schema of a collection's items has no members to require. + private static void Require(OpenApiSchema? schema, string name) + { + if (schema is null) return; + schema.Required ??= new HashSet(StringComparer.Ordinal); + schema.Required.Add(name); + } + + private static void SetMinimumLength(OpenApiSchema property, bool isArray, int value) + { + if (value <= 0) return; + if (isArray) property.MinItems = value; + else property.MinLength = value; + } + + private static void SetMaximumLength(OpenApiSchema property, bool isArray, int value) + { + if (value is <= 0 or int.MaxValue) return; + if (isArray) property.MaxItems = value; + else property.MaxLength = value; + } + + // OpenAPI 3.1 (JSON Schema): exclusiveMinimum and exclusiveMaximum are numbers, not flags. + private static string Number(double value) => value.ToString("R", CultureInfo.InvariantCulture); +} diff --git a/src/Validation.AspNetCore/Rocket.Surgery.LaunchPad.Validation.AspNetCore.csproj b/src/Validation.AspNetCore/Rocket.Surgery.LaunchPad.Validation.AspNetCore.csproj new file mode 100644 index 0000000000..a2cb43f399 --- /dev/null +++ b/src/Validation.AspNetCore/Rocket.Surgery.LaunchPad.Validation.AspNetCore.csproj @@ -0,0 +1,29 @@ + + + $(LaunchPadTargetFrameworks) + LaunchPad's validation for ASP.NET Core applications: a rejected request answers 422 with problem details that list the failures by path, with their codes and placeholder values; warnings travel on successful responses; and the rules show in the OpenAPI schemas. + $(PackageTags);dovetail;validation;aspnetcore;problem-details;openapi + + Rocket.Surgery.LaunchPad.AspNetCore + ValidationExports + false + + + + + + + + + + + + + + + + + diff --git a/src/Validation.AspNetCore/Validation/ValidationFailedJsonContext.cs b/src/Validation.AspNetCore/Validation/ValidationFailedJsonContext.cs new file mode 100644 index 0000000000..0903874afa --- /dev/null +++ b/src/Validation.AspNetCore/Validation/ValidationFailedJsonContext.cs @@ -0,0 +1,10 @@ +using System.Text.Json.Serialization; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Validation; + +/// +/// The metadata of the problem details this package writes, so they serialize without reflection. The +/// ValidationProblemDetailsJoint chains it behind the application's own resolvers. +/// +[JsonSerializable(typeof(ValidationFailedProblemDetails))] +internal sealed partial class ValidationFailedJsonContext : JsonSerializerContext; diff --git a/src/Validation.AspNetCore/Validation/ValidationFailedProblemDetails.cs b/src/Validation.AspNetCore/Validation/ValidationFailedProblemDetails.cs new file mode 100644 index 0000000000..17e15d5dc9 --- /dev/null +++ b/src/Validation.AspNetCore/Validation/ValidationFailedProblemDetails.cs @@ -0,0 +1,79 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Validation; + +/// +/// The problem details for a request LaunchPad's validators rejected: the errors grouped by the path of the member they are about, +/// and the warnings and information that came with them. +/// +[PublicAPI] +public class ValidationFailedProblemDetails : ProblemDetails +{ + /// + /// Creates the problem details for the result of a . + /// + /// The exception. + /// The problem details. + public static ValidationFailedProblemDetails From(ValidationFailedException exception) + { + ArgumentNullException.ThrowIfNull(exception); + return From(exception.Result); + } + + /// + /// Creates the problem details for a result. + /// + /// The result of a validation. + /// The problem details. + public static ValidationFailedProblemDetails From(ValidationResult result) => new() + { + Status = StatusCodes.Status422UnprocessableEntity, + Title = "One or more validation errors occurred.", + Errors = result + .Errors.GroupBy(static failure => failure.Path, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.Select(ValidationFailureDetail.From).ToArray(), StringComparer.Ordinal), + Notices = [.. result.Failures.Where(static failure => failure.Severity != ValidationSeverity.Error).Select(ValidationFailureDetail.From),], + }; + + /// + /// The errors, by the path of the member each is about (empty for the request as a whole). + /// + public IDictionary Errors { get; init; } = new Dictionary(StringComparer.Ordinal); + + /// + /// The warnings and the information: what the validators had to say that did not reject the request. + /// + public ValidationFailureDetail[] Notices { get; init; } = []; +} + +/// +/// One rule a request did not meet. +/// +/// The member the rule is about, from the request: Stages[2].Thrust. +/// The rule's code, which stays the same whatever the message says. +/// The message. +/// How serious it is: Error, Warning or Info. +/// The values of the message's placeholders, as text, for a client that writes the message itself. +[PublicAPI] +public record ValidationFailureDetail(string Path, string Code, string Message, string Severity, IDictionary Arguments) +{ + /// + /// Creates the detail of a failure. + /// + /// The failure. + /// The detail. + public static ValidationFailureDetail From(ValidationFailure failure) + { + ArgumentNullException.ThrowIfNull(failure); + var arguments = new Dictionary(StringComparer.Ordinal); + foreach (var argument in failure.Arguments) + { + arguments[argument.Key] = ValidationJson.Format(argument.Value); + } + + return new(failure.Path, failure.Code, failure.Message, failure.Severity.ToString(), arguments); + } +} diff --git a/src/Validation.AspNetCore/Validation/ValidationNoticesStartupFilter.cs b/src/Validation.AspNetCore/Validation/ValidationNoticesStartupFilter.cs new file mode 100644 index 0000000000..b7c9fb9a0a --- /dev/null +++ b/src/Validation.AspNetCore/Validation/ValidationNoticesStartupFilter.cs @@ -0,0 +1,38 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Validation; + +/// +/// Sends the warnings and information the validators of a request gathered () with its response, in +/// the header: a JSON array of failures, as writes them. +/// +internal sealed class ValidationNoticesStartupFilter : IStartupFilter +{ + /// The response header the notices are sent in. + public const string HeaderName = "Validation-Notices"; + + public Action Configure(Action next) => app => + { + app.Use( + static async (context, next) => + { + var notices = ValidationNotices.Current ?? ValidationNotices.Begin(); + context.Response.OnStarting( + static state => + { + var (context, notices) = ((HttpContext, ValidationNotices))state; + if (!notices.IsEmpty) context.Response.Headers[HeaderName] = ValidationJson.ToText(notices.ToList()); + return Task.CompletedTask; + }, + (context, notices) + ); + await next(context).ConfigureAwait(false); + } + ); + next(app); + }; +} diff --git a/src/Validation.Blazor/LaunchPadValidator.cs b/src/Validation.Blazor/LaunchPadValidator.cs new file mode 100644 index 0000000000..1a37c52aff --- /dev/null +++ b/src/Validation.Blazor/LaunchPadValidator.cs @@ -0,0 +1,144 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.AspNetCore.Blazor; + +/// +/// Validates the model of the surrounding with the validator LaunchPad generated for it, and reports the +/// failures through the form's so the validation summary and messages show them. +/// +/// +/// +/// A field is validated when it changes, with the rules of that member alone (): at once when +/// they are synchronous, and otherwise as an asynchronous field validation of the form +/// (), so +/// is for the field until its rules have run, and a later change cancels an earlier one. The view model +/// of a [Mutable] type is validated this way with the rules of the type it is of, without making one. +/// +/// +/// The whole model is validated when the form asks. , which a form's submit uses, +/// awaits the rules that wait. can't: for a model with such a rule the form throws, as it +/// does for any asynchronous validator. +/// +/// +/// The validator is found by the model's type among those the generated Add...Validators methods registered +/// (), with no reflection. A model without one is an error. A failure is shown on the field its +/// path names; warnings and information are shown as messages too. +/// +/// +[PublicAPI] +public sealed class LaunchPadValidator : ComponentBase, IDisposable +{ + private EditContext? _editContext; + private ValidationMessageStore? _messages; + private ObjectValidator? _validator; + + [CascadingParameter] + private EditContext? CurrentEditContext { get; set; } + + [Inject] + private IServiceProvider Services { get; set; } = null!; + + [Inject] + private ObjectValidators Validators { get; set; } = null!; + + /// + public void Dispose() => Detach(); + + /// + protected override void OnParametersSet() + { + if (ReferenceEquals(CurrentEditContext, _editContext)) return; + Detach(); + _editContext = CurrentEditContext ?? throw new InvalidOperationException($"{nameof(LaunchPadValidator)} must be placed inside an {nameof(EditForm)}."); + _messages = new(_editContext); + _validator = null; + _editContext.OnValidationRequested += OnValidationRequested; + _editContext.OnFieldChanged += OnFieldChanged; + } + + private void Detach() + { + if (_editContext is null) return; + _editContext.OnValidationRequested -= OnValidationRequested; + _editContext.OnFieldChanged -= OnFieldChanged; + _editContext = null; + } + + private ObjectValidator Validator(EditContext context) => + _validator ??= Validators.Find(context.Model.GetType()) + ?? throw new InvalidOperationException( + $"No validator is registered for {context.Model.GetType()}: it has no rules, or the Add...Validators method of its assembly was not called." + ); + + private void OnValidationRequested(object? sender, ValidationRequestedEventArgs e) + { + var context = _editContext!; + var validator = Validator(context); + if (validator.TryValidate(Services, context.Model, out var result)) + { + Report(context, result); + return; + } + + // A rule of the model waits. The form awaits it in ValidateAsync, and refuses it in Validate, as it does any asynchronous validator. + e.AddAsyncValidator(cancellationToken => ValidateModel(context, validator, cancellationToken)); + } + + private async Task ValidateModel(EditContext context, ObjectValidator validator, CancellationToken cancellationToken) + { + var result = await validator.ValidateAsync(Services, context.Model, cancellationToken).ConfigureAwait(true); + cancellationToken.ThrowIfCancellationRequested(); + if (ReferenceEquals(context, _editContext)) Report(context, result); + } + + // Every failure of the model replaces what was shown before. + private void Report(EditContext context, ValidationResult result) + { + _messages!.Clear(); + foreach (var failure in result.Failures) + { + _messages.Add(context.Field(failure.Path), failure.Message); + } + + context.NotifyValidationStateChanged(); + } + + private void OnFieldChanged(object? sender, FieldChangedEventArgs e) + { + var context = _editContext!; + var field = e.FieldIdentifier; + // A field of another object (a nested model) is validated with the whole model. + if (!ReferenceEquals(field.Model, context.Model)) return; + + var validator = Validator(context); + if (validator.TryValidateMember(Services, context.Model, field.FieldName, out var result)) + { + Report(context, field, result); + return; + } + + context.RegisterAsyncFieldValidator(field, cancellationToken => ValidateField(context, validator, field, cancellationToken)); + } + + private async Task ValidateField(EditContext context, ObjectValidator validator, FieldIdentifier field, CancellationToken cancellationToken) + { + var result = await validator.ValidateMemberAsync(Services, context.Model, field.FieldName, cancellationToken).ConfigureAwait(true); + // The field changed again, or the form went away, while its rules ran: a later validation answers for it. + cancellationToken.ThrowIfCancellationRequested(); + if (ReferenceEquals(context, _editContext)) Report(context, field, result); + } + + private void Report(EditContext context, in FieldIdentifier field, ValidationResult result) + { + _messages!.Clear(field); + foreach (var failure in result.Failures) + { + _messages.Add(field, failure.Message); + } + + context.NotifyValidationStateChanged(); + } +} diff --git a/src/Validation.Blazor/Rocket.Surgery.LaunchPad.Validation.Blazor.csproj b/src/Validation.Blazor/Rocket.Surgery.LaunchPad.Validation.Blazor.csproj new file mode 100644 index 0000000000..5f2a1c735f --- /dev/null +++ b/src/Validation.Blazor/Rocket.Surgery.LaunchPad.Validation.Blazor.csproj @@ -0,0 +1,20 @@ + + + $(LaunchPadTargetFrameworks) + LaunchPad's validation for Blazor forms: a LaunchPadValidator component that reports the failures of the model's validator to the form, one field at a time as the user edits and the whole model on submit. + $(PackageTags);validation;blazor;forms;editform + Rocket.Surgery.LaunchPad.AspNetCore.Blazor + true + + + + + + + + + + + + + diff --git a/src/Validation.Grpc/Joints/ValidationGrpcJoint.cs b/src/Validation.Grpc/Joints/ValidationGrpcJoint.cs new file mode 100644 index 0000000000..d197f2e50f --- /dev/null +++ b/src/Validation.Grpc/Joints/ValidationGrpcJoint.cs @@ -0,0 +1,34 @@ +using Grpc.AspNetCore.Server; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +using Rocket.Surgery.LaunchPad.Grpc.Validation; +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.Grpc.Joints; + +/// +/// Turns a into an status with the +/// failures in a trailer, and sends the warnings of a call that succeeded in a trailer too. +/// Implements the +/// +/// +/// Runs after the , so its interceptor is added after, and so runs inside, the exception interceptors that joint adds: +/// the failure is already an when they see it. +/// +/// +/// +[PublicAPI] +[DovetailExport] +[AfterJoint] +[DovetailCategory(DovetailCategory.Application)] +public class ValidationGrpcJoint : IServiceJoint +{ + /// + public void Register(IDovetailContext context, IServiceCollection services) + { + services.TryAddScoped(static _ => ValidationNotices.Current ?? new ValidationNotices()); + services.Configure(options => options.Interceptors.Add()); + } +} diff --git a/src/Validation.Grpc/Rocket.Surgery.LaunchPad.Validation.Grpc.csproj b/src/Validation.Grpc/Rocket.Surgery.LaunchPad.Validation.Grpc.csproj new file mode 100644 index 0000000000..a3c674dd8d --- /dev/null +++ b/src/Validation.Grpc/Rocket.Surgery.LaunchPad.Validation.Grpc.csproj @@ -0,0 +1,23 @@ + + + $(LaunchPadTargetFrameworks) + LaunchPad's validation for gRPC services: a rejected request answers InvalidArgument with the failures in the status detail and in a trailer, with their codes and placeholder values, and warnings travel in a trailer of successful calls. + $(PackageTags);dovetail;validation;grpc;interceptor + false + + Rocket.Surgery.LaunchPad.Grpc + ValidationExports + + + + + + + + + + + diff --git a/src/Validation.Grpc/Validation/ValidationInterceptor.cs b/src/Validation.Grpc/Validation/ValidationInterceptor.cs new file mode 100644 index 0000000000..eed2b87db8 --- /dev/null +++ b/src/Validation.Grpc/Validation/ValidationInterceptor.cs @@ -0,0 +1,79 @@ +using Grpc.Core; +using Grpc.Core.Interceptors; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.Grpc.Validation; + +/// +/// Turns a into an : the +/// detail lists each error, and the trailer carries every failure as JSON, with its path, code, severity +/// and placeholder values. A call that succeeds sends the warnings its validations gathered () in the +/// trailer, the same way. +/// +/// +/// The trailers are binary (their names end in -bin): a path such as Stages[2].Thrust is not a valid metadata key, and a +/// message need not be ASCII. Their value is the UTF-8 JSON writes. +/// +internal sealed class ValidationInterceptor : Interceptor +{ + /// The trailer of a rejected call: every failure, as UTF-8 JSON. + public const string FailuresTrailer = "validation-failures-bin"; + + /// The trailer of a successful call: its warnings and information, as UTF-8 JSON. + public const string NoticesTrailer = "validation-notices-bin"; + + public override async Task UnaryServerHandler( + TRequest request, + ServerCallContext context, + UnaryServerMethod continuation + ) + { + var notices = ValidationNotices.Current ?? ValidationNotices.Begin(); + try + { + var response = await continuation(request, context).ConfigureAwait(false); + AddNotices(context, notices); + return response; + } + catch (ValidationFailedException exception) + { + throw ToRpcException(exception); + } + } + + public override async Task ServerStreamingServerHandler( + TRequest request, + IServerStreamWriter responseStream, + ServerCallContext context, + ServerStreamingServerMethod continuation + ) + { + var notices = ValidationNotices.Current ?? ValidationNotices.Begin(); + try + { + await continuation(request, responseStream, context).ConfigureAwait(false); + AddNotices(context, notices); + } + catch (ValidationFailedException exception) + { + throw ToRpcException(exception); + } + } + + internal static RpcException ToRpcException(ValidationFailedException exception) + { + var result = exception.Result; + var trailers = new Metadata { { FailuresTrailer, ValidationJson.ToUtf8Bytes(result.Failures) }, }; + var detail = string.Join( + Environment.NewLine, + result.Errors.Select(static failure => failure.Path.Length == 0 ? failure.Message : $"{failure.Path}: {failure.Message}") + ); + return new(new(StatusCode.InvalidArgument, detail), trailers); + } + + private static void AddNotices(ServerCallContext context, ValidationNotices notices) + { + if (!notices.IsEmpty) context.ResponseTrailers.Add(NoticesTrailer, ValidationJson.ToUtf8Bytes(notices.ToList())); + } +} diff --git a/src/Validation.HotChocolate/Joints/ValidationHotChocolateJoint.cs b/src/Validation.HotChocolate/Joints/ValidationHotChocolateJoint.cs new file mode 100644 index 0000000000..e538fc4d41 --- /dev/null +++ b/src/Validation.HotChocolate/Joints/ValidationHotChocolateJoint.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +using Rocket.Surgery.LaunchPad.HotChocolate.Validation; +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.HotChocolate.Joints; + +/// +/// Reports each failure of a request LaunchPad's validators rejected as a GraphQL VALIDATION error, and sends the warnings of +/// a request that was accepted () as an extension of its result. +/// Implements the +/// +/// +/// Adds the to the GraphQL builder the other GraphQL joints share. Runs after the +/// , so the filter comes after LaunchPad's error filter, which rebuilds every error from its exception and would +/// collapse the one error per failure this filter reports. +/// +/// +[PublicAPI] +[DovetailExport] +[AfterJoint] +[DovetailCategory(DovetailCategory.Application)] +public class ValidationHotChocolateJoint : IServiceJoint +{ + /// + public void Register(IDovetailContext context, IServiceCollection services) + { + services.TryAddScoped(static _ => ValidationNotices.Current ?? new ValidationNotices()); + context + .GetOrAdd(() => services.AddGraphQL()) + .AddErrorFilter() + .UseValidationNotices(); + } +} diff --git a/src/Validation.HotChocolate/Rocket.Surgery.LaunchPad.Validation.HotChocolate.csproj b/src/Validation.HotChocolate/Rocket.Surgery.LaunchPad.Validation.HotChocolate.csproj new file mode 100644 index 0000000000..493b1e66be --- /dev/null +++ b/src/Validation.HotChocolate/Rocket.Surgery.LaunchPad.Validation.HotChocolate.csproj @@ -0,0 +1,19 @@ + + + $(LaunchPadTargetFrameworks) + LaunchPad's validation for GraphQL servers: a rejected request reports one VALIDATION error per failure, with the path of the member, the rule's code and its placeholder values. + $(PackageTags);dovetail;validation;hotchocolate;graphql + + Rocket.Surgery.LaunchPad.HotChocolate + ValidationExports + + + + + + + + diff --git a/src/Validation.HotChocolate/Validation/ValidationErrorFilter.cs b/src/Validation.HotChocolate/Validation/ValidationErrorFilter.cs new file mode 100644 index 0000000000..3faa113c8c --- /dev/null +++ b/src/Validation.HotChocolate/Validation/ValidationErrorFilter.cs @@ -0,0 +1,47 @@ +using HotChocolate; +using HotChocolate.Execution; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.HotChocolate.Validation; + +/// +/// Reports each failure of a request LaunchPad's validators rejected as a VALIDATION error, with the path of the member, the +/// rule's code, its severity and the values of the message's placeholders as extensions. The warnings and information that came with +/// the errors are reported the same way, with their own severity. +/// +[PublicAPI] +public sealed class ValidationErrorFilter : IErrorFilter +{ + /// The error code of a validation failure. + public const string ValidationCode = "VALIDATION"; + + /// + public IError OnError(IError error) + { + ArgumentNullException.ThrowIfNull(error); + if (error.Exception is not ValidationFailedException exception) return error; + var errors = exception.Result.Failures.Select(failure => ToError(error, failure)).ToArray(); + return errors.Length == 1 ? errors[0] : new AggregateError(errors); + } + + private static IError ToError(IError error, ValidationFailure failure) + { + var arguments = new Dictionary(StringComparer.Ordinal); + foreach (var argument in failure.Arguments) + { + arguments[argument.Key] = ValidationJson.Format(argument.Value); + } + + return error + .WithException(null) + .RemoveExtension("message") + .RemoveExtension("stackTrace") + .WithMessage(failure.Message) + .WithCode(ValidationCode) + .SetExtension("propertyName", failure.Path) + .SetExtension("errorCode", failure.Code) + .SetExtension("severity", failure.Severity.ToString()) + .SetExtension("arguments", arguments); + } +} diff --git a/src/Validation.HotChocolate/Validation/ValidationNoticesMiddleware.cs b/src/Validation.HotChocolate/Validation/ValidationNoticesMiddleware.cs new file mode 100644 index 0000000000..e49164c86e --- /dev/null +++ b/src/Validation.HotChocolate/Validation/ValidationNoticesMiddleware.cs @@ -0,0 +1,66 @@ +using HotChocolate.Execution; +using HotChocolate.Execution.Configuration; + +using Microsoft.Extensions.DependencyInjection; + +using Rocket.Surgery.LaunchPad.Validation; + +namespace Rocket.Surgery.LaunchPad.HotChocolate.Validation; + +/// +/// Sends the warnings and information the validators of a request gathered () with its result, as the +/// extension: a list of the failures, each with its path, code, message, severity and placeholder values. +/// +[PublicAPI] +public static class ValidationNoticesMiddleware +{ + /// The extension of a result the notices are sent in. + public const string ExtensionName = "validationNotices"; + + private const string Key = "Rocket.Surgery.LaunchPad.ValidationNotices"; + + /// + /// Adds the middleware around the execution of the operation. + /// + /// The GraphQL builder. + /// The GraphQL builder. + public static IRequestExecutorBuilder UseValidationNotices(this IRequestExecutorBuilder builder) => + builder.UseRequest( + static next => async context => + { + // A resolver has a scope of its own: the notices reach it as the ones of the request being handled. + var notices = ValidationNotices.Current ?? ValidationNotices.Begin(); + await next(context).ConfigureAwait(false); + if (context.Result is not OperationResult result || notices.IsEmpty) return; + result.Extensions = ( result.Extensions ?? [] ).Add(ExtensionName, Describe(notices.ToList())); + }, + Key, + before: WellKnownRequestMiddleware.OperationExecutionMiddleware + ); + + private static List> Describe(IReadOnlyList notices) + { + var described = new List>(notices.Count); + foreach (var notice in notices) + { + var arguments = new Dictionary(StringComparer.Ordinal); + foreach (var argument in notice.Arguments) + { + arguments[argument.Key] = ValidationJson.Format(argument.Value); + } + + described.Add( + new(StringComparer.Ordinal) + { + ["path"] = notice.Path, + ["code"] = notice.Code, + ["message"] = notice.Message, + ["severity"] = notice.Severity.ToString(), + ["arguments"] = arguments, + } + ); + } + + return described; + } +} diff --git a/src/Validation/ObjectValidator.cs b/src/Validation/ObjectValidator.cs new file mode 100644 index 0000000000..7a6f2714c0 --- /dev/null +++ b/src/Validation/ObjectValidator.cs @@ -0,0 +1,137 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// Validates a value whose type is known only at run time, with the validator registered for that type: what a form component has when +/// all it is given is the model. The registration the generator writes adds one for every validated type, so finding it takes no +/// reflection. +/// +[PublicAPI] +public abstract class ObjectValidator +{ + /// + /// The type validated. + /// + public abstract Type Type { get; } + + /// + /// Validates a value. + /// + /// Where the type's validator is found: the services of the scope the value is validated in. + /// The value, of . + /// The cancellation token. + /// The rules the value did not meet. + public abstract ValueTask ValidateAsync(IServiceProvider services, object value, CancellationToken cancellationToken = default); + + /// + /// Validates a value, if none of the type's rules waits. + /// + /// Where the type's validator is found. + /// The value, of . + /// The rules the value did not meet, when the method returns . + /// when the type is validated asynchronously only: validate it with . + public abstract bool TryValidate(IServiceProvider services, object value, out ValidationResult result); + + /// + /// Validates one member of a value, if none of its rules waits. + /// + /// Where the type's validator is found. + /// The value, of . + /// The member's name. + /// The failures of the member's rules, when the method returns . + /// when a rule of the member is asynchronous. + public abstract bool TryValidateMember(IServiceProvider services, object value, string member, out ValidationResult result); + + /// + /// Validates one member of a value. + /// + /// Where the type's validator is found. + /// The value, of . + /// The member's name. + /// The cancellation token. + /// The failures of the member's rules. + public abstract ValueTask ValidateMemberAsync(IServiceProvider services, object value, string member, CancellationToken cancellationToken = default); +} + +/// +/// The of a : it asks the services for the type's +/// and . +/// +/// The type validated. +[PublicAPI] +public sealed class ObjectValidator : ObjectValidator +{ + /// + public override Type Type => typeof(T); + + /// + public override ValueTask ValidateAsync(IServiceProvider services, object value, CancellationToken cancellationToken = default) => + Get>(services).ValidateAsync((T)value, cancellationToken); + + /// + public override bool TryValidate(IServiceProvider services, object value, out ValidationResult result) + { + ArgumentNullException.ThrowIfNull(services); +#pragma warning disable LPAD3002 // asked for at run time, for any T: a type with a rule that waits has none, which is the answer + if (services.GetService(typeof(IValidate)) is IValidate validator) +#pragma warning restore LPAD3002 + { + result = validator.Validate((T)value); + return true; + } + + result = default; + return false; + } + + /// + public override bool TryValidateMember(IServiceProvider services, object value, string member, out ValidationResult result) => + Get>(services).TryValidateMember((T)value, member, out result); + + /// + public override ValueTask ValidateMemberAsync(IServiceProvider services, object value, string member, CancellationToken cancellationToken = default) => + Get>(services).ValidateMemberAsync((T)value, member, cancellationToken); + + private static TService Get(IServiceProvider services) where TService : class + { + ArgumentNullException.ThrowIfNull(services); + return services.GetService(typeof(TService)) as TService + ?? throw new InvalidOperationException($"No {typeof(TService)} is registered: call the Add...Validators method of the assembly that declares the rules of {typeof(T)}."); + } +} + +/// +/// Finds the of a type among those registered. +/// +/// Every registered . +[PublicAPI] +public sealed class ObjectValidators(IEnumerable validators) +{ + private readonly Dictionary _byType = Index(validators); + + /// + /// Finds the validator of a type: its own, or that of the nearest base class that has one. + /// + /// The type of the value to validate. + /// The validator, or when neither the type nor a base class has rules. + public ObjectValidator? Find(Type type) + { + for (var current = type; current is not null; current = current.BaseType) + { + if (_byType.TryGetValue(current, out var validator)) return validator; + } + + return null; + } + + private static Dictionary Index(IEnumerable validators) + { + ArgumentNullException.ThrowIfNull(validators); + var byType = new Dictionary(); + foreach (var validator in validators) + { + byType[validator.Type] = validator; + } + + return byType; + } +} diff --git a/src/Validation/ValidationFailedException.cs b/src/Validation/ValidationFailedException.cs new file mode 100644 index 0000000000..4cbd81add6 --- /dev/null +++ b/src/Validation/ValidationFailedException.cs @@ -0,0 +1,49 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// A value did not meet its rules. It carries the result, which each transport answers in its own error shape: a 422 with problem +/// details over HTTP, InvalidArgument over gRPC, one error for each failure in GraphQL. +/// +[PublicAPI] +public sealed class ValidationFailedException : Exception +{ + /// + /// Creates the exception with no result. + /// + public ValidationFailedException() : this(ValidationResult.Valid) { } + + /// + /// Creates the exception with a message and no result. + /// + /// The message. + public ValidationFailedException(string message) : base(message) { } + + /// + /// Creates the exception with a message and no result. + /// + /// The message. + /// What caused it. + public ValidationFailedException(string message, Exception innerException) : base(message, innerException) { } + + /// + /// Creates the exception for a result that has errors. + /// + /// The result of the validation. + public ValidationFailedException(ValidationResult result) : base(Describe(result)) => Result = result; + + /// + /// The result of the validation: its errors, and the warnings and information that came with them. + /// + public ValidationResult Result { get; } + + private static string Describe(ValidationResult result) + { + var messages = new List(); + foreach (var failure in result.Errors) + { + messages.Add(failure.Path.Length == 0 ? failure.Message : failure.Path + ": " + failure.Message); + } + + return messages.Count == 0 ? "Validation failed." : "Validation failed: " + string.Join("; ", messages); + } +} diff --git a/src/Validation/ValidationJson.cs b/src/Validation/ValidationJson.cs new file mode 100644 index 0000000000..288d1ceb92 --- /dev/null +++ b/src/Validation/ValidationJson.cs @@ -0,0 +1,82 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// Failures as JSON, written without a serializer: what a transport sends where it has no shape of its own for them (an HTTP header, a +/// gRPC trailer). Each failure is an object of its path, code, message, severity and arguments, the +/// values of the message's placeholders as text. +/// +[PublicAPI] +public static class ValidationJson +{ + /// + /// The value of a message's placeholder as text a client can read back: a number or a date in its invariant form. + /// + /// The value. + /// The text, or for no value. + public static string? Format(object? value) => value switch + { + null => null, + string text => text, + bool flag => flag ? "true" : "false", + DateTime or DateTimeOffset or DateOnly or TimeOnly => ( (IFormattable)value ).ToString("O", CultureInfo.InvariantCulture), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString(), + }; + + /// + /// Writes failures as a JSON array. + /// + /// The writer. + /// The failures. + public static void Write(Utf8JsonWriter writer, IEnumerable failures) + { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(failures); + writer.WriteStartArray(); + foreach (var failure in failures) + { + writer.WriteStartObject(); + writer.WriteString("path", failure.Path); + writer.WriteString("code", failure.Code); + writer.WriteString("message", failure.Message); + writer.WriteString("severity", failure.Severity.ToString()); + writer.WriteStartObject("arguments"); + foreach (var argument in failure.Arguments) + { + writer.WriteString(argument.Key, Format(argument.Value)); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + + /// + /// Failures as the UTF-8 bytes of a JSON array. + /// + /// The failures. + /// The bytes. + public static byte[] ToUtf8Bytes(IEnumerable failures) + { + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + Write(writer, failures); + } + + return stream.ToArray(); + } + + /// + /// Failures as a JSON array in ASCII: every other character is escaped, so the text can be an HTTP header. + /// + /// The failures. + /// The text. + public static string ToText(IEnumerable failures) => Encoding.ASCII.GetString(ToUtf8Bytes(failures)); +} diff --git a/src/Validation/ValidationManifest.cs b/src/Validation/ValidationManifest.cs new file mode 100644 index 0000000000..d0a9061d9d --- /dev/null +++ b/src/Validation/ValidationManifest.cs @@ -0,0 +1,191 @@ +using System.Globalization; +using System.Text; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// The rules of a type's members, as data: what describes them where nothing is validated, an OpenAPI schema for one. The generator +/// writes one for every validator, with the rules of what the type derives from, and the registration adds it to the services. +/// +/// The type validated. +/// Its members that have rules. +[PublicAPI] +public sealed class ValidationManifest(Type type, params ValidatedMember[] members) +{ + /// + /// The type validated. + /// + public Type Type { get; } = type; + + /// + /// Its members that have rules. + /// + public IReadOnlyList Members { get; } = members; +} + +/// +/// A member and its rules. +/// +/// The member's name. +/// +/// The rules, each as its name and arguments: MaxLength(30). each before one says it is about the items of a +/// collection, when that it does not always reject the value: it is under a condition, or it is a warning. +/// +[PublicAPI] +public sealed class ValidatedMember(string name, params string[] rules) +{ + /// + /// The member's name. + /// + public string Name { get; } = name; + + /// + /// The rules. + /// + public IReadOnlyList Rules { get; } = [.. rules.Select(ValidatedRule.Parse),]; +} + +/// +/// One rule of a member. +/// +/// The rule: MaxLength. +/// Its arguments as they were written: a number, a string in quotes, or an expression. +/// Whether the rule is about each item of the member, a collection. +/// Whether a value that does not meet the rule may still be accepted: the rule has a condition, or is not an error. +[PublicAPI] +public sealed record ValidatedRule(string Name, IReadOnlyList Arguments, bool ForEachItem, bool IsConditional) +{ + /// + /// Reads a rule as the manifest states it. + /// + /// The rule: each MaxLength(30). + /// The rule. + public static ValidatedRule Parse(string text) + { + ArgumentNullException.ThrowIfNull(text); + var each = false; + var conditional = false; + for (var found = true; found;) + { + found = false; + if (text.StartsWith("each ", StringComparison.Ordinal)) + { + each = found = true; + text = text[5..]; + } + else if (text.StartsWith("when ", StringComparison.Ordinal)) + { + conditional = found = true; + text = text[5..]; + } + } + + var open = text.IndexOf('(', StringComparison.Ordinal); + if (open < 0 || !text.EndsWith(')')) return new(text, [], each, conditional); + + var arguments = new List(); + var current = new StringBuilder(); + var depth = 0; + var quoted = false; + var inner = text.AsSpan(open + 1, text.Length - open - 2); + for (var i = 0; i < inner.Length; i++) + { + var character = inner[i]; + if (quoted) + { + current.Append(character); + if (character == '\\' && i + 1 < inner.Length) current.Append(inner[++i]); + else if (character == '"') quoted = false; + continue; + } + + switch (character) + { + case '"': + quoted = true; + current.Append(character); + break; + case '(' or '[' or '{': + depth++; + current.Append(character); + break; + case ')' or ']' or '}': + depth--; + current.Append(character); + break; + case ',' when depth == 0: + arguments.Add(current.ToString().Trim()); + current.Clear(); + break; + default: + current.Append(character); + break; + } + } + + if (current.Length > 0) arguments.Add(current.ToString().Trim()); + return new(text[..open], arguments, each, conditional); + } + + /// + /// Reads an argument that is a number. + /// + /// Which argument. + /// The number. + /// Whether the argument is a number: one that names another member, or is an expression, is not. + public bool TryGetNumber(int index, out double value) + { + value = 0; + return index < Arguments.Count + && double.TryParse(Arguments[index].TrimEnd('m', 'M', 'd', 'D', 'f', 'F', 'l', 'L', 'u', 'U'), NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + /// + /// Reads an argument that is text in quotes. + /// + /// Which argument. + /// The text, without its quotes and escapes. + /// Whether the argument is text in quotes. + public bool TryGetText(int index, out string value) + { + value = ""; + if (index >= Arguments.Count || Arguments[index] is not ['"', .., '"'] argument || argument.Length < 2) return false; + var text = new StringBuilder(argument.Length); + for (var i = 1; i < argument.Length - 1; i++) + { + var character = argument[i]; + if (character != '\\' || i + 1 >= argument.Length - 1) + { + text.Append(character); + continue; + } + + var escaped = argument[++i]; + switch (escaped) + { + case 'n': + text.Append('\n'); + break; + case 'r': + text.Append('\r'); + break; + case 't': + text.Append('\t'); + break; + case '0': + text.Append('\0'); + break; + case 'u' when i + 4 < argument.Length && ushort.TryParse(argument.AsSpan(i + 1, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var code): + text.Append((char)code); + i += 4; + break; + default: + text.Append(escaped); + break; + } + } + + value = text.ToString(); + return true; + } +} diff --git a/src/Validation/ValidationNotices.cs b/src/Validation/ValidationNotices.cs new file mode 100644 index 0000000000..edc7ab14c3 --- /dev/null +++ b/src/Validation/ValidationNotices.cs @@ -0,0 +1,75 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// What the validations of one request had to say that did not reject it: the warnings and the information. Whatever validates a +/// request adds them here, and the transport sends them with the response: a header over HTTP, a trailer over gRPC, an extension of a +/// GraphQL result. +/// +/// +/// One for each request. A transport begins it () before the request is handled, and the integration packages +/// register it scoped as the one of the request being handled (), so a handler that runs in a scope of its own, +/// as a GraphQL resolver does, still adds to the notices its response is sent with. +/// +[PublicAPI] +public sealed class ValidationNotices +{ + private static readonly AsyncLocal Ambient = new(); + private readonly List _items = []; + + /// + /// The notices of the request being handled, if a transport began them. + /// + public static ValidationNotices? Current => Ambient.Value; + + /// + /// Begins the notices of a request: they are for everything the caller awaits from here on. + /// + /// The notices, which the caller sends with the response. + public static ValidationNotices Begin() + { + var notices = new ValidationNotices(); + Ambient.Value = notices; + return notices; + } + + /// + /// Whether there is nothing to send. + /// + public bool IsEmpty + { + get + { + lock (_items) + { + return _items.Count == 0; + } + } + } + + /// + /// The warnings and information so far. + /// + /// A copy: more may be added while the request runs. + public IReadOnlyList ToList() + { + lock (_items) + { + return [.. _items,]; + } + } + + /// + /// Adds what a result holds that is not an error. + /// + /// The result of a validation. + public void Add(ValidationResult result) + { + lock (_items) + { + foreach (var failure in result.Failures) + { + if (failure.Severity != ValidationSeverity.Error) _items.Add(failure); + } + } + } +} diff --git a/src/Validation/ValidationResult.cs b/src/Validation/ValidationResult.cs index 22707e3aa6..313d6e1c53 100644 --- a/src/Validation/ValidationResult.cs +++ b/src/Validation/ValidationResult.cs @@ -51,6 +51,13 @@ public ValidationResult(ImmutableArray failures) /// public bool IsInvalid { get; } + /// + /// Throws when the value was not valid. + /// + /// This result, which may still hold warnings and information. + /// The result has an error. + public ValidationResult ThrowIfInvalid() => IsInvalid ? throw new ValidationFailedException(this) : this; + /// /// The failures that are errors. /// diff --git a/test/Api.Generators.Tests/Api.Generators.Tests.csproj b/test/Api.Generators.Tests/Api.Generators.Tests.csproj index 4d487b950d..7e529bc275 100644 --- a/test/Api.Generators.Tests/Api.Generators.Tests.csproj +++ b/test/Api.Generators.Tests/Api.Generators.Tests.csproj @@ -28,6 +28,8 @@ + + diff --git a/test/Api.Generators.Tests/OpenApiGeneratorTests.cs b/test/Api.Generators.Tests/OpenApiGeneratorTests.cs index 48d4e80820..eac7924abc 100644 --- a/test/Api.Generators.Tests/OpenApiGeneratorTests.cs +++ b/test/Api.Generators.Tests/OpenApiGeneratorTests.cs @@ -116,9 +116,35 @@ public sealed record Request(System.Guid Id, string Name) : IRequest UnionContracts.Request(container, parameters, response); @@ -126,7 +152,7 @@ private static string ValidatedContracts() namespace Sample.Contracts.Rockets { - using ZeroAlloc.Validation; + using {{( launchPad ? "Rocket.Surgery.LaunchPad.Validation; using Rocket.Surgery.LaunchPad.Validation.Rules" : "ZeroAlloc.Validation" )}}; public enum LaunchSite { Canaveral, Vandenberg } @@ -142,11 +168,18 @@ public enum LaunchSite { Canaveral, Vandenberg } )}} {{Request( "GetLaunchPlan", - """ - [property: DataMember(Order = 1), Length(2, 20)] string Name, - [property: DataMember(Order = 2), GreaterThan(0), LessThanOrEqualTo(100)] int Take, - [property: DataMember(Order = 3), IsEnumName(typeof(LaunchSite)), MinLength(3, When = "HasSite")] string? Site - """, + launchPad + ? """ + [property: DataMember(Order = 1), Length(2, 20)] string Name, + [property: DataMember(Order = 2), GreaterThan(0), LessThanOrEqualTo(100), LessThan(Member = "Limit")] int Take, + [property: DataMember(Order = 3), Url, MinLength(3, Severity = ValidationSeverity.Warning)] string? Site, + [property: DataMember(Order = 4)] int Limit = 10 + """ + : """ + [property: DataMember(Order = 1), Length(2, 20)] string Name, + [property: DataMember(Order = 2), GreaterThan(0), LessThanOrEqualTo(100)] int Take, + [property: DataMember(Order = 3), IsEnumName(typeof(LaunchSite)), MinLength(3, When = "HasSite")] string? Site + """, "RocketModel" )}} } diff --git a/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller#Sample.Server.RocketsController.Controller.g.verified.cs b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller#Sample.Server.RocketsController.Controller.g.verified.cs new file mode 100644 index 0000000000..7afc0eb63c --- /dev/null +++ b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller#Sample.Server.RocketsController.Controller.g.verified.cs @@ -0,0 +1,268 @@ +//HintName: Rocket.Surgery.LaunchPad.Analyzers/Rocket.Surgery.LaunchPad.Analyzers.Api.Controllers.ControllerGenerator/Sample.Server.RocketsController.Controller.g.cs +// +#nullable enable +#pragma warning disable CS1591 + +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using Rocket.Surgery.LaunchPad.Api.Generated.Mvc; +using ApiControllerAttribute = global::Microsoft.AspNetCore.Mvc.ApiControllerAttribute; +using ApiFormat = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiFormat; +using ApiOpenApi = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiOpenApi; +using ApiOpenApiCase = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiOpenApiCase; +using ApiOpenApiMember = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiOpenApiMember; +using ApiProblems = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiProblems; +using ApiSchemaRule = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.ApiSchemaRule; +using AuthorizeAttribute = global::Microsoft.AspNetCore.Authorization.AuthorizeAttribute; +using CancellationToken = global::System.Threading.CancellationToken; +using ControllerBase = global::Microsoft.AspNetCore.Mvc.ControllerBase; +using CreatedResult = global::Microsoft.AspNetCore.Mvc.CreatedResult; +using EndpointNameAttribute = global::Microsoft.AspNetCore.Routing.EndpointNameAttribute; +using FromBodyAttribute = global::Microsoft.AspNetCore.Mvc.FromBodyAttribute; +using FromQueryAttribute = global::Microsoft.AspNetCore.Mvc.FromQueryAttribute; +using FromRouteAttribute = global::Microsoft.AspNetCore.Mvc.FromRouteAttribute; +using GeneratedCodeAttribute = global::System.CodeDom.Compiler.GeneratedCodeAttribute; +using Guid = global::System.Guid; +using HttpGetAttribute = global::Microsoft.AspNetCore.Mvc.HttpGetAttribute; +using HttpPostAttribute = global::Microsoft.AspNetCore.Mvc.HttpPostAttribute; +using IApiOpenApiTransformer = global::Rocket.Surgery.LaunchPad.Api.Generated.Mvc.IApiOpenApiTransformer; +using InvalidOperationException = global::System.InvalidOperationException; +using OkObjectResult = global::Microsoft.AspNetCore.Mvc.OkObjectResult; +using ProblemDetails = global::Microsoft.AspNetCore.Mvc.ProblemDetails; +using ProducesResponseTypeAttribute = global::Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute; +using RouteAttribute = global::Microsoft.AspNetCore.Mvc.RouteAttribute; +using TagsAttribute = global::Microsoft.AspNetCore.Http.TagsAttribute; +using Task = global::System.Threading.Tasks.Task; +using Uri = global::System.Uri; +using ValidationProblemDetails = global::Microsoft.AspNetCore.Mvc.ValidationProblemDetails; + +namespace Sample.Server +{ + [ApiController] + [Route("api/rockets")] + [Tags("Rockets")] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api.Controllers", "version")] + public partial class RocketsController : ControllerBase + { + /// Handles GET /api/rockets/{id:guid} by sending . + [HttpGet("{id:guid}")] + [EndpointName("GetRocket")] + [ProducesResponseType(typeof(global::Sample.Contracts.Rockets.RocketModel), 200, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), 400, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 404, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 403, "application/problem+json")] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api", "version")] + [ApiOpenApi<__GetRocketOpenApi>] + public async Task> GetRocket([FromRoute(Name = "id")] Guid @id, CancellationToken __cancellationToken) + { + var __wire = new global::Sample.Contracts.Rockets.GetRocket.Request(@id); + var __request = __wire; + var __sender = HttpContext.RequestServices.GetRequiredService(); + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return new OkObjectResult(__value); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error0) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error0.Id); + } + + if (__case is global::Sample.Contracts.Rockets.Forbidden __error1) + { + return ApiProblems.Problem(403, "Forbidden"); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.GetRocket.Request returned a Sample.Contracts.Rockets.GetRocketResult that holds none of its cases."); + } + + private sealed class __GetRocketOpenApi : IApiOpenApiTransformer + { + /// Describes GetRocket in the OpenAPI document: what its endpoint metadata can't say. + public static async Task TransformAsync(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + await ApiOpenApi.Cases(operation, context, 403, new ApiOpenApiCase[] { new ApiOpenApiCase("Forbidden", "ForbiddenProblem", null, new ApiOpenApiMember[] { }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + } + } + + /// Handles POST /api/rockets by sending . + [HttpPost("")] + [EndpointName("CreateRocket")] + [ProducesResponseType(typeof(global::Sample.Contracts.Rockets.CreateRocket.Response), 201, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), 400, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 422, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 409, "application/problem+json")] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api", "version")] + [ApiOpenApi<__CreateRocketOpenApi>] + public async Task> CreateRocket([FromBody] global::Sample.Contracts.Rockets.CreateRocket.Request __body, CancellationToken __cancellationToken) + { + var __wire = __body; + var __request = __wire; + var __sender = HttpContext.RequestServices.GetRequiredService(); + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.CreateRocket.Response __value) + { + return new CreatedResult("/api/rockets/" + Uri.EscapeDataString(ApiFormat.Value(__value.Id)), __value); + } + + if (__case is global::Sample.Contracts.Rockets.ValidationFailed __error0) + { + return ApiProblems.Problem(422, "ValidationFailed", "errors", __error0.Errors); + } + + if (__case is global::Sample.Contracts.Rockets.NameConflict __error1) + { + return ApiProblems.Problem(409, "NameConflict", "name", __error1.Name); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.CreateRocket.Request returned a Sample.Contracts.Rockets.CreateRocketResult that holds none of its cases."); + } + + private sealed class __CreateRocketOpenApi : IApiOpenApiTransformer + { + /// Describes CreateRocket in the OpenAPI document: what its endpoint metadata can't say. + public static async Task TransformAsync(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiOpenApi.Location(operation); + await ApiOpenApi.Cases(operation, context, 409, new ApiOpenApiCase[] { new ApiOpenApiCase("NameConflict", "NameConflictProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("name", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("ValidationFailed", "ValidationFailedProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("errors", typeof(string[]), null) }) }, cancellationToken).ConfigureAwait(false); + } + } + + /// Handles POST /api/rockets/{id}/launch by sending . + [HttpPost("{id}/launch")] + [EndpointName("LaunchRocket")] + [Authorize(Policy = "launch")] + [ProducesResponseType(typeof(global::Sample.Contracts.Rockets.RocketModel), 200, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), 400, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 422, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 404, "application/problem+json")] + [ProducesResponseType(401)] + [ProducesResponseType(403)] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api", "version")] + [ApiOpenApi<__LaunchRocketOpenApi>] + public async Task> LaunchRocket([FromRoute(Name = "id")] Guid @id, [FromBody] global::Sample.Contracts.Rockets.LaunchRocket.Request __body, CancellationToken __cancellationToken) + { + var __wire = __body; + __wire = __wire with + { + Id = @id + }; + var __request = __wire; + var __sender = HttpContext.RequestServices.GetRequiredService(); + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return new OkObjectResult(__value); + } + + if (__case is global::Sample.Contracts.Rockets.NotReady __error0) + { + return ApiProblems.Problem(422, "NotReady", "reason", __error0.Reason); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error1) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error1.Id); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.LaunchRocket.Request returned a Sample.Contracts.Rockets.LaunchRocketResult that holds none of its cases."); + } + + private sealed class __LaunchRocketOpenApi : IApiOpenApiTransformer + { + /// Describes LaunchRocket in the OpenAPI document: what its endpoint metadata can't say. + public static async Task TransformAsync(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiOpenApi.Authenticate(operation); + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("NotReady", "NotReadyProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("reason", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + } + } + + /// Handles POST /api/rockets/{id}/schedule by sending . + [HttpPost("{id}/schedule")] + [EndpointName("ScheduleLaunch")] + [ProducesResponseType(typeof(global::Sample.Contracts.Rockets.RocketModel), 200, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), 400, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 422, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), 404, "application/problem+json")] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api", "version")] + [ApiOpenApi<__ScheduleLaunchOpenApi>] + public async Task> ScheduleLaunch([FromRoute(Name = "id")] Guid @id, [FromBody] global::Sample.Contracts.Rockets.ScheduleLaunch.Request __body, CancellationToken __cancellationToken) + { + var __wire = __body; + __wire = __wire with + { + Id = @id + }; + var __request = __wire; + var __sender = HttpContext.RequestServices.GetRequiredService(); + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return new OkObjectResult(__value); + } + + if (__case is global::Sample.Contracts.Rockets.NotReady __error0) + { + return ApiProblems.Problem(422, "NotReady", "reason", __error0.Reason); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error1) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error1.Id); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.ScheduleLaunch.Request returned a Sample.Contracts.Rockets.LaunchRocketResult that holds none of its cases."); + } + + private sealed class __ScheduleLaunchOpenApi : IApiOpenApiTransformer + { + /// Describes ScheduleLaunch in the OpenAPI document: what its endpoint metadata can't say. + public static async Task TransformAsync(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("NotReady", "NotReadyProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("reason", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + ApiSchemaRule.Body(operation, context, "window").Required().NotEmpty().MaxLength(40).Pattern("^[A-Za-z ]+$"); + ApiSchemaRule.Body(operation, context, "crew").Minimum("1").Maximum("10"); + ApiSchemaRule.Body(operation, context, "contact").Format("email"); + } + } + + /// Handles GET /api/rockets/plan by sending . + [HttpGet("plan")] + [EndpointName("GetLaunchPlan")] + [ProducesResponseType(typeof(global::Sample.Contracts.Rockets.RocketModel), 200, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), 400, "application/problem+json")] + [GeneratedCode("Rocket.Surgery.LaunchPad.Api", "version")] + [ApiOpenApi<__GetLaunchPlanOpenApi>] + public async Task> GetLaunchPlan([FromQuery(Name = "name")] string @name, [FromQuery(Name = "take")] int @take, [FromQuery(Name = "site")] string? @site, [FromQuery(Name = "limit")] int @limit, CancellationToken __cancellationToken) + { + var __wire = new global::Sample.Contracts.Rockets.GetLaunchPlan.Request(@name, @take, @site, @limit); + var __request = __wire; + var __sender = HttpContext.RequestServices.GetRequiredService(); + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + return new OkObjectResult(__response); + } + + private sealed class __GetLaunchPlanOpenApi : IApiOpenApiTransformer + { + /// Describes GetLaunchPlan in the OpenAPI document: what its endpoint metadata can't say. + public static Task TransformAsync(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiSchemaRule.Parameter(operation, "name").MinLength(2).MaxLength(20); + ApiSchemaRule.Parameter(operation, "take").ExclusiveMinimum("0").Maximum("100"); + ApiSchemaRule.Parameter(operation, "site").Format("uri"); + return Task.CompletedTask; + } + } + } +} diff --git a/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller.verified.txt b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller.verified.txt new file mode 100644 index 0000000000..30dcb43322 --- /dev/null +++ b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=Controller.verified.txt @@ -0,0 +1,9 @@ +{ + AnalyzerDiagnostics: { + Rocket.Surgery.LaunchPad.Analyzers.Api.OperationHostAnalyzer: [] + }, + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Analyzers.Api.Controllers.ControllerGenerator: [] + } +} \ No newline at end of file diff --git a/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi#Sample.Server.RocketsEndpoints.MinimalApi.g.verified.cs b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi#Sample.Server.RocketsEndpoints.MinimalApi.g.verified.cs new file mode 100644 index 0000000000..f816df1f06 --- /dev/null +++ b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi#Sample.Server.RocketsEndpoints.MinimalApi.g.verified.cs @@ -0,0 +1,479 @@ +//HintName: Rocket.Surgery.LaunchPad.Analyzers/Rocket.Surgery.LaunchPad.Analyzers.Api.MinimalApi.MinimalApiGenerator/Sample.Server.RocketsEndpoints.MinimalApi.g.cs +// +#nullable enable +#pragma warning disable CS1591 + +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.DependencyInjection; +using ApiAcceptsMetadata = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiAcceptsMetadata; +using ApiBinding = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiBinding; +using ApiEndpointMetadata = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiEndpointMetadata; +using ApiFormat = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiFormat; +using ApiOpenApi = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiOpenApi; +using ApiOpenApiCase = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiOpenApiCase; +using ApiOpenApiMember = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiOpenApiMember; +using ApiParameterBindingMetadata = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiParameterBindingMetadata; +using ApiProblems = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiProblems; +using ApiSchemaRule = global::Rocket.Surgery.LaunchPad.Api.Generated.MinimalApi.ApiSchemaRule; +using ArgumentNullException = global::System.ArgumentNullException; +using BindingFlags = global::System.Reflection.BindingFlags; +using CancellationToken = global::System.Threading.CancellationToken; +using CultureInfo = global::System.Globalization.CultureInfo; +using FromBodyAttribute = global::Microsoft.AspNetCore.Mvc.FromBodyAttribute; +using FromQueryAttribute = global::Microsoft.AspNetCore.Mvc.FromQueryAttribute; +using FromRouteAttribute = global::Microsoft.AspNetCore.Mvc.FromRouteAttribute; +using FromServicesAttribute = global::Microsoft.AspNetCore.Mvc.FromServicesAttribute; +using GeneratedCodeAttribute = global::System.CodeDom.Compiler.GeneratedCodeAttribute; +using Guid = global::System.Guid; +using HttpContext = global::Microsoft.AspNetCore.Http.HttpContext; +using IEndpointConventionBuilder = global::Microsoft.AspNetCore.Builder.IEndpointConventionBuilder; +using IEndpointRouteBuilder = global::Microsoft.AspNetCore.Routing.IEndpointRouteBuilder; +using InvalidOperationException = global::System.InvalidOperationException; +using ProblemDetails = global::Microsoft.AspNetCore.Mvc.ProblemDetails; +using ProblemHttpResult = global::Microsoft.AspNetCore.Http.HttpResults.ProblemHttpResult; +using ProducesResponseTypeMetadata = global::Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata; +using RequestDelegate = global::Microsoft.AspNetCore.Http.RequestDelegate; +using RouteGroupBuilder = global::Microsoft.AspNetCore.Routing.RouteGroupBuilder; +using Task = global::System.Threading.Tasks.Task; +using TypedResults = global::Microsoft.AspNetCore.Http.TypedResults; +using Uri = global::System.Uri; + +namespace Sample.Server +{ + [GeneratedCode("Rocket.Surgery.LaunchPad.Api.MinimalApi", "version")] + public static partial class RocketsEndpoints + { + /// + /// Maps the operations of under /api/rockets. + /// + /// The route group, to add metadata or conventions to every operation. + public static RouteGroupBuilder MapRocketsEndpoints(this IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + var group = endpoints.MapGroup("/api/rockets"); + group.WithTags("Rockets"); + { + var endpoint = group.MapMethods("/{id:guid}", new string[] { "GET" }, new RequestDelegate(__GetRocketRequestDelegate)); + var method = typeof(RocketsEndpoints).GetMethod(nameof(__GetRocket), BindingFlags.NonPublic | BindingFlags.Static)!; + endpoint.WithMetadata(method); + endpoint.Add(builder => ApiEndpointMetadata.Populate, ProblemHttpResult>>(method, builder)); + var parameters = method.GetParameters(); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[0], true, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[1], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[2], false, false)); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(400, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(404, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(403, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithName("GetRocket"); + endpoint.WithMetadata(new GeneratedCodeAttribute("Rocket.Surgery.LaunchPad.Api", "version")); + endpoint.AddOpenApiOperationTransformer(__GetRocketOpenApi); + ConfigureGetRocket(endpoint); + } + + { + var endpoint = group.MapMethods("", new string[] { "POST" }, new RequestDelegate(__CreateRocketRequestDelegate)); + var method = typeof(RocketsEndpoints).GetMethod(nameof(__CreateRocket), BindingFlags.NonPublic | BindingFlags.Static)!; + endpoint.WithMetadata(method); + endpoint.Add(builder => ApiEndpointMetadata.Populate, ProblemHttpResult>>(method, builder)); + var parameters = method.GetParameters(); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[0], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[1], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[2], false, false)); + endpoint.WithMetadata(new ApiAcceptsMetadata(typeof(global::Sample.Contracts.Rockets.CreateRocket.Request))); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(400, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(422, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(409, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithName("CreateRocket"); + endpoint.WithMetadata(new GeneratedCodeAttribute("Rocket.Surgery.LaunchPad.Api", "version")); + endpoint.AddOpenApiOperationTransformer(__CreateRocketOpenApi); + ConfigureCreateRocket(endpoint); + } + + { + var endpoint = group.MapMethods("/{id}/launch", new string[] { "POST" }, new RequestDelegate(__LaunchRocketRequestDelegate)); + var method = typeof(RocketsEndpoints).GetMethod(nameof(__LaunchRocket), BindingFlags.NonPublic | BindingFlags.Static)!; + endpoint.WithMetadata(method); + endpoint.Add(builder => ApiEndpointMetadata.Populate, ProblemHttpResult>>(method, builder)); + var parameters = method.GetParameters(); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[0], true, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[1], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[2], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[3], false, false)); + endpoint.WithMetadata(new ApiAcceptsMetadata(typeof(global::Sample.Contracts.Rockets.LaunchRocket.Request))); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(400, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(422, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(404, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(401, typeof(void))); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(403, typeof(void))); + endpoint.WithName("LaunchRocket"); + endpoint.RequireAuthorization("launch"); + endpoint.WithMetadata(new GeneratedCodeAttribute("Rocket.Surgery.LaunchPad.Api", "version")); + endpoint.AddOpenApiOperationTransformer(__LaunchRocketOpenApi); + ConfigureLaunchRocket(endpoint); + } + + { + var endpoint = group.MapMethods("/{id}/schedule", new string[] { "POST" }, new RequestDelegate(__ScheduleLaunchRequestDelegate)); + var method = typeof(RocketsEndpoints).GetMethod(nameof(__ScheduleLaunch), BindingFlags.NonPublic | BindingFlags.Static)!; + endpoint.WithMetadata(method); + endpoint.Add(builder => ApiEndpointMetadata.Populate, ProblemHttpResult>>(method, builder)); + var parameters = method.GetParameters(); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[0], true, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[1], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[2], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[3], false, false)); + endpoint.WithMetadata(new ApiAcceptsMetadata(typeof(global::Sample.Contracts.Rockets.ScheduleLaunch.Request))); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(400, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(422, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(404, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithName("ScheduleLaunch"); + endpoint.WithMetadata(new GeneratedCodeAttribute("Rocket.Surgery.LaunchPad.Api", "version")); + endpoint.AddOpenApiOperationTransformer(__ScheduleLaunchOpenApi); + ConfigureScheduleLaunch(endpoint); + } + + { + var endpoint = group.MapMethods("/plan", new string[] { "GET" }, new RequestDelegate(__GetLaunchPlanRequestDelegate)); + var method = typeof(RocketsEndpoints).GetMethod(nameof(__GetLaunchPlan), BindingFlags.NonPublic | BindingFlags.Static)!; + endpoint.WithMetadata(method); + endpoint.Add(builder => ApiEndpointMetadata.Populate>(method, builder)); + var parameters = method.GetParameters(); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[0], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[1], true, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[2], false, true)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[3], true, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[4], false, false)); + endpoint.WithMetadata(new ApiParameterBindingMetadata(parameters[5], false, false)); + endpoint.WithMetadata(new ProducesResponseTypeMetadata(400, typeof(ProblemDetails), new string[] { "application/problem+json" })); + endpoint.WithName("GetLaunchPlan"); + endpoint.WithMetadata(new GeneratedCodeAttribute("Rocket.Surgery.LaunchPad.Api", "version")); + endpoint.AddOpenApiOperationTransformer(__GetLaunchPlanOpenApi); + ConfigureGetLaunchPlan(endpoint); + } + + return group; + } + + /// Handles GET /api/rockets/{id:guid}. + private static async Task, ProblemHttpResult>> __GetRocket([FromRoute(Name = "id")] Guid @id, [FromServices] global::Keryx.ISender __sender, CancellationToken __cancellationToken) + { + var __wire = new global::Sample.Contracts.Rockets.GetRocket.Request(@id); + var __request = __wire; + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return TypedResults.Ok(__value); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error0) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error0.Id); + } + + if (__case is global::Sample.Contracts.Rockets.Forbidden __error1) + { + return ApiProblems.Problem(403, "Forbidden"); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.GetRocket.Request returned a Sample.Contracts.Rockets.GetRocketResult that holds none of its cases."); + } + + private static async Task __GetRocketRequestDelegate(HttpContext httpContext) + { + var __cancellationToken = httpContext.RequestAborted; + string? __raw_Id = httpContext.Request.RouteValues["id"]?.ToString(); + Guid @id = default; + if (!string.IsNullOrEmpty(__raw_Id)) + { + if (!Guid.TryParse(__raw_Id, CultureInfo.InvariantCulture, out var __parsed_Id)) + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + @id = __parsed_Id; + } + else + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + var __sender = httpContext.RequestServices.GetRequiredService(); + var __result = await __GetRocket(@id, __sender, __cancellationToken).ConfigureAwait(false); + await __result.ExecuteAsync(httpContext).ConfigureAwait(false); + } + + /// Describes GetRocket in the OpenAPI document: what its endpoint metadata can't say. + private static async Task __GetRocketOpenApi(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + await ApiOpenApi.Cases(operation, context, 403, new ApiOpenApiCase[] { new ApiOpenApiCase("Forbidden", "ForbiddenProblem", null, new ApiOpenApiMember[] { }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + } + + /// Customises the generated GetRocket endpoint. Implement it in your part of . + static partial void ConfigureGetRocket(IEndpointConventionBuilder endpoint); + /// Handles POST /api/rockets. + private static async Task, ProblemHttpResult>> __CreateRocket([FromBody] global::Sample.Contracts.Rockets.CreateRocket.Request __body, [FromServices] global::Keryx.ISender __sender, CancellationToken __cancellationToken) + { + var __wire = __body; + var __request = __wire; + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.CreateRocket.Response __value) + { + return TypedResults.Created("/api/rockets/" + Uri.EscapeDataString(ApiFormat.Value(__value.Id)), __value); + } + + if (__case is global::Sample.Contracts.Rockets.ValidationFailed __error0) + { + return ApiProblems.Problem(422, "ValidationFailed", "errors", __error0.Errors); + } + + if (__case is global::Sample.Contracts.Rockets.NameConflict __error1) + { + return ApiProblems.Problem(409, "NameConflict", "name", __error1.Name); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.CreateRocket.Request returned a Sample.Contracts.Rockets.CreateRocketResult that holds none of its cases."); + } + + private static async Task __CreateRocketRequestDelegate(HttpContext httpContext) + { + var __cancellationToken = httpContext.RequestAborted; + var(__read, __body) = await ApiBinding.ReadBodyAsync(httpContext, __cancellationToken).ConfigureAwait(false); + if (!__read) + return; + var __sender = httpContext.RequestServices.GetRequiredService(); + var __result = await __CreateRocket(__body, __sender, __cancellationToken).ConfigureAwait(false); + await __result.ExecuteAsync(httpContext).ConfigureAwait(false); + } + + /// Describes CreateRocket in the OpenAPI document: what its endpoint metadata can't say. + private static async Task __CreateRocketOpenApi(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiOpenApi.Location(operation); + await ApiOpenApi.Cases(operation, context, 409, new ApiOpenApiCase[] { new ApiOpenApiCase("NameConflict", "NameConflictProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("name", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("ValidationFailed", "ValidationFailedProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("errors", typeof(string[]), null) }) }, cancellationToken).ConfigureAwait(false); + } + + /// Customises the generated CreateRocket endpoint. Implement it in your part of . + static partial void ConfigureCreateRocket(IEndpointConventionBuilder endpoint); + /// Handles POST /api/rockets/{id}/launch. + private static async Task, ProblemHttpResult>> __LaunchRocket([FromRoute(Name = "id")] Guid @id, [FromBody] global::Sample.Contracts.Rockets.LaunchRocket.Request __body, [FromServices] global::Keryx.ISender __sender, CancellationToken __cancellationToken) + { + var __wire = __body; + __wire = __wire with + { + Id = @id + }; + var __request = __wire; + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return TypedResults.Ok(__value); + } + + if (__case is global::Sample.Contracts.Rockets.NotReady __error0) + { + return ApiProblems.Problem(422, "NotReady", "reason", __error0.Reason); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error1) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error1.Id); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.LaunchRocket.Request returned a Sample.Contracts.Rockets.LaunchRocketResult that holds none of its cases."); + } + + private static async Task __LaunchRocketRequestDelegate(HttpContext httpContext) + { + var __cancellationToken = httpContext.RequestAborted; + string? __raw_Id = httpContext.Request.RouteValues["id"]?.ToString(); + Guid @id = default; + if (!string.IsNullOrEmpty(__raw_Id)) + { + if (!Guid.TryParse(__raw_Id, CultureInfo.InvariantCulture, out var __parsed_Id)) + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + @id = __parsed_Id; + } + else + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + var(__read, __body) = await ApiBinding.ReadBodyAsync(httpContext, __cancellationToken).ConfigureAwait(false); + if (!__read) + return; + var __sender = httpContext.RequestServices.GetRequiredService(); + var __result = await __LaunchRocket(@id, __body, __sender, __cancellationToken).ConfigureAwait(false); + await __result.ExecuteAsync(httpContext).ConfigureAwait(false); + } + + /// Describes LaunchRocket in the OpenAPI document: what its endpoint metadata can't say. + private static async Task __LaunchRocketOpenApi(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiOpenApi.Authenticate(operation); + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("NotReady", "NotReadyProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("reason", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + } + + /// Customises the generated LaunchRocket endpoint. Implement it in your part of . + static partial void ConfigureLaunchRocket(IEndpointConventionBuilder endpoint); + /// Handles POST /api/rockets/{id}/schedule. + private static async Task, ProblemHttpResult>> __ScheduleLaunch([FromRoute(Name = "id")] Guid @id, [FromBody] global::Sample.Contracts.Rockets.ScheduleLaunch.Request __body, [FromServices] global::Keryx.ISender __sender, CancellationToken __cancellationToken) + { + var __wire = __body; + __wire = __wire with + { + Id = @id + }; + var __request = __wire; + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + var __case = __response.Value; + if (__case is global::Sample.Contracts.Rockets.RocketModel __value) + { + return TypedResults.Ok(__value); + } + + if (__case is global::Sample.Contracts.Rockets.NotReady __error0) + { + return ApiProblems.Problem(422, "NotReady", "reason", __error0.Reason); + } + + if (__case is global::Sample.Contracts.Rockets.RocketNotFound __error1) + { + return ApiProblems.Problem(404, "RocketNotFound", "id", __error1.Id); + } + + throw new InvalidOperationException("Sample.Contracts.Rockets.ScheduleLaunch.Request returned a Sample.Contracts.Rockets.LaunchRocketResult that holds none of its cases."); + } + + private static async Task __ScheduleLaunchRequestDelegate(HttpContext httpContext) + { + var __cancellationToken = httpContext.RequestAborted; + string? __raw_Id = httpContext.Request.RouteValues["id"]?.ToString(); + Guid @id = default; + if (!string.IsNullOrEmpty(__raw_Id)) + { + if (!Guid.TryParse(__raw_Id, CultureInfo.InvariantCulture, out var __parsed_Id)) + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + @id = __parsed_Id; + } + else + { + await ApiBinding.BadRequestAsync(httpContext, "id", "route value").ConfigureAwait(false); + return; + } + + var(__read, __body) = await ApiBinding.ReadBodyAsync(httpContext, __cancellationToken).ConfigureAwait(false); + if (!__read) + return; + var __sender = httpContext.RequestServices.GetRequiredService(); + var __result = await __ScheduleLaunch(@id, __body, __sender, __cancellationToken).ConfigureAwait(false); + await __result.ExecuteAsync(httpContext).ConfigureAwait(false); + } + + /// Describes ScheduleLaunch in the OpenAPI document: what its endpoint metadata can't say. + private static async Task __ScheduleLaunchOpenApi(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + await ApiOpenApi.Cases(operation, context, 404, new ApiOpenApiCase[] { new ApiOpenApiCase("RocketNotFound", "RocketNotFoundProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("id", typeof(Guid), null) }) }, cancellationToken).ConfigureAwait(false); + await ApiOpenApi.Cases(operation, context, 422, new ApiOpenApiCase[] { new ApiOpenApiCase("NotReady", "NotReadyProblem", null, new ApiOpenApiMember[] { new ApiOpenApiMember("reason", typeof(string), null) }) }, cancellationToken).ConfigureAwait(false); + ApiSchemaRule.Body(operation, context, "window").Required().NotEmpty().MaxLength(40).Pattern("^[A-Za-z ]+$"); + ApiSchemaRule.Body(operation, context, "crew").Minimum("1").Maximum("10"); + ApiSchemaRule.Body(operation, context, "contact").Format("email"); + } + + /// Customises the generated ScheduleLaunch endpoint. Implement it in your part of . + static partial void ConfigureScheduleLaunch(IEndpointConventionBuilder endpoint); + /// Handles GET /api/rockets/plan. + private static async Task> __GetLaunchPlan([FromQuery(Name = "name")] string @name, [FromQuery(Name = "take")] int @take, [FromQuery(Name = "site")] string? @site, [FromQuery(Name = "limit")] int @limit, [FromServices] global::Keryx.ISender __sender, CancellationToken __cancellationToken) + { + var __wire = new global::Sample.Contracts.Rockets.GetLaunchPlan.Request(@name, @take, @site, @limit); + var __request = __wire; + var __response = await __sender.Send(__request, __cancellationToken).ConfigureAwait(false); + return TypedResults.Ok(__response); + } + + private static async Task __GetLaunchPlanRequestDelegate(HttpContext httpContext) + { + var __cancellationToken = httpContext.RequestAborted; + string? __raw_Name = httpContext.Request.Query["name"]; + if (string.IsNullOrEmpty(__raw_Name)) + { + await ApiBinding.BadRequestAsync(httpContext, "name", "query string value").ConfigureAwait(false); + return; + } + + var @name = __raw_Name; + string? __raw_Take = httpContext.Request.Query["take"]; + int @take = default; + if (!string.IsNullOrEmpty(__raw_Take)) + { + if (!int.TryParse(__raw_Take, CultureInfo.InvariantCulture, out var __parsed_Take)) + { + await ApiBinding.BadRequestAsync(httpContext, "take", "query string value").ConfigureAwait(false); + return; + } + + @take = __parsed_Take; + } + else + { + await ApiBinding.BadRequestAsync(httpContext, "take", "query string value").ConfigureAwait(false); + return; + } + + string? __raw_Site = httpContext.Request.Query["site"]; + var @site = string.IsNullOrEmpty(__raw_Site) ? null : __raw_Site; + string? __raw_Limit = httpContext.Request.Query["limit"]; + int @limit = default; + if (!string.IsNullOrEmpty(__raw_Limit)) + { + if (!int.TryParse(__raw_Limit, CultureInfo.InvariantCulture, out var __parsed_Limit)) + { + await ApiBinding.BadRequestAsync(httpContext, "limit", "query string value").ConfigureAwait(false); + return; + } + + @limit = __parsed_Limit; + } + else + { + await ApiBinding.BadRequestAsync(httpContext, "limit", "query string value").ConfigureAwait(false); + return; + } + + var __sender = httpContext.RequestServices.GetRequiredService(); + var __result = await __GetLaunchPlan(@name, @take, @site, @limit, __sender, __cancellationToken).ConfigureAwait(false); + await __result.ExecuteAsync(httpContext).ConfigureAwait(false); + } + + /// Describes GetLaunchPlan in the OpenAPI document: what its endpoint metadata can't say. + private static Task __GetLaunchPlanOpenApi(global::Microsoft.OpenApi.OpenApiOperation operation, global::Microsoft.AspNetCore.OpenApi.OpenApiOperationTransformerContext context, CancellationToken cancellationToken) + { + ApiSchemaRule.Parameter(operation, "name").MinLength(2).MaxLength(20); + ApiSchemaRule.Parameter(operation, "take").ExclusiveMinimum("0").Maximum("100"); + ApiSchemaRule.Parameter(operation, "site").Format("uri"); + return Task.CompletedTask; + } + + /// Customises the generated GetLaunchPlan endpoint. Implement it in your part of . + static partial void ConfigureGetLaunchPlan(IEndpointConventionBuilder endpoint); + } +} diff --git a/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi.verified.txt b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi.verified.txt new file mode 100644 index 0000000000..bec1899dcc --- /dev/null +++ b/test/Api.Generators.Tests/snapshots/OpenApiGeneratorTests.Should_State_The_Rules_Of_LaunchPad_Validation_host=MinimalApi.verified.txt @@ -0,0 +1,9 @@ +{ + AnalyzerDiagnostics: { + Rocket.Surgery.LaunchPad.Analyzers.Api.OperationHostAnalyzer: [] + }, + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Analyzers.Api.MinimalApi.MinimalApiGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs index 702db7c46d..e06580b566 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs @@ -21,16 +21,23 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.AddressGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.AddressGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DraftGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.DraftGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.DraftGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShippingAddressGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs index c63315f1e5..e303421579 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs @@ -71,6 +71,19 @@ public bool TryValidateMember(global::Sample.Address value, string member, out g return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Address), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("City", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("PostCode", "MaxLength(8)", "Must"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Country", "NotEqual(City)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Region", "NotEqual(Notes)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Street", "Must") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs index 681dc225db..2bf61b95f0 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Draft value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Draft), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("City", "NotEmpty") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Draft options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs index cae2d6e7ad..085cf39f94 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs @@ -88,6 +88,18 @@ public bool TryValidateMember(global::Sample.ShippingAddress value, string membe return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.ShippingAddress), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Recipient", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("City", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("PostCode", "MaxLength(8)", "Must", "MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Country", "NotEqual(City)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs index 565c6e538c..e820724960 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs @@ -77,6 +77,16 @@ public bool TryValidateMember(global::Contracts.Address value, string member, ou return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Contracts.Address), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("City", "NotEmpty", "MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("PostCode", "Must") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs index 3b82c4ca04..4901f2ba98 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs @@ -59,6 +59,16 @@ public bool TryValidateMember(global::Contracts.Parcel value, string member, out return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Contracts.Parcel), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Weight", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Label", "NotEmpty") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Contracts.Parcel options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs index 4240c74773..1b15e145ab 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs @@ -22,6 +22,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.ContractsValidatorsServiceCollectionExtensions.AddContractsValidators(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); @@ -33,6 +34,8 @@ public static class ApplicationValidatorsServiceCollectionExtensions global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Contracts.AddressInApplicationGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Contracts.AddressInApplicationGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); @@ -44,16 +47,24 @@ public static class ApplicationValidatorsServiceCollectionExtensions global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Contracts.ParcelInApplicationGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Contracts.ParcelInApplicationGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Contracts.ParcelInApplicationGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CarGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.CarGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.CarGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.HoldGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.HoldGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShippingAddressGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs index 96723fb348..d135ee31e5 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs @@ -61,6 +61,17 @@ public bool TryValidateMember(global::Sample.Car value, string member, out globa return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Car), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Wheels", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Doors", "InclusiveBetween(2, 5)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Car options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs index 8754ee7a81..715de6a5d7 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs @@ -61,6 +61,15 @@ public bool TryValidateMember(global::Sample.Hold value, string member, out glob return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Hold), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Code", "MustAsync") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs index 443a4e4b40..19e00f0f3b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs @@ -73,6 +73,16 @@ public bool TryValidateMember(global::Sample.ShippingAddress value, string membe return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.ShippingAddress), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("City", "NotEmpty", "MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("PostCode", "Must") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs index 62db3a52cc..3894af0974 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs @@ -21,33 +21,48 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CircleGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.CircleGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.CircleGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.IHasNameGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.IHasNameGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.IHasNameGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.IPricedGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.IPricedGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PointGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PointGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PolygonGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PolygonGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.PolygonGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.ShapeGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShapeGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.ShapeGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.SquareGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.SquareGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs index 5cbf670e11..eb99c6e586 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Circle value, string member, out gl return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Circle), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Area", "GreaterThan(0)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Circle options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs index ef0dc0cf2e..3553049f10 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.IHasName value, string member, out return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.IHasName), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.IHasName options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs index 04b080214d..928d38f60d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs @@ -59,6 +59,15 @@ public bool TryValidateMember(global::Sample.IPriced value, string member, out g return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.IPriced), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Price", "GreaterThan(0m)", "Must") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs index 9e38fa2ac1..b06d3f35a2 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs @@ -56,5 +56,14 @@ public bool TryValidateMember(global::Sample.Point value, string member, out glo TryValidateMember(value, member, out var result); return new(result); } + + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Point), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Price", "GreaterThan(0m)", "Must") + ); } } diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs index 1eb1457a08..2c85e73c46 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs @@ -57,6 +57,16 @@ public bool TryValidateMember(global::Sample.Polygon value, string member, out g return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Polygon), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Area", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Sides", "GreaterThan(2)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Polygon options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs index cee0bd7190..7c99ace3a9 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Shape value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Shape), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Area", "GreaterThan(0)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Shape options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs index 73f4b451f0..ab1ac52c40 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs @@ -75,6 +75,19 @@ public bool TryValidateMember(global::Sample.Square value, string member, out gl return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Square), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Area", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Sides", "GreaterThan(2)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Price", "GreaterThan(0m)", "Must"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Label", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs index 6f7dbbd539..9f6b83173a 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs @@ -21,14 +21,21 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.BodyGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.BodyGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.BodyGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PlanetGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PlanetGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PlanetModelGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PlanetModelGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs index 0ab9eb3201..04cf4b7907 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Body value, string member, out glob return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Body), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Mass", "GreaterThan(0)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.Body options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs index 2f6580b698..0c713164b2 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs @@ -80,6 +80,18 @@ public bool TryValidateMember(global::Sample.Planet value, string member, out gl return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Planet), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Mass", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty", "MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Moons", "GreaterThanOrEqualTo(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Star", "Must") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs index 1f2255ac57..30bcd032e6 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs @@ -87,6 +87,18 @@ public bool TryValidateMember(global::Sample.PlanetModel value, string member, o return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.PlanetModel), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Mass", "GreaterThan(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Moons", "GreaterThanOrEqualTo(0)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty", "MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Comment", "MaxLength(20)") + ); + private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync MutableTargetValidator => _mutableTargetValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync ?? throw new global::System.InvalidOperationException("PlanetModelGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs index ce9cb9e0d9..33aca37b17 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs @@ -51,6 +51,15 @@ public bool TryValidateMember(global::INamed value, string member, out global::R return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::INamed), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs index 9065a492b2..e04cc064eb 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs @@ -69,6 +69,17 @@ public bool TryValidateMember(global::Launcher value, string member, out global: return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Launcher), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Engine"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Count", "GreaterThan(0)") + ); + private global::Rocket.Surgery.LaunchPad.Validation.IValidate EngineValidator => _engineValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs index 235e144b0d..04d414f525 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs @@ -21,13 +21,20 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.BookingGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.BookingGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ManifestGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ManifestGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ScheduleGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ScheduleGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs index 4dd2122621..c4717fe7b4 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs @@ -73,6 +73,16 @@ public bool TryValidateMember(global::Sample.Booking value, string member, out g return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Booking), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Serial", "NotEmpty", "MustAsync", "when MustAsync"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Pad", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -92,7 +102,7 @@ public bool TryValidateMember(global::Sample.Booking value, string member, out g /// /// The rules of Serial. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotEmpty", "MustAsync", "MustAsync", ReadsValue = true)] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotEmpty", "MustAsync", "when MustAsync", ReadsValue = true)] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public async global::System.Threading.Tasks.ValueTask EnsureSerial(global::Sample.Booking instance, string value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs index 95905fe2ac..73dbb0b6ef 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs @@ -14,7 +14,7 @@ partial class BookingValidator /// /// The rules Validate declares for . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotEmpty", "MustAsync", "MustAsync", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotEmpty", "MustAsync", "when MustAsync", ReadsValue = true, DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] internal async global::System.Threading.Tasks.ValueTask ValidateBooking_Serial(global::Sample.Booking __instance, string __value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink, global::System.Threading.CancellationToken __cancellationToken) diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs index 2652d29d00..922051b719 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs @@ -80,6 +80,17 @@ public bool TryValidateMember(global::Sample.Manifest value, string member, out return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Manifest), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Booking"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Others") + ); + private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync BookingValidator => _bookingValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync ?? throw new global::System.InvalidOperationException("ManifestGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs index 3670cdff0a..6fb93bdc6d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs @@ -68,6 +68,15 @@ public bool TryValidateMember(global::Sample.Schedule value, string member, out return sink.ToResult(); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Schedule), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Manifest", "NotNull") + ); + private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync ManifestValidator => _manifestValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync ?? throw new global::System.InvalidOperationException("ScheduleGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs index 76ad11c8e7..b79d301a55 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs @@ -21,9 +21,12 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.Operations.BuildLauncher_RequestGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.Operations.BuildLauncher_RequestGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs index 7b2a4a37c7..7621bf2d2c 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs @@ -39,7 +39,7 @@ public static void ValidateBuildLauncher_Request_Name(string __value, global::Sa /// /// The rules Validate declares for . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotNull", "Matches(SerialPattern)", DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotNull", "when Matches(SerialPattern)", DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] public static void ValidateBuildLauncher_Request_Serial(string? __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) @@ -59,7 +59,7 @@ public static void ValidateBuildLauncher_Request_Serial(string? __value, global: /// /// The rules Validate declares for . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Seats", "NotNull", "InclusiveBetween(1, 7)", "Null", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Seats", "when NotNull", "when InclusiveBetween(1, 7)", "when Null", ReadsValue = true, DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] public static void ValidateBuildLauncher_Request_Seats(global::Sample.Operations.BuildLauncher.Request __instance, int? __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) @@ -143,7 +143,7 @@ public static void ValidateBuildLauncher_Request_Budget(global::Sample.Operation /// /// The rules Validate declares for . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tags", "NotEmpty", "MaxLength(5)", DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tags", "each NotEmpty", "each MaxLength(5)", DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] public static void ValidateBuildLauncher_Request_Tags(string[] __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) @@ -176,7 +176,7 @@ public static void ValidateBuildLauncher_Request_Tags(string[] __value, global:: /// /// The rules Validate declares for . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "GreaterThan(0)", "Must", "EnsureEach", "MinLength(1)", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "each when GreaterThan(0)", "each when Must", "when MinLength(1)", ReadsValue = true, DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] public static void ValidateBuildLauncher_Request_Engines(global::Sample.Operations.BuildLauncher.Request __instance, global::System.Collections.Generic.IReadOnlyList __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) @@ -228,7 +228,7 @@ bool __rule0(string name) /// /// The rules Validate declares for a as a whole. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "Must", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "when Must", ReadsValue = true, DeclaredBy = nameof(Validate))] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [global::System.Runtime.CompilerServices.CompilerGenerated] public static void ValidateBuildLauncher_Request(global::Sample.Operations.BuildLauncher.Request __instance, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs index fbb1205da6..0b5d1f1a37 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs @@ -83,6 +83,22 @@ public bool TryValidateMember(global::Sample.Operations.BuildLauncher.Request va return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Operations.BuildLauncher.Request), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty", "MaxLength(10)", "Matches(\"^[A-Z]\")"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Serial", "NotNull", "when Matches(SerialPattern)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Seats", "when NotNull", "when InclusiveBetween(1, 7)", "when Null"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Built", "LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime))"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Launched", "GreaterThanOrEqualTo(x => x.Built)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Budget", "Must", "Must"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Tags", "each NotEmpty", "each MaxLength(5)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Engines", "each when GreaterThan(0)", "each when Must", "when MinLength(1)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -121,7 +137,7 @@ public void EnsureName(string value, ref global::Rocket.Surgery.LaunchPad.Valida /// /// The rules of Serial. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotNull", "Matches(SerialPattern)")] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotNull", "when Matches(SerialPattern)")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public void EnsureSerial(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { @@ -131,7 +147,7 @@ public void EnsureSerial(string? value, ref global::Rocket.Surgery.LaunchPad.Val /// /// The rules of Seats. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Seats", "NotNull", "InclusiveBetween(1, 7)", "Null", ReadsValue = true)] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Seats", "when NotNull", "when InclusiveBetween(1, 7)", "when Null", ReadsValue = true)] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public void EnsureSeats(global::Sample.Operations.BuildLauncher.Request instance, int? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { @@ -171,7 +187,7 @@ public void EnsureBudget(global::Sample.Operations.BuildLauncher.Request instanc /// /// The rules of Tags. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tags", "NotEmpty", "MaxLength(5)")] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tags", "each NotEmpty", "each MaxLength(5)")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public void EnsureTags(string[] value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { @@ -181,7 +197,7 @@ public void EnsureTags(string[] value, ref global::Rocket.Surgery.LaunchPad.Vali /// /// The rules of Engines. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "GreaterThan(0)", "Must", "EnsureEach", "MinLength(1)", ReadsValue = true)] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "each when GreaterThan(0)", "each when Must", "when MinLength(1)", ReadsValue = true)] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public void EnsureEngines(global::Sample.Operations.BuildLauncher.Request instance, global::System.Collections.Generic.IReadOnlyList value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { @@ -191,7 +207,7 @@ public void EnsureEngines(global::Sample.Operations.BuildLauncher.Request instan /// /// The rules of a as a whole. /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "Must", ReadsValue = true)] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "when Must", ReadsValue = true)] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public void Ensure_Value(global::Sample.Operations.BuildLauncher.Request instance, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs index 9edc3c77f6..8bf3c10245 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs @@ -81,6 +81,24 @@ public bool TryValidateMember(global::Account value, string member, out global:: return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Account), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("UserName", "NotEmpty", "Length(3, 20)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Notes", "NotNull", "MaxLength(100)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Age", "NotNull"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Contact", "EmailAddress", "Url"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Years", "InclusiveBetween(18, 120)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Share", "GreaterThan(0)", "LessThanOrEqualTo(1)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Score", "ExclusiveBetween(0, 10)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Pin", "Matches(\"^(?:[0-9]{4})$\")"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Roles", "MinLength(1)", "MaxLength(3)", "Length(1, 3)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Confirmation", "Equal(Password)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs index db04dc67e4..6184700611 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Named value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Named), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs index de2ccd733e..796a78868d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Outer.Inner value, string member, o return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Outer.Inner), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Values", "MaxLength(3)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs index f5e72f5026..3332287785 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs @@ -54,6 +54,16 @@ public bool TryValidateMember(global::Sample.Position value, string member, out return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Position), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Latitude", "InclusiveBetween(-90, 90)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Longitude", "InclusiveBetween(-180, 180)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs index 82ba541d2f..1ec8571d35 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs @@ -57,6 +57,16 @@ public bool TryValidateMember(global::Sample.Stage value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Stage), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Thrust", "GreaterThan(0)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs index 9aab47ed0a..2463daa8e8 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs @@ -21,12 +21,17 @@ public static class ApplicationValidatorsServiceCollectionExtensions /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DelayGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.DelayGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.RetryOptionsGeneratedValidator>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.RetryOptionsGeneratedValidator.Manifest); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.RetryOptionsGeneratedValidator>()); return services; } diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs index 69b0369585..3b3cd2881c 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs @@ -51,6 +51,15 @@ public bool TryValidateMember(global::Sample.Delay value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Delay), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Milliseconds", "GreaterThan(0)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs index 3c9ffd5680..44715159ad 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.RetryOptions value, string member, return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.RetryOptions), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Attempts", "InclusiveBetween(1, 10)") + ); + /// global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.RetryOptions options) { diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs index e44597d338..65f886e6da 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs @@ -51,6 +51,15 @@ public bool TryValidateMember(global::Mistakes value, string member, out global: return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Mistakes), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Fine", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs index c57d6ed9b4..b96c08fa01 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs @@ -53,6 +53,15 @@ public bool TryValidateMember(global::Sample.Crew value, string member, out glob return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Crew), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Captain", "NotEmpty") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs index fc58eb8095..778c425f4c 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs @@ -77,6 +77,20 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Launcher), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Crew"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Booster", "NotNull"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Core"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Stages", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Backups"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Reserve") + ); + private global::Rocket.Surgery.LaunchPad.Validation.IValidate CrewValidator => _crewValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs index 33dce3d37a..1ca442b136 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs @@ -51,6 +51,15 @@ public bool TryValidateMember(global::Sample.Stage value, string member, out glo return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Stage), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Thrust", "GreaterThan(0)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs index 24dd8cc2a6..9e6968a076 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs @@ -77,6 +77,22 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out return new(result); } + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Launcher), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty", "MinLength(3)", "MaxLength(30)", "Matches(\"^[A-Z]\")"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Fuel", "IsInEnum"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Engines", "InclusiveBetween(1, 33)", "when NotEqual(13)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Price", "GreaterThanOrEqualTo(0)", "PrecisionScale(8, 2)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Built", "NotDefault", "GreaterThan(\"2000-01-01\")"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Launched", "GreaterThanOrEqualTo(Built)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Fins", "Must(IsOdd)"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Nickname", "Must(IsShort)") + ); + /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -140,7 +156,7 @@ public static void EnsureFuel(global::Sample.Fuel value, ref global::Rocket.Surg /// /// The rules of . /// - [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "InclusiveBetween(1, 33)", "NotEqual(13)")] + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "InclusiveBetween(1, 33)", "when NotEqual(13)")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public static void EnsureEngines(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) { diff --git a/test/Validation.AspNetCore.Tests/Validation.AspNetCore.Tests.csproj b/test/Validation.AspNetCore.Tests/Validation.AspNetCore.Tests.csproj new file mode 100644 index 0000000000..9448241a71 --- /dev/null +++ b/test/Validation.AspNetCore.Tests/Validation.AspNetCore.Tests.csproj @@ -0,0 +1,21 @@ + + + $(LaunchPadTargetFrameworks) + + + + + + + + + + + + + + diff --git a/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.Describes_The_Rules_In_The_Schema.verified.txt b/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.Describes_The_Rules_In_The_Schema.verified.txt new file mode 100644 index 0000000000..c7bb2d6e86 --- /dev/null +++ b/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.Describes_The_Rules_In_The_Schema.verified.txt @@ -0,0 +1,94 @@ +{ + "required": [ + "serialNumber", + "name", + "tags" + ], + "type": "object", + "properties": { + "serialNumber": { + "maxLength": 30, + "minLength": 10, + "type": "string" + }, + "name": { + "type": [ + "null", + "string" + ] + }, + "thrust": { + "exclusiveMinimum": 0, + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?(?:[eE][\u002B-]?\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "crew": { + "maximum": 100, + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "code": { + "pattern": "^[A-Z]\u002B$", + "type": "string" + }, + "contact": { + "type": "string", + "format": "email" + }, + "homepage": { + "type": [ + "null", + "string" + ], + "format": "uri" + }, + "tags": { + "minItems": 1, + "type": "array", + "items": { + "maxLength": 12, + "type": "string" + } + }, + "budget": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "spent": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "notes": { + "type": [ + "null", + "string" + ] + }, + "stages": { + "maximum": 10, + "minimum": 1, + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } +} \ No newline at end of file diff --git a/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.cs b/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.cs new file mode 100644 index 0000000000..d62f292152 --- /dev/null +++ b/test/Validation.AspNetCore.Tests/ValidationOpenApiSchemaTransformerTests.cs @@ -0,0 +1,122 @@ +using System.Text.Json.Nodes; + +using Joinery.Dovetail; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; + +using Rocket.Surgery.LaunchPad.AspNetCore.Joints; +using Rocket.Surgery.LaunchPad.AspNetCore.Validation; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.AspNetCore.Tests; + +public partial class ValidationOpenApiSchemaTransformerTests +{ + // Rules from attributes, from a function, from a base class and from an interface, all in the one schema; the conditional rule, the + // warning and the rule that compares two members are left out. + [Test] + public async Task Describes_The_Rules_In_The_Schema() + { + await using var app = await Start(); + using var client = app.GetTestClient(); + + var document = JsonNode.Parse(await client.GetStringAsync(new Uri("/openapi/v1.json", UriKind.Relative), CancellationToken.None))!; + var schema = document["components"]!["schemas"]![nameof(Launcher)]!; + + await Verify(schema.ToJsonString(new() { WriteIndented = true, })); + } + + [Test] + public async Task Requires_The_Members_Of_The_Problem_Details() + { + await using var app = await Start(); + using var client = app.GetTestClient(); + + var document = JsonNode.Parse(await client.GetStringAsync(new Uri("/openapi/v1.json", UriKind.Relative), CancellationToken.None))!; + var schemas = document["components"]!["schemas"]!; + + await Required(schemas["ProblemDetails"]).Should().BeEquivalentTo(["type", "title"], CollectionOrdering.Matching); + await Required(schemas["HttpValidationProblemDetails"]).Should().BeEquivalentTo(["type", "title", "errors"], CollectionOrdering.Matching); + await Required(schemas[nameof(ValidationFailedProblemDetails)]).Should().BeEquivalentTo(["type", "title", "errors"], CollectionOrdering.Matching); + } + + private static string?[] Required(JsonNode? schema) => [.. schema!["required"]!.AsArray().Select(x => x!.GetValue()),]; + + private static async Task Start() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseTestServer(); + builder.Services.AddOpenApi(); + builder.Services.AddValidationAspNetCoreTestsValidators(); + new ValidationOpenApiJoint().Register(await Context(), builder.Services); + var app = builder.Build(); + app.MapOpenApi(); + app.MapPost("/launchers", (Launcher launcher) => TypedResults.Ok(launcher)).ProducesProblem(500).ProducesValidationProblem(); + app.MapGet("/failure", () => TypedResults.UnprocessableEntity(new ValidationFailedProblemDetails())); + await app.StartAsync(); + return app; + } + + public interface IHasContact + { + [EmailAddress] + string Contact { get; } + } + + public abstract class Vehicle + { + [InclusiveBetween(1, 10)] + public int Stages { get; set; } + } + + public sealed partial class Launcher : Vehicle, IHasContact + { + [NotEmpty] + [MinLength(10)] + [MaxLength(30)] + public string SerialNumber { get; set; } = ""; + + // The repository's global usings make [NotNull] the nullable analysis attribute: the rule is named in full. + [Rocket.Surgery.LaunchPad.Validation.Rules.NotNull] + public string? Name { get; set; } + + [GreaterThan(0)] + public double Thrust { get; set; } + + [LessThanOrEqualTo(100)] + [GreaterThanOrEqualTo(1, Severity = ValidationSeverity.Warning)] + public int Crew { get; set; } + + public string Code { get; set; } = ""; + + public string Contact { get; set; } = ""; + + public string? Homepage { get; set; } + + [NotEmpty] + public List Tags { get; set; } = []; + + public int Budget { get; set; } + + [LessThanOrEqualTo(Member = nameof(Budget))] + public int Spent { get; set; } + + public string? Notes { get; set; } + + [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Read by the validation generator.")] + private static void Validate(IValidationBuilder v) + { + v.Ensure(x => x.Code).Matches("^[A-Z]+$"); + v.Ensure(x => x.Homepage).Url(); + v.Ensure(x => x.Notes).MaxLength(200).When(x => x.Crew > 0); + v.EnsureEach(x => x.Tags).MaxLength(12); + } + } + + private static async Task Context() => + await DovetailContext.FromAsync(DovetailContextBuilder.Create([], new Dictionary(), [])); +} diff --git a/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs b/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs new file mode 100644 index 0000000000..3009a461e9 --- /dev/null +++ b/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs @@ -0,0 +1,192 @@ +using System.Reflection; +using System.Text.Json; + +using Joinery.Dovetail; +using Joinery.Dovetail.Attributes; +using Joinery.Dovetail.Infrastructure; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using Rocket.Surgery.LaunchPad.AspNetCore.Joints; +using Rocket.Surgery.LaunchPad.AspNetCore.Rivets; +using Rocket.Surgery.LaunchPad.AspNetCore.Validation; +using Rocket.Surgery.LaunchPad.Foundation.Joints; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.AspNetCore.Tests; + +public class ValidationProblemDetailsJointTests +{ + [Test] + public async Task Is_Exported_As_An_Application_Joint_That_Runs_After_The_Problem_Details_Joint() + { + var export = ValidationExports.Joints().Single(x => x.Joint is ValidationProblemDetailsJoint); + + await export.HostType.Should().BeEqualTo(DovetailHostType.Undefined); + var x = await export.Dependencies.Should().HaveSingleItem(); + await x.Direction.Should().BeEqualTo(DependencyDirection.DependsOn); + await x.Type.Should().BeEqualTo(typeof(ProblemDetailsJoint)); + await typeof(ValidationProblemDetailsJoint).GetCustomAttribute()!.Category.ToString().Should().BeEqualTo(DovetailCategory.Application); + } + + [Test] + public async Task Maps_A_Validation_Failure_To_422_And_Keeps_The_Previous_Status_Codes() + { + var services = new ServiceCollection(); + services.AddExceptionHandler(options => options.StatusCodeSelector = _ => StatusCodes.Status404NotFound); + new ValidationProblemDetailsJoint().Register(await Context(), services); + using var provider = services.BuildServiceProvider(); + + var selector = await provider.GetRequiredService>().Value.StatusCodeSelector.Should().NotBeNull(); + + await selector(Failures.Exception(new Probe { Name = "", })).Should().BeEqualTo(StatusCodes.Status422UnprocessableEntity); + await selector(new InvalidOperationException()).Should().BeEqualTo(StatusCodes.Status404NotFound); + } + + [Test] + public async Task Registers_The_Problem_Details_Writer_Once() + { + var services = new ServiceCollection(); + var joint = new ValidationProblemDetailsJoint(); + joint.Register(await Context(), services); + joint.Register(await Context(), services); + + await services + .Count(d => d.ServiceType == typeof(IProblemDetailsWriter) && d.ImplementationType == typeof(ValidationProblemDetailsJoint.ValidationFailedProblemDetailsWriter)) + .Should() + .BeEqualTo(1); + } + + // The errors by the path of their member, each with its code, its severity and the values of its message's placeholders; the warning apart. + [Test] + public async Task Answers_A_Controller_With_The_Failures_Grouped_By_Path() + { + var context = new ExceptionContext(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), []) + { + Exception = Failures.Exception(new Probe { Name = "x", Stages = [new(0), new(5),], Crew = 12, }), + }; + + new ValidationProblemDetailsJoint.ValidationFailedExceptionFilter().OnException(context); + + await context.ExceptionHandled.Should().BeTrue(); + var details = await Assert.That(( await Assert.That(context.Result).IsTypeOf() )!.Value).IsTypeOf(); + await details!.Status.Should().BeEqualTo(StatusCodes.Status422UnprocessableEntity); + await details.Errors.Keys.Should().BeEquivalentTo(["Name", "Stages[0].Thrust"], CollectionOrdering.Matching); + await details.Errors["Name"].Select(x => x.Code).Should().BeEquivalentTo(["MinLength", "Matches"], CollectionOrdering.Matching); + await details.Errors["Name"][0].Message.Should().BeEqualTo("Name must be at least 3 characters long"); + await details.Errors["Name"][0].Arguments["Min"].Should().BeEqualTo("3"); + await details.Errors["Name"][0].Severity.Should().BeEqualTo("Error"); + await details.Notices.Select(x => x.Path + ":" + x.Code + ":" + x.Severity).Should().BeEquivalentTo(["Crew:LessThanOrEqualTo:Warning"]); + } + + // The writer serializes through the HTTP JSON options' JSON contexts: LaunchPad takes ASP.NET Core's reflection resolver out of them. + [Test] + public async Task Writes_The_Failures_Through_The_Json_Contexts() + { + var services = new ServiceCollection().AddLogging(); + var context = await Context(); + new SystemTextJsonJoint().Register(context, services); + new SystemJsonTextJoint().Register(context, services); + new ValidationProblemDetailsJoint().Register(context, services); + using var provider = services.BuildServiceProvider(); + var httpContext = new DefaultHttpContext { RequestServices = provider, }; + using var body = new MemoryStream(); + httpContext.Response.Body = body; + + await new ValidationProblemDetailsJoint.ValidationFailedProblemDetailsWriter().WriteAsync( + new() { HttpContext = httpContext, Exception = Failures.Exception(new Probe { Name = "", }), ProblemDetails = new() { Instance = "/rockets", }, } + ); + + using var document = JsonDocument.Parse(body.ToArray()); + await httpContext.Response.StatusCode.Should().BeEqualTo(StatusCodes.Status422UnprocessableEntity); + await document.RootElement.GetProperty("instance").GetString().Should().BeEqualTo("/rockets"); + var first = document.RootElement.GetProperty("errors").GetProperty("Name")[0]; + await first.GetProperty("message").GetString().Should().BeEqualTo("Name must not be empty"); + await first.GetProperty("code").GetString().Should().BeEqualTo("NotEmpty"); + await first.GetProperty("arguments").GetProperty("Name").GetString().Should().BeEqualTo("Name"); + } + + [Test] + public async Task Leaves_Other_Exceptions_To_The_Other_Filters() + { + var context = new ExceptionContext(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), []) + { + Exception = new InvalidOperationException(), + }; + + new ValidationProblemDetailsJoint.ValidationFailedExceptionFilter().OnException(context); + + await context.ExceptionHandled.Should().BeFalse(); + await context.Result.Should().BeNull(); + } + + // A request that is accepted with a warning: the response is the handler's, and the warning travels in a header. + [Test] + public async Task Sends_The_Warnings_Of_An_Accepted_Request_In_A_Header() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseTestServer(); + builder.Services.AddValidationAspNetCoreTestsValidators(); + new ValidationProblemDetailsJoint().Register(await Context(), builder.Services); + await using var app = builder.Build(); + app.MapGet( + "/rockets/{crew:int}", + (int crew, IValidate validator, ValidationNotices notices) => + { + notices.Add(validator.Validate(new() { Crew = crew, }).ThrowIfInvalid()); + return TypedResults.Ok(); + } + ); + await app.StartAsync(); + using var client = app.GetTestClient(); + + using var quiet = await client.GetAsync(new Uri("/rockets/3", UriKind.Relative)); + await quiet.Headers.Contains(ValidationNoticesStartupFilter.HeaderName).Should().BeFalse(); + + using var warned = await client.GetAsync(new Uri("/rockets/12", UriKind.Relative)); + await warned.IsSuccessStatusCode.Should().BeTrue(); + using var notices = JsonDocument.Parse(warned.Headers.GetValues(ValidationNoticesStartupFilter.HeaderName).Single()); + await notices.RootElement[0].GetProperty("path").GetString().Should().BeEqualTo("Crew"); + await notices.RootElement[0].GetProperty("code").GetString().Should().BeEqualTo("LessThanOrEqualTo"); + await notices.RootElement[0].GetProperty("severity").GetString().Should().BeEqualTo("Warning"); + await notices.RootElement[0].GetProperty("arguments").GetProperty("Other").GetString().Should().BeEqualTo("7"); + } + + private static async Task Context() => + await DovetailContext.FromAsync(DovetailContextBuilder.Create([], new Dictionary(), [])); +} + +public sealed record Stage([property: GreaterThan(0d)] double Thrust); + +public sealed class Probe +{ + [NotEmpty] + [MinLength(3)] + [Matches("^[A-Z]")] + public string? Name { get; set; } = "Falcon"; + + [ValidateNested] + public IReadOnlyList Stages { get; set; } = []; + + [LessThanOrEqualTo(7, Severity = ValidationSeverity.Warning)] + public int Crew { get; set; } +} + +internal static class Failures +{ + public static ValidationFailedException Exception(Probe rocket) + { + using var services = new ServiceCollection().AddValidationAspNetCoreTestsValidators().BuildServiceProvider(true); + using var scope = services.CreateScope(); + return new(scope.ServiceProvider.GetRequiredService>().Validate(rocket)); + } +} diff --git a/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs b/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs new file mode 100644 index 0000000000..27d7687ef0 --- /dev/null +++ b/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs @@ -0,0 +1,215 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components.Rendering; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using Rocket.Surgery.LaunchPad.AspNetCore.Blazor; +using Rocket.Surgery.LaunchPad.Foundation; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.Blazor.Tests; + +public partial class LaunchPadValidatorTests +{ + [Test] + public async Task Adds_The_Messages_Of_The_Model_When_The_Form_Is_Validated() + { + var model = new Person { Name = "", Nickname = "", }; + var editContext = new EditContext(model); + await using var renderer = await Render(editContext); + + await ( await editContext.ValidateAsync() ).Should().BeFalse(); + + await editContext.GetValidationMessages(editContext.Field(nameof(Person.Name))).Should().BeEquivalentTo(["Name is required"], CollectionOrdering.Matching); + await editContext.GetValidationMessages(editContext.Field(nameof(Person.Nickname))).Should().BeEquivalentTo(["Nickname must not be empty"], CollectionOrdering.Matching); + } + + // A model whose rules are all synchronous is validated by the synchronous Validate too. + [Test] + public async Task Validates_A_Synchronous_Model_Synchronously() + { + var editContext = new EditContext(new Person { Name = "", Nickname = "Countess", }); + await using var renderer = await Render(editContext); + +#pragma warning disable CS0618 // the obsolete synchronous Validate is still how older forms ask + await editContext.Validate().Should().BeFalse(); +#pragma warning restore CS0618 + await editContext.GetValidationMessages().Should().BeEquivalentTo(["Name is required"], CollectionOrdering.Matching); + } + + [Test] + public async Task Validates_Only_The_Field_That_Changed() + { + var model = new Person { Name = "", Nickname = "", }; + var editContext = new EditContext(model); + await using var renderer = await Render(editContext); + + editContext.NotifyFieldChanged(editContext.Field(nameof(Person.Name))); + + await editContext.GetValidationMessages().Should().BeEquivalentTo(["Name is required"], CollectionOrdering.Matching); + } + + [Test] + public async Task Clears_The_Messages_Once_The_Model_Is_Valid() + { + var model = new Person { Name = "", Nickname = "", }; + var editContext = new EditContext(model); + await using var renderer = await Render(editContext); + + await editContext.ValidateAsync(); + model.Name = "Ada"; + model.Nickname = "Countess"; + + await ( await editContext.ValidateAsync() ).Should().BeTrue(); + await editContext.GetValidationMessages().Should().BeEmpty(); + } + + [Test] + public async Task Requires_A_Model_With_Rules() + { + var editContext = new EditContext(new Plain()); + await using var renderer = await Render(editContext); + + await Assert.That(async () => await editContext.ValidateAsync()).Throws(); + } + + // The form binds to the mutable view model; the rules are the immutable request's. A field is checked without making the request. + [Test] + public async Task Validates_A_View_Model_With_The_Rules_Of_The_Value_It_Makes() + { + var model = new PersonRequestViewModel { Name = "", Nickname = "Countess", }; + var editContext = new EditContext(model); + await using var renderer = await Render(editContext); + + await ( await editContext.ValidateAsync() ).Should().BeFalse(); + await editContext.GetValidationMessages(editContext.Field(nameof(PersonRequestViewModel.Name))).Should().BeEquivalentTo(["Name must not be empty"], CollectionOrdering.Matching); + await editContext.GetValidationMessages(editContext.Field(nameof(PersonRequestViewModel.Nickname))).Should().BeEmpty(); + + model.Name = "Ada"; + editContext.NotifyFieldChanged(editContext.Field(nameof(PersonRequestViewModel.Name))); + + await editContext.GetValidationMessages().Should().BeEmpty(); + } + + // A field whose rule waits is pending until the rule has run; the others are validated at once. + [Test] + public async Task Shows_A_Field_As_Pending_While_Its_Rule_Waits() + { + var names = new Names(); + var model = new Account { UserName = "taken", Email = "", }; + var editContext = new EditContext(model); + await using var renderer = await Render(editContext, services => services.AddSingleton(names)); + var userName = editContext.Field(nameof(Account.UserName)); + + editContext.NotifyFieldChanged(editContext.Field(nameof(Account.Email))); + await editContext.GetValidationMessages().Should().BeEquivalentTo(["Email must not be empty"], CollectionOrdering.Matching); + + editContext.NotifyFieldChanged(userName); + await editContext.IsValidationPending(userName).Should().BeTrue(); + await editContext.GetValidationMessages(userName).Should().BeEmpty(); + + names.Answer.SetResult(false); + await WaitFor(() => !editContext.IsValidationPending(userName)); + + await editContext.GetValidationMessages(userName).Should().BeEquivalentTo(["UserName is taken"], CollectionOrdering.Matching); + } + + // The form's asynchronous validation awaits the rule that waits; its synchronous one can't, and says so. + [Test] + public async Task Awaits_The_Rules_That_Wait_When_The_Form_Is_Validated() + { + var names = new Names(); + names.Answer.SetResult(false); + var editContext = new EditContext(new Account { UserName = "taken", Email = "ada@example.com", }); + await using var renderer = await Render(editContext, services => services.AddSingleton(names)); + +#pragma warning disable CS0618 // the obsolete synchronous Validate is still how older forms ask + await Assert.That(editContext.Validate).Throws(); +#pragma warning restore CS0618 + await ( await editContext.ValidateAsync() ).Should().BeFalse(); + await editContext.GetValidationMessages().Should().BeEquivalentTo(["UserName is taken"], CollectionOrdering.Matching); + } + + private static async Task WaitFor(Func condition) + { + for (var i = 0; i < 200 && !condition(); i++) + { + await Task.Delay(10); + } + } + + private static async Task Render(EditContext editContext, Action? configure = null) + { + var services = new ServiceCollection().AddLogging().AddSingleton(new Names()).AddValidationBlazorTestsValidators(); + configure?.Invoke(services); + var provider = services.BuildServiceProvider(); + var renderer = new HtmlRenderer(provider, provider.GetRequiredService()); + await renderer.Dispatcher.InvokeAsync( + () => renderer.RenderComponentAsync
(ParameterView.FromDictionary(new Dictionary { [nameof(Form.EditContext)] = editContext, })) + ); + return renderer; + } + + public class Person + { + [NotEmpty(Message = "{Name} is required")] + public string Name { get; set; } = ""; + + [NotEmpty] + public string Nickname { get; set; } = ""; + } + + public class Plain + { + public string Name { get; set; } = ""; + } + + public readonly record struct PersonRequest([property: NotEmpty] string Name, [property: NotEmpty] string Nickname); + + [Mutable] + public sealed partial class PersonRequestViewModel; + + /// What knows which names are free: it answers when the test says so. + public sealed class Names + { + public TaskCompletionSource Answer { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public sealed partial class Account + { + public string UserName { get; set; } = ""; + + [NotEmpty] + public string Email { get; set; } = ""; + + [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Read by the validation generator.")] + private static void Validate(IValidationBuilder v, Names names) => + v.Ensure(x => x.UserName).MustAsync(async (name, cancellationToken) => await names.Answer.Task.WaitAsync(cancellationToken)).WithMessage("{Name} is taken"); + } + + // Stands in for an EditForm: cascades the edit context to the validator. + private sealed class Form : ComponentBase + { + [Parameter] + public EditContext EditContext { get; set; } = null!; + + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + builder.OpenComponent>(0); + builder.AddComponentParameter(1, nameof(CascadingValue.Value), EditContext); + builder.AddComponentParameter( + 2, + nameof(CascadingValue.ChildContent), + (RenderFragment)( child => + { + child.OpenComponent(3); + child.CloseComponent(); + } ) + ); + builder.CloseComponent(); + } + } +} diff --git a/test/Validation.Blazor.Tests/Validation.Blazor.Tests.csproj b/test/Validation.Blazor.Tests/Validation.Blazor.Tests.csproj new file mode 100644 index 0000000000..77e58dc2ea --- /dev/null +++ b/test/Validation.Blazor.Tests/Validation.Blazor.Tests.csproj @@ -0,0 +1,16 @@ + + + $(LaunchPadTargetFrameworks) + + + + + + + + + diff --git a/test/Validation.Grpc.Tests/Validation.Grpc.Tests.csproj b/test/Validation.Grpc.Tests/Validation.Grpc.Tests.csproj new file mode 100644 index 0000000000..b300cc523a --- /dev/null +++ b/test/Validation.Grpc.Tests/Validation.Grpc.Tests.csproj @@ -0,0 +1,8 @@ + + + $(LaunchPadTargetFrameworks) + + + + + diff --git a/test/Validation.Grpc.Tests/ValidationGrpcJointTests.cs b/test/Validation.Grpc.Tests/ValidationGrpcJointTests.cs new file mode 100644 index 0000000000..0f908e984b --- /dev/null +++ b/test/Validation.Grpc.Tests/ValidationGrpcJointTests.cs @@ -0,0 +1,121 @@ +using System.Reflection; +using System.Text.Json; +using Grpc.AspNetCore.Server; +using Grpc.Core; +using Joinery.Dovetail; +using Joinery.Dovetail.Attributes; +using Joinery.Dovetail.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Rocket.Surgery.LaunchPad.Grpc.Joints; +using Rocket.Surgery.LaunchPad.Grpc.Rivets; +using Rocket.Surgery.LaunchPad.Grpc.Validation; +using Rocket.Surgery.LaunchPad.Validation; +using ValidationResult = Rocket.Surgery.LaunchPad.Validation.ValidationResult; + +namespace Validation.Grpc.Tests; + +public class ValidationGrpcJointTests +{ + [Test] + public async Task Is_Exported_To_Run_After_The_Grpc_Joint() + { + var export = ValidationExports.Joints().Single(x => x.Joint is ValidationGrpcJoint); + + await export.HostType.Should().BeEqualTo(DovetailHostType.Undefined); + var x = await export.Dependencies.Should().HaveSingleItem(); + await x.Direction.Should().BeEqualTo(DependencyDirection.DependsOn); + await x.Type.Should().BeEqualTo(typeof(GrpcJoint)); + await typeof(ValidationGrpcJoint).GetCustomAttribute()!.Category.ToString().Should().BeEqualTo(DovetailCategory.Application); + } + + [Test] + public async Task Adds_The_Validation_Interceptor_And_The_Notices() + { + var services = new ServiceCollection(); + new ValidationGrpcJoint().Register(await Context(), services); + using var provider = services.BuildServiceProvider(); + + await provider.GetRequiredService>().Value.Interceptors.Select(x => x.Type).Should().BeEquivalentTo([typeof(ValidationInterceptor)], CollectionOrdering.Matching); + await services.Count(x => x.ServiceType == typeof(ValidationNotices) && x.Lifetime == ServiceLifetime.Scoped).Should().BeEqualTo(1); + } + + // The detail lists the errors; the trailer carries every failure, the warning too, with its path, code, severity and placeholder values. + [Test] + public async Task Rejects_An_Invalid_Request_With_Invalid_Argument() + { + var interceptor = new ValidationInterceptor(); + + var exception = await ( (Func)( () => interceptor.UnaryServerHandler( + "request", + Mock.Of().Object, + (_, _) => throw Failure( + new("Stages[2].Thrust", "GreaterThan", "Thrust must be greater than 0", ValidationSeverity.Error, [new("Other", 0d),]), + new("", "Must", "The request is not valid"), + new("Crew", "LessThanOrEqualTo", "Crew is over 7", ValidationSeverity.Warning) + ) + ) ) ).Should().Throw(); + + await exception.StatusCode.Should().BeEqualTo(StatusCode.InvalidArgument); + await exception.Status.Detail.Should().BeEqualTo("Stages[2].Thrust: Thrust must be greater than 0" + Environment.NewLine + "The request is not valid"); + using var failures = JsonDocument.Parse(exception.Trailers.GetValueBytes(ValidationInterceptor.FailuresTrailer)!); + await failures.RootElement.GetArrayLength().Should().BeEqualTo(3); + await failures.RootElement[0].GetProperty("path").GetString().Should().BeEqualTo("Stages[2].Thrust"); + await failures.RootElement[0].GetProperty("code").GetString().Should().BeEqualTo("GreaterThan"); + await failures.RootElement[0].GetProperty("arguments").GetProperty("Other").GetString().Should().BeEqualTo("0"); + await failures.RootElement[2].GetProperty("severity").GetString().Should().BeEqualTo("Warning"); + } + + [Test] + public async Task Rejects_An_Invalid_Stream_With_Invalid_Argument() + { + var interceptor = new ValidationInterceptor(); + + var exception = await ( (Func)( () => interceptor.ServerStreamingServerHandler( + "request", + IServerStreamWriter.Mock().Object, + Mock.Of().Object, + (_, _, _) => throw Failure(new ValidationFailure("Id", "NotEmpty", "Id must not be empty")) + ) ) ).Should().Throw(); + + await exception.StatusCode.Should().BeEqualTo(StatusCode.InvalidArgument); + } + + // A call that succeeds with a warning: the response is the handler's, and the warning travels in a trailer. + [Test] + public async Task Sends_The_Warnings_Of_A_Successful_Call_In_A_Trailer() + { + var interceptor = new ValidationInterceptor(); + var trailers = new Metadata(); + var context = Mock.Of(); + context.ResponseTrailersCore.Returns(trailers); + + var response = await interceptor.UnaryServerHandler( + "request", + context.Object, + (_, _) => + { + ValidationNotices.Current!.Add(new ValidationResult([new("Crew", "LessThanOrEqualTo", "Crew is over 7", ValidationSeverity.Warning),])); + return Task.FromResult("called"); + } + ); + + await response.Should().BeEqualTo("called"); + using var notices = JsonDocument.Parse(trailers.GetValueBytes(ValidationInterceptor.NoticesTrailer)!); + await notices.RootElement[0].GetProperty("path").GetString().Should().BeEqualTo("Crew"); + await notices.RootElement[0].GetProperty("severity").GetString().Should().BeEqualTo("Warning"); + } + + [Test] + public async Task Passes_Other_Exceptions_Through() + { + var interceptor = new ValidationInterceptor(); + + await ( (Func)( () => interceptor.UnaryServerHandler("request", Mock.Of().Object, (_, _) => throw new InvalidOperationException()) ) ).Should().Throw(); + } + + private static ValidationFailedException Failure(params ValidationFailure[] failures) => new(new ValidationResult([.. failures,])); + + private static async Task Context() => + await DovetailContext.FromAsync(DovetailContextBuilder.Create([], new Dictionary(), [])); +} diff --git a/test/Validation.HotChocolate.Tests/Validation.HotChocolate.Tests.csproj b/test/Validation.HotChocolate.Tests/Validation.HotChocolate.Tests.csproj new file mode 100644 index 0000000000..9d184e2b02 --- /dev/null +++ b/test/Validation.HotChocolate.Tests/Validation.HotChocolate.Tests.csproj @@ -0,0 +1,8 @@ + + + $(LaunchPadTargetFrameworks) + + + + + diff --git a/test/Validation.HotChocolate.Tests/ValidationHotChocolateJointTests.cs b/test/Validation.HotChocolate.Tests/ValidationHotChocolateJointTests.cs new file mode 100644 index 0000000000..b4e8e740bb --- /dev/null +++ b/test/Validation.HotChocolate.Tests/ValidationHotChocolateJointTests.cs @@ -0,0 +1,116 @@ +using System.Reflection; + +using HotChocolate; +using HotChocolate.Execution; + +using Joinery.Dovetail; +using Joinery.Dovetail.Attributes; +using Joinery.Dovetail.Infrastructure; + +using Microsoft.Extensions.DependencyInjection; + +using Rocket.Surgery.LaunchPad.HotChocolate.Joints; +using Rocket.Surgery.LaunchPad.HotChocolate.Rivets; +using Rocket.Surgery.LaunchPad.HotChocolate.Validation; +using Rocket.Surgery.LaunchPad.Validation; + +using ValidationResult = Rocket.Surgery.LaunchPad.Validation.ValidationResult; + +namespace Validation.HotChocolate.Tests; + +public class ValidationHotChocolateJointTests +{ + [Test] + public async Task Is_Exported_To_Run_After_The_Graphql_Joint() + { + var export = ValidationExports.Joints().Single(x => x.Joint is ValidationHotChocolateJoint); + + await export.HostType.Should().BeEqualTo(DovetailHostType.Undefined); + var x = await export.Dependencies.Should().HaveSingleItem(); + await x.Direction.Should().BeEqualTo(DependencyDirection.DependsOn); + await x.Type.Should().BeEqualTo(typeof(GraphqlJoint)); + await typeof(ValidationHotChocolateJoint).GetCustomAttribute()!.Category.ToString().Should().BeEqualTo(DovetailCategory.Application); + } + + [Test] + public async Task Reports_Each_Failure_As_A_Validation_Error() + { + var executor = await Executor(); + + var result = ( await executor.ExecuteAsync("""{ echo(name: "") }""") ).ExpectOperationResult(); + + await result.Errors.Should().NotBeNull(); + var errors = result.Errors!; + await errors.Select(x => x.Message).Should().BeEquivalentTo(["Name must not be empty", "Name must be at least 3 characters long"], CollectionOrdering.Matching); + await errors.Should().All(x => x.Code == ValidationErrorFilter.ValidationCode); + await errors[0].Extensions!["propertyName"].Should().BeEqualTo("Name"); + await errors[0].Extensions!["errorCode"].Should().BeEqualTo("NotEmpty"); + await errors[0].Extensions!["severity"].Should().BeEqualTo("Error"); + var arguments = await Assert.That(errors[1].Extensions!["arguments"]).IsTypeOf>(); + await arguments!["Min"].Should().BeEqualTo("3"); + } + + [Test] + public async Task Leaves_Other_Errors_Alone() + { + var executor = await Executor(); + + var result = ( await executor.ExecuteAsync("""{ echo(name: "boom") }""") ).ExpectOperationResult(); + + await ( await ( await result.Errors.Should().NotBeNull() )!.Should().HaveSingleItem() ).Code.Should().NotBeEqualTo(ValidationErrorFilter.ValidationCode); + } + + // A request that is accepted with a warning: the data is the resolver's, and the warning travels as an extension of the result. + [Test] + public async Task Sends_The_Warnings_Of_An_Accepted_Request_As_An_Extension() + { + var executor = await Executor(); + + var quiet = ( await executor.ExecuteAsync("""{ echo(name: "Falcon") }""") ).ExpectOperationResult(); + await ( quiet.Extensions?.ContainsKey(ValidationNoticesMiddleware.ExtensionName) ?? false ).Should().BeFalse(); + + var warned = ( await executor.ExecuteAsync("""{ echo(name: "warn") }""") ).ExpectOperationResult(); + await ( warned.Errors ?? [] ).Select(x => x.Message).Should().BeEmpty(); + var notices = await Assert.That(warned.Extensions![ValidationNoticesMiddleware.ExtensionName]).IsTypeOf>>(); + var notice = await notices!.Should().HaveSingleItem(); + await notice["path"].Should().BeEqualTo("Name"); + await notice["code"].Should().BeEqualTo("Lowercase"); + await notice["severity"].Should().BeEqualTo("Warning"); + } + + private static async Task Executor() + { + var services = new ServiceCollection(); + var context = await DovetailContext.FromAsync(DovetailContextBuilder.Create([], new Dictionary(), [])); + context.GetOrAdd(() => services.AddGraphQL()).AddQueryType(); + new GraphqlJoint().Register(context, services); + new ValidationHotChocolateJoint().Register(context, services); + return await services.BuildServiceProvider().GetRequiredService().GetExecutorAsync(); + } + + public class Query + { + public string Echo(string name, ValidationNotices notices) + { + switch (name) + { + case "": + throw new ValidationFailedException( + new ValidationResult( + [ + new("Name", "NotEmpty", "Name must not be empty"), + new("Name", "MinLength", "Name must be at least 3 characters long", ValidationSeverity.Error, [new("Min", 3),]), + ] + ) + ); + case "boom": + throw new InvalidOperationException("boom"); + case "warn": + notices.Add(new ValidationResult([new("Name", "Lowercase", "Name should start with a capital", ValidationSeverity.Warning),])); + return name; + default: + return name; + } + } + } +}