CQRS, 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. Every request its API answers is either a query or a command, and the
record of that decision, with what was weighed and what was left out, is
ADR: A request is a query or a command.
This page is the practical half: the shape, shown with whole classes read from the running build, the
counts this build has, and what this codebase deliberately does not do.
In plain words
A request either asks a question or asks for something to change. CQRS, command query responsibility
segregation, means writing those two kinds of request as two kinds of code. Here a question is a
query and a change is a command; each has exactly one piece of code that answers it, a handler,
and a query's handler is never handed anything that can write.
What that is worth: a developer can tell from one word whether a piece of code can change anything,
and can test a query without fearing it saves something; the organization gets that held by the build
on every push rather than by a reviewer reading carefully.
The words this page uses
- Query: a request that reads and changes nothing.
ReadFacetsQuery, FindVehicleQuery.
- Command: a request that changes something and may answer what it did.
PlaceBidCommand,
ResetBidsCommand.
- Handler: the one class that answers one request. Its name is the request's with
Handler in
place of the last word.
- Port: an interface the Application ring declares and an adapter implements, such as a store.
A reader port only reads; a store or writer port can write.
The two interfaces, and nothing else
The whole mechanism is two interfaces. There is no bus, no mediator library and no pipeline: the slice's
Module maps a route to its handler, the compiler checks the types, and "go to definition" on a route
lands on the code that runs.
api/TheYard.Application/Shared/Requests.cs:
public interface IQueryHandler<in TQuery, TResult>
{
Task<TResult> HandleAsync(TQuery query, CancellationToken cancellation);
}
public interface ICommandHandler<in TCommand, TResult>
{
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellation);
}
Live from api/TheYard.Application/Shared/Requests.cs, region requests, read from this build at 99df7a8.
Greg Young's documents trace the idea to Bertrand Meyer's command-query separation, a method that
either does something or answers something, lifted from methods to objects
(CQRS Documents). That
lift is all this codebase takes.
A query is handed the reading side only
The catalogue's three queries. Each takes StandingReader or IStockReader, neither of which has a
method that writes, so a listing cannot place a bid however it is changed later.
api/TheYard.Application/Features/Vehicles/VehicleHandlers.cs:
public sealed class SearchVehiclesHandler(StandingReader standings) : IQueryHandler<SearchVehiclesQuery, StandingPage>
{
public Task<StandingPage> HandleAsync(SearchVehiclesQuery request, CancellationToken cancellation) =>
standings.SearchAsync(request.Filter, request.Clock, request.Sort, request.Limit, request.Offset, cancellation);
}
public sealed class ReadFacetsHandler(IStockReader inventory) : IQueryHandler<ReadFacetsQuery, InventoryFacets>
{
public Task<InventoryFacets> HandleAsync(ReadFacetsQuery query, CancellationToken cancellation) => inventory.FacetsAsync(cancellation);
}
public sealed record ReadFacetsQuery;
public sealed class FindVehicleHandler(StandingReader standings, Func<AuctionClock> clock) : IQueryHandler<FindVehicleQuery, FoundVehicle>
{
public async Task<FoundVehicle> HandleAsync(FindVehicleQuery query, CancellationToken cancellation) =>
new(await standings.FindAsync(query.Id, cancellation), clock());
}
public sealed record FindVehicleQuery(string Id);
Live from api/TheYard.Application/Features/Vehicles/VehicleHandlers.cs, region vehicle-handlers, read from this build at 99df7a8.
StandingReader is how every query reads a vehicle: the catalogue, then everybody's bids, then the
simulated room, in the one order the price rules need, from the reading side of each.
api/TheYard.Application/Shared/Auction/StandingReader.cs:
using TheYard.Data;
using TheYard.Domain.Shared.Auction;
namespace TheYard.Application.Shared.Auction;
public sealed class StandingReader(IStockReader inventory, IBidReader bids, IRoomReader room)
{
private ListingOverlay? Overlay()
{
if (bids.IsEmpty && room.IsEmpty)
{
return null;
}
var moved = new HashSet<string>(StringComparer.Ordinal);
if (!bids.IsEmpty)
{
moved.UnionWith(bids.Standing().Keys);
}
if (!room.IsEmpty)
{
moved.UnionWith(room.Snapshot().Keys);
}
return new ListingOverlay(moved, AsItStands);
}
private Vehicle AsItStands(Vehicle vehicle) => room.Apply(bids.Apply(vehicle));
public async Task<StandingVehicle?> FindAsync(string vehicleId, CancellationToken cancellation) =>
await inventory.FindAsync(vehicleId, cancellation) is { } vehicle ? new StandingVehicle(AsItStands(vehicle), bids.IsSold(vehicleId)) : null;
public async Task<StandingPage> SearchAsync(VehicleFilter filter, AuctionClock clock, VehicleSort sort, int limit, int offset, CancellationToken cancellation)
{
var page = await inventory.SearchAsync(filter, clock, sort, limit, offset, Overlay(), cancellation);
return new StandingPage(page.Total, [.. page.Vehicles.Select(vehicle => new StandingVehicle(vehicle, bids.IsSold(vehicle.Id)))]);
}
public IReadOnlyDictionary<string, BidView> BidsOf(string userId)
{
var mine = bids.SnapshotFor(userId);
var standing = bids.Standing();
var against = room.Snapshot();
var views = new Dictionary<string, BidView>(StringComparer.Ordinal);
foreach (var (id, bid) in mine)
{
standing.TryGetValue(id, out var held);
against.TryGetValue(id, out var answered);
int highest = Math.Max(held?.Amount ?? bid.Amount, answered?.Amount ?? 0);
bool someoneElseHolds = held is not null && held.Amount > bid.Amount;
bool roomHolds = answered is not null && answered.Amount > bid.Amount;
bool outbid = !bid.WonBuyNow && (someoneElseHolds || roomHolds);
views[id] = new BidView(
bid.Amount,
Math.Max(Math.Max(bid.BidCount, held?.BidCount ?? 0), answered?.BidCount ?? 0),
bid.WonBuyNow,
bid.AtMs,
outbid,
answered?.Amount,
highest);
}
return views;
}
public async Task<BidHistory> HistoryOfAsync(string userId, CancellationToken cancellation)
{
var mine = BidsOf(userId);
var titles = (await inventory.FindManyAsync(mine.Keys.ToList(), cancellation))
.ToDictionary(v => v.Id, v => $"{v.Year} {v.Make} {v.Model}", StringComparer.Ordinal);
var entries = mine
.OrderByDescending(entry => entry.Value.AtMs)
.Select(entry => new BidHistoryEntry(
entry.Key,
titles.TryGetValue(entry.Key, out var title) ? title : "(withdrawn)",
entry.Value))
.ToList();
return new BidHistory(entries.Count, entries);
}
}
Live from api/TheYard.Application/Shared/Auction/StandingReader.cs, region *, read from this build at 99df7a8.
A command takes the side it writes through
The bid. It reads the vehicle as it stands through the same reader the queries use, then writes
through the bids' writing side, and nothing else.
api/TheYard.Application/Features/Bids/PlaceBidHandler.cs:
public sealed class PlaceBidHandler(StandingReader standings, IBidWriter bids, Func<AuctionClock> clock) : ICommandHandler<PlaceBidCommand, BidAnswer>
{
public async Task<BidAnswer> HandleAsync(PlaceBidCommand request, CancellationToken cancellation)
{
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);
}
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);
}
return new BidAnswer(
BidAnswerKind.Placed,
outcome,
null,
standings.BidsOf(request.UserId).TryGetValue(request.VehicleId, out var standing) ? standing : null,
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.
Split a port where a query needs half of it
This is Interface Segregation from SOLID, made a rule by CQRS. A port that carries reads and writes in
one interface is split so the query can be handed the read half. The blog's store, the read half:
api/TheYard.Application/Features/Blog/BlogStore.cs:
public interface IBlogReader
{
Task<BlogAvailability> AvailabilityAsync(CancellationToken cancellation);
Task<IReadOnlyList<BlogPost>> PostsAsync(CancellationToken cancellation);
Task<BlogPost?> PostAsync(string slug, CancellationToken cancellation);
Task<BlogListPage> ListAsync(BlogFilter filter, BlogVocabulary vocabulary, DateTimeOffset now, CancellationToken cancellation);
Task<BlogPostPage?> PostPageAsync(string slug, BlogVocabulary vocabulary, DateTimeOffset now, CancellationToken cancellation);
Task<BlogVocabulary?> VocabularyAsync(CancellationToken cancellation);
Task<(IReadOnlyDictionary<string, int> PerTag, int Posts)> TagCountsAsync(CancellationToken cancellation);
Task<IReadOnlyList<BlogStat>> StatsAsync(DateTimeOffset now, DateTimeOffset since, CancellationToken cancellation);
Task<IReadOnlyList<BlogSourceCount>> SourcesAsync(DateTimeOffset since, CancellationToken cancellation);
}
Live from api/TheYard.Application/Features/Blog/BlogStore.cs, region blog-reader, read from this build at 99df7a8.
And the whole store, which extends it with the three writes and is handed to the commands:
public interface IBlogStore : IBlogReader
{
Task<int> SaveAsync(BlogPost post, BlogDerived derived, DateTimeOffset at, CancellationToken cancellation);
Task SetLinkedInAsync(int postId, string linkedInUrl, DateTimeOffset publishedAt, CancellationToken cancellation);
Task<IReadOnlyList<(BlogPost Post, bool Never)>> StaleAsync(int version, CancellationToken cancellation);
Task KeepDerivedAsync(int postId, BlogDerived derived, IReadOnlyList<string>? topics, CancellationToken cancellation);
Task<int?> SeedAsync(BlogVocabulary starter, CancellationToken cancellation);
Task KeepTagsAsync(IReadOnlyList<BlogTag> tags, CancellationToken cancellation);
Task<bool> RemoveTagAsync(string key, CancellationToken cancellation);
Task KeepSynonymAsync(BlogSynonym synonym, CancellationToken cancellation);
Task<bool> RemoveSynonymAsync(string word, CancellationToken cancellation);
Task MarkStaleAsync(CancellationToken cancellation);
Task KeepReadAsync(BlogRead read, CancellationToken cancellation);
Task KeepEventAsync(BlogEvent blogEvent, CancellationToken cancellation);
}
Live from api/TheYard.Application/Features/Blog/BlogStore.cs, region blog-store, read from this build at 99df7a8.
The auction's three parts are split the same way, one reading and one writing interface each:
api/TheYard.Application/Shared/Auction/AuctionParts.cs:
public interface IStockReader
{
Task<Vehicle?> FindAsync(string id, CancellationToken cancellation);
Task<IReadOnlyList<Vehicle>> FindManyAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);
Task<IReadOnlyList<Vehicle>> FirstLiveAsync(AuctionClock clock, int take, CancellationToken cancellation);
Task<InventoryFacets> FacetsAsync(CancellationToken cancellation);
Task<SearchResult> SearchAsync(VehicleFilter filter, AuctionClock clock, VehicleSort sort = VehicleSort.EndingSoonest, int limit = int.MaxValue, int offset = 0, ListingOverlay? overlay = null, CancellationToken cancellation = default);
}
public interface IBidReader
{
bool IsEmpty { get; }
IReadOnlyDictionary<string, BidState> SnapshotFor(string userId);
IReadOnlyDictionary<string, VehicleStanding> Standing();
bool IsSold(string vehicleId);
IReadOnlyDictionary<string, BidState> StandingAsBids();
Vehicle Apply(Vehicle vehicle);
}
public interface IBidWriter
{
Task<BidOutcome> PlaceBidAsync(Vehicle vehicle, int amount, AuctionClock clock, string userId, CancellationToken cancellation);
Task<BidOutcome> BuyNowAsync(Vehicle vehicle, AuctionClock clock, string userId, CancellationToken cancellation);
Task<IReadOnlyList<string>> ResetAsync(string userId, CancellationToken cancellation);
}
public interface IRoomReader
{
bool IsEmpty { get; }
IReadOnlyDictionary<string, MarketBid> Snapshot();
Vehicle Apply(Vehicle vehicle);
}
public interface IRoomWriter
{
IReadOnlyList<string> Tick(IReadOnlyList<Vehicle> candidates, IReadOnlyDictionary<string, BidState> buyerBids, AuctionClock clock, int maxBids = 3);
void Forget(IEnumerable<string> vehicleIds);
}
Live from api/TheYard.Application/Shared/Auction/AuctionParts.cs, region auction-parts, read from this build at 99df7a8.
No services
A class named BidService is a bag of use cases behind one name: it placed bids, reset them and read
standings, and anything handed it could do all three. Each use case is a handler now, and the shared
state the handlers need is a part with two sides. Jimmy Bogard's vertical slices make the same move:
organise by request, and the request is already a command or a query, so shared layers of services and
repositories mostly fall away
(Vertical Slice Architecture).
The test that holds it
api/TheYard.Tests/CqrsTests.cs:
public sealed class CqrsTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
private static readonly Assembly Application = typeof(IQueryHandler<,>).Assembly;
private const string Features = "TheYard.Application.Features";
private static List<Type> Requests(string word) =>
[.. Application.GetTypes().Where(type => type.IsClass && type.Namespace?.StartsWith(Features, StringComparison.Ordinal) == true && type.Name.EndsWith(word, StringComparison.Ordinal))];
private static List<string> Services() =>
[.. Application.GetTypes()
.Where(type => type.IsClass && !type.Name.StartsWith('<') && type.Name.EndsWith("Service", StringComparison.Ordinal)
&& (type.Namespace == "TheYard.Application" || type.Namespace?.StartsWith(Features, StringComparison.Ordinal) == true))
.Select(type => type.Name)];
private static List<Type> HandlerTypes() =>
[.. Application.GetTypes().Where(type => type.IsClass && !type.IsAbstract && type.Name.EndsWith("Handler", StringComparison.Ordinal) && type.Namespace?.StartsWith(Features, StringComparison.Ordinal) == true)];
private static List<(Type Contract, Type Request, bool Query)> Contracts(Type handler) =>
[.. handler.GetInterfaces()
.Where(contract => contract.IsGenericType && (contract.GetGenericTypeDefinition() == typeof(IQueryHandler<,>) || contract.GetGenericTypeDefinition() == typeof(ICommandHandler<,>)))
.Select(contract => (contract, contract.GetGenericArguments()[0], contract.GetGenericTypeDefinition() == typeof(IQueryHandler<,>)))];
[Fact]
public void Every_handler_is_exactly_one_query_or_command_handler_named_for_its_request()
{
var handlers = HandlerTypes();
Assert.True(handlers.Count >= 27, $"only {handlers.Count} handlers were found");
var wrong = new List<string>();
foreach (var handler in handlers)
{
var contracts = Contracts(handler);
if (contracts.Count != 1)
{
wrong.Add($"{handler.Name} implements {contracts.Count} of IQueryHandler and ICommandHandler; it implements exactly one");
continue;
}
var (_, request, query) = contracts[0];
string expected = handler.Name[..^"Handler".Length] + (query ? "Query" : "Command");
if (request.Name != expected)
{
wrong.Add($"{handler.Name} handles {request.Name}; its request is named {expected}");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public void Every_query_and_command_has_exactly_one_handler()
{
var requests = Requests("Query").Concat(Requests("Command")).ToList();
Assert.True(requests.Count >= 27, $"only {requests.Count} requests were found");
var handled = HandlerTypes().SelectMany(Contracts).GroupBy(contract => contract.Request).ToDictionary(group => group.Key, group => group.ToList());
var wrong = new List<string>();
foreach (var request in requests)
{
int count = handled.TryGetValue(request, out var found) ? found.Count : 0;
if (count != 1)
{
wrong.Add($"{request.Name} has {count} handlers; it has exactly one");
}
else if (request.Name.EndsWith("Query", StringComparison.Ordinal) != found![0].Query)
{
wrong.Add($"{request.Name} is handled as a {(found[0].Query ? "query" : "command")}; its name says otherwise");
}
if (!request.IsSealed)
{
wrong.Add($"{request.Name} is not sealed");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public void A_query_handler_is_handed_no_store_and_no_writer()
{
static string Bare(Type type) => (Nullable.GetUnderlyingType(type) ?? type).Name;
var wrong = HandlerTypes()
.Where(handler => Contracts(handler).Any(contract => contract.Query))
.SelectMany(handler => handler.GetConstructors().SelectMany(constructor => constructor.GetParameters())
.Where(parameter => Bare(parameter.ParameterType).EndsWith("Store", StringComparison.Ordinal) || Bare(parameter.ParameterType).EndsWith("Writer", StringComparison.Ordinal))
.Select(parameter => $"{handler.Name} takes {Bare(parameter.ParameterType)} {parameter.Name}; a query takes the reader"))
.ToList();
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public void A_query_handler_is_handed_no_port_that_can_write()
{
var wrong = HandlerTypes()
.Where(handler => Contracts(handler).Any(contract => contract.Query))
.SelectMany(handler => handler.GetConstructors().SelectMany(constructor => constructor.GetParameters())
.Select(parameter => (handler, parameter, writes: WritingMembers(Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType)))
.Where(found => found.writes.Count > 0)
.Select(found => $"{found.handler.Name} takes {found.parameter.ParameterType.Name} {found.parameter.Name}, which can {string.Join(", ", found.writes)}; a query takes a port that only reads"))
.Where(line => !ExemptReaders.Any(exempt => line.StartsWith(exempt.Key + " ", StringComparison.Ordinal)))
.ToList();
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
private static readonly Regex WritingVerb = new(@"^(Keep|Write|Save|Upsert|Delete|Add|Remove|Record|Put|Set)(?=[A-Z_]|$)", RegexOptions.Compiled);
private static readonly Dictionary<string, string> ExemptReaders = new(StringComparer.Ordinal);
private static List<string> WritingMembers(Type port)
{
if (port.Namespace?.StartsWith("TheYard.", StringComparison.Ordinal) != true)
{
return [];
}
IEnumerable<Type> contracts = port.IsInterface ? port.GetInterfaces().Prepend(port) : [port];
return [.. contracts
.SelectMany(contract => contract.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly))
.Where(member => member is not MethodInfo { IsSpecialName: true } && WritingVerb.IsMatch(member.Name))
.Select(member => member.Name)
.Distinct(StringComparer.Ordinal)
.Order(StringComparer.Ordinal)];
}
[Fact]
public void No_type_in_the_Application_ring_s_slices_or_root_is_a_service()
{
var services = Services();
Assert.True(services.Count == 0, "types named *Service: " + string.Join(", ", services));
}
[Fact]
public void Every_route_that_asks_a_handler_asks_a_query_or_a_command_handler()
{
var routes = factory.Services.GetRequiredService<EndpointDataSource>().Endpoints.OfType<RouteEndpoint>()
.Select(endpoint => endpoint.Metadata.GetMetadata<MethodInfo>())
.OfType<MethodInfo>()
.Where(answer => answer.DeclaringType?.Namespace?.StartsWith("TheYard.Api.Features.", StringComparison.Ordinal) == true)
.ToList();
Assert.NotEmpty(routes);
var wrong = routes
.SelectMany(answer => answer.GetParameters()
.Where(parameter => parameter.ParameterType.Namespace?.StartsWith(Features, StringComparison.Ordinal) == true && parameter.ParameterType.Name.EndsWith("Handler", StringComparison.Ordinal))
.Where(parameter => Contracts(parameter.ParameterType).Count != 1)
.Select(parameter => $"{answer.DeclaringType!.Name}.{answer.Name} asks {parameter.ParameterType.Name}, which is not a query or a command handler"))
.ToList();
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public void The_practices_page_quotes_the_counts_this_build_has()
{
string page = File.ReadAllText(Path.Combine(Repo.Root(), "docs", "best-practices", "CQRS.md"));
var counted = new Dictionary<string, int>(StringComparer.Ordinal)
{
["queries"] = Requests("Query").Count,
["commands"] = Requests("Command").Count,
["handlers"] = HandlerTypes().Count,
["services"] = Services().Count,
};
var wrong = new List<string>();
foreach (var (shape, actual) in counted)
{
var quoted = Regex.Match(page, $@"^\| {shape} \| (\d+) \|", RegexOptions.Multiline);
if (!quoted.Success)
{
wrong.Add($"docs/best-practices/CQRS.md has no row for {shape}");
}
else if (int.Parse(quoted.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) != actual)
{
wrong.Add($"docs/best-practices/CQRS.md says {quoted.Groups[1].Value} {shape} and this build has {actual}");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
}
Live from api/TheYard.Tests/CqrsTests.cs, region cqrs-tests, read from this build at 99df7a8.
How the rule reads a port
A port's name is a promise and nothing checks a promise. From 1.0.4.68 the rule reads what a port can do: every type a query handler takes by constructor, among this codebase's own, is read by reflection with every interface it inherits, and a member whose name starts with a writing verb (Keep, Write, Save, Upsert, Delete, Add, Remove, Record, Put or Set) makes it a port that writes. A query handler handed one is red, whatever the port is called. The name check stays beside it.
[Fact]
public void A_query_handler_is_handed_no_port_that_can_write()
{
var wrong = HandlerTypes()
.Where(handler => Contracts(handler).Any(contract => contract.Query))
.SelectMany(handler => handler.GetConstructors().SelectMany(constructor => constructor.GetParameters())
.Select(parameter => (handler, parameter, writes: WritingMembers(Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType)))
.Where(found => found.writes.Count > 0)
.Select(found => $"{found.handler.Name} takes {found.parameter.ParameterType.Name} {found.parameter.Name}, which can {string.Join(", ", found.writes)}; a query takes a port that only reads"))
.Where(line => !ExemptReaders.Any(exempt => line.StartsWith(exempt.Key + " ", StringComparison.Ordinal)))
.ToList();
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
private static readonly Regex WritingVerb = new(@"^(Keep|Write|Save|Upsert|Delete|Add|Remove|Record|Put|Set)(?=[A-Z_]|$)", RegexOptions.Compiled);
private static readonly Dictionary<string, string> ExemptReaders = new(StringComparer.Ordinal);
private static List<string> WritingMembers(Type port)
{
if (port.Namespace?.StartsWith("TheYard.", StringComparison.Ordinal) != true)
{
return [];
}
IEnumerable<Type> contracts = port.IsInterface ? port.GetInterfaces().Prepend(port) : [port];
return [.. contracts
.SelectMany(contract => contract.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly))
.Where(member => member is not MethodInfo { IsSpecialName: true } && WritingVerb.IsMatch(member.Name))
.Select(member => member.Name)
.Distinct(StringComparer.Ordinal)
.Order(StringComparer.Ordinal)];
}
Live from api/TheYard.Tests/CqrsTests.cs, region a-reader-is-known-by-what-it-can-do, read from this build at 99df7a8.
The counts this build has
Read back by CqrsTests on every build, so a number here cannot go stale.
The Function finds its read-only use cases rather than being told them
The job hunt's Function answers no request, so it has no query to name and no handler to count. The half
of this page that does carry over is the half that matters: a use case that only reads cannot write. Its
ports are split for it - IMergeStore extends IShareReader, IInbox extends IInboxReader - and the
reading use cases take the reading halves.
Until 1.0.4.126 that rule ran over a dictionary of two names kept by hand in the Function's CqrsTests,
which made it exactly as good as somebody's memory: a new use case that reads the share and is handed the
writing half of its port was never asked the question, because it was not in the dictionary. A rule whose
subject is a list only covers the list.
So the subject is read from the build. tests/rules/UseCaseRule.cs asks the ring which types are handed a
port, and asks the compiled code which of them write; the rule runs over the ones that do not. It finds the
same two the dictionary named, which is the point - the number did not change, the way of arriving at it
did, and the next read-only use case is covered the moment it is written.
Whether a use case writes is read from its code and never from its name, and two hops make that harder
than scanning one method body. The first is the state machine: an async method's own body is builder
plumbing, and the calls a reader sees in the source live in the MoveNext of a nested compiler-generated
type that the builder starts generically, so no call instruction joins the two. The second is delegation:
TrackerMerger is handed the writing port and calls nothing that writes, because it makes a MergeContext
and the merge steps and lets them write. Measured one method deep it reads as a use case that only reads
holding a port that writes - this rule's own failure message, aimed at the type whose whole job is writing.
So writes travel backwards along the calls a method makes, over methods rather than types: collapsed to
types, MergerHealth would read as a writer for calling TrackerMerger.IsSpoolFile, a static that tests a
file name.
public static class UseCaseRule
{
public sealed record Handed(Type Port, string Where, string Name, IReadOnlyList<string> Writes);
public sealed record UseCase(Type Type, IReadOnlyList<Handed> Ports, bool Writes);
public static List<UseCase> Discover(Assembly ring, string writingVerbs)
{
var verb = new Regex("^(" + writingVerbs + ")(?=[A-Z_]|$)", RegexOptions.Compiled);
string family = Family(ring);
var writers = Writers(ring.Location, family, verb);
return [.. ring.GetTypes()
.Where(type => !type.IsInterface && !type.IsEnum && type.DeclaringType is null && !type.Name.StartsWith('<'))
.Select(type => new UseCase(type, Ports(type, family, verb), writers.Contains(type.FullName ?? type.Name)))
.Where(found => found.Ports.Count > 0)
.OrderBy(found => found.Type.Name, StringComparer.Ordinal)];
}
public static List<string> ReadOnlyCasesHandedAWrite(Assembly ring, string writingVerbs) =>
[.. Discover(ring, writingVerbs)
.Where(found => !found.Writes)
.SelectMany(found => found.Ports
.Where(port => port.Writes.Count > 0)
.Select(port => $"{found.Type.Name} only reads and takes {port.Port.Name} {port.Name} by {port.Where}, which can {string.Join(", ", port.Writes)}; a use case that only reads takes the reading half"))
.Distinct(StringComparer.Ordinal)
.Order(StringComparer.Ordinal)];
private static string Family(Assembly ring) => (ring.GetName().Name ?? "").Split('.')[0] + ".";
private static bool Ours(string? space, string family) => space?.StartsWith(family, StringComparison.Ordinal) == true;
private static bool IsPort(Type type, string family) =>
Ours(type.Namespace, family) && !type.IsEnum
&& (type.IsInterface || (type.IsClass && type.GetMethod("<Clone>$", BindingFlags.Public | BindingFlags.Instance) is null));
private static List<Handed> Ports(Type type, string family, Regex verb)
{
static Type Bare(Type type) => Nullable.GetUnderlyingType(type) ?? type;
bool Written(MemberInfo member) =>
member is not MethodInfo { IsSpecialName: true }
&& member.GetCustomAttribute<CompilerGeneratedAttribute>() is null
&& verb.IsMatch(member.Name);
List<string> Writes(Type port)
{
IEnumerable<Type> contracts = port.IsInterface ? port.GetInterfaces().Prepend(port) : [port];
return [.. contracts
.SelectMany(contract => contract.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly))
.Where(Written)
.Select(member => member.Name)
.Distinct(StringComparer.Ordinal)
.Order(StringComparer.Ordinal)];
}
var taken = new List<(Type Port, string Where, string Name)>();
foreach (var maker in type.GetConstructors())
{
taken.AddRange(maker.GetParameters().Select(parameter => (Bare(parameter.ParameterType), "its constructor", parameter.Name ?? "?")));
}
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(method => !method.IsSpecialName && method.GetCustomAttribute<CompilerGeneratedAttribute>() is null))
{
taken.AddRange(method.GetParameters().Select(parameter => (Bare(parameter.ParameterType), method.Name, parameter.Name ?? "?")));
}
return [.. taken
.Where(found => IsPort(found.Port, family))
.DistinctBy(found => found.Port.FullName + " " + found.Name, StringComparer.Ordinal)
.Select(found => new Handed(found.Port, found.Where, found.Name, Writes(found.Port)))];
}
private static HashSet<string> Writers(string module, string family, Regex verb)
{
using var read = ModuleDefinition.ReadModule(module);
var all = read.GetTypes().SelectMany(type => type.Methods).ToList();
var calls = all.ToDictionary(method => method, _ => new List<MethodDefinition>());
var writes = new HashSet<MethodDefinition>();
MethodDefinition? Here(MethodReference called)
{
try
{
var found = called.Resolve();
return found is not null && found.Module == read ? found : null;
}
catch (AssemblyResolutionException)
{
return null;
}
}
foreach (var method in all)
{
foreach (var built in method.CustomAttributes
.Where(attribute => attribute.AttributeType.Name is "AsyncStateMachineAttribute" or "IteratorStateMachineAttribute")
.Where(attribute => attribute.ConstructorArguments.Count > 0)
.Select(attribute => (attribute.ConstructorArguments[0].Value as TypeReference)?.Resolve())
.OfType<TypeDefinition>())
{
calls[method].AddRange(built.Methods.Where(calls.ContainsKey));
}
if (!method.HasBody)
{
continue;
}
foreach (var called in method.Body.Instructions.Select(instruction => instruction.Operand).OfType<MethodReference>())
{
if (Ours(called.DeclaringType.Namespace, family) && verb.IsMatch(called.Name))
{
writes.Add(method);
}
if (Here(called) is { } target)
{
calls[method].Add(target);
}
}
}
var owners = new HashSet<string>(StringComparer.Ordinal);
foreach (var start in all.Where(method => !owners.Contains(Outermost(method.DeclaringType))))
{
var seen = new HashSet<MethodDefinition> { start };
var waiting = new Queue<MethodDefinition>([start]);
while (waiting.Count > 0)
{
var at = waiting.Dequeue();
if (writes.Contains(at))
{
owners.Add(Outermost(start.DeclaringType));
break;
}
foreach (var next in calls[at].Where(seen.Add))
{
waiting.Enqueue(next);
}
}
}
return owners;
}
private static string Outermost(TypeReference type)
{
var owner = type;
while (owner.DeclaringType is { } holder)
{
owner = holder;
}
return owner.FullName;
}
}
Live from tests/rules/UseCaseRule.cs, region use-case-rule, read from this build at 99df7a8.
Read back by the Function's CqrsTests on every build, so these two cannot go stale either.
What this codebase does not do, and why
No second store for reads, no events between a write side and a read side, no event sourcing and no
bus. Martin Fowler's page warns that for most systems the full pattern adds risky complexity and keeps
it to the parts of a system that need it (CQRS), and
Microsoft's pattern page is plain that the basic form shares one store and that separate stores bring
synchronisation and data that can be behind
(CQRS pattern). Here each store
answers a page of a hundred thousand vehicles inside the site's budget, and the bid that changes a
price has to be read back at once by the buyer who placed it. Two stores would buy nothing this site
needs and cost the one thing a bid must have, a price that is current. The Admin tab's 24 reads became
queries in 1.0.4.43; what is still exempt is the host serving its own files, its health and its error
rings, fifteen routes named in HandlerRuleTests with the reason for each.