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: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th
- `src/Primitives.Analyzers` (its own package, an exception to ADR-0004) holds every generator, analyzer (LPAD2001 and up; LPAD2101 and up for the generator) and code fix, except LPAD2024, which LaunchPad's own analyzer (`src/Analyzers/Primitives`) reports in an application that uses domain primitives through a library without referencing Primitives, as Primitives' analyzers don't run there. The attributes are not compiled into any assembly: the generator writes `Sources/PrimitiveAttributes.cs` into every project that references Primitives, `internal`, `[Conditional("CodeGeneration")]` and `[Embedded]`, as a C# 15 closed hierarchy (`PrimitiveAttribute` for the kinds, `PrimitiveRuleAttribute` for the rules). A domain primitive in a referenced assembly is found by `IDomainPrimitive<TSelf, TValue>` (a value object by `IValueObject<TSelf>`), never by its attributes. The NodaTime members of `DatePrimitiveKind` are behind `#if LAUNCHPAD_PRIMITIVES_NODATIME`, which the package's targets define when the project references NodaTime.
- 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).
- 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.
- 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.
- `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
4 changes: 4 additions & 0 deletions LaunchPad.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@
<Project Path="src/Primitives.Analyzers/Rocket.Surgery.LaunchPad.Primitives.Analyzers.csproj" />
<Project Path="src/Primitives/Rocket.Surgery.LaunchPad.Primitives.csproj" />
<Project Path="src/Spatial/Rocket.Surgery.LaunchPad.Spatial.csproj" />
<Project Path="src/Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.csproj" />
<Project Path="src/Validation/Rocket.Surgery.LaunchPad.Validation.csproj" />
<Project Path="src/StrawberryShake.Spatial/Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj" />
<Project Path="src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj" />
</Folder>
Expand Down Expand Up @@ -141,6 +143,8 @@
<Project Path="test/Sdk.Tests/Sdk.Tests.csproj" />
<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/Validation.Tests.csproj" />
<Project Path="test/TestSupport/TestSupport.csproj" />
</Folder>
<Folder Name="/test/Api/" />
Expand Down
7 changes: 7 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ lists what the SDK adds for each technology.
| [Rocket.Surgery.LaunchPad.Primitives][nuget-primitives] | [![nuget-primitives-badge]][nuget-primitives] | Domain primitives, strong IDs, smart enums and value objects, with OpenAPI, HotChocolate, EF Core and OpenTelemetry joints as templates |
| Rocket.Surgery.LaunchPad.Primitives.Analyzers | not published yet | The domain primitive generator, analyzers and code fixes Primitives depends on; a port of dotnet-domain-primitives (MIT) |

### 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 |

## Contributing

`mise install` installs the toolchain, `mise run build` builds, tests and packs, and `hk check` lints.
Expand Down
34 changes: 34 additions & 0 deletions docs/adr/0012-launchpad-owns-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# LaunchPad owns validation

`Rocket.Surgery.LaunchPad.Validation` is LaunchPad's own validation: a runtime package and a source generator in an analyzer package of its own (`Rocket.Surgery.LaunchPad.Validation.Analyzers`), in place of ZeroAlloc.Validation. It is optional and depends on no other LaunchPad package, as Primitives is ([ADR-0008](0008-primitives-is-an-independent-strong-types-package.md)); its analyzer package is the same exception to [ADR-0004](0004-one-generator-assembly.md). The design is in [`docs/design/validation.md`](../design/validation.md), and the work is tracked by [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374).

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;
- 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.

## Why

ZeroAlloc.Validation declares rules with attributes only, so a rule that needs code (one that reads two members, applies under a condition or asks a service) has nowhere to go but a `[Must]` method. Its generator can't see what LaunchPad's `[Mutable]` and `[InheritFrom]` generators write, so the types they complete go unvalidated or are validated by delegation. And LaunchPad controls neither what it emits (the failure type, the paths, the codes, the registration) nor its vocabulary, which is not the one OpenAPI, Blazor and EF Core tooling already read.

## Considered Options

- **Keep ZeroAlloc.Validation and add function validators beside it.** Rejected: two validators per type with two failure types, and the composition with `[Mutable]` and `[InheritFrom]` stays unsolved.
- **[ValiCraft](https://github.com/hquinn/ValiCraft)** (MIT), whose generator rewrites a fluent `DefineRules` method the way this one rewrites `Validate`. Rejected as a dependency for the same reason as ZeroAlloc.Validation: its generator knows nothing of attributes, of LaunchPad's generators or of rules that cross assemblies. Its approach is the model for the function validators.
- **FluentValidation.** Rejected: it builds expression trees and compiles them at run time, which is what LaunchPad 2.0 left behind.
- **A `Validate` body that runs**, over a builder that takes values instead of lambdas. Rejected: the rules would not be known at build time, so they could not be carried over to another type, described to OpenAPI or split by member for a Blazor field.
- **The generator in LaunchPad's one analyzer assembly** ([ADR-0004](0004-one-generator-assembly.md)), where it could share the `[Mutable]` and `[InheritFrom]` models directly. Rejected: Validation would then need Foundation's analyzer, and it is meant to be usable without the rest of LaunchPad. The models are shared as linked source instead.
- **Integrations as templates**, as Primitives ships its Joints. Rejected: the gRPC interceptor, the HotChocolate error filter and the Blazor component are more than wiring. They stay integration packages ([ADR-0002](0002-package-per-integration.md)), renamed from `Rocket.Surgery.LaunchPad.ZeroAlloc.*` to `Rocket.Surgery.LaunchPad.Validation.*`.

## 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.

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