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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th
- 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 `<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.
- `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. A project that references `Rocket.Surgery.LaunchPad.Validation` itself gets the `Validation.*` integration package of each partner it has (`Sdk/Rocket.Surgery.LaunchPad.Detection.Validation.targets`), as one that references ZeroAlloc.Validation gets the `ZeroAlloc.*` ones. 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
26 changes: 14 additions & 12 deletions docs/src/content/docs/concepts/integration-packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ small packages, which the [LaunchPad SDK](../launchpad-sdk/) chooses for you.

## The packages the SDK chooses

| The project references | The SDK adds |
| ------------------------------- | ----------------------------------------------------------------------------------------------------- |
| a [host model](../host-models/) | `Rocket.Surgery.LaunchPad.Hosting` |
| the `WebApplication` host model | `Rocket.Surgery.LaunchPad.AspNetCore`, and `.AspNetCore.Mvc` unless `PublishAot` or `IsAotCompatible` |
| `NodaTime` | `.NodaTime`, and `.NodaTime.HotChocolate` / `.NodaTime.StrawberryShake` with those libraries |
| `NetTopologySuite` | `.Spatial`, and `.StrawberryShake.Spatial` with StrawberryShake |
| `ZeroAlloc.Validation` | `.ZeroAlloc.AspNetCore` in an ASP.NET Core application, `.ZeroAlloc.Blazor` in a Blazor one |
| `HotChocolate` | `.HotChocolate` |
| `StrawberryShake` | `.StrawberryShake` |
| `Grpc.AspNetCore` | `.Grpc` |

Validation is ZeroAlloc.Validation's, and a validation failure is an error case, not an exception. `Rocket.Surgery.LaunchPad.Foundation`
| The project references | The SDK adds |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| a [host model](../host-models/) | `Rocket.Surgery.LaunchPad.Hosting` |
| the `WebApplication` host model | `Rocket.Surgery.LaunchPad.AspNetCore`, and `.AspNetCore.Mvc` unless `PublishAot` or `IsAotCompatible` |
| `NodaTime` | `.NodaTime`, and `.NodaTime.HotChocolate` / `.NodaTime.StrawberryShake` with those libraries |
| `NetTopologySuite` | `.Spatial`, and `.StrawberryShake.Spatial` with StrawberryShake |
| `ZeroAlloc.Validation` | `.ZeroAlloc.AspNetCore` in an ASP.NET Core application, `.ZeroAlloc.Blazor` in a Blazor one |
| `Rocket.Surgery.LaunchPad.Validation` | the Validation ASP.NET Core, gRPC, HotChocolate and Blazor packages with those |
| `HotChocolate` | `.HotChocolate` |
| `StrawberryShake` | `.StrawberryShake` |
| `Grpc.AspNetCore` | `.Grpc` |

LaunchPad has [validation of its own](../validation/), which is being built: the SDK adds its integration packages to a project that
references it, and it will replace ZeroAlloc.Validation. Until then, validation is ZeroAlloc.Validation's, and a validation failure is an error case, not an exception. `Rocket.Surgery.LaunchPad.Foundation`
writes a validation behavior into each application that uses Keryx, LaunchPad's mediator, and references ZeroAlloc.Validation. The
behavior checks each `[Validate]` request against its rules before the handler runs and answers a request that fails with the
`UnprocessableEntity` case of its response (see [validation](../../guides/api-generators/#validation)). Each transport answers that case
Expand Down
125 changes: 125 additions & 0 deletions docs/src/content/docs/concepts/validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
---
title: Validation
description: Rocket.Surgery.LaunchPad.Validation writes one validator for each type at build time, from rule attributes, DataAnnotations and Validate functions, with no reflection and no expression trees.
---

`Rocket.Surgery.LaunchPad.Validation` is LaunchPad's own validation. You declare **rules** for a type, and a source generator writes
one **validator** for it at build time: straight-line code, with no reflection and no expression trees, so it works under trimming
and native AOT. It is optional: an application opts in by referencing the package, and the [LaunchPad SDK](../launchpad-sdk/) never
adds it.

:::caution[In progress]
LaunchPad's validation is being built ([#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)). The samples and the
mediator still validate with ZeroAlloc.Validation, and nothing validates a request before its handler for you yet: you call the
validator yourself.
:::

## Declaring rules

Rules come from three places, and the generator merges them into the one validator of the type.

**Attributes** on the members, from `Rocket.Surgery.LaunchPad.Validation.Rules`:

```csharp
using Rocket.Surgery.LaunchPad.Validation.Rules;

public sealed record CreateRocket
{
[NotEmpty, MaxLength(30)]
public string Name { get; init; } = "";

[InclusiveBetween(1, 33)]
public int Engines { get; init; }

[ValidateNested]
public IReadOnlyList<Stage> Stages { get; init; } = [];
}
```

The `System.ComponentModel.DataAnnotations` attributes the generator knows (`[Required]`, `[StringLength]`, `[Range]`,
`[RegularExpression]`, `[EmailAddress]` and others) are compiled the same way. A custom `ValidationAttribute` never runs: the
generator reports it and points at `[Must]` or a function.

**A function validator**: a static `Validate` method in any partial type. Its first parameter is the builder, and the others are
services the rules need:

```csharp
public static partial class CreateRocketRules
{
private static void Validate(IValidationBuilder<CreateRocket> v, ICatalog catalog)
{
v.Ensure(x => x.Name).Must(name => !catalog.IsTaken(name)).WithCode("NameTaken").WithMessage("{Name} is taken");
v.Ensure(x => x.Engines).GreaterThan(8).When(x => x.Stages.Count > 1);
}
}
```

The body never runs. The generator reads it at build time and writes each chain as a method of the type that contains it, so a
`Validate` body may only call the builder.

**A class validator**: a partial class that implements `IValidator<T>`, whose dependencies are its constructor's.

A member is validated with its own type's validator only where you say so, with `[ValidateNested]` or `.ValidateNested()`. An
analyzer warns about a member whose type has rules and that says neither that nor `[SkipValidation]`.

## Using a validator

The generator writes `Add{AssemblyName}Validators()` for each assembly. It registers the assembly's validators and those of the
assemblies it references.

```csharp
services.AddMyAppValidators();

public sealed class RocketService(IValidate<CreateRocket> validator)
{
public void Create(CreateRocket request)
{
validator.Validate(request).ThrowIfInvalid();
// ...
}
}
```

| You inject | It gives |
| --------------------- | ------------------------------------------------------------------------ |
| `IValidate<T>` | `Validate(value)`. Only a type with no rule that waits has one. |
| `IValidateAsync<T>` | `ValidateAsync(value, cancellationToken)`. Every validated type has one. |
| `IValidateMembers<T>` | One member at a time, which a form does when a field changes. |

A type with a `MustAsync` rule is validated asynchronously only. Asking for its `IValidate<T>` is a build error, with a fix that
makes the use asynchronous.

A failure carries the path of the member (`Stages[2].Thrust`), a code that stays the same whatever the message says (`MaxLength`),
the message, a severity and the values of the message's placeholders. Only an error makes a result invalid: a rule declared as a
warning (`Severity = ValidationSeverity.Warning`) is reported and does not reject the value.

## Rules from other types

- A rule declared for a **base class** or an **interface** applies to every type that derives from or implements it, in the same
assembly or in one that references it.
- `[InheritFrom<T>]` and `v.Include<T>()` bring `T`'s rules for the members the type takes from it.
- The view model of a `[Mutable<T>]` type is validated as the `T` it makes, and one field at a time with `T`'s rules.
- An application can add rules to a type a library declares. Its validator runs the library's rules and then its own.

## Transports

Each transport has an integration package, which the SDK adds to a project that references `Rocket.Surgery.LaunchPad.Validation`
and that transport. Each turns a `ValidationFailedException` into the transport's error shape, and sends the warnings of a request
that was accepted with its response.

| Package | A rejected request | Warnings of an accepted request |
| -------------------------------------------------- | --------------------------------------------------------- | --------------------------------- |
| `Rocket.Surgery.LaunchPad.Validation.AspNetCore` | 422 problem details, with the errors by path | the `Validation-Notices` header |
| `Rocket.Surgery.LaunchPad.Validation.Grpc` | `InvalidArgument`, with the failures in a trailer | a trailer |
| `Rocket.Surgery.LaunchPad.Validation.HotChocolate` | one `VALIDATION` error for each failure | the `validationNotices` extension |
| `Rocket.Surgery.LaunchPad.Validation.Blazor` | the `LaunchPadValidator` component shows them in the form | shown as messages |

The ASP.NET Core package also states the rules in the OpenAPI document: required members, lengths, ranges, patterns, e-mail
addresses and URLs.

In a Blazor form, put `<LaunchPadValidator />` inside the `EditForm`. A field is validated when it changes, and
`EditContext.IsValidationPending` is `true` for it while a rule that waits is running.

The design and the decisions behind it are in
[`docs/design/validation.md`](https://github.com/RocketSurgeonsGuild/LaunchPad/blob/main/docs/design/validation.md) and
[ADR 0012](https://github.com/RocketSurgeonsGuild/LaunchPad/blob/main/docs/adr/0012-launchpad-owns-validation.md).
Loading
Loading