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
7 changes: 5 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th
- 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.
- 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.
- Not written yet ([#3378](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3378)): rules declared for a base class, an interface or a type of another assembly (LPAD3110), `Include`, the rules `[InheritFrom]` and `[Mutable]` carry over, and validators for generic types (LPAD3101).
- `test/Validation.Tests` runs the generator as an application does and proves what the validators do; `test/Validation.Analyzers.Tests` has the snapshots of what the generator writes and reports.
- 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.
- 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.
- `src/Sdks/LaunchPad` is the **LaunchPad SDK** (`Rocket.Surgery.LaunchPad.Sdk`), an MSBuild SDK an application applies with an `<Sdk>` 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<Tech>=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 `<Sdk Name="Chirograph" />` 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<TestRecord>` (`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()`.
Expand Down
1 change: 1 addition & 0 deletions LaunchPad.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
<Project Path="test/Serilog.AspNetCore.Tests/Serilog.AspNetCore.Tests.csproj" />
<Project Path="test/Spatial.Serilog.Tests/Spatial.Serilog.Tests.csproj" />
<Project Path="test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj" />
<Project Path="test/Validation.Tests.Contracts/Validation.Tests.Contracts.csproj" />
<Project Path="test/Validation.Tests/Validation.Tests.csproj" />
<Project Path="test/TestSupport/TestSupport.csproj" />
</Folder>
Expand Down
12 changes: 9 additions & 3 deletions docs/design/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Items marked _(decided)_ were settled in the interview. The rest are proposals;
1. **Names** _(decided)_. Authoring: `IValidationBuilder<T>`, whose `Ensure` returns an `IMemberRules<T, TMember>`, and `IValidator<T>` (the class shape). Consuming: `IValidate<T>` (sync and async) and `IValidateAsync<T>` (async only). Result: `ValidationResult` holding `ValidationFailure`s.
2. **A failure carries** _(decided)_ `Path` (`Stages[2].Thrust`), `Code` (stable, the rule's name by default, e.g. `MaxLength`), `Message`, `Severity` (`Error`, `Warning`, `Info`) and the values of the message's placeholders. Only `Error` makes a result invalid. Warnings and info travel to clients on every transport, on successful responses too: each integration defines its shape for them (problem details and GraphQL extensions, gRPC trailers).
**Messages** _(decided)_: each rule has a default English template compiled in. At run time an optional `IValidationMessageProvider`, keyed by code, can replace any message (an `IStringLocalizer` adapter is the expected use), and transports send the code and placeholder values so a client can localise for itself.
3. **Merge order**: attributes, then base class and interface rules, then inherited (`[InheritFrom]`) rules, then the type's own functions and classes in a stable order (assembly, then file path, then position). Every rule runs; a chain stops at its first failure only where `.StopOnFailure()` says so.
3. **Merge order**: the rules of the base classes, the farthest first, then of the interfaces, then the type's own, member by member in the order the members first have a rule; for one member, its attributes, then the rules carried by `[InheritFrom]` and `Include`, then the type's functions and classes in a stable order (file path, then position). Every rule runs; a chain stops at its first failure only where `.StopOnFailure()` says so.
4. **Nested values are validated where asked** _(decided)_: `[ValidateNested]` on the member, or `.ValidateWith()` in a chain, validates it with its type's validator (a collection item by item) and prefixes its failures with the member's path. An analyzer warns on every member whose type has rules and that is marked neither `[ValidateNested]` nor `[SkipValidation]`, with a fix for each.
5. **Containing types are partial.** The generator writes the validator inside the type that declares the function or class, so the rewritten rules can reach its private members and the captured dependencies. A non-partial container is a build error.
6. **Dependencies** of every function and class that contributes to `T` become constructor parameters of the generated validator, resolved from DI. A `CancellationToken` parameter is the call's token, not a dependency. Dependencies travel with carried rules _(decided)_: a type that inherits a rule that needs a service takes that service too, and one that inherits an async rule is async-only.
Expand Down Expand Up @@ -159,10 +159,16 @@ Where the code so far differs from the text above:
- **A private `Validate` function is never called**, so the compiler and formatters would take it for unused (`dotnet format` deletes it under IDE0051). The rule methods written from it name it (`DeclaredBy = nameof(Validate)`), which makes it used.
- **A chain is about one member** (`x => x.Member`) or the whole value (`x => x`); a path through another member (`x => x.Engine.Name`) is an error. Rules for the members of a member go in that member's type, or in `EnsureEach` for a collection.
- **Lifetimes**: a validator that takes services, or that validates a member with the member's validator, is scoped; the others are singletons. Only a synchronous singleton is an `IValidateOptions<T>`.
- **Rules can be declared** only for a class, struct or record of the same assembly so far (LPAD3110); `Include` is an error; `ValidateNested` in a chain can't be under a condition.
- **`ValidateNested` in a chain** can't be under a condition.
- **A validator holds only the rules declared for its type** in its assembly. Each has a rule method for every member with rules (`Ensure{Member}`, and `Ensure_Value` for the rules about the whole value), which checks that member's attributes, then the rules it carries, then calls the rule methods of the functions and classes; `ValidateDeclared` runs them all, and `Validate` runs the `ValidateDeclared` of every validator of what the type is, then its own. A rule method is static unless it takes a service, a class validator or the validator of the member. These methods, with their `[GeneratedRule]`, are the rule manifest: the generator reads them from a referenced assembly's validators, which it finds by the name of the type (`{Type}GeneratedValidator`, in the assembly that declares the type) and by `[assembly: ContributedValidator]`.
- **Base classes and interfaces.** A type's validator calls the validator of each base class and each interface that has rules, in this compilation or a referenced assembly. A type with no rules of its own gets a validator when something it derives from has one. An interface, or an abstract class, with rules has a validator too (`IValidate<IHasName>`). The attributes of a base class's members are read into the validator of the first type down the chain that has a validator: a base class this compilation can't write one for (a generic one, one of an assembly that doesn't run the generator) has its attributes read by each type that derives from it.
- **`[InheritFrom]` and `Include<TOther>()`** carry rules member by member: the rule method of a copied member calls the rule method `TOther`'s validator has for it. Where that method takes services, the validator takes `TOther`'s validator, which the registration adds; where it waits, the type is asynchronous only. A member's rules are not carried when they read the whole `TOther` (a `Must((x, value) => ...)`, a `When`), compare it with a member that was not copied, or the member's type differs: LPAD3112, a warning, says which. The generator works out which members `[InheritFrom]` copies with the code that copies them (`src/Shared/GeneratedMembers.cs`). `Include` takes the members the two types share by name and type.
- **`[Mutable<T>]`**: the view model's validator validates the whole value as `T` (`ToImmutable()`, with the `IValidate<T>` or `IValidateAsync<T>` of the service provider), then the view model's own rules. `[Mutable]`'s generator still writes the ZeroAlloc.Validation validator beside it until that library goes (phase 6).
- **`IValidateMembers<T>`** is the per-member entry point, and every generated validator is one, not only a view model's: `TryValidateMember(value, member, out result)` checks the rules of one member, from every validator of what the type is, and returns `false` when one of them waits; `ValidateMemberAsync` checks them either way. A view model checks the rules `T` and its base classes and interfaces have for the member with the view model's value, without making a `T`; a rule that reads the whole `T` is left to the validation of the whole view model.
- **Rules for a type of another assembly.** A `Validate` function may declare rules for any class, struct, record or interface the compilation can reach. For a type another assembly declares, the validator is `{Type}In{Assembly}GeneratedValidator`, in the type's namespace; it runs the validators the referenced assemblies have for the type, then its own rules, and the registration replaces what is registered for the type with it (`RemoveAll`, then add), so the rules of each assembly run once. `[assembly: ContributedValidator]` tells the assemblies that reference this one about it. An asynchronous rule added to a type whose own assembly validates it synchronously is an error (LPAD3113), as proposed above.
- **String rules** (`EmailAddress`, `Url`, `Matches`) are declared for `IEquatable<string>`, and the length rules for `IEnumerable`, so the rules after them still see a `string` member as `string` and a `string?` one as `string?`. `IMemberRules<T, out TMember>` is covariant, so a rule an application declares for a base type applies to the members of derived ones.
- **The LPAD3002 fix** changes the uses in one document. Where the result must stay synchronous (a `Func<T, bool>`, a method that wraps the result in `Task.FromResult`) what it leaves does not compile, and says where.
- **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. An `internal AddLaunchPadValidators()` in every assembly would be ambiguous in any project that sees another's internals (`InternalsVisibleTo`), which this repository's tests do.
- **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. Each validator is registered as the type's `IValidateAsync<T>`, its `IValidate<T>` if no rule waits, and its `IValidateMembers<T>`. An `internal AddLaunchPadValidators()` in every assembly would be ambiguous in any project that sees another's internals (`InternalsVisibleTo`), which this repository's tests do.
- **Options**: there is no adapter. Each validator of a class implements `IValidateOptions<T>` itself and is registered as one, so an options class with rules is validated wherever it is used.
- **Nested validators** are asked of the `IServiceProvider` the validator is made with, when first needed, and not injected: a type can then be validated inside itself, and what is asked for is the composed validator the application registered.
- **A pattern in an attribute** (`[Matches]`, `[RegularExpression]`) is an interpreted `Regex` held by the validator: the regular expression generator can't see what another generator writes. A `Validate` function can pass a `[GeneratedRegex]` member.
Expand Down
Loading
Loading