Ferrous Ferrous

Ferrous Music Store Case Study

A complete, runnable 6-chapter guide porting a classic .NET Music Store web app (ASP.NET Core Minimal APIs + EF Core SQLite + OpenAPI) from idiomatic vanilla C# to Rust-grade compile-time safety—one git tag at a time.

git clone https://github.com/bradwestness/FerrousMusicStore.git
Chapter 1

The Vanilla C# Baseline

chapter-01-vanilla

Every real-world .NET codebase starts somewhere familiar. In chapter-01-vanilla, our Music Store looks clean and idiomatic: EF Core with SQLite, Minimal APIs, OpenAPI, and an xUnit test suite. Everything compiles with <Nullable>enable</Nullable> and TreatWarningsAsErrors.

Yet hiding inside this perfectly "clean" C# are six classic production failure modes that the C# compiler cannot see:

  • Primitive obsession: Album.Id, ArtistId, GenreId, and Order.Id are all raw int. Swapping two arguments compiles silently.
  • Unvalidated strings & quantities: CustomerEmail is a raw string, Quantity can be 0 or -5, and Title can be whitespace.
  • Exception-driven control flow: CheckoutAsync throws ArgumentException, KeyNotFoundException, and InvalidOperationException—none of which appear in its return type Task<Order>.
  • Nullable ambiguity: FindAlbumAsync returns Task<Album?>, pushing null checks onto every caller.
  • Detached locking: InventoryCache uses private readonly object _gate = new();—nothing stops a future developer from reading _stock without taking _gate.
  • Invalid state transitions: Order.Status is a mutable enum (Draft, Reserved, Paid, Cancelled). Nothing stops code from marking a draft order Paid without reserving stock, or charging it twice.
Vanilla C# — StoreService.cs (chapter-01-vanilla)
public async Task<Order> CheckoutAsync(CheckoutRequest request, CancellationToken ct = default)
{
    if (request.Quantity <= 0)
        throw new ArgumentException("Quantity must be positive.", nameof(request));

    Album? album = await db.Albums.FirstOrDefaultAsync(a => a.Id == request.AlbumId, ct);
    if (album is null)
        throw new KeyNotFoundException($"Album {request.AlbumId} was not found.");

    if (album.Stock < request.Quantity)
        throw new InvalidOperationException($"Album '{album.Title}' only has {album.Stock} left.");
    ...
}
First Step on Any Existing Codebase

Running dotnet fe migrate ./src --report against chapter-01-vanilla immediately flags the throwing methods, nullable-returning methods, and raw lock (_gate) blocks—giving you an actionable migration punch list before you touch a single line of code.

Chapter 2

Eliminating Primitive Obsession

chapter-02-newtypes

In Chapter 2, we install Ferrous and Ferrous.EntityFrameworkCore and replace every raw primitive identifier and invariant-bearing field with zero-allocation domain types.

Before — Raw Primitives
public sealed class Album
{
    public int Id { get; set; }
    public int ArtistId { get; set; }
    public int GenreId { get; set; }
    public string Title { get; set; } = "";
}
After — [Newtype] & Refined Types
[Newtype(typeof(int))] public readonly partial struct AlbumId;
[Newtype(typeof(int))] public readonly partial struct ArtistId;
[Newtype(typeof(int))] public readonly partial struct GenreId;

public sealed class Album
{
    public AlbumId Id { get; set; }
    public ArtistId ArtistId { get; set; }
    public GenreId GenreId { get; set; }
    public NonEmptyString Title { get; set; }
}

Validated Newtypes & Zero-Boilerplate EF Core

For CustomerEmail, adding a single private static bool TryValidate(string value, out string error) method causes Ferrous.Unions to generate CustomerEmail.TryCreate(...) and a System.Text.Json converter automatically. And in MusicStoreDbContext, two lines wire up EF Core value converters for every refined type and [Newtype] in the domain assembly:

MusicStoreDbContext.cs — Zero Per-Property Converter Boilerplate
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder
        .UseFerrousConventions()          // NonEmptyString, NonZero<T>
        .UseFerrousNewtypes<AlbumId>();   // Auto-discovers all [Newtype] structs in the assembly
}
Benefit: Invalid States Become Unrepresentable

Passing an ArtistId where an AlbumId is expected is now a compile error (CS1503), AlbumId binds directly from ASP.NET Core route parameters via generated IParsable<AlbumId>, and SQLite translates a => a.Id == id straight to indexed SQL integer equality.

Full Chapter Diff (10 files changed) +166 -43 Compare on GitHub →
Directory.Packages.props
@@ -3,6 +3,10 @@
     <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
   </PropertyGroup>
   <ItemGroup>
+    <PackageVersion Include="Ferrous" Version="2.3.0" />
+    <PackageVersion Include="Ferrous.AspNetCore" Version="2.3.0" />
+    <PackageVersion Include="Ferrous.EntityFrameworkCore" Version="2.3.0" />
+    <PackageVersion Include="Ferrous.Testing" Version="2.3.0" />
     <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.15" />
     <PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="10.0.15" />
     <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
src/MusicStore.Api/Data/MusicStoreDbContext.cs
@@ -1,15 +1,34 @@
+using Ferrous.EntityFrameworkCore;
+using Ferrous.Results;
 using Microsoft.EntityFrameworkCore;
 using MusicStore.Domain;
 
 namespace MusicStore.Api.Data;
 
-/// <summary>EF Core SQLite database context for the Music Store.</summary>
+/// <summary>EF Core SQLite database context with automatic Ferrous refined-type and [Newtype] conventions.</summary>
 public sealed class MusicStoreDbContext(DbContextOptions<MusicStoreDbContext> options) : DbContext(options)
 {
     public DbSet<Album> Albums => Set<Album>();
 
     public DbSet<Order> Orders => Set<Order>();
 
+    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
+    {
+        configurationBuilder
+            .UseFerrousConventions()
+            .UseFerrousNewtypes<AlbumId>();
+    }
+
+    protected override void OnModelCreating(ModelBuilder modelBuilder)
+    {
+        modelBuilder.Entity<Album>(e => e.HasKey(a => a.Id));
+        modelBuilder.Entity<Order>(e =>
+        {
+            e.HasKey(o => o.Id);
+            e.Property(o => o.Id).ValueGeneratedNever();
+        });
+    }
+
     /// <summary>Seeds the catalog with classic albums if empty.</summary>
     public static async Task SeedAsync(MusicStoreDbContext db)
     {
@@ -19,10 +38,41 @@ public sealed class MusicStoreDbContext(DbContextOptions<MusicStoreDbContext> op
         }
 
         db.Albums.AddRange(
-            new Album { Id = 1, ArtistId = 10, GenreId = 1, Title = "Kind of Blue", Price = 14.99m, Stock = 5 },
-            new Album { Id = 2, ArtistId = 11, GenreId = 1, Title = "A Love Supreme", Price = 15.99m, Stock = 3 },
-            new Album { Id = 3, ArtistId = 12, GenreId = 2, Title = "Abbey Road", Price = 18.99m, Stock = 8 });
+            new Album
+            {
+                Id = new AlbumId(1),
+                ArtistId = new ArtistId(10),
+                GenreId = new GenreId(1),
+                Title = RequireTitle("Kind of Blue"),
+                Price = 14.99m,
+                Stock = 5,
+            },
+            new Album
+            {
+                Id = new AlbumId(2),
+                ArtistId = new ArtistId(11),
+                GenreId = new GenreId(1),
+                Title = RequireTitle("A Love Supreme"),
+                Price = 15.99m,
+                Stock = 3,
+            },
+            new Album
+            {
+                Id = new AlbumId(3),
+                ArtistId = new ArtistId(12),
+                GenreId = new GenreId(2),
+                Title = RequireTitle("Abbey Road"),
+                Price = 18.99m,
+                Stock = 8,
+            });
 
         await db.SaveChangesAsync();
     }
+
+    private static NonEmptyString RequireTitle(string raw)
+    {
+        return NonEmptyString.TryCreate(raw).Match(
+            some => some,
+            () => throw new InvalidOperationException($"Invalid seed title '{raw}'."));
+    }
 }
src/MusicStore.Api/MusicStore.Api.csproj
@@ -1,5 +1,8 @@
 <Project Sdk="Microsoft.NET.Sdk.Web">
   <ItemGroup>
+    <PackageReference Include="Ferrous" />
+    <PackageReference Include="Ferrous.AspNetCore" />
+    <PackageReference Include="Ferrous.EntityFrameworkCore" />
     <PackageReference Include="Microsoft.AspNetCore.OpenApi" />
     <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
   </ItemGroup>
src/MusicStore.Api/Program.cs
@@ -6,7 +6,7 @@ using MusicStore.Domain;
 
 WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
-var keepAliveConnection = new SqliteConnection("Data Source=:memory:");
+await using var keepAliveConnection = new SqliteConnection("Data Source=:memory:");
 keepAliveConnection.Open();
 
 builder.Services.AddSingleton(keepAliveConnection);
@@ -26,7 +26,7 @@ using (IServiceScope scope = app.Services.CreateScope())
 
 app.MapOpenApi();
 
-app.MapGet("/api/albums/{id:int}", async (int id, StoreService svc, CancellationToken ct) =>
+app.MapGet("/api/albums/{id}", async (AlbumId id, StoreService svc, CancellationToken ct) =>
 {
     Album? album = await svc.FindAlbumAsync(id, ct);
     return album is not null ? Results.Ok(album) : Results.NotFound();
src/MusicStore.Api/Services/InventoryCache.cs
@@ -1,15 +1,17 @@
+using MusicStore.Domain;
+
 namespace MusicStore.Api.Services;
 
 /// <summary>
-/// Vanilla C# thread-safe inventory cache using a raw <c>lock (_gate)</c>.
+/// Thread-safe inventory cache keyed by strongly-typed <see cref="AlbumId"/>.
 /// Replaced by data-owning <c>Mutex&lt;T&gt;</c> in Lesson 5.
 /// </summary>
 public sealed class InventoryCache
 {
     private readonly object _gate = new();
-    private readonly Dictionary<int, int> _stock = new();
+    private readonly Dictionary<AlbumId, int> _stock = new();
 
-    public void SetStock(int albumId, int count)
+    public void SetStock(AlbumId albumId, int count)
     {
         lock (_gate)
         {
@@ -17,7 +19,7 @@ public sealed class InventoryCache
         }
     }
 
-    public int? GetStock(int albumId)
+    public int? GetStock(AlbumId albumId)
     {
         lock (_gate)
         {
@@ -25,7 +27,7 @@ public sealed class InventoryCache
         }
     }
 
-    public bool TryReserve(int albumId, int quantity)
+    public bool TryReserve(AlbumId albumId, int quantity)
     {
         lock (_gate)
         {
src/MusicStore.Api/Services/StoreService.cs
@@ -1,3 +1,5 @@
+using Ferrous.Concurrency;
+using Ferrous.Results;
 using Microsoft.EntityFrameworkCore;
 using MusicStore.Api.Data;
 using MusicStore.Domain;
@@ -5,53 +7,63 @@ using MusicStore.Domain;
 namespace MusicStore.Api.Services;
 
 /// <summary>
-/// Vanilla C# store service returning nullable types and throwing exceptions for business failures.
+/// Store service using strongly-typed IDs and validated domain values (still throwing in Lesson 2;
+/// migrated to <see cref="Result{T, TError}"/> in Lesson 3).
 /// </summary>
 public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
 {
-    public async Task<Album?> FindAlbumAsync(int id, CancellationToken ct = default)
+    private static readonly Mutex<int> NextOrderId = new(1000);
+
+    public async Task<Album?> FindAlbumAsync(AlbumId id, CancellationToken ct = default)
     {
         return await db.Albums.FirstOrDefaultAsync(a => a.Id == id, ct);
     }
 
     public async Task<Order> CheckoutAsync(CheckoutRequest request, CancellationToken ct = default)
     {
-        if (request.Quantity <= 0)
+        if (!NonZero<int>.TryCreate(request.Quantity).TryGetValue(out NonZero<int> qty) || qty.Value < 0)
         {
             throw new ArgumentException("Quantity must be positive.", nameof(request));
         }
 
-        if (string.IsNullOrWhiteSpace(request.CustomerEmail) || !request.CustomerEmail.Contains('@', StringComparison.Ordinal))
+        if (!CustomerEmail.TryCreate(request.CustomerEmail, out CustomerEmail email, out string emailErr))
         {
-            throw new ArgumentException("Invalid customer email.", nameof(request));
+            throw new ArgumentException(emailErr, nameof(request));
         }
 
         Album? album = await db.Albums.FirstOrDefaultAsync(a => a.Id == request.AlbumId, ct);
         if (album is null)
         {
-            throw new KeyNotFoundException($"Album {request.AlbumId} was not found.");
+            throw new KeyNotFoundException($"Album {request.AlbumId.Value} was not found.");
         }
 
-        if (album.Stock < request.Quantity)
+        if (album.Stock < qty.Value)
         {
-            throw new InvalidOperationException($"Album '{album.Title}' only has {album.Stock} left in stock.");
+            throw new InvalidOperationException($"Album '{album.Title.Value}' only has {album.Stock} left in stock.");
         }
 
-        decimal discount = request.PromoCode == "JAZZ10" ? 0.10m : 0m;
-        if (!string.IsNullOrWhiteSpace(request.PromoCode) && discount == 0m)
+        decimal discount = request.PromoCode is { Value: "JAZZ10" } ? 0.10m : 0m;
+        if (request.PromoCode is { Value.Length: > 0 } && discount == 0m)
         {
-            throw new ArgumentException($"Unknown promo code '{request.PromoCode}'.", nameof(request));
+            throw new ArgumentException($"Unknown promo code '{request.PromoCode.Value.Value}'.", nameof(request));
         }
 
-        album.Stock -= request.Quantity;
+        album.Stock -= qty.Value;
         cache.SetStock(album.Id, album.Stock);
 
+        int nextId;
+        using (var idGuard = NextOrderId.Lock())
+        {
+            nextId = ++idGuard.Value;
+        }
+
         var order = new Order
         {
+            Id = new OrderId(nextId),
             AlbumId = album.Id,
-            Quantity = request.Quantity,
-            CustomerEmail = request.CustomerEmail,
-            TotalAmount = Math.Round(album.Price * request.Quantity * (1m - discount), 2),
+            Quantity = qty,
+            CustomerEmail = email,
+            TotalAmount = Math.Round(album.Price * qty.Value * (1m - discount), 2),
             Status = OrderStatus.Paid,
         };
 
src/MusicStore.Domain/Ids.cs
@@ -0,0 +1,40 @@
+using Ferrous;
+
+namespace MusicStore.Domain;
+
+/// <summary>Strongly-typed album identifier (prevents swapping with ArtistId or OrderId).</summary>
+[Newtype(typeof(int))]
+public readonly partial struct AlbumId;
+
+/// <summary>Strongly-typed artist identifier.</summary>
+[Newtype(typeof(int))]
+public readonly partial struct ArtistId;
+
+/// <summary>Strongly-typed genre identifier.</summary>
+[Newtype(typeof(int))]
+public readonly partial struct GenreId;
+
+/// <summary>Strongly-typed order identifier.</summary>
+[Newtype(typeof(int))]
+public readonly partial struct OrderId;
+
+/// <summary>Validated customer email address.</summary>
+[Newtype(typeof(string))]
+public readonly partial struct CustomerEmail
+{
+    private static bool TryValidate(string value, out string error)
+    {
+        if (string.IsNullOrWhiteSpace(value) || !value.Contains('@', StringComparison.Ordinal))
+        {
+            error = "Customer email must be a non-empty address containing '@'.";
+            return false;
+        }
+
+        error = string.Empty;
+        return true;
+    }
+}
+
+/// <summary>Optional promotional discount code.</summary>
+[Newtype(typeof(string))]
+public readonly partial struct PromoCode;
src/MusicStore.Domain/Models.cs
@@ -1,3 +1,5 @@
+using Ferrous.Results;
+
 namespace MusicStore.Domain;
 
 /// <summary>Classic mutable order status enum — replaced by linear [Typestate] in Lesson 4.</summary>
@@ -9,32 +11,32 @@ public enum OrderStatus
     Cancelled,
 }
 
-/// <summary>An album in the music store catalog.</summary>
+/// <summary>An album in the music store catalog with strongly-typed IDs and refined title.</summary>
 public sealed class Album
 {
-    public int Id { get; set; }
+    public AlbumId Id { get; set; }
 
-    public int ArtistId { get; set; }
+    public ArtistId ArtistId { get; set; }
 
-    public int GenreId { get; set; }
+    public GenreId GenreId { get; set; }
 
-    public string Title { get; set; } = string.Empty;
+    public NonEmptyString Title { get; set; }
 
     public decimal Price { get; set; }
 
     public int Stock { get; set; }
 }
 
-/// <summary>A customer order.</summary>
+/// <summary>A customer order with strongly-typed IDs, non-zero quantity, and validated email.</summary>
 public sealed class Order
 {
-    public int Id { get; set; }
+    public OrderId Id { get; set; }
 
-    public int AlbumId { get; set; }
+    public AlbumId AlbumId { get; set; }
 
-    public int Quantity { get; set; }
+    public NonZero<int> Quantity { get; set; }
 
-    public string CustomerEmail { get; set; } = string.Empty;
+    public CustomerEmail CustomerEmail { get; set; }
 
     public decimal TotalAmount { get; set; }
 
@@ -42,4 +44,4 @@ public sealed class Order
 }
 
 /// <summary>Request payload to place an order.</summary>
-public sealed record CheckoutRequest(int AlbumId, int Quantity, string CustomerEmail, string? PromoCode = null);
+public sealed record CheckoutRequest(AlbumId AlbumId, int Quantity, string CustomerEmail, PromoCode? PromoCode = null);
src/MusicStore.Domain/MusicStore.Domain.csproj
@@ -2,4 +2,8 @@
   <PropertyGroup>
     <Description>Domain models for the Ferrous Music Store case study.</Description>
   </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Ferrous" />
+  </ItemGroup>
 </Project>
tests/MusicStore.Tests/MusicStoreTests.cs
@@ -10,7 +10,7 @@ namespace MusicStore.Tests;
 public sealed class MusicStoreTests
 {
     [Fact]
-    public async Task VanillaCheckoutSucceedsAndThrowsOnErrors()
+    public async Task NewtypeCheckoutPersistsWithZeroBoilerplateConventions()
     {
         await using var connection = new SqliteConnection("Data Source=:memory:");
         await connection.OpenAsync();
@@ -25,15 +25,21 @@ public sealed class MusicStoreTests
 
         var svc = new StoreService(db, new InventoryCache());
 
-        Album? album = await svc.FindAlbumAsync(1);
+        Album? album = await svc.FindAlbumAsync(new AlbumId(1));
         Assert.NotNull(album);
-        Assert.Equal("Kind of Blue", album.Title);
+        Assert.Equal("Kind of Blue", album.Title.Value);
+
+        Order order = await svc.CheckoutAsync(new CheckoutRequest(
+            new AlbumId(1),
+            2,
+            "miles@jazz.fm",
+            new PromoCode("JAZZ10")));
 
-        Order order = await svc.CheckoutAsync(new CheckoutRequest(1, 2, "miles@jazz.fm", "JAZZ10"));
         Assert.Equal(OrderStatus.Paid, order.Status);
         Assert.Equal(26.98m, order.TotalAmount);
+        Assert.Equal("miles@jazz.fm", order.CustomerEmail.Value);
 
-        await Assert.ThrowsAsync<KeyNotFoundException>(() =>
-            svc.CheckoutAsync(new CheckoutRequest(999, 1, "miles@jazz.fm")));
+        await Assert.ThrowsAsync<ArgumentException>(() =>
+            svc.CheckoutAsync(new CheckoutRequest(new AlbumId(1), 1, "not-an-email")));
     }
 }
Chapter 3

Typed Errors & Exhaustive Unions

chapter-03-results-unions

Exceptions are invisible in C# signatures. When CheckoutAsync returns Task<Order>, nothing tells the HTTP endpoint which failures are possible—or reminds you to update the endpoint when a new business rule is added six months later.

In Chapter 3, we model every domain error as a zero-boxing [DiscriminatedUnion] with thiserror-style [ErrorMessage] templates, and switch EF Core queries from FirstOrDefaultAsync to FirstOrOptionAsync / FirstOrErrAsync:

StoreError.cs — Exhaustive, Zero-Boxing Error Union
[DiscriminatedUnion]
public readonly partial struct StoreError
{
    [ErrorMessage("Album {id} was not found.")]
    public static partial StoreError AlbumNotFound(AlbumId id);

    [ErrorMessage("Album '{title}' only has {available} copies left in stock (requested {requested}).")]
    public static partial StoreError OutOfStock(string title, int available, int requested);

    [ErrorMessage("Unknown promo code '{code}'.")]
    public static partial StoreError InvalidPromoCode(string code);

    [ErrorMessage("Payment declined: {reason}")]
    public static partial StoreError PaymentDeclined(string reason);

    [ErrorMessage("Validation failed: {message}")]
    public static partial StoreError ValidationFailed(string message);
}

Now CheckoutAsync returns Task<Result<Order, StoreError>>, and the HTTP endpoint maps every variant exhaustively to RFC 7807 ProblemDetails status codes:

Program.cs — Exhaustive HTTP Status Mapping
return result.ToProblemResult(
    statusCodeSelector: err => err.Match(
        onAlbumNotFound: _ => StatusCodes.Status404NotFound,
        onOutOfStock: (_, _, _) => StatusCodes.Status409Conflict,
        onInvalidPromoCode: _ => StatusCodes.Status422UnprocessableEntity,
        onPaymentDeclined: _ => StatusCodes.Status402PaymentRequired,
        onValidationFailed: _ => StatusCodes.Status400BadRequest),
    titleSelector: err => err.FormatError());
Benefit: Compiler-Enforced Exhaustiveness + Zero Allocation

Add a 6th error variant (e.g., RegionRestricted) and every Match call site fails to compile until you explicitly decide how to handle it. Plus [MustUse] (FE0001) ensures callers can never silently discard a Result or Option.

Full Chapter Diff (4 files changed) +86 -41 Compare on GitHub →
src/MusicStore.Api/Program.cs
@@ -1,3 +1,5 @@
+using Ferrous.AspNetCore;
+using Ferrous.Results;
 using Microsoft.Data.Sqlite;
 using Microsoft.EntityFrameworkCore;
 using MusicStore.Api.Data;
@@ -28,25 +30,20 @@ app.MapOpenApi();
 
 app.MapGet("/api/albums/{id}", async (AlbumId id, StoreService svc, CancellationToken ct) =>
 {
-    Album? album = await svc.FindAlbumAsync(id, ct);
-    return album is not null ? Results.Ok(album) : Results.NotFound();
+    Option<Album> album = await svc.FindAlbumAsync(id, ct);
+    return album.ToHttpResult(notFoundDetail: $"Album {id.Value} was not found.");
 });
 
 app.MapPost("/api/orders", async (CheckoutRequest req, StoreService svc, CancellationToken ct) =>
 {
-    try
-    {
-        Order order = await svc.CheckoutAsync(req, ct);
-        return Results.Ok(order);
-    }
-    catch (KeyNotFoundException ex)
-    {
-        return Results.NotFound(new { error = ex.Message });
-    }
-    catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
-    {
-        return Results.BadRequest(new { error = ex.Message });
-    }
+    Result<Order, StoreError> result = await svc.CheckoutAsync(req, ct);
+    return result.ToProblemResult(
+        statusCodeSelector: err => err.Match(
+            onAlbumNotFound: _ => StatusCodes.Status404NotFound,
+            onOutOfStock: (_, _, _) => StatusCodes.Status409Conflict,
+            onInvalidPromoCode: _ => StatusCodes.Status422UnprocessableEntity,
+            onPaymentDeclined: _ => StatusCodes.Status402PaymentRequired,
+            onValidationFailed: _ => StatusCodes.Status400BadRequest));
 });
 
 app.Run();
src/MusicStore.Api/Services/StoreService.cs
@@ -1,51 +1,61 @@
 using Ferrous.Concurrency;
+using Ferrous.EntityFrameworkCore;
 using Ferrous.Results;
-using Microsoft.EntityFrameworkCore;
 using MusicStore.Api.Data;
 using MusicStore.Domain;
 
 namespace MusicStore.Api.Services;
 
 /// <summary>
-/// Store service using strongly-typed IDs and validated domain values (still throwing in Lesson 2;
-/// migrated to <see cref="Result{T, TError}"/> in Lesson 3).
+/// Exception-free store service returning <see cref="Option{T}"/> and
+/// <see cref="Result{T, TError}"/> with exhaustive <see cref="StoreError"/> variants.
 /// </summary>
 public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
 {
     private static readonly Mutex<int> NextOrderId = new(1000);
 
-    public async Task<Album?> FindAlbumAsync(AlbumId id, CancellationToken ct = default)
+    /// <summary>Finds an album by its strongly-typed ID without returning <see langword="null"/>.</summary>
+    public Task<Option<Album>> FindAlbumAsync(AlbumId id, CancellationToken ct = default)
     {
-        return await db.Albums.FirstOrDefaultAsync(a => a.Id == id, ct);
+        return db.Albums.FirstOrOptionAsync(a => a.Id == id, ct);
     }
 
-    public async Task<Order> CheckoutAsync(CheckoutRequest request, CancellationToken ct = default)
+    /// <summary>Executes checkout without throwing exceptions for business failures.</summary>
+    public async Task<Result<Order, StoreError>> CheckoutAsync(CheckoutRequest request, CancellationToken ct = default)
     {
         if (!NonZero<int>.TryCreate(request.Quantity).TryGetValue(out NonZero<int> qty) || qty.Value < 0)
         {
-            throw new ArgumentException("Quantity must be positive.", nameof(request));
+            return Result.Err<Order, StoreError>(StoreError.ValidationFailed("Quantity must be positive."));
         }
 
         if (!CustomerEmail.TryCreate(request.CustomerEmail, out CustomerEmail email, out string emailErr))
         {
-            throw new ArgumentException(emailErr, nameof(request));
+            return Result.Err<Order, StoreError>(StoreError.ValidationFailed(emailErr));
         }
 
-        Album? album = await db.Albums.FirstOrDefaultAsync(a => a.Id == request.AlbumId, ct);
-        if (album is null)
+        Result<Album, StoreError> albumResult = await db.Albums.FirstOrErrAsync(
+            a => a.Id == request.AlbumId,
+            () => StoreError.AlbumNotFound(request.AlbumId),
+            ct);
+
+        if (!albumResult.TryGetOk(out Album? album))
         {
-            throw new KeyNotFoundException($"Album {request.AlbumId.Value} was not found.");
+            return albumResult.MapErr(e => e).Match(
+                _ => Result.Err<Order, StoreError>(StoreError.AlbumNotFound(request.AlbumId)),
+                Result.Err<Order, StoreError>);
         }
 
         if (album.Stock < qty.Value)
         {
-            throw new InvalidOperationException($"Album '{album.Title.Value}' only has {album.Stock} left in stock.");
+            return Result.Err<Order, StoreError>(
+                StoreError.OutOfStock(album.Title.Value, album.Stock, qty.Value));
         }
 
         decimal discount = request.PromoCode is { Value: "JAZZ10" } ? 0.10m : 0m;
         if (request.PromoCode is { Value.Length: > 0 } && discount == 0m)
         {
-            throw new ArgumentException($"Unknown promo code '{request.PromoCode.Value.Value}'.", nameof(request));
+            return Result.Err<Order, StoreError>(
+                StoreError.InvalidPromoCode(request.PromoCode.Value.Value));
         }
 
         album.Stock -= qty.Value;
@@ -69,6 +79,6 @@ public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
 
         db.Orders.Add(order);
         await db.SaveChangesAsync(ct);
-        return order;
+        return Result.Ok<Order, StoreError>(order);
     }
 }
src/MusicStore.Domain/StoreError.cs
@@ -0,0 +1,32 @@
+using Ferrous;
+
+namespace MusicStore.Domain;
+
+/// <summary>
+/// Exhaustive, zero-boxing discriminated union of all domain errors in the Music Store.
+/// Replaces <see cref="KeyNotFoundException"/>, <see cref="ArgumentException"/>, and
+/// <see cref="InvalidOperationException"/> with compile-time exhaustiveness checking.
+/// </summary>
+[DiscriminatedUnion]
+public readonly partial struct StoreError
+{
+    /// <summary>The requested album does not exist in the catalog.</summary>
+    [ErrorMessage("Album {id} was not found.")]
+    public static partial StoreError AlbumNotFound(AlbumId id);
+
+    /// <summary>Requested quantity exceeds current inventory.</summary>
+    [ErrorMessage("Album '{title}' only has {available} copies left in stock (requested {requested}).")]
+    public static partial StoreError OutOfStock(string title, int available, int requested);
+
+    /// <summary>The supplied promo code is not recognized.</summary>
+    [ErrorMessage("Unknown promo code '{code}'.")]
+    public static partial StoreError InvalidPromoCode(string code);
+
+    /// <summary>Payment authorization was declined.</summary>
+    [ErrorMessage("Payment declined: {reason}")]
+    public static partial StoreError PaymentDeclined(string reason);
+
+    /// <summary>Input validation failed.</summary>
+    [ErrorMessage("Validation failed: {message}")]
+    public static partial StoreError ValidationFailed(string message);
+}
tests/MusicStore.Tests/MusicStoreTests.cs
@@ -1,3 +1,4 @@
+using Ferrous.Results;
 using Microsoft.Data.Sqlite;
 using Microsoft.EntityFrameworkCore;
 using MusicStore.Api.Data;
@@ -10,7 +11,7 @@ namespace MusicStore.Tests;
 public sealed class MusicStoreTests
 {
     [Fact]
-    public async Task NewtypeCheckoutPersistsWithZeroBoilerplateConventions()
+    public async Task ResultAndDiscriminatedUnionEliminateExceptions()
     {
         await using var connection = new SqliteConnection("Data Source=:memory:");
         await connection.OpenAsync();
@@ -25,21 +26,26 @@ public sealed class MusicStoreTests
 
         var svc = new StoreService(db, new InventoryCache());
 
-        Album? album = await svc.FindAlbumAsync(new AlbumId(1));
-        Assert.NotNull(album);
-        Assert.Equal("Kind of Blue", album.Title.Value);
+        Option<Album> album = await svc.FindAlbumAsync(new AlbumId(1));
+        Assert.True(album.IsSome);
 
-        Order order = await svc.CheckoutAsync(new CheckoutRequest(
+        Result<Order, StoreError> ok = await svc.CheckoutAsync(new CheckoutRequest(
             new AlbumId(1),
             2,
             "miles@jazz.fm",
             new PromoCode("JAZZ10")));
-
-        Assert.Equal(OrderStatus.Paid, order.Status);
-        Assert.Equal(26.98m, order.TotalAmount);
-        Assert.Equal("miles@jazz.fm", order.CustomerEmail.Value);
-
-        await Assert.ThrowsAsync<ArgumentException>(() =>
-            svc.CheckoutAsync(new CheckoutRequest(new AlbumId(1), 1, "not-an-email")));
+        Assert.True(ok.IsOk);
+        Assert.Equal(26.98m, ok.Match(o => o.TotalAmount, _ => 0m));
+
+        Result<Order, StoreError> missing = await svc.CheckoutAsync(
+            new CheckoutRequest(new AlbumId(999), 1, "miles@jazz.fm"));
+        Assert.True(missing.IsErr);
+        string msg = missing.Match(_ => "", e => e.FormatError());
+        Assert.Contains("999", msg, StringComparison.Ordinal);
+
+        Result<Order, StoreError> outOfStock = await svc.CheckoutAsync(
+            new CheckoutRequest(new AlbumId(1), 50, "miles@jazz.fm"));
+        Assert.True(outOfStock.IsErr);
+        Assert.Contains("left in stock", outOfStock.Match(_ => "", e => e.FormatError()), StringComparison.Ordinal);
     }
 }
Chapter 4

Linear Typestate Checkout Protocol

chapter-04-typestate-checkout

A mutable OrderStatus enum only validates transitions at runtime—if you remember to write the if (order.Status != OrderStatus.Reserved) check in every method. Forget one check and you can capture payment twice, ship an unpaid cart, or leak reserved inventory when an error occurs mid-checkout.

In Chapter 4, we encode the checkout lifecycle directly into the C# type system using Ferrous's [Typestate] and [ConsumesSelf] attributes:

stateDiagram-v2
    [*] --> DraftCart
    DraftCart --> DraftCart: ApplyPromo
    DraftCart --> ReservedOrder: ReserveInventory
    DraftCart --> CancelledOrder: Abandon
    ReservedOrder --> PaidOrder: CapturePayment
    ReservedOrder --> CancelledOrder: ReleaseInventory
    PaidOrder --> [*]
    CancelledOrder --> [*]
          
CheckoutProtocol.cs — Compile-Time Enforced State Machine
[Typestate(IsInitial = true)]
public sealed class DraftCart
{
    [ConsumesSelf] public DraftCart ApplyPromo(decimal discountRate) { ... }
    [ConsumesSelf] public ReservedOrder ReserveInventory(OrderId orderId) { ... }
    [ConsumesSelf] public CancelledOrder Abandon(string reason) { ... }
}

[Typestate]
public sealed class ReservedOrder
{
    [ConsumesSelf] public PaidOrder CapturePayment(string receiptId) { ... }
    [ConsumesSelf] public CancelledOrder ReleaseInventory(string reason) { ... }
}

[Typestate(IsTerminal = true)] public sealed class PaidOrder { ... }
[Typestate(IsTerminal = true)] public sealed class CancelledOrder { ... }
Real Compiler Catch During Development (FE0303)

While writing Chapter 4, we initially wrote DraftCart priced = discount > 0m ? draft.ApplyPromo(discount) : draft;. Ferrous immediately rejected it with error FE0303: non-terminal typestate 'draft' falls out of scope without transitioning on the false branch! Calling draft.ApplyPromo(discount).ReserveInventory(...) linearly fixed the ownership flow—and the compiler proved that ReservedOrder can never leak without either CapturePayment or ReleaseInventory.

Explore the generated documentation (including the live Mermaid diagram embedded automatically by dotnet fe doc) in the Music Store API Reference.

Full Chapter Diff (2 files changed) +160 -17 Compare on GitHub →
src/MusicStore.Api/Services/StoreService.cs
@@ -45,12 +45,6 @@ public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
                 Result.Err<Order, StoreError>);
         }
 
-        if (album.Stock < qty.Value)
-        {
-            return Result.Err<Order, StoreError>(
-                StoreError.OutOfStock(album.Title.Value, album.Stock, qty.Value));
-        }
-
         decimal discount = request.PromoCode is { Value: "JAZZ10" } ? 0.10m : 0m;
         if (request.PromoCode is { Value.Length: > 0 } && discount == 0m)
         {
@@ -58,24 +52,25 @@ public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
                 StoreError.InvalidPromoCode(request.PromoCode.Value.Value));
         }
 
-        album.Stock -= qty.Value;
-        cache.SetStock(album.Id, album.Stock);
-
         int nextId;
         using (var idGuard = NextOrderId.Lock())
         {
             nextId = ++idGuard.Value;
         }
 
-        var order = new Order
+        var draft = new DraftCart(album.Id, qty, email, album.Price);
+        ReservedOrder reserved = draft.ApplyPromo(discount).ReserveInventory(new OrderId(nextId));
+        if (album.Stock < qty.Value)
         {
-            Id = new OrderId(nextId),
-            AlbumId = album.Id,
-            Quantity = qty,
-            CustomerEmail = email,
-            TotalAmount = Math.Round(album.Price * qty.Value * (1m - discount), 2),
-            Status = OrderStatus.Paid,
-        };
+            CancelledOrder cancelled = reserved.ReleaseInventory("Insufficient stock");
+            return Result.Err<Order, StoreError>(StoreError.OutOfStock(album.Title.Value, album.Stock, qty.Value));
+        }
+
+        album.Stock -= qty.Value;
+        cache.SetStock(album.Id, album.Stock);
+
+        PaidOrder paid = reserved.CapturePayment($"RCPT-{nextId}");
+        Order order = paid.ToOrderEntity();
 
         db.Orders.Add(order);
         await db.SaveChangesAsync(ct);
src/MusicStore.Domain/CheckoutProtocol.cs
@@ -0,0 +1,148 @@
+using Ferrous;
+using Ferrous.Results;
+
+namespace MusicStore.Domain;
+
+/// <summary>
+/// Initial state of the linear checkout protocol. Cannot be paid or shipped until inventory is reserved
+/// via <see cref="ReserveInventory"/> (enforced at compile time by <c>FE0300</c>–<c>FE0303</c>).
+/// </summary>
+[Typestate(IsInitial = true)]
+public sealed class DraftCart
+{
+    /// <summary>Initializes a new draft cart for checkout.</summary>
+    public DraftCart(AlbumId albumId, NonZero<int> quantity, CustomerEmail email, decimal unitPrice, decimal discountRate = 0m)
+    {
+        AlbumId = albumId;
+        Quantity = quantity;
+        Email = email;
+        UnitPrice = unitPrice;
+        DiscountRate = discountRate;
+    }
+
+    public AlbumId AlbumId { get; }
+
+    public NonZero<int> Quantity { get; }
+
+    public CustomerEmail Email { get; }
+
+    public decimal UnitPrice { get; }
+
+    public decimal DiscountRate { get; }
+
+    /// <summary>Consumes this draft cart and returns a new draft cart with <paramref name="discountRate"/> applied.</summary>
+    [ConsumesSelf]
+    public DraftCart ApplyPromo(decimal discountRate)
+    {
+        return new DraftCart(AlbumId, Quantity, Email, UnitPrice, discountRate);
+    }
+
+    /// <summary>Consumes this draft cart and transitions to <see cref="ReservedOrder"/>.</summary>
+    [ConsumesSelf]
+    public ReservedOrder ReserveInventory(OrderId orderId)
+    {
+        decimal total = Math.Round(UnitPrice * Quantity.Value * (1m - DiscountRate), 2);
+        return new ReservedOrder(orderId, AlbumId, Quantity, Email, total);
+    }
+
+    /// <summary>Abandons the draft cart cleanly without holding inventory.</summary>
+    [ConsumesSelf]
+    public CancelledOrder Abandon(string reason)
+    {
+        return new CancelledOrder(reason);
+    }
+}
+
+/// <summary>
+/// Intermediate state holding reserved inventory. Must transition to either <see cref="PaidOrder"/>
+/// or <see cref="CancelledOrder"/> before leaving scope (otherwise <c>FE0301</c> flags a resource leak).
+/// </summary>
+[Typestate]
+public sealed class ReservedOrder
+{
+    internal ReservedOrder(OrderId orderId, AlbumId albumId, NonZero<int> quantity, CustomerEmail email, decimal totalAmount)
+    {
+        OrderId = orderId;
+        AlbumId = albumId;
+        Quantity = quantity;
+        Email = email;
+        TotalAmount = totalAmount;
+    }
+
+    public OrderId OrderId { get; }
+
+    public AlbumId AlbumId { get; }
+
+    public NonZero<int> Quantity { get; }
+
+    public CustomerEmail Email { get; }
+
+    public decimal TotalAmount { get; }
+
+    /// <summary>Captures payment and transitions to the terminal <see cref="PaidOrder"/> state.</summary>
+    [ConsumesSelf]
+    public PaidOrder CapturePayment(string receiptId)
+    {
+        return new PaidOrder(OrderId, AlbumId, Quantity, Email, TotalAmount, receiptId);
+    }
+
+    /// <summary>Releases reserved inventory and transitions to the terminal <see cref="CancelledOrder"/> state.</summary>
+    [ConsumesSelf]
+    public CancelledOrder ReleaseInventory(string reason)
+    {
+        return new CancelledOrder(reason);
+    }
+}
+
+/// <summary>Terminal state representing a paid, ready-to-fulfill order.</summary>
+[Typestate(IsTerminal = true)]
+public sealed class PaidOrder
+{
+    internal PaidOrder(OrderId orderId, AlbumId albumId, NonZero<int> quantity, CustomerEmail email, decimal totalAmount, string receiptId)
+    {
+        OrderId = orderId;
+        AlbumId = albumId;
+        Quantity = quantity;
+        Email = email;
+        TotalAmount = totalAmount;
+        ReceiptId = receiptId;
+    }
+
+    public OrderId OrderId { get; }
+
+    public AlbumId AlbumId { get; }
+
+    public NonZero<int> Quantity { get; }
+
+    public CustomerEmail Email { get; }
+
+    public decimal TotalAmount { get; }
+
+    public string ReceiptId { get; }
+
+    /// <summary>Projects this terminal paid order into the persisted <see cref="Order"/> entity.</summary>
+    public Order ToOrderEntity()
+    {
+        return new Order
+        {
+            Id = OrderId,
+            AlbumId = AlbumId,
+            Quantity = Quantity,
+            CustomerEmail = Email,
+            TotalAmount = TotalAmount,
+            Status = OrderStatus.Paid,
+        };
+    }
+}
+
+/// <summary>Terminal state representing a cancelled or abandoned checkout.</summary>
+[Typestate(IsTerminal = true)]
+public sealed class CancelledOrder
+{
+    internal CancelledOrder(string reason)
+    {
+        Reason = reason;
+    }
+
+    public string Reason { get; }
+}
Chapter 5

Fearless Concurrency, RAII Rollback & Pedantic Mode

chapter-05-concurrency-pedantic

Chapter 5 hardens the runtime execution path and flips on <FerrousPedantic>true</FerrousPedantic> across the entire solution so every Ferrous safety rule is enforced as a build error:

Before — Detached lock (_gate)
private readonly object _gate = new();
private readonly Dictionary<AlbumId, int> _stock = new();

public Option<int> GetStock(AlbumId id)
{
    // Nothing forces callers to lock(_gate)!
    lock (_gate)
        return _stock.TryGetValue(id, out int c)
            ? Option.Some(c) : Option.None<int>();
}
After — Data-Owning Mutex<T>
private readonly Mutex<Dictionary<AlbumId, int>> _stock
    = new(new Dictionary<AlbumId, int>());

public Option<int> GetStock(AlbumId id)
{
    using var guard = _stock.Lock();
    return guard.Value.TryGetValue(id, out int c)
        ? Option.Some(c) : Option.None<int>();
}
  • Structured Concurrency (TaskScope): GetCatalogSummaryAsync spawns child tasks inside await using var scope = new TaskScope(ct)—guaranteeing every child completes or cancels cleanly before returning (FE0503 prevents detached Task.Run).
  • Zero-Allocation RAII Rollback (ScopeGuard.Defer): CommitInventoryAndCapture takes [Consuming] ReservedOrder and registers a stack-only rollback guard that restores stock automatically unless rollback.Dismiss() is reached.
  • Zero-Reflection Tracing ([Instrument]): Decorating FindAlbumAsync and CheckoutAsync generates System.Diagnostics.ActivitySource spans with parameter tagging at compile time.
Real Compiler Catches (FE0401, FE0408, FE0419, FE0501)

Turning on <FerrousPedantic>true</FerrousPedantic> immediately caught four subtle issues in our own code: a mutable static _nextOrderId field (FE0501), an undisposed SqliteConnection in Program.cs (FE0419), raw .Unwrap() calls in seed data (FE0401), and unawaited Task discards (FE0408). Every single one was fixed cleanly before shipping.

Full Chapter Diff (3 files changed) +94 -31 Compare on GitHub →
Directory.Build.props
@@ -4,6 +4,7 @@
     <Nullable>enable</Nullable>
     <ImplicitUsings>enable</ImplicitUsings>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+    <FerrousPedantic>true</FerrousPedantic>
     <GenerateDocumentationFile>true</GenerateDocumentationFile>
     <NoWarn>$(NoWarn);CS1591</NoWarn>
   </PropertyGroup>
src/MusicStore.Api/Services/InventoryCache.cs
@@ -1,43 +1,43 @@
+using Ferrous.Concurrency;
+using Ferrous.Results;
 using MusicStore.Domain;
 
 namespace MusicStore.Api.Services;
 
 /// <summary>
-/// Thread-safe inventory cache keyed by strongly-typed <see cref="AlbumId"/>.
-/// Replaced by data-owning <c>Mutex&lt;T&gt;</c> in Lesson 5.
+/// Data-owning inventory cache backed by <see cref="Mutex{T}"/>.
+/// Eliminates raw <c>lock</c> blocks — it is impossible to read or mutate the dictionary without holding the guard.
 /// </summary>
 public sealed class InventoryCache
 {
-    private readonly object _gate = new();
-    private readonly Dictionary<AlbumId, int> _stock = new();
+    private readonly Mutex<Dictionary<AlbumId, int>> _stock = new(new Dictionary<AlbumId, int>());
 
+    /// <summary>Updates the cached stock level for <paramref name="albumId"/>.</summary>
     public void SetStock(AlbumId albumId, int count)
     {
-        lock (_gate)
-        {
-            _stock[albumId] = count;
-        }
+        using var guard = _stock.Lock();
+        guard.Value[albumId] = count;
     }
 
-    public int? GetStock(AlbumId albumId)
+    /// <summary>Reads the cached stock level for <paramref name="albumId"/> as an <see cref="Option{T}"/>.</summary>
+    public Option<int> GetStock(AlbumId albumId)
     {
-        lock (_gate)
-        {
-            return _stock.TryGetValue(albumId, out int count) ? count : null;
-        }
+        using var guard = _stock.Lock();
+        return guard.Value.TryGetValue(albumId, out int count)
+            ? Option.Some(count)
+            : Option.None<int>();
     }
 
+    /// <summary>Atomically reserves <paramref name="quantity"/> units if sufficient stock is cached.</summary>
     public bool TryReserve(AlbumId albumId, int quantity)
     {
-        lock (_gate)
+        using var guard = _stock.Lock();
+        if (!guard.Value.TryGetValue(albumId, out int current) || current < quantity)
         {
-            if (!_stock.TryGetValue(albumId, out int current) || current < quantity)
-            {
-                return false;
-            }
-
-            _stock[albumId] = current - quantity;
-            return true;
+            return false;
         }
+
+        guard.Value[albumId] = current - quantity;
+        return true;
     }
 }
src/MusicStore.Api/Services/StoreService.cs
@@ -1,26 +1,70 @@
+using Ferrous;
 using Ferrous.Concurrency;
 using Ferrous.EntityFrameworkCore;
+using Ferrous.Guard;
 using Ferrous.Results;
+using Microsoft.EntityFrameworkCore;
 using MusicStore.Api.Data;
 using MusicStore.Domain;
 
 namespace MusicStore.Api.Services;
 
+/// <summary>Snapshot of store catalog and order metrics gathered via structured concurrency.</summary>
+public sealed record CatalogSummary(int AlbumCount, int TotalStock, int OrderCount);
+
 /// <summary>
-/// Exception-free store service returning <see cref="Option{T}"/> and
-/// <see cref="Result{T, TError}"/> with exhaustive <see cref="StoreError"/> variants.
+/// Exception-free, instrumented store service combining <see cref="Result{T, TError}"/>,
+/// linear <c>[Typestate]</c> checkout, <see cref="ScopeGuard"/> rollback, and structured <see cref="TaskScope"/>.
 /// </summary>
-public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
+public sealed partial class StoreService(MusicStoreDbContext db, InventoryCache cache)
 {
     private static readonly Mutex<int> NextOrderId = new(1000);
 
     /// <summary>Finds an album by its strongly-typed ID without returning <see langword="null"/>.</summary>
+    [Instrument("MusicStore.FindAlbum")]
     public Task<Option<Album>> FindAlbumAsync(AlbumId id, CancellationToken ct = default)
     {
         return db.Albums.FirstOrOptionAsync(a => a.Id == id, ct);
     }
 
-    /// <summary>Executes checkout without throwing exceptions for business failures.</summary>
+    /// <summary>
+    /// Computes a catalog summary using structured concurrency (<see cref="TaskScope"/>) so all
+    /// child tasks are guaranteed to complete or cancel before returning.
+    /// </summary>
+    public async Task<CatalogSummary> GetCatalogSummaryAsync(CancellationToken ct = default)
+    {
+        List<Album> albums = await db.Albums.AsNoTracking().ToListAsync(ct);
+        int orderCount = await db.Orders.CountAsync(ct);
+
+        int albumCount = 0;
+        int totalStock = 0;
+
+        await using (var scope = new TaskScope(ct))
+        {
+            _ = scope.Spawn(_ =>
+            {
+                albumCount = albums.Count;
+                return Task.CompletedTask;
+            });
+
+            _ = scope.Spawn(_ =>
+            {
+                int sum = 0;
+                foreach (Album album in albums)
+                {
+                    sum += album.Stock;
+                }
+
+                totalStock = sum;
+                return Task.CompletedTask;
+            });
+        }
+
+        return new CatalogSummary(albumCount, totalStock, orderCount);
+    }
+
+    /// <summary>Executes linear typestate checkout with <see cref="ScopeGuard"/> rollback protection.</summary>
+    [Instrument("MusicStore.Checkout")]
     public async Task<Result<Order, StoreError>> CheckoutAsync(CheckoutRequest request, CancellationToken ct = default)
     {
         if (!NonZero<int>.TryCreate(request.Quantity).TryGetValue(out NonZero<int> qty) || qty.Value < 0)
@@ -40,7 +84,7 @@ public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
 
         if (!albumResult.TryGetOk(out Album? album))
         {
-            return albumResult.MapErr(e => e).Match(
+            return albumResult.Match(
                 _ => Result.Err<Order, StoreError>(StoreError.AlbumNotFound(request.AlbumId)),
                 Result.Err<Order, StoreError>);
         }
@@ -60,20 +104,38 @@ public sealed class StoreService(MusicStoreDbContext db, InventoryCache cache)
 
         var draft = new DraftCart(album.Id, qty, email, album.Price);
         ReservedOrder reserved = draft.ApplyPromo(discount).ReserveInventory(new OrderId(nextId));
+
         if (album.Stock < qty.Value)
         {
-            CancelledOrder cancelled = reserved.ReleaseInventory("Insufficient stock");
+            _ = reserved.ReleaseInventory("Insufficient stock");
             return Result.Err<Order, StoreError>(StoreError.OutOfStock(album.Title.Value, album.Stock, qty.Value));
         }
 
-        album.Stock -= qty.Value;
-        cache.SetStock(album.Id, album.Stock);
-
-        PaidOrder paid = reserved.CapturePayment($"RCPT-{nextId}");
+        PaidOrder paid = CommitInventoryAndCapture(album, qty, reserved, nextId);
         Order order = paid.ToOrderEntity();
 
         db.Orders.Add(order);
         await db.SaveChangesAsync(ct);
+
         return Result.Ok<Order, StoreError>(order);
     }
+
+    private PaidOrder CommitInventoryAndCapture(Album album, NonZero<int> qty, [Consuming] ReservedOrder reserved, int nextId)
+    {
+        int previousStock = album.Stock;
+        using var rollback = ScopeGuard.Defer(
+            (cache, album, previousStock),
+            static s =>
+            {
+                s.album.Stock = s.previousStock;
+                s.cache.SetStock(s.album.Id, s.previousStock);
+            });
+
+        album.Stock -= qty.Value;
+        cache.SetStock(album.Id, album.Stock);
+
+        PaidOrder paid = reserved.CapturePayment($"RCPT-{nextId}");
+        rollback.Dismiss();
+        return paid;
+    }
 }
Chapter 6

Minimal APIs, OpenAPI & Rust-Grade Testing

chapter-06-web-data-testing

In the final chapter, we wire Ferrous.AspNetCore into the Minimal API pipeline and prove our invariants with three complementary layers of testing from Ferrous.Testing:

Program.cs — Clean Minimal APIs + Unwrapped OpenAPI 3.1 Schemas
builder.Services.AddOpenApi(options => options.AddFerrousOpenApi());

var api = app.MapGroup("/api").WithFerrousResults();

// Returns Task<Option<Album>> directly — auto-unwrapped to 200 OK or 404 Not Found!
api.MapGet("/albums/{id}", (AlbumId id, StoreService svc, CancellationToken ct) =>
    svc.FindAlbumAsync(id, ct))
    .Produces<Album>(StatusCodes.Status200OK);

Proving Invalid States Cannot Compile (CompileAssert) & Property Laws (PropAssert)

Compile-Fail Test (trybuild-style)
// Proves FE0300 (direct Paid construction),
// FE0200 (use-after-move), and FE0303 (leaked
// ReservedOrder) are caught at compile time:
CompileAssert.Fails(badCode,
    "FE0300", "FE0200", "FE0303");
Property-Based Shrinking Test
PropAssert.ForAll(
    Gen.Decimal(1m, 200m),
    Gen.NonZeroInt(1, 20),
    Gen.Decimal(0m, 0.5m),
    (price, qty, discount) => {
        var paid = new DraftCart(id, qty, email, price)
            .ApplyPromo(discount)
            .ReserveInventory(orderId)
            .CapturePayment("RCPT");
        return paid.TotalAmount >= 0m
            && paid.TotalAmount <= price * qty.Value;
    }, iterations: 200, seed: 42);
Full Chapter Diff (4 files changed) +175 -44 Compare on GitHub →
Directory.Packages.props
@@ -3,10 +3,10 @@
     <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
   </PropertyGroup>
   <ItemGroup>
-    <PackageVersion Include="Ferrous" Version="2.3.0" />
-    <PackageVersion Include="Ferrous.AspNetCore" Version="2.3.0" />
-    <PackageVersion Include="Ferrous.EntityFrameworkCore" Version="2.3.0" />
-    <PackageVersion Include="Ferrous.Testing" Version="2.3.0" />
+    <PackageVersion Include="Ferrous" Version="2.3.1" />
+    <PackageVersion Include="Ferrous.AspNetCore" Version="2.3.1" />
+    <PackageVersion Include="Ferrous.EntityFrameworkCore" Version="2.3.1" />
+    <PackageVersion Include="Ferrous.Testing" Version="2.3.1" />
     <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.15" />
     <PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="10.0.15" />
     <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
src/MusicStore.Api/Program.cs
@@ -15,7 +15,7 @@ builder.Services.AddSingleton(keepAliveConnection);
 builder.Services.AddDbContext<MusicStoreDbContext>(opt => opt.UseSqlite(keepAliveConnection));
 builder.Services.AddSingleton<InventoryCache>();
 builder.Services.AddScoped<StoreService>();
-builder.Services.AddOpenApi();
+builder.Services.AddOpenApi(options => options.AddFerrousOpenApi());
 
 WebApplication app = builder.Build();
 
@@ -28,13 +28,16 @@ using (IServiceScope scope = app.Services.CreateScope())
 
 app.MapOpenApi();
 
-app.MapGet("/api/albums/{id}", async (AlbumId id, StoreService svc, CancellationToken ct) =>
-{
-    Option<Album> album = await svc.FindAlbumAsync(id, ct);
-    return album.ToHttpResult(notFoundDetail: $"Album {id.Value} was not found.");
-});
+var api = app.MapGroup("/api").WithFerrousResults();
+
+api.MapGet("/albums/{id}", (AlbumId id, StoreService svc, CancellationToken ct) =>
+    svc.FindAlbumAsync(id, ct))
+    .Produces<Album>(StatusCodes.Status200OK);
+
+api.MapGet("/catalog/summary", (StoreService svc, CancellationToken ct) =>
+    svc.GetCatalogSummaryAsync(ct));
 
-app.MapPost("/api/orders", async (CheckoutRequest req, StoreService svc, CancellationToken ct) =>
+api.MapPost("/orders", async (CheckoutRequest req, StoreService svc, CancellationToken ct) =>
 {
     Result<Order, StoreError> result = await svc.CheckoutAsync(req, ct);
     return result.ToProblemResult(
@@ -43,7 +46,8 @@ app.MapPost("/api/orders", async (CheckoutRequest req, StoreService svc, Cancell
             onOutOfStock: (_, _, _) => StatusCodes.Status409Conflict,
             onInvalidPromoCode: _ => StatusCodes.Status422UnprocessableEntity,
             onPaymentDeclined: _ => StatusCodes.Status402PaymentRequired,
-            onValidationFailed: _ => StatusCodes.Status400BadRequest));
+            onValidationFailed: _ => StatusCodes.Status400BadRequest),
+        titleSelector: err => err.FormatError());
 });
 
 app.Run();
tests/MusicStore.Tests/MusicStore.Tests.csproj
@@ -5,6 +5,8 @@
 
   <ItemGroup>
     <FrameworkReference Include="Microsoft.AspNetCore.App" />
+    <PackageReference Include="Ferrous.Testing" />
+    <PackageReference Include="Microsoft.AspNetCore.OpenApi" />
     <PackageReference Include="Microsoft.AspNetCore.TestHost" />
     <PackageReference Include="Microsoft.NET.Test.Sdk" />
     <PackageReference Include="xunit" />
tests/MusicStore.Tests/MusicStoreTests.cs
@@ -1,6 +1,15 @@
+using System.Net;
+using System.Net.Http.Json;
+using Ferrous.AspNetCore;
 using Ferrous.Results;
+using Ferrous.Testing;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.TestHost;
 using Microsoft.Data.Sqlite;
 using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
 using MusicStore.Api.Data;
 using MusicStore.Api.Services;
 using MusicStore.Domain;
@@ -11,41 +20,157 @@ namespace MusicStore.Tests;
 public sealed class MusicStoreTests
 {
     [Fact]
-    public async Task ResultAndDiscriminatedUnionEliminateExceptions()
+    public async Task EndToEndHttpPipelineAndOpenApiWorkTogether()
     {
         await using var connection = new SqliteConnection("Data Source=:memory:");
         await connection.OpenAsync();
 
-        DbContextOptions<MusicStoreDbContext> options = new DbContextOptionsBuilder<MusicStoreDbContext>()
-            .UseSqlite(connection)
-            .Options;
-
-        await using var db = new MusicStoreDbContext(options);
-        await db.Database.EnsureCreatedAsync();
-        await MusicStoreDbContext.SeedAsync(db);
-
-        var svc = new StoreService(db, new InventoryCache());
-
-        Option<Album> album = await svc.FindAlbumAsync(new AlbumId(1));
-        Assert.True(album.IsSome);
-
-        Result<Order, StoreError> ok = await svc.CheckoutAsync(new CheckoutRequest(
-            new AlbumId(1),
-            2,
-            "miles@jazz.fm",
-            new PromoCode("JAZZ10")));
-        Assert.True(ok.IsOk);
-        Assert.Equal(26.98m, ok.Match(o => o.TotalAmount, _ => 0m));
-
-        Result<Order, StoreError> missing = await svc.CheckoutAsync(
-            new CheckoutRequest(new AlbumId(999), 1, "miles@jazz.fm"));
-        Assert.True(missing.IsErr);
-        string msg = missing.Match(_ => "", e => e.FormatError());
-        Assert.Contains("999", msg, StringComparison.Ordinal);
-
-        Result<Order, StoreError> outOfStock = await svc.CheckoutAsync(
-            new CheckoutRequest(new AlbumId(1), 50, "miles@jazz.fm"));
-        Assert.True(outOfStock.IsErr);
-        Assert.Contains("left in stock", outOfStock.Match(_ => "", e => e.FormatError()), StringComparison.Ordinal);
+        WebApplicationBuilder builder = WebApplication.CreateBuilder();
+        builder.WebHost.UseTestServer();
+        builder.Services.AddDbContext<MusicStoreDbContext>(opt => opt.UseSqlite(connection));
+        builder.Services.AddSingleton<InventoryCache>();
+        builder.Services.AddScoped<StoreService>();
+        builder.Services.AddOpenApi(options => options.AddFerrousOpenApi());
+
+        await using WebApplication app = builder.Build();
+        using (IServiceScope scope = app.Services.CreateScope())
+        {
+            MusicStoreDbContext db = scope.ServiceProvider.GetRequiredService<MusicStoreDbContext>();
+            await db.Database.EnsureCreatedAsync();
+            await MusicStoreDbContext.SeedAsync(db);
+        }
+
+        app.MapOpenApi();
+        var api = app.MapGroup("/api").WithFerrousResults();
+        api.MapGet("/albums/{id}", (AlbumId id, StoreService svc, CancellationToken ct) => svc.FindAlbumAsync(id, ct))
+            .Produces<Album>(StatusCodes.Status200OK);
+        api.MapGet("/catalog/summary", (StoreService svc, CancellationToken ct) => svc.GetCatalogSummaryAsync(ct));
+        api.MapPost("/orders", async (CheckoutRequest req, StoreService svc, CancellationToken ct) =>
+            (await svc.CheckoutAsync(req, ct)).ToProblemResult(
+                statusCodeSelector: err => err.Match(
+                    onAlbumNotFound: _ => StatusCodes.Status404NotFound,
+                    onOutOfStock: (_, _, _) => StatusCodes.Status409Conflict,
+                    onInvalidPromoCode: _ => StatusCodes.Status422UnprocessableEntity,
+                    onPaymentDeclined: _ => StatusCodes.Status402PaymentRequired,
+                    onValidationFailed: _ => StatusCodes.Status400BadRequest),
+                titleSelector: err => err.FormatError()));
+
+        await app.StartAsync();
+        using HttpClient client = app.GetTestClient();
+
+        using HttpResponseMessage okAlbum = await client.GetAsync("/api/albums/1");
+        Assert.Equal(HttpStatusCode.OK, okAlbum.StatusCode);
+
+        using HttpResponseMessage missingAlbum = await client.GetAsync("/api/albums/999");
+        Assert.Equal(HttpStatusCode.NotFound, missingAlbum.StatusCode);
+
+        using HttpResponseMessage summaryResp = await client.GetAsync("/api/catalog/summary");
+        Assert.Equal(HttpStatusCode.OK, summaryResp.StatusCode);
+        string summaryJson = await summaryResp.Content.ReadAsStringAsync();
+        Assert.Contains("\"albumCount\":3", summaryJson, StringComparison.OrdinalIgnoreCase);
+
+        using HttpResponseMessage orderOk = await client.PostAsJsonAsync(
+            "/api/orders",
+            new CheckoutRequest(new AlbumId(1), 2, "miles@jazz.fm", new PromoCode("JAZZ10")));
+        Assert.Equal(HttpStatusCode.OK, orderOk.StatusCode);
+
+        using HttpResponseMessage orderConflict = await client.PostAsJsonAsync(
+            "/api/orders",
+            new CheckoutRequest(new AlbumId(1), 99, "miles@jazz.fm"));
+        Assert.Equal(HttpStatusCode.Conflict, orderConflict.StatusCode);
+
+        using HttpResponseMessage openApi = await client.GetAsync("/openapi/v1.json");
+        Assert.Equal(HttpStatusCode.OK, openApi.StatusCode);
+        string openApiJson = await openApi.Content.ReadAsStringAsync();
+        Assert.Contains("\"minLength\": 1", openApiJson, StringComparison.Ordinal);
+
+        await app.StopAsync();
+    }
+
+    [Fact]
+    public void CheckoutProtocolPricingHoldsUnderPropertyTesting()
+    {
+        CustomerEmail email = CustomerEmail.TryCreate("buyer@music.fm", out CustomerEmail parsed, out _)
+            ? parsed
+            : throw new InvalidOperationException();
+
+        PropAssert.ForAll(
+            Gen.Decimal(1m, 200m),
+            Gen.NonZeroInt(1, 20),
+            Gen.Decimal(0m, 0.5m),
+            (unitPrice, qty, discount) =>
+            {
+                var draft = new DraftCart(new AlbumId(1), qty, email, unitPrice);
+                ReservedOrder reserved = draft.ApplyPromo(discount).ReserveInventory(new OrderId(1));
+                PaidOrder paid = reserved.CapturePayment("RCPT-PROP");
+                return paid.TotalAmount >= 0m && paid.TotalAmount <= Math.Round(unitPrice * qty.Value, 2) + 0.01m;
+            },
+            iterations: 200,
+            seed: 42);
+    }
+
+    [Fact]
+    public async Task InventoryCacheNeverGoesNegativeUnderAsyncPropertyTesting()
+    {
+        await PropAssert.ForAllAsync(
+            Gen.Int(1, 50),
+            Gen.Int(1, 60),
+            async (initialStock, requested) =>
+            {
+                await Task.Yield();
+                var cache = new InventoryCache();
+                var id = new AlbumId(7);
+                cache.SetStock(id, initialStock);
+
+                bool reserved = cache.TryReserve(id, requested);
+                int remaining = cache.GetStock(id).UnwrapOr(-1);
+
+                Assert.Equal(requested <= initialStock, reserved);
+                Assert.True(remaining >= 0);
+            },
+            iterations: 100,
+            seed: 99);
+    }
+
+    [Fact]
+    public void InvalidTypestateTransitionsFailToCompile()
+    {
+        // Proves at compile time (via Ferrous.Testing CompileAssert) that:
+        // 1. Constructing a non-initial typestate directly fails with FE0300.
+        // 2. Using a consumed typestate fails with FE0200.
+        // 3. Leaking a non-terminal typestate without transitioning fails with FE0303.
+        const string badCode = """
+            using Ferrous;
+
+            [Typestate(IsInitial = true)]
+            public sealed class Draft
+            {
+                [ConsumesSelf]
+                public Reserved Reserve() => new Reserved();
+            }
+
+            [Typestate]
+            public sealed class Reserved
+            {
+                [ConsumesSelf]
+                public Paid Pay() => new Paid();
+            }
+
+            [Typestate(IsTerminal = true)]
+            public sealed class Paid;
+
+            public static class Broken
+            {
+                public static void Bad()
+                {
+                    _ = new Paid();
+                    var d = new Draft();
+                    Reserved r = d.Reserve();
+                    _ = d.Reserve();
+                }
+            }
+            """;
+
+        CompileAssert.Fails(badCode, "FE0300", "FE0200", "FE0303");
     }
 }

Summary: Every Vanilla Bug Eliminated at Compile Time

Vanilla C# Risk (Chapter 1) Ferrous Replacement Compile-Time Guarantee
Swapped int IDs [Newtype(typeof(int))] (AlbumId, OrderId) CS1503 type mismatch + zero-boilerplate EF Core & OpenAPI
Empty titles / zero quantities / invalid emails NonEmptyString, NonZero<int>, validated CustomerEmail FE0405 ([NoDefault]) + smart constructors
Hidden exceptions & silent nulls Result<Order, StoreError>, Option<Album>, [DiscriminatedUnion] Exhaustive Match + FE0001 ([MustUse])
Double-charge / skipped reservation / leaked state Linear [Typestate] + [ConsumesSelf] FE0200 + FE0300–FE0303 + Mermaid docs
Unlocked shared state / detached tasks Mutex<T>, TaskScope, ScopeGuard.Defer FE0501–FE0503 + FE0408 + FE0419
Chapter 7 · Beyond the Code

Tooling & Ecosystem Utilities

dotnet fe CLI

Ferrous isn't just runtime types and analyzers—it ships with a Cargo-inspired CLI tool (Ferrous.Tool), Roslyn IDE refactorings (Ferrous.CodeFixes), and a project template (Ferrous.Templates) designed for day-to-day workflows on real repositories like FerrousMusicStore.

The dotnet fe CLI (Ferrous.Tool)

Shell — Install once, run anywhere
dotnet tool install -g Ferrous.Tool

# 1. Generate searchable static HTML API docs (powers /music-store/api/)
dotnet fe doc ./src --output ./docs-site --title "Ferrous Music Store API" --logo ./assets/icon.png --watch

# 2. Extract [Typestate] state machines as Mermaid diagrams (or sync into Markdown)
dotnet fe graph ./src/MusicStore.Domain/CheckoutProtocol.cs --format mermaid

# 3. Inspect generated [DiscriminatedUnion] and [Newtype] C# (like cargo expand)
dotnet fe expand ./src/MusicStore.Domain/StoreError.cs

# 4. Audit build hygiene, pinned packages, SPDX licenses, lockfiles, NativeAOT & CVEs
dotnet fe audit . --packages --allow-licenses MIT --lockfile --semver --aot --cve

# 5. Scan legacy C# for migration opportunities & apply safe mechanical upgrades
dotnet fe migrate ./src --report
dotnet fe migrate ./src --apply

# 6. Run unit tests + executable XML/Markdown doc-tests together
dotnet fe test

IDE Quick-Fixes & On-Demand Migration Refactorings

Installing Ferrous automatically loads Ferrous.CodeFixes in Visual Studio, VS Code (C# Dev Kit), and JetBrains Rider—giving you 15 diagnostic quick-fixes (FE0001–FE0501) plus 5 on-demand Ctrl+. migration refactorings:

  • Convert throwing method (sync or async Task<T>) → Result<T, string>
  • Convert nullable method (T?, async Task<T?>, or expression-bodied) → Option<T>
  • Wrap primitive parameter → [Newtype(typeof(T))] struct
  • Convert abstract record hierarchy → zero-boxing [DiscriminatedUnion]
  • Convert lock (_gate) + field → data-owning Mutex<T>

Greenfield Scaffolding & Zero-Allocation Guards

Shell — Start a new Ferrous project in one command
dotnet new install Ferrous.Templates
dotnet new ferrous -n MyService   # Pre-wired with <FerrousPedantic>true</FerrousPedantic>, CPM & NativeAOT
Hot-Path Allocation Verification

Need to prove a parser, serializer, or domain rule allocates zero bytes on the managed heap? Wrap it in AllocAssert.Zero(() => ...) from Ferrous.Testing—no benchmark harness required, and any accidental boxing or closure allocation fails your unit test immediately.