Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th
- Its settings are MSBuild properties (`LaunchPadPrimitivesTrim`, `...NotEmpty`, `...MaxLength`, `...ExceptionType`, `...OpenApiRepresentation`, `...GraphQLRepresentation`) in `src/Primitives/build/Rocket.Surgery.LaunchPad.Primitives.targets`.
- It ships its OpenAPI, HotChocolate, EF Core and OpenTelemetry Joints as templates the same way as Hosting (`src/Primitives/build/*.cs.template`, declared in `Rocket.Surgery.LaunchPad.Primitives.Templates.targets`, which the root `Directory.Build.targets` imports too), reading the `LaunchPadPrimitives` registry its generator fills in. The EF Core value converters, the Dapper type handlers and `AddLaunchPadPrimitivesInstrumentation()` are written by the registry generator (`src/Primitives.Analyzers/Registry`) when the application references those libraries; `ConfigureDomainPrimitives()` is in the EF Core template. `test/Sdk.Tests` (`SdkPrimitivesTests`) proves them end to end.
- `LaunchPad.Validation` is LaunchPad's own validation, which is replacing ZeroAlloc.Validation ([ADR-0012](docs/adr/0012-launchpad-owns-validation.md), [`docs/design/validation.md`](docs/design/validation.md), [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)). It depends on no other LaunchPad package. Until that work is done, ZeroAlloc.Validation is still what validates everywhere.
- `src/Validation` holds what a validator is written with and what a generated validator implements and calls. In `Rocket.Surgery.LaunchPad.Validation`: `IValidationBuilder<T>` and `IMemberRules<T, TMember>` (the builder a `Validate` function or an `IValidator<T>` class declares rules on; nothing implements them, the generator reads the calls), `IValidate<T>` and `IValidateAsync<T>` (what an application injects), `ValidationResult`, `ValidationFailure`, `ValidationSink` and `IValidationMessageProvider`. In `.Rules`: `Rule` (the checks of the built-in rules), the rule attributes, and `MemberRulesExtensions` (the same rules on the builder).
- `src/Validation` holds what a validator is written with and what a generated validator implements and calls. In `Rocket.Surgery.LaunchPad.Validation`: `IValidationBuilder<T>` and `IMemberRules<T, TMember>` (the builder a `Validate` function or an `IValidatorDefinition<T>` class declares rules on; nothing implements them, the generator reads the calls), `IValidator<T>` (what an application injects: `ValidateAsync`, the only way to validate a whole value), `ValidationResult`, `ValidationFailure`, `ValidationSink` and `IValidationMessageProvider`. In `.Rules`: `Rule` (the checks of the built-in rules), the rule attributes, and `MemberRulesExtensions` (the same rules on the builder).
- A rule is declared twice, as an attribute and as an extension method of `IMemberRules<T, TMember>`, with the same name; both carry a `[ValidationRule]` that names the method that checks it, and that method carries the rule's code and message in a `[RuleDefaults]`. Add a rule in all three places.
- `src/Validation.Analyzers` (its own package, an exception to ADR-0004 as Primitives' is) holds the generator, the analyzers (LPAD3001 and up; LPAD3101 and up for the generator) and the code fixes. `ValidatorGenerator` needs no marker: for every class, struct or record with a rule attribute on a member (LaunchPad's, or the `System.ComponentModel.DataAnnotations` ones it compiles) it writes `{Type}GeneratedValidator` beside the type (`{Type}Validator` is what an application names its class validator), with one public static rule method per member (`Ensure{Member}`) and the rule manifest (`[GeneratedValidator]`, `[GeneratedRule]`). `Model/RuleReader.cs` binds each rule's call as C# would (a speculative binding of the method the attribute's `[ValidationRule]` names), so the overload, its code and message and the placeholders' names come from the compiler.
- A **function validator** (`static void Validate(IValidationBuilder<T> v, ...dependencies)`, in any partial type) and a **class validator** (a partial class that implements `IValidator<T>`) are found by shape and read by `Model/FunctionReader.cs`. The body may only call the builder, and never runs: each chain becomes part of a rule method written into the type that contains it (`Validate{Type}_{Member}`, in a file that repeats the usings of the source file), and each lambda is copied as a local function of that method, so what it names resolves as it does where it was written. The generated methods name the function (`DeclaredBy = nameof(Validate)`): nothing calls a private `Validate`, and without that reference `dotnet format` deletes it as unused. `MergedModel` (in `ValidatorGenerator.cs`) puts the attributes, functions and classes of one type into its one validator, attributes first.
- A type with a rule that waits (`MustAsync`, or a member validated with the validator of such a type) gets an `IValidateAsync<T>` and no `IValidate<T>`; LPAD3002 is an error on `IValidate<T>` of such a type, and its fix makes the use asynchronous. A validator that takes services, or validates a member with that member's validator, is registered scoped; the others are singletons, and only those are `IValidateOptions<T>`.
- A member is validated with its own type's validator only where it says `[ValidateNested]` (or `[ValidateWith<T>]`); LPAD3001 warns where a type with rules has a member whose type has rules and that says neither that nor `[SkipValidation]`. The nested validator is asked of the `IServiceProvider` the validator is made with.
- A **function validator** (`static void Validate(IValidationBuilder<T> v, ...dependencies)`, in any partial type) and a **class validator** (a partial class that implements `IValidatorDefinition<T>`) are found by shape and read by `Model/FunctionReader.cs`. The body may only call the builder, and never runs: each chain becomes part of a rule method written into the type that contains it (`Validate{Type}_{Member}`, in a file that repeats the usings of the source file), and each lambda is copied as a local function of that method, so what it names resolves as it does where it was written. The generated methods name the function (`DeclaredBy = nameof(Validate)`): nothing calls a private `Validate`, and without that reference `dotnet format` deletes it as unused. `MergedModel` (in `ValidatorGenerator.cs`) puts the attributes, functions and classes of one type into its one validator, attributes first.
- Validation is asynchronous: there is no synchronous interface. The validator of a type none of whose rules waits (no `MustAsync`, no member validated with its own validator, not a `[Mutable]` view model) answers `ValidateAsync` with a completed `ValueTask`, and only such a validator, when it is a singleton, is an `IValidateOptions<T>` too. A validator that takes services, or validates a member with that member's validator, is registered scoped; the others are singletons.
- A member is validated with its own type's validator only where it says `[ValidateNested]` (or `[ValidateWith<T>]`); LPAD3001 warns where a type with rules has a member whose type has rules and that says neither that nor `[SkipValidation]`. The nested validator (the `IValidator<T>` registered for the member's type) is given to the validator's constructor; only where making it takes this validator (a type with a member of its own type, two types that validate each other, `Resolver.Cycles`) is it asked of an `IServiceProvider` when first used.
- In a project that references the dependency injection abstractions, the generator writes `Add{AssemblyName}Validators()` (`LaunchPadValidators.g.cs`), which registers the assembly's validators and calls the same method of each referenced assembly (found by `[assembly: ValidatorAssembly]`); with Microsoft.Extensions.Options, a singleton validator of a class is an `IValidateOptions<T>` too.
- 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<T>` (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<TOther>()` carry rules member by member (LPAD3112 where a member's rules can't be carried), and the validator of a `[Mutable<T>]` 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.
- 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.
- 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)).
Expand Down
6 changes: 3 additions & 3 deletions docs/adr/0012-launchpad-owns-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
The generator writes one validator per validated type at build time, and merges into it every rule the type has:

- rule attributes on its members: LaunchPad's own, one for each rule, and the `System.ComponentModel.DataAnnotations` attributes the generator knows, compiled to the same checks;
- **function validators**, `static void Validate(IValidationBuilder<T> v, ...dependencies)`, and **class validators**, partial classes that implement `IValidator<T>` and take their dependencies in their constructor. Both are found by their shape, as Keryx finds handlers, and several for one type merge;
- **function validators**, `static void Validate(IValidationBuilder<T> v, ...dependencies)`, and **class validators**, partial classes that implement `IValidatorDefinition<T>` and take their dependencies in their constructor. Both are found by their shape, as Keryx finds handlers, and several for one type merge;
- the rules of the type's base classes and interfaces, and the rules `[InheritFrom<T>]` and `[Mutable<T>]` carry over from `T`.

A `Validate` body is a build-time language: it may only call the builder, the generator reads it and writes the checks, and it never runs. Nothing is interpreted at run time: no reflection, no expression trees, no rule objects.

Each generated validator exposes one static **rule method** per member and a **rule manifest** that describes them. That is how rules cross assemblies with no source to read: a type that inherits from another calls its rule methods with its own values, the application's registration composes the validators several assemblies wrote for one type, and the API generators read the manifest for the OpenAPI schema.

A validator is synchronous unless one of its rules is asynchronous. An application injects `IValidate<T>` or `IValidateAsync<T>`; using the synchronous one for a type with an asynchronous rule is a build error with a code fix.
Validation is asynchronous. An application injects `IValidator<T>` and awaits `ValidateAsync`; there is no synchronous interface. A validator none of whose rules waits answers with a completed `ValueTask`, so it costs no more than a synchronous call.

## Why

Expand All @@ -29,6 +29,6 @@ ZeroAlloc.Validation declares rules with attributes only, so a rule that needs c

## Consequences

Replacing ZeroAlloc.Validation is a breaking change for every application that validates: the attributes move to `Rocket.Surgery.LaunchPad.Validation.Rules`, the injected type becomes `IValidate<T>` or `IValidateAsync<T>`, and the failures have LaunchPad's shape (path, code, message, severity and the values of the message's placeholders). The rule attributes share names with `System.ComponentModel.DataAnnotations` (`[MaxLength]`, `[EmailAddress]`), so a file imports one namespace or the other, or aliases one.
Replacing ZeroAlloc.Validation is a breaking change for every application that validates: the attributes move to `Rocket.Surgery.LaunchPad.Validation.Rules`, the injected type becomes `IValidator<T>`, whose only method is asynchronous, and the failures have LaunchPad's shape (path, code, message, severity and the values of the message's placeholders). The rule attributes share names with `System.ComponentModel.DataAnnotations` (`[MaxLength]`, `[EmailAddress]`), so a file imports one namespace or the other, or aliases one.

LaunchPad now maintains a validation library: every built-in rule, its message, and a diagnostic for everything the generator refuses to read. A type that holds a `Validate` function, and every class validator, must be `partial`, because the generated validator is written inside it to reach its private members and dependencies. The generated rule methods are public members of every library that validates, hidden from IntelliSense: changing a library's rules changes what the assemblies that inherit them call.
Loading
Loading