The walk
The files are found by walking up
The dataset, the README, the docs and the photo manifest are located once, at startup, in
Composition/HostPaths.cs. The API does not assume a fixed folder depth, because it is started from three
places: dotnet run from the project folder, the test host from bin/Debug/..., and the published image
from /app. FindUpward walks from the content root toward the disk root until it finds the named file,
and throws a clear FileNotFoundException if it never does. HostPaths is registered, so an endpoint that
serves a file asks for it as a parameter.
private static string FindUpward(string startDirectory, string relativePath)
{
for (var dir = new DirectoryInfo(startDirectory); dir is not null; dir = dir.Parent)
{
string candidate = Path.Combine(dir.FullName, relativePath);
if (File.Exists(candidate))
{
return candidate;
}
}
throw new FileNotFoundException($"Could not locate {relativePath} in or above {startDirectory}");
}
Live from api/TheYard.Api/Shared/Wiring/HostPaths.cs, region find-upward, read from this build at 99df7a8.
The table of contents
What the file is today:
56 total
12 comment
7 blank
37 code, across 0 endpoints
No route is mapped in Program.cs itself. Until 1.0.3.39 it was one file of 2,667 lines holding 48
endpoints; the record that replaced that decision says what changed and holds the new shape with a test.
var builder = WebApplication.CreateBuilder(args);
var paths = HostPaths.Find(builder.Environment.ContentRootPath);
var build = new BuildInfo(builder.Configuration["APP_VERSION"] ?? "dev", builder.Configuration["APP_COMMIT"] ?? "local");
var identity = HostIdentity.From(builder.Configuration);
builder.Services.AddSingleton(paths);
builder.Services.AddSingleton(build);
builder.Services.AddSingleton(identity);
var stores = await builder.AddTheYardStoresAsync(paths, CancellationToken.None);
builder.AddTheYardObservability(stores.Backends, stores.Document, stores.SqlLog, stores.StoreLog, stores.Accessor, stores.CurrentRequest);
builder.AddTheYardSessions();
builder.AddTheYardActivity(stores.Backends, stores.Document, stores.Relational);
builder.AddTheYardApi(build);
builder.AddTheYardTelemetry(identity);
builder.AddTheYardAdmin(stores.Relational, build, identity);
builder.AddTheYardCosts(identity, stores.Relational);
builder.AddTheYardUsage();
var modules = Modules.InThisHost();
foreach (var module in modules)
{
module.Register(builder.Services, builder.Configuration);
}
builder.AddTheYardStartup(identity);
builder.AddTheYardHostedSites();
var app = builder.Build();
await app.MountTheHostedSitesAsync(app.Lifetime.ApplicationStopping);
app.UseTheYardRequestPipeline(paths, identity);
Live from api/TheYard.Api/Program.cs, region composition, read from this build at 99df7a8.
No class, no Main
The file uses top-level statements: C# lets the entry file read like a script, and the compiler writes
the Program class and Main around it. The one visible trace is the last line,
public sealed partial class Program;, which exists so the integration tests can name the class when they
boot the host in memory with WebApplicationFactory<Program>.
public sealed partial class Program;
Live from api/TheYard.Api/Program.cs, region records-and-test-hook, read from this build at 99df7a8.
What the steps hand one another
Registration is a sequence, and a later step needs what an earlier one made: the accounts need the
signing key, the kept log needs the stores, the page sweep needs the build's version. YardComposition
carries those between the steps, filled once at startup and never read by a request except through what
was registered. It is the one class in the composition with state, which is why it lives beside the other
state types at the project's root and not in Composition/, where every class is static.
The stores come first
builder.AddTheYardStoresAsync (Composition/StoreRegistration.cs) is the only step that waits: it brings
both stores up before anything is registered, because the answer decides what gets registered. The
relational store is SQL Server when the deploy gave one and SQLite otherwise; the document store is there
when an account is configured; each stands behind the same ports, on the JSON files until it comes up, and
a store that refused at startup is asked again every thirty seconds for an hour (the second chance).
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);
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),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
services.GetRequiredService<YardDbContext>(),
services.GetService<IdentityErrorDescriber>()));
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);
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.
Nearly every registration in the steps is AddSingleton, one instance for the life of the process,
because the dataset is loaded once and shared by every request and each store's standing bids live in
memory beside it. InventoryService holds the expanded dataset in a Lazy, so a Scoped registration
would expand 100,000 records per request. The two exceptions are decided per request and can only be:
CurrentBackend, which store this request is on, and Identity's user store over it.
The rest of the registrations
Each is one file and one method, in the order the host needs them:
AddTheYardObservability (Composition/ObservabilityRegistration.cs): the rings behind the Admin tab,
the kept log, and the request hook that files every request once.
AddTheYardSessions and AddTheYardAccounts (Composition/AuthRegistration.cs): the signing key and the
session issuer first, because the activity feature keys visitor tokens with the same key; then Identity
and the JWT read back from its cookie.
AddTheYardActivity (Composition/ActivityRegistration.cs) and AddTheYardEmail
(Composition/EmailRegistration.cs): the collectors that write off the request path, and the one email.
AddTheYardApi (Composition/ApiRegistration.cs): snake_case bodies, one ProblemDetails for every
failure, one log line per request, and the OpenAPI document.
AddTheYardTelemetry and AddTheYardAdmin: Application Insights where it is configured, and what the
Admin tab reads that is not a ring.
Started before it serves
app.StartTheYardAsync (Composition/Startup.cs) runs after Build() and before anything is served: the
loggers attached, a store that did not come up said out loud, and the default store's catalogue and bids
loaded and timed. If the dataset is missing or malformed the process exits with the real error, the
container's health check fails, and the deploy's verify step stops the roll, which is a better place to
learn it than a 500 on the first visitor.
Middleware order, the part that bites
app.UseTheYardRequestPipeline (Composition/RequestPipeline.cs) holds every piece of middleware in one
method, in the order it runs, with the reason beside each. Timing is outermost, so a failed request is
recorded with the status that was actually sent; then the problem shape, the request log, the user, the
session's renewal, the store's warmth, the error record, the cache rules, and the files last. Endpoints
run at the end of the pipeline whichever line maps them, so the order that matters is the order in this
one file.
app.Use(async (context, next) =>
{
long start = Stopwatch.GetTimestamp();
recorder.MarkOperator(context);
context.Response.OnStarting(() =>
{
context.Response.Headers["Server-Timing"] = string.Create(
System.Globalization.CultureInfo.InvariantCulture,
$"app;dur={Stopwatch.GetElapsedTime(start).TotalMilliseconds:0.#}");
return Task.CompletedTask;
});
try
{
await next();
}
finally
{
recorder.Record(context, Stopwatch.GetElapsedTime(start));
}
});
Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region request-timing, read from this build at 99df7a8.
app.Use(async (context, next) =>
{
try
{
await next();
if (context.Response.StatusCode >= 500)
{
errorLog.Record(context.Request.Path, context.Response.StatusCode, "server error response");
}
}
catch (Exception ex)
{
if (!ProblemHandler.CallerLeft(context, ex))
{
errorLog.Record(context.Request.Path, 500, ex.GetType().Name, StackFrames.Of(ex));
}
throw;
}
});
Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region error-log, read from this build at 99df7a8.
Endpoints: binding, then delegation
Each feature is a static class under Endpoints/ with one Map...Endpoints method and private, named
handlers: VehicleEndpoints, BidEndpoints, DocumentationEndpoints, HealthEndpoints, ErrorEndpoints,
AdminEndpoints, AccountEndpoints, and ReferenceEndpoints for the OpenAPI document and its page. A
handler binds the request, calls the service that owns the rule, and shapes the reply; the rules live in
Domain and Application. A handler's return type is a Results<...> union or a typed result, which is what
the OpenAPI document reads, so naming the handlers changed nothing a client sees.
private static async Task<Results<Ok<VehiclePage>, ProblemHttpResult>> List(
SearchVehiclesHandler handler,
[AsParameters] VehicleQueryParams query,
CancellationToken cancellation)
{
if (!query.TryBuildFilter(out var filter, out var clock, out var sort, out var error))
{
return TypedResults.Problem(detail: error, statusCode: 400, title: "The query could not be read");
}
var result = await handler.HandleAsync(new SearchVehiclesQuery(filter, clock, sort, query.EffectiveLimit, query.EffectiveOffset), cancellation);
return TypedResults.Ok(new VehiclePage(result.Total, [.. result.Vehicles.Select(v => VehicleWire.ToWire(v, clock))]));
}
Live from api/TheYard.Api/Features/Vehicles/VehicleEndpoints.cs, region inventory-endpoint, read from this build at 99df7a8.
The two bid endpoints share one method, HandleBid, which answers three questions in order: is this
session on this store, does the vehicle exist, does the domain accept the action, on the server's clock.
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));
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))),
};
Live from api/TheYard.Api/Features/Bids/BidEndpoints.cs, region bid-handling, read from this build at 99df7a8.
Liveness, readiness, and the Admin tab
/healthz answers "ok" if the process is up; the container's HEALTHCHECK asks it. /readyz runs the
checks that gate traffic and answers 503 until the files the app needs are in place; the deploy's verify
step asks it. /api/health returns every check with its timing for the Admin tab.
app.MapGet("/healthz", Liveness)
.WithName("Liveness")
.WithTags("Health")
.WithSummary("Is the process up")
.WithDescription("The container's own health check. Answers ok the moment the process is listening and says nothing else.")
.Produces<string>(StatusCodes.Status200OK, "text/plain")
.ShortCircuit();
app.MapGet("/readyz", Readiness)
.WithName("Readiness")
.WithTags("Health")
.WithSummary("Should traffic be sent here")
.WithDescription("The deploy's verify step. Only the checks that gate readiness run, and the database is not one "
+ "of them: a container whose store is gone still serves the catalogue from files.")
.Produces<string>(StatusCodes.Status200OK, "text/plain")
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ShortCircuit();
app.MapGet("/api/health", Health)
.WithName("GetHealth")
.WithTags("Health")
.WithSummary("Every check, timed, and the build that answered")
.WithDescription("The Admin tab's health card. One check per store, named by the store, so a container running "
+ "both says which one is unavailable.");
Live from api/TheYard.Api/Features/Health/HealthEndpoints.cs, region probes, read from this build at 99df7a8.
The single-page app, last
app.MapTheYardSpa (Composition/SpaRegistration.cs) answers any address that is not an API route or a
real file with index.html, so a missing bundle file is a 404 and never a page dressed as a script.
app.MapFallbackToFile("{*path:nonfile}", "index.html");
Live from api/TheYard.Api/Shared/Wiring/SpaRegistration.cs, region spa-fallback, read from this build at 99df7a8.
Addendum, 2026-09-08: two stores in one file
The walk above still reads top to bottom, and two of its stops changed shape
when the document store moved in beside the relational one (ADR: One
container, both stores).
The persistence region no longer chooses a store. It reads both settings, the
SQL connection string and the Cosmos DB endpoint, and creates the two rings
and the request describer early, because the interceptor that feeds the SQL
ring is attached to a context factory built by hand before the container
exists. The migrate-and-seed region then builds one Backend per store: the
relational one always, the document one when there is an endpoint, each
brought up and timed on its own, each holding its own InventoryService,
BidService and MarketService, and each saying how to build Identity's
store over its accounts. The three services left the container entirely; an
endpoint takes CurrentBackend, which is scoped to the request and resolved
once from the request's header, cookie or the container's default.
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);
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),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
services.GetRequiredService<YardDbContext>(),
services.GetService<IdentityErrorDescriber>()));
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);
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.
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
cosmos = CosmosConnection.Connect(
configuredCosmos!,
builder.Configuration["Cosmos:Database"] ?? "theyard",
builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
AzureIds.ClientId(builder.Configuration),
storeLog);
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;
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),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
StoreAttachment CosmosAttachment(DatabaseState state) => new(
state,
new DocumentDiagnostics(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.
Identity is registered once and unconditionally; its store is the one thing
about it chosen per request. The health check runs one database probe per
store. The metrics endpoint answers the store the request is on at the top
level, as it always did, and lists every store below it. And two endpoints
were added for the toggle at the top of the page.
app.MapGet("/api/stores", AdminObservabilityRoutes.Stores)
.WithName("GetStores")
.WithTags("Stores")
.WithSummary("Which stores this container runs, and which one this request is on")
.WithDescription("A request names a store with the X-Yard-Store header (sql or cosmos) or gets the site's default. "
+ "The other site, if there is one, is the same code with the other default.");
Live from api/TheYard.Api/Features/Admin/Operations/AdminEndpoints.cs, region stores-endpoints, read from this build at 99df7a8.
The numbers in the section above are the file's numbers on the day this
addendum was written; the test that holds them to the file does not care
which day that was.