Skip to content

Onion architecture, the practices

Onion architecture, the practices

TheYard is a used-vehicle auction platform built in the open: a .NET 11 API, a React front end, and two databases underneath it. Its server is built as an onion, and the record of that decision, with every ring, every rule the build runs and what each one stops, is ADR: Onion and SOLID, how this codebase holds them. This page is the practical half. Each section is one practice you can copy, shown with a drawing or a whole file read from the running build, and each section has an address of its own so a link can land on it.

In plain words

The server is built in rings. The auction's rules sit in the middle, the code that carries out what a visitor asks for wraps them, and the database code and the web endpoints sit on the outside. Code may use the rings inside it and never the ones outside it. This page follows one bid through those rings, shows how the inner ring can save a bid without knowing which database it is talking to, why the rules never read the clock, how 19 tests keep the shape from slipping, and how a small codebase gets the same shape from folders instead of projects.

What that is worth: a developer can copy each practice into their own codebase this week, and the organization gets business rules that are tested in milliseconds with no database, plus a structure the build defends on every push instead of one that depends on a reviewer noticing.

The words this page uses

  • Ring: one layer of the code. Here each inner ring is its own .NET project; in a smaller codebase a ring can be a folder.
  • Dependency: code in one place using a type from another, through a project reference, a using line, or a call inside a method body.
  • Domain: the rules of the business, here the auction's: who may bid, how much, and when.
  • Use case: one thing a visitor does, such as placing a bid, written as a method that runs the rules and the stores in the right order.
  • Port: an interface the inner code declares for something it needs from outside, such as a place to keep bids.
  • Adapter: a class in an outer ring that implements a port against one real thing, such as SQL Server or Cosmos DB.
  • Host: the web application itself, the endpoints that read a request and write the answer.
  • Composition root: the one place, at startup, where the real classes are created and handed to the code that needs them.
  • BCL: the .NET base class library, the System namespaces every .NET program has.

The rule in one sentence

Dependencies point inward: code may use the rings inside it and never the ones outside it.

TheYard's rings: Data at the centre, then Domain, then Application, with the host and the adapters outside, every dependency pointing inward

A preview. Open the rings diagram in a new page to zoom in and follow it.

Innermost first: Data (the dataset's shapes, with no behaviour), Domain (the rules), Application (the use cases and the ports), and outside them the adapters and the host. What lives in each ring is listed in the record, under The rings, and is not repeated here.

Jeffrey Palermo, who named the pattern in 2008, put the same rule this way: "All code can depend on layers more central, but code cannot depend on layers further out from the core." Everything else on this page is a way of keeping that sentence true once the code is large and the week is busy.

A request walks the rings

The rule is easiest to see by following one request. A signed-in buyer bids on a vehicle with POST /api/vehicles/{id}/bids, and the code meets the rings in this order:

One bid through TheYard's rings: the endpoint asks Application, Application asks Domain, Domain decides, Application saves through the IBidStore port, an adapter writes the store, and the endpoint answers

A preview. Open the bid's walk in a new page to zoom in and follow it.

  1. The host reads. The endpoint checks that the session belongs to this store (401 if not) and that the vehicle exists (404 if not), reads the server's clock once, and asks PlaceBidHandler, the one handler that request has (ADR-115).
  2. Application composes. PlaceBidHandler reads the vehicle as it stands through StandingReader and hands the bid to BidBook, which keeps everybody's bids. It lets one bid through at a time and folds everybody's bids into the vehicle, so the rules see the price as it stands.
  3. Application asks Domain. BidBook calls BidRules.ResolveBid with the vehicle, the amount, the clock and whether anybody has already bought it.
  4. Domain decides. The answer is a BidOutcome: refused because the vehicle is sold, the auction is not live or the bid is under the minimum; won at the buy-now price; or accepted. It is a pure function, so the same inputs give the same answer every time.
  5. Application saves through the port. On yes, BidBook calls IBidStore.TrySaveAsync, which writes only if the standing still has the version it read (a compare-and-set), and only then records the bid in memory, so a failed or overtaken write means the bid did not happen anywhere.
  6. An adapter writes. Whichever adapter the composition root wired in at startup, for SQL or for Cosmos DB, writes the row or the document.
  7. The host answers. A refusal becomes a 400 with the reason; a bid that stands becomes a 200 with the bid and the vehicle as it now stands.

The practice: an endpoint reads the request, asks one use case, and writes the answer. It does not decide anything and does not put services together itself. Two of the onion's architecture tests hold that (Endpoints_never_reach_a_store_or_the_service_container and Endpoints_reach_the_auction_only_through_the_Application_ring).

The code in the order the bid meets it: three files whole, and the one method between them. The endpoint, api/TheYard.Api/Features/Bids/BidEndpoints.cs:

using System.ComponentModel;
using Microsoft.AspNetCore.Http.HttpResults;
using TheYard.Application.Features.Bids;

namespace TheYard.Api.Features.Bids;

/// <summary>
/// Bidding and buying now, the caller's standing and history, one round of the
/// simulated room, and one person's start-over. Every write needs a signed-in
/// bidder; the domain's BidRules decide, on the server's clock.
/// </summary>
public static class BidEndpoints
{
    /// <summary>Maps the bidding routes under /api/vehicles/{id}, /api/bids and /api/market.</summary>
    public static IEndpointRouteBuilder MapBidEndpoints(this IEndpointRouteBuilder app)
    {
        #region bid-endpoints
        // Bidding. Every write needs a signed-in bidder, and the domain's BidRules decide on the
        // server's clock. Nothing here is only the caller's to change: a bid moves the price
        // everybody sees, and it is kept in the store.
        app.MapPost("/api/vehicles/{id}/bids", PlaceBid)
            .RequireAuthorization()
            .WithName("PlaceBid")
            .WithTags("Bids")
            .WithSummary("Bid on a vehicle")
            .WithDescription("Whole dollars. The rules run on the server: a sold vehicle takes no bid, an amount at or above "
                + "the buy-now price wins outright at that price, and anything else has to clear the minimum next bid "
                + "measured against the room's standing price. A session bids on the store it was opened on.")
            .ProducesProblem(StatusCodes.Status400BadRequest)
            .ProducesProblem(StatusCodes.Status401Unauthorized)
            .ProducesProblem(StatusCodes.Status404NotFound);

        // No body: a purchase names the vehicle in its address and nothing else.
        app.MapPost("/api/vehicles/{id}/buy-now", BuyNow)
            .RequireAuthorization()
            .WithName("BuyNow")
            .WithTags("Bids")
            .WithSummary("Buy a vehicle outright")
            .WithDescription("No body: the vehicle is named in the address. Refused when the vehicle has no buy-now price, "
                + "is already sold, or its auction is not live.")
            .ProducesProblem(StatusCodes.Status400BadRequest)
            .ProducesProblem(StatusCodes.Status401Unauthorized)
            .ProducesProblem(StatusCodes.Status404NotFound);

        #region market-endpoints
        // The buyer's bids, each one answering the question the badge asks: am I still
        // winning this? The server owns that answer because it owns both sides of it.
        // Signed out, this is an empty map rather than a 401: the page asks for it on
        // every load, and "you have no bids" is the true answer for somebody who has
        // not signed in. The endpoints that change something are the ones that refuse.
        app.MapGet("/api/bids", MyBids)
            .WithName("GetMyBids")
            .WithTags("Bids")
            .WithSummary("The caller's standing on every vehicle they have bid on")
            .WithDescription("Keyed by vehicle id. Signed out, this is an empty map rather than a 401: the page asks for it "
                + "on every load, and no bids is the true answer for a visitor with no session.");

        #region history
        // The account page's list, newest first, with the vehicle each bid is on. The
        // only query the bids table serves that is not "load everything at startup";
        // the primary key leads with the user column, so it needs no index of its own.
        app.MapGet("/api/bids/history", History)
            .RequireAuthorization()
            .WithName("GetBidHistory")
            .WithTags("Bids")
            .WithSummary("The caller's bids, newest first, with the vehicle each is on")
            .ProducesProblem(StatusCodes.Status401Unauthorized);
        #endregion history

        // One round of bidding by the room, driven by the page rather than a timer. The room
        // bids on the server's clock, the same one every visitor is served, so the auctions it
        // can see are the ones the visitor sees.
        app.MapPost("/api/market/tick", Tick)
            .RequireAuthorization()
            .WithName("TickRoom")
            .WithTags("Bids")
            .WithSummary("One round of bidding by the room")
            .WithDescription("The simulated room bids against the caller's auctions and a page of live ones, on the server's "
                + "clock. Driven by the page rather than a timer, and only by a signed-in visitor, because moving the "
                + "room moves everybody's prices.")
            .ProducesProblem(StatusCodes.Status401Unauthorized);
        #endregion market-endpoints

        app.MapDelete("/api/bids", ResetMine)
            .RequireAuthorization()
            .WithName("ResetMyBids")
            .WithTags("Bids")
            .WithSummary("Forget the caller's bids, and the room's answers to them")
            .WithDescription("One person's start-over. Nobody else's bids move.")
            .ProducesProblem(StatusCodes.Status401Unauthorized);
        #endregion bid-endpoints

        return app;
    }

    // #region bid-handling
    // Each route binds its wire and asks one handler (ADR: The onion cut into vertical slices,
    // rule 7); the handler answers in the Application ring's words and this file turns them into
    // the status codes the browser relies on: 401, 404, then 400.
    private static async Task<Results<Ok<BidResult>, ProblemHttpResult>> PlaceBid(PlaceBidHandler handler, CurrentBackend current, HttpContext http, string id, BidRequest request, CancellationToken cancellation) =>
        Answer(await handler.HandleAsync(new PlaceBidCommand(id, http.UserId(), http.SessionIsOn(current), request.Amount), cancellation), current, id);

    private static async Task<Results<Ok<BidResult>, ProblemHttpResult>> BuyNow(PlaceBidHandler handler, CurrentBackend current, HttpContext http, string id, CancellationToken cancellation) =>
        Answer(await handler.HandleAsync(new PlaceBidCommand(id, http.UserId(), http.SessionIsOn(current), null), cancellation), current, id);

    private static async Task<Ok<IReadOnlyDictionary<string, BidView>>> MyBids(ReadMyBidsHandler handler, HttpContext http, CancellationToken cancellation) =>
        TypedResults.Ok(await handler.HandleAsync(new ReadMyBidsQuery(http.UserIdOrNull()), cancellation));

    private static async Task<Ok<BidHistory>> History(ReadBidHistoryHandler handler, HttpContext http, CancellationToken cancellation) =>
        TypedResults.Ok(await handler.HandleAsync(new ReadBidHistoryQuery(http.UserId()), cancellation));

    // The room's round, and the caller's own badges riding back with it, so a page does not need
    // a second request to find out it has been outbid.
    private static async Task<Ok<TickResult>> Tick(RoomRoundHandler handler, HttpContext http, CancellationToken cancellation)
    {
        var round = await handler.HandleAsync(new RoomRoundCommand(http.UserIdOrNull()), cancellation);
        return TypedResults.Ok(new TickResult(round.Raised, round.Bids));
    }

    private static async Task<Results<NoContent, ProblemHttpResult>> ResetMine(ResetBidsHandler handler, HttpContext http, CancellationToken cancellation) =>
        await handler.HandleAsync(new ResetBidsCommand(http.UserIdOrNull()), cancellation)
            ? TypedResults.NoContent()
            : TypedResults.Problem(detail: "Sign in to reset your bids.", statusCode: 401, title: "Not signed in");

    private static Results<Ok<BidResult>, ProblemHttpResult> Answer(BidAnswer answer, CurrentBackend current, string id) => answer.Kind switch
    {
        BidAnswerKind.SessionElsewhere => TypedResults.Problem(
            detail: $"This session was opened on another store. Sign in on {current.Name} to bid here.",
            statusCode: 401, title: "The bid was rejected"),
        BidAnswerKind.NoSuchVehicle => TypedResults.Problem(detail: "No vehicle has that id.", statusCode: 404, title: "No such vehicle"),
        BidAnswerKind.Rejected => TypedResults.Problem(detail: answer.Reason, statusCode: 400, title: "The bid was rejected"),
        _ => TypedResults.Ok(new BidResult(
            answer.Outcome!.Value.Kind.ToString().ToLowerInvariant(),
            answer.Outcome.Value.Amount,
            answer.Standing,
            VehicleWire.ToWire(answer.Vehicle!, answer.Clock!.Value))),
    };
    // #endregion bid-handling
}

/// <summary>
/// Bid submission: the amount, and nothing else. The schedule is the server's, so a request
/// never names a time.
/// </summary>
/// <param name="Amount">Whole dollars, at or above the vehicle's min_next_bid.</param>
public sealed record BidRequest([property: Description("Whole dollars, at or above the vehicle's min_next_bid.")] int Amount);

Live from api/TheYard.Api/Features/Bids/BidEndpoints.cs, region *, read from this build at 99df7a8.

The use case the bid route asks, one command and its handler, api/TheYard.Application/Features/Bids/PlaceBidHandler.cs:

/// <summary>
/// Places a bid, or buys now, for one signed-in bidder (ADR: The onion cut into vertical slices,
/// rule 7). The order of the three questions is the contract the browser relies on: the session's
/// store first, then the vehicle, then the rules. The vehicle is read as it stands and the bid is
/// written through the bids' writing side, each handed in by the slice's Module; the clock is the server's.
/// </summary>
/// <param name="standings">The request store's vehicles as they stand, and the caller's badges: the reading side only.</param>
/// <param name="bids">Everybody's bids, writing side: the bid and the buy-now purchase.</param>
/// <param name="clock">The server's clock, read once per request.</param>
public sealed class PlaceBidHandler(StandingReader standings, IBidWriter bids, Func<AuctionClock> clock) : ICommandHandler<PlaceBidCommand, BidAnswer>
{
    /// <summary>Answers one bid or Buy Now.</summary>
    /// <param name="request">Who, on which vehicle, and the amount or none for Buy Now.</param>
    /// <param name="cancellation">The request's cancellation.</param>
    public async Task<BidAnswer> HandleAsync(PlaceBidCommand request, CancellationToken cancellation)
    {
        // A session bids where its account is. The token names the store that opened it, so
        // this check costs no lookup; a bid on the other store would be a row under an id that
        // store has no account for.
        if (!request.SessionOnThisStore)
        {
            return BidAnswer.Refused(BidAnswerKind.SessionElsewhere, null);
        }
        var now = clock();
        cancellation.ThrowIfCancellationRequested();
        if (await standings.FindAsync(request.VehicleId, cancellation) is not { } vehicle)
        {
            return BidAnswer.Refused(BidAnswerKind.NoSuchVehicle, null);
        }
        // The bid is measured against the vehicle as it stands, the room's price included: measuring
        // against the dataset's figure alone would let a buyer retake the lead below the going rate.
        var outcome = request.Amount is { } amount
            ? await bids.PlaceBidAsync(vehicle.Vehicle, amount, now, request.UserId, cancellation)
            : await bids.BuyNowAsync(vehicle.Vehicle, now, request.UserId, cancellation);
        if (outcome.Kind == BidOutcomeKind.Rejected)
        {
            return BidAnswer.Refused(BidAnswerKind.Rejected, outcome.Reason);
        }
        // The room's answer rides back with the bid, so the badge is right the moment the
        // response lands. TryGetValue, because a reset from the same account in a second tab can
        // land between the bid and this read. The vehicle is read again after the bid, so the
        // price and the sold flag are the ones it left.
        return new BidAnswer(
            BidAnswerKind.Placed,
            outcome,
            null,
            standings.BidsOf(request.UserId).TryGetValue(request.VehicleId, out var standing) ? standing : null,
            // Read with no token: the bid has been taken and this is the answer describing
            // what it left, so a caller who has gone must not turn a placed bid into an error.
            await standings.FindAsync(request.VehicleId, CancellationToken.None) ?? vehicle,
            now);
    }
}

Live from api/TheYard.Application/Features/Bids/PlaceBidHandler.cs, region place-bid, read from this build at 99df7a8.

The method that asks the rules and then calls the port, from the part of BidBook that moves a price, api/TheYard.Application/Shared/Auction/BidBook.Bidding.cs:

/// <summary>
/// Places one bid for one buyer. The rules run against the store's standing
/// for the vehicle, read under the gate, and the bid is kept only if the
/// store still holds that same standing when it is written. If the other
/// site moved it in between, the standing is read again and the rules run
/// again, so a bid that no longer clears the minimum is refused with the
/// sentence it would have got a moment later.
///
/// <para>The caller's cancellation is honoured up to the gate and not past it. Waiting
/// a turn is the one part of a bid a caller who has gone can be let out of for nothing;
/// once the turn is theirs the store is written and memory follows, and a sequence
/// abandoned between those two would leave the store holding a standing this process
/// does not know about. So the body runs under no token, deliberately, which is the
/// promise the ports record made and this rung kept (ADR: The ports learn to wait, the
/// addendum on the token).</para>
/// </summary>
public async Task<BidOutcome> PlaceBidAsync(Vehicle vehicle, int amount, AuctionClock clock, string userId, CancellationToken cancellation)
{
    await LoadAsync(cancellation);
    await _gate.WaitAsync(cancellation);
    try
    {
        for (int attempt = 1; attempt <= Attempts; attempt++)
        {
            var (held, version) = await CurrentAsync(vehicle.Id, CancellationToken.None);
            var merged = held is null ? vehicle : vehicle.RaisedTo(held.Amount, held.BidCount);
            // Sold is read from the same standing the write will compare
            // against, so two buyers, on one site or two, cannot both find
            // it false.
            var outcome = BidRules.ResolveBid(merged, amount, clock, held?.SoldBuyNow ?? false);
            if (outcome.Kind == BidOutcomeKind.Rejected)
            {
                return outcome;
            }

            var state = new BidState(
                outcome.Amount,
                merged.BidCount + 1,
                WonBuyNow: outcome.Kind == BidOutcomeKind.Won,
                AtMs: clock.NowMs);
            var next = StandingFold.Next(held, userId, state);
            // The store first, then memory. A store that throws leaves the
            // dictionaries as they were, so a failed write means the bid did
            // not happen anywhere, which is the answer the caller already has.
            if (await _store.TrySaveAsync(userId, vehicle.Id, state, next, version, CancellationToken.None))
            {
                _ledger.Record(userId, vehicle.Id, state, next);
                return outcome;
            }
        }
        return BidOutcome.Rejected(MovedReason);
    }
    finally
    {
        _gate.Release();
    }
}

Live from api/TheYard.Application/Shared/Auction/BidBook.Bidding.cs, region place, read from this build at 99df7a8.

The rules, api/TheYard.Domain/Shared/Auction/BidRules.cs. Nothing in it is async, nothing in it reads a file, and the clock arrives as an argument:

using System.Globalization;
using TheYard.Data;

namespace TheYard.Domain.Shared.Auction;

public enum BidOutcomeKind
{
    Rejected,
    Accepted,
    Won,
}

/// <summary>The result of a bid or buy-now attempt.</summary>
/// <param name="Kind">Whether the attempt was rejected, accepted or won the vehicle.</param>
/// <param name="Amount">The amount that stands, in whole dollars; zero when rejected.</param>
/// <param name="Reason">Why the attempt was rejected, or null when it was not.</param>
public readonly record struct BidOutcome(BidOutcomeKind Kind, int Amount, string? Reason)
{
    public static BidOutcome Rejected(string reason) => new(BidOutcomeKind.Rejected, 0, reason);
    public static BidOutcome Accepted(int amount) => new(BidOutcomeKind.Accepted, amount, null);
    public static BidOutcome Won(int amount) => new(BidOutcomeKind.Won, amount, null);
}

/// <summary>
/// The auction bidding rules, server-side and authoritative:
///  - tiered increments: under $5k +$100, $5k–$19,999 +$250, $20k and up +$500;
///  - the minimum next bid is the high bid plus its tier's increment, or the
///    opening ask before any bids exist;
///  - bids are valid only while the auction is live;
///  - a bid at or above buy_now_price wins outright at the buy-now price,
///    even when it fails the minimum-increment check;
///  - a vehicle somebody has bought is sold, to everybody: no bid and no second
///    purchase, whatever the clock says.
/// </summary>
public static class BidRules
{
    /// <summary>
    /// The most a bid may be, in whole dollars. The dataset's dearest vehicle is under a
    /// hundredth of this, so no real bid meets it, and every sum the rules make from a price
    /// under it fits in an int with room to spare.
    /// </summary>
    public const int MaxBid = 10_000_000;

    public static int Increment(int currentBid) =>
        currentBid < 5_000 ? 100 : currentBid < 20_000 ? 250 : 500;

    public static int MinNextBid(Vehicle vehicle) =>
        vehicle.CurrentBid is { } bid ? bid + Increment(bid) : vehicle.StartingBid;

    // #region sold
    /// <summary>
    /// The sentence a sold vehicle answers every bid and every purchase with.
    /// One string, because the store's fact and the page's words should not be
    /// able to drift apart.
    /// </summary>
    public const string SoldReason = "This vehicle has been sold.";

    /// <summary>
    /// <paramref name="sold"/> is whether anybody has bought this vehicle
    /// outright, which the rules cannot know from the vehicle alone: the
    /// dataset has no such field and the schedule has no such state. The caller
    /// that holds everybody's standing says so, and it is asked before the
    /// clock and before the buy-now shortcut, so a second account bidding the
    /// buy-now price on a vehicle already bought is refused, not told it has
    /// won (ADR: Accounts and per-user bids, the addendum on the second buyer).
    /// </summary>
    public static BidOutcome ResolveBid(Vehicle vehicle, int amount, AuctionClock clock, bool sold)
    {
        if (sold)
        {
            return BidOutcome.Rejected(SoldReason);
        }
        // Before the buy-now shortcut, so an absurd number is refused rather than read as a
        // purchase, and before any sum, so no price this method adds to can overflow.
        if (amount > MaxBid)
        {
            return BidOutcome.Rejected($"A bid can be at most ${MaxBid.ToString("N0", CultureInfo.InvariantCulture)}.");
        }
        var status = AuctionSchedule.StatusFor(vehicle.Id, clock);
        if (status == AuctionStatus.Live && vehicle.BuyNowPrice is { } buyNow && amount >= buyNow)
        {
            // Instant win, charged the buy-now price rather than the overbid.
            return BidOutcome.Won(buyNow);
        }
        if (status == AuctionStatus.Upcoming)
        {
            return BidOutcome.Rejected("This auction has not started yet.");
        }
        if (status == AuctionStatus.Ended)
        {
            return BidOutcome.Rejected("This auction has ended.");
        }

        int min = MinNextBid(vehicle);
        return amount < min
            ? BidOutcome.Rejected($"Bid must be at least ${min.ToString("N0", CultureInfo.InvariantCulture)}.")
            : BidOutcome.Accepted(amount);
    }

    public static BidOutcome ResolveBuyNow(Vehicle vehicle, AuctionClock clock, bool sold)
    {
        if (sold)
        {
            return BidOutcome.Rejected(SoldReason);
        }
        if (vehicle.BuyNowPrice is not { } buyNow)
        {
            return BidOutcome.Rejected("This vehicle has no Buy Now price.");
        }
        return AuctionSchedule.StatusFor(vehicle.Id, clock) == AuctionStatus.Live
            ? BidOutcome.Won(buyNow)
            : BidOutcome.Rejected("Buy Now is only available while the auction is live.");
    }
    // #endregion sold
}

Live from api/TheYard.Domain/Shared/Auction/BidRules.cs, region *, read from this build at 99df7a8.

The inner ring owns the interface

The rule in one sentence has an obvious problem. Application has to save a bid, and the database is outside it. The answer is dependency inversion, the D in SOLID: the inner ring declares the interface it needs, in its own words, and the outer ring implements it. At compile time every arrow points inward, at the interface. Only the call at runtime travels outward, and it travels through a type the inner ring owns.

The inner ring owns the interface: Application declares IBidStore and uses it, EfBidStore and CosmosBidStore implement it from the outer ring, and the composition root decides which one each store gets

A preview. Open the port and its adapters in a new page to zoom in and follow it.

Microsoft's architecture guide for .NET describes the same move: "defining abstractions, or interfaces, in the Application Core, which are then implemented by types defined in the Infrastructure layer." TheYard runs it twice over, because two stores, SQL and Cosmos DB, each adapt the same auction ports in Ports.cs (IVehicleSource, IPhotoManifestSource, IBidStore and IVehicleCatalogue). Since the auction's reads and writes were split, the use cases reach them through a reading and a writing interface each (IStockReader; IBidReader and IBidWriter; IRoomReader and IRoomWriter), and the rules have no idea which store is answering.

The practice: name the port for what the inner ring needs (IBidStore) and keep the technology out of the name (ISqlBidRepository would leak it), and keep every type the port mentions inside the inner ring. Give it an in-memory implementation beside it that keeps the same rules, as MemoryBidStore is here, and the use cases can be tested with no database and no mocking framework.

The ports, whole, api/TheYard.Application/Shared/Auction/Ports.cs:

using TheYard.Data;

namespace TheYard.Application.Shared.Auction;

// #region ports
// The three seams the layers meet at. Application declares what it needs and
// never learns where the data lives; Infrastructure implements these against
// EF Core and SQLite, against Cosmos DB, the tests against in-memory arrays,
// and the 100,000-record scale-up is a decorator over IVehicleSource that
// nothing above it can see.
//
// Every member returns a Task, because the document store has no synchronous
// driver, and a port that held a request thread while a cloud store answered
// would stall a one-vCPU container (ADR: The ports learn to wait). Every member
// also takes a CancellationToken, because a read the visitor walked away from is
// work the site pays for twice, and a path that drops the token cannot be made to
// stop later without changing every caller (the same record, the addendum on the
// token). Taking it is not the same as cancelling: a bid write that has entered
// the gate runs to its end, and the two startup loads take the host's stopping
// token rather than any request's.
/// <summary>Port: where the vehicle dataset comes from.</summary>
public interface IVehicleSource
{
    Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation);
}

/// <summary>Port: where the photo manifest comes from.</summary>
public interface IPhotoManifestSource
{
    Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation);
}

/// <summary>
/// Port: where everybody's bids are kept, and the one place each vehicle's
/// standing is decided. Two sites run one image over the same store, so the
/// standing (price, count, high bidder, sold) is a row or document the store
/// owns, written with a compare-and-set on its version. Memory is a cache of
/// it, and a cache can be stale; the store cannot be argued with
/// (ADR: Three readers with no memory of the project, item 5).
/// A bid belongs to a user (ADR: Accounts and per-user bids), so a buyer's row
/// is keyed by the pair and the standing by the vehicle.
/// </summary>
public interface IBidStore
{
    /// <summary>Every buyer's row, for the replay at startup.</summary>
    Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation);

    /// <summary>Every vehicle's stored standing, for the replay at startup.</summary>
    Task<IReadOnlyList<StoredStanding>> LoadStandingsAsync(CancellationToken cancellation);

    /// <summary>One vehicle's stored standing and its version, or null when the store holds none for it.</summary>
    Task<StoredStanding?> ReadStandingAsync(string vehicleId, CancellationToken cancellation);

    /// <summary>
    /// Every buyer's row on one vehicle. Read when the store holds no standing
    /// for it, which is a vehicle bid on before standings existed or one a
    /// reset cleared, so the standing is worked out from the rows rather than
    /// taken to be the opening ask.
    /// </summary>
    Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation);

    /// <summary>
    /// Writes the buyer's row and the vehicle's new standing, but only if the
    /// standing still carries <paramref name="expectedVersion"/>; null expects
    /// there to be no standing yet. False means another writer moved it first,
    /// and nothing of this bid was kept: the caller reads again and runs the
    /// rules again.
    /// </summary>
    Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation);

    /// <summary>
    /// Forget one person's bids, and the standing of every vehicle they bid on,
    /// so the next read works each one out again from whoever is left. Not
    /// everybody's: this is what the reset button on a page a stranger can also
    /// be looking at is allowed to do (ADR: Reset is one person's start-over).
    /// </summary>
    Task ClearAsync(string userId, CancellationToken cancellation);
}

/// <summary>
/// Port: the catalogue as the store holds it, all hundred thousand vehicles with
/// the slot each id's hash gives it, and the store doing the filtering, the
/// ordering and the paging (ADR: The store does the work). Application plans a
/// listing out of these primitives, the three schedule segments, the room's and
/// the bids' overlay, the page, and the adapters only translate a filter and an
/// order into their own query: EF Core over the Catalogue table, the SDK over the
/// catalogue container. Every read is bounded by the page it asks for; nothing
/// here hands back the whole catalogue.
/// </summary>
public interface IVehicleCatalogue
{
    /// <summary>How many vehicles this catalogue is the first of: the expansion's target count.</summary>
    int Target { get; }

    /// <summary>How the store wants to be filled: a batch at a time, a pause between, and up to how many it fills at warm-up.</summary>
    CatalogueFillPace Pace { get; }

    /// <summary>How many of the first <see cref="Target"/> vehicles the store holds with their slot, read as one count.</summary>
    Task<int> FilledAsync(CancellationToken cancellation);

    /// <summary>Writes one batch of the expansion, each vehicle at its place; a vehicle already there is left as it is or rewritten the same.</summary>
    Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation);

    /// <summary>How many vehicles match, split by the three schedule segments, in one read where the store allows it.</summary>
    Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation);

    /// <summary>One page of the matches in one order, skipped and taken in the store's own query.</summary>
    Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation);

    /// <summary>The vehicles with these ids, by point read where the address names the partition; an id the catalogue lacks is simply absent.</summary>
    Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);

    /// <summary>The distinct values behind the filters, read once at warm-up.</summary>
    Task<InventoryFacets> FacetsAsync(CancellationToken cancellation);
}

// #endregion ports

Live from api/TheYard.Application/Shared/Auction/Ports.cs, region *, read from this build at 99df7a8.

The relational adapters, whole: EF Core over Azure SQL Database or SQLite, api/TheYard.Infrastructure/Shared/Auction/EfSources.cs. EfBidStore is the last class in the file:

// The three ports, answered from the database: the seed catalogue, the photo manifest, and the
// bids. These are the adapters the composition root wires when the relational store opens.
// The rest of the relational plumbing has a file of its own beside this one:
//   VehicleRows.cs     row to domain and back
//   DatabaseState.cs   whether the store is usable, and one sentence about why
//   EfBidStore.Standing.cs   each vehicle's standing, moved with a compare-and-set
//   YardDatabase.cs    bringing the database up once at startup
//   SeedResult.cs      what the first boot found
//   YardSeed.cs        filling an empty catalogue from the JSON files
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using TheYard.Application.Shared.Auction;
using TheYard.Data;

namespace TheYard.Infrastructure.Shared.Auction;

/// <summary>
/// Adapter: the seed catalogue, out of the database. Same port the JSON file
/// reader implements, and the synthetic scale-up still wraps it, so nothing
/// above this layer depends on which storage is underneath.
/// </summary>
public sealed class EfVehicleSource(IDbContextFactory<YardDbContext> factory) : IVehicleSource
{
    // #region ef-sources
    /// <summary>Every seed vehicle, in the order it was seeded, read once without change tracking.</summary>
    /// <param name="cancellation">The caller's; in a running container this is the host's stopping token, because the warm-up is what asks.</param>
    public async Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync(cancellation);
        // Read once, in seed order, tracking nothing: these rows are a
        // catalogue this process will never write back.
        return await db.Vehicles.AsNoTracking().OrderBy(row => row.Seq).Select(row => row.ToVehicle()).ToListAsync(cancellation);
    }
    // #endregion ef-sources
}

/// <summary>Adapter: the photo manifest, out of the database.</summary>
public sealed class EfPhotoManifestSource(IDbContextFactory<YardDbContext> factory) : IPhotoManifestSource
{
    /// <summary>Every photo entry, in manifest order, read once without change tracking.</summary>
    /// <param name="cancellation">The caller's, carried to EF Core.</param>
    public async Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync(cancellation);
        return await db.Photos.AsNoTracking().OrderBy(row => row.Seq)
            .Select(row => new PhotoEntry(row.File, row.Style, row.Title))
            .ToListAsync(cancellation);
    }
}

/// <summary>
/// Adapter: bids and the standing they add up to, which are the only things
/// here that change after startup, because they are the only things a visitor
/// creates. The standing half is in EfBidStore.Standing.cs.
/// </summary>
public sealed partial class EfBidStore(IDbContextFactory<YardDbContext> factory) : IBidStore
{
    // #region bid-store
    /// <summary>Every stored bid, for BidBook to replay into its indexes at startup.</summary>
    /// <param name="cancellation">The caller's; the replay's starter lends it, and in a container that is the host.</param>
    public async Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync(cancellation);
        return await db.Bids.AsNoTracking().Select(row => new StoredBid(
                row.UserId,
                row.VehicleId,
                new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
            .ToListAsync(cancellation);
    }

    /// <summary>
    /// Every buyer's row on one vehicle. There is no index on VehicleId alone,
    /// so this reads the table; it runs only when a vehicle has no standing yet,
    /// once per vehicle, on a table of visitor bids.
    /// </summary>
    /// <param name="vehicleId">The vehicle.</param>
    /// <param name="cancellation">The caller's. A table read is the most expensive thing this adapter does, so it is the one most worth stopping.</param>
    public async Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync(cancellation);
        return await db.Bids.AsNoTracking().Where(row => row.VehicleId == vehicleId).Select(row => new StoredBid(
                row.UserId,
                row.VehicleId,
                new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
            .ToListAsync(cancellation);
    }

    /// <summary>
    /// The buyer's row and the vehicle's standing in one transaction, the
    /// standing first with a compare-and-set on its version. An update that
    /// names a version no longer there changes no row, and an insert where
    /// another writer has just inserted breaks the key; either way the
    /// transaction is rolled back and the answer is false, so BidBook reads
    /// again and runs the rules again. The buyer's row keeps its own token,
    /// which catches one account writing from two sites at once, and that too
    /// answers false rather than writing over what it never saw.
    ///
    /// <para>The token this takes is never handed to the transaction, and that is the whole of
    /// what the ports record promised: a write abandoned between the standing and the buyer's
    /// row would leave the store holding a standing nothing has a row for. The caller above
    /// has already stopped honouring cancellation by the time it gets here, so the parameter
    /// exists to keep one shape across the port and not to be used (ADR: The ports learn to
    /// wait, the addendum on the token).</para>
    /// </summary>
    public async Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync();
        await using var transaction = await db.Database.BeginTransactionAsync();
        if (expectedVersion is not null && !await TryMoveStandingAsync(db, vehicleId, standing, long.Parse(expectedVersion, CultureInfo.InvariantCulture), CancellationToken.None))
        {
            return false;
        }

        if (expectedVersion is null)
        {
            db.Standings.Add(RowOf(vehicleId, standing, version: 1));
        }

        await StageBuyerRowAsync(db, userId, vehicleId, state, cancellation);
        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            return false;
        }
        catch (DbUpdateException) when (expectedVersion is null)
        {
            // An insert that broke a key lost to another writer's insert of the
            // same standing. Anything else that broke is a real failure and
            // travels.
            await transaction.RollbackAsync();
            if (await StandingExistsAsync(vehicleId, CancellationToken.None))
            {
                return false;
            }
            throw;
        }

        await transaction.CommitAsync();
        return true;
    }

    /// <summary>
    /// The buyer's row for this vehicle, added or changed in place on the
    /// context, with the concurrency token moved where the provider does not
    /// move it itself. Nothing is written until the caller saves.
    /// </summary>
    private static async Task StageBuyerRowAsync(YardDbContext db, string userId, string vehicleId, BidState state, CancellationToken cancellation)
    {
        var existing = await db.Bids.FindAsync(userId, vehicleId);
        if (existing is null)
        {
            existing = new BidRow
            {
                UserId = userId,
                VehicleId = vehicleId,
                Amount = state.Amount,
                BidCount = state.BidCount,
                WonBuyNow = state.WonBuyNow,
                AtMs = state.AtMs,
            };
            db.Bids.Add(existing);
        }
        else
        {
            existing.Amount = state.Amount;
            existing.BidCount = state.BidCount;
            existing.WonBuyNow = state.WonBuyNow;
            existing.AtMs = state.AtMs;
        }

        // SQL Server keeps the token itself; SQLite has no rowversion type, so
        // the store is what moves it. Setting it here rather than in a trigger
        // keeps the difference between the two providers in one readable place
        // (ADR: The SQL Server backend).
        if (db.Database.IsSqlite())
        {
            existing.RowVersion = Guid.NewGuid().ToByteArray();
        }
    }

    /// <summary>
    /// Deletes one buyer's rows, every vehicle, and the standing of each of
    /// those vehicles, in one transaction. The standings go so the next bid on
    /// each vehicle works its standing out again from whoever is left.
    ///
    /// <para>Like the bid write, the token is not given to the transaction: the standings and
    /// the rows go together or not at all, and a reset stopped between them would leave
    /// vehicles with no standing and rows still claiming one.</para>
    /// </summary>
    public async Task ClearAsync(string userId, CancellationToken cancellation)
    {
        using var db = await factory.CreateDbContextAsync();
        await using var transaction = await db.Database.BeginTransactionAsync();
        // One person's rows and nobody else's. A delete over the whole table,
        // on a site two strangers can be looking at, would let either of them
        // delete the other's bids (ADR: Reset is one person's start-over).
        var touched = await db.Bids.Where(bid => bid.UserId == userId).Select(bid => bid.VehicleId).ToListAsync();
        await db.Standings.Where(row => touched.Contains(row.VehicleId)).ExecuteDeleteAsync();
        await db.Bids.Where(bid => bid.UserId == userId).ExecuteDeleteAsync();
        await transaction.CommitAsync();
    }
    // #endregion bid-store
}

Live from api/TheYard.Infrastructure/Shared/Auction/EfSources.cs, region *, read from this build at 99df7a8.

The document store adapters, whole: the Cosmos DB SDK, api/TheYard.Infrastructure.Cosmos/Shared/Auction/CosmosSources.cs. CosmosBidStore is the last class in this one too:

using System.Net;
using Microsoft.Azure.Cosmos;
using TheYard.Application.Shared.Auction;
using TheYard.Data;
using TheYard.Infrastructure.Cosmos.Shared.Stores;

namespace TheYard.Infrastructure.Cosmos.Shared.Auction;

/// <summary>
/// Adapter: the seed catalogue, out of the document store. The same port the
/// JSON file reader and the relational adapter implement, and the synthetic
/// scale-up still wraps it, so nothing above this line can tell which store
/// answered (ADR: A second store on Cosmos DB, and what it costs).
/// </summary>
public sealed class CosmosVehicleSource(CosmosStore store) : IVehicleSource
{
    // #region cosmos-sources
    public async Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
    {
        // The whole container, once, as one cross-partition query, and ordered
        // here rather than by the store. ORDER BY needs an index on the sorted
        // path, and an index on seq would be paid for on every write to save a
        // sort of two hundred documents that costs nothing (ADR: The partition
        // key).
        var documents = await store.QueryAsync<VehicleDocument>(
            store.Vehicles, new QueryDefinition("SELECT * FROM c"), partitionKey: null, "cross-partition", cancellation: cancellation);
        return documents.OrderBy(d => d.Seq).Select(d => d.ToVehicle()).ToList();
    }
    // #endregion cosmos-sources
}

/// <summary>Adapter: the photo manifest, out of the document store.</summary>
public sealed class CosmosPhotoManifestSource(CosmosStore store) : IPhotoManifestSource
{
    /// <summary>Every photo entry, read once as one cross-partition query.</summary>
    /// <param name="cancellation">The caller's; the warm-up is what asks, so in a container this is the host's stopping token.</param>
    public async Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation)
    {
        var documents = await store.QueryAsync<PhotoDocument>(
            store.Photos, new QueryDefinition("SELECT * FROM c"), partitionKey: null, "cross-partition", cancellation: cancellation);
        return documents.OrderBy(d => d.Seq).Select(d => d.ToEntry()).ToList();
    }
}

/// <summary>
/// Adapter: bids, in a container partitioned on the buyer, and each vehicle's
/// standing in the same container under a partition of its own. Every operation
/// here names the partition, so every one of them is a point operation or a
/// query inside one partition; the fan-outs are the read at startup and the
/// rows on one vehicle that has no standing yet (ADR: The partition key). The
/// standing half is in CosmosBidStore.Standing.cs.
/// </summary>
public sealed partial class CosmosBidStore(CosmosStore store) : IBidStore
{
    private const string Partition = "pinned to the buyer";

    // #region cosmos-bid-store
    /// <summary>Every buyer's document, and none of the standings that share the container.</summary>
    /// <param name="cancellation">The caller's; the replay's starter lends it, which in a container is the host.</param>
    public async Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation)
    {
        var documents = await store.QueryAsync<BidDocument>(
            store.Bids,
            new QueryDefinition("SELECT * FROM c WHERE c.user_id != @standing").WithParameter("@standing", StandingDocument.Partition),
            partitionKey: null,
            "cross-partition", cancellation: cancellation);
        return documents.Select(d => d.ToStoredBid()).ToList();
    }

    /// <summary>
    /// Every buyer's document on one vehicle: the id is the vehicle, so this is
    /// one id across every buyer's partition. It runs only when the vehicle has
    /// no standing yet.
    /// </summary>
    public async Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation)
    {
        var documents = await store.QueryAsync<BidDocument>(
            store.Bids,
            new QueryDefinition("SELECT * FROM c WHERE c.id = @vehicle AND c.user_id != @standing")
                .WithParameter("@vehicle", vehicleId)
                .WithParameter("@standing", StandingDocument.Partition),
            partitionKey: null,
            "cross-partition", cancellation: cancellation);
        return documents.Select(d => d.ToStoredBid()).ToList();
    }

    /// <summary>
    /// The standing first, with a compare-and-set on its etag, then the buyer's
    /// document. They live in different partitions, so this is two writes and
    /// not a transaction: the standing goes first because it is what the rules
    /// read, and a buyer's document missing after a standing that names them is
    /// repaired from the standing when the cache is next read from the store.
    /// A 412 or 409 on the standing answers false, nothing written.
    ///
    /// <para>The token is taken and not used, which is this rung's one deliberate exception:
    /// the standing goes first and the buyer's document second, and a write stopped between
    /// them leaves the store holding a standing whose holder has no row. The caller above has
    /// already stopped honouring cancellation by the time it reaches here (ADR: The ports
    /// learn to wait, the addendum on the token).</para>
    /// </summary>
    public async Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation)
    {
        if (!await TryWriteStandingAsync(vehicleId, standing, expectedVersion, CancellationToken.None))
        {
            return false;
        }

        await SaveBuyerAsync(userId, vehicleId, state, CancellationToken.None);
        return true;
    }

    /// <summary>
    /// One document per buyer per vehicle, replaced rather than appended. A
    /// point read, then a create if there was nothing or a replace carrying the
    /// etag the read returned. Three tries, then the exception travels: a 412
    /// means another writer moved this buyer's document between the read and
    /// the write, a 409 means another writer created it first, and both take
    /// the one account bidding from two sites at once. The standing has
    /// already been decided by then, so the retry writes this bid over what it
    /// finds.
    /// </summary>
    private async Task SaveBuyerAsync(string userId, string vehicleId, BidState state, CancellationToken cancellation)
    {
        for (int attempt = 1; ; attempt++)
        {
            try
            {
                await WriteAsync(userId, vehicleId, state, cancellation);
                return;
            }
            catch (CosmosException ex) when (attempt < 3
                && ex.StatusCode is HttpStatusCode.PreconditionFailed or HttpStatusCode.Conflict)
            {
                // Deliberately empty. The retry is the handling.
            }
        }
    }

    private async Task WriteAsync(string userId, string vehicleId, BidState state, CancellationToken cancellation)
    {
        var existing = await store.ReadAsync<BidDocument>(store.Bids, vehicleId, userId, Partition, cancellation: cancellation);
        var document = new BidDocument
        {
            Id = vehicleId,
            UserId = userId,
            Amount = state.Amount,
            BidCount = state.BidCount,
            WonBuyNow = state.WonBuyNow,
            AtMs = state.AtMs,
        };
        if (existing is null)
        {
            await store.CreateAsync(store.Bids, document, userId, Partition, cancellation: cancellation);
        }
        else
        {
            await store.ReplaceAsync(store.Bids, document, vehicleId, userId, existing.ETag, Partition, cancellation: cancellation);
        }
    }

    /// <summary>
    /// One person's documents: a query inside that person's partition for the
    /// ids, then the deletes as an atomic batch, then the standing of each of
    /// those vehicles, so the next bid works it out again from whoever is left.
    /// There is no ExecuteDelete on this side; the batch is what a partition
    /// offers instead (ADR: Reset is one person's start-over).
    /// </summary>
    public async Task ClearAsync(string userId, CancellationToken cancellation)
    {
        var ids = await store.QueryAsync<string>(
            store.Bids,
            new QueryDefinition("SELECT VALUE c.id FROM c WHERE c.user_id = @user").WithParameter("@user", userId),
            partitionKey: userId,
            Partition, cancellation: cancellation);
        if (ids.Count > 0)
        {
            // Both with no token, as a pair: a reset that dropped the buyer's documents and
            // then stopped would leave every vehicle they touched standing at a price nobody
            // holds, which is the one thing a start-over must not do.
            await store.DeleteBatchAsync(store.Bids, userId, ids, Partition, cancellation: CancellationToken.None);
            await ForgetStandingsAsync(ids, CancellationToken.None);
        }
    }
    // #endregion cosmos-bid-store
}

Live from api/TheYard.Infrastructure.Cosmos/Shared/Auction/CosmosSources.cs, region *, read from this build at 99df7a8.

And the one place that names an adapter: the composition root, api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, building the relational store's backend and then the document store's. Look for new BidBook(new EfBidStore(contexts)) in the first and new BidBook(new CosmosBidStore(store)) in the second:

// The relational store, on SQL Server or SQLite. A factory rather than a
// scoped context: the two sources and the bid store are singletons that each
// want a context for one operation, and there is no request scope at startup
// when the catalogue is read. The interceptor puts every statement on the Admin
// tab; it is attached here so YardConnection stays a description of where the
// database is.
// How long the first of the five asks waits after a refusal (two seconds unless the
// configuration shortens it, which only a test that proves the fallback does).
var firstWait = StorePrepare.FirstWaitFrom(builder.Configuration);
var sqlStartup = new StartupTimings();
var sqlState = await sqlStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => YardDatabase.PrepareAsync(yard, seedVehicles, seedPhotos, stopping), firstWait), cancellation);
// The backend stands on the files until its store is attached: the same two
// ports answered out of the JSON, the null bid store, no accounts, with the
// synthetic scale-up still decorating the vehicle source (ADR: The relational
// store). Attached at once below when the store came up, or by the second
// chance when it comes up later (ADR: The relational store, the addendum on
// the second chance).
var sqlBackend = new Backend
{
    Key = StoreKeys.Relational,
    Name = yard.Describe(),
    Database = sqlState,
    Startup = sqlStartup,
    Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
    Bids = new BidBook(new MemoryBidStore()),
    Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
    Probe = _ => Task.FromResult(false),
};
// Identity's store over the accounts tables, keyed by the store, given a context from the
// request's scope. The type is the one AddEntityFrameworkStores would have registered for a
// user type with no roles; naming it here is what lets the other backend register a
// different one under the same interface. Registered whether or not the store came up: the
// Accounts slice asks the backend whether it is ready before it asks for the store
// (ADR: The onion cut into vertical slices, rule 4: the backend names no adapter).
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
    new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
        services.GetRequiredService<YardDbContext>(),
        services.GetService<IdentityErrorDescriber>()));
// Everything that stands on the relational store, built from a state that
// says it came up. The loggers are attached the moment the host exists (the
// factory is read at call time, so an attach after startup gets them too).
StoreAttachment SqlAttachment(DatabaseState state)
{
    var sqlOptions = new DbContextOptionsBuilder<YardDbContext>();
    yard.Configure(sqlOptions);
    sqlOptions.AddInterceptors(new SqlLogInterceptor(sqlLog, currentRequest, TimeProvider.System));
    var contexts = new ContextFactory(sqlOptions.Options);
    // The same database without the interceptor, for the activity counters:
    // a batch every five seconds would fill the SQL log with the feature that
    // reads the SQL log, the observer effect the request ring designed out
    // (ADR: Site activity, and the line an address does not cross).
    var quietOptions = new DbContextOptionsBuilder<YardDbContext>();
    yard.Configure(quietOptions);
    var quietContexts = new ContextFactory(quietOptions.Options);
    if (loggers.Factory is not null)
    {
        contexts.Attach(loggers.Factory);
    }
    relationalContexts.Hold(contexts, quietContexts);
    return new StoreAttachment(
        state,
        new RelationalDiagnostics(contexts, yard.Describe(), () => loggers.Factory?.CreateLogger<RelationalDiagnostics>()),
        Catalogues.Sql(contexts, yard, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Relational, servesBothSites)),
        new BidBook(new EfBidStore(contexts)),
        new EfActivityStore(quietContexts),
        token => YardDatabase.HasSeedAsync(contexts, token));
}
if (sqlState.Ready)
{
    sqlBackend.Attach(SqlAttachment(sqlState));
}
backendList.Add(sqlBackend);

Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region sql-backend, read from this build at 99df7a8.

// The document store, when there is an account to talk to. Same question, same
// answer shape, other store: are the containers there with the keys this code
// was written for, and is the seed in them. A refusal falls through to the
// file-backed catalogue exactly as a missing schema does on SQL Server.
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
    cosmos = CosmosConnection.Connect(
        configuredCosmos!,
        builder.Configuration["Cosmos:Database"] ?? "theyard",
        builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
        // "managed-identity" on the deployed container; anything else, which
        // is what a developer's machine and the test runner have, means the
        // signed-in Azure CLI session.
        builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
        AzureIds.ClientId(builder.Configuration),
        storeLog);
    // Every operation is filed under the request that caused it, the first one included.
    cosmos.Recorder.CurrentRequest = currentRequest;
    var cosmosStartup = new StartupTimings();
    var cosmosState = await cosmosStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => cosmos.Starting.PrepareAsync(seedVehicles, seedPhotos, stopping), firstWait), cancellation);
    var store = cosmos;
    // The relational backend's shape: the files until the store is attached (ADR: A
    // second store on Cosmos DB, and what it costs).
    var cosmosBackend = new Backend
    {
        Key = StoreKeys.Document,
        Name = "Azure Cosmos DB",
        Database = cosmosState,
        Startup = cosmosStartup,
        Diagnostics = new DocumentDiagnostics(cosmos),
        Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
        Bids = new BidBook(new MemoryBidStore()),
        Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
        Probe = _ => Task.FromResult(false),
    };
    // One document per account and one per address, and none of Identity's seven tables
    // (ADR: Accounts on a document store), keyed by the store the way the relational one is.
    builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
    StoreAttachment CosmosAttachment(DatabaseState state) => new(
        state,
        new DocumentDiagnostics(store),
        // The same three ports, answered out of the document store.
        Catalogues.Cosmos(store, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Document, servesBothSites)),
        new BidBook(new CosmosBidStore(store)),
        new CosmosActivityStore(store),
        store.Starting.ProbeAsync);
    if (cosmosState.Ready)
    {
        cosmosBackend.Attach(CosmosAttachment(cosmosState));
    }
    backendList.Add(cosmosBackend);
    cosmosSecondChance = new StoreSecondChance.Plan(
        cosmosBackend,
        () => store.Starting.PrepareAsync(seedVehicles, seedPhotos, CancellationToken.None),
        async state =>
        {
            var attachment = CosmosAttachment(state);
            await attachment.Inventory.WarmAsync(CancellationToken.None);
            await attachment.Bids.LoadAsync(CancellationToken.None);
            cosmosBackend.Attach(attachment);
        });
}

Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region cosmos-backend, read from this build at 99df7a8.

The rules take the clock as a value

A rule that reads DateTime.UtcNow for itself gives a different answer every time it runs, and a test of it can only check what happens "now". A rule that is handed the time gives the same answer for the same inputs, so a test can pin any moment it likes: one millisecond before an auction opens, the millisecond it opens, the last millisecond before it ends.

TheYard reads the clock at the edge, in the host. Its api/TheYard.Api/Shared/Instance/Clocks.cs turns the current moment into an AuctionClock (now, and the UTC midnight the day's auctions are scheduled from), and every endpoint that needs the time passes that value inward:

namespace TheYard.Api.Shared.Instance;

/// <summary>
/// The AuctionClock for a request: now, and the UTC midnight that began the
/// day, the same for every caller. A request never names a day, because an
/// auction that depended on the caller's clock would be a different auction
/// for every visitor.
/// </summary>
public static class Clocks
{
    /// <summary>The auction's clock for this request: now, and the UTC midnight that began the day.</summary>
    public static AuctionClock Now() => AuctionClock.Utc(UtcNow());

    /// <summary>
    /// The server's UTC clock, the one place an endpoint reads the time, so a handler that
    /// stamps a record or picks a reporting window reads the same clock the auction does.
    /// </summary>
    public static DateTimeOffset UtcNow() => DateTimeOffset.UtcNow;
}

Live from api/TheYard.Api/Shared/Instance/Clocks.cs, region *, read from this build at 99df7a8.

The clock itself is a value in Domain, api/TheYard.Domain/Shared/Auction/AuctionClock.cs:

namespace TheYard.Domain.Shared.Auction;

/// <summary>
/// The two instants auction scheduling needs: the current moment, and the
/// midnight the schedule anchors to. The anchor is the server's, the current
/// UTC day's midnight, so every visitor is in the same auction and no request
/// can name a day. An anchor the caller chose would put two visitors in
/// different zones in different auctions, and would let a caller that sent
/// yesterday's midnight bid on a vehicle that has ended for everyone else.
/// </summary>
/// <param name="NowMs">The current moment, as Unix epoch milliseconds.</param>
/// <param name="AnchorMs">The UTC midnight the schedule anchors to, as Unix epoch milliseconds.</param>
public readonly record struct AuctionClock(long NowMs, long AnchorMs)
{
    // #region utc
    /// <summary>The clock for a moment: that moment, and the UTC midnight that began its day.</summary>
    public static AuctionClock Utc(DateTimeOffset utcNow)
    {
        var midnight = new DateTimeOffset(utcNow.UtcDateTime.Date, TimeSpan.Zero);
        return new AuctionClock(utcNow.ToUnixTimeMilliseconds(), midnight.ToUnixTimeMilliseconds());
    }
    // #endregion utc
}

Live from api/TheYard.Domain/Shared/Auction/AuctionClock.cs, region *, read from this build at 99df7a8.

And the rule that uses it, whole, api/TheYard.Domain/Shared/Auction/AuctionSchedule.cs. Every auction's opening and closing times are worked out from the vehicle's id and the anchor, so nothing about the schedule is stored, and the status is a comparison of two numbers:

namespace TheYard.Domain.Shared.Auction;

public enum AuctionStatus
{
    Upcoming,
    Live,
    Ended,
}

/// <summary>An auction's open/close instants as Unix epoch milliseconds.</summary>
/// <param name="StartsAtMs">When the auction opens, as Unix epoch milliseconds.</param>
/// <param name="EndsAtMs">When the auction closes, as Unix epoch milliseconds.</param>
public readonly record struct AuctionWindow(long StartsAtMs, long EndsAtMs);

/// <summary>
/// Derives each vehicle's auction window from its id: an FNV-1a seed, end
/// times spread across the two days before through five days after the
/// midnight anchor, two to four day runs. The anchor is the server's UTC
/// midnight (AuctionClock.Utc), one for every visitor. This is the only place
/// the window is computed; the browser receives the instants on the wire and
/// formats them (src/lib/auction.ts recomputes the status from those instants
/// and the clock, never the window), so a daylight-saving change cannot move
/// the two sides' windows apart.
/// </summary>
public static class AuctionSchedule
{
    private const long HourMs = 60L * 60 * 1000;
    private const long DayMs = 24 * HourMs;

    /// <summary>End times land within [anchor - Lookback, anchor - Lookback + Span).</summary>
    private const long ScheduleLookbackMs = 2 * DayMs;
    private const long ScheduleSpanMs = 7 * DayMs;

    /// <summary>Each auction runs 2–4 days from open to close.</summary>
    private const long MinDurationMs = 2 * DayMs;
    private const long ExtraDurationMs = 2 * DayMs;

    /// <summary>Deterministic per id and anchor (the UTC midnight that began the day).</summary>
    public static AuctionWindow Window(string vehicleId, long anchorMs)
    {
        uint hash = Fnv1a.Hash(vehicleId);
        double endFraction = hash % 100_000 / 100_000.0;
        double durationFraction = hash / 100_000 % 1_000 / 1_000.0;
        long endsAt = (long)Math.Round(anchorMs - ScheduleLookbackMs + endFraction * ScheduleSpanMs);
        long durationMs = (long)Math.Round(MinDurationMs + durationFraction * ExtraDurationMs);
        return new AuctionWindow(endsAt - durationMs, endsAt);
    }

    /// <summary>Live from StartsAt (inclusive) until EndsAt (exclusive).</summary>
    public static AuctionStatus Status(AuctionWindow window, long nowMs)
    {
        if (nowMs < window.StartsAtMs)
        {
            return AuctionStatus.Upcoming;
        }
        return nowMs < window.EndsAtMs ? AuctionStatus.Live : AuctionStatus.Ended;
    }

    public static AuctionStatus StatusFor(string vehicleId, AuctionClock clock) =>
        Status(Window(vehicleId, clock.AnchorMs), clock.NowMs);
}

Live from api/TheYard.Domain/Shared/Auction/AuctionSchedule.cs, region *, read from this build at 99df7a8.

One test, from api/TheYard.Tests/AuctionScheduleTests.cs, pins the moment one millisecond either side of each edge of a window. Clock is built once at the top of the class from a fixed date, so the anchor never depends on the day the test runs. With a clock the rule read for itself, this test could not be written:

// The rule is handed the moment as a number, so the test can name the exact millisecond on
// each side of both edges of a window: one before it opens, the one it opens, the last one
// before it closes, and the one it closes. A rule that read the clock for itself could not
// be asked about any of these four.
[Fact]
public void Status_boundaries_are_start_inclusive_and_end_exclusive()
{
    var window = AuctionSchedule.Window("some-id", Clock.AnchorMs);

    Assert.Equal(AuctionStatus.Upcoming, AuctionSchedule.Status(window, window.StartsAtMs - 1));
    Assert.Equal(AuctionStatus.Live, AuctionSchedule.Status(window, window.StartsAtMs));
    Assert.Equal(AuctionStatus.Live, AuctionSchedule.Status(window, window.EndsAtMs - 1));
    Assert.Equal(AuctionStatus.Ended, AuctionSchedule.Status(window, window.EndsAtMs));
}

Live from api/TheYard.Tests/AuctionScheduleTests.cs, region boundaries, read from this build at 99df7a8.

The practice: read the clock once, at the edge, and pass it inward as a value. The build holds this one too: Domain_never_reaches_the_disk_the_network_or_the_clock reads every method body in Domain for a call to DateTime.Now, DateTime.UtcNow, DateTime.Today or their DateTimeOffset twins, and fails on the first it finds. .NET 8 added TimeProvider for code that needs a clock it can swap, and the record says why a plain value is enough here (What is kept on purpose).

How many things a class may be handed

The S in SOLID is the half of this page's record that is not about rings, and it is held by a number rather than by a yes-or-no test, because one more constructor parameter is never the moment to object. The number is wide_service_classes in .github/quality-ratchet.json: how many classes are handed six or more things (ADR: The numbers that may only fall). Six collaborators is more than one job, and a class with more than one job is changed for more than one reason.

Count parameters, not commas. The rule used to read five commas on the line a class was declared on, which is a different question and gets a different answer. A generic type argument carries a comma of its own, so Func<CancellationToken, Task<string?>> read as two parameters and three classes taking four and five were counted as wide; and a parameter list long enough to wrap puts its last parameters on the lines below, so seven classes taking six to eight were not counted at all. It now reads the whole signature and splits it on a comma at the list's own bracket depth, outside any angle brackets:

# Service classes (not records) handed six or more dependencies: the SRP signal that matters.
# The count is of PARAMETERS, read the way a reader reads them, and it used to be of commas on
# one line. Two different things: a generic type argument carries a comma of its own, so
# Func<CancellationToken, Task<string?>> was read as two parameters and three classes taking
# four and five were counted as taking six; and a parameter list wide enough to wrap puts its
# last parameters on the lines below, so six classes taking six to eight were not counted at
# all. The whole-signature helper above already reads a declaration's brackets across the lines
# it takes, so this rule now reads the list through it and splits that list only where a reader
# would: a comma at the list's own bracket depth, outside any angle brackets (ADR: The numbers
# that may only fall, the addendum on counting a constructor's width).
#
# What this still does not see, said out loud rather than left for the next reader to find: a
# traditional constructor, "public Thing(...)" inside the class body. Telling a class's
# constructor from a record's would mean tracking the enclosing type, which is more than a line
# reader can do, and the one production type it hides is named in the record's addendum.
def handed(taken):
    """The parameters in a parameter list, split where a reader would split them."""
    if taken is None:
        return []
    depth = angle = 0
    out, cur = [], ""
    for ch in taken:
        if ch == "(":
            depth += 1
        elif ch == ")":
            depth -= 1
        elif ch == "<":
            angle += 1
        elif ch == ">":
            angle = max(0, angle - 1)
        if ch == "," and depth == 0 and angle == 0:
            out.append(cur)
            cur = ""
        else:
            cur += ch
    out.append(cur)
    return [p.strip() for p in out if p.strip()]


PRIMARY = re.compile(r"^\s*(public|internal)\s+(sealed\s+|partial\s+|abstract\s+)*class\s+\w+(<[^>]*>)?\s*\(")
WIDE_AT = 6

wide = []
for f in CS_PROD:
    all_lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
    for n, line in enumerate(all_lines, 1):
        m = PRIMARY.search(line.split("//")[0])
        if m and len(handed(parameters(all_lines, n - 1, m.end() - 1))) >= WIDE_AT:
            wide.append(f"{rel(f)}:{n}")
R["wide_service_classes"] = {"count": len(wide), "list": wide}

Live from .github/quality.py, region constructor-width, read from this build at 99df7a8.

A split is by job, and the file that keeps the name lists its parts. The announcement the host makes about its stores took seven things to do two jobs: attach the loggers, then say what came up. Attaching is a type of its own, saying is another, and what is left is the order between them, which is the only thing that was ever really a decision:

// What the host does about its stores the moment it starts, in two moves: attach the loggers,
// then say what came up. The two moves are types of their own in this folder,
// StoreLogAttachment.cs and StoreStartupLines.cs; this file holds the order and nothing else.

namespace TheYard.Api.Shared.Hosted;

/// <summary>
/// Attaches the host's loggers to the stores and says what came up, in that order, because a line
/// written before the factory is attached goes nowhere a reader will look. Runs first of the
/// startup services, so the catalogue's warm is logged. The two jobs are
/// <see cref="StoreLogAttachment"/> and <see cref="StoreStartupLines"/>, which is why this service
/// is handed two things and not seven.
/// </summary>
/// <param name="attachment">The host's loggers, attached to the stores.</param>
/// <param name="lines">The sentences about the stores and the signing key.</param>
public sealed class StoreAnnouncement(StoreLogAttachment attachment, StoreStartupLines lines) : IHostedService
{
    /// <summary>Attaches the loggers and writes the startup lines.</summary>
    /// <param name="cancellationToken">The host's start cancellation.</param>
    public Task StartAsync(CancellationToken cancellationToken)
    {
        attachment.Attach();
        lines.Write();
        return Task.CompletedTask;
    }

    /// <summary>Nothing to stop.</summary>
    /// <param name="cancellationToken">The host's stop cancellation.</param>
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

Live from api/TheYard.Api/Shared/Hosted/StoreAnnouncement.cs, region *, read from this build at 99df7a8.

A parameter object is sometimes the right answer, and it is not the same thing. Four of this host's constructors were wide only because the four rings this process keeps were handed over one at a time. The rings are one concern, named in a record's own title, and every answer those classes give reads the rings and nothing else about them, so they travel as one collaborator now. That is worth distinguishing out loud: grouping parameters that belong together removes the width, and grouping parameters that have nothing to do with each other only hides it, which leaves a class with the same several reasons to change and a tidier signature.

A third way: hand over the collaborator, not its parts. The performance proof's runner was handed two ring buffers so it could build the type that measures one request out of them. Building its own collaborator cost it two parameters and cost every test the chance to hand it another one, so the collaborator arrives by constructor now and the two rings go to the type whose job they are. That is not a parameter object: nothing was grouped, a class stopped doing a job that was already somebody else's. The same move made room for a clock in all three classes this rung split, each of which keeps an answer for a window and so has to be able to be told what time it is:

/// <summary>
/// The last hour, as the Admin tab shows it: the kept answer while it is younger than
/// <see cref="GoodFor"/> on the handed clock, and otherwise one read of the component.
///
/// <para>Failures are kept like successes. Without that, a component that has gone unreachable
/// costs a full timeout on every request to a public, unauthenticated endpoint, and the answer
/// is the same every time anyway.</para>
/// </summary>
/// <param name="cancellation">Cancelled when the poll that asked has gone.</param>
public async Task<object> GetRecentAsync(CancellationToken cancellation)
{
    if (!Configured)
    {
        return new
        {
            configured = false,
            note = "Application Insights is not configured for this build. It is wired at deploy time from Azure; a local run reports nothing.",
        };
    }
    lock (_gate)
    {
        if (_cached is not null && clock.GetUtcNow() - _cachedAt < GoodFor)
        {
            return _cached;
        }
    }

    return Keep(await source.AskAsync(cancellation));
}

Live from api/TheYard.Api/Shared/Observability/Telemetry.cs, region read, read from this build at 99df7a8.

Two things to know before splitting one. The compiler catches every new X(...) whose arity changed, so the only break it cannot see is a type the service container activates by name: a part split off a class and registered nowhere fails when something first asks for it, which on this project meant a red gate on a store boot the shipping machine cannot run. And a class at exactly five is one parameter from the line, so the clock or the token the next rung wants to hand it is the parameter that makes it wide; the two rungs are worked in that order for that reason, and the four classes that sat at five with a clock they could not be handed are where that order paid.

A file at the cap is cut by job, before anything is added to it

The same S, one line down: no production C# file runs past 300 lines, and no type does across all of its parts (FileShapeTests). A cap alone is a cliff, so the ratchet counts the files within ten lines of it, files_within_10_of_cap, which is the list of files whose next edit is the one that would have to split them. The rule is to cut them at that point and not at the cliff, because the edit that finds a file at 299 lines is never the edit that wants to think about its shape.

The cut follows a job, and the file that keeps the name keeps the decision. The request pipeline had reached exactly 300 lines holding eleven middleware steps and the order between them. The order is the only part of it that was ever a decision, so that is what the file kept; what every answer is recorded and stamped with went to one file, and what a browser and the edge may keep went to another:

// Every answer names the web app that gave it, App Service's own WEBSITE_SITE_NAME, so the
// edge card's hourly sample reads who answered a page and who answered the API instead of
// saying so from memory. App Service sets it as an environment setting; off where none is set.
if (identity.SiteName is { } siteName)
{
    app.Use(async (context, next) =>
    {
        context.Response.OnStarting(() =>
        {
            context.Response.Headers[EdgeKeeps.SiteHeader] = siteName;
            return Task.CompletedTask;
        });
        await next();
    });
}

Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region site-header, read from this build at 99df7a8.

Where the pieces are not next to each other, the file that holds the order says so by calling them separately. Two of those eleven steps sit on either side of the exception handler: the timing outside it, so it records the status the caller actually got, and the error record directly inside it, so it sees a failure in anything below. Gathering them into one call is tidier and wrong, and the test that reads the error list said so within a minute of the first attempt.

The build holds the rings

A rule held by code review alone slips the first busy week. TheYard's is held by 19 tests that read the compiled code with NetArchTest, a library that opens .NET assemblies (the compiled .dll files) and checks which types use which. Reading compiled code matters: it sees method bodies and the hidden types the compiler writes for lambdas and async methods, so a dependency tucked inside a lambda fails the build as surely as a using line would. This repository uses the maintained fork, NetArchTest.eNhancedEdition.

The first ten rules, each with what it stops, are a table in the record, under How the build holds them. The rest came later, each for a break it stops, and the record's addendum of 17 November names them all; the test file, OnionTests.cs, is the list. Each one was watched failing before it was trusted. Four failed against the code as it stood when they were written:

  • the two endpoint rules found IServiceProvider in the account and admin handlers, and the bid services in the bid, vehicle and admin handlers;
  • the document store rule found the Cosmos DB adapter using the relational adapter's DatabaseState;
  • the database rule found three queries in the host, one of them in a lambda inside the composition root.

The other six were proved by planting a forbidden reference and watching each go red. The whole file, api/TheYard.Tests/OnionTests.cs:

using Mono.Cecil;
using NetArchTest.Rules;
using TheYard.Data;
using TheYard.Infrastructure;

namespace TheYard.Tests;

/// <summary>
/// The onion, held by the build. Dependencies point inward: Data at the centre, then Domain,
/// then Application, with the adapters (Infrastructure for the relational store,
/// Infrastructure.Cosmos for the document store) and the host (Api) outside them. Each rule reads
/// the compiled assemblies with NetArchTest, so a reference that only shows up in a method body,
/// a fully qualified name or a generic argument is caught as surely as a using line. An adapter
/// can never use the host because the host references the adapters and the compiler refuses a
/// cycle, so that line needs no test of its own.
/// (ADR: Onion and SOLID, how this codebase holds them)
/// </summary>
public sealed class OnionTests
{
    // #region rings
    /// <summary>The namespaces every ring may use: the .NET base class library and nothing else.</summary>
    private const string BaseClassLibrary = "System";

    /// <summary>
    /// The tracker the coverage collector writes into every assembly it measures. CI runs these
    /// tests with coverage on, so without this the rings would fail on code nobody wrote.
    /// </summary>
    private const string CoverageTracker = "Coverlet.Core.Instrumentation";

    /// <summary>
    /// The parts of the base class library that reach the disk, the network or a database. The
    /// rules above allow the whole library, so these are held out of the inner rings by name.
    /// </summary>
    private static readonly string[] TheDiskAndTheNetwork =
    [
        "System.IO.File", "System.IO.Directory", "System.IO.FileStream", "System.IO.StreamReader", "System.IO.StreamWriter",
        "System.IO.FileInfo", "System.IO.DirectoryInfo", "System.IO.FileSystemInfo", "System.IO.Compression", "System.IO.MemoryMappedFiles", "System.IO.Pipes",
        "System.Net", "System.Data",
    ];

    /// <summary>What a rule that takes everything it needs as a value never reads for itself: a clock, a process, a type found by its name.</summary>
    private static readonly string[] TheMachine = ["System.Random", "System.TimeProvider", "System.Environment", "System.Diagnostics.Stopwatch", "System.Diagnostics.Process"];

    [Fact]
    public void Data_depends_on_nothing_outside_the_BCL()
    {
        var result = InRing(typeof(Vehicle), "TheYard.Data")
            .ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
        // System is allowed whole, so the disk, the network and the machine are held out by name.
        var reaches = InRing(typeof(Vehicle), "TheYard.Data").ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine]).GetResult();
        Assert.True(reaches.IsSuccessful, Explain(reaches));
        Assert.Empty(TypeLookups(typeof(Vehicle).Assembly.Location, "TheYard.Data"));
    }

    [Fact]
    public void Data_has_no_behaviour()
    {
        // Pure records (CLAUDE.md): a property, a constructor, what the compiler writes for a record,
        // and nothing else. A computed rule in Data is a second Domain nobody tests as one.
        Assert.Empty(Behaviour(typeof(Vehicle).Assembly.Location));
    }

    [Fact]
    public void Domain_depends_on_nothing_outside_the_BCL_and_Data()
    {
        var result = InRing(typeof(BidRules), "TheYard.Domain")
            .ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void Application_depends_only_on_Domain_Data_and_the_BCL()
    {
        var result = InRing(typeof(StandingReader), "TheYard.Application")
            .ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain", "TheYard.Application")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void Domain_never_reaches_the_disk_the_network_or_the_clock()
    {
        // A rule is a function of what it is handed: the vehicle, the bids and the clock. Reading
        // the time, a random number or a file itself would make it untestable with a fixed clock.
        var result = InRing(typeof(BidRules), "TheYard.Domain")
            .ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine])
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
        Assert.Empty(ClockReads(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
        Assert.Empty(TypeLookups(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
    }

    [Fact]
    public void Application_never_reaches_the_disk_or_the_network()
    {
        // A use case reaches a store or a service through a port; the disk and the network belong
        // to the adapters behind those ports.
        var result = InRing(typeof(StandingReader), "TheYard.Application")
            .ShouldNot().HaveDependencyOnAny(TheDiskAndTheNetwork)
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void The_document_store_adapter_borrows_only_the_shared_user_from_the_relational_one()
    {
        // Identity's user entity is the one type both stores keep accounts as. Anything else from
        // the relational adapter, and Entity Framework above all, stays on its own side.
        string[] relational = typeof(YardDbContext).Assembly.GetTypes()
            .Where(type => type.IsPublic && type != typeof(YardUser))
            .Select(type => type.FullName!)
            .Append("Microsoft.EntityFrameworkCore")
            .Append("Microsoft.AspNetCore.Identity.EntityFrameworkCore")
            .Append("Microsoft.Data")
            .ToArray();
        var result = Types.InAssembly(typeof(CosmosStore).Assembly)
            .ShouldNot().HaveDependencyOnAny(relational)
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }
    [Fact]
    public void Infrastructure_adapts_and_decides_nothing()
    {
        // An adapter turns a port's call into a store's and back. The web (beyond Identity's user
        // store) is the host's, and a rule about money is the Domain's: an adapter method that takes a
        // price or a bid by name and compares it, or reads a vehicle's price and compares it, is a
        // second copy of BidRules that no Domain test sees.
        var found = new List<string>();
        foreach (var adapter in new[] { typeof(YardDbContext).Assembly, typeof(CosmosStore).Assembly })
        {
            using var module = ModuleDefinition.ReadModule(adapter.Location);
            found.AddRange(module.GetTypeReferences()
                .Where(reference => reference.Namespace.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal) && !reference.Namespace.StartsWith("Microsoft.AspNetCore.Identity", StringComparison.Ordinal))
                .Select(reference => $"{adapter.GetName().Name} uses {reference.FullName}"));
            found.AddRange(MoneyDecisions(module));
        }
        Assert.True(found.Count == 0, string.Join(Environment.NewLine, found.Distinct()));
    }
    // #endregion rings

    // #region host
    [Fact]
    public void Endpoints_never_reach_a_store_or_the_service_container()
    {
        // An endpoint reads the request, asks the Application ring, and writes the answer. A
        // database context, a Cosmos DB client or a service looked up by hand would make it a
        // second place where the rules and the wiring live.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .That().MeetCustomRule(IsPartOfAnEndpointClass)
            .ShouldNot().HaveDependencyOnAny(
                "Microsoft.EntityFrameworkCore",
                "Microsoft.Azure.Cosmos",
                "Microsoft.Data.SqlClient",
                "Microsoft.Data.Sqlite",
                "System.Data.Common",
                "TheYard.Infrastructure.Cosmos",
                "TheYard.Infrastructure.YardDbContext",
                "TheYard.Infrastructure.Shared.Stores.ContextFactory",
                "System.IServiceProvider",
                "Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void Endpoints_reach_the_auction_only_through_the_Application_ring()
    {
        // The order bids are composed in (the buyer's first, the room's second) and the price a
        // bid is measured against are Application's, in StandingReader and the bid handlers. An endpoint
        // that held the parts itself could compose them in another order.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .That().MeetCustomRule(IsPartOfAnEndpointClass)
            .ShouldNot().HaveDependencyOnAny(
                "TheYard.Application.Shared.Auction.BidBook",
                "TheYard.Application.Shared.Auction.Room",
                "TheYard.Application.Shared.Auction.Stock")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void Endpoints_see_the_auction_and_the_request_s_store_never_a_backend()
    {
        // A backend is the shared wiring's: which adapter stands behind a store is said by its
        // diagnostics, and an endpoint reads the request's store through CurrentBackend's key,
        // name and auction (ADR: The onion cut into vertical slices, rule 4). The Admin tab's and
        // the health report's endpoints read every backend on purpose until their slices have
        // handlers of their own, which is rule 7's rung.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .That().MeetCustomRule(type => IsPartOfAnEndpointClass(type)
                && !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Admin")
                && !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Health"))
            .ShouldNot().HaveDependencyOnAny("TheYard.Api.Shared.Stores.Backend", "TheYard.Api.Shared.Stores.Backends", "TheYard.Infrastructure.Cosmos.Shared.Stores.CosmosStore")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void The_host_uses_the_sheds_assembly_only_from_the_shed_s_own_site()
    {
        // The Shed is a whole application of its own, hosted in this process (ADR: The onion cut
        // into vertical slices, rule 5). ShedSite and ShedApplication may use its types; anything
        // else that did would fuse the two applications the merge kept apart by construction.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .That().MeetCustomRule(type => Outermost(type).Name is not ("ShedSite" or "ShedApplication"))
            .ShouldNot().HaveDependencyOnAny(["TestProject"])
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void The_host_never_queries_a_database_itself()
    {
        // A statement against a store belongs to the adapter for that store; the host asks the
        // adapter. Entity Framework's design-time factory and the composition root may name the
        // context type, and neither runs a query.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .ShouldNot().HaveDependencyOnAny(
                "Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions",
                "Microsoft.EntityFrameworkCore.RelationalQueryableExtensions",
                "Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions",
                "Microsoft.EntityFrameworkCore.DbSet",
                "Microsoft.Data.SqlClient",
                "Microsoft.Data.Sqlite",
                "System.Data.Common.DbCommand",
                "System.Data.Common.DbConnection",
                "Microsoft.Azure.Cosmos.QueryDefinition",
                "Microsoft.Azure.Cosmos.Container")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void Services_are_registered_only_in_the_composition_root()
    {
        // Registration classes in Shared/, the slices' modules and Program.cs are where the container is filled.
        // Anywhere else, a registration would be wiring hidden inside behaviour.
        var result = Types.InAssembly(typeof(Program).Assembly)
            .That().MeetCustomRule(type => !IsCompositionRoot(type))
            .ShouldNot().HaveDependencyOnAny(
                "Microsoft.Extensions.DependencyInjection.IServiceCollection",
                "Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions",
                "Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions")
            .GetResult();
        Assert.True(result.IsSuccessful, Explain(result));
    }

    [Fact]
    public void The_host_finds_nothing_at_runtime_outside_its_composition_root()
    {
        // A dependency arrives by constructor (ADR: The onion cut into vertical slices, rule 6).
        // Reading the environment, a service container or the built app's configuration from
        // inside behaviour is wiring hidden where a test cannot hand it a value; the types in
        // CompositionRoot are where those are read, each for the reason beside it.
        Assert.Empty(RuntimeLookups(typeof(Program).Assembly.Location));
    }

    [Fact]
    public void A_route_or_a_handler_is_handed_its_settings_never_the_configuration()
    {
        // Rule 6 by its other door: IConfiguration injected into a route delegate is the built app's
        // configuration read per request. A setting is bound once, at composition, into a type the
        // route takes (SiteHosts carries Site:Url), so a test hands the route its value.
        using var module = ModuleDefinition.ReadModule(typeof(Program).Assembly.Location);
        var taking = module.GetTypes()
            .Where(type => !IsCompositionRoot(type) && (IsPartOfAnEndpointClass(type) || Outermost(type).Name.EndsWith("Handler", StringComparison.Ordinal)))
            .SelectMany(type => type.Methods)
            .Where(method => method.Parameters.Any(parameter => parameter.ParameterType.FullName == "Microsoft.Extensions.Configuration.IConfiguration"))
            .Select(method => $"{method.DeclaringType.FullName}.{method.Name} takes IConfiguration")
            .ToList();
        Assert.True(taking.Count == 0, string.Join(Environment.NewLine, taking));
    }

    [Fact]
    public void The_application_ring_finds_nothing_at_runtime_at_all()
    {
        // The handlers and services take their ports by constructor; a handler that took an
        // IServiceProvider and asked it for a port would pass the ring rule (System is allowed)
        // and hide its dependency from every fake-port test (the review of 1.0.4.0, finding 5).
        Assert.Empty(RuntimeLookups(typeof(TheYard.Application.Shared.Auction.StandingReader).Assembly.Location));
    }

    /// <summary>
    /// Every call this site makes to Claude goes through IClaudeClient, whose one adapter writes a
    /// usage document from every answer (ADR: Every Claude lane reports its usage). So the Anthropic
    /// API's address and an Anthropic SDK namespace appear in that adapter's file and in no other
    /// source file of the six projects or the page; a feature that called the API itself would be a
    /// lane that reports no usage, which the record calls a defect.
    /// </summary>
    [Fact]
    public void Claude_is_asked_only_through_the_one_client_that_reports_its_usage()
    {
        string root = Repo.Root();
        string adapter = Path.Combine("api", "TheYard.Api", "Shared", "Usage", "AnthropicClaudeClient.cs");
        var sources = new[] { "TheYard.Data", "TheYard.Domain", "TheYard.Application", "TheYard.Infrastructure", "TheYard.Infrastructure.Cosmos", "TheYard.Api" }
            .SelectMany(project => Directory.EnumerateFiles(Path.Combine(root, "api", project), "*.cs", SearchOption.AllDirectories))
            .Concat(Directory.EnumerateFiles(Path.Combine(root, "src"), "*.ts*", SearchOption.AllDirectories))
            .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
                           && !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
            .ToList();
        Assert.Contains(sources, path => path.EndsWith(adapter, StringComparison.Ordinal));
        var calling = sources
            .Where(path => !path.EndsWith(adapter, StringComparison.Ordinal))
            .Where(path => File.ReadAllText(path) is var text
                && (text.Contains("api.anthropic.com", StringComparison.OrdinalIgnoreCase) || text.Contains("using Anthropic", StringComparison.Ordinal) || text.Contains("@anthropic-ai/", StringComparison.Ordinal)))
            .Select(path => Path.GetRelativePath(root, path))
            .ToList();
        Assert.True(calling.Count == 0, "these files reach the Anthropic API around IClaudeClient: " + string.Join(", ", calling));
        Assert.Contains(typeof(TheYard.Application.Shared.History.IUsageLog), typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient).GetConstructors().Single().GetParameters().Select(p => p.ParameterType));
        Assert.True(typeof(TheYard.Application.Shared.Claude.IClaudeClient).IsAssignableFrom(typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient)));
    }
    // #region host-opens-no-socket
    [Fact]
    public void The_host_opens_no_socket()
    {
        // Only Infrastructure opens a socket (ADR: The onion cut into vertical slices, rule 8). The host builds a
        // request as data and hands it to an Outbound, which Infrastructure's OutboundHttp makes; a client, a
        // handler or a client factory in any host type but Program and a slice's Module is a second door to the
        // network that no adapter test sees. The allow list is empty.
        // The body is tests/rules/SocketRule.cs, the one the job hunt's suite runs over its inner rings too.
        var wrong = TheYard.Rules.SocketRule.Opens(typeof(Program).Assembly, name => name == "Program" || name.EndsWith("Module", StringComparison.Ordinal));
        Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
    }
    // #endregion host-opens-no-socket
    // #endregion host

    /// <summary>
    /// Every place an assembly's method bodies, outside the composition root, read the environment
    /// (Environment.GetEnvironmentVariable), a service container (IServiceProvider.GetService and
    /// the GetService, GetRequiredService and GetServices extensions over it, ActivatorUtilities,
    /// HttpContext.RequestServices) or the built app's configuration (WebApplication.Configuration).
    /// </summary>
    private static List<string> RuntimeLookups(string assemblyPath)
    {
        using var module = ModuleDefinition.ReadModule(assemblyPath);
        // Coverlet's tracker, which a coverage run injects into the host's assembly and which reads
        // the environment itself, is left out the way the ring rules leave out CoverageTracker: it
        // is the measuring tool's code, not this codebase's (CI on main ran red on it from 1.0.3.188).
        return [.. module.GetTypes()
            .Where(type => !IsCompositionRoot(type) && !(type.Namespace ?? "").StartsWith(CoverageTracker, StringComparison.Ordinal))
            .SelectMany(type => type.Methods.Where(method => method.HasBody))
            .SelectMany(method => method.Body.Instructions
                .Select(instruction => instruction.Operand)
                .OfType<MethodReference>()
                .Where(called => (called.DeclaringType.FullName, called.Name) is
                    ("System.Environment", "GetEnvironmentVariable")
                    or ("System.IServiceProvider", "GetService")
                    or ("Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions", _)
                    or ("Microsoft.Extensions.DependencyInjection.ServiceProviderKeyedServiceExtensions", _)
                    or ("Microsoft.Extensions.DependencyInjection.ActivatorUtilities", _)
                    or ("Microsoft.AspNetCore.Http.HttpContext", "get_RequestServices")
                    or ("Microsoft.AspNetCore.Builder.WebApplication", "get_Configuration"))
                .Select(called => $"{method.DeclaringType.FullName}.{method.Name} calls {called.DeclaringType.Name}.{called.Name}"))];
    }

    /// <summary>
    /// Every type in one ring's assembly and namespace, including the types the compiler writes
    /// inside them for lambdas and async methods, which carry the method bodies.
    /// </summary>
    private static PredicateList InRing(Type marker, string ring) =>
        Types.InAssembly(marker.Assembly).That().MeetCustomRule(type => InNamespace(Outermost(type).Namespace, ring));

    /// <summary>
    /// Every place a ring's method bodies read the system clock (DateTime.Now, DateTime.UtcNow,
    /// DateTime.Today and the DateTimeOffset ones). The type is allowed, because a rule takes the
    /// time as a value; reading it is not, and only a scan of the calls can tell the two apart.
    /// </summary>
    private static List<string> ClockReads(string assemblyPath, string ring)
    {
        using var module = ModuleDefinition.ReadModule(assemblyPath);
        return [.. module.GetTypes()
            .Where(type => InNamespace(Outermost(type).Namespace, ring))
            .SelectMany(type => type.Methods.Where(method => method.HasBody))
            .SelectMany(method => method.Body.Instructions
                .Select(instruction => instruction.Operand)
                .OfType<MethodReference>()
                .Where(called => called.DeclaringType.FullName is "System.DateTime" or "System.DateTimeOffset"
                    && called.Name is "get_Now" or "get_UtcNow" or "get_Today")
                .Select(called => $"{method.DeclaringType.FullName}.{method.Name} reads {called.DeclaringType.Name}.{called.Name[4..]}"))];
    }

    /// <summary>
    /// Every place a ring finds a type or loads an assembly by its name (Type.GetType, Assembly.Load
    /// and its kin): a reference the compiler never sees, so no ring rule can.
    /// </summary>
    private static List<string> TypeLookups(string assemblyPath, string ring)
    {
        using var module = ModuleDefinition.ReadModule(assemblyPath);
        return [.. module.GetTypes()
            .Where(type => InNamespace(Outermost(type).Namespace, ring))
            .SelectMany(type => type.Methods.Where(method => method.HasBody))
            .SelectMany(method => method.Body.Instructions
                .Select(instruction => instruction.Operand)
                .OfType<MethodReference>()
                .Where(called => (called.DeclaringType.FullName == "System.Type" && called.Name == "GetType" && called.Parameters.Count > 0)
                    || (called.DeclaringType.FullName == "System.Reflection.Assembly" && called.Name.StartsWith("Load", StringComparison.Ordinal))
                    || called.DeclaringType.FullName == "System.Activator")
                .Select(called => $"{method.DeclaringType.FullName}.{method.Name} calls {called.DeclaringType.Name}.{called.Name}"))];
    }

    /// <summary>What the compiler writes for a record, and the only methods besides accessors and constructors a Data type may carry.</summary>
    private static readonly HashSet<string> RecordMembers = ["ToString", "PrintMembers", "Equals", "GetHashCode", "<Clone>$", "Deconstruct", "op_Equality", "op_Inequality", "get_EqualityContract"];

    /// <summary>Every Data method with a body that is not an accessor, a constructor or a member the compiler writes for a record.</summary>
    private static List<string> Behaviour(string assemblyPath)
    {
        using var module = ModuleDefinition.ReadModule(assemblyPath);
        return [.. module.GetTypes()
            .Where(type => InNamespace(Outermost(type).Namespace, "TheYard.Data") && !type.CustomAttributes.Any(IsCompilerGenerated))
            .SelectMany(type => type.Methods.Where(method => method.HasBody))
            .Where(method => !method.IsGetter && !method.IsSetter && !method.IsConstructor && !RecordMembers.Contains(method.Name) && !method.CustomAttributes.Any(IsCompilerGenerated))
            .Select(method => $"{method.DeclaringType.FullName}.{method.Name} is behaviour in Data")];
    }

    private static bool IsCompilerGenerated(CustomAttribute attribute) =>
        attribute.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute";

    /// <summary>A parameter named for money: a price, a bid, an amount, a reserve or an increment.</summary>
    private static readonly System.Text.RegularExpressions.Regex Money = new("^(amount|bid|buyNow|price|reserve|increment|minNextBid|currentBid|startingBid)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    /// <summary>The comparisons in IL: what turns a value into a decision.</summary>
    private static readonly HashSet<Mono.Cecil.Cil.Code> Comparisons =
    [
        Mono.Cecil.Cil.Code.Clt, Mono.Cecil.Cil.Code.Clt_Un, Mono.Cecil.Cil.Code.Cgt, Mono.Cecil.Cil.Code.Cgt_Un,
        Mono.Cecil.Cil.Code.Blt, Mono.Cecil.Cil.Code.Blt_S, Mono.Cecil.Cil.Code.Blt_Un, Mono.Cecil.Cil.Code.Blt_Un_S,
        Mono.Cecil.Cil.Code.Bgt, Mono.Cecil.Cil.Code.Bgt_S, Mono.Cecil.Cil.Code.Bgt_Un, Mono.Cecil.Cil.Code.Bgt_Un_S,
        Mono.Cecil.Cil.Code.Ble, Mono.Cecil.Cil.Code.Ble_S, Mono.Cecil.Cil.Code.Ble_Un, Mono.Cecil.Cil.Code.Ble_Un_S,
        Mono.Cecil.Cil.Code.Bge, Mono.Cecil.Cil.Code.Bge_S, Mono.Cecil.Cil.Code.Bge_Un, Mono.Cecil.Cil.Code.Bge_Un_S,
    ];

    /// <summary>Adapter methods that compare money: a money parameter by name, or a vehicle's price read, beside a comparison.</summary>
    private static IEnumerable<string> MoneyDecisions(ModuleDefinition module) =>
        module.GetTypes()
            .SelectMany(type => type.Methods.Where(method => method.HasBody))
            .Where(method => method.Body.Instructions.Any(instruction => Comparisons.Contains(instruction.OpCode.Code)))
            .Where(method => method.Parameters.Any(parameter => Money.IsMatch(parameter.Name))
                || method.Body.Instructions.Select(instruction => instruction.Operand).OfType<MethodReference>()
                    .Any(called => called.DeclaringType.FullName == "TheYard.Data.Vehicle" && called.Name is "get_CurrentBid" or "get_BuyNowPrice" or "get_ReservePrice" or "get_StartingBid"))
            .Select(method => $"{method.DeclaringType.FullName}.{method.Name} decides on money in an adapter");

    /// <summary>True for the ring's namespace and every namespace under it.</summary>
    private static bool InNamespace(string name, string ring) =>
        name == ring || name.StartsWith(ring + ".", StringComparison.Ordinal);

    /// <summary>
    /// True for an endpoint class and for the types the compiler writes inside one (its async state
    /// machines and lambdas): a type named *Endpoints, or any type outside the composition root whose
    /// code maps a route (calls a Map method of the route builder), whatever it is named.
    /// </summary>
    private static bool IsPartOfAnEndpointClass(TypeDefinition type)
    {
        var outer = Outermost(type);
        return !IsCompositionRoot(outer) && (outer.Name.EndsWith("Endpoints", StringComparison.Ordinal) || RouteMappers.Value.Contains(outer.FullName));
    }

    /// <summary>The host's types whose method bodies, or the bodies the compiler wrote inside them, map a route.</summary>
    private static readonly Lazy<HashSet<string>> RouteMappers = new(() =>
    {
        using var module = ModuleDefinition.ReadModule(typeof(Program).Assembly.Location);
        return module.GetTypes()
            .Where(type => type.Methods.Any(method => method.HasBody && method.Body.Instructions
                .Select(instruction => instruction.Operand).OfType<MethodReference>()
                .Any(called => called.DeclaringType.Name.EndsWith("EndpointRouteBuilderExtensions", StringComparison.Ordinal) && called.Name.StartsWith("Map", StringComparison.Ordinal))))
            .Select(type => Outermost(type).FullName)
            .ToHashSet(StringComparer.Ordinal);
    });

    /// <summary>
    /// The types where the container is filled and read, by name, each with its reason: Program and
    /// the registration classes in Shared/ fill it; a slice's Module fills its part; the two pipeline
    /// steps read the built container once, when Program builds the pipeline; The Shed's application
    /// composes a guest site's own container; IModule is the shape every slice's Module has. A type is on this list or it is behaviour, so a new
    /// FooModule or BarRegistration elsewhere is not exempt by its name (the review of 1.0.4.0, finding 5).
    /// </summary>
    private static readonly HashSet<string> CompositionRoot =
    [
        "Program", "<Program>$",
        "ActivityRegistration", "AdminRegistration", "ApiRegistration", "AuthRegistration", "CostRegistration", "HostedSiteRegistration",
        "ObservabilityRegistration", "SpaRegistration", "StartupRegistration", "StoreRegistration", "TelemetryRegistration", "UsageRegistration",
        "Modules", "IModule",
        "RequestPipeline", "HostedSiteMount", "ShedApplication",
    ];

    /// <summary>True for a type on the composition root's list, for a slice's Module (TheYard.Api.Features.*.Module), and for the types the compiler writes inside them.</summary>
    private static bool IsCompositionRoot(TypeDefinition type)
    {
        var outer = Outermost(type);
        return CompositionRoot.Contains(outer.Name)
            || (outer.Name == "Module" && (outer.Namespace ?? "").StartsWith("TheYard.Api.Features.", StringComparison.Ordinal));
    }

    /// <summary>The type a nested or compiler-written type sits inside, all the way out.</summary>
    private static TypeDefinition Outermost(TypeDefinition type)
    {
        while (type.DeclaringType is { } outer)
        {
            type = outer;
        }
        return type;
    }

    /// <summary>The failing types and why, so a red test names the line to fix rather than only saying no.</summary>
    private static string Explain(TestResult result) =>
        result.IsSuccessful
            ? ""
            : string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}"));
}

Live from api/TheYard.Tests/OnionTests.cs, region *, read from this build at 99df7a8.

Watch one go red on your own repository

  1. Add the package to your test project: dotnet add <your test project> package NetArchTest.eNhancedEdition.
  2. Write one rule: your Domain project may depend on System and on itself, and nothing else (the test is below).
  3. Run dotnet test and watch it pass.
  4. Plant a forbidden reference: add Microsoft.Extensions.Logging.Abstractions to the Domain project and write _ = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; in any Domain method.
  5. Run dotnet test again: it fails and names the type and the dependency it found. Delete the line, and keep the test.
using NetArchTest.Rules;
using Xunit;

public sealed class OnionTests
{
    [Fact]
    public void Domain_depends_on_nothing_outside_the_BCL()
    {
        // Every type in the Domain assembly, including the ones the compiler writes for lambdas and
        // async methods, may use the base class library and Domain itself. Nothing else.
        var result = Types.InAssembly(typeof(YourApp.Domain.SomeRule).Assembly)
            .ShouldNot().HaveDependencyOtherThan("System", "YourApp.Domain")
            .GetResult();

        // A red run names each type that broke the rule and what it reached for, so the message
        // points at the line to fix.
        Assert.True(
            result.IsSuccessful,
            string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}")));
    }
}

If your continuous integration collects code coverage, add "Coverlet.Core.Instrumentation" to the allowed list: the coverage tool writes a tracker into every assembly it measures, and the rule would otherwise fail on code nobody wrote.

One project, rings as folders

Folders can draw the rings as well as projects can. The Shed, a file and folder browser that lives beside TheYard in this repository (samples/theshed) and runs at theshed.stevenstout.biz, is one project. Its rings are folders, each folder is a namespace, and the tests select a ring by namespace instead of by project: Data, Domain, Application, Infrastructure, Controllers, Documentation and Composition. The reasoning for keeping it to one project is its own record, One project, seven folders, dependencies inward.

One project costs one thing. Across projects, the compiler refuses a reference that would make a cycle, so an adapter can never use the host and nobody has to test it. Inside one project the compiler allows anything, so every direction is a test's job, and so is a type that lands in a folder no rule names. The last test in the file below exists for exactly that: a new folder or a missing namespace line would otherwise be checked by none of the rules.

The practice: in a small codebase, start with folders and these tests, and split a ring into a project of its own the day a second store or a second host appears. This is the section to copy first.

The Shed's tests, whole, samples/theshed/tests/TestProject.Tests/OnionTests.cs:

using Mono.Cecil;
using NetArchTest.Rules;
using TestProject.Domain;

namespace TestProject.Tests;

/// <summary>
/// Checks the onion by reading the compiled app. The folders are rings, innermost first: Data,
/// Domain, Application, then Infrastructure and Controllers on the outside, and Composition, which
/// wires them together. A ring may use the rings inside it and never one outside it. NetArchTest
/// reads every type, including the ones the compiler writes for lambdas and async methods, so a
/// reference in a method body or a fully written name is caught as surely as a using line.
/// (more in docs/ADR-013-onion-and-solid.md)
/// </summary>
public sealed class OnionTests
{
    /// <summary>The tracker a coverage run writes into the app, which is nobody's dependency.</summary>
    private const string Coverage = "Coverlet.Core.Instrumentation";

    private static readonly string[] DataMayUse = ["System", Coverage, "TestProject.Data"];
    private static readonly string[] DomainMayUse = ["System", Coverage, "TestProject.Data", "TestProject.Domain"];
    private static readonly string[] ApplicationMayUse = ["System", Coverage, "TestProject.Data", "TestProject.Domain", "TestProject.Application"];
    private static readonly string[] InfrastructureMustNotUse = ["TestProject.Controllers", "TestProject.Composition", "TestProject.Documentation", "Microsoft.AspNetCore"];
    private static readonly string[] TheDisk = ["System.IO.File", "System.IO.Directory", "System.IO.FileInfo", "System.IO.DirectoryInfo", "System.IO.FileStream", "System.IO.FileSystemInfo", "System.IO.StreamReader", "System.IO.StreamWriter"];
    private static readonly string[] ControllersMustNotUse = [.. TheDisk, "TestProject.Infrastructure", "TestProject.Composition", "TestProject.Application.IFileStore", "TestProject.Domain.HomePath", "Microsoft.AspNetCore.Mvc.PhysicalFileResult"];
    private static readonly string[] DocumentationMustNotUse = ["TestProject.Controllers", "TestProject.Composition", "TestProject.Infrastructure", "Microsoft.AspNetCore"];
    private static readonly string[] Registration = ["Microsoft.Extensions.DependencyInjection.IServiceCollection", "Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions"];

    // #region rings
    [Fact]
    public void Data_depends_on_nothing_outside_the_BCL() =>
        AssertHolds(InRing("TestProject.Data").ShouldNot().HaveDependencyOtherThan(DataMayUse).GetResult());

    [Fact]
    public void Domain_depends_on_nothing_outside_the_BCL_and_Data() =>
        AssertHolds(InRing("TestProject.Domain").ShouldNot().HaveDependencyOtherThan(DomainMayUse).GetResult());

    [Fact]
    public void Application_depends_only_on_Domain_Data_and_the_BCL() =>
        AssertHolds(InRing("TestProject.Application").ShouldNot().HaveDependencyOtherThan(ApplicationMayUse).GetResult());

    [Fact]
    public void Application_never_touches_the_disk_itself() =>
        AssertHolds(InRing("TestProject.Application").ShouldNot().HaveDependencyOnAny(TheDisk).GetResult());

    [Fact]
    public void Infrastructure_depends_on_nothing_outside_it() =>
        AssertHolds(InRing("TestProject.Infrastructure").ShouldNot().HaveDependencyOnAny(InfrastructureMustNotUse).GetResult());

    [Fact]
    public void Controllers_never_touch_the_disk_or_the_file_store() =>
        AssertHolds(InRing("TestProject.Controllers").ShouldNot().HaveDependencyOnAny(ControllersMustNotUse).GetResult());

    [Fact]
    public void Documentation_reaches_only_Data_and_the_framework() =>
        AssertHolds(InRing("TestProject.Documentation").ShouldNot().HaveDependencyOnAny(DocumentationMustNotUse).GetResult());

    [Fact]
    public void Services_are_registered_only_in_Composition() =>
        AssertHolds(Types.InAssembly(typeof(HomePath).Assembly)
            .That().MeetCustomRule(type => Outermost(type).Namespace != "TestProject.Composition")
            .ShouldNot().HaveDependencyOnAny(Registration)
            .GetResult());

    [Fact]
    public void Every_type_sits_in_one_of_the_folders_the_rings_name()
    {
        // A type in a namespace no rule names (a new folder, a typo, a missing namespace line)
        // would be checked by none of the rules above. The compiler's own helpers are skipped:
        // their names start with "<", and the attributes it writes sit under System or Microsoft.
        // Program alone sits in the project's own namespace, above every folder.
        using var module = ModuleDefinition.ReadModule(typeof(HomePath).Assembly.Location);
        var strays = module.Types
            .Where(type => !type.Name.StartsWith('<'))
            .Where(type => !type.Namespace.StartsWith("System", StringComparison.Ordinal) && !type.Namespace.StartsWith("Microsoft", StringComparison.Ordinal) && !type.Namespace.StartsWith("Coverlet", StringComparison.Ordinal))
            .Where(type => type.Namespace != "TestProject" && !Folders.Any(ring => InNamespace(type.Namespace, ring)))
            .Select(type => type.FullName)
            .ToList();
        Assert.True(strays.Count == 0, "outside every ring: " + string.Join(", ", strays));
    }
    // #endregion rings

    /// <summary>The folders, each one a ring and a namespace.</summary>
    private static readonly string[] Folders = ["TestProject.Data", "TestProject.Domain", "TestProject.Application", "TestProject.Infrastructure", "TestProject.Controllers", "TestProject.Documentation", "TestProject.Composition"];

    /// <summary>
    /// Every type in one ring, including the ones the compiler writes inside them. A ring is a
    /// folder, and each folder is a namespace; a folder inside it belongs to the same ring.
    /// </summary>
    private static PredicateList InRing(string ring) =>
        Types.InAssembly(typeof(HomePath).Assembly).That().MeetCustomRule(type => InNamespace(Outermost(type).Namespace, ring));

    /// <summary>True for the ring's namespace and every namespace under it.</summary>
    private static bool InNamespace(string name, string ring) =>
        name == ring || name.StartsWith(ring + ".", StringComparison.Ordinal);

    /// <summary>The type a nested or compiler-written type sits inside, all the way out.</summary>
    private static TypeDefinition Outermost(TypeDefinition type)
    {
        while (type.DeclaringType is { } outer)
        {
            type = outer;
        }
        return type;
    }

    /// <summary>Passes when the rule held, and names each failing type and why when it did not.</summary>
    private static void AssertHolds(TestResult result) =>
        Assert.True(
            result.IsSuccessful,
            string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}")));
}

Live from samples/theshed/tests/TestProject.Tests/OnionTests.cs, region *, read from this build at 99df7a8.

When not to build it this way

The rings cost projects, interfaces and tests, and they pay that back only when there is something to protect: here, two stores behind the same rules, a host with an operator's tab, and rules worth testing on their own. A small service over one table, a spike written to learn something quickly, or a script that reads, changes and writes is clearer flat, and gains a ring the day a second store or a rule worth testing alone turns up. The record draws that line in more detail, under When not to build it this way, and The Shed above is the middle road between the two.

References

Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn