Onboarding guide
16. Aspire Orchestration & Service Defaults
This chapter covers the hosting boundary: how the distributed MMCA system is composed and run, locally as a single dotnet run, and in Azure Container Apps (ACA) as a set of independent revisions. Four distinct concerns live side by side here, and it pays to separate them up front. AppHost-side code (MMCA.Common.Aspire.Hosting, MMCA.ADC.AppHost) is the orchestrator: it declares the resource graph, containers, databases, broker, the four services, the gateway, the UI, and wires their dependencies. Service-side code (MMCA.Common.Aspire) is the baseline every running process opts into: OpenTelemetry, health checks, service discovery, HTTP resilience, Kestrel listener profiles, startup warm-up, Redis wiring, Serilog, a startup tripwire that fails a host whose configuration asks for a cloud-vendor capability no adapter call registered, and hardened security headers. Edge-side code (MMCA.Common.Aspire.Gateway) is the small kit a reverse-proxy host adds on top: correlation, an edge rate limiter, and per-downstream readiness. YARP building blocks (MMCA.Common.Gateway) are the fourth: cluster request profiles, destination health-check defaults, route/cluster trace headers, named per-route limiter policies, header hygiene on the proxied request, an opt-in connect-failure retry, and the forwarded-headers step, all applied on top of whatever route table the host loaded. The AppHost and service assemblies are deliberately kept apart so a running service never drags in the full Aspire.Hosting tooling graph (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:14-18), and the service-side package carries exactly one first-party project reference, MMCA.Common.Shared, taken solely so the resilience constants have one home (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/MMCA.Common.Aspire.csproj:57-59). The gateway package goes further: it has no project reference at all and one runtime package, YARP (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/MMCA.Common.Gateway.csproj:15), because the host it serves has no application container to share. ADC has no app-local ServiceDefaults project: all four services, the Gateway, and the Blazor UI host consume MMCA.Common.Aspire's AddServiceDefaults() directly (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:123, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:111, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:99, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:101, MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:77, MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:60). Everything in this group is plumbing, but it is the plumbing that makes ADR-006 (database-per-service), ADR-008 (service topology + YARP), ADR-009 (resilience / RTO-RPO), and ADR-041 (observability and telemetry) real at runtime rather than aspirational.
The orchestrator: declaring the resource graph
When you run dotnet run --project Source/Hosting/MMCA.ADC.AppHost, Aspire executes Program.cs top to bottom, building a resource model rather than starting anything immediately. It declares a persistent SQL Server container (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:15), four databases on it (ADC_Identity / ADC_Conference / ADC_Engagement / ADC_Notification, Program.cs:37-40), Redis (:44), a broker chosen in one call at :98, and a MailDev SMTP container (:106), then the four service projects, each wired by one WithMmcaServiceInfrastructure call (:137, :159, :197, :222), the YARP Gateway with its HTTPS endpoint pinned to port 6001 (:364), and the Blazor UI pinned to 6002 (:394). All of the cross-cutting wiring vocabulary lives in one reusable, cross-app namespace, MMCA.Common.Aspire.Hosting, whose core is the Extensions static class (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:24). It supplies the fluent helpers, grouped into C# extension(T) blocks by the resource type they attach to (primer §4): the three provisioning helpers AddMailDev (:201), AddMessageBroker (:220) and AddServiceBusEmulatorBroker (:261); the two WithBroker overloads (:312 for RabbitMQ, :341 for the emulator); WithJwksDiscovery (:370); the five CI and local-run switches WithE2eRsaKeys (:414), WithE2eRegistrationThrottleLift (:456), WithE2eForceServer (:490), WithE2eForceWebAssembly (:514) and WithE2eGatewayRateLimitLift (:548); and the per-engine data-source helpers WithSQLServerDataSource (:587), WithPostgreSQLDataSource (:617), WithCosmosDataSource (:646) and WithSqliteDataSource (:671), the last three added for polyglot persistence (ADR-018).
.WithSQLServerDataSource(db, "Conference") (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:587) is the AppHost manifestation of ADR-006: in one fluent chain it adds .WithReference(database), .WaitFor(database), and injects a single connection-string env var, DataSources__{logicalName}__SQLServerConnectionString (Extensions.cs:595-598). That one entry is the whole configuration: with no top-level connection string the single database a host declares this way also becomes its Default source, so the framework's own tables and the readiness health check both resolve from it, and the logical name collapses onto Default, leaving one context, one change tracker and one migration set per service (the method's own doc comment, :571-582). The routing types that consume those env vars, DataSourceResolver and EntityDataSourceRegistry, live in the persistence group. The ADC AppHost does not call it directly: it is the first link of the shared per-service chain below (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:74), which ADC applies once per service (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:137,159,196,221). This paragraph is where [Rubric §8, Data Architecture] (each service owns its store, with no shared write path) meets [Rubric §7, Microservices Readiness] (the topology is a declaration in one file, not a rewrite).
The per-service chain is itself framework code, and so is the front door. ServiceInfrastructureExtensions (Level 2, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:16) exposes one method, WithMmcaServiceInfrastructure(database, logicalName, cache, mailServer, attachBroker, profile, probeEndpointName) (:57), which applies, in order, the service's own database, a reference to the cache, the selected broker through the delegate AddSelectedBroker returns, a wait on the cache and a wait on the mail server (:73-78), then the startup probe its ServiceEndpointProfile argument picks (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceEndpointProfile.cs:7): Http2Only (:13) gets WithH2cHealthCheck on the http endpoint unless another is named, and Mixed (:19) gets Aspire's stock WithHttpHealthCheck, both on /alive (ServiceInfrastructureExtensions.cs:80-84). Its remarks fix three rules every host inherits (:27-43): service endpoints stay internal because a backend is reached through the gateway, the probe is always liveness and never readiness, and no project resource is referenced, so the project-to-project edge set is exactly what the host declares itself. GatewayUiExtensions (Level 2, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/GatewayUiExtensions.cs:16) is the front-door twin: WithMmcaGateway(httpsPort, services) (:40) references and waits for each service, marks the gateway's endpoints external, probes /alive and pins its https port (:47-56); WithMmcaUi(gateway, httpsPort, services) (:88) references and waits for the gateway, then only waits for each service, because the UI calls every API through the gateway and a service reference would plant a discovery name nothing resolves (:70-75, :97-105), and gates on /health/ready (:108), which is safe only because nothing waits for the UI (:77-82); and WithGatewayApiEndpoints(gateway) (:128) sets both Api__ApiEndpoint and Api__WasmApiEndpoint to the gateway's https endpoint (:133-137), the second because it is the URL the browser is handed and a browser cannot resolve a service-discovery name, the first because a SignalR HubConnection builds its own message handler and never sees the discovery handler (:116-124). IdentityLinkExtensions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/IdentityLinkExtensions.cs:23) hands Identity the addresses it cannot know itself: WithUiLinks(ui) (:74) roots the OAuth redirect base and the password-reset, email-confirmation and sign-in links at the UI's https endpoint (:79-91), and WithIssuer(gateway) (:100) sets Jwt__Issuer to the gateway's (:105). This package references none of the packages that own those settings, so the section and property names are internal mirrors (:25-50) that the hosting tests cross-assert against their owners (:12-17), and EnvironmentKey (:61-62) turns a section and property into the __ form configuration binds. ServiceTokenExtensions (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceTokenExtensions.cs:22) does the same for the local gRPC service-token signing key (ADR-061, :8-16): AddServiceTokenSigningKey() (:46) adds a secret parameter that, when configuration supplies none, is generated (64 letters and digits) and persisted to the AppHost's user secrets (:51-55) under the slot existing AppHosts already used (DefaultSigningKeyParameterName, :28), and WithServiceTokenSigningKey(signingKey) (:67) hands that parameter to one service as Grpc__ServiceToken__SigningKey (:72-74). MmcaReplicas (Level 4, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/MmcaReplicas.cs:24) is the local multi-replica opt-in: FromEnvironment(variableName) (:33) reads a count that falls back to 1 when unset, unparsable, or 1 or less (:37-43), and WithMmcaReplicas(replicas, distributedRateLimiting) (:63) is a no-op at 1 and otherwise runs the service at that many replicas, adding RateLimiting__Distributed=true when asked so a per-user limit does not multiply by the replica count (:67-76). Its remarks state the limit of what such a run proves: Aspire's proxy balances per TCP connection, so pooled HTTP/2 connections tend to pin to one replica, and a run proves correctness under concurrency, not capacity (:14-18). ADC applies all of them: the token key to Identity, Engagement and Notification (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:243-246), ADC_REPLICAS to the four services with the distributed limiter and to the gateway without it, whose edge limiters stay per replica (:449-454), and the gateway API endpoints and the UI links last (:469, :477).
The remaining AppHost helpers complete that vocabulary. AddMessageBroker() (Extensions.cs:220) provisions RabbitMQ with the management plugin in a single call (:224), defaulting the resource name to the DefaultBrokerResourceName constant, rabbitmq (:29); WithBroker(broker) (:312) attaches a service to it with .WithReference(broker), .WaitFor(broker) and MessageBus__Provider=RabbitMq (:318-321), the env var that the consuming service's AddBrokerMessaging reads to select RabbitMQ over InProcessMessageBus (selection driven by MessageBusProviders / MessageBusSettings, ADR-066). AddMailDev() (:201) provisions the local SMTP sink from an image pinned to 3.0.0 (MailDevImageTag, :178) with a persistent lifetime so the captured inbox survives an AppHost restart (:207), on two fixed host ports, 1080 for the web UI and 1025 for SMTP (:208-209), because a developer opens the first by hand and every consumer's Smtp:Port setting names the second (:187-191). The two numbers live in MailDevDefaults (Level 0, MMCA.Common/Source/Build/MailDev/MailDevDefaults.cs:17, HttpPort at :20, SmtpPort at :23), re-exposed as MailDevHttpPort and MailDevSmtpPort (Extensions.cs:163,169): one internal source file compiled into both this package and MMCA.Common.Testing.E2E through a linked Compile Include, because a shared reference would make the E2E package depend on the Aspire hosting SDK, or the hosting package on Playwright, for two integers (MailDevDefaults.cs:10-16). WithJwksDiscovery(identity, gateway?) (Extensions.cs:370) references and waits for Identity (:377-379) and sets Authentication__JwtBearer__Authority (:396) so the consuming service validates RS256 tokens against Identity's published keys (IJwksProvider / RsaJwksProvider). The non-trivial part, captured in a long inline comment (:382-392), is that it prefers the gateway endpoint over Identity's (:393-395): the three REST services run HTTP/2-only on cleartext (h2c) so gRPC clients can use prior-knowledge negotiation, but the default JwtBearer backchannel HttpClient speaks HTTP/1.1, which Kestrel rejects on an HTTP/2-only endpoint. Routing the JWKS and /.well-known/* fetch through the gateway (which terminates TLS and supports both protocols via ALPN, ADR-008) makes the default backchannel work end-to-end without weakening the services (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:374-376). The other half of that contract is identityService.WithIssuer(gateway) (Program.cs:386, the IdentityLinkExtensions helper above): the issuer Identity stamps into every token it signs is derived from the same gateway endpoint, so an Aspire run cannot mint wrong-issuer tokens if the pinned port ever moves. That is the runtime embodiment of the cross-service token validation boundary in ADR-004, with the transport caveat spelled out in ADR-012.
The E2E switches are the CI-shaped siblings, and every one is a no-op unless its trigger variable is set, so ADC calls all five unconditionally (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:230,410,418,424,431). WithE2eRsaKeys() (Extensions.cs:414) forwards an ephemeral RSA keypair from E2E_JWT_PRIVATE_KEY_PEM / E2E_JWT_PUBLIC_KEY_PEM (read at :418-419) onto Identity's Jwt__RsaPrivateKeyPem / Jwt__RsaPublicKeyPem / Jwks__RsaPublicKeyPem (:425-428), returning untouched when either variable is absent (:420-423), so locally and in production user-secrets or Key Vault supply the keys. WithE2eRegistrationThrottleLift() (:456) raises Identity's per-IP registration cap to the E2eRegistrationsPerIpPerHour constant of 1000 (:36) and its per-IP auth limiter to E2eAuthIpPermitLimit, 100000 (:94), injected as LoginProtection__MaxRegistrationsPerIpPerHour and RateLimiting__AuthIpPermitLimit (:462-470): a Playwright suite registers far more than ten accounts from one localhost IP, and with passkeys offered every visit to the login page spends one auth-ip permit before the login spends another, so without the lift the anti-abuse controls refuse the suite and the failures look like broken registration (:432-447). WithE2eGatewayRateLimitLift() (:548) is the gateway-side twin: it raises the edge limiter to 100000 permits and 10000 concurrent requests and the named auth-tight route policy to 100000 (:75, :81, :87, injected at :559-568), because the whole suite arrives from one loopback IP and both the per-IP window and the anti-credential-stuffing policy read it as the flood they exist to stop (:531-537). Both lifts fire on E2E_LIFT_REGISTRATION_THROTTLE (:43) or on a forced-WebAssembly run, which implies the same volume (:460, :552). Note what those env-var keys are built from: the package's own internal constants (RateLimitingSection at :102, GatewayRateLimitingSection at :112, MmcaGatewaySection at :119, AuthTightPolicyName at :126) rather than the settings types, which this AppHost-tier package does not reference. The UI pair picks the render mode for a run. WithE2eForceServer() (:490) sets E2E__ForceServer=true (E2eForceServerConfigurationKey, :55) when E2E_FORCE_SERVER (:49) reads true, pinning the UI host to InteractiveServer because under InteractiveAuto the post-login page load switches to the background-downloaded WASM runtime, whose boot on a shared 2-core CI runner exceeds every suite wait (:477-481). WithE2eForceWebAssembly() (:514) is the local-run opposite: it sets E2E__ForceWebAssembly=true (:69) when E2E_FORCE_WASM (:63) is true, so every interactive page boots the WebAssembly runtime and the client render path is exercised end to end (:502-506, written at :518-520). When both are set, forced WebAssembly wins, because the force-server switch then writes nothing (:494). The PostgreSQL, Cosmos and SQLite siblings (Extensions.cs:618,648,674) inject the equivalent per-engine connection-string env vars (ADR-018) and are layered on top of, not instead of, the SQL Server source; the ADC AppHost wires none of them.
Broker parity: RabbitMQ by default, the Service Bus emulator on demand
RabbitMQ is a different broker from the one production runs, so anything that only misbehaves on Azure Service Bus (entity-name limits, topic and subscription provisioning, scheduled redelivery pacing) is invisible in the inner loop. AddServiceBusEmulatorBroker(sqlServer) (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:261) closes that divergence for a host that opts in: it declares a ServiceBusEmulatorResource (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceBusEmulatorResource.cs:32) from the official image pinned to tag 2.0.1 (Extensions.cs:150,274-275), publishes both of the emulator's planes (AMQP on container port 5672 and the HTTP management plane on 5300, ServiceBusEmulatorResource.cs:41,44, wired at Extensions.cs:276-282), accepts the EULA the image demands (:287), points it at the existing SQL Server resource for its own state rather than starting a second engine (:288-293), and waits for that SQL Server because the emulator's first act is to create its schema (:295-297). The image tag floor is not cosmetic: the HTTP management plane shipped in emulator 2.0.0, and the Azure Service Bus transport provisions its own topology when its receiver starts, so a broker with no admin plane is not usable at all (ServiceBusEmulatorResource.cs:11-15). The resource's ConnectionStringExpression ends in UseDevelopmentEmulator=true (:66-68), the marker MMCA.Common.Azure's Service Bus transport detects to take its emulator branch, which a real connection string never carries (:18-23), and AdminEndpointExpression (:81-83) is the second address that transport needs to build its administration client on the emulator (:70-74). The matching WithBroker overload (Extensions.cs:341) sets MessageBus__Provider=AzureServiceBus plus those two settings as MessageBus__ConnectionString and MessageBus__EmulatorAdminEndpoint (:347-352). One deliberate gap is recorded in the resource's own doc comment (ServiceBusEmulatorResource.cs:25-30): it declares no health check, so a WaitFor on it gates on the container running rather than on the emulator finishing warm-up, and the consuming service absorbs the remainder because the transport's receiver provisions and connects in the background, retrying, rather than failing host startup.
The choice itself is framework code as well. BrokerSelection (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/BrokerSelection.cs:25) owns everything except the variable's name, which stays in the app's AppHost (:13-19). IsServiceBusSelected(environmentVariableName) (:36) answers true only when that variable reads the ServiceBusSelection constant, servicebus (:28), compared case-insensitively (:40-43), so unset or any other value keeps RabbitMQ. Because the two WithBroker overloads take different resource types, the choice cannot be one variable handed to one call, so AddSelectedBroker(environmentVariableName, sqlServer) (:58), in an extension(IDistributedApplicationBuilder) block, provisions the selected broker once (the emulator over the existing SQL Server at :65-69, otherwise AddMessageBroker() with a persistent container lifetime so the broker survives an AppHost restart, :71-73) and returns an attach delegate, which WithSelectedBroker(attach) (:82), in an extension(IResourceBuilder<DotnetProjectResource>) block, simply invokes (:86). ADC makes the choice in one line, builder.AddSelectedBroker("ADC_BROKER", sqlServer) (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98, rationale in the comment block from :69), and hands the delegate to every service's WithMmcaServiceInfrastructure call (Program.cs:137,159,196,221), which applies it as the single .WithSelectedBroker(attachBroker) link of the shared chain (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:76); that is what stops a fifth service from quietly being wired to the wrong broker. [Rubric §33, Developer Experience] (environment parity available on demand, at a cost the everyday inner loop does not pay).
Startup ordering, health-gated waits, and the gRPC deadlock-avoidance trick
Aspire's WaitFor builds a startup dependency graph from the resource model: a service does not start until the resources it waits on report healthy. What "healthy" means for a project resource is the health check that resource carries, and this is where the h2c profile bites a second time. Aspire's stock WithHttpHealthCheck probes with a default HttpClient, which sends HTTP/1.1, and an HttpProtocols.Http2 Kestrel endpoint answers that with GOAWAY HTTP_1_1_REQUIRED rather than the health payload, so the check never turns healthy and every WaitFor edge into that resource degrades to "the process started". H2cHealthCheckExtensions (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/H2cHealthCheckExtensions.cs:42) fixes that with WithH2cHealthCheck(path, endpointName) (:111), which registers an H2cEndpointHealthCheck (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/H2cEndpointHealthCheck.cs:23) against the named endpoint and then associates it with the resource (:128-137, both halves being required for a WaitFor to gate). Three details carry the design. The default path is /alive, not /health/ready (:54): a startup gate must probe liveness, because a readiness endpoint aggregates downstream and warm-up checks and gating startup on it can deadlock the graph. The probe budget is 2 seconds (:67), short because Aspire polls for as long as a dependent resource is waiting. And the endpoint URL is resolved on every check rather than captured at registration (H2cEndpointHealthCheck.cs:71-72,108), with an unallocated endpoint reported as the failure status rather than thrown or passed (:110-120), because Aspire only allocates the endpoint once the resource starts and a pre-allocation poll must not release the wait. The shared probe client's keep-alive ping trio (:46-52) is load-bearing rather than tuning: Aspire's endpoint proxy listens before the target Kestrel does, so a first probe can open a connection that is accepted and never answered, and without the pings every later probe queues onto that one zombie connection forever. H2cHealthCheckRegistry (Level 0, same file :154) makes a repeat registration a no-op: IServiceCollection offers no way to ask which health checks exist and a duplicate key is a startup exception, so GetOrAdd (:185) attaches one ledger to the AppHost's own collection and TryClaim (:168) skips a key an earlier call took.
ADC applies both probe shapes through that ServiceEndpointProfile argument and explains the split in a long comment block (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:326-348): Identity, Conference and Engagement pass Http2Only (:222, :197, :159) and so take WithH2cHealthCheck(), because they run Kestrel Http2-only on cleartext, while Notification passes Mixed (:137) and takes the stock WithHttpHealthCheck("/alive"), because it runs the mixed Http1AndHttp2 profile. Every service gate is /alive, never /health/ready, and the reason is a startup cycle: service readiness includes the warm-up gate, whose OIDC task fetches discovery through the gateway, but the gateway waits for the services (:342-345). The gateway resource itself stays on /alive (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/GatewayUiExtensions.cs:55, applied by WithMmcaGateway at Program.cs:365) in the sharpest form of the same rule, because a startup gate on readiness pulls cross-resource state into the startup order: when the gateway's readiness still carried one probe per downstream service, one unreachable downstream stopped ui.WaitFor(gateway) from ever releasing, and although the downstream checks are now tagged optional (on /health only), liveness is still what a wait needs (GatewayUiExtensions.cs:28-34). Only the UI, which nothing waits for, gates on /health/ready (GatewayUiExtensions.cs:108, applied by WithMmcaUi at Program.cs:395). One further subtlety worth internalizing: Conference and Engagement form a bidirectional gRPC pair, and a reciprocal WaitFor would deadlock, so the AppHost deliberately omits the reverse edge (Program.cs:277, reasoning at :259 and :275) and lets transient "peer not ready" failures self-heal via the Polly pipeline baked into AddTypedGrpcClient. The same judgement is applied to the other reverse-direction edges: Engagement to Notification carries no WaitFor because the publish is fire-and-forget (:284, reasoning from :281), Identity's two export edges and its feedback edge to Conference carry none because Identity is the leaf the other services already wait on (:294-295, :300, reasoning at :271 and :289-291), and Notification's edge to Conference deliberately carries none either (:304-308). The typed-client and interceptor machinery, JwtForwardingClientInterceptor and GrpcResultExceptionInterceptor, lives in the gRPC group (ADR-007).
The service baseline: AddServiceDefaults()
Every running host calls one method early in Program.cs: AddServiceDefaults() from the single framework-grade Extensions in MMCA.Common.Aspire (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:24, a partial class whose health-check and telemetry halves live in Extensions.Health.cs and Extensions.Telemetry.cs beside it). There is no ADC-local copy. AddServiceDefaults() (Extensions.cs:36, declared in an extension<TBuilder>(TBuilder builder) block constrained to IHostApplicationBuilder at :24-25) is four lines of composition, ConfigureOpenTelemetry(), AddDefaultHealthChecks(), AddWarmupReadiness(), AddServiceDiscovery() (:35-38), then the cloud-adapter tripwire described below, registered as an options validator behind ValidateOnStart so it runs with the other startup validators (:40-46), followed by one ConfigureHttpClientDefaults block (:50) that applies to every HttpClient the host later creates: typed clients, named clients, the YARP forwarder, and the gateway's own downstream probe clients alike. That block installs the standard Polly pipeline with its values read from HttpResilienceDefaults (:60-65) and switches its one retry off for POST and PATCH (:74): an attempt that timed out may still be running server-side, and most hops carry no idempotency key, so replaying one risks a duplicate write. GET, PUT, DELETE and the other idempotent verbs keep their retry, which is why the code names the two verbs rather than calling DisableForUnsafeHttpMethods, a helper that would also strip it from PUT and DELETE (:67-73). It then wraps the retry's ShouldHandle so a 429 whose Retry-After asks for longer than the client is willing to wait is not retried at all (:76-84, decided by RetryAfterHeader.ExceedsRetryBudget, below): left alone, the standard handler honors the header, and a rate limiter sets it to the rest of its window, so one refused action would hold a request for up to a minute. The block then re-adds service discovery to the handler chain (:86) and replaces the primary handler with a tuned SocketsHttpHandler (:99-107, rationale comment at :88-98). The handler is the clearest [Rubric §31, Cost & FinOps] decision in the codebase: recycling pooled connections picks up ACA replica DNS rollover without a restart, holding idle connections in the pool avoids paying TCP and TLS handshakes on every low-traffic inter-service call, and socket-level keep-alive pings keep the TCP connection warm without generating HTTP traffic, so an idle replica stays on idle-vCPU billing (documented in-code as roughly 8x cheaper than active). EnableMultipleHttp2Connections = true (:106) keeps a single multiplexed HTTP/2 connection from becoming the bottleneck for the gRPC edges above.
One source of truth for resilience numbers
The numbers that pipeline uses are not literals in the Aspire package. They live in HttpResilienceDefaults (Level 0, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:12), a static class of read-only properties in MMCA.Common.Shared: a 30 second per-attempt timeout (:15), a 60 second circuit-breaker sampling window (:18), a 90 second total request timeout including retries (:21), one retry beyond the initial attempt (:32), an 8 second ceiling on how long a client waits out a 429's Retry-After before retrying (MaxRetryAfterWait, :40, the longest step of the UI retry backoff), a 10 minute pooled-connection lifetime (:46), a 5 minute pooled idle timeout (:49), and 60 second / 30 second keep-alive ping delay and timeout (:56,59). It sits in Shared for a layer reason: MMCA.Common.Aspire, the UI service base classes and MMCA.Common.Grpc may only depend on Shared, so one file answers "what timeout does this client get" for all three (the doc comment at :3-11). The retry budget is the interesting constant: it is pinned at one deliberately (:23-31) because the UI service base classes already own user-facing retries (their policy makes up to 4 attempts), and a full retry budget re-applied at every hop turns a backend brownout into an up-to-16x request storm at exactly the wrong moment. The same remarks state the mutation rule both clients honor: the HTTP clients refuse the retry for POST and PATCH, and the gRPC clients (all POST) retry only a failure to reach the service (:29-30).
The same file carries the east-west gRPC path's own values under a Grpc prefix (HttpResilienceDefaults.cs:61-135), which is what the typed gRPC clients in MMCA.Common.Grpc read (group 13), so one file answers "what timeout does this client get" for every HTTP-based client. The gRPC timeouts are sized from measured latency rather than inherited: an 8 second per-attempt timeout (GrpcAttemptTimeout, :79, about ten times the slowest measured east-west p99 of 784ms, :75-76), a 5 second deadline on a unary call whose caller set none (GrpcCallDeadline, :87), deliberately below the attempt timeout so the call's own deadline, which the peer also receives, ends a hung call first as DeadlineExceeded (:82-85, :69-72), and a 20 second total covering two attempts plus the backoff (GrpcTotalRequestTimeout, :90), because an in-cluster call answers in well under a second and the 30s/90s outbound budget would hold a caller on a hung peer for a minute and a half (:61-64). The retry budget and the sampling window are shared with the HTTP path, while the breaker shape is stated explicitly, a 0.5 failure ratio (:96), a minimum throughput of 10 calls (:102) and a 10 second break, about one container-replica restart (:108), because an east-west call addresses a peer directly and bypasses the gateway's active health checks, so the breaker is the only thing that notices a peer going bad (:65-68). So are the ceilings the library would otherwise default: at most 1000 concurrent calls per typed client on a replica (GrpcMaxConcurrentCalls, :117), no queue beyond that because a saturated peer would only spend the queued call's deadline (GrpcConcurrentCallQueueLimit, :125, :120-123), and a 4 MiB message limit applied on both the client and the service side, so an oversized reply fails as ResourceExhausted at the sender instead of after crossing the network (GrpcMaxMessageSize, :135, :128-133). A consumer whose edge is legitimately slower overrides these per client through AddTypedGrpcClient's configureResilience callback (:68-69).
RetryAfterHeader (Level 1, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:15) sits beside it and owns both ends of the Retry-After contract on a 429 (:6-14). The server half, Format (:28), turns a rejected lease's retry-after hint into whole seconds, rounded up so a client never retries before the window has moved on, and never negative (:30-31); it takes the TimeSpan hint rather than the lease because System.Threading.RateLimiting ships in the ASP.NET Core shared framework, which this package (also loaded by Blazor WebAssembly) does not reference, so a lease without the hint, a concurrency-limiter rejection for one, sends its 429 without the header (:17-24). The client half, TryGetDelay (:43), reads the header in either form, a delta in seconds or an HTTP date measured against an injected TimeProvider, clamping anything already past to zero (:48-63), and ExceedsRetryBudget (:75) is the predicate the ConfigureHttpClientDefaults retry consults: true only for a 429 that carries the header and asks for more than MaxRetryAfterWait (:76-78), so a refused user action costs one request rather than a held connection. Keeping it in Shared on pure BCL types is what lets the API, Aspire and UI.Web limiters and the UI and Aspire retry policies apply one rule (:10-12); the gateway's edge limiter below writes its header through it directly, and MMCA.Common.Gateway, which references no MMCA package, carries a test-pinned internal copy of the server half (:12-13).
BrokerResilienceDefaults (Level 0, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/BrokerResilienceDefaults.cs:25) is the third member of the folder and does the same job for the other outbound transport: the circuit breaker guarding the outbox's broker-publish path. Four properties, a 0.5 failure ratio (:32), a minimum throughput of 10 attempts (:40), a 30 second sampling window (:47), and a 15 second break duration (:55), are read by OutboxProcessor in MMCA.Common.Infrastructure. Its doc comment carries the two decisions worth reading (BrokerResilienceDefaults.cs:8-23): a breaker is needed at all because a broker outage makes each of a 50-row batch's publishes wait out its own transport timeout, so one cycle can spend minutes discovering nothing; and it is deliberately not paired with a Polly retry, because the outbox already owns retry (RetryCount, exponential backoff with jitter, then dead-letter) and a second policy would make a row's effective attempt count an accident of two independent budgets. Two constants files and one header rule, every outbound transport, no drift: [Rubric §29, Resilience & Business Continuity] (ADR-009) and [Rubric §29, Resilience, Reliability & Business Continuity].
Listeners and probes: one Kestrel profile per host shape
Before a service can answer a health probe it has to be listening on a protocol the prober speaks, and that is not free when the same port serves inbound gRPC. KestrelEndpointExtensions (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Kestrel/KestrelEndpointExtensions.cs:24) turns both deployed profiles into a single call, ConfigureEndpointsWithHealthProbe(defaultProtocols, redeclareCleartextEndpoint, cleartextPort) (:77). It applies the requested protocols to every Kestrel endpoint default and then declares the explicit listeners computed by BuildListenerPlan (:84-98, plan at :113). The plan is empty when HealthProbe:Port (:31) is unconfigured (:119-122), which is exactly the local and integration-test case: no explicit Listen call, so Aspire's dynamic ports keep working and two co-hosted services cannot collide. When the deployment injects the port, the plan is one or two KestrelListenerSpec records (:132), each a (Port, Protocols) pair: an Http1-only listener on the probe port, preceded by a re-declaration of the main cleartext listener (default 8080, :37) when redeclareCleartextEndpoint is left at its default (:124-126), because an explicit Listen call otherwise overrides the container's ASPNETCORE_HTTP_PORTS binding entirely. The reason for the second listener is operational and documented at the top of the file (:8-22): ACA httpGet probes speak HTTP/1.1, which an Http2-only endpoint rejects with GOAWAY HTTP_1_1_REQUIRED, which is why those probes used to be TCP-only and never consulted the real dependency-aware health checks. A dedicated Http1 listener on a port that is never published through ingress gives the platform a real target, since MapDefaultEndpoints() maps the health routes on every listener. ADC's three REST services pass HttpProtocols.Http2 (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:94, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:83, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:71) and the SignalR-hosting Notification service passes Http1AndHttp2 with redeclareCleartextEndpoint: false because its endpoints come from configuration (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:73). This is ADR-012 made concrete, and it tags [Rubric §17, DevOps & Deployment].
Health checks: liveness, readiness, and the "optional" tag
MapDefaultEndpoints() (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:143) exposes the three-probe surface the platform reads: /health (every check, for humans and dashboards, :134), /alive (only checks tagged live, :138-141), and /health/ready (:154-156). None of those three paths is a literal at the mapping site: they come from HealthEndpointPaths (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/HealthEndpointPaths.cs:8), a constants holder carrying Health (:11), Alive (:14) and Ready (:17) plus one predicate, IsProbePath (:29), which answers case-insensitively for /alive, /health, and anything below /health/, so a sub-route a host adds later is covered without a second edit (:30-33). The type exists to keep the mapping, the probe telemetry filters and the gateway's downstream probe from drifting apart (:3-7). Every ADC host maps it: the four services through the shared UseMmcaServiceHostAsync (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:300, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:255, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:152), which calls MapDefaultEndpoints() once the schema is migrated (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:56), the gateway directly (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:195), and the UI host through UseMmcaBlazorWebPipeline (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120-122, mapped at MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:199). The tag vocabulary is a named type rather than string literals, HealthCheckTags (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/HealthCheckTags.cs:6), with three constants: Live (:12), Ready (:18), and Optional (:32). Read the readiness predicate carefully, because it encodes a hard-won operational rule: it excludes both live and optional (Extensions.Health.cs:176). Excluding live keeps a downstream SQL outage from restarting the container. Excluding optional is the subtler half, argued at length in both the tag's own doc comment (HealthCheckTags.cs:20-31) and the endpoint comment (Extensions.Health.cs:168-173): a dependency the app degrades gracefully without (a distributed cache behind an in-memory fallback, a broker behind a retrying outbox) must not gate readiness, because making it readiness-fatal converts a partial degradation into a total outage when every replica goes unready at once. Those checks still surface on /health, so the degradation stays visible without being self-inflicted.
The two aggregating probes are not computed per request. /health and /health/ready are both mapped through MapCachedHealthChecks(path, predicate) (Extensions.Health.cs:192-220), which answers exactly as MapHealthChecks does (the status name as text/plain, 503 only when unhealthy, :182-189) but serves the report from CachedHealthReportProvider (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/CachedHealthReportProvider.cs:32), keyed by path so the full report and the readiness subset never share a result (Extensions.Health.cs:189, :179). The window comes from HealthReportCacheOptions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/HealthReportCacheOptions.cs:29): one property, CacheSeconds, defaulting to 5 and range-validated to 0-300, with 0 restoring probe-per-request behavior (:37-38), bound from the HealthChecks section (:31). Read the reason in its remarks (:10-22), because it is an availability finding rather than a performance tweak: both endpoints are anonymous and sit on the always-bypassed rate-limit prefix, and executing every registered check per request turned N anonymous requests into N x (services + database + cache) backend operations, a SELECT 1 on a pooled SQL connection, a Redis PING, a broker check, and on a gateway one outbound /alive per fronted service, which exhausts the SQL pool without an account. Caching the report bounds that amplification at one probe round per window regardless of inbound rate, which a bypass list alone cannot do. /alive is deliberately left uncached (Extensions.Health.cs:152-153, HealthReportCacheOptions.cs:20-23): it runs only the self check, costs nothing, and is what the platform restarts a container on, so it must answer for the current instant. The provider keeps one private Entry (CachedHealthReportProvider.cs:42-49) per endpoint key, in a dictionary guarded by one Lock (:37-38): a cached report, its expiry, and the Task<HealthReport> of the round in progress. The single-flight rule is the subtle part: a fresh report is returned as is (:79-82); while a round is running, a caller serves the stale report rather than queueing (:84-92), so a slow dependency cannot convert a probe flood into a request backlog; only a call with nothing cached yet (the first after startup) waits for the round in progress (:94, :102), and otherwise the caller starts a new round (:98). That round belongs to the provider, not the caller: it runs under Task.Run on a token cancelled only when the provider is disposed (:107-113) and publishes the report and its expiry under the lock (:121-127), so a caller's token only stops that caller waiting (:102). The clock is an injected TimeProvider (:35, registered with TryAddSingleton(TimeProvider.System) at Extensions.Health.cs:37) so the window is testable without waiting.
AddDefaultHealthChecks() (Extensions.Health.cs:25) registers the baseline self check tagged Live (:28) and, alongside it, the cache: the options bound with ValidateDataAnnotations().ValidateOnStart() (:33-36) and the provider as a singleton (:38). AddInfrastructureHealthChecks(requireDatabase) (:76) adds the dependency probes, every one registered with the per-check timeout read from HealthChecks:CheckTimeoutSeconds, 5 seconds when absent (:79, :287-294). The relational half is engine-agnostic and multi-source: AddDatabaseHealthChecks (:237) asks RelationalSources (:326) for every distinct database the host declares on each of the three relational engines, SQL Server, PostgreSQL and SQLite (:243-245), across both the top-level ConnectionStrings section and every named DataSources entry, then registers one untagged check per database (:255-284). Untagged means they do gate readiness: readiness for a host that owns several databases means every database it serves from is reachable. The requireDatabase asymmetry is deliberate and documented (Extensions.Health.cs:57-75): a host that cannot resolve its own database is misconfigured, so no relational engine at all throws at startup (:247-253), the same fail-fast posture as ADR-070; Redis and RabbitMQ are optional per host and are added only when their connection string is present, tagged Optional (Extensions.Health.cs:83-100, :103-123), so the same binary runs unchanged in an integration-test environment where those containers are absent. Every one of those checks is Common's own code rather than a health-check package registration. SqlServerHealthCheck (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/SqlServerHealthCheck.cs:16) and SqliteHealthCheck (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/SqliteHealthCheck.cs:15) open a connection and run SELECT 1 under the check's cancellation token (SqlServerHealthCheck.cs:37-46, SqliteHealthCheck.cs:36-45), rethrow only a cancellation the caller asked for and report anything else as the failure status (SqlServerHealthCheck.cs:52-56); they hold no state, because the driver's pool keyed by the connection string carries the reuse, so one instance is shared across probes (SqlServerHealthCheck.cs:9-14, created once per database at Extensions.Health.cs:259, :282). The SQL Server check uses the same Microsoft.Data.SqlClient build Infrastructure connects with, so a connection string that authenticates for the contexts authenticates here too (SqlServerHealthCheck.cs:12-13). PostgreSqlHealthCheck (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/PostgreSqlHealthCheck.cs:26) is the one with a twist: MMCA.Common.Infrastructure registers a keyed NpgsqlDataSource singleton, keyed by the connection string, once a data-source configurator is added (RDS IAM tokens, for one), and a check built from the bare connection string would authenticate without that password provider and report a healthy database as down (:12-17). This package cannot reference Infrastructure, so the check decides per probe, because the two registrations can arrive in either order: it probes the shared data source when the keyed lookup finds one, and otherwise a data source of its own, built on first use, kept for every later probe and disposed with the check, never disposing the shared one (:20-24, the probe at :55). It is registered as a keyed singleton per check name so that owned data source is built once (Extensions.Health.cs:265-277). The broker check splits the same way between a probe and a holder. RabbitMqHealthCheck (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RabbitMqHealthCheck.cs:15) opens and closes one channel on the connection that RabbitMqHealthConnection (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RabbitMqHealthConnection.cs:22) hands it (RabbitMqHealthCheck.cs:36-39) and never opens or disposes that connection itself (:9-12). The holder exists because opening a connection per probe round would leave one AMQP connection on the broker every successful round: it keeps at most one, replaces it only when it is gone or no longer open, creates it single-flight under its own token on the check-timeout budget so a port that accepts TCP and never answers cannot hang the handshake, and closes it when the host stops (RabbitMqHealthConnection.cs:6-16, registered as a singleton at Extensions.Health.cs:116 from the rabbitmq or messaging connection string, :103-106). No ADC service makes that call itself: each enters the shared start-up sequence of ServiceHostBuilderExtensions through AddMmcaServiceHost (for one, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:76), and that sequence passes requireDatabase: true for every extracted service (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:106).
The Redis branch is worth reading as a case study in why the tag rules exist, because it was learned in production. RedisCachingExtensions (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Caching/RedisCachingExtensions.cs:40) is the framework-owned way to wire a host to Redis: AddRedisCaching(connectionName) (:70) registers the distributed cache and the IConnectionMultiplexer client with DisableHealthChecks = true on both (:77-78), and AddRedisOutputCaching(connectionName) (:112) backs the ASP.NET Core output cache with the same instance so tag eviction crosses replicas (:84-86). Both are no-ops when the connection string is absent (:72, :114). The reason for the wrapper is stated in its own doc comment (:10-24): Aspire's Redis integrations register the AspNetCore.HealthChecks.Redis check with no tags, an untagged check silently gates readiness, and that check issues CLUSTER INFO against anything StackExchange.Redis 3.x detects as clustered, which is how it sees Azure Managed Redis (Enterprise tier). The server refuses that command outside admin mode, so every probe threw against a healthy cache, every replica reported not ready, and the platform stopped routing traffic the applications could serve. The fix is structural rather than a tag patch on someone else's registration: the Aspire checks are switched off at the source and Common contributes RedisPingHealthCheck (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RedisPingHealthCheck.cs:27), which issues nothing but PING (:53), resolves the multiplexer from DI (:48) and only lazily builds its own behind a semaphore when the host registered no client (:31, :102-105), reports rather than throws on any failure (:61-73), and is registered once as a singleton tagged Optional (Extensions.Health.cs:92-100). The output-cache store opens no connection of its own: it rides the host's IConnectionMultiplexer, registering the client only when none is registered yet (RedisCachingExtensions.cs:119-128), so the one connection this package opens outside Aspire's Redis client is that fallback multiplexer (RedisPingHealthCheck.cs:102), and it goes through RedisConfigurationOptionsPipeline (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Caching/RedisConfigurationOptionsPipeline.cs:19). Its CreateConfigured (:29) parses the connection string and runs every registered IPostConfigureOptions<ConfigurationOptions> over it (:33-45), the same post-configure steps Aspire's client options go through, and returns null when none is registered so the caller keeps its plain connection-string path (:34-37). That is how a Redis configurator, the Entra token configurator of MMCA.Common.Azure for one, reaches that fallback connection, just as it reaches Aspire's client and the stores riding it through the client's options pipeline (RedisCachingExtensions.cs:31-37), without this package referencing Infrastructure: both sides name only the StackExchange.Redis type and the options abstractions (RedisConfigurationOptionsPipeline.cs:12-16). ADC's four services call AddRedisCaching() (.../Conference.Service/Program.cs:185, .../Identity.Service/Program.cs:130, .../Engagement.Service/Program.cs:108, .../Notification.Service/Program.cs:111), and Conference additionally calls AddRedisOutputCaching() (:196). This is [Rubric §17, DevOps & Deployment] (the probe contract the deployment platform consumes) and [Rubric §13, Observability & Operability] made concrete; the readiness revision is recorded in ADR-025.
The optional-tag rule is also proven against real outages, in an opt-in ADC tier that runs the whole AppHost. AdcOutageAppHostFixture (Level 3, MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageAppHostFixture.cs:17) boots the real ADC AppHost over the shipped AppHostFixtureBase and runs only with the opt-in variable, a container runtime and a valid developer certificate, a missing precondition making every test skip with the gate's sentence rather than hang (:10-16, :60-63). It clears ADC_BROKER so the stack selects RabbitMQ, since the Service Bus emulator has no stop-and-start story this tier can assert (:52-57), allows 12 minutes to start and 8 to turn healthy (:69-70), awaits only Identity, Notification and the gateway, all liveness-gated so the wait cannot deadlock on a dependency a test takes away (:72-77), and shortens Identity's outbox retry, lease and polling so the outbox outlasts an outage (:93-96). AdcOutageCollection (Level 4, MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageCollection.cs:9) turns parallelization off, because an outage test stops a container the whole stack shares (:3-8). AdcDependencyOutageTests (Level 5, MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcDependencyOutageTests.cs:22) derives from the shipped DependencyOutageTestBase and probes Notification through two scenarios: a Redis outage (:26) and a broker outage (:45) each fail /health but keep readiness, because those checks are tagged optional, and recover once the container starts again (:7-12). The broker scenario also registers an attendee through the gateway while RabbitMQ is down, so the UserRegistered event parks in Identity's outbox, which the base asserts pending and, after the broker returns, drained (:65-70, :73-96). There is deliberately no SQL Server scenario: an Aspire start recreates a stopped container with empty databases and the services migrate only at start, so a "recovered" readiness would be asserted over a missing schema (:14-19).
Telemetry: what gets exported, and what it costs
ConfigureOpenTelemetry() (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:120) wires logging with formatted messages and scopes (:122-126), metrics (:129), and tracing (:130-195). Metrics are configured by a private ConfigureMetrics(metrics, configuration) (:293), which first hands the ASP.NET Core instrumentation to ConfigureAspNetCoreMetrics (:295, defined at :390) and then subscribes every framework meter from one public list, FrameworkMeterNames (:61), by literal name: MMCA.Common.Outbox, MMCA.Common.Cqrs, MMCA.Common.Idempotency, MMCA.Common.Scheduler, MMCA.Common.Broker, MMCA.Common.OutputCache, MMCA.Common.BestEffort, MMCA.Common.InternalCommands, MMCA.Common.Persistence, MMCA.Common.Auth, and the optional AI package's MMCA.Common.AI (the AiTelemetryName constant at :43) (:63-73, subscribed at :353), because the Aspire package has no reference to the assemblies that define them (its only project reference is Shared), plus Polly's own Polly meter (:360, the PollyMeterName constant at :30). A fitness test holds that list equal to the meters the Common packages actually create, so a new meter cannot ship unexported (:58-59). Tracing adds the host's own application-name source plus FrameworkActivitySourceNames (:87), the MMCA.Common.Outbox, MMCA.Common.Messaging, MMCA.Common.InternalCommands and MMCA.Common.AI sources, again as literals held equal to the sources Common creates by the same kind of test (:89-92, :84-85, subscribed at :132-133). Several of those meters are inert until a host opts into the feature behind them, the scheduler in a host that never enables Scheduler:Enabled, the broker meter in a host that stays on the in-process bus, best-effort side effects, and the AI meter until a host adds that package and enables Ai:Enabled, which the in-code comment states explicitly (:349-352). Four cost levers hang off this method, and all four fail safe; a fifth, Telemetry:EnablePollyDurationMetrics (the key is a named constant at :24, read by IsInstrumentationEnabled at :271-272), inverts the default the other way and drops the two Polly duration histograms unless a host asks for them (:362-377), while the resilience.polly.strategy.events counter, the only production signal that a client is retrying or a circuit opened, is never dropped (:367-369, :95-101). First, OutboxPollFilterProcessor (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/OutboxPollFilterProcessor.cs:17) is registered via .AddProcessor(...) (Extensions.Telemetry.cs:171): a BaseProcessor<Activity> whose OnEnd (OutboxPollFilterProcessor.cs:34) walks each ending span's in-process parent chain (:44) and, on meeting a background poll, clears ActivityTraceFlags.Recorded (:51) so the batch exporters skip it. Two polls qualify, the outbox's OutboxPoll on MMCA.Common.Outbox and the internal-command queue's InternalCommandPoll on MMCA.Common.InternalCommands, each matched on both source and operation name so an unrelated span that shares a poll's name is not swept up (:42-43, the four literals pinned as private constants at :28-31, duplicated deliberately because this package does not reference Infrastructure, with a test pinning them to their owners, :19-27). It must be registered before the exporters, including any vendor adapter's exporter added after AddServiceDefaults(), so its OnEnd runs first (Extensions.Telemetry.cs:164-170), and it returns rather than throws on a null activity (OutboxPollFilterProcessor.cs:36-40), because a telemetry callback must never take the process down. Real per-message OutboxProcess and per-command InternalCommandExecute work restores an explicit parent context and is never a poll descendant, so genuine outbox and queue telemetry survives (:12-15; the poll machinery, OutboxProcessor, IOutboxSignal, and OutboxMessage, lives in the events and outbox group, ADR-003). Right behind it, and always on, sits a privacy processor rather than a cost one. AccessTokenQueryRedactionProcessor (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/AccessTokenQueryRedactionProcessor.cs:18) is registered under the same ordering rule (Extensions.Telemetry.cs:173-177) because a SignalR WebSocket client sends its bearer as ?access_token=, which the ASP.NET Core and HttpClient instrumentation would otherwise record. Its OnEnd (AccessTokenQueryRedactionProcessor.cs:29) rewrites the value of every access_token query parameter, matched case-insensitively, to REDACTED (:21, :96-99) in the four URL tags the instrumentation writes across semantic-convention versions, url.query, url.full, http.target and http.url (:26), and returns on a null activity like the others (:31-35). Only the exported tag changes, never the request, so the hub still authenticates from the query string (:7-12); a value that carries no such parameter comes back as the same instance and is not re-set (:42-45, :60-63), and a fragment is left as it is (:65-70). Second, TryGetTraceSampleRatio (Extensions.Telemetry.cs:235) reads an optional Telemetry:TracesSampleRatio and, only when it parses inside the open interval (0,1) (:239-247), installs a ParentBasedSampler(TraceIdRatioBasedSampler(...)) (:193-194) for head-based sampling; a typo, a blank, or an out-of-range value falls back to sampling everything, so a mistake can never silently blackhole all telemetry, and ParentBased keeps a sampled-in trace intact across service boundaries. Third, IsInstrumentationDisabled (Extensions.Telemetry.cs:258-259) backs three opt-in kill switches, Telemetry:DisableAspNetCoreMetrics (:392), Telemetry:DisableHttpClientMetrics (:304) and Telemetry:DisableRuntimeMetrics (:332), which drop the highest-volume metric families on a low-traffic multi-service deployment. The ASP.NET Core family (http.server.*, kestrel.*, aspnetcore.*, signalr.server.*) is the largest of the three: its doc comment records it as 73% of both production workspaces' ingestion over one week, mostly gauges re-emitted on replicas serving no traffic, with no alert reading any of it, since request latency and failures alert off the request traces (:381-386). Note how they drop them: skipping the Add*Instrumentation call is not enough, because a deployed host may also wire the Azure Monitor distro through the MMCA.Common.Azure adapter, and that distro adds the System.Net.Http and System.Runtime meters itself, so each branch installs a MetricStreamConfiguration.Drop View over the whole meter instead (:317-321, where System.Net.NameResolution rides along with the HttpClient family, :337-340, and for ASP.NET Core one Microsoft.AspNetCore. prefix match at :397-400; reasoning at :306-316 and at :394-396). A View applies to the MeterProvider regardless of which component added the meter, which is what makes the toggle authoritative rather than advisory. Unset keeps everything, so a host that does not opt in sees no behavior change; with the runtime switch unset, the runtime's own System.Runtime meter is subscribed directly (:344-346). Fourth, and unlike the other three on by default, Telemetry:FilterProbeTelemetry (the key is a named constant, Extensions.Telemetry.cs:18, read by IsProbeTelemetryFilterEnabled at :283-284) keeps health-probe traffic out of trace export: absent, blank or unparseable all mean filter, and only an explicit boolean false turns it off for a host debugging its own probes (:274-284). It takes two passes, because a probe request and its dependency children are sampled independently. ProbeTelemetryFilter (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/ProbeTelemetryFilter.cs:27) supplies the two instrumentation predicates, wired onto the default-named ASP.NET Core and HttpClient options (Extensions.Telemetry.cs:150-156) so they also govern the instrumentation a vendor distro such as Azure Monitor adds, which is what makes them authoritative without a View. ShouldCollectRequest (ProbeTelemetryFilter.cs:40) refuses an inbound probe request and on its way out stamps an mmca.probe tag (:33, :51) on the current server activity; ShouldCollectOutgoing (:62) refuses the outbound probe calls that have no inbound parent to inherit from, the gateway's DownstreamServiceHealthCheck calls to each backend's /alive and YARP's active health checks, both driven by background timers (:20-25). The marker exists because refusing the request makes the instrumentation return before it writes url.path, leaving descendants with no way to recognize their probe ancestor (:12-19). ProbeTelemetryFilterProcessor (Level 2, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/ProbeTelemetryFilterProcessor.cs:20) is the second pass, registered only when the knob is on and, like the outbox one, ahead of the exporters (Extensions.Telemetry.cs:179-185): OnStart (:29) and OnEnd (:40) run the same walk up the in-process parent chain (:52) and, on a probe ancestor, clear both ActivityTraceFlags.Recorded and IsAllDataRequested (:59-60), so the database check's SELECT 1, the Redis PING and the gateway's /alive call never reach an exporter. A parent counts as a probe when it carries the marker tag (:68) or is a server span whose url.path, http.route, or route-suffixed display name is a probe path (:76-79); server kind only, so a normal request never loses its whole subtree because one dependency happened to be a probe (:73-75). Both passes return rather than throw on a null activity (:44-48), and running at end as well as at start is deliberate, since a client span is started before its instrumentation has written any attribute (:32-39). Metrics are untouched by design, so probe traffic stays on dashboards while leaving the trace bill (:14-17); the volume is concrete, probe requests accounted for every AppRequests row in both production workspaces and their children for most of the AppDependencies volume (ProbeTelemetryFilter.cs:8-11, ProbeTelemetryFilterProcessor.cs:10-12). Exporters are equally conditional, and the core ships only the vendor-neutral one: AddOpenTelemetryExporters (Extensions.Telemetry.cs:217) enables OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is present (the local Aspire dashboard, :219-225). A vendor exporter is an adapter package's registration made after AddServiceDefaults(), AddAzureMonitorExporter() from MMCA.Common.Azure for one, so the filter processors above still run ahead of its batch processor, and both exporters can be active at once (:206-215). ConfigureOpenTelemetry() leaves a ServiceDefaultsTelemetry HostIntegrationMarker behind (:199-201), the receipt that adapter checks for so it refuses to run ahead of this call. ADC's four services add the Azure Monitor exporter through the AfterServiceDefaults callback that the shared service host runs right after AddServiceDefaults() (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:85-86; MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:124, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:90-95, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:76, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:85), the UI head the same way (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:42-47), and the Gateway calls it directly (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:82). The whole shape is ADR-041: instrument where auto-instrumentation is blind, then expose cost knobs whose defaults never go dark. [Rubric §13, Observability & Operability] and [Rubric §31, Cost & FinOps].
One logging detail belongs to this boundary rather than to the telemetry pipeline itself. SerilogHostExtensions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Logging/SerilogHostExtensions.cs:38) carries the bootstrap every service host used to repeat by hand: AddCommonSerilog(logFilePath, configure) (:48) builds the framework configuration (CreateLoggerConfiguration at :98: minimum level Debug in Development and Information elsewhere via ResolveMinimumLevel at :76, EF Core and ASP.NET Core overridden to Warning at :108-109, console always at :110, a daily rolling file sink everywhere except Production via ShouldWriteFileSink at :87), publishes it as the global Log.Logger, and registers it with builder.Logging.AddSerilog(...) (:54-55). That last line is the load-bearing part, stated in the type's doc comment (:16-21): UseSerilog() replaces the whole ILoggerFactory and silently bypasses every other provider, including the OpenTelemetry one that carries logs to Azure Monitor once AddAzureMonitorExporter() is wired, so a host that calls it publishes no application log line to App Insights at all. AddSerilog adds Serilog alongside the others instead. CreateBootstrapLoggerFactory() (:67) covers the startup diagnostics a host needs before the DI container exists, module discovery above all. All four ADC services call AddCommonSerilog ahead of AddServiceDefaults(), with only the MMCA.Common.Azure vault configuration source between them (.../Conference.Service/Program.cs:103,117, .../Identity.Service/Program.cs:101,114, .../Engagement.Service/Program.cs:85,98, .../Notification.Service/Program.cs:88,101).
Warm-up: defeating ACA cold-start
The warm-up subsystem exists for one concrete failure mode: the "first request fails, second succeeds" pattern on a CPU-throttled idle ACA replica, where lazy initialization (OIDC discovery fetch, connection-pool establishment, JIT) stretches past a client timeout. AddWarmupReadiness() (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:137, folded into AddServiceDefaults at :34) registers four cooperating pieces. IWarmupTask (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/IWarmupTask.cs:9) is the unit of startup work: a Name for logs (:12) plus ExecuteAsync (:15). WarmupHostedService (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupHostedService.cs:28) is a BackgroundService that runs all registered tasks in parallel exactly once (:53) and then opens the gate in a finally block (:56-60), so even when a task throws, the replica is never wedged permanently out of rotation. Each task additionally runs under a 120 second ceiling applied with WaitAsync over an injectable TimeProvider (:42,44-45,69): a task that neither completes nor throws used to leave Task.WhenAll pending forever and the gate closed with it, and the timeout turns that case into the same log-and-continue path as a failure (:77-82), which closes the one gap ADR-025 originally recorded as open. A per-task catch logs a genuine failure at Warning and lets the others proceed (:84-88), while a real host-shutdown cancellation is rethrown (:73-76). WarmupReadinessGate (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupReadinessGate.cs:10) is a thread-safe one-shot flag (Volatile.Read at :15, Interlocked.Exchange at :18, over an int), consumed by WarmupReadinessHealthCheck (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupReadinessHealthCheck.cs:9), which is registered tagged HealthCheckTags.Ready (Extensions.cs:144-145) and reports Unhealthy until the gate opens (WarmupReadinessHealthCheck.cs:14-16). That is exactly what makes /health/ready hold ingress traffic off a still-warming replica.
Two task shapes ship with the framework. OpenIdConnectMetadataWarmupTask (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/OpenIdConnectMetadataWarmupTask.cs:25) is registered unconditionally by AddWarmupReadiness (Extensions.cs:142): it reads Authentication:JwtBearer:Authority (:30, the same key the AppHost's WithJwksDiscovery injects), returns quietly when it is unset (:31-34), warns and returns when it is not a valid absolute URI (:36-43), and otherwise GETs {authority}/.well-known/openid-configuration through the shared IHttpClientFactory (:45-46) to warm DNS, TCP, TLS, and the connection pool. Its remarks state the honest caveat (:14-20): the JwtBearer middleware caches discovery state separately and still performs its own first fetch, but now over a warm connection. SelfHttpWarmupTaskBase (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/SelfHttpWarmupTaskBase.cs:28) is the abstract base for the deeper variant: after awaiting ApplicationStarted (:102, implemented at :191, because the warm-up runner starts before Kestrel is listening) it replays a subclass-supplied list of WarmupPaths (:59) against this host's own bound cleartext port, resolved from the server's addresses feature with ASPNETCORE_URLS and port 8080 as fallbacks (ResolveWarmupPort, :157, default at :39). Three virtual members are the extension points that make it usable on every host shape: RequestVersion and RequestVersionPolicy default to HTTP/2 pinned exactly (:70,77), because an Http2-only cleartext endpoint rejects a silently downgraded HTTP/1.1 request, and RequireSuccessStatusCode (:90) can be turned off so an intentional 401 on an [Authorize] route still counts (the refusal traverses Kestrel, routing, and authentication, which is the JIT cost being paid down). The whole task is skipped under the Testing environment (:46,95-98), where WebApplicationFactory's in-memory server never opens a socket. Services register their own tasks via AddWarmupTask<TTask>() (Extensions.cs:160): ADC wires SelfHttpOutputCacheWarmupTask in Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:311) and a SelfHttpWarmupTask in Engagement and Identity (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:173, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:165). This whole subsystem is the decision recorded in ADR-025: warm-up is wired into AddServiceDefaults so every host gets it, the gate opens even when a task fails or times out (availability over strict warmth), and the missed work is re-paid as a lazy retry on the first real request through the resilience pipeline. Tag-wise it leans on [Rubric §29, Resilience & Business Continuity] and [Rubric §17, DevOps & Deployment].
Cloud adapters and the startup tripwire
Connection strings, RSA signing keys, OAuth client secrets, the Application Insights exporter and a multi-replica DataProtection key ring all have to reach a deployed process, and none of them is wired by this group: the core packages reference no cloud vendor SDK, and each vendor capability is one registration call in an adapter package (MMCA.Common.Azure, MMCA.Common.Aws, MMCA.Common.Gcp), documented in the cloud provider adapters chapter (AzureKeyVaultConfigurationExtensions, AzureDataProtectionExtensions) under ADR-134. What stays here is the check that the adapter call was made. Without it, a deployment that still sets KeyVault:Uri but no longer calls AddAzureKeyVaultConfiguration() would start cleanly with every vault secret missing, or ship no telemetry at all, and look healthy while doing it (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationTripwire.cs:6-12).
The mechanism is four small types in MMCA.Common.Aspire.Integrations. HostIntegrationMarker (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationMarker.cs:10) is a registration receipt: a sealed class carrying one Name (:13) that an adapter's host-level registration adds to the service collection, because the core never names an adapter type and so can only check a well-known string (:3-8). HostIntegrationNames (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationNames.cs:8) is that vocabulary: ServiceDefaultsTelemetry (:14), the one the core registers itself from ConfigureOpenTelemetry() (Extensions.Telemetry.cs:201), and eight adapter names, Azure's AzureMonitorExporter, AzureKeyVaultConfiguration and AzureDataProtection (HostIntegrationNames.cs:17,20,23), AWS's Secrets Manager source and key ring (:26,29), and Google Cloud's Secret Manager source, key ring and telemetry exporter (:32,35,38). HostIntegrationTripwire (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationTripwire.cs:15) is an internal IValidateOptions that collects every marker's name into a set (:56) and, in Validate (:59), pairs eight configuration keys with the receipt each requires (:63-102): APPLICATIONINSIGHTS_CONNECTION_STRING (:20) with the Azure Monitor exporter, KeyVault:Uri (:23) with the vault source, DataProtection:BlobStorageUri (:26) with the Azure key ring, and the AWS and Google Cloud equivalents (:29-46). A key that is set without its receipt adds a failure naming the missing call and its consequence (Check at :117-123, where set means non-whitespace, :125). One rule is not about a missing call: setting more than one of the three key-ring gates (:49-54) also fails, because whichever registration runs last owns the repository, and services that disagree on the order mint cookies the others cannot decrypt (:104-112). Every failure is returned together rather than only the first (:114). HostIntegrationTripwireOptions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationTripwireOptions.cs:8) is an empty internal options type whose only job is to carry the tripwire through ValidateOnStart (:3-7): AddServiceDefaults() registers it with AddOptions<HostIntegrationTripwireOptions>().ValidateOnStart() plus a TryAddEnumerable of the validator (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:51-53), so the check runs with the other startup validators, before any hosted service starts. This is the ADR-070 fail-fast posture applied to the vendor boundary. ADC's four services, Gateway and Blazor UI host call AddAzureKeyVaultConfiguration() ahead of AddServiceDefaults(), because that call reads configuration eagerly itself and must see vault values too (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:121, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:109, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:97, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:99, MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:75, MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:58), and the two hosts that mint cookies and antiforgery tokens, Identity and the UI, call AddAzureDataProtection() (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:124, MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:67). [Rubric §11, Security] and [Rubric §17, DevOps & Deployment].
Security headers and CORS at the host edge
The next boundary in this group hardens the request and response edge. The shared response-header middleware is defined in MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs. SecurityHeadersSettings (Level 0, :19) holds the strongly-typed values bound from the "SecurityHeaders" section (:22): FrameOptions defaulting to DENY (:25), ReferrerPolicy (:28), PermissionsPolicy (:31), HSTS opt-out and value (:34,51), an enforce-versus-report-only switch (:72), and a complete hardened CSP baseline (:67-69) that ships script-src 'self' 'wasm-unsafe-eval' and style-src 'self' 'unsafe-inline' at exactly the strength Blazor and MudBlazor require, so an HTML host that never registers a provider still gets a functional policy rather than one silently missing both directives, while the JSON, WebSocket and static responses of API and gateway hosts are unaffected (:53-66). It also carries CredentialPathPrefixes (:48), defaulting to /reset-password and /auth/oauth-complete: the pages a credential arrives on, whose URL must not travel onward in a Referer header or sit in a browser or proxy cache after the token is spent (:36-46). That list is guarded by LeadingSlashPathPrefixesAttribute (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/LeadingSlashPathPrefixesAttribute.cs:13), an internal ValidationAttribute that rejects every non-blank entry not starting with / and names all the offenders in one message (:25-31), skipping blanks as the matchers do. The reason is in its doc comment (:5-11): PathString refuses a non-empty value without a leading slash, so an entry such as "hubs" would otherwise throw on every request that reaches the matcher instead of failing once at startup, the ADR-070 posture. ICspPolicyProvider (Level 1, SecurityHeaders.cs:86) is the per-host CSP extension point, with StaticCspPolicyProvider (Level 2, :93) as the default that resolves the configured policy once in its constructor (:97-104) and returns it for every request (:106); a Blazor host registers its own dynamic implementation before calling AddCommonSecurityHeaders, which is exactly what ADC's UI host does: its AddMmcaBlazorWebHost call (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27) registers the shared BlazorCspPolicyProvider through AddCommonBlazorCsp() immediately before AddCommonSecurityHeaders (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:155-156). That host keeps HSTS on for its own origin, because an HSTS pin is per-origin and the Gateway's header says nothing about the UI's sibling hostname (Program.cs:183-188). CspPolicy (Level 0, SecurityHeaders.cs:78) is the resolved (Value, Enforce) record that decides between Content-Security-Policy and Content-Security-Policy-Report-Only, keeping a policy and its enforcement mode inseparable. SecurityHeadersMiddleware (Level 2, :147) stamps X-Content-Type-Options, X-Frame-Options, Referrer-Policy, and Permissions-Policy on every response (:190-195), switching Referrer-Policy to no-referrer on a credential path (:192-194). A credential path is matched by whole segments, case-insensitively, so /reset-password covers /reset-password/anything but never /reset-passwords (:178-182), and its response also leaves with Cache-Control: no-store, no-cache, must-revalidate, max-age=0 plus Pragma: no-cache (:156, :246-250). Those are applied once up front and again from a response-start callback (:197-212): the Razor Components endpoint writes its own weaker Cache-Control while it renders, and a callback registered before the rest of the pipeline runs after every downstream one, so the strict value settles last. HSTS is added only outside Development (decided once in the constructor at :175, applied at :214-217), and the middleware emits whichever CSP header the provider's Enforce flag selects (:233-240). Between those two steps sits the nonce path: a policy carrying the literal {nonce} token gets a fresh 16-byte value per request (:150,153,226-231), stashed raw in HttpContext.Items before the rest of the pipeline runs so the page render can read it, and substituted into the header as the quoted 'nonce-<value>' source-list form. CspNonce (Level 0, :124) is the tiny public surface for that: the ItemKey constant (:127) and a Get(context) helper (:134) a layout calls to stamp the value onto its own script tags. It is the supported path off 'unsafe-inline', and a policy with no placeholder generates nothing (:110-122). SecurityHeadersExtensions (Level 3, :258) supplies the two registration halves: AddCommonSecurityHeaders (:268), which validates the options with ValidateDataAnnotations().ValidateOnStart() so a malformed credential prefix fails the host once rather than every request (:274-277), binds the config section when one is supplied (:278-281), and registers the default provider through TryAddSingleton so a pre-registered custom provider wins (:288), and UseCommonSecurityHeaders (:296). The stated point is to centralize what each client-facing host previously hand-rolled, eliminating drift; this is ADR-023.
One sibling completes this boundary. GatewayCorsExtensions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/GatewayCorsExtensions.cs:16) exposes AddCommonGatewayCors (:24), which registers the reverse proxy's default CORS policy: allow-any origin in Development (:34-41) but in every other environment restricting origins to Cors:AllowedOrigins while allowing any header and method plus credentials (:44-52), because the CORS spec forbids combining allow-any-origin with credentials. It is the gateway half of the two-tier posture in ADR-082, deliberately looser than MMCA.Common.API's per-service allow-listed AddCommonCors, because a proxy must pass arbitrary client headers through; ADC's Gateway wires it alongside the header middleware (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:135,140,196). The multi-replica half of the same story, a DataProtection key ring every replica shares so an auth cookie or antiforgery token minted by one can be decrypted by another (ADR-069), is a cloud-adapter call rather than part of this package (AzureDataProtectionExtensions), guarded at startup by the tripwire above. Relevant tags across this boundary: [Rubric §11, Security] and [Rubric §26, Front-End Security] (defense-in-depth headers and CSP with a nonce path), and [Rubric §13, Observability & Operability] (one shared middleware and one shared CORS policy instead of N hand-rolled copies).
The gateway edge kit: correlation, rate limiting, downstream readiness
A YARP gateway is the one process every client request passes through, and it is also the one host that has no application container: no DbContext, no module loader, no ICorrelationContext. That is why the three edge behaviors live in their own namespace, MMCA.Common.Aspire.Gateway, with no dependency beyond ASP.NET Core itself. The decision, including the three responsibilities the edge explicitly declines, is ADR-088.
GatewayCorrelationMiddleware (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayCorrelationMiddleware.cs:30) is the twin of MMCA.Common.API's CorrelationIdMiddleware and exists precisely because that one cannot run here: it writes onto a scoped ICorrelationContext that only a host with the Common application services registered owns (:11-16). This one takes RequestDelegate and nothing else (:29), which is what makes it safe to drop into a bare proxy. InvokeAsync (:51) reads X-Correlation-ID (the header name is a public constant deliberately duplicating the API package's literal, :36, since the two packages share no reference) and applies the service's own rule to a caller-supplied value, mirrored in a private Sanitize (:87-91): cut to MaxLength, 64 characters, the stored width (:43), and discarded when any character falls outside printable ASCII, because Kestrel refuses to echo a non-ASCII or control character (:21-23). When nothing usable arrived it mints one from Activity.Current?.TraceId with TraceIdentifier as the fallback (:62-64), and it writes the result onto the request headers whenever it differs from what the caller sent (:66-69). Writing the request side is the whole point: the proxied request carries the ID downstream, so the service-side middleware adopts it instead of minting a second one, and because the echo runs after the forwarder has copied the service's headers, the edge must forward and echo exactly the value the service keeps (:57-59). The response echo is registered through HttpResponse.OnStarting (:72-76) so it survives a response whose headers the forwarder writes. GatewayCorrelationExtensions (Level 1, same file :99) is the one-line UseGatewayCorrelation() pipeline call (:108).
The edge limiter is two types and a mode. GatewayRateLimitingSettings (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingSettings.cs:50) binds the optional GatewayRateLimiting section (:51): PermitLimit 120 (:60), WindowSeconds 60 (:64), GlobalConcurrencyLimit 200 (:74), extra BypassPathPrefixes (:85, guarded by the same LeadingSlashPathPrefixesAttribute at :84, so a bad entry fails registration instead of every request), two header-and-secret pairs, the synthetic-traffic pair (:94, :118) and the trusted-internal-caller pair (:128, :156), and the TrustedCallerMode that decides what the second pair buys (:166). Three properties of the design are load-bearing and stated in its remarks: the limiters count in this replica's memory, so the effective allowance multiplies by replica count, a trade taken because an edge limiter must answer in microseconds and a shared counter would put a network round trip in front of every request; partitioning is by Connection.RemoteIpAddress, so forwarded headers must be applied before the limiter or every request is attributed to the ingress; and a scheduled capacity proof drives its whole load from one runner IP, which the per-IP window cannot tell from a flood, so a run presenting the configured synthetic-traffic value takes the same no-limiter partition a bypassed path takes. The trusted-caller pair exists for a server-rendered UI host, which makes every back-end call from one address on behalf of every signed-in visitor; both secrets are off unless configured, and the trusted one identifies a deployed component, never a browser. TrustedCallerMode (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/TrustedCallerMode.cs:8) decides how such a caller is counted. The default, PerVisitor (:17), counts a trusted-caller request that carries the end visitor's address in X-Forwarded-For against that visitor's own per-IP window and every named route policy keyed on the visitor, exactly as the visitor's direct request would be, and gives only a request with no visitor address, a background call, the no-limiter partition (:10-16); Exempt (:23) gives every trusted-caller request the no-limiter partition whatever address it carries (:19-22). GatewayRateLimitingExtensions (Level 2, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:48) composes them: IsBypassed (:98) matches whole path segments case-insensitively against the always-exempt /health, /alive, /.well-known (:86) plus the host's configured prefixes, IsSyntheticTraffic (:125) and IsTrustedInternalCaller (:161) both go through one PresentsSecret (:176) that compares the header with CryptographicOperations.FixedTimeEquals (:192), and IsExemptFromLimiters (:204-207) is the union of the three. ClientIpPartition (:222) decides a trusted caller first (:230). Under PerVisitor it reads the visitor from the last X-Forwarded-For entry (TrustedCallerVisitorIp, :280-297), stamps that address into HttpContext.Items under TrustedCallerVisitorIpItemKey (:76) for the named per-route policies that run later and cannot see these settings, and counts the request in the visitor's window (:246-249); with no visitor, under Exempt, or on a bypassed path or synthetic run it stamps TrustedInternalCallerItemKey (:67) instead and returns the no-limiter partition (:236-243). Any other exempt request also gets the no-limiter partition (:252-254), so does an unresolvable IP (fail open rather than collapsing every unattributable request into one bucket, :259-263), and everything else gets a fixed window per client address with no queue (:266, :300-315, QueueLimit = 0 at :312). The visitor window and the direct one take the same shared key, which folds an IPv6 address to its /64 and unmaps an IPv4-mapped one (ClientAddressKey.For, :257-258, :249). That window is a wrapper, RemainingWindowFixedWindowRateLimiter, because the framework limiter's Retry-After is always the whole window and the wrapper reports the time actually left in it (:304-307). ConcurrencyPartition (:326) is one process-wide bucket that also rejects immediately rather than queueing (:333-338), because the failure it guards against is a slow downstream backing requests up until the edge runs out of threads. AddGatewayRateLimiting has two overloads: the configuration one binds with ValidateDataAnnotations().ValidateOnStart() (:352-361), and the settings one runs Validator.ValidateObject at registration (:374, :382) because the limiter closes over an eagerly bound copy rather than resolving IOptions per request, which honors ADR-070 on both paths at the cost of no hot reload. The two limiters are chained (:395-399), so a request must satisfy both, and rejection is 429 (:386). Every rejection also passes through RetryAfterRejection.WithRetryAfterHeader (installed at :390), a linked source file shared with the route policies below (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42), which writes a Retry-After header in whole seconds, its Format a pinned copy of the shared RetryAfterHeader's, whenever the rejecting lease carries a retry-after hint (the fixed window does, a concurrency rejection does not) and then runs whatever OnRejected callback was configured before it, because that callback is one slot shared with the route policies (GatewayRateLimitingExtensions.cs:388-390, RetryAfterRejection.cs:33-52). UseGatewayRateLimiting() is the pipeline half. Note the deliberate inversion of ADR-019: the service-side global limiter exempts anonymous callers, and the edge does not, because the output cache that justified that exemption sits behind the proxy. [Rubric §11, Security] and [Rubric §12, Performance & Scalability].
Readiness is the third piece, and it is the one that learned the most. GatewayHealthCheckExtensions (Level 5, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:72) exposes AddGatewayDownstreamHealthChecks in two overloads (:131, :149) that funnel into one private Register (:162), which for each Aspire service name registers a named HttpClient whose base address is the service-discovery form http://{name} (:190-196, resolved by the AddServiceDiscovery that AddServiceDefaults already wired, so nothing hard-codes a host or port) and a downstream-{name} health check over it (:237-242). Two choices carry the design (:114-130): the checks are tagged Ready, never Live, because restarting the gateway fixes nothing about a downstream outage; and their failure status is Unhealthy rather than Degraded, because /health/ready treats Degraded as passing, so a Degraded check would report a problem while still taking traffic the gateway cannot serve. The probe budget is 2 seconds (:85), short because it runs per downstream on every readiness poll, and two registration details protect it. The probe client strips every ResilienceHandler that AddServiceDefaults() put on it (:204-221), because the standard pipeline's one retry lands inside the two-second budget and turns a healthy downstream into a timed-out one, and a refused HTTP/2 attempt must reach the check at once so it can fall back. And the check is one keyed singleton per downstream (:223-235), because the health-check service runs the registration factory on every poll and a fresh instance each time would drop the latched HTTP version described below. DownstreamServiceHealthCheck (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/DownstreamServiceHealthCheck.cs:41) is the hand-rolled check itself, a GET and a status comparison (:143-175), with a narrow catch list plus a cancellation guard so host shutdown is never reported as a dependency fault (:75-87). It probes /alive, not /health/ready, taking the path from the shared HealthEndpointPaths.Alive constant rather than a literal of its own (:46), and the reason is in its remarks (:17-21): the gateway needs to know whether the service exists and is reachable, and probing readiness would make every rolling downstream deployment register as a gateway failure. The protocol question is settled per downstream rather than configured: DownstreamProbeVersion (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:11) offers Auto, Http2 and Http11 (:19,26,33), and GatewayDownstreamHealthCheckOptions (Level 1, same file :41) defaults to Auto (:60) because neither fixed answer is right for every head: an h2c-only endpoint refuses HTTP/1.1, and a mixed Http1AndHttp2 cleartext endpoint without ALPN answers HTTP_1_1_REQUIRED to HTTP/2 forever (:43-58). Under Auto the check asks for HTTP/2 first and, on a protocol refusal only (IsProtocolRefusal at DownstreamServiceHealthCheck.cs:184 matching VersionNegotiationError or HttpProtocolError), retries once as HTTP/1.1 inside the same poll (:98-131), then latches the version that answered with Interlocked.CompareExchange (:192) so the fallback is a one-time cost per downstream rather than a per-poll one. Nothing latches on a connectivity fault, because a transient outage says nothing about which protocol the endpoint speaks. GatewayDownstreamRegistry (Level 0, GatewayHealthCheckExtensions.cs:259) is the small ledger that makes the registration idempotent, the same shape as the H2c one above: GetOrAdd (:287) attaches one instance to the collection and TryClaim (:270) skips a name an earlier call already registered.
The YARP building blocks: cluster profiles, ejection, trace headers, route policies
The route table itself is configuration, not code (ADR-089), and MMCA.Common.Gateway deliberately does not load it: LoadFromConfig (or any other IProxyConfigProvider) stays the host's call, and this package only adds behavior on top of whatever source the host chose (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:24-29). GatewaySettings (Level 2, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:13) is its whole configuration surface, bound from the MmcaGateway section (:15): cluster request defaults and per-cluster overrides (:22, :29), destination health-check defaults (:33), trace headers (:36), named route policies (:42) and the opt-in connect retry (:49), duplicating nothing from the YARP ReverseProxy section. GatewayReverseProxyExtensions (Level 4, GatewayReverseProxyExtensions.cs:35) is the single entry point, AddMmcaGateway, in a configuration overload that binds with ValidateDataAnnotations().ValidateOnStart() (:56-66) and a settings overload for a host that composes in code (:82, supplying an explicit IOptions<> instance at :90). Both funnel into one private Wire (:100) that validates the settings and registers the named policies (:105-106), installs the connect retry when it is enabled (:108-111), post-configures Kestrel's header encoding (:113-114), and attaches two config filters plus two transform providers (:116-120). The validation step exists because ValidateDataAnnotations reads only the attributes on the properties of GatewaySettings itself and does not recurse into the objects it holds, so a blank trace-header name would pass startup and then throw from every proxied request (GatewayReverseProxyExtensions.cs:102-104). GatewaySettingsValidator (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettingsValidator.cs:19), an internal IValidateOptions<GatewaySettings>, closes that gap over four nested objects, TraceHeaders, both halves of HealthCheckDefaults, and Retry (NestedObjects at :50-55), and it is used the two ways the route policies are checked. ThrowIfInvalid (:23) runs over each and fails registration for both overloads (called from Wire at GatewayReverseProxyExtensions.cs:105, the ADR-070 posture), and the configuration overload also registers the validator through TryAddEnumerable (GatewayReverseProxyExtensions.cs:70) so the value the options pipeline binds is checked again on start, where Validate (GatewaySettingsValidator.cs:32) collects every failure rather than stopping at the first.
Four building blocks hang off that. First, GatewayClusterProfileConfigFilter (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayClusterProfileConfigFilter.cs:25) resolves each cluster's forwarder request profile from three sources, per property rather than per block (Resolve at :59, the four most-specific-wins helpers at :82-122): the cluster's own HttpRequest, then GatewayClusterRequestProfile (Level 0, GatewaySettings.cs:82) under ClusterRequestOverrides[clusterId], then ClusterRequestDefaults. That ordering is the point: a gateway fronting services that all speak h2c declares the shared activity timeout once instead of repeating an identical block per cluster, while the one cluster that genuinely differs still says so locally. The profile expresses the version pair as text (:58,64) so a mistyped value fails at startup with a message naming the cluster (ParseVersion at :76, ParseVersionPolicy at :96) instead of binding to a silent default, and IsSameAs (:131) returns an unchanged cluster by reference so YARP's config-change detection sees no churn on reload. Second, GatewayHealthCheckDefaultsConfigFilter (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:17) fills in destination health checks for clusters that declare none (:25-47), additively: an operator's explicit Passive or Active block is kept verbatim (:29-33). GatewayHealthCheckDefaults (Level 1, GatewaySettings.cs:149) splits into GatewayPassiveHealthCheckDefaults (Level 0, :132), on by default with the built-in TransportFailureRate policy and a 60 second reactivation period (:135-142) because passive checks watch the responses the gateway is already forwarding and cost no extra traffic, and GatewayActiveHealthCheckDefaults (Level 0, :150), off by default with ConsecutiveFailures, a 10 second interval, a 5 second timeout and a /alive path (:153-171) chosen for the same reason the gateway's own probes use it: readiness on a downstream flips during its own rolling deployment, and ejecting a destination for that is the gateway reacting to a healthy deployment as if it were an outage. Third, GatewayTraceHeaderTransformProvider (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Transforms/GatewayTraceHeaderTransformProvider.cs:18) stamps the matched route id and target cluster id onto every proxied request from GatewayTraceHeaderSettings (Level 0, GatewaySettings.cs:208, defaults X-MMCA-Route and X-MMCA-Cluster at :181,184), capturing the ids once at build time (:51-54) and removing any inbound value before writing its own (:60-61), because a header a service trusts must be one only the gateway can set. Fourth, GatewayRoutePolicyExtensions (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:29) registers one named fixed-window policy per entry in RateLimiterPolicies (AddGatewayRoutePolicies at :61), the policies a YARP route references through its own RateLimiterPolicy property. Each GatewayRoutePolicySettings (Level 1, GatewaySettings.cs:242) states a GatewayRoutePolicyPartition (Level 0, :229, ClientIp or Global), a permit limit defaulting to 30, a 60 second window and a queue limit of zero (:245-260), and its PartitionKey (:273) returns null for an unresolvable IP so Partition (GatewayRoutePolicyExtensions.cs:113) hands back a no-limiter partition rather than one shared bucket. The edge limiter's trusted-caller decision carries over through the two HttpContext.Items keys it stamps first: a request it counted against a forwarded visitor's window is keyed on that visitor's address here too (TrustedCallerVisitorIpItemKey, :49, read at :122), and a request it exempted takes a no-limiter partition here as well (TrustedInternalCallerItemKey, :40, checked at :127-129), so a server-rendered UI's sign-ins, which all leave from one address, are never pooled into one per-IP bucket. Values are validated at registration, not at the first throttled request (:71-74), again ADR-070. These policies are additive to any global limiter the host installs (:18-22): ASP.NET Core evaluates the global limiter and the route's named policy independently, so a request must satisfy both, and the two packages stay independent of each other. Both registrations write to the one shared OnRejected slot, so the route policies install the same Retry-After writer the edge limiter does and chain whatever callback came before (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:80-82). That writer is RetryAfterRejection.WithRetryAfterHeader (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42), one source file compiled as an internal type into each of the four packages that register a limiter, MMCA.Common.API, MMCA.Common.Aspire, MMCA.Common.UI.Web and this one, through a linked Compile Include (RetryAfterRejection.cs:12-18, linked here at MMCA.Common/Source/Hosting/MMCA.Common.Gateway/MMCA.Common.Gateway.csproj:24). It sets the header only when the rejecting lease carries a MetadataName.RetryAfter hint and then runs the previous callback (RetryAfterRejection.cs:46-51). Its Format (:27-31) is a copy of RetryAfterHeader.Format rather than a reference because this package deliberately references no MMCA project, and a test pins the two together so they cannot drift (:15-17). The window behind each policy comes from a second linked file: Partition builds a RemainingWindowFixedWindowRateLimiter (GatewayRoutePolicyExtensions.cs:145-154, MMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:31) instead of the framework's fixed-window limiter, whose Retry-After is always the whole window, so a throttled caller is told the time actually left in it (GatewayRoutePolicyExtensions.cs:138-142, RemainingWindowFixedWindowRateLimiter.cs:5-11).
The fifth type in this package is not about YARP configuration at all. ForwardedHeadersExtensions (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/ForwardedHeadersExtensions.cs:23) supplies UseCommonForwardedHeaders() (:36) and the shared CreateForwardedHeadersOptions() (:55) that applies X-Forwarded-For, -Proto and -Host with the known-proxy and known-network allow-lists cleared (:59-63). Clearing them is load-bearing: cloud reverse proxies front the app from internal IPs that are in neither default allow-list, so leaving the defaults in place makes the middleware ignore every forwarded header and report the ingress IP as the client. It lives here because a service host gets this step from UseCommonMiddlewarePipeline in MMCA.Common.API, and a gateway takes none of that package (:9-17); without it a gateway hand-rolls the same five lines, and getting them wrong is invisible until production, where an unforwarded gateway collapses the per-client-IP rate-limit partition into one shared window for every real user.
Three more pieces harden the forwarding path itself. GatewayHeaderEncoding (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayHeaderEncoding.cs:14) lets the gateway's Kestrel read X-Correlation-ID (:20) as Latin-1 instead of ASCII. Kestrel answers a non-ASCII header byte with an empty 400 and Connection: close before any middleware runs, so without it GatewayCorrelationMiddleware would never get to replace the unusable value with a generated id (:6-13). Apply (:27) chains the rule in front of whatever selector the host set, which keeps deciding every other header (:31-35), and Wire post-configures it so it wraps the host's own ConfigureKestrel (GatewayReverseProxyExtensions.cs:113-114). GatewayBypassHeaderTransformProvider (Level 0, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Transforms/GatewayBypassHeaderTransformProvider.cs:20) removes the edge limiter's trusted-caller and synthetic-traffic headers from every proxied request (:50-64), so the secrets they carry end at the gateway and no downstream service, sidecar or header log receives them, while the limiter, which reads both before the proxy runs, is unaffected (:7-11). Because this package takes no reference to the Aspire one, it reads the header names from the GatewayRateLimiting section by name and falls back to the limiter's defaults, X-Internal-Caller-Key and X-Synthetic-Traffic-Key (:23-29, :66-81). The third is an opt-in connect-failure retry. GatewayRetrySettings (Level 0, GatewaySettings.cs:59), bound from MmcaGateway:Retry (:49, :52-57), is off by default (Enabled, :64), allows one to three extra attempts defaulting to one (:67-68), and waits at most five seconds before each, defaulting to 200 milliseconds (:71-72). When it is enabled, Wire replaces YARP's forwarder client factory with GatewayRetryForwarderHttpClientFactory (Level 3, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayRetryForwarderHttpClientFactory.cs:12, registered at GatewayReverseProxyExtensions.cs:153-154), and fails registration rather than silently replacing a factory the host registered itself (:130-146). Its WrapHandler (GatewayRetryForwarderHttpClientFactory.cs:64-68) installs GatewayConnectRetryHandler (Level 1, MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayConnectRetryHandler.cs:20) as the outermost handler of every cluster client, so a retried attempt goes through the whole inner pipeline again (GatewayRetryForwarderHttpClientFactory.cs:7-11). The handler retries only what never reached the destination: a body-less GET or HEAD (GatewayConnectRetryHandler.cs:36-38) whose attempt failed with a name-resolution, connection or TLS error (:41-44), logging a Warning per retry (:61-67) and waiting the configured delay on an injected TimeProvider (:70-73). Any response, any other exception and a cancellation pass through untouched, and a spent budget rethrows the last exception, so YARP still answers 502 and the passive health policy counts one failure (:5-15).
ADC's Gateway wires all of this in an order the comments call out as contractual (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:67-151 for registration, :160-234 for the pipeline): AddAzureKeyVaultConfiguration() first (:68), then AddServiceDefaults() (:70) and AddAzureMonitorExporter() (:75), the edge limiter (:76), one call registering all four downstream checks on the Auto default (:90), shared security headers (:120) and CORS (:125), then AddReverseProxy().LoadFromConfig(...).AddMmcaGateway(...).AddServiceDiscoveryDestinationResolver() (:148-151). The pipeline is forwarded headers first so the limiter sees the real client IP (:160), then correlation (:165) so even a 429 from the limiter carries an ID, then security headers (:170), MapDefaultEndpoints (:172), CORS (:173), the limiter after CORS so a rejected preflight is still a CORS answer (:180), static files and the /privacy alias (:185-193), and finally MapReverseProxy() (:234) so a throttled request never reaches a backend. Its GatewayRateLimiting section adds /hubs to the bypass list (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:25) because a SignalR connection is long-lived and its negotiate and reconnect traffic must not be throttled, and it names the trusted-caller header while the secret itself arrives from Key Vault (:26-32); the UI head presents that secret on its server-side calls through AddTrustedCallerHeader, which stamps it only on requests to the configured gateway origin (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:131-136). Its MmcaGateway section declares the shared 100 second forwarder activity timeout, the one-hour override for the notification-hub cluster, active destination probing explicitly left off (:57-61), and the auth-tight per-route policy at 30 permits per 60 second window per client IP (:62-68), all within appsettings.json:43-70. [Rubric §7, Microservices Readiness], [Rubric §13, Observability & Operability], and [Rubric §29, Resilience & Business Continuity].
How it all fits at runtime
Putting the pieces in sequence: the AppHost declares the graph, picks a broker once, and injects per-service env vars (WithMmcaServiceInfrastructure for each service's database, cache, broker and mail waits, WithJwksDiscovery, WithIssuer, WithUiLinks, WithServiceTokenSigningKey, the E2E switches, and the gRPC WithReferences), attaching an /alive health check to every service resource in the shape its ServiceEndpointProfile names (WithH2cHealthCheck for the three h2c services, the stock probe for Notification) so each WaitFor edge gates on a real answer. Each service boots, sets its Kestrel protocol profile and optional Http1 probe listener with ConfigureEndpointsWithHealthProbe, calls AddCommonSerilog, then AddAzureKeyVaultConfiguration() from the Azure adapter so everything that binds settings afterwards (service defaults included) reads vault-backed secrets, then AddServiceDefaults() to opt into telemetry, health, resilience, warm-up and the adapter tripwire, then AddAzureMonitorExporter() behind the trace filter processors, AddRedisCaching() (and AddRedisOutputCaching() where the output cache must cross replicas), AddInfrastructureHealthChecks(requireDatabase: true) for its dependency probes, AddAzureDataProtection() where cookies must survive scale-out, and AddCommonSecurityHeaders plus UseCommonSecurityHeaders at the edge. The Gateway boots on the same vault source and AddServiceDefaults() and adds the edge kit (AddGatewayRateLimiting, AddGatewayDownstreamHealthChecks, AddCommonGatewayCors, UseCommonForwardedHeaders, UseGatewayCorrelation, UseGatewayRateLimiting) plus AddMmcaGateway over a route table it loads from configuration. Aspire withholds traffic via WaitFor and the /health/ready predicate until each replica is past its warm-up gate and its non-optional dependencies are healthy, and the gateway's own readiness additionally reflects whether it can reach the four services, on whichever HTTP version each of them latched. The warm-up tasks pre-pay the cold paths, bounded by the 120 second per-task ceiling. Once live, outbound calls ride the shared HttpResilienceDefaults pipeline over the idle-cost-tuned socket handler, east-west gRPC rides the Grpc-prefixed values in the same HttpResilienceDefaults file, integration events flow through the broker selected by the env vars behind the BrokerResilienceDefaults circuit breaker, YARP ejects a failing destination on the package's passive health-check defaults, and telemetry streams to the OTLP endpoint or Azure Monitor minus the suppressed outbox-poll and health-probe spans, any dropped metric family, and any head-sampled trace fraction. The same env-var-and-abstraction contract is what lets a module run in-process or as an extracted service without code changes (ADR-007 and ADR-008): the AppHost decides topology by what it wires, and the service code stays transport-agnostic. The per-type sections that follow document each of these classes in ascending Level order; the module-registration and message-bus types they reference are in the module system (group 14) and events and outbox (group 04) chapters.
GatewayCorsExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/GatewayCorsExtensions.cs:16· Level 0 · class (static)
- What it is: Registers the shared default CORS policy for the reverse-proxy Gateway via a single
AddCommonGatewayCorsextension method. - Depends on:
Microsoft.ExtensionsCORS / Configuration / Hosting (ASP.NET Core, BCL). No first-party types. - Concept introduced:
[Rubric §11, Security],[Rubric §26, Front-End Security],[Rubric §9, API & Contract Design]. §11 and §26 assess a cross-origin policy that stays safe while still allowing credentials. The doc comment (GatewayCorsExtensions.cs:7-15) draws the distinction from a service host's CORS: a reverse-proxy gateway must pass arbitrary client headers through to the services it fronts, so, unlikeMMCA.Common.API.AddCommonCors's allow-listed headers and methods, the production gateway policy allows any header and method while restricting origins toCors:AllowedOrigins. That origin restriction is load-bearing: the CORS specification forbids combiningAllowAnyOrigin()withAllowCredentials(), so to let cookies andAuthorizationheaders flow, the policy must name explicit origins. ADR-082 is the record for exactly this two-tier posture (allow-listed service policies plus an any-header gateway policy). This is the browser-facing edge of the Gateway topology (ADR-008). - Walkthrough:
AddCommonGatewayCors(configuration, environment)sits in anextension(IServiceCollection services)block (GatewayCorsExtensions.cs:18, method at:24). It null-guards the receiver and both arguments (:28-30), then registers a default policy insideservices.AddCors(:32). In Development it allows any origin, header, and method (:37-40), with a scoped#pragma warning disable S5122(:36, restored at:41) whose comment records that allow-any-origin is confined to Development. Otherwise it reads theCors:AllowedOriginsstring array, defaulting to[](:45-47), and buildsWithOrigins(origins).AllowAnyHeader().AllowAnyMethod().AllowCredentials()(:48-52). Because it is registered as the default policy, hosts pair it with a bareapp.UseCors()(no named policy). - Why it's built this way: Credentialed cross-origin traffic requires enumerated origins, so the non-Development branch reads them from configuration rather than allowing everything; the any-header and any-method latitude reflects the gateway's pass-through role. One shared method keeps the ADC and Store gateways from drifting apart.
- Where it's used: The YARP Gateway hosts:
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:140andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:77, each followed by a bareapp.UseCors()(ADCProgram.cs:137, StoreProgram.cs:162). Note the pipeline order in both hosts:UseCors()runs before GatewayRateLimitingExtensions'UseGatewayRateLimiting()(ADC:137,:144; Store:162,:170), and both hosts carry a comment saying why (ADC:139, Store:164): a rejected preflight is still a CORS answer, and a throttled cross-origin caller still receives the headers it needs in order to read the 429. - Caveats / not-in-source: Outside Development, an unset or empty
Cors:AllowedOriginsyields an empty origin list, which blocks all cross-origin credentialed calls. That is fail-closed (a misconfiguration denies rather than permits), but the browser client cannot reach the gateway until origins are configured.
HealthCheckTags
MMCA.Common.Aspire ·
MMCA.Common.Aspire·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/HealthCheckTags.cs:6· Level 0 · class (static)
- What it is: The three tag-name constants (
live,ready,optional) that the standard health endpoints mapped byMapDefaultEndpoints()filter on. - Depends on: Nothing. Three
const stringfields. Consumed by the Extensions registration and endpoint-mapping code, by RedisPingHealthCheck's registration, and by GatewayHealthCheckExtensions. - Concept introduced, health-check tags as a routing vocabulary.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity],[Rubric §17, DevOps]. ASP.NET Core health checks each carry a set of string tags, and an endpoint maps aPredicateover those tags. That means the tag vocabulary is the operational contract between the app and the platform (Azure Container Apps or Kubernetes probes). Getting it wrong is not cosmetic: a liveness probe that fails restarts the container, and a readiness probe that fails removes the replica from traffic. Naming the three tags once, in a shared constants class, is what stops a consumer from tagging a check"Ready"or"live "and silently landing it on the wrong endpoint. - Walkthrough:
Live = "live"(HealthCheckTags.cs:12): liveness only. The check runs on/aliveand is excluded from readiness. Its doc comment (:8-11) reserves it for self checks, "so an external dependency outage never restarts the container".Ready = "ready"(HealthCheckTags.cs:18): the readiness gate. The check runs on/health/readyand holds traffic back until it passes. This is the tag the warm-up gate uses, and the tag the gateway's downstream checks use.Optional = "optional"(HealthCheckTags.cs:32): a dependency the application degrades gracefully without. It is reported on/healthbut excluded from/health/ready. The long doc comment (:20-31) is the teaching part and is worth reading in full: a distributed cache sitting behind an in-memory fallback, or a broker behind a retrying outbox, can fail without the app losing the ability to serve. Gating readiness on such a dependency converts a partial degradation into a total outage, because every replica goes unready simultaneously and the platform stops routing traffic the app could still handle. A check is left untagged only when the app genuinely cannot serve correct responses without it, its own database being the standard example.
- Why it's built this way: Constants rather than an enum, because the health-checks API takes
stringtags; aconstalso lets the values appear in collection expressions such astags: [HealthCheckTags.Optional]with no conversion. The three-way split (live / ready / optional / untagged) encodes a deliberate blast-radius policy: liveness restarts, readiness withholds traffic, optional only reports. That policy is recorded in ADR-025, whose revision added theoptionalexclusion to/health/readyfor exactly the total-outage reason above, and it is what ADR-088 applies to a dependency rather than to a startup task. - Where it's used: The service-defaults Extensions: the warm-up check is registered with
[HealthCheckTags.Ready](MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:145), the"self"check with[HealthCheckTags.Live](:238), and the conditional Redis and RabbitMQ checks with[HealthCheckTags.Optional](:289,:301). The endpoint predicates read them back:/aliverequiresLive(:376-379) and/health/readyexcludes bothLiveandOptional(:392-395). The relational database checks are deliberately left untagged (:462,:467), which is what makes them readiness-fatal. GatewayHealthCheckExtensions tags every downstream probeReady. The tagging is asserted by InfrastructureHealthChecksTests and, for the Redis path specifically, by RedisReadinessSafetyTests.
HealthEndpointPaths
MMCA.Common.Aspire ·
MMCA.Common.Aspire·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/HealthEndpointPaths.cs:8· Level 0 · class (static)
- What it is: The three health-probe route constants (
/health,/alive,/health/ready) plus one predicate,IsProbePath(string?), that answers whether a request path addresses any of them. Where HealthCheckTags names the tag vocabulary, this names the routes. - Depends on: Nothing first-party beyond a doc-comment reference to HealthCheckTags (
HealthEndpointPaths.cs:13). Threeconst stringfields and a static method overstring.Equals/string.StartsWith. - Concept introduced, one owner for the probe route vocabulary.
[Rubric §13, Observability & Operability],[Rubric §31, Cost / FinOps]. The probe routes are read in two very different places: the code that maps them (Extensions.MapDefaultEndpoints()) and the code that recognises them after the fact, namely the trace filters that keep probe traffic out of telemetry export (ProbeTelemetryFilter and ProbeTelemetryFilterProcessor) and the gateway's own downstream probe (DownstreamServiceHealthCheck). A literal"/alive"retyped on the recognising side is the classic silent break: the endpoint keeps working, the filter quietly stops matching, and the only symptom is a telemetry bill. Naming the routes once makes the mapping side and the matching side provably the same strings. The cost half of that is recorded in ADR-041. - Walkthrough:
Health = "/health"(HealthEndpointPaths.cs:11),Alive = "/alive"(:14),Ready = "/health/ready"(:17): the full report, the liveness probe, and the readiness probe respectively, each with a one-line doc comment naming which checks run there (:10,:13,:16).HealthPrefix(:19) is private and composed fromHealth + "/", so it cannot drift from the constant it extends.IsProbePath(path)(:29) returnsfalsefor null or empty, then matchesAliveorHealthexactly and anything underHealthPrefix(:30-33). The prefix arm is what makes/health/readymatch without being listed, and it also covers any sub-route a host maps later. Every comparison isOrdinalIgnoreCase, which the doc comment (:21-28) ties to ASP.NET Core routing being case-insensitive.
- Why it's built this way: Constants rather than an options type, because these routes are a platform contract (the Container Apps probe configuration and the availability web test point at them) and are not per-host configurable.
IsProbePathlives beside them rather than inside either filter because both filters and the gateway probe need the same answer; putting the predicate next to the strings keeps the "what counts as a probe" definition in one file. The prefix rule is deliberately broader than the three constants, so adding a/health/livestyle route later needs no change on the recognising side. - Where it's used: Extensions
.MapDefaultEndpoints()maps all three (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:154,:138,:154). ProbeTelemetryFilter callsIsProbePathfor the inbound request path (Telemetry/ProbeTelemetryFilter.cs:42) and for an outgoing request URI (:63). ProbeTelemetryFilterProcessor calls it three ways on a finished activity, theurl.pathtag, thehttp.routetag, and the route parsed out of the display name (Telemetry/ProbeTelemetryFilterProcessor.cs:77-79). DownstreamServiceHealthCheck builds its relative probe URI fromAlive(Gateway/DownstreamServiceHealthCheck.cs:46), so the gateway probes exactly the route its backends map. - Caveats / not-in-source: The predicate takes a path only; it never sees a query string, and the doc comment states that as the caller's obligation (
:24-25). Nothing enforces that a host which maps extra health routes puts them under/health/, so a differently named probe route would evade the telemetry filters.
DownstreamProbeVersion
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:11· Level 0 · enum
- What it is: The three-value vocabulary for "which HTTP version does the gateway's downstream
/aliveprobe ask for": negotiate it, or pin one of the two answers. - Depends on: Nothing first-party. Its doc comments reference
HttpVersionPolicy(BCL). It is carried on GatewayDownstreamHealthCheckOptions and consumed by DownstreamServiceHealthCheck. - Concept introduced, protocol negotiation as a health-check concern.
[Rubric §13, Observability & Operability],[Rubric §7, Microservices Readiness],[Rubric §29, Resilience & Business Continuity]. §13 assesses whether an operational signal tells the truth, and this enum exists because a probe that asks the wrong protocol lies in the most expensive direction: it reports a downstream outage that does not exist. The two facts that force the choice are in the options doc comment (GatewayHealthCheckExtensions.cs:46-54). A service serving cross-service gRPC on cleartext runs KestrelHttp2-only, so h2c prior knowledge is the only thing it answers, and a stockHttpClientsends HTTP/1.1, which it refuses. Sending HTTP/2 unconditionally has the mirror-image failure: an HTTP/1.1-only endpoint, or a mixedHttp1AndHttp2cleartext endpoint where Kestrel disables h2 because there is no ALPN to disambiguate, answersHTTP_1_1_REQUIREDforever. Neither fixed answer is right for every head, so the framework makes discovery the default and pinning the exception. ADR-012, in its 2026-08-29 update, is the governing record. - Walkthrough:
Auto(:18) is the zero value and the default. It tries HTTP/2 first and, when the downstream refuses the protocol rather than the connection, falls back to HTTP/1.1 inside the same check, so a single readiness poll still produces one verdict (doc comment:12-17). The version that answered is then latched for the life of the process, making the fallback a one-time cost per downstream rather than a per-poll one.Http2(:25) always sends HTTP/2 over cleartext withHttpVersionPolicy.RequestVersionExact, so the request never negotiates down (:20-24).Http11(:32) always sends HTTP/1.1 withRequestVersionOrLower, which is exactly stockHttpClientbehavior (:27-31).- That
Autois the zero value is load-bearing beyond defaulting: the latch field in DownstreamServiceHealthCheck stores the underlyingintand reads zero as "not settled yet" (DownstreamServiceHealthCheck.cs:50-57).
- Why it's built this way: An enum rather than a
boolbecause there are genuinely three states (discover, pin high, pin low), and the previous shape (a per-downstreamProbeOverHttp2boolean opt-out) could express only two. ADR-012 records that the boolean was removed outright in v1.168.0 with no compatibility facade left behind. Both pinned values are documented as optimisations ("to skip the one-time negotiation"), never as correctness requirements, which is what keeps a singleAddGatewayDownstreamHealthCheckscall correct for a mixed fleet. - Where it's used: Set on GatewayDownstreamHealthCheckOptions (
GatewayHealthCheckExtensions.cs:60), captured at registration (:174), passed into each check (:209), and branched on at probe time (DownstreamServiceHealthCheck.cs:70,:149). Neither gateway pins a value today: ADC registers all four downstreams in one call (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:105) and Store all three (MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:112), both relying onAuto. Covered by GatewayDownstreamHealthChecksTests, whoseOptions_DefaultToAutoNegotiationand the pinned-mode cases (Probe_WhenPinnedToHttp2_NeverFallsBack,Probe_WhenPinnedToHttp11_SendsHttp11) pin all three values.
GatewayDownstreamRegistry
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:259· Level 0 · class (sealed, internal)
- What it is: A registration-time ledger of the downstream service names already wired by
AddGatewayDownstreamHealthChecks, so a repeated name cannot register a second health check under the same name. - Depends on:
IServiceCollection(it stores itself in the collection as a singleton instance) andStringComparer(BCL). Used only by GatewayHealthCheckExtensions; it hands out no runtime behaviour. Its AppHost-tier twin is H2cHealthCheckRegistry. - Concept introduced, registration-time state parked in the service collection.
[Rubric §15, Best Practices & Code Quality],[Rubric §15, Best Practices & Code Quality].IServiceCollectionis a list of descriptors, not a queryable model: there is no supported way to ask "is a health check named X already registered", and a duplicate health-check name is a startup exception rather than a harmless second registration (class doc commentGatewayHealthCheckExtensions.cs:253-258). The idiom the framework reaches for is to park a small mutable object in the collection itself as anImplementationInstanceand look it up on the next call, which makes idempotence a property of the registration API rather than a rule the caller has to remember. - Walkthrough:
private readonly List<string> _names = [](:232). The doc comment above it (:227-231) explains the choice of a list over a case-insensitiveHashSet<string>: a gateway fronts a handful of services, and the comparer-carryingHashSetconstructor is one of the initializer shapes the IDE0028 analyzer misreports here.TryClaim(serviceName)(:240) returnsfalsewhen the name is already present, compared withStringComparer.OrdinalIgnoreCase(:242-245), otherwise appends it and returnstrue(:247-248). Case-insensitivity is what makes a second call passing"CATALOG"a no-op rather than a duplicate.GetOrAdd(services)(:257) walks the descriptors looking for one whoseServiceTypeis this type and whoseImplementationInstanceis a registry (:259-266), returning it when found; otherwise it constructs one, registers it withAddSingleton(registry)and returns it (:268-270).
- Why it's built this way:
internal sealed, because it is an implementation detail of one extension method and part of no public contract; the assembly's<InternalsVisibleTo Include="MMCA.Common.Aspire.Tests" />(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/MMCA.Common.Aspire.csproj:13) is what keeps it reachable from its tests. Scanning for anImplementationInstancerather than building a provider is deliberate: this runs during registration, when no provider exists yet. - Where it's used: The shared registration body fetches it once per call (
GatewayHealthCheckExtensions.cs:181) and claims each name in the loop (:181). The idempotence it buys is asserted by GatewayDownstreamHealthChecksTests (AddGatewayDownstreamHealthChecks_IsIdempotent, which calls the method twice with overlapping and differently-cased names). - Caveats / not-in-source: The registry is a registration-time artifact that stays registered as a singleton in the built provider; nothing consumes it at runtime. It also lives per
IServiceCollection, so two independently-built collections do not share claims, which is what makes the tests independent.
RedisConfigurationOptionsPipeline
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Caching·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Caching/RedisConfigurationOptionsPipeline.cs:19· Level 0 · class (static, internal)
- What it is: A one-method helper that builds the StackExchange.Redis
ConfigurationOptionsfor the two Redis connections this package opens outside Aspire's Redis client (the output-cache store and the PING health check's own connection), running them through the same post-configure steps Aspire's client options go through. It returnsnullwhen no such step is registered, so the caller keeps its plain connection-string path. - Depends on:
IServiceProvider,IPostConfigureOptions<ConfigurationOptions>andOptions.DefaultName(Microsoft.Extensions.Options), and StackExchange.RedisConfigurationOptions. No first-party type: it names neither MMCA.Common.Infrastructure'sIRedisConfigurationOptionsConfiguratornor any vendor adapter. Consumed by RedisCachingExtensions and RedisPingHealthCheck. - Concept introduced, reaching a configurator across a package boundary through a type both sides already know.
[Rubric §11, Security],[Rubric §15, Best Practices & Code Quality]. The class doc comment (RedisConfigurationOptionsPipeline.cs:7-18) states the problem. A Redis configurator, for example the Entra token login MMCA.Common.Azure registers throughAddAzureRedisEntraAuthentication(MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:232), is anIRedisConfigurationOptionsConfiguratordeclared in MMCA.Common.Infrastructure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/IRedisConfigurationOptionsConfigurator.cs:8-9), a package this one does not reference. Aspire's client reads its options through the options pipeline and picks the configurator up for free; a connection this package builds by hand from the connection string would not, and would authenticate with whatever access key the string carries (the condition the startup tripwire names,Integrations/HostIntegrationTripwire.cs:167). The meeting point is the abstraction both sides can name: the configurator registration adds anIPostConfigureOptions<ConfigurationOptions>(:12-16), and this helper replays every such step onto options it parses itself. Neither package learns the other's name. - Walkthrough:
CreateConfigured(services, connectionString)(:36,internal static) null-guardsservices(:38), collects every registeredIPostConfigureOptions<ConfigurationOptions>(:40) and returnsnullwhen there are none (:41-44). Otherwise it parses the connection string withConfigurationOptions.Parse(:46), applies each step underOptions.DefaultName(:47-50) and returns the configured options (:52).
- Why it's built this way: Returning
nullrather than parsed-but-unconfigured options leaves the no-configurator path exactly as it is: callers assign the result only when it is non-null, so a host without a configurator still connects from the connection string.internal, because it bridges two framework call sites and is no consumer extension point; the public extension point isAddRedisConfigurationOptionsConfigurator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:288). Routing the hand-built connections through the same post-configure steps as Aspire's client means one configurator registration covers every Redis connection the framework opens, which is what ADR-040 relies on for the output-cache store. - Where it's used:
AddRedisOutputCachingassigns its result toRedisOutputCacheOptions.ConfigurationOptionswhen non-null (Caching/RedisCachingExtensions.cs:115-123), and RedisPingHealthCheck calls it when opening its own connection (Health/RedisPingHealthCheck.cs:102). - Caveats / not-in-source: The connection string is parsed on every call and nothing is cached here; caching the result is the caller's concern. A post-configure step that throws surfaces where the options are resolved (the output-cache store or the health check), not at registration. Every registered post-configure step for
ConfigurationOptionsis replayed, whatever it configures.
TrustedCallerMode
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/TrustedCallerMode.cs:8· Level 0 · enum
- What it is: The two-value switch for how the edge limiter meters a request that proves the trusted-caller secret: against the end visitor it forwards, or not at all.
- Depends on: Nothing. Carried on GatewayRateLimitingSettings as
TrustedCallerModeand branched on by GatewayRateLimitingExtensions. - Concept introduced, exempting the caller without exempting the visitor.
[Rubric §11, Security],[Rubric §12, Performance & Scalability]. The trusted-caller secret exists because a server-rendered UI host sends every visitor's back-end calls from one address. Exempting that address outright stops the 429s, but it also leaves the visitor unmetered at the edge: every call the host makes on one visitor's behalf skips the per-IP window.PerVisitorkeeps the fix and closes that gap. The host forwards the visitor's address inX-Forwarded-For, and the limiter counts the call against that visitor's per-IP window and every named route policy keyed on the visitor, exactly as the visitor's own direct request would be (TrustedCallerMode.cs:10-16). The replica-wide concurrency ceiling still exempts a trusted caller in both modes (GatewayRateLimitingSettings.cs:160-167), because that ceiling bounds replica load, not a visitor (GatewayRateLimitingExtensions.cs:317-321). ADR-088 is the governing record for the edge tier. - Walkthrough:
PerVisitor = 0(:17) is the default and the zero value. A trusted-caller request that carries a visitor address takes that visitor's window; one with no visitor address (a background call) takes the no-limiter partition (:10-16).Exempt = 1(:23): every trusted-caller request takes the no-limiter partition on the per-IP window and the named route policies, whatever visitor address it carries (:19-22).
- Why it's built this way: The metered mode is the zero value, so a settings object built without naming the mode, or a configuration section that omits it, meters per visitor (
GatewayRateLimitingSettings.cs:168).Exemptis an explicit choice for a deployment that wants every trusted-caller request unmetered. An enum rather than aboolnames both behaviors at the configuration site. - Where it's used: Read once, in
ClientIpPartition(GatewayRateLimitingExtensions.cs:232-234), which extracts the visitor address throughTrustedCallerVisitorIp(:302) only underPerVisitor. Covered by GatewayTrustedCallerPerVisitorTests (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Gateway/GatewayTrustedCallerPerVisitorTests.cs). - Caveats / not-in-source:
PerVisitortrusts the address the caller writes: the limiter takes the right-mostX-Forwarded-Forentry left after the forwarded-headers step (GatewayRateLimitingExtensions.cs:270-276), so a trusted caller that forwards a wrong address meters the wrong visitor. Which calling-host component writes that header, and whether either consumer gateway overrides the default mode, is not determinable from this package's source.
GatewayRateLimitingSettings
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingSettings.cs:50· Level 1 · class (sealed)
- What it is: The bound configuration for the edge limiter: how many requests one client IP gets per window, how much work the replica will hold at once, which path prefixes are exempt, the header-plus-secret pair a synthetic-traffic run presents to skip both limiters, and the header-plus-secret pair and TrustedCallerMode that decide how a trusted internal caller is metered. Every property has a working default, so the section is optional.
- Depends on:
System.ComponentModel.DataAnnotations([Range],[Required],[StringLength]) and TrustedCallerMode. Consumed by GatewayRateLimitingExtensions. Its service-tier counterpart is RateLimitingSettings inMMCA.Common.API. - Concept introduced, the per-replica limiter and what it can and cannot promise.
[Rubric §11, Security],[Rubric §12, Performance & Scalability],[Rubric §29, Resilience]. The remarks on this type (GatewayRateLimitingSettings.cs:11-38) are the teaching material and are worth reading whole. Both limiters count in this process's memory, so the effective allowance is the configured number multiplied by the replica count: three replicas admit roughly 3 xPermitLimitper window from one client IP. That is the accepted trade, not an oversight. An edge limiter exists to stop one misbehaving caller from exhausting a replica's sockets and threads, and it must answer in microseconds on every request, whereas a shared counter puts a network round trip in front of the whole edge and fails open (or fails the edge) whenever the counter store blips. When a limit has to mean the same thing fleet-wide, the distributed counter inMMCA.Common.API'sRateLimitingSettings.Distributedis the tool. The second remark (:22-27) is the operational trap: partitioning is byConnection.RemoteIpAddress, soUseForwardedHeadersmust run beforeUseGatewayRateLimitingor every request behind an ingress is attributed to the ingress and collapses into one window. - Concept introduced, the synthetic-traffic bypass.
[Rubric §11, Security],[Rubric §12, Performance & Scalability]. The third remark (:28-34) names a failure mode that only appears once a system has a scheduled capacity proof: a load run drives its whole traffic from one runner IP, so the per-IP window cannot tell it from an unauthenticated flood and the run ends up measuring the limiter instead of the system. The answer here is a proof-of-secret, not a configuration switch: a run that presents the configured header carrying the configured secret takes the same no-limiter partition a bypassed path takes, and the whole mechanism is off unless the secret is set. - Concept introduced, generalizing the bypass to a trusted internal caller.
[Rubric §11, Security],[Rubric §29, Resilience].TrustedCallerHeaderName/TrustedCallerSecret(:120-156) apply the exact same proof-of-secret mechanism to a second, distinct problem: a server-rendered UI host makes all of its back-end calls, token refreshes above all, from ONE address on behalf of every signed-in visitor, so the per-IP window collapses the whole site into one partition and starts answering 429 under ordinary load. The per-IP limiter cannot tell that address apart from a genuine flood; the fix is not a bigger limit but a second, independently-configured secret that identifies a specific deployed component, never an end user's browser.TrustedCallerMode(:158-166) then decides what the proof buys: by default the call is counted against the end visitor the caller forwards inX-Forwarded-For, so the component escapes the shared-address collapse without its visitors escaping the limiter; only the concurrency ceiling exempts a trusted caller unconditionally. ADR-088 covers this amendment alongside the synthetic-traffic one. - Walkthrough:
SectionName = "GatewayRateLimiting"(:51), astatic readonly stringused for options binding.PermitLimit(:60,[Range(1, 1_000_000)]at:59) defaults to 120, requests per window per client IP per replica. Its doc comment (:53-58) states the deliberate divergence from the service tier: this applies to anonymous traffic too, because the service-side global limiter exempts anonymous callers (public reads are output-cached and Blazor Server traffic shares one host IP) and the edge is exactly where an unauthenticated flood has to be stopped.WindowSeconds(:64,[Range(1, 3600)]at:63) defaults to 60.GlobalConcurrencyLimit(:74,[Range(1, 1_000_000)]at:73) defaults to 200. Its doc comment (:66-72) explains why a concurrency cap sits beside a rate limit: the failure it guards against is a slow downstream backing requests up until the edge runs out of threads and sockets, which no rate limit prevents and only a ceiling on simultaneous work does. Excess is rejected immediately with 429 rather than queued, so a saturated edge sheds load instead of growing latency.BypassPathPrefixes(:85) is anIReadOnlyList<string>, empty by default, matched case-insensitively on whole path segments. The doc comment (:76-83) records that/health,/aliveand/.well-knownare always exempt regardless of this list, because probes and JWKS discovery run at high frequency by design and throttling them turns a traffic spike into a failed liveness probe and a container restart. It also states the entry rule: every entry must start with/, and a bad entry fails registration instead of failing every request. That rule is enforced by the property's[LeadingSlashPathPrefixes]attribute (:84), see LeadingSlashPathPrefixesAttribute.SyntheticTrafficHeaderName(:94,[Required]at:93) defaults to"X-Synthetic-Traffic-Key". Only the name lives here, and the doc comment (:87-92) says why that is safe inappsettings.json: the header is worthless without the secret, so renaming it is a coordination change rather than a security control.SyntheticTrafficSecret(:118,[StringLength(int.MaxValue, MinimumLength = 32)]at:117) is nullable and null by default, which disables the bypass entirely so no header value can claim it. The remarks (:101-116) carry two rules. It must come from a secret store or the environment (GatewayRateLimiting__SyntheticTrafficSecret) and never from a checked-inappsettingsfile, because a value in source control is a published key to the edge limiter. And the 32-character floor is validated at registration, so a short value fails startup rather than shipping a guessable bypass;StringLengthtreats null as valid, which is exactly the intended "off" state.TrustedCallerHeaderName(:128,[Required]at:127) defaults to"X-Internal-Caller-Key". Same shape asSyntheticTrafficHeaderName: only the name lives here, so it is safe inappsettings.json. The doc comment (:120-126) states that presenting it claims whichever treatmentTrustedCallerModeselects, the no-limiter partition or the forwarded visitor's own window.TrustedCallerSecret(:156,[StringLength(int.MaxValue, MinimumLength = 32)]at:155) is nullable and null by default, disabling the trusted-caller treatment entirely (:130-135). Its remarks (:136-154) carry the same two rules asSyntheticTrafficSecret: production must supply it from a secret store or the environment (GatewayRateLimiting__TrustedCallerSecret), never a checked-in file, and it must never be handed to client-side code since it identifies a deployed component, not an end user.TrustedCallerMode(:166) defaults to TrustedCallerMode.PerVisitor. The doc comment (:158-165) gives both modes:PerVisitorcounts a proven request against the end visitor's own per-IP window and route policies when the caller forwards the visitor's address inX-Forwarded-For, and exempts it when no visitor address is present;Exemptexempts every trusted-caller request. The replica-wide concurrency ceiling exempts a trusted caller in both modes. It carries no validation attribute.
- Why it's built this way:
sealedwithinit-only properties, so the settings object the limiter closes over cannot be mutated after validation. Data-annotation attributes rather than hand-written guards, because both entry points into the limiter validate them: the configuration overload throughValidateDataAnnotations().ValidateOnStart()and the object overload through an explicitValidator.ValidateObjectcall, which is ADR-070's fail-fast contract honoured on both paths. The per-replica choice, the anonymous inclusion, the two-tier bypass and the synthetic-traffic and trusted-caller amendments are all recorded in ADR-088, which extends ADR-019 with this fourth, edge tier. The trusted-caller secret is a second, independent property rather than a reuse ofSyntheticTrafficSecret, so the two exemptions can be granted, rotated and revoked one without the other. - Where it's used: Bound from the
"GatewayRateLimiting"section byAddGatewayRateLimiting(IConfiguration)(GatewayRateLimitingExtensions.cs:357-364) and read by GatewayRateLimitingExtensions' bypass checks and the two partition functions. Both consumers configure it in the gatewayappsettings.jsonbeside the route table: ADC keeps the defaults and bypasses/hubs(MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:21-26), because a SignalR negotiate-plus-reconnect storm from one shared office address is the pattern a per-IP window misreads as abuse; Store keeps the defaults and bypasses/Payments(MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:16-21), because a 429 to a Stripe webhook is a retry and eventually a disabled endpoint. The synthetic-traffic secret is deployment-only in both apps: a Key Vault secret namedsynthetic-traffic-secretmapped ontoGatewayRateLimiting__SyntheticTrafficSecretand present only when the parameter is supplied (MMCA.ADC/infra/main.bicep:979-982,:1690;MMCA.Store/infra/main.bicep:924-927), and ADC's scheduled load test presents it asX-Synthetic-Traffic-Key(MMCA.ADC/.github/workflows/load-test.yml:8-11).TrustedCallerSecretis read on the calling-host side byMMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/TrustedCallerHandler.csandDependencyInjection.cs. - Caveats / not-in-source: The range bounds constrain each value independently; nothing checks that
GlobalConcurrencyLimitis sensible relative toPermitLimit, or that a bypass prefix matches a real route. The multiplication by replica count is documented on the type but not enforced or measured anywhere in source. Neither secret has a rotation mechanism in source.
DownstreamServiceHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/DownstreamServiceHealthCheck.cs:41· Level 1 · class (sealed, internal)
- What it is: One
IHealthCheckthat GETs a single downstream service's/aliveendpoint through a service-discovery-resolvedHttpClient, negotiating the HTTP version when told to, and reports the outcome as the gateway's own health. - Depends on: DownstreamProbeVersion (its version profile),
IHttpClientFactory,IHealthCheck/HealthCheckResult/HealthCheckContext(ASP.NET Core diagnostics), andHttpRequestError/HttpVersionPolicy/Interlocked(BCL). The probed path comes from HealthEndpointPaths. Registered, named and budgeted by GatewayHealthCheckExtensions; itsReadytag comes from HealthCheckTags. - Concept introduced, dependency-aware readiness at the edge.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity],[Rubric §7, Microservices Readiness]. §29 assesses whether a partial failure is contained rather than amplified. A reverse-proxy gateway whose readiness reports only "this process is up" is routed traffic by the platform and then forwards it to services that are not answering, converting a downstream outage into a wall of 502s from a replica the platform believes is healthy. This check is the correction: readiness becomes "can this edge do useful work". ADR-088 is the governing record. - Concept introduced, latching a negotiated protocol.
[Rubric §12, Performance & Scalability],[Rubric §15, Best Practices & Code Quality]. The class doc (:22-30) argues the safety of the latch in one move: a service cannot change the protocol of its cleartext endpoint without a redeploy, and a redeploy of the topology restarts this gateway too, so a stale latch cannot outlive the endpoint that justified it. That is the reasoning pattern worth copying, a cache is safe when its invalidation is structurally guaranteed rather than scheduled. - Walkthrough:
- A primary constructor takes the factory, the Aspire service name (used only in messages), the named-client registration to resolve, and the registration-time DownstreamProbeVersion (
:39-43). ProbePathis astatic readonly Uribuilt fromHealthEndpointPaths.Alive(:46), the shared/aliveconstant (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/HealthEndpointPaths.cs:14), so the probe and the endpoint that answers it cannot drift apart by a typo. It probes/alive, not/health/ready, deliberately (doc comment:16-21): a downstream replica's readiness is that replica's own business and its ingress already routes around a warming instance, so probing readiness would make every rolling deployment downstream register as a gateway health failure. What the gateway needs to know is whether the service exists and is reachable at all.private int _latchedProbeVersion(:55) holds the settled version as the enum's underlying value, so zero (which isAuto) reads as "not settled yet". It is written withInterlocked.CompareExchangerather than a plain assignment because two readiness polls can overlap on a cold gateway: the first writer wins and nothing ever unlatches (:48-54).CheckHealthAsync(:58) null-guards the context (:62), creates the named client (:64), then branches:Autogoes toNegotiateAsync(:68-71), a pinned mode goes straight toSendProbeAsync(:73).- The outer catch (
:75-87) is narrow on purpose:HttpRequestException,TaskCanceledException,TimeoutExceptionandInvalidOperationException(unreachable, DNS-unresolvable, or slower than the probe budget) are reported ascontext.Registration.FailureStatuswith the exception attached, while thewhen (!cancellationToken.IsCancellationRequested)guard keeps host shutdown from being reported as a dependency fault. Reading the failure status from the registration rather than returningUnhealthydirectly is what lets the same check be re-tagged by a future caller without touching this file. The comment (:78-82) adds the second rule: nothing latches on this path, because a transient outage says nothing about which protocol the endpoint speaks and pinning the wrong one would outlive the outage. NegotiateAsync(:98) reads the latch withVolatile.Readand short-circuits to the settled version when there is one (:103-107). Otherwise it probes HTTP/2 and, on any HTTP response at all, latchesHttp2(:111-117); the comment there (:114-115) draws the distinction that matters, any response proves the endpoint speaks HTTP/2, and the status code is the health verdict rather than the protocol verdict. Its catch is scoped toHttpRequestException when (IsProtocolRefusal(ex) && !cancellationToken.IsCancellationRequested)(:119) and retries once as HTTP/1.1 inside the same check and token budget (:125-129), so the poll still returns a verdict; if that also fails, the outer handler reports the failure status and nothing latches.SendProbeAsync(:143) is where the version pair is applied, per request rather than on the client because one client serves both attempts of a negotiation (:151):Version = HttpVersion.Version11withRequestVersionOrLowerfor HTTP/1.1, otherwiseVersion20withRequestVersionExact(:152-158). A success status returnsHealthywith the numeric code formatted invariantly (:164-169); anything else returns the registration's failure status with the same message shape (:171-174).IsProtocolRefusal(exception)(:184-186) is the classifier and the whole safety of the fallback: onlyHttpRequestError.VersionNegotiationErrorandHttpProtocolErrorjustify retrying at another version, because DNS, a refused connection, a TLS fault or a timeout say nothing about which protocol the endpoint speaks (:177-181).Latch(version)(:192-196) is the singleInterlocked.CompareExchangeagainstAuto: first writer wins, a latched value is never replaced.
- A primary constructor takes the factory, the Aspire service name (used only in messages), the named-client registration to resolve, and the registration-time DownstreamProbeVersion (
- Why it's built this way:
internal sealed, since it is only ever constructed by the registration extension in the same assembly. It is a hand-rolled check rather than a reference to theAspNetCore.HealthChecks.Urispackage, and the class doc says why (:10-15): the whole check is one GET and a status comparison, and adding a package to a framework assembly that fifteen consumers restore is a real cost for no behaviour a dozen lines do not already give. The negotiate-then-latch shape means the fallback costs one extra request per downstream per process rather than one per poll. - Where it's used: Constructed inside the shared registration body (
GatewayHealthCheckExtensions.cs:209-213), one instance per named service, which is what makes the latch effectively per downstream. Covered by GatewayDownstreamHealthChecksTests, whose negotiation cases pin every branch (Probe_WhenAutoAndHttp2Answers_LatchesHttp2AndStopsNegotiating,Probe_WhenAutoAndHttp2IsRefused_FallsBackToHttp11WithinTheSameCheck,Probe_WhenAutoHasFallenBack_GoesStraightToHttp11,Probe_WhenAutoAndTheDownstreamIsUnreachable_ReportsUnhealthyWithoutLatching), and end to end by GatewayHardeningTests against the booted ADC Gateway host. - Caveats / not-in-source: The check has no retry and no memory for health: one failed probe fails the gateway's readiness for that poll. That is intentional given the 2 second budget, but it means a downstream that answers slowly under load flaps the gateway's readiness rather than degrading it. The latch is per instance, so it is reset by a gateway restart and by nothing else.
GatewayDownstreamHealthCheckOptions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:41· Level 1 · class (sealed)
- What it is: The per-call options object for
AddGatewayDownstreamHealthChecks. It carries exactly one setting today, the probe's HTTP version profile. - Depends on: DownstreamProbeVersion. Consumed by GatewayHealthCheckExtensions.
- Concept introduced, per-call options instead of a per-name map.
[Rubric §9, API & Contract Design],[Rubric §15, Best Practices & Code Quality]. The class doc (:35-39) states the shape decision plainly: one instance covers every service name passed to that call, so a gateway that wants to pin a profile for some of its heads makes one call per profile rather than carrying a per-name dictionary. That keeps the common case (one call, all downstreams, default options) a single readable line, and makes the uncommon case cost a second call rather than a new data structure. The long remarks onProbeVersion(:45-57) are the same negotiation argument taught at DownstreamProbeVersion, stated from the caller's side. - Walkthrough: One member.
ProbeVersion(:59) is aget/setproperty defaulting toDownstreamProbeVersion.Auto, which the doc describes as the value that "settles the question per downstream and needs no per-service configuration". Pinning either fixed value is documented as an optimisation for a downstream whose profile is known and fixed, to skip the one-time negotiation (:54-57). - Why it's built this way: Mutable
setrather thaninit, because the consumption pattern is the standardAction<TOptions>configurator (GatewayHealthCheckExtensions.cs:153-156), which needs to write to an instance the framework created. The registration body immediately reads the value into a local before the closure captures anything (:172-174), with the comment giving the reason: the registration must not hold the mutable options object, or a later call reusing the same instance would retro-change checks that are already registered. That pairing (mutable options, eagerly copied at registration) is worth noticing, it is how a configurator API stays convenient without leaking mutability into runtime state. - Where it's used: Constructed and configured inside
Register(:169-170), which both public overloads funnel into. No consumer passes a configurator today: ADC and Store both call theparams-only overload. Covered by GatewayDownstreamHealthChecksTests (Options_DefaultToAutoNegotiation,AddGatewayDownstreamHealthChecks_WithOptions_RegistersTheSameChecks, andProbeVersion_IsScopedToItsOwnRegistrationCall, which is the test that pins the eager copy).
RedisCachingExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Caching·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Caching/RedisCachingExtensions.cs:40· Level 0 · class (static)
- What it is: The framework-owned way to wire a host to Redis.
AddRedisCaching()registers the distributed cache plus theIConnectionMultiplexerclient, andAddRedisOutputCaching()backs the ASP.NET Core output cache with the same instance, riding that client's connection rather than opening its own. Both are no-ops when the connection string is absent, and both exist specifically so a host never calls Aspire's Redis integrations directly. - Depends on: The Aspire Redis client integrations (
AddRedisDistributedCache,AddRedisClient),Microsoft.AspNetCore.OutputCaching.StackExchangeRedis(AddStackExchangeRedisOutputCache,RedisOutputCacheOptions) and StackExchange.Redis'sIConnectionMultiplexer, overIHostApplicationBuilder. It pairs with RedisPingHealthCheck and HealthCheckTags (the replacement check registered from Extensions), and downstream with HybridCacheService, the two-level cache that needs the multiplexer. - Concept introduced, wrapping a third-party integration to own its health-check contract.
[Rubric §29, Resilience & Business Continuity],[Rubric §13, Observability & Operability],[Rubric §11, Security],[Rubric §15, Best Practices & Code Quality]. The class doc comment (RedisCachingExtensions.cs:9-39) is a production incident write-up, dated 2026-09-02, and it is the clearest worked example in the codebase of why the tag vocabulary above is load-bearing. Aspire's Redis integrations register theAspNetCore.HealthChecks.Redischeck under the nameStackExchange.Rediswith no tags (:14-16). The readiness endpoint fromMapDefaultEndpoints()includes every check that is not taggedliveoroptional, so an untagged check silently gates readiness (:16-17). That check issuesCLUSTER INFOwhenever the client detects a clustered server, and Azure Managed Redis (Enterprise tier, port 10000) is detected as a cluster by StackExchange.Redis 3.x, which refuses the command without admin mode (:17-20). Every probe therefore threw against a healthy cache, every replica reported not ready, and the platform stopped routing traffic the applications were perfectly able to serve (:20-21). The teaching point is the shape of the fix (:24-28): rather than patching a tag onto someone else's registration, the Aspire checks are switched off at the source withDisableHealthChecksand Common contributes its own PING-only check, namedredisand taggedOptional, fromAddInfrastructureHealthChecks(). - Concept introduced, one connection that every Redis consumer rides.
[Rubric §11, Security],[Rubric §31, Cost / FinOps]. The last paragraph of the class doc (:30-38) states the second contract: a Redis configurator registered throughAddRedisConfigurationOptionsConfigurator(MMCA.Common.Infrastructure; for example the Entra token login ofAddAzureRedisEntraAuthentication) reaches the one connection these calls open. The client reads its options from the options pipeline the configurator registration post-configures, and the distributed cache and the output-cache store both ride that client'sIConnectionMultiplexerinstead of connecting on their own. With no configurator registered, the connection is made from the connection string alone. A replica therefore holds one Redis connection rather than two, and there is exactly one place a credential has to reach (doc comment:93-100). - Walkthrough:
DefaultConnectionName = "redis"(:45) is the connection-string name every MMCA host uses for its Redis resource, so the two methods default to it and a host normally calls them with no arguments.- Both methods live in a generic
extension<TBuilder>(TBuilder builder) where TBuilder : IHostApplicationBuilderblock (:47-48), the same shape as the other opt-in host extensions in this group. AddRedisCaching(connectionName = DefaultConnectionName)(:70) returns immediately whenGetConnectionString(connectionName)is null or blank (:72-75). Past that gate it callsbuilder.AddRedisDistributedCache(connectionName, settings => settings.DisableHealthChecks = true)(:77) andbuilder.AddRedisClient(connectionName, settings => settings.DisableHealthChecks = true)(:78). The doc comment (:54-63) pairs it withAddCommonHybridCacheWhenRedisConfigured(MMCA.Common.Infrastructure), the cache service over this distributed cache, and says why the client is registered alongside the cache on purpose: the two-level cache keeps its prefix-invalidation generation tokens on it, and without it an ICacheInvalidating command's invalidation reaches only the replica that ran the command; the Redis distributed lock, the distributed rate limiter and theredisPING health check all resolve it too. A cross-replica invalidation that silently stays local produces no error and no log line, which is why the two registrations are welded together in one call.AddRedisOutputCaching(connectionName = DefaultConnectionName)(:112) applies the same connection-string gate (:114-117). Past it, whenHasRedisClientfinds no client yet (:119) it registers one itself withAddRedisClient(connectionName, settings => settings.DisableHealthChecks = true)(:121), so the method stands alone even whenAddRedisCachingwas not called. It then registers the store with an empty configurator,AddStackExchangeRedisOutputCache(static _ => { })(:124), and adds aConfigure<IServiceProvider>step onRedisOutputCacheOptions(:125-128) that setsoptions.ConnectionMultiplexerFactoryto a factory returningservices.GetRequiredService<IConnectionMultiplexer>(). The store therefore never parses a connection string of its own: it is handed the host's multiplexer. The doc comment (:83-106) covers four things: cross-replica tag eviction is the reason it exists (the built-in store is per-replica memory, so anEvictByTagAsyncreaches only the replica that served the mutation); it should be called beforeAddOutputCache(...), which registers its store withTryAddso the explicit Redis store wins either way, but the order documents the intent; the store rides the client and should come afterAddRedisCaching, asAddMmcaServiceHostdoes (:93-100); and this integration registers no health check of its own, so there is nothing to disable in this method.HasRedisClient(services)(:137, private static) walks the service collection and returnstrueon the first descriptor whoseServiceTypeisIConnectionMultiplexerand which is not keyed (:139-145). Only an unkeyed registration counts, because that is the oneGetRequiredService<IConnectionMultiplexer>()resolves.
- Why it's built this way: The wrapper is a structural fix, not a patch. A tag added to another package's registration would have to be re-applied every time that package changed its registration shape, and the incident showed that an untagged check is invisible until a specific server tier trips it. Disabling the vendor checks at the source and contributing one PING-only check the framework owns makes the readiness contract explicit and testable. ADR-025 is the record for the "readiness checks are PING-class" rule. Handing the output-cache store the shared multiplexer, rather than letting it build a second connection, halves the connections per replica and means a Redis configurator (for example the Entra token login) applies to the store by construction instead of through a parallel options path. The multiplexer is resolved lazily through
Configure<IServiceProvider>, so the factory sees the final container, configurators registered after this call included. - Where it's used: No ADC or Store host calls these methods directly any more. The composed service host,
AddMmcaServiceHostinMMCA.Common.ServiceHost, callsbuilder.AddRedisCaching()unconditionally right afterAddServiceDefaults()(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:91), relying on its self-gate, and callsbuilder.AddRedisOutputCaching()only when the host setsUseRedisOutputCaching(:92-95), beforeAddCommonHybridCacheWhenRedisConfigured(:97). All four ADC services and all three Store services build throughAddMmcaServiceHost(for exampleMMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88,MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:32); ADC Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:135) and Store Catalog (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:53) setUseRedisOutputCaching = true. Covered by RedisReadinessSafetyTests, which asserts that the wrapper registers no untagged Aspire check, that every Redis check is taggedOptional, that the readiness predicate admits none of them, and that both methods register nothing without a connection string. - Caveats / not-in-source: The methods gate on the connection string only; nothing here verifies the endpoint is reachable, which is what the separate PING check is for.
HasRedisClientchecks only for an unkeyedIConnectionMultiplexerregistration: a host that registered its client under a key gets a second, unkeyed client fromAddRedisOutputCaching. CallingAddRedisOutputCachingbeforeAddRedisCachingalso works but registers the client from the output-cache call first, andAddRedisCachingthen callsAddRedisClientagain for the same name; the doc comment asks for theAddRedisCaching-first order. Not determinable from this file: whether the store's multiplexer factory is invoked once or per operation (that isMicrosoft.AspNetCore.OutputCaching.StackExchangeRedisbehavior).
GatewayRateLimitingExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:48· Level 2 · class (static)
- What it is: The edge rate limiter: a per-client-IP fixed window chained with a process-wide concurrency ceiling, registered by
AddGatewayRateLimitingand inserted into the pipeline byUseGatewayRateLimiting. A proven trusted internal caller is metered against the visitor it forwards, or exempted, as TrustedCallerMode selects. Every 429 it produces carries aRetry-Afterheader whenever the rejecting limiter can say when to come back. - Depends on: GatewayRateLimitingSettings (its configuration), TrustedCallerMode, RetryAfterRejection (the shared
OnRejectedwrapper that writesRetry-After,MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:19), ClientAddressKey (the shared per-IP partition key,MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:31) and RemainingWindowFixedWindowRateLimiter (the fixed window that reports the time left in it, fromMMCA.Common.RateLimiting,:12), plusSystem.Threading.RateLimiting(PartitionedRateLimiter,RateLimitPartition,FixedWindowRateLimiterOptions,ConcurrencyLimiterOptions,MetadataName), ASP.NET Core rate limiting (OnRejectedContext),CryptographicOperations(BCL cryptography),IServiceCollection/IApplicationBuilder, andValidator(BCL data annotations). - Concept introduced, two limiters that answer two different questions.
[Rubric §11, Security],[Rubric §12, Performance & Scalability],[Rubric §29, Resilience]. The class doc (:15-43) states both halves. First (:18-24), the edge posture is the deliberate opposite of the service tier's:AddCommonRateLimitinginMMCA.Common.APIpartitions by authenticated user and exempts anonymous traffic, but at the edge there is no authenticated identity yet (the gateway forwards the token, it does not validate it into a principal) and anonymous traffic is precisely what has to be bounded, so the partition key is the client IP and anonymity is not an exemption. Second (:25-29), the two limiters are chained rather than merged because a fixed window bounds how fast one caller may arrive, while a concurrency limiter bounds how much work the replica holds at once regardless of who sent it; a request must satisfy both, and the second failure is one a per-IP window structurally cannot see. ADR-088 extends ADR-019 with this fourth tier. - Concept introduced, a constant-time secret comparison at the edge.
[Rubric §11, Security],[Rubric §14, Testability].PresentsSecret, the shared check behind both bypasses, is small but is the only place in this chapter that handles a secret, and the remarks onIsSyntheticTraffic(:117-124) name three separate defences that are easy to get wrong individually: the comparison runs over UTF-8 bytes throughCryptographicOperations.FixedTimeEquals, which is constant time for equal-length inputs and returns false for unequal lengths without leaking anything past the length an attacker already chose; exactly one header value is required, so a caller cannot spray candidates in a multi-valued header; and the whole path is short-circuited when no secret is configured, so a bypass cannot be claimed by presenting the header alone. - Concept introduced, two independent secrets exempting the same partition.
[Rubric §11, Security],[Rubric §9, API & Contract Design].IsSyntheticTrafficandIsTrustedInternalCallerare two distinct checks over two distinct header/secret pairs, but they both fall through the samePresentsSecrethelper and both feed the sameIsExemptFromLimitersunion (:204-207). The remarks onIsTrustedInternalCaller(:146-153) state the case it generalizes the synthetic-traffic bypass for: a server-rendered UI host makes every back-end call, token refreshes above all, from ONE address on behalf of every signed-in visitor, so the per-IP window collapses the whole site into one partition under ordinary load. Keeping the two secrets separate properties (never merged into one "bypass secret") is deliberate: a load-test runner's credential and a UI host's credential are granted, rotated and revoked independently. The two proofs also buy different things. Synthetic traffic is exempt from both limiters. A trusted caller is exempt from the concurrency ceiling, but on the per-IP window it is decided first, by TrustedCallerMode, so under the defaultPerVisitormode a call that forwards a visitor address counts against that visitor's own window (doc comments:137-141,:195-199). The trusted-caller decision is also the only one that outlives this limiter: the per-IP partition stamps it intoHttpContext.Items, either the exemption flag or the visitor's address, so the named per-route policies of GatewayRoutePolicyExtensions, which run after the global limiter and cannot see these settings, apply the same decision without re-checking the secret. - Concept introduced, a 429 that says when to retry.
[Rubric §9, API & Contract Design],[Rubric §29, Resilience]. A bare 429 leaves a client to guess its back-off.RetryAfterRejection.WithRetryAfterHeader(MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42) reads the rejecting lease'sMetadataName.RetryAfterhint and writes it asRetry-Afterin whole seconds, rounded up so a client never retries before the window has moved on (RetryAfterRejection.Format,RetryAfterRejection.cs:27, a copy ofRetryAfterHeader.Formatkept because the Gateway package references no MMCA project, with a test pinning the two together, remarksRetryAfterRejection.cs:12-18). Only the fixed-window limiter supplies that hint; a concurrency rejection carries none and goes out without the header (doc commentRetryAfterRejection.cs:33-39). The hint is honest: the framework's own fixed-window limiter always reports the whole window as itsRetry-After, so every fixed window here is aRemainingWindowFixedWindowRateLimiterthat reports the time actually left in the window (comment:304-306).OnRejectedis a single shared slot onRateLimiterOptions, and the route-policy registration inMMCA.Common.Gatewayinstalls the same writer (the same linked source file), so each registration wraps whatever callback is already there rather than overwriting it (:388-390). The calling side reads the same header: the service-defaults retry in Extensions declines to retry a 429 whoseRetry-Afterexceeds its wait budget. - Walkthrough:
- Three partition-key constants (
:51,:54,:57):"__bypass"for anything exempt,"__unknown-ip"for an unattributable caller, and"__gateway", the single key the concurrency limiter counts everything against. TrustedInternalCallerItemKey = "MMCA.Common.Gateway.TrustedInternalCaller"(:67) is theHttpContext.Itemskey the per-IP partition stamps (valuetrue) when a proven trusted caller takes the no-limiter partition. Its doc comment (:59-66) explains why the literal is duplicated rather than shared: the named per-route policies ofMMCA.Common.Gatewayread it (the same literal isGatewayRoutePolicyExtensions.TrustedInternalCallerItemKey), the global limiter runs before the endpoint policy in the same middleware, and the Gateway package deliberately takes no reference to this one, so the proof travels on the request rather than being re-derived.TrustedCallerVisitorIpItemKey = "MMCA.Common.Gateway.TrustedCallerVisitorIp"(:76) is its per-visitor twin: the per-IP partition stamps the visitor'sIPAddressunder it when a trusted caller is metered underPerVisitor, and the named route policies key on that address instead of the connecting one (doc comment:69-75, same duplicated-literal arrangement asGatewayRoutePolicyExtensions.TrustedCallerVisitorIpItemKey).ForwardedForHeaderName = "X-Forwarded-For"(:79) is the header the visitor address is read from.- The
OnRejectedwriter is not defined in this class: the registration below installsRetryAfterRejection.WithRetryAfterHeader(previous)(MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42), one internal source file linked intoMMCA.Common.API,MMCA.Common.Aspire,MMCA.Common.UI.WebandMMCA.Common.Gateway(remarksRetryAfterRejection.cs:12-18). It returns a callback that, whencontext.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter)succeeds, setsResponse.Headers.RetryAfter = Format(retryAfter)(RetryAfterRejection.cs:46-49), then invokespreviousif one was configured, or completes (RetryAfterRejection.cs:51). The header is written before the earlier callback runs. AlwaysBypassedPrefixes = ["/health", "/alive", "/.well-known"](:86). The comment above it (:81-85) is the reason these are hard-coded rather than configured: probes and JWKS discovery run at high frequency by design, and throttling them converts a traffic spike into a failed probe and a container restart.IsBypassed(path, settings)(:98) concatenates the hard-coded prefixes with the host's configuredBypassPathPrefixesand matches withPathString.StartsWithSegments(..., OrdinalIgnoreCase)(:103-106), skipping blank entries. Segment matching is the detail:/healthzis not matched by/health. It isinternalrather thanprivateso the matcher is unit-testable.IsSyntheticTraffic(httpContext, settings)(:125) delegates straight toPresentsSecretwithSyntheticTrafficHeaderName/SyntheticTrafficSecret(:130-133).IsTrustedInternalCaller(httpContext, settings)(:161) delegates the same way withTrustedCallerHeaderName/TrustedCallerSecret(:166-169). It only establishes the proof; what the proof buys on the per-IP window is decided inClientIpPartition.PresentsSecret(httpContext, headerName, expectedSecret)(:176) is the shared implementation both delegate to: returnsfalsewhen either the secret or the header name is blank (:178-181), requires exactly one header value (:184-187), and finishes withCryptographicOperations.FixedTimeEqualsover the UTF-8 bytes of both sides (:189-192).IsExemptFromLimiters(httpContext, settings)(:204) is the union: bypassed path, or proven synthetic traffic, or a proven trusted internal caller (:205-207). The concurrency ceiling applies it as is; on the per-IP window the trusted-caller case is decided first, so there it reaches only bypassed paths and synthetic traffic (doc comment:195-199).ClientIpPartition(httpContext, settings, timeProvider = null)(:222) first handles a proven trusted caller (:230-250). UnderPerVisitorit reads the visitor address throughTrustedCallerVisitorIp; underExemptthe address is treated as absent (:232-234). When there is no visitor address, or the path is bypassed, or the request also proves synthetic traffic, it stampshttpContext.Items[TrustedInternalCallerItemKey] = trueand returnsRateLimitPartition.GetNoLimiter(BypassPartitionKey)(:236-244), the inline comment naming the reason (the named per-route policies run after this limiter and cannot see these settings). Otherwise it stamps the visitor address underTrustedCallerVisitorIpItemKeyand returns the fixed window keyed onClientAddressKey.For(visitorIp)(:248-249), the same partition key a direct request from the visitor takes. A request that is not a trusted caller takes the no-limiter partition whenIsExemptFromLimitersapplies (:252-255). Otherwise its key isClientAddressKey.For(Connection.RemoteIpAddress)(:257-258), the shared client-address key: an IPv4-mapped address is unmapped to IPv4 and an IPv6 address is masked to its /64 prefix (MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:42, rationale in the remarks atClientAddressKey.cs:12-19), so a caller rotating the low 64 bits of an IPv6 address, or reaching the gateway under both spellings of one IPv4 address, stays in one window. When that key is null (no remote address) it takesGetNoLimiter(UnknownIpPartitionKey)(:259-264), a fail-open choice whose comment explains the alternative it rejects, that collapsing every unattributable request into one shared bucket would throttle an in-processTestServerand the integration tier to a standstill; and otherwise takes the fixed window keyed on that address key (:266). ThetimeProviderparameter (null in production, the system clock) exists so tests can drive the remaining-window hint. Only this partition stamps the items:ConcurrencyPartitiondoes not.TrustedCallerVisitorIp(httpContext)(:280,internal static) returnsnullwhenX-Forwarded-Foris absent (:284-288), otherwise joins every header value, splits on commas, takes the right-most non-empty entry (:290-292) and parses it withIPEndPoint.TryParse, returning the address ornull(:294-296). The doc comment (:269-276) explains the right-most choice:UseForwardedHeadershas already consumed the hop the gateway's own ingress appended, so the right-most remaining entry is the one the trusted caller wrote.FixedWindowPartition(partitionKey, settings, timeProvider)(:300, private) builds oneRemainingWindowFixedWindowRateLimiterper key throughRateLimitPartition.Get(:307-315), withPermitLimitandWindowfrom settings andQueueLimit = 0, so overage is rejected immediately rather than queued. The comment (:304-306) gives the reason for not usingRateLimitPartition.GetFixedWindowLimiter: the framework limiter'sRetry-Afteris always the whole window, and the partitioned limiter drives replenishment on its own timer either way.ConcurrencyPartition(httpContext, settings)(:326) appliesIsExemptFromLimiters, so every proven trusted caller is exempt here in both modes (doc comment:317-321), and otherwise returns one concurrency limiter on the single"__gateway"key withGlobalConcurrencyLimitpermits and, again,QueueLimit = 0(:333-340).AddGatewayRateLimiting(IConfiguration configuration)(:352, in anextension(IServiceCollection services)block at:343) binds the"GatewayRateLimiting"section throughAddOptions().Bind(section).ValidateDataAnnotations().ValidateOnStart()(:357-361), then delegates to the object overload with an eagerly-bound copy, falling back to defaults when the section is absent (:363-364).AddGatewayRateLimiting(GatewayRateLimitingSettings settings)(:374) is the overload every path funnels into. It runsValidator.ValidateObject(settings, ..., validateAllProperties: true)at registration (:382), with the reasoning inline in the comment above it (:379-381): the limiter closes over this settings instance rather than resolvingIOptionsper request, so an out-of-range value (or a secret under 32 characters, synthetic or trusted-caller) has to throw where it is configured, not at the first throttle. It then callsAddRateLimiter(:384), setsRejectionStatusCodeto 429 (:386), chains the header writer withoptions.OnRejected = RetryAfterRejection.WithRetryAfterHeader(options.OnRejected)(:390), and assignsoptions.GlobalLimiter = PartitionedRateLimiter.CreateChained(...)over the two partition functions (:395-399). Assignment rather thanAddPolicyis deliberate (:392-394): calling the method twice replaces the limiter instead of throwing on a duplicate policy name.UseGatewayRateLimiting()(:412, in anextension(IApplicationBuilder app)block at:404) null-guards (:414) and returnsapp.UseRateLimiter()(:415). Its doc comment (:406-410) carries the ordering contract: afterUseForwardedHeaders()so the client IP is the caller's rather than the ingress's, and before the proxy is mapped.
- Three partition-key constants (
- Why it's built this way: Pure static partition functions with
internalvisibility make the decisions that actually contain the policy (which paths are exempt, which requests prove which secret, which partition a request lands in) assertable without a running server, which is[Rubric §14, Testability]applied at the smallest useful granularity. Both secret checks funneling through onePresentsSecretprivate helper means the constant-time comparison and the multi-value guard are written and reviewed once, not twice. WrappingOnRejectedrather than assigning it lets the global limiter and the per-route policies share one slot without either silently dropping the other's callback. Validating in the object overload rather than only through the options pipeline closes the second way in. Keying every fixed window through the sharedClientAddressKeykeeps the per-IP window, the per-visitor window and the named route policies on one key definition, so an IPv6 /64 or a dual-stack spelling cannot buy a second window at one layer and not the other. And the in-memory, per-replica design is accepted rather than solved (see GatewayRateLimitingSettings): an approximate ceiling that needs no network call and cannot fail is the right shape for the one process the whole fleet sits behind. The class carries the same scopedCA1708suppression as its siblings. - Where it's used: Registered in both gateways from configuration (
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:89,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:96) and inserted into the pipeline before the proxy is mapped (ADCProgram.cs:186, StoreProgram.cs:181).IsTrustedInternalCaller's counterpart on the calling side lives inMMCA.Common.UI.Web'sTrustedCallerHandlerandDependencyInjection.cs, which attach the same header/secret pair to outbound calls. Covered by GatewayRateLimitingTests (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Gateway/GatewayRateLimitingTests.cs),GatewayTrustedCallerTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Gateway/GatewayTrustedCallerTests.cs), GatewayTrustedCallerPerVisitorTests (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Gateway/GatewayTrustedCallerPerVisitorTests.cs) and GatewayRetryAfterTests (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Gateway/GatewayRetryAfterTests.cs), and end to end by GatewayHardeningTests in both apps (MMCA.ADC/Tests/Hosts/MMCA.ADC.Gateway.Tests/GatewayHardeningTests.cs,MMCA.Store/Tests/Hosts/MMCA.Store.Gateway.Tests/GatewayHardeningTests.cs). The E2E lift that raises these limits for a CI run lives in the AppHost tier (Extensions'WithE2eGatewayRateLimitLift). - Caveats / not-in-source: The limiter closes over an eagerly-bound settings copy, so a configuration reload does not change the live limits: a change takes a restart. Both the synthetic-traffic and trusted-caller bypasses are shared secrets with no rotation mechanism in source; rotating either means redeploying the affected host(s) with a new Key Vault value. A 429 from the concurrency ceiling carries no
Retry-After, because that limiter offers no retry hint. UnderPerVisitorthe limiter believes the right-mostX-Forwarded-Forentry a proven trusted caller sends, so the accuracy of per-visitor metering is only as good as the address the calling host forwards; an entry that does not parse as an address falls back to the no-limiter partition. Because an IPv6 caller is keyed by its /64 prefix, distinct clients that share one /64 share one window.
GatewayHealthCheckExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayHealthCheckExtensions.cs:72· Level 5 · class (static)
- What it is: Two overloads of
AddGatewayDownstreamHealthChecksthat register adownstream-{name}health check (reported on/health, kept off readiness and liveness) and a matching namedHttpClientfor each service the gateway fronts, one taking just the names and one taking a per-call options configurator. - Depends on: DownstreamServiceHealthCheck (the check it constructs), GatewayDownstreamHealthCheckOptions / DownstreamProbeVersion (the version profile), GatewayDownstreamRegistry (the de-duplication ledger), HealthCheckTags (the
Optionaltag), plusIServiceCollection,IHttpClientFactoryandHealthCheckRegistration(ASP.NET Core). It relies on the service discovery that Common.Aspire Extensions'AddServiceDefaults()wires onto every client. - Concept introduced, service discovery as the address book for a health probe.
[Rubric §7, Microservices Readiness],[Rubric §13, Observability & Operability],[Rubric §29, Resilience]. Nothing here hard-codes a host or a port: the client'sBaseAddressis the literalhttp://{name}, the Aspire service-discovery form, which the resolver rewrites into the real endpoint at request time (comment:196-198). That is what lets the same registration work unchanged against a local AppHost with dynamic ports and against Container Apps. The second idea is the tag choice, argued in two parts in the remarks (:115-134). TaggingOptionalputs the check on/healthbut keeps it off both/health/readyand/alive(:117-118). A deployment usually runs one gateway in front of every route, so a gateway made unready by one downstream outage would stop serving the healthy routes too: one failed service becomes a whole-site outage, and a downstream that scales to zero or rolls a deployment looks like one; deployed consumers hit exactly that and had to point the gateway's readiness probe at/aliveto get away from it (:118-123). Restarting the gateway fixes nothing about a downstream outage either, so the checks gate neither probe: the gateway's readiness is its own warm-up, and a request to a service that is down fails on that service's routes alone (:123-126). The failure status is stillUnhealthy, notDegraded, because/healthanswers503only for Unhealthy, so an availability test or dashboard polling the gateway's/healthstill alerts on a downstream outage and the report names the service that failed (:129-132). ADR-088 is the record. - Walkthrough:
- Shared vocabulary:
CheckNamePrefix = "downstream-"(:75),ClientNamePrefix = "gateway-downstream-"(:78), and the helpersCheckName(serviceName)(:91) andClientName(serviceName)(:96) that apply them. Allinternal, so the tests can assert the exact registered names. ProbeTimeout = TimeSpan.FromSeconds(2)(:86). Its doc comment (:80-85) is the reasoning worth keeping: this runs on every/healthround, once per downstream, and "a probe that takes longer than the poll interval turns the report into a queue"; a service that cannot answer a liveness ping in two seconds is not one the gateway should be routing to anyway.- Two public overloads sit in one
extension(IServiceCollection services)block (:98).AddGatewayDownstreamHealthChecks(params string[] serviceNames)(:135) andAddGatewayDownstreamHealthChecks(Action<GatewayDownstreamHealthCheckOptions>? configure, params string[] serviceNames)(:153) both delegate to the privateRegister(:136,:156), so there is exactly one registration body and the two entry points cannot drift. Register(services, configure, serviceNames)(:166) null-guards both collections (:171-172), builds the options and applies the configurator (:174-175), then copiesoptions.ProbeVersioninto a local (:179) with the comment stating why (:177-178): the registration closure must not hold the mutable options object, because a later call reusing the same instance would retro-change these checks.- It fetches the registry (
:181) and the health-checks builder (:182), then loops. Blank names and names an earlier call already claimed are skipped (:186-189), which is what makes the method idempotent. - For each surviving name it registers a named client whose
BaseAddressishttp://{name}and whoseTimeoutisProbeTimeout(:194-206). Two comments there matter: the client timeout is the real probe budget while the registration timeout below only bounds the health-check service's own wait (:196-198), and the HTTP version is deliberately not pinned on the client because it belongs to the request, since underAutoa single poll may send both versions (:202-205). - The probe client carries no resilience handler.
.ConfigureAdditionalHttpMessageHandlers(...)(:216-225) walks the handler list backwards and removes everyResilienceHandler. The comment (:208-215) gives the reason:AddServiceDefaults()puts the standard Polly pipeline on every factory client, and its one retry (about two seconds of backoff) lands inside the two-second probe budget, whereas a refused HTTP/2 attempt must reach the check at once so it can fall back to HTTP/1.1, and a probe is re-sent on the next poll anyway. It is whatRemoveAllResilienceHandlers()does, written against the stable handler hook because that helper is stillEXTEXP0001(experimental). - One check instance per downstream, held as a keyed singleton.
services.AddKeyedSingleton(checkName, ...)(:233-239) constructs the DownstreamServiceHealthCheck once withIHttpClientFactory, the service name, the client name and the captured probe version. The comment (:227-231) is the reason: the health-check service rebuilds a check from its registration factory on every poll, so a factory that news one up would drop the latched HTTP version between polls and renegotiate each time (the latch itself is already safe under overlapping polls,Interlocked, first writer wins). - It then adds a
HealthCheckRegistration(:241-246) namedcheckNamewhose factory merely resolves that singleton withGetRequiredKeyedService<DownstreamServiceHealthCheck>(checkName)(:243), withfailureStatus: HealthStatus.Unhealthy(:244),tags: [HealthCheckTags.Optional](:245) andtimeout: ProbeTimeout(:246). Because Extensions' readiness predicate excludes theOptionaltag and/aliveadmits onlyLive, the tag alone is what keeps these checks out of both probes.
- Shared vocabulary:
- Why it's built this way: A
paramsarray, so a gateway lists its downstreams in one line that reads like the topology, and an options overload rather than a per-name map, so the uncommon case costs a second call (see GatewayDownstreamHealthCheckOptions). Idempotence is engineered rather than assumed, because a duplicate health-check name is a startup exception (see GatewayDownstreamRegistry). The class carries the scopedCA1708suppression (:68-71) for theextension(T)analyzer false positive. Keeping the checks on/healthbut off both probes splits two questions that used to share one answer: "should the platform route to this gateway" (its own warm-up) and "is everything behind it reachable" (the aggregate report an operator or availability test reads). And the whole kit lives inMMCA.Common.Aspirerather thanMMCA.Common.APIbecause of a packaging constraint ADR-088 names explicitly: a YARP host has no controllers, so it never takes the API package, and anything the edge owns has to be reachable from the Aspire package alone. - Where it's used:
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:105with four names (identity,conference,engagement,notification) andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:124with three (catalog,identity,sales). Both are single calls, and bothProgram.csfiles carry a long comment above the call (ADC:91-104, Store:99-123) noting that the Container Apps readiness probe targets/aliverather than this aggregate, and explaining why no per-service pin is warranted now that the probe negotiates, the Store one naming the exact Kestrel log line and the e2e run where an h2c-pinned probe reported a Sales outage that did not exist). Covered by GatewayDownstreamHealthChecksTests (one check per service, the client registration, no pinned client version, idempotence, blank names) and by GatewayHardeningTests against the booted ADC host. - Caveats / not-in-source: The service names are strings with no compile-time relationship to the
ReverseProxycluster destinations inappsettings.json; a typo registers a check that can never pass rather than failing the build, and since the check isOptionalthat typo shows up only on/health, never as an unready gateway. A downstream outage likewise never takes the gateway out of rotation: alerting on it depends on something polling the gateway's/health. The 2 second budget is a constant with no configuration knob.
GatewayCorrelationMiddleware
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayCorrelationMiddleware.cs:30· Level 9 · class (sealed)
- What it is: Middleware that guarantees every request entering the edge carries an
X-Correlation-ID, writing the value onto the request headers when the caller supplied none or an unusable one (over 64 characters is cut, non-printable-ASCII is replaced), and echoing it back on the response. - Depends on:
RequestDelegate,HttpContextandSystem.Diagnostics.Activityonly. Registered through GatewayCorrelationExtensions. It is the edge twin of CorrelationIdMiddleware inMMCA.Common.API. - Concept introduced, ensuring an id rather than reading one.
[Rubric §13, Observability & Operability],[Rubric §13, Observability & Operability]. A correlation id minted independently by each service is not a correlation id: a browser call crossing the gateway into two services produces two unrelated ids, neither of them present in the gateway's own logs, and the one process guaranteed to see the request exactly once is the only one not stamping it. The fix is not "log an id at the edge" but "write the id onto the outbound request", because the service-side middleware adopts a header that is already present instead of minting its own (doc comment:19-25). ADR-088 records this as the first of the three responsibilities the edge owns, extending ADR-041's correlation id one hop outward. - Walkthrough:
HeaderName = "X-Correlation-ID"(:36), apublic const. Its doc comment (:31-35) flags that this is deliberately the same literal asCorrelationIdMiddleware.HeaderNameinMMCA.Common.APIrather than a shared reference: the two packages share no dependency, and the whole point of the pair is that the edge and the services agree on the string. (Compare Extensions, which mirrors two configuration section names for the same reason and pins the duplication with a test.)MaxLength = 64(:43,internal const, doc comment:38-42) is the longest correlation id kept. It is the twin ofCorrelationIdMiddleware.MaxLengthinMMCA.Common.API(the persisted column width), repeated as a literal on purpose for the same no-shared-reference reason asHeaderName.InvokeAsync(HttpContext)(:51) null-guards the context (:53) and reads the first inbound value of the header intoheader(:55).- The id is then computed in one expression (
:62-64): a non-blank inbound value passes throughSanitize(:87), and when that yields null (blank, or rejected) the id falls back toActivity.Current?.TraceIdand then tocontext.TraceIdentifier(the same precedence the service middleware uses, so the correlation id and the distributed trace line up). The comment (:57-61) says why the rule is mirrored: the response echo runs fromOnStartingafter the forwarder copied the service's headers, so the edge must forward and echo exactly what the service keeps and stores. - Write-back is conditional on a change. When the computed id differs from the inbound header (
:66), it is written back ontocontext.Request.Headers(:68), which covers a minted id, a truncated one and a replaced one. That single assignment is what makes the forwarded request carry the id downstream. Sanitize(string)(:87, private static, doc comment:81-86) cuts the value toMaxLengthcharacters (:89) and keeps it only when every character is printable ASCII,>= ' 'and<= '~'(:90); otherwise it returns null so a generated id replaces it.- The response echo is registered through
context.Response.OnStarting(:72-76) rather than set inline, because a proxied response has its headers written by the forwarder; a callback fired as the response starts survives that. Finally the pipeline continues by returningnext(context)directly (:78):InvokeAsyncis a plainTask-returning method, notasync(:51), so there is no state machine and noawaiton the hop, which is safe because nothing runs after the downstream call completes.
- Why it's built this way:
sealed, conventional (constructor plusInvokeAsync) middleware, and context-free by constraint, not by accident. Its only constructor dependency is theRequestDelegate(:29). The service-tier version writes the id onto a scopedICorrelationContextthat the CQRS logging decorators read, and this Aspire package cannot reference the Application layer that declares that abstraction. The doc comment states the constraint directly (:10-17): a reverse-proxy gateway forwards bytes, it has no application container and no correlation context to populate, which is what makes this middleware safe to drop into a bare YARP host with no DI graph beyond the proxy. - Where it's used: Both gateway pipelines, deliberately first among each gateway's own concerns so the id is stamped before anything (a 429 from the edge limiter included) can short-circuit:
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:188andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:155. Covered by GatewayCorrelationMiddlewareTests, and end to end by GatewayHardeningTests in both apps. - Caveats / not-in-source: A caller-supplied id is bounded and shaped (at most 64 printable-ASCII characters) but is otherwise client-controlled, so a client still chooses the value that appears in gateway and service logs. The
64and the ASCII rule are mirrored by hand fromCorrelationIdMiddlewareinMMCA.Common.API; nothing in this file ties the two copies together.
GatewayCorrelationExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayCorrelationMiddleware.cs:100· Level 10 · class (static)
- What it is: The one-line pipeline registration for GatewayCorrelationMiddleware:
app.UseGatewayCorrelation(). - Depends on: GatewayCorrelationMiddleware and
IApplicationBuilder(ASP.NET Core). - Concept reinforced: the
Use*pipeline-extension idiom.[Rubric §13, Observability & Operability],[Rubric §9, API & Contract Design]: the value this adds over callingUseMiddleware<T>()directly is the documented ordering rule, which is the part a host gets wrong. - Walkthrough: One
extension(IApplicationBuilder app)block (:75) containingUseGatewayCorrelation()(:82), which null-guards the receiver (:84) and returnsapp.UseMiddleware<GatewayCorrelationMiddleware>()(:85). The doc comment carries the contract (:77-79): call it first, before the proxy or forwarder is mapped, so the id is on the request the gateway forwards. The class carries the same scopedCA1708suppression as its siblings (:69-72) for theextension(T)analyzer false positive. - Why it's built this way: A static class with an
extension(T)block is the codebase's standard registration idiom (see primer, C#extension(T)types, and ADR-106 for the policy). Keeping the extension in the same file as the middleware means the ordering rule and the behaviour it protects are read together. - Where it's used:
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:188andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:155, in both cases before every other gateway concern, and in particular before GatewayRateLimitingExtensions'UseGatewayRateLimiting()(ADC:144, Store:170), so a throttled request still carries a correlation id.
Extensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:24· Level 4 · class (static)
Disambiguation: this is the framework (Common.Aspire)
Extensions, the canonical service-defaults bootstrap consumed by every running service, including all four ADC services and all three Store services (neither app ships a localServiceDefaultsproject). The other class namedExtensionsin this chapter is the Common.Aspire.HostingExtensions, the AppHost-side broker, JWKS, and data-source wiring.
- What it is: The shared Aspire service-defaults bootstrap:
AddServiceDefaults(),AddWarmupReadiness(),ConfigureOpenTelemetry(),AddDefaultHealthChecks(),AddInfrastructureHealthChecks(),AddWarmupTask<T>(),MapDefaultEndpoints(), andMapCachedHealthChecks(). It configures OpenTelemetry (logs, metrics, tracing), Kestrel with noServerresponse header, cached health-check endpoints (/health,/alive,/health/ready), service discovery, the warm-up readiness pipeline, a startup tripwire for vendor integrations configured but never registered, and a Polly resilience pipeline plus a FinOps-tunedSocketsHttpHandlerfor every outboundHttpClient. - Depends on: IWarmupTask, OpenIdConnectMetadataWarmupTask, WarmupHostedService, WarmupReadinessGate, WarmupReadinessHealthCheck, HealthCheckTags, HealthEndpointPaths, RedisPingHealthCheck, CachedHealthReportProvider, HealthReportCacheOptions, OutboxPollFilterProcessor, ProbeTelemetryFilter, ProbeTelemetryFilterProcessor, HttpResilienceDefaults, HostIntegrationTripwire, HostIntegrationTripwireOptions, RetryAfterHeader, and CommitOutcomeUnknown; plus Azure Monitor, OpenTelemetry, Polly /
Microsoft.Extensions.Http.Resilience, the AspNetCore health-check packages, and the RabbitMQ client (NuGet). - Concept introduced, Aspire service defaults as a shared cross-cutting bootstrap.
[Rubric §13, Observability & Operability](centralised OpenTelemetry plus health endpoints; it subscribes ten MMCA meters (Extensions.Telemetry.cs:61-74), Polly's own resilience meter, and theMMCA.Common.Outbox/MMCA.Common.Messaging/MMCA.Common.InternalCommandstrace sources (FrameworkActivitySourceNames,Extensions.Telemetry.cs:87-92) by literal name, plus the optional AI package's meter and trace source under the single literalAiTelemetryName = "MMCA.Common.AI"(Extensions.Telemetry.cs:43), inert until a host adoptsMMCA.Common.AIand setsAi:Enabled, and installs OutboxPollFilterProcessor to drop noisy idle-poll spans before export, plus, by default, the two probe-telemetry filters).[Rubric §29, Resilience & Business Continuity](Polly on every outbound client, ADR-009, and the Polly meter now exported so a retry storm or an open circuit shows up as a signal rather than plain latency).[Rubric §31, Cost / FinOps](six trace/metric-side cost knobs:Telemetry:FilterProbeTelemetryon by default,Telemetry:EnablePollyDurationMetricsoff by default, plusTelemetry:TracesSampleRatioand the three ASP.NET Core/HttpClient/runtime metric-family switches opt-in (Extensions.Telemetry.cs:392,:282,:310); and theSocketsHttpHandlertuning atExtensions.cs:114-122, whose rationale comment at:101-113is the codebase's clearest FinOps decision:PooledConnectionLifetimepicks up ACA replica DNS rollover,PooledConnectionIdleTimeoutavoids repeated TLS handshakes, and HTTP/2 keep-alive PING frames go out every 60 seconds only while a request is in flight (KeepAlivePingPolicy.WithActiveRequests), so a peer that dies mid-call or mid-stream is detected within the ping timeout, while an idle connection sends nothing at all, which is what keeps an idle replica on idle-vCPU billing, roughly 8x cheaper than active (:106-111)).[Rubric §27, Security/AppSec](the health-report cache: SEC-Common-71/SEC-ADC-17 bound an anonymous-flood amplification on/healthand/health/ready, see theMapCachedHealthChecksbullet below).[Rubric §13, Observability & Operability](one call, one baseline, every host). The telemetry half of this is ADR-041; the warm-up half is ADR-025. - Walkthrough:
AddServiceDefaults<TBuilder>()(Extensions.cs:36, in a genericextension<TBuilder>(TBuilder builder) where TBuilder : IHostApplicationBuilderblock at:26-27, so it works for a web host or a worker): callsConfigureOpenTelemetry,AddDefaultHealthChecks,AddWarmupReadiness, thenAddServiceDiscovery(:38-41). It then turns off Kestrel'sServerresponse header withConfigure<KestrelServerOptions>(kestrel => kestrel.AddServerHeader = false)(:45); the comment (:43-44) gives the reason, the header names the server family to a scanner and carries nothing a client needs. It then registers the startup tripwire (:51-53):AddOptions<HostIntegrationTripwireOptions>().ValidateOnStart()plus aTryAddEnumerableof HostIntegrationTripwire as theIValidateOptions<HostIntegrationTripwireOptions>. The comment above it (:47-50) names what it catches, a vendor integration the configuration asks for but no adapter call registered (an Application Insights connection string with no exporter, a vault URI with no configuration source, a key-ring blob with no DataProtection sink), and when: with the otherValidateOnStartvalidators, before any hosted service starts. Next comesConfigureHttpClientDefaults(:58), which affects everyHttpClientregistered downstream through the client factory (typed clients, named clients, and the gateway's own downstream probe clients, which opt out of the resilience handler again, see GatewayHealthCheckExtensions). The YARP forwarder is not one of them: it builds its clients through its own forwarder client factory (comment:55-57). Inside it,AddStandardResilienceHandler(:69) pulls all four values from HttpResilienceDefaults (:71-74): a 30-second per-attempt timeout, a 60-second circuit-breaker sampling window, a 90-second total request timeout, andMaxRetryAttempts = 1. It then callsoptions.Retry.DisableFor(HttpMethod.Post, HttpMethod.Patch)(:83), so a POST or PATCH is never replayed: the comment at:76-82explains that an attempt which timed out may still be running server-side and most hops carry no idempotency key (a server-to-server call never does; the UI'sAPIClientstamps one only onEntityServiceBasecreates and updates, whose replay the UI service base classes own), while GET, PUT, DELETE and the other idempotent verbs keep their one retry, which is why it names the two verbs instead of usingDisableForUnsafeHttpMethods(that helper would also switch the retry off for PUT and DELETE). It then wraps the retry'sShouldHandle(:92-97): when RetryAfterHeader.ExceedsRetryBudget(args.Outcome.Result, TimeProvider.System)is true, or the response is one CommitOutcomeUnknown.Is(response)recognizes, the outcome is not retried; otherwise the original predicate decides. The comment at:85-91gives the reasons. First,ShouldRetryAfterHeader(on by default) makes the retry wait out a 429'sRetry-After, which a rate limiter sets to the rest of its window, up to a minute holding the request; a 429 asking for more thanHttpResilienceDefaults.MaxRetryAfterWait(8 seconds,MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:40) is therefore not retried here, matching the UI service base classes, so a refused action is one request. Second, a 500 marked as a commit with an unknown outcome (the response carriesX-Commit-Outcome: unknown,MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:34-37, read byIs(HttpResponseMessage)at:59) is never retried either, because a PUT or DELETE would otherwise run again against a write that may already be durable.http.AddServiceDiscovery()(:99) lets clients resolve logical service names, andConfigurePrimaryHttpMessageHandlerinstalls the tunedSocketsHttpHandler(:114-122) includingKeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests(:120, pings only while a request is in flight, so an idle pooled connection stays silent andPooledConnectionIdleTimeoutalone decides how long it stays pooled, comment:106-111) andEnableMultipleHttp2Connections = true(:121, so one multiplexed HTTP/2 connection cannot become a bottleneck). The comment at:60-68is worth reading for the retry-budget reasoning: exactly one retry per hop, because the UI service base classes own user-facing retries, and full budgets at both layers would multiply a backend brownout into up to sixteen gateway hits per user action. The same comment notes that the gRPC typed clients inMMCA.Common.Grpcshare only the retry budget and the breaker window from HttpResilienceDefaults, not the timeouts.AddWarmupReadiness()(Extensions.cs:137): registers the singleton WarmupReadinessGate (:139), the WarmupHostedService runner (:140), the built-in OpenIdConnectMetadataWarmupTask as anIWarmupTask(:142), which pre-fetches the OIDC discovery document for the configuredAuthentication:JwtBearer:Authority(doc comment:128-135), and the WarmupReadinessHealthCheck as the"warmup"check taggedHealthCheckTags.Ready(:144-145).AddWarmupTask<TTask>()(:160, in anextension(IServiceCollection services)block at:151) lets a consumer add service-specific warm-ups by registeringAddSingleton<IWarmupTask, TTask>()(:163).ConfigureOpenTelemetry()(Extensions.Telemetry.cs:120): logging withIncludeFormattedMessageandIncludeScopes(:105-106); the metrics half is a dedicated privateConfigureMetrics(metrics, configuration)method (called at:129, defined at:293, "a method rather than an inline lambda so each knob stays readable",:267). Tracing adds the application's own source plus every name inFrameworkActivitySourceNameswith one.AddSource([.. FrameworkActivitySourceNames])call (Extensions.Telemetry.cs:132-133); that public list (:87-92) holdsMMCA.Common.Outbox,MMCA.Common.Messaging,MMCA.Common.InternalCommands, andAiTelemetryName, the optional AI package's combined trace/metric name: inert until a host both referencesMMCA.Common.AIand enables it, because subscribing a source nothing publishes to is a no-op. Then branches on the probe-telemetry cost knob,IsProbeTelemetryFilterEnabled(:131, defined at:261). When filtering is on (the default), ASP.NET Core andHttpClientinstrumentation are added with filters,options.Filter = Telemetry.ProbeTelemetryFilter.ShouldCollectRequestandoptions.FilterHttpRequestMessage = Telemetry.ProbeTelemetryFilter.ShouldCollectOutgoing(:137-140); when it is off they are added plain (:144-145). The comment above the branch (:119-130) carries the measurement behind it: Container Apps liveness and readiness probes, the gateway's downstream aggregate probes, YARP active health checks and the availability web test made up 100% of theAppRequestsrows in both production workspaces, and their children (the health check'sSELECT 1, the Redis PING, the gateway's calls to each backend's/alive) most of theAppDependenciesrows; sampling cannot help there, because probe spans are exactly what the sampler keeps proportionally. It also records what is deliberately left alone: metrics, so probe traffic still shows on dashboards. Because both filters configure the default-named instrumentation options, they also apply to the instrumentation the Azure Monitor distro adds, which is why this knob needs no View, unlike the metrics knobs inConfigureMetrics(comment:134-136)..AddProcessor(new Telemetry.OutboxPollFilterProcessor())(:155) always registers, and aProbeTelemetryFilterProcessoronly under the same knob (:157-163), both before the exporters so theirOnEndclears theRecordedflag first. WhenTryGetTraceSampleRatiosucceeds it installsnew ParentBasedSampler(new TraceIdRatioBasedSampler(ratio))(:171-172), parent-based so a sampled-in request keeps its whole trace intact across service boundaries. It then calls the privateAddOpenTelemetryExporters(:175, defined at:195, OTLP only whenOTEL_EXPORTER_OTLP_ENDPOINTis set), and finally registers aHostIntegrationMarkerforHostIntegrationNames.ServiceDefaultsTelemetry(:179): the receipt a vendor exporter checks for, which is whyAddAzureMonitorExporter()refuses to run ahead of this call (comment:177-178).ConfigureMetrics(metrics, configuration)(Extensions.Telemetry.cs:293, private static): first calls the privateConfigureAspNetCoreMetrics(:273, defined at:368), which adds ASP.NET Core instrumentation (:382) unlessTelemetry:DisableAspNetCoreMetricsis set, in which case it installs ametrics.AddView(...)that drops every meter under theMicrosoft.AspNetCore.prefix (:370-378); its doc comment (:359-365) records that this family was 73% of both production workspaces' ingestion over 2026-09-22..28 and that no alert reads it. Then come the two other metric-family disable knobs,Telemetry:DisableHttpClientMetrics(:282) andTelemetry:DisableRuntimeMetrics(:310), each a two-part switch where the disabled branch does not merely skip the instrumentation call: it installs ametrics.AddView(...)that returnsMetricStreamConfiguration.Dropfor theSystem.Net.Http/System.Net.NameResolutionmeters (:295-299) or theSystem.Runtimemeter (:315-318); the enabled runtime branch subscribes theSystem.Runtimemeter the runtime publishes itself (:324). The comment inside the HttpClient branch (:284-294) records why the View is needed: a deployed host may also callUseAzureMonitor(), and the Azure Monitor distro adds those meters itself, so the toggle is authoritative only because a View applies to the wholeMeterProviderregardless of which component added the meter. It then subscribes every MMCA.Common meter with one call,metrics.AddMeter([.. FrameworkMeterNames])(:331).FrameworkMeterNames(:61-74, public) holds eleven literal names:MMCA.Common.Outbox,.Cqrs,.Idempotency,.Scheduler,.Broker,.OutputCache,.BestEffort,.InternalCommands,.Persistence,.Auth, andAiTelemetryName("MMCA.Common.AI",:43) for the optional AI package's token spend and call duration, inert until a host adds that package and enablesAi:Enabled. Its doc comment (:45-60) names what each meter carries and notes that a fitness test holds the list equal to the meters the Common packages actually create, so a new meter cannot ship unexported; the comment at the call (:327-330) names which are inert until a host opts in. It then adds Polly's own meter,PollyMeterName = "Polly"(:30,:338), the meterPolly.Extensions' telemetry listener emits through, named as a literal because Aspire holds no reference to Polly's own assemblies (:27-28); the comment at:333-337explains why this matters: the standard resilience handler is on everyHttpClientand every gRPC typed client, so it decides whether an inter-service call is retried, timed out, or refused by an open circuit, and without this meter none of that leaves the process and a brownout looks, from the outside, exactly like latency. The always-exported counter isresilience.polly.strategy.events(PollyStrategyEventsInstrument,:82), tagged withpipeline.name,strategy.name,event.name(OnRetry/OnCircuitOpened/OnCircuitClosed/OnTimeout/...),event.severityandexception.type(:77-80). Polly's two duration histograms,resilience.polly.strategy.attempt.durationandresilience.polly.pipeline.duration(PollyAttemptDurationInstrument/PollyPipelineDurationInstrument,:85,88), are an opt-in cost knob: dropped by ametrics.AddView(:350-355) unless a host setsTelemetry:EnablePollyDurationMetrics=true(EnablePollyDurationMetricsConfigKey,:24), because they re-measure whathttp.client.request.durationand the dependency traces already report and run on a pipeline invoked on every outbound call (:340-347).TryGetTraceSampleRatio(configuration, out ratio)(Extensions.Telemetry.cs:235,internal static): reads the optionalTelemetry:TracesSampleRatioknob and returnstrueonly for a value that parses invariantly and falls in the open interval (0,1); absent, unparseable, or out-of-range input returnsfalseand leavesratioat1.0. Sampling therefore fails toward keeping everything, so a typo can never silently drop all telemetry.IsInstrumentationDisabled(configuration, configKey)(Extensions.Telemetry.cs:258,internal static): the fail-safe shape for the two metric-family disable knobs,bool.TryParse(configuration[configKey], out var disabled) && disabled. It returnstrue(drop that family) only when the value parses as booleantrue; absent, blank, or unparseable keeps the instrumentation.IsInstrumentationEnabled(configuration, configKey)(Extensions.Telemetry.cs:271,internal static) is the new mirror image for the Polly duration histograms, an opt-in knob:bool.TryParse(configuration[configKey], out var enabled) && enabled. Absent, blank, or unparseable all mean "stay off", so a typo can never silently add a high-volume stream to a host's bill; this is the opposite bias fromIsInstrumentationDisabled, where absent/unparseable keeps the (already-on) instrumentation.IsProbeTelemetryFilterEnabled(configuration)(Extensions.Telemetry.cs:283,internal static) reads the key held asFilterProbeTelemetryConfigKey = "Telemetry:FilterProbeTelemetry"(:35) and inverts the default:!bool.TryParse(...) || enabled, so absent, blank, or unparseable all mean "filter" and only an explicitfalseturns filtering off. That is the opposite bias from the metrics disable knobs, and the doc comment says why: probe chatter is ingestion no host wants billed, while a metrics family dropped by accident is a blind spot.AddDefaultHealthChecks()(Extensions.Health.cs:25) registers a"self"check taggedHealthCheckTags.Live(:239-240). New (SEC-Common-71, SEC-ADC-17,:242-244): it also binds and validates HealthReportCacheOptions (:245-248), and registersTimeProvider.System(:249) plus a singleton CachedHealthReportProvider (:250), the short-TTL single-flight report cache thatMapCachedHealthChecksserves/healthand/health/readyfrom.AddInfrastructureHealthChecks(bool requireDatabase = false)(Extensions.Health.cs:76) is the conditional part. It resolves the health-checks builder (:283), delegates the relational engines to the privateAddDatabaseHealthChecks(:285), then adds Redis and RabbitMQ only when their connection strings are present. The Redis branch (:287-304) is the incident-hardened one: itTryAddSingletons a RedisPingHealthCheck built from the connection string (:296-297) and registers it as aHealthCheckRegistrationnamed"redis"tagged[HealthCheckTags.Optional](:299-303). The comment above it (:290-295) explains both halves: PING only, never an administrative command, because theAspNetCore.HealthChecks.Redischeck this replaced issuedCLUSTER INFOagainst any server StackExchange.Redis 3.x detects as clustered (which is how it sees Azure Managed Redis Enterprise tier) and the server refuses that command outside admin mode, so every probe threw against a healthy cache; and singleton registration so the fallback multiplexer is built once, not per probe, and disposed with the container. The RabbitMQ branch (:306-316) reads therabbitmqconnection string falling back tomessaging(:306-307), requires it to parse as an absolute URI (:308-309), and registers anAddRabbitMQcheck named"rabbitmq"tagged[HealthCheckTags.Optional](:311-315) whose factory builds a connection per probe. The parameter doc (:262-266) now names a third accepted shape:SQLServerConnectionString,PostgreSQLConnectionString, orSqliteConnectionString.AddDatabaseHealthChecks(healthChecks, configuration, requireDatabase)(Extensions.Health.cs:237, private static) holds the asymmetry that matters. It now collects SQL Server, PostgreSQL, and SQLite sources (:635-637), and whenrequireDatabaseis true and all three are empty it throwsInvalidOperationExceptionnaming all three accepted shapes (:639-645). Otherwise it adds oneAddSqlServercheck per SQL source (:647-650), oneAddNpgSqlcheck per PostgreSQL source (:652-655, new), and oneAddSqlitecheck per SQLite source (:657-660), all untagged, so every one of them gates readiness. The reasoning is unchanged: Redis and RabbitMQ are optional per host, but a host that cannot resolve its own database connection string is misconfigured, and silently registering no check would let it report healthy and take traffic it cannot serve.RelationalSources(configuration, key)(Extensions.Health.cs:326, private static) is the small piece of logic behind "one check per database", now driving three engines instead of two: it mapskeytosqlserver/postgresql/sqlite(:682-687), reads the top-levelConnectionStringsentry (:691-695) and then every namedDataSourceschild carrying the same key (:697-704), and finally deduplicates by connection string with an ordinalHashSet(:706-714). Two details are deliberate: the first surviving database keeps the historical check name for its engine and only a genuinely second, different database gets the{engine}:{source}form; and because deduplication is by connection string, logical names that collapse onto one physical database contribute one check rather than one per logical name.MapDefaultEndpoints()(Extensions.Health.cs:143, in anextension(WebApplication app)block at:110):/healthnow maps throughMapCachedHealthChecks(HealthEndpointPaths.Health, predicate: null)(:395) instead ofMapHealthChecksdirectly;/alivestill filters toHealthCheckTags.Livevia plainMapHealthChecks, but now with an explicit.AllowAnonymous()(:399-402, new SECURITY comment at:386-388: a host that adopts the framework's fallback authorization policy would otherwise 401 its own liveness/readiness probes, and a probe that cannot answer takes the replica out of rotation);/health/readyalso now goes throughMapCachedHealthChecks, with astaticpredicate excludingLiveandOptionaltags (:415-417). All three routes still come from the HealthEndpointPaths constants.MapCachedHealthChecks(path, predicate)(Extensions.Health.cs:192, new public method) is the security fix behind the/healthand/health/readyrewrite (SEC-Common-71, SEC-ADC-17, comment at:390-393): it maps GET/HEAD to a handler that callsCachedHealthReportProvider.GetReportAsync(path, predicate, cancellationToken)(:437-441) instead of running the underlying checks per request, then answers exactly asMapHealthCheckswould,text/plainwith the status name,503only when unhealthy (:443-450). The endpoint is.AllowAnonymous().ExcludeFromDescription()(:452-453). Because the cache is keyed bypath, an anonymous flood on either cached endpoint costs at most one probe round per cache window rather than one per request;/aliveis deliberately left uncached (mapped with plainMapHealthChecks) since it is a single in-memory check with no downstream dependency to protect.AddOpenTelemetryExporters()(Extensions.Telemetry.cs:217, private): enables OTLP whenOTEL_EXPORTER_OTLP_ENDPOINTis set (:336-342, the local Aspire dashboard sets it) and Azure Monitor whenAPPLICATIONINSIGHTS_CONNECTION_STRINGis set (:344-350, set by the Container Apps Bicep). Both can be active simultaneously, and each exporter ships only its own copy.
- Why it's built this way: One bootstrap means a baseline change (a new meter, a tighter timeout, the poll filter, the Redis check swap, the health-report cache) propagates to every consumer in lockstep. There is a single framework copy and no per-app variants: neither ADC nor Store ships an app-local
ServiceDefaultsproject, so the warm-up gate, the MMCA meters, the poll filter, and the Azure Monitor exporter branch are uniform across every service. Every knob that could hide end-user signal defaults to the expensive-but-safe setting, which is the deliberate bias recorded in ADR-041: a cost surprise is recoverable, a silent telemetry blackout during an incident is not. The two knobs that default the other way,Telemetry:FilterProbeTelemetryandTelemetry:EnablePollyDurationMetrics, are the exceptions that prove the rule: what the first drops is the platform probing itself, and what the second withholds is a histogram that duplicates signal already captured elsewhere; neither one hides an incident. The health-report cache added underAddDefaultHealthChecks/MapCachedHealthChecksextends the same bias to a different axis, DoS resistance: an anonymous flood on/healthor/health/readycan no longer force one dependency probe round per request. The class also carries a scopedCA1708suppression documenting a known analyzer false positive: with two or moreextension(T)blocks in one static class, the compiler-generated grouping members trip the "identifiers should differ by more than case" rule. - Where it's used:
builder.AddServiceDefaults()early in each framework-consuming host'sProgram.cs: ADC Gateway (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:66), ADC UI (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:55), the four ADC services (Identity:97, Conference:100, Engagement:83, Notification:86), the Store gateway, UI and three services (MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:65,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:76,MMCA.Store/Source/Services/MMCA.Store.Identity.Service/Program.cs:74,MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:68,MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:85), and the Helpdesk seed (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:14).app.MapDefaultEndpoints()followsBuild()in each (ADC Gateway:136, ADC UI:119, ADC Conference:375, Helpdesk:129).AddInfrastructureHealthChecks(requireDatabase: true)is the standard service-host call: ADC Identity:146, Conference:163, Engagement:143, Notification:128, Store Identity:129, Catalog:133, Sales:142, and Helpdesk:31. The internal cost-knob helpers are covered by TracesSampleRatioTests and MetricsInstrumentationToggleTests; the Polly meter by PollyResilienceMetricsTests (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Telemetry/PollyResilienceMetricsTests.cs); the conditional infrastructure checks by InfrastructureHealthChecksTests and RedisReadinessSafetyTests. - Caveats / not-in-source: Because the POST/PATCH retry exclusion lives in
ConfigureHttpClientDefaults, it applies to everyHttpClientin the host; a transient failure on a non-idempotent call surfaces after one attempt, and any replay for those verbs is the caller's decision. The same host-wide scope applies to the 429 rule: a 429 whoseRetry-AfterexceedsMaxRetryAfterWaitreaches the caller at once on every verb, and a 429 without the header follows the normal one-retry, no-POST/PATCH rule. Likewise a 500 carryingX-Commit-Outcome: unknownis never retried on any verb, so the caller (or the user) decides whether to read the resource back before trying again.requireDatabasedefaults tofalse, so a service host that forgets to passtrueregisters no database check and can report ready without one; every current service host passes it. The RabbitMQ branch silently registers nothing when the connection string is present but not a valid absolute URI, so a malformed broker URI produces no check and no error at startup. Probe-trace filtering is on by default, so a host debugging its own probes sees no request traces for them until it setsTelemetry:FilterProbeTelemetry=false; nothing logs that the filter is active.Telemetry:EnablePollyDurationMetricsdefaults to off, so the per-attempt and per-pipeline duration histograms are silent unless a host explicitly opts in. TheAiTelemetryNamesource and meter are always subscribed regardless of whether a host referencesMMCA.Common.AI; nothing logs that they are inert, andAiDependencyIsolationTestsBaseis what keeps the reference itself out of hosts that never adopt the package./healthand/health/readynow serve a cached report rather than always running the underlying checks live; the cache window/behavior is governed by HealthReportCacheOptions and CachedHealthReportProvider, not by this class.
Entry
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/CachedHealthReportProvider.cs:42· Level 0 · class (private, sealed, nested)
- What it is: The per-endpoint-key cache slot nested inside CachedHealthReportProvider: the last computed
HealthReport, when it expires, and the probe round currently running for that key, which is what lets concurrent callers share one round instead of each starting their own. - Depends on:
HealthReport(ASP.NET Core diagnostics),Task<HealthReport>,DateTimeOffset(BCL). Owned exclusively by CachedHealthReportProvider, which keys one instance perendpointKeyin its_entriesdictionary (CachedHealthReportProvider.cs:37). - Walkthrough: Three mutable properties and no behaviour.
Report(:44) is nullable, holding the last computed report ornullbefore the first round completes.ExpiresAt(:46) is theDateTimeOffsetthe owner'sRunRoundAsyncadvances when it publishes a report (:123-127).Round(:48) is the nullableTask<HealthReport>of the most recent round, set byStartRound(:111); while it is not completed, the owner'sGetReportAsynctreats the key as "a round is in flight" (:84) and either serves the staleReportor awaits that same task. - Why it's built this way:
private sealed, an implementation detail of one class with no meaning outside it. Holding the in-flightTaskrather than a lock object makes the single flight a shared awaitable: a caller that must wait awaits the round itself (with its own token), and nothing needs releasing afterwards, so the type is a plain data holder and notIDisposable. Every read and write of its properties happens under the owner's_gatelock (:76-100,:123-127). - Where it's used: Created and looked up by
CachedHealthReportProvider.GetEntry(CachedHealthReportProvider.cs:132-141), which the owner calls only while holding_gate(:78); itsRoundis assigned inStartRound(:107-113) and itsReport/ExpiresAtpair inRunRoundAsync(:115-130).CachedHealthReportProvider.Disposeclears the dictionary that holds the entries (:154). - Caveats / not-in-source: Entries are never evicted for endpoint keys that stop being probed, so
_entriesonly grows for the life of the provider; the framework's own callers pass the endpoint path as the key (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:189,:201), which keeps that set small and fixed.
HealthReportCacheOptions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/HealthReportCacheOptions.cs:29· Level 0 · class (sealed)
- What it is: The bound
"HealthChecks"configuration for the health endpoints, with two settings: how many seconds CachedHealthReportProvider reuses a computed health report, and how many seconds each infrastructure dependency check may run before it is cancelled. - Depends on:
System.ComponentModel.DataAnnotations([Range]) only. Consumed by CachedHealthReportProvider viaIOptions<HealthReportCacheOptions>, and read directly from configuration byAddInfrastructureHealthChecksin the Common.Aspire Extensions for the per-check timeout. - Walkthrough:
- Two
internal constbounds,MinimumCheckTimeoutSeconds = 1(:32) andMaximumCheckTimeoutSeconds = 60(:35), shared by the[Range]attribute and the registration-time check so the two cannot disagree. SectionName = "HealthChecks"(:38), astatic readonly stringused for options binding.CacheSeconds(:45,[Range(0, 300)]at:44) defaults to 5. The doc comment (:40-43) states the escape hatch:0disables caching and restores the probe-per-request behaviour.CheckTimeoutSeconds(:55,[Range(MinimumCheckTimeoutSeconds, MaximumCheckTimeoutSeconds)]at:54) defaults to 5. Its doc comment (:47-53) states the effect: a dependency that holds a connection without answering turns/healthunhealthy withinCacheSecondsplus this value instead of leaving the last report in place, and a host whose dependency legitimately answers slower raises it.
- Two
- Why it's built this way: Two
intsettings rather than a richer policy, because the only knobs a cached health report needs are how stale a stand-in answer may be and how long one probe may hang; single-flight recomputation and per-key isolation are CachedHealthReportProvider's fixed behaviour, not configuration. The timeout is validated twice on purpose:AddDefaultHealthChecksbinds the section withValidateDataAnnotations().ValidateOnStart()(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:33-36), butAddInfrastructureHealthChecksneeds the value while it registers checks, before any options validation runs, so itsCheckTimeouthelper re-reads the section and throwsInvalidOperationExceptionoutside 1 to 60 (Extensions.Health.cs:294-304). Part of the same edge caching work ADR-088 records for the gateway. - Where it's used: Bound in
AddDefaultHealthChecks(Extensions.Health.cs:33-36, beside theTryAddSingleton<CachedHealthReportProvider>()at:38), read byCachedHealthReportProvider.GetReportAsyncon every call (CachedHealthReportProvider.cs:69), and read once at registration byCheckTimeout(Extensions.Health.cs:296-298), whose result becomes thetimeout:of every database, Redis and RabbitMQ registration (:100,:123,:260,:277,:283). Covered byCachedHealthReportProviderTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/CachedHealthReportProviderTests.cs, 6 references). - Caveats / not-in-source:
CheckTimeoutSecondsbounds only the checksAddInfrastructureHealthChecksregisters; the"self"liveness check and any check a host adds itself carry no timeout from this type. Not determinable from source: whether/healthand/health/readyshare one cache window or are keyed independently is decided by theendpointKeyvalue each caller passes toGetReportAsync, not by this type.
PostgreSqlHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/PostgreSqlHealthCheck.cs:26· Level 0 · class (internal, sealed)
- What it is: The framework's readiness check for one PostgreSQL database. It opens a connection and runs
SELECT 1under the probe's cancellation token, on the sameNpgsqlDataSourcethe PostgreSQL contexts use whenever the host registered one (class docPostgreSqlHealthCheck.cs:7-10). - Depends on:
NpgsqlDataSource(Npgsql),IHealthCheck/HealthCheckResult(ASP.NET Core diagnostics),IKeyedServiceProvider, and theLocktype. The keyed data source it looks for is registered byMMCA.Common.Infrastructure; the engine itself is covered at ADR-113. Registered by the Common.Aspire Extensions. - Concept introduced, a probe must authenticate the way the workload does.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity],[Rubric §8, Data Architecture]. Infrastructure registers the data source as a keyed singleton, keyed by the connection string, once a data-source configurator is added (RDS IAM tokens throughAddAwsRdsIamAuthentication, for one). A check built from the bare connection string would then connect without the password provider and report a healthy database as down (:12-15). This package cannot reference Infrastructure, so the contract is an Npgsql type plus a string, decided per probe because the two registrations can arrive in either order (:16-17). - Walkthrough:
- Five fields (
:28-32): the connection string, the provider, aLock, the nullable_ownedDataSource, and a_disposedflag. The constructor (:37-44) guards both arguments and does no I/O. CheckHealthAsync(:47) opens a connection fromDataSourceForProbe()(:55), runsSELECT 1;(:61-62), and returnsHealthy(:66).OperationCanceledExceptionwhen the probe token was cancelled is rethrown (:68-71); every other exception becomes a result with the registration'sFailureStatusand the description"PostgreSQL did not answer SELECT 1."(:73-80).DataSourceForProbe()(:102-103,internalso the tests can see the choice) returnsSharedDataSource() ?? OwnedDataSource().SharedDataSource(:105-108) asks anIKeyedServiceProviderfor theNpgsqlDataSourcekeyed by the connection string.OwnedDataSource(:110-117) builds one withNpgsqlDataSource.Createon first use under the lock and throwsObjectDisposedExceptiononce the check is disposed (:114).Dispose(:84) andDisposeAsync(:87-94) both go throughTakeOwnedDataSourceForDisposal(:119-128), which sets the flag and hands out the owned data source exactly once; the shared one is never disposed here, since the container that registered it owns it (:22-23).
- Five fields (
- Why it's built this way: Decided on every call rather than at construction, because the keyed data source can be registered after this check. The owned fallback is kept for every later probe so its pool carries the reuse (
:20-22) instead of a new data source per probe.IDisposableplusIAsyncDisposable, because the check is a container singleton and the owned data source must be released with it. - Where it's used: Registered once per PostgreSQL source in the database loop of
AddInfrastructureHealthChecks(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:263-278): a keyed singleton keyed by the check name (:269-271) resolved by theHealthCheckRegistration(:272-277) with no tags and the default failure status, so it gates readiness (:255-256), and with the per-check timeout from HealthReportCacheOptions. Covered byPostgreSqlHealthCheckDataSourceTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/PostgreSqlHealthCheckDataSourceTests.cs, includingDisposingTheContainer_DisposesTheOwnedDataSource_ButNotTheSharedOneat:62) andDependencyHealthCheckTests.PostgreSql_WhenTheServerIsUnreachable_ReportsTheFailureStatus(DependencyHealthCheckTests.cs:75). - Caveats / not-in-source: A
PostgreSqlHealthCheckresolved through a provider that is not anIKeyedServiceProvideralways uses its owned data source. No consumer AppHost wires a PostgreSQL source today (see Extensions), so this path runs only where a host configures one.
RabbitMqHealthConnection
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RabbitMqHealthConnection.cs:22· Level 0 · class (internal, sealed)
- What it is: The holder of the one AMQP connection the RabbitMqHealthCheck probes through. It hands out the held connection while it is open and replaces it only when it is gone or closed (class doc
RabbitMqHealthConnection.cs:5-20). - Depends on:
RabbitMQ.Client(IConnection,ConnectionFactory),TimeProvider.System, and theLocktype. Used only by RabbitMqHealthCheck; registered as a singleton by the Common.Aspire Extensions. - Concept introduced, a probe must not leak what it opens.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity],[Rubric §12, Performance & Scalability]. The check asks for a connection on every probe round and never disposes it, so opening one per call would leave one AMQP connection on the broker for every successful round (:8-10). The holder keeps at most one for the whole process. The second half of the concept is a bounded handshake: a broker port that accepts TCP and never answers must end the attempt on the holder's own timeout, even when no probe is still waiting (:12-14). ADR-009 is the governing resilience record. - Walkthrough:
- Fields (
:24-34): aFunc<CancellationToken, Task<IConnection>>creation delegate, the timeout, aLock, the held_connection, the in-flight_creatingtask, and a_disposedflag. The public constructor (:39-42) builds the delegate from aConnectionFactory { Uri = uri }; theinternalone (:47-54) takes any delegate, which is what the tests drive, and rejects a non-positive timeout (:50). GetAsync(:64-89), under the lock: throwObjectDisposedExceptiononce disposed (:69), return an open held connection directly (:71-74), otherwise start a single creation if none is in flight (:76-83), taking the stale connection out of the holder first so no later caller can be handed it (:78-81). Every caller then waits on that one task with its own token (:88), so a caller's cancellation stops only that caller.CreateAsync(:194-224) disposes the stale connection best effort, connects, and stores the result only if the holder was not disposed meanwhile (:205-212); otherwise it disposes the new connection and throwsObjectDisposedException(:214-215). Itsfinallyclears_creating(:217-223), so a failed creation is not cached and the next round tries again.ConnectWithinTimeoutAsync(:166-192) gives the attempt aCancellationTokenSourcecancelled at the timeout (:168) and also abandons the wait at the timeout throughWaitAsync(_timeout, TimeProvider.System)(:174), for a client that ignores its token. OnTimeoutExceptionit cancels the token explicitly (:183) and hands the abandoned task toDisposeWhenCreatedAsync(:184,:144-159), which disposes any late connection and only then the token source.DisposeAsync(:92-112) is idempotent, sets the flag, and disposes the held connection best effort; a creation still in flight sees the flag and disposes its own result (:107).
- Fields (
- Why it's built this way: Single flight because ten concurrent probe rounds must not open ten connections. A creation token owned by the holder rather than the probe's token, because the handshake must end even after every waiting probe has given up. The best-effort helpers (
DisposeQuietlyAsync:115-125,CancelQuietlyAsync:128-138) catch everything exceptOutOfMemoryException, because a connection that fails to close is already of no use and a throwing cancel callback must not replace the timeout being reported. - Where it's used: Registered with
TryAddSingleton(_ => new Health.RabbitMqHealthConnection(rabbitUri, checkTimeout))inAddInfrastructureHealthChecks(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:116), with the per-check timeout from HealthReportCacheOptions as its creation budget; the comment above it (:108-115) states the design. Covered byRabbitMqHealthConnectionTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/RabbitMqHealthConnectionTests.cs), whose cases includeTenConcurrentFirstCalls_CreateExactlyOneConnection(:77),ACreationThatNeverCompletes_EndsAtTheTimeout_AndLeavesNothingHeld(:124) andACreationThatFinishesAfterDispose_IsDisposed_AndNotHeld(:109). - Caveats / not-in-source: An attempt abandoned at the timeout keeps running in the background until the client returns;
DisposeWhenCreatedAsyncis fire-and-forget (:184), so nothing awaits that cleanup at host shutdown. Not determinable from source: how long RabbitMQ.Client takes to honour a cancelled handshake token.
SqliteHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/SqliteHealthCheck.cs:15· Level 0 · class (internal, sealed)
- What it is: The framework's readiness check for one SQLite database: open a connection, run
SELECT 1, both under the probe's cancellation token (class docSqliteHealthCheck.cs:6-14). - Depends on:
Microsoft.Data.Sqlite(SqliteConnection) andIHealthCheck/HealthCheckResult(ASP.NET Core diagnostics). Registered by the Common.Aspire Extensions. - Walkthrough: The constructor (
:21-25) guards and stores the connection string and does no I/O.CheckHealthAsync(:28) creates aSqliteConnection(:36), opens it (:39), runsSELECT 1;(:44-45) and returnsHealthy(:49). A cancellation of the probe token is rethrown (:51-54); any other exception becomes a result with the registration'sFailureStatusand the description"SQLite did not answer SELECT 1."(:56-63). - Why it's built this way: Stateless, because the provider's pool, keyed by the connection string, already carries connection reuse (
:10-12), so one instance is safely shared across probes. The rethrow filter is the same one every dependency check in this folder uses: host shutdown is not reported as a database fault. It mirrors SqlServerHealthCheck line for line apart from the driver. - Where it's used: Constructed once per SQLite source in the database loop of
AddInfrastructureHealthChecks(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:280-284) and registered with no tags, so it gates readiness (:255-256), and with the per-check timeout from HealthReportCacheOptions (:283). Covered byDependencyHealthCheckTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/DependencyHealthCheckTests.cs:88,:98). - Caveats / not-in-source: Opening a SQLite connection to a missing file creates it unless the connection string sets a read-only or open-existing mode, so for a default connection string this check proves the file is openable rather than that the schema exists. Not determinable from source: which modes consumer connection strings use.
SqlServerHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/SqlServerHealthCheck.cs:16· Level 0 · class (internal, sealed)
- What it is: The framework's readiness check for one SQL Server database: open a connection, run
SELECT 1, both under the probe's cancellation token (class docSqlServerHealthCheck.cs:6-15). - Depends on:
Microsoft.Data.SqlClient(SqlConnection) andIHealthCheck/HealthCheckResult(ASP.NET Core diagnostics). Registered by the Common.Aspire Extensions. - Walkthrough: The constructor (
:22-26) guards and stores the connection string and does no I/O.CheckHealthAsync(:29) creates aSqlConnection(:37), opens it (:40), runsSELECT 1;(:45-46) and returnsHealthy(:50). A cancellation of the probe token is rethrown (:52-55); any other exception becomes a result with the registration'sFailureStatusand the description"SQL Server did not answer SELECT 1."(:57-64). - Why it's built this way: Stateless, because the driver's pool, keyed by the connection string, carries the reuse. The driver is the same
Microsoft.Data.SqlClientbuildMMCA.Common.Infrastructureconnects with, so a connection string that authenticates for the contexts authenticates here too (:12-13): the same "probe the way the workload connects" rule PostgreSqlHealthCheck implements with a shared data source. - Where it's used: Constructed once per SQL Server source in the database loop of
AddInfrastructureHealthChecks(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:257-261) and registered with no tags, so it gates readiness (:255-256), and with the per-check timeout from HealthReportCacheOptions (:260). Covered byDependencyHealthCheckTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/DependencyHealthCheckTests.cs:50,:62). - Caveats / not-in-source:
SELECT 1proves the login and the database open; it does not prove the schema is migrated or that the login can write.
CachedHealthReportProvider
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/CachedHealthReportProvider.cs:32· Level 1 · class (sealed)
- What it is: A short-lived, per-endpoint-key cache in front of
HealthCheckService.CheckHealthAsync, with single-flight recomputation so a burst of concurrent probes against the same endpoint triggers at most one round of health checks, and that round belongs to the provider rather than to whichever caller started it. - Depends on: Entry (its cache slot), HealthReportCacheOptions (its configuration),
HealthCheckService,HealthReport,HealthCheckRegistration(ASP.NET Core diagnostics),CancellationTokenSourceandTimeProvider(BCL, the clock injected rather than read fromDateTimeOffset.UtcNowso the cache window is testable). - Concept introduced, single-flight caching for a probe endpoint.
[Rubric §12, Performance & Scalability],[Rubric §29, Resilience],[Rubric §13, Observability & Operability]. §12 assesses whether a hot path avoids redundant work under load; a health endpoint polled every few seconds by both Container Apps and a load balancer is exactly that hot path, and without a cache each poll re-runs every registeredIHealthCheck, including whatever they do over the network. The comment onGetReportAsync's in-flight branch (:86-88) states the resilience half directly: while a round is in progress, a caller serves the stale report rather than queuing, so a slow dependency never converts a probe flood into a request backlog. ADR-088 is the governing record. - Walkthrough:
- Four fields (
:37-40):_entries, aDictionary<string, Entry>keyed byendpointKey;_gate, aLockguarding that dictionary and every Entry property;_shutdown, aCancellationTokenSourcewhose token every round runs under; and_disposed, the idempotency flag forDispose(). GetReportAsync(endpointKey, predicate, cancellationToken)(:62) guardsendpointKeyagainst null or whitespace (:67), then readsHealthReportCacheOptions.CacheSecondsinto awindow(:69). Whenwindow <= TimeSpan.Zeroit skips the cache entirely and callsCheckHealthAsyncwith the caller's own token (:70-73), soCacheSeconds = 0restores the probe-per-request behaviour.- Otherwise, inside one
lock (_gate)block (:76-100), it fetches the Entry for the key (:78) and returns the cached report whileGetUtcNow()is beforeExpiresAt(:79-82). - The single-flight branch: when
entry.Roundis not yet completed (:84), a caller with any cached report returns it even though it is stale (:89-92); only when nothing has ever been cached for the key does it take the running round as the one to wait for (:94), because there is no stand-in answer to serve. With no round in flight it starts one throughStartRound(:98). - Outside the lock it awaits the chosen round with
round.WaitAsync(cancellationToken)(:102). The caller's token stops only that caller's wait; the doc comment (:57-60) states that it never cancels a cached round, which other callers share. StartRound(:107-113), called under_gate, captures the_shutdowntoken (:109), runsRunRoundAsyncthroughTask.Run(..., CancellationToken.None)so the checks themselves execute off the lock (:110, comment:105-106), and records the task inentry.Round(:111).RunRoundAsync(:115-130) callsCheckHealthAsyncunder the shutdown token (:121), then retakes_gateto publishReportand the newExpiresAt(:123-127).GetEntry(:132-141) creates the slot on first use and takes no lock itself; its only caller already holds_gate.Dispose()(:144-159) sets_disposedand clears_entriesunder_gate, returning early on a second call (:148-151), then cancels and disposes_shutdown(:157-158), so a round still in progress at host shutdown is cancelled.
- Four fields (
- Why it's built this way: The round is owned by the provider, not by a caller: it runs under the provider's shutdown token instead of the request token that happened to start it, so one probe client disconnecting cannot cancel a round every other waiter shares, and a round every caller has abandoned still completes and fills the cache. Awaiting the shared
Taskreplaces a semaphore, so a waiter needs nothing released afterwards.TimeProviderinjected rather than read from the clock directly, the standard testability boundary for time-based caches in this codebase.Lock(the .NET 9+ type) for_gate, held only for dictionary and property access and never across anawait. - Where it's used: Registered with
TryAddSingleton<CachedHealthReportProvider>()inAddDefaultHealthChecks(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:38) and injected into the endpoint delegate ofMapCachedHealthChecks(Extensions.Health.cs:192-201), which passes the endpoint path asendpointKey(:189,:201);/health/readyis mapped through it at:174-176. ADC's gateway refers to it in a comment on how/healthand/health/readyare served (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:108). Covered byCachedHealthReportProviderTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/CachedHealthReportProviderTests.cs), includingConcurrentColdRequests_ShareOneProbeRound(:144),TheStartingCallerCancelling_DoesNotCancelTheSharedRound(:242),ARoundAbandonedByEveryCaller_StillFillsTheCache(:271),Disposing_CancelsTheRoundInProgress(:299) andWithCachingDisabled_EveryRequestProbes(:325). - Caveats / not-in-source:
_entrieshas no eviction and no cap; it stays bounded only because the framework's callers key it by endpoint path.GetReportAsyncdoes not check_disposed: a call afterDispose()that needs a new round reaches_shutdown.Tokenon a disposed source (:109), which the BCL rejects withObjectDisposedException, so the provider is not meant to be used past host shutdown. Not determinable from source: whether a host maps further cached endpoints beyond the framework's own.
RabbitMqHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RabbitMqHealthCheck.cs:15· Level 1 · class (internal, sealed)
- What it is: The framework's RabbitMQ reachability check. It takes the connection RabbitMqHealthConnection holds and opens, then closes, one channel on it under the probe's cancellation token (class doc
RabbitMqHealthCheck.cs:5-14). - Depends on: RabbitMqHealthConnection (the only connection it ever uses),
RabbitMQ.Client(IConnection.CreateChannelAsync), andIHealthCheck/HealthCheckResult(ASP.NET Core diagnostics). Registered by the Common.Aspire Extensions under the HealthCheckTagsOptionaltag. - Walkthrough: The constructor (
:21-25) guards and stores the holder.CheckHealthAsync(:28) gets the connection with the probe token (:36), opens a channel (:38), disposes it (:39) and returnsHealthy(:41). A cancellation of the probe token is rethrown (:43-46); any other exception, including the holder'sObjectDisposedExceptionafter host shutdown or itsTimeoutException, becomes a result with the registration'sFailureStatusand the description"RabbitMQ did not open a channel."(:48-55). - Why it's built this way: The check never opens or disposes a connection (
:9-12): that is the holder's job, so a probe round leaves nothing behind on the broker. Opening a channel rather than only checkingIsOpenmakes the broker answer a real AMQP request. Tagged optional rather than gating readiness, because the broker is optional per host (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:63-64): an outage degrades/healthand stays off/health/ready(:46-47). ADR-009 is the governing resilience record. - Where it's used: Registered in
AddInfrastructureHealthCheckswhen arabbitmq(or, failing that,messaging) connection string parses as an absolute URI (Extensions.Health.cs:103-106): theHealthCheckRegistrationnamed"rabbitmq"constructs a check over the singleton holder (:118-123), taggedHealthCheckTags.Optionaland given the per-check timeout from HealthReportCacheOptions. Covered byDependencyHealthCheckTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Health/DependencyHealthCheckTests.cs:110,:129). - Caveats / not-in-source: A connection string that is not an absolute URI registers no RabbitMQ check at all, silently (
Extensions.Health.cs:105-106). The channel is disposed only on the success path; ifCreateChannelAsyncthrows there is no channel to dispose.
RedisPingHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Health·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/RedisPingHealthCheck.cs:27· Level 1 · class (internal, sealed)
- What it is: The framework's own Redis reachability check. It issues
PINGand nothing else, and reports the round-trip latency as its healthy description. - Depends on:
StackExchange.Redis(IConnectionMultiplexer,ConnectionMultiplexer,ConfigurationOptions), RedisConfigurationOptionsPipeline (for its owned connection),IHealthCheck/HealthCheckResult(ASP.NET Core diagnostics), andIServiceProvider. It pairs with RedisCachingExtensions'AddRedisCaching()and is registered by the Common.Aspire Extensions under the HealthCheckTagsOptionaltag. - Concept introduced, a health check must not ask a question only an administrator can answer.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity],[Rubric §11, Security]. The class doc (RedisPingHealthCheck.cs:9-26) records a real incident shape. TheAspNetCore.HealthChecks.Redischeck this replaced branches on the detected server type and issuesCLUSTER INFOagainst anything it considers clustered. Azure Managed Redis (Enterprise tier, port 10000) is detected as a cluster by StackExchange.Redis 3.x and refuses administrative commands unless the client opted into admin mode, so that check threwRedisCommandExceptionon every probe against a perfectly healthy cache. The lesson generalises: a command whose success depends on the caller's privileges reports the caller as much as the dependency, and a probe cannot tell those two answers apart.PINGanswers the only question a health check has, "can this process talk to Redis right now", and is never gated on admin mode, on server topology, or on deployment tier. ADR-025 states the rule and names this file as its implementation. - Walkthrough:
- Four fields (
:29-32): the connection string, the provider, aSemaphoreSlim(1, 1)connect gate, and a nullable_ownedMultiplexer. The constructor (:34-38) stores the first two and does no I/O, which is what lets the check be registered without a reachable server. CheckHealthAsync(:40) null-guards the context (:44), then resolves the multiplexer with_services.GetService<IConnectionMultiplexer>() ?? await GetOrCreateOwnedMultiplexerAsync()(:48-49). That single line is the two-mode design in the doc comment (:20-25): a host that wired Redis throughAddRedisCaching()shares the container's multiplexer, and a host that configured a connection string without registering a client gets one this check owns.- It then checks cancellation explicitly (
:51), issuesmultiplexer.GetDatabase().PingAsync()(:53), and returnsHealthywith the latency formatted invariantly (:55-59). - Two catch clauses in a deliberate order.
OperationCanceledExceptionwhen the token was cancelled is rethrown (:61-64), so host shutdown is not reported as a dependency fault. Everything else is reported, never thrown (:66-75, with theCA1031suppression scoped to that one clause at:65and:67), and the comment states the reason (:69-70): this check is tagged optional and must degrade the/healthpayload rather than fault the probe pipeline. DisposeAsync(:78-87) disposes the owned multiplexer if one was created and always disposes the gate.GetOrCreateOwnedMultiplexerAsync(:93-114) connects under the semaphore only while_ownedMultiplexeris null (:98). It first asksRedisConfigurationOptionsPipeline.CreateConfigured(_services, _connectionString)(:102) for the options a registered Redis configurator produces: with none it connects from the connection string alone, otherwise from those configured options (:103-105), so the owned connection is configured the same way the DI client is (:100-101). The comment above the method (:89-92) is worth reading: there is no lock-free fast path on purpose, because probes run on a timer rather than the request path, and a failed connect leaves the field null so the next probe retries instead of latching a faulted result forever.
- Four fields (
- Why it's built this way:
internal sealedframework code rather than a per-host registration, because ADR-025 makes the probe command itself a framework-owned decision: a host that reaches for an Aspire client integration directly puts the package's untagged check back and defeats the rule.IAsyncDisposablerather than a fire-and-forget connection, so the fallback multiplexer is built once and released with the container. The owned path goes through the configurator pipeline for the same reason PostgreSqlHealthCheck probes the shared data source: a probe that connects differently from the workload reports the probe, not the dependency.PINGreturns aTimeSpan, which is why the healthy description can carry latency at no extra cost. - Where it's used: Registered inside
AddInfrastructureHealthChecksonly when aredisconnection string is present (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Health.cs:83-101):TryAddSingletonbuilds it once (:92-93) and theHealthCheckRegistrationnamed"redis"resolves that singleton, tags itHealthCheckTags.Optionaland gives it the per-check timeout from HealthReportCacheOptions (:95-100), so a cache outage degrades/healthwithout ever failing/health/ready. The Aspire client integrations' own checks are switched off at the source in RedisCachingExtensions (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Caching/RedisCachingExtensions.cs:77-78,DisableHealthChecks = trueon both the distributed cache and the client) precisely so this one is the only Redis check in the pipeline. Covered by RedisPingHealthCheckTests, whose cases includeCheckHealthAsync_UsesPingOnly_AndNeverAnAdministrativeCommandandCheckHealthAsync_WhenTheServerRefusesACommand_ReportsUnhealthyWithoutRethrowing, and by RedisReadinessSafetyTests for the tagging. - Caveats / not-in-source:
PINGproves reachability, not capacity: a cache that answers pings while evicting under memory pressure reports healthy.PingAsynctakes no cancellation token, so a slow ping is bounded by the registration timeout and the StackExchange.Redis client timeouts, not by the explicit check at:51. Not determinable from source: which Redis configurators a consumer host registers.
BrokerSelection
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/BrokerSelection.cs:25· Level 0 · class (public static)
- What it is: The framework's AppHost broker selector. It reads one app-named environment variable, provisions the matching broker once (
AddSelectedBroker), and hands back an attach delegate that every service applies withWithSelectedBroker, so each service's wiring chain reads the same single line whichever broker is running. - Depends on:
Aspire.Hosting(IDistributedApplicationBuilder,IResourceBuilder<DotnetProjectResource>,SqlServerServerResource) and the Common AppHost-side Extensions:AddMessageBroker(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:220, RabbitMQ),AddServiceBusEmulatorBroker(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:261, returning a ServiceBusEmulatorResource builder) and the twoWithBrokeroverloads (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:312,:341). The env var those calls ultimately set is read by MessageBusSettings / MessageBusProviders in the consuming service. - Concept introduced, deferring a resource-type choice as a delegate.
[Rubric §33, Developer Experience],[Rubric §7, Microservices Readiness],[Rubric §15, Best Practices & Code Quality]. The twoWithBrokeroverloads take different resource types, so the choice cannot be one variable handed to one call. The class doc comment (BrokerSelection.cs:8-20) states the answer:AddSelectedBrokermakes the choice once and returns it as aFunc<IResourceBuilder<DotnetProjectResource>, IResourceBuilder<DotnetProjectResource>>, andWithSelectedBrokerapplies it, which stops a new service from quietly being wired to the wrong broker. §33 is the environment-parity category, and this type makes parity a one-variable switch instead of a per-service edit. - Walkthrough:
IsServiceBusSelected(environmentVariableName)(:36) rejects a blank name withArgumentException.ThrowIfNullOrWhiteSpace(:38) and returns true only when the variable equalsServiceBusSelection, the constant"servicebus"(:28), compared ordinal and case-insensitive (:40-43); unset or any other value is false.AddSelectedBroker(environmentVariableName, sqlServer)(:58-60, inside theextension(IDistributedApplicationBuilder builder)block at:46) null-guardsbuilderandsqlServer(:62-63), then branches (:65): when selected it callsbuilder.AddServiceBusEmulatorBroker(sqlServer)and returnsservice => service.WithBroker(serviceBus)(:67-68); otherwise it callsbuilder.AddMessageBroker().WithLifetime(ContainerLifetime.Persistent)(a persistent container, so the broker survives an AppHost restart) and returnsservice => service.WithBroker(rabbit)(:71-73).WithSelectedBroker(attach)(:82-83, in theextension(IResourceBuilder<DotnetProjectResource> service)block at:77) null-guards the delegate (:85) and returnsattach(service)(:86). The class carries aCA1708suppression with a justification (:21-24): with severalextension(T)blocks in one static class the analyzer flags compiler-generated grouping members, a false positive. - Why it's built this way: The selector lives in Common and the variable's name stays in the app, so each AppHost passes its own selector (
ADC_BROKER) and keeps everything else about its stack. RabbitMQ is a different broker from the one production runs, so anything that only misbehaves on Azure Service Bus (entity-name limits, topic and subscription provisioning, scheduled redelivery pacing) is invisible in the inner loop. Opting in swaps in the official emulator, which reuses the already-declaredsqlServerresource rather than starting a second engine. Unset stays on RabbitMQ because the emulator costs a second container plus a warm-up, "which is not a price the everyday inner loop should pay" (:11-12). The emulator's quota and TTL handling lives inside MMCA.Common'sAddBrokerMessaging, keyed off theUseDevelopmentEmulator=trueconnection-string marker, so no serviceProgram.cschanges. The transport-selection policy is ADR-066; theextension(T)public surface follows ADR-106. - Where it's used: ADC's AppHost declares
var withBroker = builder.AddSelectedBroker("ADC_BROKER", sqlServer);(MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98) and hands that delegate to ServiceInfrastructureExtensions'WithMmcaServiceInfrastructureonce per service, which applies.WithSelectedBroker(attachBroker)itself (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:76): Notification (Program.cs:137-138), Engagement (:159), Conference (:197) and Identity (:222). Store does the same withAddSelectedBroker("STORE_BROKER", sqlServer)(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:74).BrokerSelectionTests.csinMMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/covers it. - Caveats / not-in-source: When the broker env var is absent entirely (for example integration tests that boot a service through
WebApplicationFactory<Program>with no AppHost),AddBrokerMessagingshort-circuits to in-process mode and InProcessMessageBus keeps working (Program.cs:64-67); that fallback lives in the consuming service, not here.
H2cHealthCheckRegistry
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/H2cHealthCheckExtensions.cs:154· Level 0 · class (sealed, internal)
- What it is: The AppHost-tier twin of GatewayDownstreamRegistry: a registration-time ledger of the resource-and-endpoint pairs already wired by
WithH2cHealthCheck, so a repeated call cannot register a duplicate health-check key. - Depends on:
IServiceCollectionandStringComparer(BCL). Used only by H2cHealthCheckExtensions. - Concept reinforced: the registration-time ledger, taught at GatewayDownstreamRegistry.
[Rubric §15, Best Practices & Code Quality],[Rubric §14, Testability]. The one idea this copy adds is in its own class doc (H2cHealthCheckExtensions.cs:148-152): the ledger is attached to the AppHost's own service collection rather than kept in a static field, so twoDistributedApplication.CreateBuilderinstances in one process, which is exactly what a test run is, never see each other's claims. A static ledger would make the second test in a file silently skip its registration. - Walkthrough:
private readonly List<string> _keys = [](:160), with the same list-over-HashSetnote the gateway registry carries (:155-159).TryClaim(key)(:168) compares case-insensitively and returnsfalseon a repeat (:170-173), otherwise appends and returnstrue(:175-176).GetOrAdd(services)(:185) scans the descriptors for a matchingImplementationInstance(:187-194) and otherwise registers a fresh one as a singleton (:196-198). The keys it holds are built byCheckKey(resourceName, endpointName)(:75-76), so the endpoint name is part of the identity and one resource can gate two endpoints. - Why it's built this way:
internal sealed, reachable from its tests through<InternalsVisibleTo Include="MMCA.Common.Aspire.Hosting.Tests" />(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/MMCA.Common.Aspire.Hosting.csproj:7). It is a deliberate duplicate rather than a shared type: this assembly is the AppHost tier and must not reference the service-defaults assembly (see Extensions for the same packaging rule applied to configuration section names). - Where it's used:
WithH2cHealthCheckclaims its key before registering anything (H2cHealthCheckExtensions.cs:122-125). Both behaviours it buys are pinned by H2cHealthCheckExtensionsTests:WithH2cHealthCheck_IsIdempotent,WithH2cHealthCheck_KeysTheCheckByEndpointSoOneResourceCanGateTwo, andWithH2cHealthCheck_DoesNotShareItsDuplicateGuardAcrossBuilders.
IdentityLinkExtensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/IdentityLinkExtensions.cs:23· Level 0 · class (public static)
- What it is: Two AppHost calls that point the Identity service's outward-facing URLs at the right resources:
WithUiLinks(ui)roots the OAuth redirect and the three emailed links (password reset, email confirmation, sign-in link) at the UI'shttpsendpoint, andWithIssuer(gateway)sets the JWT issuer to the gateway'shttpsendpoint. - Depends on:
Aspire.Hosting(IResourceBuilder<DotnetProjectResource>,GetEndpoint,ReferenceExpression). The configuration it writes is read by the Identity service's own settings classes (OAuthControllerBase.UIBaseUrlConfigKey,PasswordResetSettings,EmailConfirmationSettings,SignInLinkSettings,JwtSettings), whose section names it mirrors. - Concept introduced, deriving a service's public URLs from the resource graph.
[Rubric §33, Developer Experience],[Rubric §7, Microservices Readiness]. §33 asks whether the inner loop works without hand-tuned local configuration. Aspire allocates the UI and gateway endpoints at run time, so a hardcodedhttps://localhost:6002/reset-passwordin appsettings is a guess that breaks the moment a port moves. These calls hand Identity an endpoint reference instead, so every link it emails resolves to wherever the UI actually listens. Both calls add no reference and no wait (doc comments:66-71,:94-97), so they do not change the AppHost's startup graph. - Walkthrough:
- Six
internal constsection mirrors (:26-41):OAuthplus the propertyUIBaseUrl,PasswordReset,Authentication:EmailConfirmation,Authentication:SignInLinksandJwt. Three page routes from MMCA.Common.UI:/reset-password(:44),/confirm-email(:47) and/auth/sign-in-link(:50). The privateHttpsEndpointName = "https"(:52). EnvironmentKey(section, property)(:61-62) maps a configuration path to the environment-variable form .NET binds: every:becomes__and the property is appended after__, soAuthentication:SignInLinksplusSignInUrlbecomesAuthentication__SignInLinks__SignInUrl.WithUiLinks(ui)(:74, in anextension(IResourceBuilder<DotnetProjectResource> identity)block at:64) null-guards both builders (:76-77), resolves the UI'shttpsendpoint once (:79) and sets four variables (:81-91):OAuth__UIBaseUrlto the bare endpoint, andPasswordReset__ResetUrl,Authentication__EmailConfirmation__ConfirmationUrlandAuthentication__SignInLinks__SignInUrlto the endpoint plus the matching page route, each built withReferenceExpression.Create.WithIssuer(gateway)(:100) null-guards and setsJwt__Issuerto the gateway'shttpsendpoint (:105), the address clients see.
- Six
- Why it's built this way: The section names are mirrored as
internal constrather than referenced, because this AppHost-tier package must not reference the service-side packages that own the settings classes (the same rule Extensions applies to its rate-limit sections).EnvironmentKeyisinternalso ServiceTokenExtensions composes its own key the same way. Password reset links are the cache-backed flow recorded in ADR-091; the AppHost-only scope is ADR-098. - Where it's used: ADC sets the issuer (
MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:386) and the UI links (:477); Store does both atMMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:380-381.ServiceTokenExtensions.cs:73reusesEnvironmentKey. Covered byIdentityLinkExtensionsTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/IdentityLinkExtensionsTests.cs). - Caveats / not-in-source: The mirrored section names are not tied to the settings classes by anything in this file; source shows no cross-assertion here, so a renamed settings section would leave these variables unread.
ServiceBusEmulatorResource
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceBusEmulatorResource.cs:32· Level 0 · class (sealed)
What it is: The Aspire resource type for the official Azure Service Bus emulator container, publishing both of the emulator's planes and exposing the two connection expressions a consuming service needs.
Depends on:
Aspire.Hosting.ApplicationModel(ContainerResource,IResourceWithConnectionString,EndpointReference,ReferenceExpression,EndpointProperty). Provisioned by Extensions'AddServiceBusEmulatorBroker, and consumed by theWithBrokeroverload that takes it. The settings it feeds are MessageBusSettings / MessageBusProviders.Concept introduced, environment parity as a first-class local resource.
[Rubric §33, Developer Experience],[Rubric §17, DevOps],[Rubric §7, Microservices Readiness]. §33 assesses how closely the inner loop resembles production. RabbitMQ is fast and dependency-free but is a different broker with different topology semantics, so anything that only breaks on Azure Service Bus (entity naming limits, topic and subscription provisioning, scheduled redelivery) stays invisible locally until it reaches production. This resource closes that divergence for a stack that wants it. The class doc (ServiceBusEmulatorResource.cs:10-16) explains why two endpoints are non-negotiable: the emulator serves two planes on two protocols, AMQP for every publish and consume, and HTTP for the management plane that creates topics, subscriptions and queues. The Azure Service Bus transport provisions its own topology through that plane when its receiver starts, so a broker with no admin plane is not merely limited, it is unusable. ADR-066, in its 2026-09-01 revision, is the record.Concept introduced, a connection-string marker as a mode switch.
[Rubric §15, Best Practices & Code Quality],[Rubric §11, Security].ConnectionStringExpressionends inUseDevelopmentEmulator=true, and the doc comment (:18-24) says that suffix is not decoration: it keeps the Azure SDK clients on plain TCP and HTTP against a local host, and it is the markerMMCA.Common.Infrastructuredetects to take its emulator configuration branch. A real Azure Service Bus connection string never carries it, which is what makes the emulator path impossible to enter by accident in production.Walkthrough:
- Four constants pin the wire contract:
AmqpEndpointName = "amqp"(:35),AdminEndpointName = "admin"(:38),AmqpTargetPort = 5672(:41) andAdminTargetPort = 5300(:44). - The constructor (
:48-53) callsbase(name)and creates the twoEndpointReferences against itself. The resource name doubles as the container's network alias (:47). AmqpEndpoint(:56) andAdminEndpoint(:59) expose those references.ConnectionStringExpression(:66-68) buildsEndpoint=sb://{host}:{port};SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;from the allocated AMQP endpoint's host and port properties. The key name and value are the emulator's own fixed placeholders because it authenticates nothing (:62-64).AdminEndpointExpression(:81-83) builds{scheme}://{host}:{port}from the admin endpoint. The scheme is read off the allocated endpoint rather than written literally (:76-78), so the value tracks whatever the endpoint was declared as (httptoday: the management plane is cleartext by design and reachable only from the local development stack). A consumer hands this toMessageBus:EmulatorAdminEndpoint, which is what lets the infrastructure layer build the second administration client the Azure Service Bus transport provisions topology through on the emulator (:71-74).- The last doc paragraph (
:25-30) records a deliberate omission: no health check is declared. AWaitForon this resource therefore gates on the container running, not on the emulator finishing its warm-up, and the consuming service absorbs the remainder because the transport's receiver provisions and connects in the background, retrying, rather than failing host startup.
- Four constants pin the wire contract:
Why it's built this way: A dedicated resource type rather than a bare
AddContainerbecause the two connection expressions are the reusable part, andIResourceWithConnectionStringis what letsWithReferenceinject the AMQP string automatically. Both endpoint names and both container ports arepublic constso tests and consumers can assert them without string literals, which is exactly how ServiceBusEmulatorBrokerTests pins the published planes.Where it's used: Constructed by
AddServiceBusEmulatorBroker(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:261-298) and consumed by theWithBroker(IResourceBuilder<ServiceBusEmulatorResource>)overload (Extensions.cs:341-353). Both consumer AppHosts can select it through BrokerSelection: ADC picks the emulator over RabbitMQ whenADC_BROKER=servicebus(MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98) and Store whenSTORE_BROKER=servicebus(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:74), leaving RabbitMQ as the default inner loop. Covered end to end by ServiceBusEmulatorBrokerTests (ConnectionString_IsTheEmulatorForm_BuiltFromTheAllocatedAmqpEndpoint,AdminEndpoint_IsBuiltFromTheAllocatedManagementEndpoint).Caveats / not-in-source: The connection string is built from the allocated endpoint, so reading it before the application model has allocated ports is not meaningful. Nothing in this file constrains the emulator's own quota or TTL limits; that handling lives in MMCA.Common's
AddBrokerMessaging, keyed off theUseDevelopmentEmulator=truemarker, which is not this type's concern.
ServiceEndpointProfile
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceEndpointProfile.cs:7· Level 0 · enum
- What it is: The two cleartext endpoint profiles an MMCA service can run, used to pick the right AppHost startup probe for it.
- Depends on: Nothing. Read by ServiceInfrastructureExtensions.
- Concept reinforced: the probe must speak the protocol the endpoint serves, taught at H2cEndpointHealthCheck.
[Rubric §33, Developer Experience]. The enum turns that rule into a required argument, so a new service cannot be wired without stating which profile it runs. - Walkthrough:
Http2Only = 0(:13): the cleartext endpoint is h2c only, so the probe isWithH2cHealthCheck, since a stock HTTP/1.1 probe is answered with GOAWAY and never turns healthy (:9-12).Mixed = 1(:19): the ADR-012 mixed profile, where the default endpoint servesHttp1AndHttp2, so Aspire's stockWithHttpHealthCheckworks (:15-18). - Why it's built this way: Explicit values, and an enum rather than a boolean, so the call site reads as the profile name. ADR-012 records the two profiles.
- Where it's used: The branch in
WithMmcaServiceInfrastructure(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:80-84). ADC runs Notification asMixed(MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:138) and Engagement, Conference and Identity asHttp2Only(:159,:197,:222); Store runs Catalog and Identity asHttp2Only(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:162,:187).
HostIntegrationMarker
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Integrations·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationMarker.cs:10· Level 0 · class (sealed)
- What it is: A registration receipt. Each vendor adapter's host-level call (a configuration source, an exporter, a DataProtection key-ring sink) adds one of these to the service collection so the cloud-neutral core can tell at startup that the call was made (doc comment
HostIntegrationMarker.cs:3-8). - Depends on: Nothing beyond
string. ItsNameis meant to be one of the HostIntegrationNames constants (:9), and the markers are read by HostIntegrationTripwire. - Concept introduced, a receipt instead of a type reference.
[Rubric §7, Microservices Readiness],[Rubric §15, Best Practices & Code Quality],[Rubric §13, Observability & Operability]. The core packages never name an adapter type, because the adapters (MMCA.Common.Azure,MMCA.Common.Aws,MMCA.Common.Gcp) depend on the core and not the other way round. A marker carrying a well-known string is how the core still asks "did the Azure Key Vault call run?" without a compile-time edge to Azure. This is the dependency direction ADR-134 records for the cloud-neutral core. - Walkthrough: A primary constructor over
name(:10) and one get-only property,Name(:13). Registered as a plain singleton instance, for examplebuilder.Services.AddSingleton(new HostIntegrationMarker(HostIntegrationNames.AzureKeyVaultConfiguration))(MMCA.Common/Source/Hosting/MMCA.Common.Azure.Startup/AzureKeyVaultConfigurationExtensions.cs:115), so several markers coexist and resolve together asIEnumerable<HostIntegrationMarker>. - Why it's built this way:
public sealedbecause adapter packages outsideMMCA.Common.Aspiremust construct it. An instance per integration rather than one flag object keeps every adapter's registration a single additive line that cannot clobber another's. - Where it's used: Added by every adapter call that has a configuration gate:
AddAzureMonitorExporter(MMCA.Common/Source/Hosting/MMCA.Common.Azure.Startup/AzureMonitorExporterExtensions.cs:69),AddAzureKeyVaultConfiguration(AzureKeyVaultConfigurationExtensions.cs:84),AddAzureDataProtection(AzureDataProtectionExtensions.cs:57),AddAwsSecretsManagerConfiguration(MMCA.Common/Source/Hosting/MMCA.Common.Aws/AwsSecretsManagerConfigurationExtensions.cs:126),AddAwsDataProtection(AwsDataProtectionExtensions.cs:88),AddGoogleSecretManagerConfiguration(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/GoogleSecretManagerConfigurationExtensions.cs:117),AddGoogleCloudDataProtection(GoogleCloudDataProtectionExtensions.cs:103) andAddGoogleCloudTelemetryExporter(GoogleCloudTelemetryExporterExtensions.cs:127). The core itself adds theServiceDefaultsTelemetrymarker fromConfigureOpenTelemetry()(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:201). Two readers: HostIntegrationTripwire at startup, and the two vendor exporters, which scan the service descriptors for theServiceDefaultsTelemetrymarker and throwInvalidOperationExceptionwhen it is absent, so they cannot be registered ahead of the trace filter processors (AzureMonitorExporterExtensions.cs:50-57,GoogleCloudTelemetryExporterExtensions.cs:104-107). - Caveats / not-in-source: Nothing enforces that
Nameis one of the HostIntegrationNames constants; a misspelled name is simply a receipt nothing checks.
HostIntegrationNames
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Integrations·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationNames.cs:8· Level 0 · class (static)
- What it is: The vocabulary of well-known HostIntegrationMarker names. The core registers
ServiceDefaultsTelemetryitself; every other name is registered by the adapter call that owns it and checked at startup against the configuration that needs it (doc commentHostIntegrationNames.cs:3-7). - Depends on: Nothing. Read by HostIntegrationTripwire and by the adapter packages that write the markers.
- Walkthrough: Fourteen
public const stringvalues, each equal to its own identifier:ServiceDefaultsTelemetry(:14, registered byConfigureOpenTelemetry()and so byAddServiceDefaults(), the receipt a vendor exporter must be registered after),AzureMonitorExporter(:17),AzureKeyVaultConfiguration(:20),AzureDataProtection(:23),AwsSecretsManagerConfiguration(:26),AwsDataProtection(:29),GoogleSecretManagerConfiguration(:32),GoogleCloudDataProtection(:35)GoogleCloudTelemetryExporter(:38) andAwsTelemetryExporter(:41), then the four database and cache token-authentication receipts, registered byservices-level calls that takeconfiguration:AzurePostgreSqlEntraAuthentication(:44),AzureRedisEntraAuthentication(:47),AwsRdsIamAuthentication(:50) andGoogleCloudSqlIamAuthentication(:53). Each doc comment names the registering call and its package. - Why it's built this way: Constants in the core rather than in each adapter, so the core can check a name without referencing the package that writes it (ADR-134).
ServiceDefaultsTelemetryis the odd one out: it is not checked by the tripwire but is the ordering receipt the Azure Monitor and Google Cloud exporters require. - Where it's used: Every
HostIntegrationMarkerconstruction listed under HostIntegrationMarker, the nineCheckand fourCheckBooleanGatecalls in HostIntegrationTripwire (HostIntegrationTripwire.cs:91-156), andHostIntegrationTripwireTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Integrations/HostIntegrationTripwireTests.cs).
HostIntegrationTripwireOptions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Integrations·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationTripwireOptions.cs:8· Level 0 · class (internal, sealed, empty)
- What it is: An empty options type whose only job is to carry HostIntegrationTripwire through
ValidateOnStart, so the check runs with the other startup validators, before any hosted service starts (doc commentHostIntegrationTripwireOptions.cs:3-7). - Depends on: Nothing; it has no members (
:8is a bodylessinternal sealed class HostIntegrationTripwireOptions;). - Why it's built this way: The options validation pipeline is the framework's existing fail-fast hook (ADR-070). Riding it with a placeholder options type gets the tripwire the same timing and the same aggregated
OptionsValidationExceptionas every bound settings class, without inventing a second startup-check mechanism. - Where it's used: Registered in the Common.Aspire Extensions with
builder.Services.AddOptions<HostIntegrationTripwireOptions>().ValidateOnStart()plus aTryAddEnumerableofIValidateOptions<HostIntegrationTripwireOptions>mapped toHostIntegrationTripwire(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:51-53).AddServiceDefaults_ValidatesOnStart_AndFailsTheHostinHostIntegrationTripwireTests.cs:326pins that wiring.
H2cEndpointHealthCheck
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/H2cEndpointHealthCheck.cs:23· Level 1 · class (sealed, internal)
- What it is: An AppHost-side
IHealthCheckthat GETs one path on an Aspire endpoint over HTTP/2 with prior knowledge (h2c) and reports the outcome as that resource's health. - Depends on:
Aspire.Hosting.ApplicationModel(EndpointReference),IHealthCheck/HealthCheckResult(ASP.NET Core diagnostics), andSocketsHttpHandler/HttpClient/HttpVersionPolicy(BCL). Registered by H2cHealthCheckExtensions, whoseProbeTimeoutit reuses. It is the AppHost-tier analogue of DownstreamServiceHealthCheck, sharing the same version pair. - Concept introduced, gating a
WaitForon a protocol the resource actually speaks.[Rubric §29, Resilience & Business Continuity],[Rubric §33, Developer Experience],[Rubric §13, Observability & Operability]. Aspire's stock HTTP health check probes with a defaultHttpClient, so the request goes out HTTP/1.1 and an Http2-only cleartext endpoint refuses it with GOAWAYHTTP_1_1_REQUIRED(doc comment:11-16). The check therefore never turns healthy, the resource cannot be health-gated at all, and everyWaitForedge into it degrades to "the process started". The version pair below is the whole difference. - Concept introduced, a keep-alive ping as a correctness control rather than tuning.
[Rubric §29, Resilience],[Rubric §12, Performance & Scalability]. This is the most instructive comment in the chapter (:25-45) and it describes a real wedge. The client is shared for the process lifetime and HTTP/2 pools one connection per origin. Aspire's endpoint proxy listens before the target Kestrel does, so the first probe of a starting resource can open a connection that is accepted and then never answered: the TCP connect succeeds, the HTTP/2 handshake never completes, and the proxy holds that socket open for the life of the AppHost. Without pings, every later probe queues onto that one zombie connection and times out forever, even after the service is up, so the resource can never turn healthy and everyWaitForedge into it wedges the whole stack (the comment cites the 2026-08-31 apphost-smoke wedge and nightly runs 33392642362 / 33399413579). The pings bound the zombie's life instead: a connection that stops answering pings is torn down and the next probe opens a fresh one. The comment also records the fix that does not work and why,ConnectTimeoutdoes not cover this case because the connect itself succeeds. - Walkthrough:
ProbeHandler(:46-52) is astatic readonly SocketsHttpHandlerwithUseProxy = false(:48, the target is a sibling process on the developer's own machine or a sibling replica inside the deployment network) and the ping trio:KeepAlivePingDelayandKeepAlivePingTimeoutof one second each (:49-50) withHttpKeepAlivePingPolicy.Always(:51).ProbeClient(:59-60) is one process-lifetimeHttpClientover that handler, constructed withdisposeHandler: falseandTimeout = H2cHealthCheckExtensions.ProbeTimeout. Static rather than per-registration so a handful of gated resources do not each hold their own connection pool, and so this type owns no disposable instance state (:54-58).- Three readonly fields (
:62-64): aFunc<string>URL resolver, the path, and a send delegate. The production constructor (:71-74) takes anEndpointReferenceand passes() => endpoint.UrlplusProbeClient.SendAsync. The endpoint URL is resolved on every check, not captured at registration (:18-21), because the AppHost registers this check while building the application model and Aspire only allocates the endpoint once the resource starts. - The second constructor (
:88-96) is the test one, taking the resolver and the send delegate directly. Its doc comment (:76-83) explains the choice of a send delegate over anHttpMessageHandler: it keeps this type free of a disposable instance field, since the shared client is process-lifetime state and a per-instance client would make every registration an owner of one. CheckHealthAsync(:99) resolves the URL first, inside its owntry(:106-120). AnInvalidOperationExceptionthere means the endpoint has no allocation yet, which is the normal state for the first polls after the AppHost starts, and it returns the registration's failure status rather than Healthy and rather than letting the exception escape. The comment (:112-115) states the invariant: Aspire releases a wait only on Healthy, so a pre-allocation poll must not pass.- It then issues the GET (
:124-135) withVersion = HttpVersion.Version20andVersionPolicy = HttpVersionPolicy.RequestVersionExact(:131-132), the pair whose comment (:128-130) restates the h2c rule: with no TLS there is no ALPN to negotiate with, so the request has to go out as HTTP/2 and must not be allowed to fall back. Success returnsHealthywith a description naming the status and the protocol (:137-142); any other status returns the registration's failure status with the same description (:145). - The catch (
:147-161) is narrow (HttpRequestException,TaskCanceledException,TimeoutException,InvalidOperationException,UriFormatException) so a genuine programming error still surfaces. It carries no cancellation guard, and the comment (:149-156) explains that this is the considered choice rather than an omission: the registration's own timeout cancels the same token this method receives, so with such a guard a probe that outlivesProbeTimeoutwould slip past the filter and be logged by the health service as an unhandled exception rather than reported here. The other canceller is AppHost shutdown, where an Unhealthy result goes nowhere and costs nothing.
- Why it's built this way:
internal sealedwith two constructors, one for production and one that injects both collaborators, which is what lets the tests exercise the pre-allocation branch and the timeout branch without a running AppHost. The shared static client is the deliberate counterpart of that: process-lifetime state kept out of instance fields. - Where it's used: Constructed by
WithH2cHealthCheckinside itsHealthCheckRegistrationfactory (H2cHealthCheckExtensions.cs:131). Covered by H2cHealthCheckExtensionsTests, whose cases pin the version pair (Probe_SendsHttp2WithPriorKnowledge), the ping guard (ProbeHandler_KeepsTheKeepAlivePingGuardAgainstPoisonedConnections), the pre-allocation branch (Probe_WhenTheEndpointIsNotAllocatedYet_ReportsUnhealthyWithoutThrowing) and the cancelled-token branch (Probe_WhenTheRegistrationTimeoutHasCancelledTheToken_StillReportsUnhealthyRatherThanThrowing). - Caveats / not-in-source: The static handler and client are shared across every gated resource in the AppHost process, so the ping settings are global rather than per resource. This type is AppHost-only: nothing in a deployed service uses it, and the platform's own probes go through the dedicated Http1 listener described at KestrelEndpointExtensions.
H2cHealthCheckExtensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/H2cHealthCheckExtensions.cs:42· Level 1 · class (static)
What it is: One call,
WithH2cHealthCheck(path, endpointName), that registers an HTTP/2 health check against a project resource's endpoint and associates it with the resource, soWaitForedges into that resource wait for a real answer instead of merely for process start.Depends on: H2cEndpointHealthCheck (the check it constructs), H2cHealthCheckRegistry (the de-duplication ledger), plus
Aspire.Hosting(IResourceBuilder<DotnetProjectResource>,EndpointReference,WithHealthCheck) andHealthCheckRegistration(ASP.NET Core).Concept introduced, a startup gate must probe liveness, never readiness.
[Rubric §29, Resilience & Business Continuity],[Rubric §33, Developer Experience],[Rubric §13, Observability & Operability]. This is the rule to carry away from the whole chapter, and the doc comment onDefaultProbePath(:44-53) argues it as a cycle rather than a preference. A readiness endpoint aggregates downstream and warm-up checks, so gating startup on it can deadlock the dependency graph: the gateway waits for a service to report ready, that service's readiness includes a warm-up task that fetches through the gateway, and neither side can complete first. Liveness answers as soon as the process can serve a request, which is exactly what a dependent resource needs to know before it starts. ADR-012's 2026-08-29 update records the same reasoning and notes that the mixed-endpoint hosts' stock gates moved to/alivefor the same reason, leaving only the UI resources (which nothing waits for) gated on/health/ready.Concept introduced, recording a rejected alternative in the code that replaced it.
[Rubric §34, Architecture Governance & Documentation],[Rubric §15, Best Practices & Code Quality]. The class doc's second half (:24-35) exists so one specific idea is not re-proposed: surfacing the deployed HTTP/1.1 health-probe listener as an Aspire endpoint and pointing a stock check at it. InjectingHealthProbe__Portlocally flips KestrelEndpointExtensions out of endpoint-defaults mode and into explicit-listener mode, whoseListencalls then override theASPNETCORE_URLSbinding Aspire injects, so the service stops listening on the dynamic port Aspire allocated and every co-hosted service collides on one fixed cleartext port. The probe listener is a deployment-only construct; locally, the answer is to speak the protocol the service already serves.Walkthrough:
DefaultProbePath = "/alive"(:54) andDefaultEndpointName = "http"(:60, the cleartext endpoint is the h2c one, since anhttpsendpoint negotiates the version through ALPN and needs nothing special).ProbeTimeout = TimeSpan.FromSeconds(2)(:67), matching the gateway's downstream budget, and short for the same reason (:62-66): Aspire polls this check for as long as a dependent resource is waiting, and a probe slower than the poll interval turns the wait into a queue.CheckKey(resourceName, endpointName)(:76-77) composes{resource}-h2c-{endpoint}. The endpoint name is part of the key because a resource may expose more than one endpoint worth gating (:69-71).WithH2cHealthCheck(path = DefaultProbePath, endpointName = DefaultEndpointName)(:111, in anextension(IResourceBuilder<DotnetProjectResource> builder)block at:79) guards the builder and rejects blank arguments (:115-117), reaches the AppHost's own service collection (:119), builds the key (:120), and returns the builder unchanged when the ledger has already claimed it (:122-125), which is what makes a second call a no-op rather than a duplicate-key startup exception.- It then resolves the endpoint with
builder.GetEndpoint(endpointName)(:127). That resolution is lazy by design (:105-108): an endpoint name the resource never declares is not an error here, it surfaces as a permanently unhealthy check, which keeps the dependent resource waiting instead of letting it start against a service nobody verified. - The registration (
:129-134) names the key, constructs an H2cEndpointHealthCheck over that endpoint and path, setsfailureStatus: HealthStatus.Unhealthy, passestags: null(AppHost-side checks are not on a service's/healthendpoints, so the HealthCheckTags vocabulary does not apply), and appliesProbeTimeout. - The final
return builder.WithHealthCheck(key)(:138) is the half that is easy to miss, and the comment says so (:136-137):WithHealthCheckonly associates the named check with the resource, while the registration above is what supplies it, and both halves are required for aWaitForedge to gate.
Why it's built this way: An extension on
IResourceBuilder<DotnetProjectResource>so it chains into the existing AppHost fluent wiring, with defaults chosen so the common call is.WithH2cHealthCheck()with no arguments. Idempotence is engineered rather than assumed (see H2cHealthCheckRegistry). The doc comment is explicit that this replaces the stock extension only where it must: for an endpoint that servesHttp1AndHttp2, Aspire'sWithHttpHealthCheckis fine and this one is unnecessary (:85-89). The class carries the same scopedCA1708suppression as its siblings (:37-40).Where it's used: Applied with the default path to every ServiceEndpointProfile
Http2Onlyservice by ServiceInfrastructureExtensions'WithMmcaServiceInfrastructure(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:82-84), so neither AppHost calls it directly any more than it callsWithHttpHealthCheckfor its services. ADC gates Engagement, Conference and Identity that way (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:159,:197,:222), with the AppHost's own narrative block repeating the rationale (:328-337); Store gates Catalog and Identity (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:162,:187). GatewayUiExtensions reusesDefaultProbePathfor the gateway's stock liveness check. Covered by H2cHealthCheckExtensionsTests, whose cases pin the defaults, the association, the registration, idempotence, per-endpoint keying, cross-builder isolation, the lazy endpoint resolution and both argument guards.Caveats / not-in-source: This is AppHost-only wiring, so it affects local and CI runs rather than a deployed environment: ADR-012 records that production probes keep targeting the dedicated Http1-only listener. Nothing here validates that the probed path exists on the resource; a wrong path produces a permanently unhealthy check, which by design keeps dependents waiting.
HostIntegrationTripwire
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Integrations·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Integrations/HostIntegrationTripwire.cs:15· Level 1 · class (internal, sealed)
- What it is: A startup validator that fails the host when configuration asks for a vendor integration whose adapter call was never made. A deployment that still sets
KeyVault:Uribut no longer callsAddAzureKeyVaultConfiguration()would otherwise start cleanly with every vault secret missing, or ship no telemetry at all, and look healthy while doing it (doc commentHostIntegrationTripwire.cs:5-12). - Depends on:
IConfiguration,IEnumerable<HostIntegrationMarker>(the receipts), HostIntegrationNames (what each receipt is called) andIValidateOptions<HostIntegrationTripwireOptions>(Microsoft.Extensions.Options), which is how it runs. - Concept introduced, a cloud-neutral core still owes a loud failure for a missing adapter.
[Rubric §13, Observability & Operability],[Rubric §11, Security],[Rubric §17, DevOps]. Moving vendor code out of the core (ADR-134) turns each vendor feature into an opt-in call, and an opt-in call can be forgotten without any compile error. The tripwire converts that silent omission into a startup failure that names the missing call and its package, in line with the fail-fast contract of ADR-070. The integrations it guards are the ones whose absence is invisible at runtime: telemetry export (ADR-041), secret sources (ADR-061) and the shared DataProtection key ring (ADR-069). - Walkthrough:
Nine
internal constpresence-gate keys (:20-49):APPLICATIONINSIGHTS_CONNECTION_STRING,KeyVault:Uri,DataProtection:BlobStorageUri,SecretsManager:NamePrefix,DataProtection:S3ObjectUri,GoogleSecretManager:NamePrefix,DataProtection:GcsObjectUri,GoogleCloudTelemetry:ProjectIdandAwsTelemetry:Region, beside the four boolean database and Redis token gates (:51-74). The Google Secret Manager comment (:34-39) explains why the prefix, not the project id, is the gate: the prefix declares that the host reads its settings from Secret Manager, while a project id alone only names a location.KeyRingKeys(:77-82) lists the three DataProtection gates, and_registered(:84) is aHashSet<string>of every marker'sName, built once in the constructor.Validate(name, options)(:87) makes nineCheckcalls (:91-135), one per presence gate paired with its integration name and a consequence message that names the call to add and where (for example "Reference MMCA.Common.Azure.Startup (or MMCA.Common.Azure, which includes it) and call builder.AddAzureMonitorExporter() after AddServiceDefaults()",:94), then fourCheckBooleanGatecalls (:137-156) for the Azure PostgreSQL, RDS IAM, Cloud SQL IAM and Azure Redis token configurators.Check(:171-177) adds"{key} is set, but {consequence}."when the key is set and the receipt is missing;IsSet(:195) treats blank and whitespace values as unset.CheckBooleanGate(:179-193) reads its key throughReadBooleanGate(:202-211): blank or absent is off,trueorfalsein any case parses, and any other value is itself a failure naming the accepted values, because unreadable is not off: whoever wroteyesor1meant on (:184-185). A true gate with no receipt adds"{key} is true, but {consequence}.".A cross-check (
:158-166): more than one configured key ring fails even when every adapter call was made, because whichever registration runs last owns the repository, so services that disagree on the order mint cookies and tokens the others cannot decrypt (:158-160). The message names the keys that are set and asks to clear the ones for clouds the host does not run on.All failures are collected and returned together through
ValidateOptionsResult.Fail(failures)(:168), so a host missing several calls learns about all of them in one start.
- Why it's built this way: An
IValidateOptions<T>over an empty options type rather than a hosted service, so it runs with the otherValidateOnStartvalidators before any hosted service starts. It reads markers rather than adapter types so the core keeps no reference to Azure, AWS or Google packages.ServiceDefaultsTelemetryis deliberately not checked here: that receipt orders exporters and is enforced by the exporters themselves (see HostIntegrationMarker). - Where it's used: Registered unconditionally by the Common.Aspire Extensions (
MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:47-53), so every host built on service defaults carries it. Covered byHostIntegrationTripwireTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Integrations/HostIntegrationTripwireTests.cs), includingConfiguredWithoutTheAdapterCall_FailsNamingTheCall(:55),EveryMissingIntegration_IsReportedInOneFailure(:88),AllThreeDataProtectionKeyRings_FailOnce_NamingEach(:139),GoogleSecretManagerProjectIdAlone_StaysSilent(:157),TokenGateNotABoolean_FailsEvenWithTheMarker(:304) andAddServiceDefaults_ValidatesOnStart_AndFailsTheHost(:326); the Redis gate also hasAzureRedisEntraTripwireTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Integrations/AzureRedisEntraTripwireTests.cs). - Caveats / not-in-source: It checks only that a receipt exists, not that the adapter call succeeded or ran in the right order. A gate key it does not list (any new vendor setting) gets no protection until a constant and a
CheckorCheckBooleanGatecall are added here.
Extensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:24· Level 1 · class (static)
Disambiguation: this is the Common.Aspire.Hosting
Extensions(the AppHost-side broker, mail, JWKS, E2E and data-source wiring). The other class namedExtensionsin this chapter is the framework's Common.AspireExtensions(the canonical service-defaults bootstrap, service-side). Neither app ships a localServiceDefaultsproject; their services consume the Common.Aspire one directly.
What it is: AppHost-side Aspire extension methods that wire shared local infrastructure (a RabbitMQ broker or the Azure Service Bus emulator, a MailDev SMTP sink), JWKS-based identity discovery, CI/E2E signing keys and limit lifts, and per-service database routing onto Aspire resources.
Depends on: ServiceBusEmulatorResource and
Aspire.Hosting/Aspire.Hosting.RabbitMQ/Aspire.Hosting.Azure/Aspire.Hosting.PostgreSQL(IDistributedApplicationBuilder,IResourceBuilder<ContainerResource>,IResourceBuilder<RabbitMQServerResource>,IResourceBuilder<DotnetProjectResource>,IResourceBuilder<SqlServerDatabaseResource>,IResourceBuilder<PostgresDatabaseResource>,AzureCosmosDBDatabaseResource,ReferenceExpression). Conceptually pairs with MessageBusProviders / MessageBusSettings (the env vars it sets), the JWKS auth side (IJwksProvider, RsaJwksProvider), the multi-source routing in DataSourceResolver / EntityDataSourceRegistry, and GatewayRateLimitingSettings (the section its gateway lift writes into), plus MailDevDefaults (the linked source of both MailDev ports).Concept introduced, the AppHost tier is a separate package on purpose.
[Rubric §7, Microservices Readiness],[Rubric §8, Data Architecture],[Rubric §17, DevOps],[Rubric §11, Security],[Rubric §32, Dependency & Supply-Chain]. This assembly is deliberately separate fromMMCA.Common.Aspire(the service-defaults assembly every running service consumes) so that running services do not pull in the heavyAspire.Hostingtooling package (doc commentExtensions.cs:14-18). The rule bites in a visible place: rather than referencingGatewayRateLimitingSettings.SectionName, this class mirrors the literal as its own constant, and the comment (:104-111) states both halves of the trade, that the AppHost tier must not pull in the service-defaults graph (OpenTelemetry, Redis, the health-check drivers, Serilog) to spell one configuration key, and that a unit test cross-asserts the two are equal so a section rename cannot silently orphan the lift. That is the general answer to "a duplicated literal across a package boundary": duplicate it, then pin the duplication with a test. ADR-098 records the scope of Aspire adoption here (orchestration and service defaults, not a testing substrate). The class also carries a scopedCA1708suppression (:19-22) documenting the known analyzer false positive: with two or moreextension(T)blocks in one static class, the compiler-generated grouping members trip the "identifiers should differ by more than case" rule.Walkthrough:
Constants.
DefaultBrokerResourceName = "rabbitmq"(:29) andE2eRegistrationsPerIpPerHour = 1000(:36), the latter "high enough that no suite can reach it" while production keeps the real anti-abuse throttle (:31-35). The E2E group addsE2eLiftTriggerVariable = "E2E_LIFT_REGISTRATION_THROTTLE"(:43, internal, the CI trigger both lifts read), the InteractiveServer pairE2eForceServerTriggerVariable = "E2E_FORCE_SERVER"(:49) andE2eForceServerConfigurationKey = "E2E__ForceServer"(:55), and the InteractiveWebAssembly pairE2eForceWebAssemblyTriggerVariable = "E2E_FORCE_WASM"(:63) andE2eForceWebAssemblyConfigurationKey = "E2E__ForceWebAssembly"(:69); the doc comment on the first (:57-62) states that a forced-WebAssembly run also implies both lifts and vetoesWithE2eForceServer, so it needs no second variable. The lifted values areE2eGatewayPermitLimit = 100000(:75),E2eGatewayGlobalConcurrencyLimit = 10000(:81),E2eAuthTightPermitLimit = 100000(:87) andE2eAuthIpPermitLimit = 100000(:94), composed into keys from four internal constants:RateLimitingSection = "RateLimiting"(:102, mirroringRateLimitingSettings.SectionName),GatewayRateLimitingSection(:112),MmcaGatewaySection = "MmcaGateway"(:119) andAuthTightPolicyName = "auth-tight"(:126, the one part with no framework type to derive it from, because a route policy name is app configuration). The emulator group pinsDefaultServiceBusEmulatorResourceName = "servicebus"(:131),ServiceBusEmulatorImageRegistry = "mcr.microsoft.com"(:136),ServiceBusEmulatorImage(:141) andServiceBusEmulatorImageTag = "2.0.1"(:150), the tag comment (:143-149) recording that 2.x is a floor rather than a preference: the HTTP management plane the Azure Service Bus transport provisions its topology through shipped in 2.0.0, so a silent downgrade to a 1.x image leaves the broker unusable rather than merely older. The mail group fixesDefaultMailDevResourceName = "maildev"(:155),MailDevHttpPort(:163) andMailDevSmtpPort(:169), both read from the linked MailDevDefaults soMMCA.Common.Testing.E2E'sMailDevInboxreads the inbox from the same port (:157-162), andMailDevImageTag = "3.0.0"(:178), pinned because the untagged image drifted (a fresh CI pull took 3.0.0 while a developer's persistent container stayed on 2.2.1) and 3.x serves the REST message list at/api/emailrather than/email(:171-177).AddMailDev(name)(:201, in anextension(IDistributedApplicationBuilder builder)block at:180):AddContainer(name, "maildev/maildev", MailDevImageTag)with a persistent lifetime and two published endpoints (:206-209). Both host ports are fixed rather than dynamic (:186-191), because the web UI is opened by hand and the SMTP port is what each consumer'sSmtp:Portsetting names; the persistent lifetime is what lets the captured inbox survive an AppHost restart. The last doc paragraph (:192-197) is the upgrade step that follows from it: a persistent container created from another image keeps running until removed, so remove it once (docker rm -f, AppHost stopped) after a tag change.AddMessageBroker(name)(:220):builder.AddRabbitMQ(name).WithManagementPlugin()(:224), so one call provisions the broker container with its management UI. Production overrides the connection string via configuration so the same projects can target Azure Service Bus without an AppHost change (:213-216). See ADR-066.AddServiceBusEmulatorBroker(sqlServer, name)(:261): the parity option. It constructs a ServiceBusEmulatorResource (:269) and chainsWithImagebeforeWithImageRegistry, with the comment explaining the ordering (:272-273): the registry call updates the image annotation the image call creates, and throws when there is none yet. It then publishes the AMQP endpoint astcpand the admin endpoint as HTTP (:276-282), setsACCEPT_EULA=Y(:287, with the comment at:284-286noting the image is only ever used for local development and test), passes the existing SQL Server's host and SA password asSQL_SERVER/MSSQL_SA_PASSWORD(:288-293), and finishes with.WaitFor(sqlServer)(:297) because the emulator's first act is to create its schema. The doc comment (:227-260) carries the design: the emulator stores its state in SQL Server, so it reuses the stack's engine rather than starting a second one, it is opt-in because it costs a container and a warm-up, and host ports are left to Aspire because nothing outside the stack dials them.WithBroker<TResource>(broker), RabbitMQ overload (:312, in a genericextension<TResource>(IResourceBuilder<TResource> service) where TResource : IResourceWithEnvironment, IResourceWithWaitSupportblock at:301-302):.WithReference(broker)+.WaitFor(broker)+.WithEnvironment("MessageBus__Provider", "RabbitMq")(:319-321). One fluent step wires the reference, holds the service until the broker is healthy, and selects the transport. The generic constraint statically restricts the method to capable resources.WithBroker<TResource>(broker), emulator overload (:341): the same reference and wait,MessageBus__Provider=AzureServiceBus, and two more env vars,MessageBus__ConnectionStringfrom the resource's emulator-form connection string andMessageBus__EmulatorAdminEndpointfrom its management-plane expression (:347-352); the doc comment (:324-330) describes that address as what the Azure Service Bus transport needs to build its administration client. It then restates the mode-switch rule (:331-337): the connection string carriesUseDevelopmentEmulator=true, which is the marker the Azure Service Bus transport keys its emulator branch off, and that transport isAddAzureServiceBusTransport()fromMMCA.Common.Azure, which the service must register itself. A production connection string never carries the marker, so the emulator path cannot be entered by accident.WithJwksDiscovery<TResource>(identity, gateway?)(:370, both parametersIResourceBuilder<DotnetProjectResource>):.WithReference(identity)+.WaitFor(identity)(:378-379), then a deferred.WithEnvironment(context => ...)(:380) that setsAuthentication__JwtBearer__Authority(:396), which the consuming service passes toAddForwardedJwtBearer(authority, audience, configuration, environment)(:357). It prefers the gateway HTTPS endpoint over Identity's (:393-395) because, per the inline comment (:382-392), Identity listens HTTP/2-only on cleartext for gRPC h2c, but the defaultJwtBearerbackchannelHttpClientsends HTTP/1.1, which Kestrel rejects on an Http2-only endpoint. The gateway terminates TLS, supports HTTP/1.1 and HTTP/2 via ALPN, and forwards/.well-known/*to Identity, so the metadata fetch works end to end. With no gateway passed it falls back to Identity's HTTPS endpoint, with the HTTP/1.1 caveat. See ADR-004, ADR-008 and ADR-012.WithE2eRsaKeys()(:414, in anextension(IResourceBuilder<DotnetProjectResource> identity)block at:401): a CI/E2E-only helper that readsE2E_JWT_PRIVATE_KEY_PEM/E2E_JWT_PUBLIC_KEY_PEMfrom the AppHost's own environment (:418-419), returns the builder unchanged when either is missing (:420-423), and otherwise maps them ontoJwt__RsaPrivateKeyPem,Jwt__RsaPublicKeyPemandJwks__RsaPublicKeyPem(:425-428). The doc comment (:403-411) records the failure it prevents: without the forwarding, every CI login and register fails with "No supported key formats were found" and the readiness gate times out. It is a no-op locally and in production, where the variables are absent and user-secrets or Key Vault supply the keys.WithE2eRegistrationThrottleLift()(:456): computesliftasIsTrue(E2eLiftTriggerVariable) || IsTrue(E2eForceWebAssemblyTriggerVariable)(:460) and, when lifted, sets two variables formatted invariantly (:462-470):LoginProtection__MaxRegistrationsPerIpPerHourtoE2eRegistrationsPerIpPerHourandRateLimiting__AuthIpPermitLimittoE2eAuthIpPermitLimit; otherwise it returns the builder untouched. The doc comment states both problems. Production allows ten registrations per IP per hour, and an E2E suite registers far more than that from a single localhost IP, so the default refuses every register test past the tenth and the failures look like broken registration (:432-438). The per-IP auth limiter (default 30 a minute) runs out the same way, because with passkeys offered every visit to the login page spends one auth-ip permit on the passkey autofill options call before the login spends another, so the suite's logins fail with 429 (:440-446).WithE2eForceServer()(:490, in anextension(IResourceBuilder<DotnetProjectResource> ui)block at:474): the render-mode peer of the two lifts, applied to the UI resource instead of a service. It computesforceasIsTrue(E2eForceServerTriggerVariable) && !IsTrue(E2eForceWebAssemblyTriggerVariable)(:494) and, when forced, setsE2E__ForceServer=true(:496-498); otherwise it returns the builder untouched. The doc comment (:477-481) gives the reason: under InteractiveAuto the post-login second page load switches to the background-downloaded WASM runtime, whose boot on a shared 2-core CI runner exceeds every suite wait, so the suite pins the host to InteractiveServer. WhenE2E_FORCE_WASMalso reads true nothing is written: forced WebAssembly wins (:483-486). The UI host readsE2E:ForceServeritself; this method only forwards the switch.WithE2eForceWebAssembly()(:514): the opposite pin, for local runs. WhenE2E_FORCE_WASMreads true it setsE2E__ForceWebAssembly=true(:518-520), so every interactive page boots the WebAssembly runtime and the client render path can be exercised end to end; the UI host reads the key throughE2eRenderMode.Resolvein MMCA.Common.UI.Web (:502-506). Absent in CI and in production, so it is safe to call unconditionally (:508-510).WithE2eGatewayRateLimitLift()(:548, in anextension(IResourceBuilder<DotnetProjectResource> service)block at:524): the same trigger (:552) applied to the edge limiter, returning the builder unchanged when not lifted (:554-557). When lifted it writes three overrides (:559-568):GatewayRateLimiting__PermitLimit,GatewayRateLimiting__GlobalConcurrencyLimit, and the per-routeMmcaGateway__RateLimiterPolicies__auth-tight__PermitLimit, all composed from the mirrored section constants rather than hard-coded strings. The doc comment (:526-545) is worth reading for the diagnosis: the whole suite arrives from one loopback client IP, so the per-IP window that protects production reads the suite itself as the flood (it names ADC run 32185349945 and its twelve login failures), and the named anti-credential-stuffing policy has the same problem for the same reason. It closes with the operational warning that a regression here surfaces as login and register E2E reds, never as a build failure. All three E2E triggers are read by the privateIsTrue(variable)helper (:714-715): onlytrue, in any case, switches a trigger on.WithSQLServerDataSource(database, logicalName)(:587): the AppHost manifestation of ADR-006. After the argument guards, which include the privateThrowIfInvalidLogicalName(logicalName)check (:593, see the end of this walkthrough), one fluent chain:.WithReference(database),.WaitFor(database), then a single.WithEnvironmentsettingDataSources__{logicalName}__SQLServerConnectionString(:595-598), which the double-underscore convention flattens toDataSources:{logicalName}:SQLServerConnectionStringfor the multi-source routing layer. The doc comment (:577-582) is explicit that that one entry is the whole configuration: with no top-level connection string, the single database a host declares this way also becomes itsDefaultsource, so the framework's own tables and the readiness health check both land on it and the logical name collapses ontoDefault, giving one context, one change tracker and one migration set per deployed service.WithPostgreSQLDataSource(database, logicalName)(:618-630, doc comment:601-617): the PostgreSQL peer ofWithSQLServerDataSource, added alongside ADR-113 (PostgreSQL as a first-class engine). Same shape, one fluent chain overIResourceBuilder<PostgresDatabaseResource>, settingDataSources__{logicalName}__PostgreSQLConnectionStringinstead. The doc comment restates the SQL Server rule verbatim: that one entry is the whole configuration, and with no top-level connection string the single database a host declares this way also becomes itsDefaultsource.WithCosmosDataSource(database, logicalName)(:648): the Azure Cosmos DB sibling (ADR-018)..WithReference+.WaitFor+ two env vars: the account connection string the resolver hands toCosmosDbContext.UseCosmos(...), andCosmosDatabaseName, sinceUseCosmostakes the database name separately. Unlike SQL Server, a service typically uses Cosmos for one module alongside its SQL Server source, so this is layered on top of rather than instead ofWithSQLServerDataSource.WithSqliteDataSource(logicalName, filePath)(:674): the SQLite sibling. SQLite has no Aspire container resource (it is an in-process file), so this only injectsDataSources__{logicalName}__SqliteConnectionStringbuilt asData Source=<path>. Note the different signature, afilePathstring instead of a database resource, which it rejects when blank (:680).ThrowIfInvalidLogicalName(logicalName)(:698-708, private): the guard all fourWith*DataSourcehelpers call before wiring anything (:593,:624,:654,:679). It rejects a null, empty or whitespace name withArgumentException.ThrowIfNullOrWhiteSpace(:700), and throwsArgumentExceptionfor a name containing:or__(:702-707). The doc comment (:689-695) gives the reason for each: a blank name is an emptyDataSourceskey the service refuses at startup, and a:or__nests the connection string under another key, so the service binds no usable named source and silently falls back to a top-level connection string if it has one. Failing in the AppHost puts the error beside the call that caused it.
Why it's built this way: Fluent extensions on
IResourceBuilder<T>match the Aspire AppHost idiom; the assembly split keeps service runtimes free of AppHost-only dependencies; the optionalgateway?lets a monolith deployment still use JWKS by pointing straight at Identity. The fourWith*DataSourcehelpers share one naming shape so an engine move is a one-line AppHost change, and makinglogicalNamean explicit parameter keeps each service's database identity discoverable by reading the AppHost;WithPostgreSQLDataSourcemirrorsWithSQLServerDataSource's doc comment almost word for word rather than abbreviating it, which is deliberate: the "one entry is the whole configuration" rule is the part a reader must not miss on either engine. The fiveWithE2e*helpers are the same idea applied to test infrastructure: the knowledge that CI needs a keypair forwarded, the limiters lifted and the UI host pinned to one render mode lives in the framework rather than being copied into each app's AppHost. None takes a call-site flag, and each is inert unless its trigger environment variable is set (the two lifts readE2E_LIFT_REGISTRATION_THROTTLEorE2E_FORCE_WASM,WithE2eForceServerreadsE2E_FORCE_SERVERand yields toE2E_FORCE_WASM,WithE2eForceWebAssemblyreadsE2E_FORCE_WASM, andWithE2eRsaKeysreads the key variables directly), so an AppHost calls every one unconditionally.Where it's used: The AppHost
Program.csof every consumer, much of it through the composite helpers. ADC chooses its broker through BrokerSelection (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98), which callsAddServiceBusEmulatorBroker(sqlServer)when the variable isservicebusand otherwiseAddMessageBroker()with a persistent lifetime, adds MailDev once (:106), and wires each service's database through ServiceInfrastructureExtensions'WithMmcaServiceInfrastructure(:137-138,:159,:196,:221), which callsWithSQLServerDataSourceitself. It forwards E2E keys to Identity (:230), wires JWKS discovery for the three non-Identity services through the gateway (:374-376), pins the UI withui.WithE2eForceWebAssembly()(:410) andui.WithE2eForceServer()(:418), and applies both lifts (:424on Identity,:431on the gateway). Store does the same for its three services: broker viaAddSelectedBroker("STORE_BROKER", sqlServer)atMMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:74, MailDev at:80,WithMmcaServiceInfrastructureat:162,:187,:245,WithE2eRsaKeys()at:200,WithJwksDiscoveryat:337-338, the lifts at:348and:357, and the UI pins at:405and:410. The Helpdesk seed app calls the data-source helper directly on its single host:MMCA.Helpdesk/Source/Hosting/MMCA.Helpdesk.AppHost/Program.cs:33.WithPostgreSQLDataSource,WithCosmosDataSource, andWithSqliteDataSourceare available framework plumbing but no consumer wires them today: every ADC and Store service runs on SQL Server. The E2E lifts are covered by E2eLiftTests,WithE2eForceServerbyE2eForceServerTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/E2eForceServerTests.cs), the emulator path by ServiceBusEmulatorBrokerTests.Caveats / not-in-source: For all four
With*DataSourcehelpers thelogicalNamemust match the key the owning entity's configuration derives (module namespace or[UseDatabase]).ThrowIfInvalidLogicalName(:698) checks only the name's shape (non-blank, a single configuration key segment), not that it matches any entity's derived key, so a well-formed but mismatched name still routes that entity to theDefaultsource rather than failing at startup.WithSQLServerDataSourcesets only theDataSources__key; a host that also needs the top-level connection string sets it itself, as the Helpdesk AppHost does and explains (MMCA.Helpdesk/Source/Hosting/MMCA.Helpdesk.AppHost/Program.cs:10-12,:34). No consumer AppHost callsWithPostgreSQLDataSourceyet, so it has no live usage site beyond the framework's own tests.
ServiceTokenExtensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceTokenExtensions.cs:22· Level 1 · class (public static)
- What it is: The AppHost half of service-to-service token signing: one call adds the shared signing key as a generated, persisted secret parameter, and a second hands that parameter to each service as
Grpc__ServiceToken__SigningKey. - Depends on:
Aspire.Hosting(ParameterResource,GenerateParameterDefault,AddParameter,IResourceBuilder<DotnetProjectResource>) andEnvironmentKeyfrom IdentityLinkExtensions. The value is read service-side byServiceTokenSettings, whose section and property names it mirrors. - Concept introduced, a generated secret that survives restarts.
[Rubric §11, Security],[Rubric §33, Developer Experience]. Every service that mints or verifies a service token must hold the same key, and a developer should not have to create one by hand.AddServiceTokenSigningKeyasks Aspire to generate the value when configuration supplies none and to persist it to the AppHost's user secrets (doc comment:38-43), so the key is random per developer, never committed, and stable across AppHost restarts. Handing services the parameter itself rather than a copy of its value (:61-63) keeps the secret flagged as a secret all the way to the resource. - Walkthrough:
DefaultSigningKeyParameterName = "grpc-service-token-signing-key"(:28), chosen because it is the user-secrets slot existing AppHosts already persisted the key under, so adopting the helper regenerates no developer key (:24-27). Two internal mirrors compose the target key:ServiceTokenSection = "Grpc:ServiceToken"(:31) andSigningKeyProperty = "SigningKey"(:34).AddServiceTokenSigningKey(name)(:46, in anextension(IDistributedApplicationBuilder builder)block at:36) guards its arguments (:48-49) and callsAddParameterwithGenerateParameterDefault { MinLength = 64, Special = false },secret: trueandpersist: true(:51-55). Sixty-four letters and digits is valid Base64 decoding to 48 bytes, above the 32-byte floorServiceTokenSettingsenforces (:39-41).WithServiceTokenSigningKey(signingKey)(:67, in anextension(IResourceBuilder<DotnetProjectResource> service)block at:59) guards and setsGrpc__ServiceToken__SigningKeyto the parameter (:72-74).
- Why it's built this way: The section names are mirrored rather than referenced for the same AppHost-tier packaging reason as Extensions. The default parameter name is the compatibility choice: a rename would silently mint a new key on every developer machine.
- Where it's used: ADC adds the key once and hands it to Identity, Engagement and Notification (
MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:243-246); Store adds it and hands it to Identity and Sales (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:212-213,:270). Covered byServiceTokenExtensionsTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/ServiceTokenExtensionsTests.cs).
GatewayUiExtensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/GatewayUiExtensions.cs:16· Level 2 · class (public static)
- What it is: The edge half of an MMCA AppHost in three calls:
WithMmcaGatewaywires the gateway over the services it fronts,WithMmcaUiwires the UI head over the gateway and the services, andWithGatewayApiEndpointstells the UI where the gateway lives. - Depends on:
Aspire.Hosting(IResourceBuilder<DotnetProjectResource>,WithExternalHttpEndpoints,WithHttpHealthCheck,WithEndpoint,GetEndpoint) and H2cHealthCheckExtensions'DefaultProbePath. - Concept reinforced: probe liveness for a startup gate, taught at H2cHealthCheckExtensions, plus its one deliberate exception.
[Rubric §29, Resilience & Business Continuity],[Rubric §33, Developer Experience]. A startup gate on readiness pulls cross-resource state into the startup order; the doc comment (:28-34) names the 2026-08-29 UI WaitFor wedge, from when the gateway's readiness still included one probe per downstream service, so one unreachable downstream stoppedui.WaitFor(gateway)from ever releasing, the stack never became ready and a whole E2E run reported zero tests executed. The downstream checks are now tagged optional (reported on/healthonly), but liveness is still what a wait needs: Kestrel up and serving. The UI is the exception: it gates on readiness, because it runs the defaultHttp1AndHttp2profile, maps the readiness endpoint itself, and nothing in the AppHost waits for it, so no startup cycle can form; the E2E suite and a developer's browser then wait for a real 200 (:77-81). - Walkthrough:
HttpsEndpointName = "https"(:18).WithMmcaGateway(httpsPort, params services)(:40, in anextension(IResourceBuilder<DotnetProjectResource> gateway)block at:20) guards its arguments (:44-45), adds a reference to and a wait on each service in the order given, guarding each (:47-51), then marks the endpoints external, addsWithHttpHealthCheck(H2cHealthCheckExtensions.DefaultProbePath)(the/aliveliveness path) and pins thehttpsendpoint tohttpsPort(:53-56), the well-known URL every client and the E2E suite dial.WithMmcaUi(gateway, httpsPort, params services)(:88, in theextension(IResourceBuilder<DotnetProjectResource> ui)block at:60) marks the UI external with a reference to and wait on the gateway (:97-99), a wait on each service, guarding each (:101-105), thenWithHttpHealthCheck("/health/ready")and the pinnedhttpsendpoint (:107-109). The services are waited for but not referenced, and the doc comment (:70-74) says why: the UI calls every API through the gateway, so aservices__{service}__*variable in the UI process would be a discovery name nothing resolves, and a service-discovery edge production does not have (the UI container app is given only the gateway). The waits alone keep the startup order, so the UI comes up once the services behind the gateway are live. The UI project must be added with itshttpslaunch profile so that endpoint exists to pin.WithGatewayApiEndpoints(gateway)(:128) sets bothApi__ApiEndpointandApi__WasmApiEndpointto the gateway'shttpsendpoint (:133-137), adding no reference and no wait. The doc comment (:116-124) explains why both: the WASM value is what the browser receives (and what the Blazor CSP pinsconnect-srcto), and a browser cannot resolve an Aspire service-discovery name; the server value defaults tohttp://gateway, which everyIHttpClientFactoryclient resolves, but a SignalRHubConnectionbuilds its own handler, never sees the discovery handler, and so needs the real endpoint too.
- Why it's built this way: Both AppHosts wired the gateway and UI identically, so the shape lives once in the framework, with the probe rule written into it rather than left to each app. Deployed environments own their own probes (
:34); these helpers set only the local AppHost's startup gates. - Where it's used: ADC wires the gateway on port 6001 over four services (
MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:365), the UI on 6002 (:395) and the UI's API endpoints (:470); Store wires the gateway on 6001 over three services (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:320), the UI on 6002 (:367) and the UI's API endpoints (:372) the same way. Inside the framework, ServiceInfrastructureExtensions is its one other source reference. - Caveats / not-in-source: No test file for this type appears in the brief's usage sites; not determinable from source here which tests cover it.
ServiceInfrastructureExtensions
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/ServiceInfrastructureExtensions.cs:16· Level 2 · class (public static)
- What it is: One call,
WithMmcaServiceInfrastructure, that wires a backend service to its database, cache, broker and mail server and adds the startup probe its endpoint profile needs. - Depends on: Extensions'
WithSQLServerDataSource, BrokerSelection'WithSelectedBroker, H2cHealthCheckExtensions and ServiceEndpointProfile, plusAspire.Hosting(IResourceBuilder<SqlServerDatabaseResource>,IResourceBuilder<IResourceWithConnectionString>,IResourceBuilder<IResource>,WithHttpHealthCheck). - Concept introduced, one composite call per service as the AppHost's unit of repetition.
[Rubric §33, Developer Experience],[Rubric §7, Microservices Readiness],[Rubric §29, Resilience & Business Continuity]. Every service needs the same five edges and one probe, and a hand-written chain per service is where one service quietly loses its cache wait or gets a readiness gate. The doc comment (:20-44) fixes the order (database, cache reference, broker, cache wait, mail wait, probe, so the waits are database, broker, cache, mail), keeps the service's endpoints internal because a backend is reached through the gateway (:28-32), always probes liveness (:34-37), and references only the cache, the database and the broker, never another project, so the AppHost's project-to-project edges are exactly what the host declares itself (:39-43). - Walkthrough:
WithMmcaServiceInfrastructure(database, logicalName, cache, mailServer, attachBroker, profile, probeEndpointName = null)(:57-64, in anextension(IResourceBuilder<DotnetProjectResource> service)block at:18) null-guards every resource and the delegate and rejects a blanklogicalName(:66-71). It chainsWithSQLServerDataSource(database, logicalName),WithReference(cache),WithSelectedBroker(attachBroker),WaitFor(cache)andWaitFor(mailServer)(:73-78). The probe branch (:80-84):Mixedgets Aspire'sWithHttpHealthCheck("/alive", endpointName: probeEndpointName), where a null name leaves the endpoint choice to Aspire;Http2OnlygetsWithH2cHealthCheck("/alive", probeEndpointName ?? "http"). - Why it's built this way:
attachBrokeris the delegateAddSelectedBrokerreturns, so this helper stays broker-neutral (ADR-066). The profile is a required argument so the probe choice that ADR-012 records cannot be skipped. Host-specific additions (seeding switches, cross-service references, E2E keys) chain after the call, keeping the composite free of app knowledge (ADR-098). - Where it's used: ADC wires all four services through it, Notification as
Mixedprobing itshttpendpoint (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:137-138) and Engagement, Conference and Identity asHttp2Only(:159,:197,:222); Store wires Catalog (MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:162), Identity (:187) and Sales (:245). Covered byServiceInfrastructureExtensionsTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/ServiceInfrastructureExtensionsTests.cs). - Caveats / not-in-source: Only SQL Server is accepted as the service database (
IResourceBuilder<SqlServerDatabaseResource>,:58); a PostgreSQL service would chainWithPostgreSQLDataSourceby hand.
MmcaReplicas
MMCA.Common.Aspire.Hosting ·
MMCA.Common.Aspire.Hosting·MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/MmcaReplicas.cs:24· Level 4 · class (public static)
- What it is: The AppHost switch for running services as several replicas locally:
FromEnvironmentreads the count from an environment variable, andWithMmcaReplicasapplies it to one service. - Depends on:
Aspire.Hosting(WithReplicas) and Extensions'RateLimitingSection(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:102). - Concept introduced, rehearsing multi-replica behaviour in the inner loop.
[Rubric §12, Performance & Scalability],[Rubric §33, Developer Experience]. Bugs that appear only with more than one instance (per-instance caches, in-memory rate-limit windows, background work running twice) are invisible to a single-instance stack. This type makes "run it at three replicas" an environment variable instead of an AppHost edit, and it carries the one setting a replicated service needs to stay correct:RateLimiting__Distributed=true, because without it each replica keeps its own in-memory window and a per-user limit multiplies by the replica count (:53-57). The rate-limiting design is ADR-019. - Walkthrough:
FromEnvironment(variableName)(:33) rejects a blank name (:35), parses the variable as an invariant-culture integer (:37-41), and returns the value only when it parsed and is above 1, otherwise 1 (:43), so unset or unparsable means the single-instance stack.WithMmcaReplicas(replicas, distributedRateLimiting)(:63, in anextension(IResourceBuilder<DotnetProjectResource> service)block at:46) returns the builder unchanged for a count of 1 or less (:67-70), so it is safe to call unconditionally with theFromEnvironmentvalue; otherwise it callsWithReplicas(replicas)(:72) and, when asked, addsRateLimiting__Distributed=true(:74-76).
- Why it's built this way: The distributed switch is a parameter rather than automatic because the gateway's edge limiters stay per replica, as in production (
:57-59). - Where it's used: ADC reads
ADC_REPLICASand applies it to its four services with the distributed limiter and to the gateway without (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:450-455); Store readsSTORE_REPLICASand applies it to its three services and the gateway, all withdistributedRateLimiting: false(MMCA.Store/Source/Hosting/MMCA.Store.AppHost/Program.cs:392-396). Covered byMmcaReplicasTests(MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Hosting.Tests/Topology/MmcaReplicasTests.cs). - Caveats / not-in-source: Why Store passes
falsefor its services is not stated in the AppHost lines read here; not determinable from the source cited.
AccessTokenQueryRedactionProcessor
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Telemetry·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/AccessTokenQueryRedactionProcessor.cs:18· Level 0 · class (internal sealed)
- What it is: An OpenTelemetry span processor that replaces the value of every
access_tokenquery parameter withREDACTEDin the URL tags of a finished activity, so a bearer token a SignalR WebSocket client sends in the query string is never exported with a trace (AccessTokenQueryRedactionProcessor.cs:7-13). The request itself is untouched: the hub still authenticates from the query string. - Depends on: OpenTelemetry's
BaseProcessor<Activity>,System.Diagnostics.ActivityandSystem.Text.StringBuilder(AccessTokenQueryRedactionProcessor.cs:1-3). No first-party types. Registered by the service-defaults Extensions between its two sibling filter processors, OutboxPollFilterProcessor and ProbeTelemetryFilterProcessor. - Concept introduced, a credential in a URL is a credential in your telemetry.
[Rubric §11, Security],[Rubric §13, Observability & Operability]. SignalR WebSocket connections cannot send HTTP headers, so the client passes its JWT as anaccess_tokenquery-string parameter and the framework's JWT bearer setup reads it back from the query for hub paths (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:167-169,:196). The ASP.NET Core and HttpClient tracing instrumentations record the request URL as span tags, so without intervention the bearer would travel to Application Insights or an OTLP backend, where anyone with read access to traces could replay it until it expires. §11 is the concern: a secret must not leak into a lower-trust store. §13 is the constraint on the fix: the span is kept, with its path and every other query parameter intact, and only the token value is replaced. Like the other filter processors it does its work inOnEnd, before any batch export processor reads the activity (remarksAccessTokenQueryRedactionProcessor.cs:14-17; registration commentMMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:173-176). - Walkthrough:
- Three constants.
RedactedValue = "REDACTED"(:21,internal),AccessTokenParameterName = "access_token"(:23), andUrlTagNames = ["url.query", "url.full", "http.target", "http.url"](:26): the URL tags the tracing instrumentation of each semantic-convention version writes, currenturl.*and legacyhttp.*alike. OnEnd(Activity data)(:29) returns on a null activity rather than throwing (:31-35, under "Never throw from a telemetry callback"), then for each tag name readsGetTagItemas a string (:37-39), runs it throughRedact, and callsSetTagonly when the result is a different instance (:42-45).Redacthands back the same reference when there is nothing to change, so the common case (no token) writes nothing.Redact(string value)(:58,internal static) exits early when a case-insensitiveIndexOf("access_token")finds nothing (:60-63). Otherwise it locates the query: after the first?, or from position 0 for a bare query, becauseurl.querycarries no?in the current conventions; the query ends at a#fragment, which is preserved (:65-70). It passes that slice toRedactQueryand splices the result back between the untouched prefix and fragment (:72-76).RedactQuery(ReadOnlySpan<char> query)(:84) walks the&-separated pairs (:90-113). A pair whose name equalsaccess_tokencase-insensitively (:96) is rewritten as the name, the=, andREDACTED(:98); every other pair is copied verbatim. It returnsnullwhen no pair was rewritten (:108), which is what letsRedactreturn the original instance.
- Three constants.
- Why it's built this way: A processor sees the finished activity whichever instrumentation wrote the URL tag, so one class covers inbound server spans and outbound HttpClient spans alike, and the four-tag list covers both semantic-convention generations. It is always on with no configuration key, unlike the cost knobs around it: there is no legitimate reason to export a bearer. It does not lean on the ASP.NET Core instrumentation's own query redaction, which a host can switch off with
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION; the framework test runs with that switch both ways, so the guarantee holds even when the instrumentation's default is disabled (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Telemetry/AccessTokenQueryRedactionTests.cs:14-22,:25). Only the value is replaced and the parameter name stays, so a trace still shows that the request authenticated through the query string.internal sealed, because onlyConfigureOpenTelemetryconstructs it. - Where it's used: Registered unconditionally inside
ConfigureOpenTelemetry'sWithTracingblock astracing.AddProcessor(new Telemetry.AccessTokenQueryRedactionProcessor())(Extensions.Telemetry.cs:177), directly after OutboxPollFilterProcessor (:171), ahead of the conditional ProbeTelemetryFilterProcessor (:184) and beforebuilder.AddOpenTelemetryExporters()(:197). Every host that callsAddServiceDefaults()gets it. Covered by AccessTokenQueryRedactionTests: an end-to-end request to a hub path throughConfigureOpenTelemetry()on a test server, asserting that no exported tag contains the token while the endpoint still reads it, with the instrumentation's own redaction on and off (AccessTokenQueryRedactionTests.cs:30), and a client span carrying all four URL tags, asserting the exact rewritten values, including an upper-caseACCESS_TOKENand a preserved#frag(:80,:119-122). - Caveats / not-in-source: Only the four named tags are rewritten (
:26). A token that application code copies into another tag, a log message, or an exception message is out of reach, and so is a token sent under any parameter name other thanaccess_token. A pair with no=is copied as it is (:94-96). The rewrite happens inOnEnd, so anything that observes the activity while it is still running, or a processor registered ahead of this one, still sees the raw value.
CspNonce
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:124· Level 0 · class (static)
- What it is: The tiny public surface of the per-request Content-Security-Policy nonce: the key the nonce is stored under, and one
Get(HttpContext)accessor a page render calls to read it. - Depends on: Nothing first-party.
HttpContext(ASP.NET Core). Produced by SecurityHeadersMiddleware; the value it exposes originates from a CspPolicy that carries the{nonce}token. - Concept introduced, the CSP nonce as the supported escape from
'unsafe-inline'.[Rubric §11, Security]assesses HTTP response headers and the strength of the content policy behind them;[Rubric §26, Front-End Security]assesses how the browser-side app defends itself against injected script. A CSP that allows'unsafe-inline'for scripts allows any injected<script>in the page to execute, which is precisely the attack CSP exists to stop. The standard alternative is a nonce: the response header names one unguessable per-response token, and only the tags carrying that exact token run. The mechanics are documented on the type itself (SecurityHeaders.cs:112-123): a policy asks for a nonce by writing the literal token{nonce}as a source-list entry (for examplescript-src 'self' {nonce}), the middleware generates a fresh value for that request, replaces every occurrence with the quoted source-list form'nonce-<value>', and stashes the raw value inHttpContext.Itemsbefore the rest of the pipeline runs, because the page render is what needs to read it. A policy with no placeholder generates no nonce and stores nothing. ADR-023 records the placeholder as "the supported path off'unsafe-inline'". - Walkthrough:
public const string ItemKey = "MMCA.CspNonce"(SecurityHeaders.cs:127), theHttpContext.Itemskey under which the raw (unquoted, Base64) value lives. It is public so a caller can read the item directly, but the accessor below is the intended door.static string? Get(HttpContext context)(:120): null-guards the context (:122), thenreturn context.Items.TryGetValue(ItemKey, out var value) ? value as string : null(:123). Theas stringrather than a cast means a foreign object stored under the same key degrades tonullinstead of throwing on a response path.- A
nullreturn has two indistinguishable meanings, and the doc comment says both (:115-118): the resolved policy carried no{nonce}placeholder, or the middleware did not run at all. - The intended consumption shape is in the remarks (
:104-107): a layout injectsIHttpContextAccessorand writes<script nonce="@CspNonce.Get(Http.HttpContext!)" src="app.js">.
- Why it's built this way: A static class with a constant and one pure accessor, because there is nothing to inject and nothing to configure: the value already lives on the request. Putting the nonce in
HttpContext.Itemsrather than in a scoped service keeps the producer (middleware) and the consumer (a Razor render further down the pipeline) decoupled with no DI registration on either side, which is what makes the feature free for a host that never uses it. Storing the raw value while the header carries the quoted'nonce-<value>'form is deliberate: the two spellings differ, and a layout that stamped the quoted form onto an attribute would produce a token the browser never matches. - Where it's used: Written by SecurityHeadersMiddleware at
SecurityHeaders.cs:229, immediately before the placeholder substitution at:188. Exercised end to end by SecurityHeadersMiddlewareTests, which asserts that the stored value is the oneGetreturns (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Security/SecurityHeadersMiddlewareTests.cs:201-203), that two requests get different values (:156), that a policy without the placeholder stores nothing (:178-179), and thatGeton a context the middleware never touched returnsnull(:183-184). - Caveats / not-in-source: No host in either app emits a
{nonce}policy today. The shared BlazorCspPolicyProvider that both Blazor hosts register buildsstyle-src 'self' 'unsafe-inline'(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:103) rather than a nonce source list, and no.razorfile in the workspace referencesCspNonce. The mechanism is framework capability with test coverage, not a live production path.
CspPolicy
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:78· Level 0 · record (sealed)
- What it is: A resolved Content-Security-Policy: the directive string plus whether it is enforced or emitted report-only.
- Depends on: Nothing first-party. Returned by ICspPolicyProvider, constructed by StaticCspPolicyProvider, consumed by SecurityHeadersMiddleware.
- Concept introduced:
[Rubric §11, Security]assesses HTTP security headers (CSP, HSTS,X-Frame-Options) as defence in depth; this record is the unit a policy provider hands the middleware. CSP itself is taught at the middleware section; here the point is the enforce versus report split. The whole security-headers pipeline is governed by ADR-023 (centralized security-response-headers middleware with a pluggable CSP). - Walkthrough: The whole type is the positional record
CspPolicy(string Value, bool Enforce)(SecurityHeaders.cs:78, per-parameter doc comments at:61-63).Valueis the full directive string, for example the framework baselinedefault-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'.Enforcedecides the header name:truemakes the middleware writeContent-Security-Policy(:193),falsemakes it writeContent-Security-Policy-Report-Only(:197), which browsers report violations against without blocking anything, the standard way to trial a tightened policy without breaking the page. - Why it's built this way:
sealed recordfor immutability and structural equality. CarryingEnforceon the record rather than as a second provider method keeps the policy and its enforcement mode atomic: a provider cannot return a policy string without saying how to enforce it. ADR-023 makes this two-field shape the contract. - Where it's used: Returned by
ICspPolicyProvider.GetPolicy(SecurityHeaders.cs:89); constructed by StaticCspPolicyProvider (:89) and by the shared BlazorCspPolicyProvider; read bySecurityHeadersMiddleware.InvokeAsync(:177-199). - Caveats / not-in-source: A
nullreturn from a provider is a third state the record cannot express (emit no CSP at all); that case is handled by the nullable return type on ICspPolicyProvider, not here.
LeadingSlashPathPrefixesAttribute
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/LeadingSlashPathPrefixesAttribute.cs:13· Level 0 · class (internal sealed)
- What it is: An internal
ValidationAttributethat checks a list of request path prefixes: every non-blank entry must start with/. It is applied toSecurityHeadersSettings.CredentialPathPrefixes(SecurityHeaders.cs:47). - Depends on:
System.ComponentModel.DataAnnotations.ValidationAttribute(BCL); no first-party types. Its only consumer is SecurityHeadersSettings. - Concept introduced:
[Rubric §11, Security], with the fail-fast configuration contract of ADR-070.PathStringrefuses a non-empty value without a leading slash, so an entry such as"hubs"would otherwise throw on every request that reaches the credential-path matcher; the attribute moves that failure to host startup, once (doc commentLeadingSlashPathPrefixesAttribute.cs:5-11). - Walkthrough:
[AttributeUsage(AttributeTargets.Property)](:12) restricts it to properties.IsValid(object?, ValidationContext)(:16) null-guards the context, returnsValidationResult.Successwhen the value is not anIEnumerable<string>(:20-23), then collects the offenders: entries that are not blank and whose span does not start with'/', tested asprefix.AsSpan().StartsWith('/')(:25). No offenders is success; otherwise theValidationResultmessage reads"{MemberName} entries must start with '/': ..."and names the member (:27-31).- Blank entries are skipped on purpose, matching
SecurityHeadersMiddleware.IsCredentialPath, which also filters withIsNullOrWhiteSpace.
- Why it's built this way: A data-annotation attribute plugs into the
ValidateDataAnnotations().ValidateOnStart()call that SecurityHeadersExtensions already chains, so no bespoke validator class orIValidateOptions<T>is needed. It isinternalbecause only this settings class uses it. - Where it's used: Applied once, to
SecurityHeadersSettings.CredentialPathPrefixes(SecurityHeaders.cs:47). Source shows no usage outside the defining file and that property. - Caveats / not-in-source: Validation covers only the leading slash; it does not check that the prefix matches a real route. It runs only when options validation runs, which
AddCommonSecurityHeaderswires.
SecurityHeadersSettings
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:19· Level 0 · class (sealed)
- What it is: Strongly-typed configuration for SecurityHeadersMiddleware, centralising the security-header values each client-facing host previously hand-rolled, plus the credential-path list that earns extra
Referrer-Policyand cache-control treatment. - Depends on: Nothing first-party. Consumed through
IOptions<SecurityHeadersSettings>by StaticCspPolicyProvider and SecurityHeadersMiddleware. - Concept introduced:
[Rubric §11, Security]assesses hardened HTTP response headers, and[Rubric §34, Architecture Governance & Documentation]assesses whether such a decision is written down once instead of re-derived per host. Previously each host setX-Frame-Options,Referrer-Policy,Permissions-Policy, HSTS, and CSP independently, inviting drift; pulling them into one shared settings class with hardened defaults means a new host inherits the safe values automatically, with per-host overrides through the"SecurityHeaders"configuration section or aconfiguredelegate. - Walkthrough:
SectionName = "SecurityHeaders"(SecurityHeaders.cs:22), the configuration section the registration binds.- The defaults are the interesting part:
FrameOptions = "DENY"(:25, anti-clickjacking, no framing at all);ReferrerPolicy = "strict-origin-when-cross-origin"(:28, leaks no path cross-origin);PermissionsPolicydenying geolocation, microphone, camera, and payment (:31);EnableHsts = true(:34) withHstsValue = "max-age=31536000; includeSubDomains"(:51, one year including subdomains). CredentialPathPrefixes(:48) is anIList<string>(get-only, mutable collection) defaulting to["/reset-password", "/auth/oauth-complete"], annotated[LeadingSlashPathPrefixes](:47) so LeadingSlashPathPrefixesAttribute rejects any entry without a leading/at startup. The doc comment (:36-46) states the SECURITY reasoning: these are the pages a credential arrives on, so a reset or OAuth-completion URL a user opens must not carry the token onward in aRefererheader to whatever the page loads next, and must not sit in a browser's or proxy's cache after the token has been spent. Matching is segment-based and case-insensitive, applied by SecurityHeadersMiddleware'sIsCredentialPath; the same comment (:43-44) states that a bad entry fails options validation at startup instead of failing every request.ContentSecurityPolicy(:67-69) defaults to a complete hardened baseline:default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'. The doc comment (:53-66) explains the calibration:script-srcandstyle-srcship at exactly the strength Blazor ('wasm-unsafe-eval') and MudBlazor ('unsafe-inline'styles) require, so an HTML host that never registers a provider still gets a functional policy instead of one silently missing both directives, while the JSON, WebSocket, and static responses of API and Gateway hosts are unaffected. Setting the property tonullor empty emits no CSP at all, and the{nonce}placeholder (see CspNonce) is named there as the supported path off'unsafe-inline'.EnforceContentSecurityPolicy = true(:72); set itfalseand the middleware emits the same policy report-only.
- Why it's built this way: Sealed and mutable (
get; set;, notinit-only) so theconfiguredelegate andIOptionsbinding can adjust the defaults before the middleware starts.CredentialPathPrefixesis exposed as a get-onlyIList<string>rather than a settable property, so a host augments the default list in place (.Add(...)) instead of replacing it outright. The complete-baseline default is codified in ADR-023, whose Status block records the 2026-09-01 revision that replaced the earlier deliberately-incomplete baseline (which omittedscript-srcandstyle-srcto avoid breaking a Blazor host) with one that ships both directives at Blazor and MudBlazor strength. The trade-off moved from "safe but partial" to "functional and still hardened", and the property's own doc comment carries the reasoning rather than leaving it only in the ADR. - Where it's used: Bound and registered by SecurityHeadersExtensions
.AddCommonSecurityHeaders(SecurityHeaders.cs:276-281, which also runsValidateDataAnnotations().ValidateOnStart()at:277so the[LeadingSlashPathPrefixes]check fires at host start); read by StaticCspPolicyProvider (:86-89) and SecurityHeadersMiddleware, whoseIsCredentialPathhelper readsCredentialPathPrefixeson every request to decide theReferrer-Policyand cache-control headers. Both apps' UI hosts reach it through the sharedAddMmcaBlazorWebHost(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:30), which callsAddCommonSecurityHeaders(configuration)with noconfiguredelegate (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:157), so they keep the defaults (EnableHstsistrue,SecurityHeaders.cs:34), as both Gateways do (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:135,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:71). - Caveats / not-in-source:
X-Content-Type-Optionshas no setting; the middleware hard-codesnosniff, so it is the one header a host cannot weaken through configuration. Matching againstCredentialPathPrefixesis segment-based (StartsWithSegments), so/reset-passwordcovers/reset-password/anythingbut never/reset-passwords; the only validation is the leading-slash check (:47), and source shows nothing confirming that a configured prefix actually corresponds to a route either app declares.
KestrelListenerSpec
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Kestrel·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Kestrel/KestrelEndpointExtensions.cs:132· Level 0 · record (sealed, internal, nested)
- What it is: One explicit Kestrel listener expressed as data: a port and the protocols accepted on it. It is the intermediate value that lets the listener decision be computed and tested without ever binding a socket.
- Depends on:
HttpProtocols(Microsoft.AspNetCore.Server.Kestrel.Core). Produced by KestrelEndpointExtensions.BuildListenerPlanand consumed by itsConfigureEndpointsWithHealthProbe. - Concept introduced, a pure plan object as a testability lever.
[Rubric §14, Testability]assesses whether behavior can be verified without standing up infrastructure;[Rubric §15, Best Practices & Code Quality]covers the small-value-type habit that makes it possible.ConfigureKestrelis a callback that only runs when the host boots, andListenAnyIPbinds a real socket, so the logic of "which listeners does this configuration imply" would normally be unreachable from a test. Extracting that logic into a function returningIReadOnlyList<KestrelListenerSpec>turns the decision into a value you can assert on, which is exactly what KestrelEndpointExtensionsTests does across its cases. - Walkthrough: The entire type is
internal sealed record KestrelListenerSpec(int Port, HttpProtocols Protocols)(KestrelEndpointExtensions.cs:132), a positional record nested insideKestrelEndpointExtensions, with per-parameter doc comments at:129-131.Portis the port to listen on;Protocolsis the protocol set that port accepts (Http1,Http2, orHttp1AndHttp2). - Why it's built this way: A record, so structural equality makes a test assertion read as a plain comparison of expected listeners.
internaland nested, because it is an implementation detail of one extension class and no part of any public contract; the assembly's<InternalsVisibleTo Include="MMCA.Common.Aspire.Tests" />(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/MMCA.Common.Aspire.csproj:13) is what keeps it reachable from the tests without widening the public surface. Modelling a listener as a pair rather than callingListenAnyIPinline is the whole reason the surprising parts of the wiring (re-declaring the cleartext endpoint, forcing the probe listener toHttp1) are verifiable at all. - Where it's used: Returned in declaration order by
BuildListenerPlan(KestrelEndpointExtensions.cs:113-127) and looped over insideConfigureKestrelat:94-97, where each spec becomes onekestrel.ListenAnyIP(listener.Port, endpoint => endpoint.Protocols = listener.Protocols)call.
SerilogHostExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Logging·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Logging/SerilogHostExtensions.cs:38· Level 0 · class (static)
- What it is: The framework's Serilog bootstrap, packaged as one call that the two composed hosts run before
AddServiceDefaults(): console sink always, a rolling daily file sink outside Production, the framework's minimum-level overrides, removal of the default console provider (and only that provider), and registration of Serilog as one logging provider beside the others. - Depends on: Nothing first-party. Serilog (
LoggerConfiguration,Log.Logger,RollingInterval,LogEventLevel),Serilog.Extensions.Logging(builder.Logging.AddSerilog),Microsoft.Extensions.Logging.Console(ConsoleLoggerProvider),Microsoft.Extensions.DependencyInjection(IServiceCollection), andMicrosoft.Extensions.Hosting/Microsoft.AspNetCore.Builder(IHostEnvironment,WebApplicationBuilder). Called before AddServiceDefaults, whose OpenTelemetry provider joins the same factory. - Concept introduced, additive logging providers versus provider replacement.
[Rubric §13, Observability & Operability]assesses whether application logs actually reach the place operators query, and this class exists because of a specific way that fails.[Rubric §13, Observability & Operability]and[Rubric §15, Best Practices & Code Quality]cover the collapse of per-host bootstraps into one. The load-bearing fact is in the class doc comment (SerilogHostExtensions.cs:18-22):UseSerilog()replaces the wholeILoggerFactoryand therefore silently bypasses every other provider, including the OpenTelemetry-to-Azure-Monitor one wired byAddAzureMonitorExporter()(MMCA.Common.Azure). A host that calls it publishes no application log line to Application Insights at all, and nothing fails: the symptom is absence, in a place nobody watches for absence.builder.Logging.AddSerilog(...)adds Serilog alongside the others, which is why this helper does that and never the former. The same comment (:25-31) names the one exception: the defaultConsoleLoggerProviderthatWebApplication.CreateBuilderregisters is removed, because the Serilog console sink already writes every event to stdout, so keeping both writes each line twice and a container platform ships and bills both copies (the comment records a measured 64 percent of console volume from the duplicate).ClearProviders()is never called, since it would also drop the OpenTelemetry provider and any vendor adapter's. ADR-041 records the decision and its costs. - Walkthrough, in teaching order.
- The one public entry point.
AddCommonSerilog(logFilePath, configure = null)(:59, inside anextension(WebApplicationBuilder builder)block at:40) null-guards the builder (:63), assignsLog.Logger = CreateLoggerConfiguration(builder.Environment, logFilePath, configure).CreateLogger()(:65), strips the default console provider withRemoveDefaultConsoleProvider(builder.Services)(:66), registers Serilog withbuilder.Logging.AddSerilog(Log.Logger, dispose: true)(:67), and returns the builder (:69). The globalLog.Loggeris published (which is what the bootstrap factory below then reads) and the same instance is added as one provider on the host's existing factory.dispose: truehands the provider ownership of the logger so buffered events flush on shutdown. The doc comment (:43-46) states the ordering rule: call it beforeAddServiceDefaults(), as the hosts do, so the OpenTelemetry provider registered there joins the same factory. CreateBootstrapLoggerFactory()(:79-80, public static):LoggerFactory.Create(logging => logging.AddSerilog()), a factory writing to the current globalLog.Logger. It exists for the startup-time diagnostics a host needs before the DI container is built, module discovery above all (the framework's own module host names it in its doc comment,MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:39). The doc comment (:73-77) is explicit that the caller disposes it once startup wiring is done and that it does not ownLog.Logger, which is why disposing it does not silence the host.RemoveDefaultConsoleProvider(services)(:88, internal static) walks the service collection backwards (:90) and removes a descriptor only when all three hold: its service type isILoggerProvider, it is not keyed, and its implementation type is exactlyConsoleLoggerProvider(:93-97). Everything else stays registered, so the OpenTelemetry provider and any adapter-registered provider survive the call (doc comment:82-86).ResolveMinimumLevel(environment)(:108-109, internal static):Debugin Development,Informationeverywhere else. One expression, extracted so the policy can be asserted rather than inferred.ShouldWriteFileSink(environment)(:119-120, internal static):!environment.IsProduction(). The doc comment (:111-115) gives the reasoning, and it is a genuine operational judgement rather than a preference: a Production container writes to ephemeral disk nothing reads, and stdout plus OpenTelemetry already carry production logs, so the file sink is added everywhere except Production, which is local development and the CI E2E stack, where the file is what a failure gets diagnosed from.CreateLoggerConfiguration(environment, logFilePath, configure)(:130, internal static) is where the defaults actually live. It guards both inputs, includingArgumentException.ThrowIfNullOrWhiteSpace(logFilePath)(:135-136), then buildsMinimumLevel.Is(ResolveMinimumLevel(environment))with two noise overrides,Microsoft.EntityFrameworkCoreandMicrosoft.AspNetCoreboth floored atWarning(:139-141), andWriteTo.Console(formatProvider: CultureInfo.InvariantCulture)(:142). WhenShouldWriteFileSinksays so it addsWriteTo.File(logFilePath, rollingInterval: RollingInterval.Day, ...)(:144-150). Only then does it invoke the optionalconfigurehook (:152) and return the uncreated configuration (:154).- The ordering in that last method is the testability lever: the hook runs after the defaults, so a host can add a sink or override a level, and the method stops short of
CreateLogger(), so the shape can be asserted without publishing a global logger.[Rubric §14, Testability]shows up exactly there, and SerilogHostExtensionsTests drives all four internal helpers plus the public call.
- The one public entry point.
- Why it's built this way: A static class with one
extension(WebApplicationBuilder)block, the codebase's standard registration idiom (see primer, C#extension(T)types), which is also why it carries the scopedCA1708suppression with the false-positive justification spelled out (:34-37). Two invariants matter and both are guarded by framework tests: exactly one Serilog provider, never a factory replacement (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Logging/SerilogHostExtensionsTests.cs:141), and the registered provider set after the call equals theCreateBuilderdefaults minusConsoleLoggerProviderplus Serilog, nothing more and nothing less (SerilogHostExtensionsTests.cs:176), with a direct test that the removal helper leaves every other provider registration in place (:209). ADR-041 flags the first as guarded in the framework rather than at the consumer: nothing in a host's own build stops a new service from reaching forUseSerilog(). - Where it's used: Through the two composed hosts rather than in any consumer
Program.cs.AddMmcaServiceHostcallsAddCommonSerilog(options.LogFilePath)beforeAddServiceDefaults()(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:84-85) and later creates the bootstrap factory forModuleLoader(:101-104);AddMmcaBlazorWebHostmakes the same first call for the Blazor Web heads (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:84-85). The consumers reach it through those calls: the four ADC service hosts (for exampleMMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88), the three Store service hosts (for exampleMMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:32), and both UI.Web heads (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:30), each supplying onlyLogFilePath. - Caveats / not-in-source: Neither Gateway references Serilog: they take the plain OpenTelemetry logging that
AddServiceDefaultsgives them. The helper also attaches only toWebApplicationBuilder, not to the genericIHostApplicationBuilderthatAddServiceDefaultsuses, so a non-web worker host cannot call it. The console-provider removal matches on the exactConsoleLoggerProviderimplementation type of a non-keyed registration (:93-97), so a console provider registered by factory or as a keyed service is not removed.
OutboxPollFilterProcessor
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Telemetry·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/OutboxPollFilterProcessor.cs:17· Level 0 · class (sealed)
- What it is: An OpenTelemetry span processor that marks the two families of background-poll spans, and everything nested under them, as not-recorded so the exporters drop them: the outbox's poll and the internal-commands queue's poll (
OutboxPollFilterProcessor.cs:6-16). It is the framework's answer to a fleet that polls its outbox and internal-command tables around the clock and would otherwise pay to ingest telemetry about doing nothing. - Depends on: OpenTelemetry's
BaseProcessor<Activity>andSystem.Diagnostics.Activity/ActivityTraceFlags(OutboxPollFilterProcessor.cs:1-2). No first-party types, on purpose (see the walkthrough). Conceptually it is paired with OutboxProcessor andInternalCommandProcessor(ADR-114), whose spans it filters, and it is registered by the service-defaults Extensions. - Concept introduced, suppressing a span without breaking the trace.
[Rubric §13, Observability & Operability],[Rubric §31, Cost & FinOps]. OpenTelemetry gives everyActivityaRecordedflag, and the SDK's batch export processors skip anything unrecorded. Clearing that flag in an earlier processor'sOnEndis therefore how you drop a span from export without interfering with its creation, its timing, or its parent-child links, which is what you want when the span is real work that simply is not worth paying to store. §31 is the category that makes this necessary rather than nice: the OutboxProcessor polls every relational outbox on a recurring cycle, and the internal-commands processor polls every internal-command queue table the same way, and in a deployed environment the Azure Monitor distro's automatic instrumentation adds aSqlClientdependency span for each of those queries. Idle polls would dominate Application Insights and Log Analytics ingestion and spam the local Aspire dashboard, for zero diagnostic value. §13 is the constraint on the fix: filtering must not blind you to real work, and it does not, because per-messageOutboxProcessspans and per-commandInternalCommandExecutespans are started with an explicit parent context restored from the trace and span ids stored on the message (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:1286-1295, and the sameActivityContextshape atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:788) and so are never descendants of a poll span. ADR-041 records the policy this implements: instrument where auto-instrumentation is blind, then add cost knobs whose defaults never go dark; ADR-114 is what added the second poll family this processor now shares that policy with. - Walkthrough:
- Four
private const stringfields:OutboxActivitySourceName = "MMCA.Common.Outbox",PollActivityName = "OutboxPoll",InternalCommandsActivitySourceName = "MMCA.Common.InternalCommands",InternalCommandsPollActivityName = "InternalCommandPoll"(:28-31). They are duplicated literals, not references to the Infrastructure constants, and the comment above them (:19-27) is the design rationale:MMCA.Common.Aspiredoes not referenceMMCA.Common.Infrastructure, soAddServiceDefaults()stays usable from a host that never takes the persistence stack (EF Core, the broker transports, SignalR/Redis). Its one project reference isMMCA.Common.Shared, for HttpResilienceDefaults. The two source names also appear in theFrameworkActivitySourceNameslist (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:87-93), whichConfigureOpenTelemetrysubscribes in one.AddSource([.. FrameworkActivitySourceNames])call (Extensions.Telemetry.cs:133). The counterparts they must stay in sync with areOutboxProcessor.PollActivityName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:78) and its activity source, plusInternalCommandMetrics.MeterNameandInternalCommandProcessor.PollActivityName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:58) on the queue side. The comment (:24-27) names the test that holds them together (see Caveats). OnEnd(Activity data)(:34) is the single override. It opens with a null check that returns instead of throwing (:36-40), under the comment "Never throw from a telemetry callback": an exception escaping an SDK callback is an observability feature taking the process down.- The match is a loop up the in-process parent chain,
for (var current = data; current is not null; current = current.Parent)(:44). Walking rather than checking only the immediate parent is what catches grandchildren: theSqlClientspan the Azure Monitor distro creates can sit more than one level below the poll. - The predicate is factored out into
IsSuppressedPoll(Activity)(:57-66), which matches either poll family:OperationName == PollActivityName && Source.Name == OutboxActivitySourceName, orOperationName == InternalCommandsPollActivityName && Source.Name == InternalCommandsActivitySourceName. Matching on both operation name and source name (not name alone) is what guards against a consumer span that happens to share a poll's name from a different source (:42-43). - On a match it clears the flag with
data.ActivityTraceFlags &= ~ActivityTraceFlags.Recordedand returns (:51-52). The comment (:48-50) states the ordering contract that makes it work: the batch export processors skip an unrecorded activity, and this processor is registered before the exporters so itsOnEndruns first.
- Four
- Why it's built this way: Sealed, stateless, and registered as a single instance. The literal duplication is a deliberate, commented trade of a small sync obligation against an assembly dependency that would force every service-defaults consumer to take the persistence stack, and the obligation is discharged by an architecture test rather than by review. Clearing
Recordedrather than declining to start the activity keeps the poll span available to a local debugger and to any processor registered before this one, and keeps the parent chain intact for the spans that are exported. ExtractingIsSuppressedPollrather than inlining a secondifinside the loop is what let the internal-commands family join without touching the walk or the null-guard:OnEndstill reads as one loop over one predicate. Returning on a null activity rather than asserting follows the rule the rest of the telemetry code obeys: a cost knob must never be able to fail the request path. ADR-041 documents this as one of three cost levers whose defaults fail safe, alongside head-based sampling and the two metric kill switches. - Where it's used: Registered once, inside
ConfigureOpenTelemetry'sWithTracingblock (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:130), astracing.AddProcessor(new Telemetry.OutboxPollFilterProcessor())(Extensions.Telemetry.cs:171), after the framework sources are subscribed (:133), immediately ahead of AccessTokenQueryRedactionProcessor (:177), and beforebuilder.AddOpenTelemetryExporters()(:197). Every host that callsAddServiceDefaults()gets it, with no opt-in and no configuration key. The outbox spans it targets are opened in three places, eachusing var pollActivity = OutboxActivitySource.StartActivity(PollActivityName): the saturated-batch backlogCOUNT(OutboxProcessor.cs:311), the candidate fetch (OutboxProcessor.cs:337), and the unblocked-candidate fetch (OutboxProcessor.cs:357). The internal-commands spans come from the queue side's own polls,InternalCommandActivitySource.StartActivity(PollActivityName)atInternalCommandProcessor.cs:231and:272. Covered by OutboxPollFilterProcessorTests, which drives a realActivityListenerand asserts each behaviour: the poll span itself is unrecorded (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Telemetry/OutboxPollFilterProcessorTests.cs:32), a child is (:43), a grandchild is (:57), an unrelated root and a same-name span from a different source stay recorded (:70,:81), a realOutboxProcessspan stays recorded (:93), and a null activity does not throw (:105). - Caveats / not-in-source: The walk is over
Activity.Parent, which is the in-process chain only. A span whose parent exists only as a propagated remote context is not matched, so the suppression covers exactly what the poll starts inside the same process, which is what theSqlClientchild is. Suppression is unconditional: there is no configuration key to keep poll spans for a debugging session, so diagnosing either poll path means reading the outbox or internal-commands meters, or temporarily removing the processor. The four duplicated literals are not checked by the compiler; they are checked byThePollFilter_NamesTheSourcesAndOperationsTheProcessorsUsein FrameworkActivitySourceExportTests (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/Telemetry/FrameworkActivitySourceExportTests.cs:52), which reads each private constant by reflection and asserts it equals its owner: the outbox activity source name andOutboxProcessor.PollActivityName,InternalCommandMetrics.MeterName, andInternalCommandProcessor.PollActivityName(FrameworkActivitySourceExportTests.cs:59-66). A rename on either side therefore fails a test rather than silently letting the polls through to the exporters.
ICspPolicyProvider
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:86· Level 1 · interface
- What it is: The contract for resolving the Content-Security-Policy for a response. The framework ships a static default; a host that needs a dynamic policy registers its own implementation.
- Depends on: CspPolicy (return type);
HttpContext(ASP.NET Core). - Concept introduced, the CSP extension point.
[Rubric §11, Security](CSP as defence in depth) and[Rubric §26, Front-End Security](CSP protecting Blazor pages from injected script). The doc comment (SecurityHeaders.cs:80-85) states the extensibility rule: a Blazor host needing a dynamicconnect-src, for example one pinned at runtime to its API origin, registers a customICspPolicyProviderbefore callingAddCommonSecurityHeaders, because that method registers the default only viaTryAddSingleton(:237), so a pre-registered custom provider wins. - Walkthrough: A single method,
CspPolicy? GetPolicy(HttpContext context)(SecurityHeaders.cs:89): returns the policy to emit for the current response, ornullto emit none. Taking theHttpContextmakes it per-request, so a provider can vary the policy by path or request properties.[Rubric §1, SOLID]is the shape: one method, one reason to change, and the middleware depends on this abstraction rather than on any concrete policy source. - Why it's built this way: A one-method interface is the minimal extension point for a per-consumer CSP allow-list; returning the CspPolicy record rather than a bare string carries the enforce-or-report decision atomically. ADR-023 explains why the indirection exists at all: a JSON/Gateway host and a Blazor/MudBlazor host need different policies (the latter must pin
connect-srcto an origin it only learns at runtime from configuration), and a wrong CSP hard-breaks the app, so the policy must be resolved through a provider rather than baked in as a constant. - Where it's used: Implemented by the default StaticCspPolicyProvider (
SecurityHeaders.cs:93) and by the shared BlazorCspPolicyProvider inMMCA.Common.UI.Web, which both apps' Blazor hosts register throughAddCommonBlazorCsp(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:66) ahead ofAddCommonSecurityHeaders, both called inside the sharedAddMmcaBlazorWebHost(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:156-157) that each UI host invokes (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:30). Resolved per request inside SecurityHeadersMiddleware (SecurityHeaders.cs:219).
KestrelEndpointExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Kestrel·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Kestrel/KestrelEndpointExtensions.cs:24· Level 1 · class (static)
- What it is: One call,
ConfigureEndpointsWithHealthProbe(...), that applies a protocol profile to every Kestrel endpoint default and, when a probe port is configured, adds a dedicated HTTP/1.1-only listener so the platform'shttpGethealth probes have something they can actually speak to. - Depends on: KestrelListenerSpec (the plan it computes);
WebApplicationBuilder,HttpProtocols,IConfiguration(ASP.NET Core and BCL). Pairs with the health endpoints mapped by the Common.AspireExtensionsMapDefaultEndpoints(). - Concept introduced, the protocol mismatch between gRPC hosts and platform probes.
[Rubric §7, Microservices Readiness],[Rubric §13, Observability & Operability],[Rubric §17, DevOps],[Rubric §29, Resilience & Business Continuity]. The class doc comment (KestrelEndpointExtensions.cs:8-23) states the two facts that force the design. First, a service serving inbound gRPC on cleartext must answer HTTP/2 with prior knowledge (h2c): there is no TLS, therefore no ALPN to negotiate with, and the typed gRPC clients fromMMCA.Common.Grpcspeak h2c directly. Second, Azure Container AppshttpGetprobes speak HTTP/1.1, which an Http2-only endpoint rejects with GOAWAYHTTP_1_1_REQUIRED. The consequence is the operational point worth internalising: that mismatch is why those probes used to be TCP-only and never consulted the real, dependency-aware health checks, meaning the platform could not tell a live socket from a service whose database was gone. A separateHttp1-only listener on a port never published through ingress gives the platform a probe target, and becauseMapDefaultEndpoints()maps/health,/alive, and/health/readyon every listener, that probe listener serves the real health pipeline. ADR-012 (gRPC host transport) is the governing decision. - Walkthrough:
- Two public constants.
HealthProbePortConfigKey = "HealthProbe:Port"(:31), which deployment infrastructure injects asHealthProbe__Portand which the doc comment (:26-30) says is deliberately absent locally so Aspire's dynamic ports keep working and co-hosted services cannot collide on one machine.DefaultCleartextPort = 8080(:37), the platform's own default binding. ConfigureEndpointsWithHealthProbe(defaultProtocols, redeclareCleartextEndpoint = true, cleartextPort = DefaultCleartextPort)(:77, inside anextension(WebApplicationBuilder builder)block at:39): null-guards the builder (:82), computes the listener plan up front (:84-88), then insidebuilder.WebHost.ConfigureKestrel(:90) setskestrel.ConfigureEndpointDefaults(endpoint => endpoint.Protocols = defaultProtocols)(:92) and declares each planned listener withkestrel.ListenAnyIP(...)(:94-97).- The two deployed profiles are the same call with different arguments, and the doc comment (
:48-60) spells both out. A REST/gRPC service passesHttpProtocols.Http2and keepsredeclareCleartextEndpointat its default, because an explicitListencall overrides the container'sASPNETCORE_HTTP_PORTSdefault binding, so the main h2c endpoint has to be re-declared next to the probe port or it silently disappears. A host whose endpoints come from configuration (for example a SignalR host running anHttp1AndHttp2endpoint for the WebSocket upgrade handshake plus an Http2-only gRPC endpoint, both fromappsettings.json) passesHttpProtocols.Http1AndHttp2andredeclareCleartextEndpoint: false, so the probe listener is strictly additive and nothing re-binds a port the configuration already owns. BuildListenerPlan(configuration, defaultProtocols, redeclareCleartextEndpoint, cleartextPort)(:113,internal static) is the pure decision function and the only place the branching lives.configuration.GetValue<int?>(HealthProbePortConfigKey) is not int probePortreturns an empty plan (:119-122), which is the local and test case: endpoint defaults alone, Aspire's dynamic ports intact. Otherwise it returns either two specs ([new KestrelListenerSpec(cleartextPort, defaultProtocols), new KestrelListenerSpec(probePort, HttpProtocols.Http1)]) or just the probe spec, depending onredeclareCleartextEndpoint(:124-126). The probe listener is alwaysHttpProtocols.Http1, whatever the defaults are, which is the entire point.- Failure behavior is deliberate and documented on the method (
:72-76): a probe port that is not an integer makesGetValue<int?>throwInvalidOperationExceptionat startup, because a mistyped probe port that silently produced no listener would leave the platform probing a closed port and the revision would never come up. A blank value, by contrast, is treated as absent.
- Two public constants.
- Why it's built this way: The decision is separated from the binding so it can be asserted as data (see KestrelListenerSpec). The probe port is configuration-gated rather than always-on so local and test runs keep Aspire's dynamic ports. Failing fast rather than failing quiet follows the same contract as ADR-070: a misconfiguration whose only symptom is a silently unprobeable revision is worth a startup crash. And the helper lives in the shared framework package rather than in each service, which is what let seven service hosts across two apps collapse onto one implementation.
- Where it's used: All four ADC services, three on the h2c profile (
MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:83,MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:94,MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:71) and Notification on the mixed profile (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:73, passingHttpProtocols.Http1AndHttp2, redeclareCleartextEndpoint: false); plus all three Store services, two on h2c (MMCA.Store/Source/Services/MMCA.Store.Identity.Service/Program.cs:64,MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:58) and Sales on the mixed profile (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:75). Covered by KestrelEndpointExtensionsTests, whose cases pin the empty-plan, blank-value, fail-fast, both-profile, always-Http1, and custom-cleartext-port behaviors. - Caveats / not-in-source: The probe port is supplied per app by the Container Apps Bicep rather than by anything in application code, so a host whose deployment omits
HealthProbe__Portsimply gets the empty plan and answers probes on its configured endpoints. Source does not state why the two mixed-profile hosts (ADC Notification and Store Sales) are the ones configured fromappsettings.json.
ProbeTelemetryFilter
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Telemetry·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/ProbeTelemetryFilter.cs:27· Level 9 · class (internal static)
- What it is: The two predicates the OpenTelemetry instrumentations call to decide whether a request is worth tracing.
ShouldCollectRequestrefuses an inbound health-probe request and leaves a marker tag behind on the way out;ShouldCollectOutgoingrefuses an outbound call to a probe endpoint. Together they are the front half of theTelemetry:FilterProbeTelemetrycost knob, the back half being ProbeTelemetryFilterProcessor. - Depends on: HealthEndpointPaths, which owns the one definition of what counts as a probe path (
ProbeTelemetryFilter.cs:40,:61). Externals:System.Diagnostics.Activity/ActivityKindandMicrosoft.AspNetCore.Http.HttpContext(:1-2), plusHttpRequestMessagefor the outbound predicate. Wired into the instrumentation options by the service-defaults Extensions; the marker constant it publishes is read by ProbeTelemetryFilterProcessor. - Concept introduced, filtering at the instrumentation rather than at the exporter.
[Rubric §31, Cost & FinOps],[Rubric §13, Observability & Operability]. OutboxPollFilterProcessor taught the exporter-side move: let the span exist, then clear itsRecordedflag so the batch exporters skip it. OpenTelemetry offers an earlier lever as well. Both the ASP.NET Core and the HttpClient instrumentations expose a predicate (Filter,FilterHttpRequestMessage) consulted at request start, and returningfalsestops the instrumentation from collecting the span at all: no attributes are written, no enrichment runs. §31 is why it is worth reaching for. Health probes are pure infrastructure chatter (Container Apps liveness and readiness probes, the gateway's downstream aggregate probes, YARP active health checks and the availability web test), and the class doc records that together they accounted for everyAppRequestsrow in both production workspaces (:6-12). They are also invisible to the sampling knob: head-based sampling keeps a proportion of everything, so aTracesSampleRatioof 0.1 keeps a tenth of the probe noise too. §13 is the constraint on the fix, and it shows up as a deliberate scope limit: the filter touches traces only. Metrics are untouched, sohttp.server.request.duration, Kestrel and routing instruments keep reporting probe traffic and a dashboard does not go dark (ProbeTelemetryFilterProcessor.cs:16-18). - Walkthrough:
ProbeMarkerTagName = "mmca.probe"(:33) is the tag stamped on a refused probe request activity. Its doc states that it is never exported (:28-32), which is true by construction: the same pass that stamps it is the pass that refuses the span.ShouldCollectRequest(HttpContext context)(:40) returnstrue(collect) for a null context or any non-probe path, delegating the path test toHealthEndpointPaths.IsProbePath(context.Request.Path.Value)(:42-45). Only when the path is a probe does it continue.- Before returning
falseit stamps the marker onActivity.Current, guarded by a pattern match onKind: ActivityKind.Server(:49-52). The comment above it (:47-48) is the ordering fact that makes this legal: the instrumentation invokes the filter from its start callback, after ASP.NET Core has already started the request activity and made it current, soActivity.Currenthere is the request span. - Why stamp at all, when the span is about to be dropped? Because refusing the request means the instrumentation returns before it writes
url.path, so the probe's descendants (the health check's SQLSELECT 1, the Redis PING) would have no evidence left on their ancestor to recognize. The marker is the evidence the processor matches on (:13-19). ShouldCollectOutgoing(HttpRequestMessage request)(:62) is a single expression: collect unless the request has a URI whose path is a probe path (:63). A request with noRequestUriis collected, so the predicate never suppresses something it cannot classify.PathOf(Uri uri)(:72) extracts that path. An absolute URI yieldsAbsolutePathdirectly (:74-77); a relative one (legal on a client with aBaseAddress) is trimmed at the first?or#over a span (:79-81). The doc gives the reason for handling both shapes inline (:65-67): service discovery hands the client an absolute URI, but combining a relative one into a newUriwould allocate on every outbound call.
- Why it's built this way: The split between the two predicates is not symmetry for its own sake, it follows the two ways probe traffic arrives.
ShouldCollectRequesthandles probes received, whose children are handled downstream by the processor.ShouldCollectOutgoinghandles probes sent from a background timer, which are never descendants of any inbound request and so would never reach the processor at all: the gateway's DownstreamServiceHealthCheck calls to each backend's/alive, and YARP's active health checks (:20-25). Both filters are attached to the default-named instrumentation options (Extensions.Telemetry.cs:153-156), which is what makes them authoritative over the instrumentation the Azure Monitor distro adds as well, unlike the metric toggles that need a View. The type isinternal static: it is a predicate pair, not an extension point, and the assembly exports the processor rather than the filter. ADR-041 is the policy this implements, cost knobs whose defaults never go dark, which here means traces filtered by default while metrics keep flowing. - Where it's used: Assigned to both instrumentation options inside
ConfigureOpenTelemetry'sWithTracingblock, but only on the enabled branch:options.Filter = Telemetry.ProbeTelemetryFilter.ShouldCollectRequestandoptions.FilterHttpRequestMessage = Telemetry.ProbeTelemetryFilter.ShouldCollectOutgoing(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:153-156). Theelsebranch registers the same two instrumentations with no filter (Extensions.Telemetry.cs:158-162), so turning the knob off costs nothing but the filtering. The knob itself isTelemetry:FilterProbeTelemetry(Extensions.Telemetry.cs:18), read byIsProbeTelemetryFilterEnabled(Extensions.Telemetry.cs:283-284). Covered by ProbeTelemetryFilterTests, which pins each behaviour: probe paths are not collected (ProbeTelemetryFilterTests.cs:57), normal paths are (:66), a null context is (:70), a probe request marks the current server activity (:75) and a normal one does not (:91), outbound probe calls are refused on absolute (:110) and relative (:117) URIs, a normal outbound call is collected (:126) and one without a URI is (:131). The same class also pins the knob's default-on parsing (:30,:38,:46). - Caveats / not-in-source: The marker is stamped on
Activity.Currentonly, so if some future instrumentation invoked the predicate outside the request activity's scope the marker would be lost and the processor would fall back to its tag and display-name matching. What counts as a probe is entirely HealthEndpointPaths' definition:/alive,/healthand anything under/health/(HealthEndpointPaths.cs:29-33), so a host that maps a probe on a bespoke path is not filtered. The production-volume claims in the class doc (:6-12) are the recorded observation behind the knob and are not verifiable from source.
SecurityHeadersMiddleware
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:147· Level 2 · class (sealed)
- What it is: ASP.NET Core middleware that adds hardened security response headers to every response:
X-Content-Type-Options: nosniff,X-Frame-Options,Referrer-Policy,Permissions-Policy, HSTS (outside Development), a CSP resolved from ICspPolicyProvider including per-request nonce substitution, and, on the credential paths named by SecurityHeadersSettings, a tightenedReferrer-Policyplus no-cache headers. - Depends on: SecurityHeadersSettings, ICspPolicyProvider, CspPolicy, CspNonce;
RequestDelegate,IWebHostEnvironment,IOptions<T>(ASP.NET Core),PathString/StringComparison(BCL), andRandomNumberGenerator(System.Security.Cryptography). - Concept introduced, centralized security headers as shared middleware.
[Rubric §11, Security](X-Frame-Options, CSP, HSTS,Referrer-Policy,Permissions-Policy, all defence in depth),[Rubric §17, DevOps & Deployment](the doc comment atSecurityHeaders.cs:144-145states it centralizes what each client-facing host previously hand-rolled),[Rubric §26, Front-End Security](CSP restricting content sources, reducing the impact of injected script on Blazor pages). - Concept introduced, hardening the pages a credential travels through.
[Rubric §11, Security].IsCredentialPath(:179-182) checks the current request path against every non-blank entry inSecurityHeadersSettings.CredentialPathPrefixes(string.IsNullOrWhiteSpacefilter,:181) withpath.StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase), segment-based so/reset-passwordmatches/reset-password/anythingbut never/reset-passwords. On a match,InvokeAsyncwritesReferrer-Policy: no-referrerinstead of the configured default (:192-194) and appliesCache-Control: no-store, no-cache, must-revalidate, max-age=0(theCredentialCacheControlconstant,:156) plusPragma: no-cachethroughApplyCredentialCacheHeaders(:199,:246-250). It also registers aResponse.OnStartingcallback (:205-211) that re-applies the same two headers at response start: the Razor Components endpoint writes its own, weakerCache-Controlwhile rendering, and because this callback is registered before the rest of the pipeline runs it executes after every downstream callback (last-registered runs first), so the credential value wins. The inline comment on the settings property states why: a reset or OAuth-completion URL a user opens must not carry the token onward in aRefererheader to whatever the page loads next, and must not remain cached after the token has been spent. - Walkthrough:
- Three private constants:
NoncePlaceholder = "{nonce}"(:150), the literal token a policy uses to request a nonce;NonceByteCount = 16(:153), whose doc comment records that 16 bytes (128 bits) is the CSP specification's recommendation; andCredentialCacheControl(:156), theCache-Controlvalue a credential page must leave with. - Four readonly fields. The constructor (
:164-176) null-guardsoptionsandenvironment, captures the next delegate, the CSP provider, and the settings snapshot, and computes_enableHsts = options.Value.EnableHsts && !environment.IsDevelopment()(:175) so HSTS is never emitted in development, where it would pinlocalhostto HTTPS in the browser for a year. IsCredentialPath(PathString path)(:179-182) is a private expression-bodied helper: it filters_settings.CredentialPathPrefixesto non-blank entries and returns whether any matches the request path's segments, case-insensitively.InvokeAsync(:185) null-guards the context, takes the response header collection once (:189), and setsXContentTypeOptions = "nosniff"(:190),XFrameOptions(:191), aReferrer-Policychosen byIsCredentialPath(no-referreron a match,_settings.ReferrerPolicyotherwise,:192-194), andPermissions-Policy(:195). When the path is a credential path it also callsApplyCredentialCacheHeadersand registers theOnStartingre-apply (:197-212); it then conditionally setsStrictTransportSecurity(:214-217).- It then asks the provider for a CspPolicy and, when the result is non-null, runs the nonce path: if the value contains
{nonce}, a freshConvert.ToBase64String(RandomNumberGenerator.GetBytes(16))value is generated, stored underCspNonce.ItemKeyinHttpContext.Items, and substituted into every occurrence as'nonce-<value>'. The comment above it records why the raw value lands inItemsbefore the pipeline runs: the page render is what stamps it onto its script and style tags. Finally the header is written asContentSecurityPolicywhenEnforceis true andContentSecurityPolicyReportOnlyotherwise. - The last statement is
return _next(context)(:243):InvokeAsyncis a non-asyncmethod returningTask, so it hands back the downstream task directly with no state machine. Note the ordering: every header is written before the rest of the pipeline runs, which is what makes them survive on responses produced further down, including forwarded YARP responses, and what makes the nonce readable by the render.
- Three private constants:
- Why it's built this way: A sealed conventional middleware (constructor plus
InvokeAsync), not anIMiddleware, so it is a singleton per pipeline with zero per-request resolution. Resolving CSP through the injectedICspPolicyProviderrather than reading settings directly is what makes per-host dynamic policies possible while every other header stays uniform. Computing_enableHstsonce in the constructor avoids re-checking the environment on every request, and the nonce generation is gated on the placeholder being present, so a policy that does not ask for one pays no cryptographic-RNG call at all.IsCredentialPathis evaluated per request against configuration rather than hard-coded, so a host extends the credential-path list (both apps'/reset-passwordand/auth/oauth-completeroutes today) without a code change. This single middleware is ADR-023's "one hardened default, defined once" decision: centralising the header set removes the per-host drift between Gateway and UI (and between apps) that came from each edge host hand-rolling its own headers, and makes a new edge host secure by default. - Where it's used: Added to the pipeline by SecurityHeadersExtensions
.UseCommonSecurityHeaders(SecurityHeaders.cs:299). Per ADR-023 it is wired at both edges of both apps:MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:193andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:159directly, and both UI hosts through the sharedUseMmcaBlazorWebPipeline(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:186, called atMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:92). Covered by SecurityHeadersMiddlewareTests inMMCA.Common.Aspire.Tests, whose nonce cases assert that every placeholder occurrence is replaced (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Security/SecurityHeadersMiddlewareTests.cs:190-192), and by the shared per-host SecurityHeadersTestsBase that both Gateway test projects subclass. - Caveats / not-in-source: The general headers are set on the way in, so a downstream component that removes or overwrites them after this point wins; only the credential-path
Cache-ControlandPragmaare re-asserted at response start (:205-211).IsCredentialPathrecomputes the segment match twice per credential-path request (once forReferrer-Policy, once for the cache-control branch); source shows no caching of that boolean within oneInvokeAsynccall.
StaticCspPolicyProvider
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:93· Level 2 · class (sealed, internal)
- What it is: The default ICspPolicyProvider: it returns the static CSP configured in SecurityHeadersSettings, or
nullwhen none is configured. - Depends on: ICspPolicyProvider (implements), SecurityHeadersSettings (via
IOptions<T>), CspPolicy (returns). - Concept introduced: Cross-reference ICspPolicyProvider for the provider extension point.
[Rubric §11, Security]: this is the safe fallback, so a host that registers nothing still gets the hardened baseline rather than no CSP at all. - Walkthrough: One readonly
CspPolicy? _policyfield (SecurityHeaders.cs:95). The constructor (:83) null-guardsoptions(:85), readsoptions.Value.ContentSecurityPolicy(:86), and sets_policytonullwhen that string is null or whitespace, otherwise to a new CspPolicy capturing the string and theEnforceContentSecurityPolicyflag (:87-89).GetPolicy(HttpContext context)(:92) simply returns the cached_policy, ignoring the request context, which is exactly what "static" means here. - Why it's built this way:
internal sealed, since it is the framework's own default and is registered byTryAddSingletonso a custom provider registered first by a Blazor host wins. Computing the policy once in the constructor rather than per request makesGetPolicyallocation-free on the hot path, which matters because it runs on every single response. Per ADR-023 this static baseline is now a complete hardened policy rather than a partial one, correct for JSON, WebSocket, and static hosts (API, Gateway) and functional for an HTML host that never registers a fuller provider. - Where it's used: Registered by SecurityHeadersExtensions
.AddCommonSecurityHeadersviaTryAddSingleton(SecurityHeaders.cs:288); resolved per request by SecurityHeadersMiddleware (:177). Its baseline output is asserted by SecurityHeadersMiddlewareTests. - Caveats / not-in-source: Because the policy is captured in the constructor from
IOptions<T>rather thanIOptionsMonitor<T>, a configuration reload of the"SecurityHeaders"section does not change the live CSP: that takes a restart.
ProbeTelemetryFilterProcessor
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Telemetry·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Telemetry/ProbeTelemetryFilterProcessor.cs:20· Level 10 · class (sealed)
- What it is: The span processor that suppresses everything underneath a health-probe request: the database check's SQL
SELECT 1, the Redis PING, the gateway's HttpClient call to a backend's/alive. ProbeTelemetryFilter refuses the probe request span itself, but its children are sampled independently and would still be exported without this pass (ProbeTelemetryFilterProcessor.cs:6-12). - Depends on: ProbeTelemetryFilter for the marker tag name (
:68) and HealthEndpointPaths for the path test (:77-79). Externals: OpenTelemetry'sBaseProcessor<Activity>andSystem.Diagnostics.Activity/ActivityKind/ActivityTraceFlags(:1-2). Registered by the service-defaults Extensions; it is the structural twin of OutboxPollFilterProcessor. - Concept introduced: none new. The suppression mechanism (clear
Recordedso the batch export processors skip the span, keeping the parent chain intact) is taught at OutboxPollFilterProcessor; the probe-filtering rationale is taught at ProbeTelemetryFilter.[Rubric §31, Cost & FinOps]: the class doc records that probe descendants made up most of theAppDependenciesvolume in both production workspaces (:6-12), and this is the pass that removes them.[Rubric §13, Observability & Operability]: the suppression is scoped by span kind so a normal request never loses its subtree because one dependency happened to be a probe call (:73-79). - Walkthrough:
- Two
private const stringfields,UrlPathTagName = "url.path"andHttpRouteTagName = "http.route"(:25-26). The comment above them (:22-24) states both the source of the values (set by the ASP.NET Core instrumentation on the server span at request start) and why they are literals: the package deliberately takes no dependency on the instrumentation's internal attribute class. This is the same commented literal-duplication trade OutboxPollFilterProcessor makes. OnStartandOnEndare both one-liners delegating to the sameSuppressWhenUnderProbe(data)(:29,:40). TheOnEndremarks (:31-39) explain why the pass runs twice: a span's identifying tags do not all exist at start (a client span is started before its instrumentation has written any attribute), so anOnStart-only filter would depend on callback ordering it does not control. ClearingRecordedat end is what actually keeps the span out of the exporters; theOnStartpass additionally stops the instrumentation from collecting data it will never export.SuppressWhenUnderProbe(:42) opens with a null check that returns rather than throws, under the comment "Never throw from a telemetry callback" (:44-48), matching the sibling processor's rule.- It then walks the in-process parent chain,
for (var current = data; current is not null; current = current.Parent)(:52), because a probe's dependency spans can sit several levels below the request span: HttpClient handler, then connection, then DNS (:50-51). - On the first ancestor that is a probe it clears two things (
:59-60):data.ActivityTraceFlags &= ~ActivityTraceFlags.Recordedmakes the batch export processors skip the activity, anddata.IsAllDataRequested = falsestops instrumentation from enriching it in the first place (:56-58). IsProbeRequest(Activity activity)(:66) tries the cheap answer first: the marker tag ProbeTelemetryFilter stamped, matched by presence rather than value (:68-71). Failing that it requiresKind == ActivityKind.Serverand then tries three probe-path candidates in turn: theurl.pathtag, thehttp.routetag, and the route parsed out of the display name (:76-79). The server-kind restriction is the §13 guard named above (:73-75): an outgoing call to a probe endpoint is the gateway's own health check, and is filtered at the instrumentation instead.RouteOfDisplayName(string displayName)(:89) finds the last space withdisplayName.AsSpan().LastIndexOf(' ')and takes the substring after it, or the whole name when there is none (:91-92). Its doc gives the reason this third candidate exists (:82-88): once the route is resolved the ASP.NET Core instrumentation renames the span to"{method} {route}", which is the only probe evidence left on a span whose tags an exporter-side enricher has already consumed.
- Two
- Why it's built this way: Three independent recognitions (marker tag, path or route tag, display name) exist because the same probe span is identifiable by different evidence depending on which pass is looking and what has already run. Matching a whole subtree by walking parents rather than by trace id keeps the processor stateless: there is no per-trace dictionary to bound or evict, which is what lets it be a single sealed instance on the path of every span. Registering it only on the enabled branch, rather than making it check a flag per span, keeps the off state genuinely free. ADR-041 is the governing record: cost levers with defaults that fail safe, alongside head-based sampling and the metric kill switches.
- Where it's used: Registered once, inside
ConfigureOpenTelemetry'sWithTracingblock, astracing.AddProcessor(new Telemetry.ProbeTelemetryFilterProcessor())guarded by the samefilterProbeTelemetryflag as the instrumentation filters (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:179-185), immediately after.AddProcessor(new Telemetry.OutboxPollFilterProcessor())(Extensions.Telemetry.cs:171) and before the sampler andAddOpenTelemetryExporters(). The comment there restates the ordering contract (Extensions.Telemetry.cs:181-183): registration before the exporters is what makes the clearedRecordedflag the thing their batch processors see. Every host callingAddServiceDefaults()gets it unless it setsTelemetry:FilterProbeTelemetry=false. Covered by ProbeTelemetryFilterProcessorTests, which drives a realActivityListenerand pins each path: a child of a probe request is unrecorded (ProbeTelemetryFilterProcessorTests.cs:46), a child of a normal request stays recorded (:73), a grandchild is unrecorded (:86), the probe request itself is (:99), recognition works by marker tag (:109), byhttp.routealone (:126) and by display name alone (:142), a client span to a probe endpoint stays recorded (:154), an unrelated root stays recorded (:171), a span whose tags arrive after start is caught by theOnEndpass (:183), and a null activity does not throw (:200). - Caveats / not-in-source: The walk is over
Activity.Parent, the in-process chain only, so a span whose probe ancestor exists only as a propagated remote context is not matched. Suppression is all-or-nothing per host: the one knob turns both the filters and this processor off together, so there is no way to keep probe dependency spans while dropping the probe request spans. Recognition by display name is a heuristic on an instrumentation-chosen format, and source shows nothing that would fail if that format changed: a non-probe span whose display name happens to end in/healthor/aliveand whose kind isServerwould also be suppressed.
SecurityHeadersExtensions
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Security·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Security/SecurityHeaders.cs:258· Level 3 · class (static)
- What it is: The registration and pipeline extensions for the common security-headers middleware:
AddCommonSecurityHeaders(DI) andUseCommonSecurityHeaders(pipeline). - Depends on: SecurityHeadersSettings, ICspPolicyProvider, StaticCspPolicyProvider, SecurityHeadersMiddleware.
- Concept reinforced, middleware registration via extension members.
[Rubric §11, Security](HTTP security headers) and[Rubric §26, Front-End Security](CSP defending the Blazor front end). The two-call shape,AddCommonSecurityHeadersduring service registration andUseCommonSecurityHeadersin the pipeline, is the idiomatic ASP.NET Core split, expressed here with twoextension(T)blocks in one static class (SecurityHeaders.cs:260,:293), which is also why the class carries the scopedCA1708suppression with its false-positive justification (:254-257). - Walkthrough:
AddCommonSecurityHeaders(configuration = null, configure = null)(SecurityHeaders.cs:268): null-guards the receiver (:272), builds anAddOptions<SecurityHeadersSettings>()(:276), chainsValidateDataAnnotations().ValidateOnStart()(:277) so a malformed credential prefix (see LeadingSlashPathPrefixesAttribute) fails the host once at startup rather than every request that reaches the matcher (ADR-070), binds the"SecurityHeaders"configuration section whenconfigurationis supplied (:278-281), applies the optionalconfiguredelegate when supplied (:283-286), then callsTryAddSingleton<ICspPolicyProvider, StaticCspPolicyProvider>()(:288). TheTryAddis the key detail: a host that registered a custom provider before this call keeps it; otherwise the static default is used. Both parameters are optional, so a host can take the hardened defaults with a bareAddCommonSecurityHeaders().UseCommonSecurityHeaders()(:296): null-guards the app (:298) and returnsapp.UseMiddleware<SecurityHeadersMiddleware>()(:299). Call it early in the pipeline so headers land on every response, including forwarded ones.
- Why it's built this way: A static class with
extension(T)blocks is the codebase's standard DI and registration idiom (see primer, C#extension(T)types and ADR-106). TheTryAddSingletonordering contract is what makes the per-consumer CSP override work without a configuration flag or a builder API. ADR-023 documents the matching foot-gun: because the default provider isTryAdd-registered, a host must register its customICspPolicyProviderbefore callingAddCommonSecurityHeaders, or the static default silently wins. - Where it's used: Called by each client-facing host:
MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:135andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:71directly, and both UI hosts (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:30) through the sharedAddMmcaBlazorWebHost(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:157). That helper callsAddCommonBlazorCsp()first (BlazorWebHostExtensions.cs:156, with the ordering comment right above it at:156) so BlazorCspPolicyProvider wins over the StaticCspPolicyProvider default. - Caveats / not-in-source: Nothing enforces the registration order at build time; the ordering contract is documented in the doc comments, in both hosts' inline comments, and in ADR-023, but a host that got it backwards would silently ship the static baseline instead of its own policy.
IWarmupTask
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/IWarmupTask.cs:9· Level 0 · interface
- What it is: A unit of startup work executed once after the host starts, to take lazy initialisation off the first user request: cache priming, opening connection pools, pre-fetching discovery documents.
- Depends on: Nothing. Implemented by the built-in OpenIdConnectMetadataWarmupTask and by every host task derived from SelfHttpWarmupTaskBase; run by WarmupHostedService; completion published through WarmupReadinessGate.
- Concept introduced, startup warm-up.
[Rubric §29, Resilience & Business Continuity]assesses proactive elimination of cold-start failure modes;[Rubric §12, Performance & Scalability]assesses whether latency is predictable rather than paid by whoever arrives first. After a deployment, or after an idle Azure Container Apps replica is scaled back up, the first requests hit cold paths: EF model build, connection-pool establishment, JIT, OIDC discovery. Warm-up tasks run those eagerly. Per the interface doc comment (IWarmupTask.cs:3-8), tasks run in parallel after host start, and failures are logged but do not prevent the readiness gate from opening, so a transient dependency outage cannot wedge a replica permanently out of rotation. - Walkthrough:
string Name { get; }(IWarmupTask.cs:12), a stable identifier used in the runner's structured logs and, per the doc comment, in metrics.Task ExecuteAsync(CancellationToken cancellationToken)(:15) performs the work; the token is the host'sstoppingToken, passed through by the runner. - Why it's built this way: An interface rather than an abstract class, for maximum implementation freedom. The one place the framework does supply a base class is the self-HTTP shape (SelfHttpWarmupTaskBase), where the mechanics rather than the contract are the shared risk. The non-fatal-failure contract is enforced by the runner (WarmupHostedService), not by the interface, so implementations stay simple and never reason about their own failure semantics. ADR-025 records the decision.
- Where it's used: Discovered via DI.
AddWarmupReadinessregisters the built-in OpenIdConnectMetadataWarmupTask (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:142), and a host adds its own withAddWarmupTask<TTask>()(Extensions.cs:160, whose body is the singleservices.AddSingleton<IWarmupTask, TTask>()at:351). The wholeIEnumerable<IWarmupTask>is injected into WarmupHostedService (Warmup/WarmupHostedService.cs:29). - Caveats / not-in-source: The interface carries no timeout, no ordering, and no retry. All three are the runner's business: tasks run concurrently in whatever order
Task.WhenAllschedules them (WarmupHostedService.cs:53-54), each under a 120-second ceiling (:42, applied at:69), and a failed task is never retried by the subsystem, only re-paid lazily on the first real request.
WarmupReadinessGate
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupReadinessGate.cs:10· Level 0 · class (sealed)
- What it is: A thread-safe one-shot flag that WarmupHostedService flips to
trueexactly once when every IWarmupTask has finished, failed, or timed out, gating the/health/readyendpoint. - Depends on: Nothing first-party. Read by WarmupReadinessHealthCheck, set by WarmupHostedService. Uses
VolatileandInterlocked(BCL). - Concept introduced, the readiness probe.
[Rubric §29, Resilience & Business Continuity],[Rubric §17, DevOps],[Rubric §13, Observability & Operability]. Azure Container Apps (and Kubernetes) withhold traffic from a replica until its readiness probe returns healthy. The health check reports unhealthy untilIsReadyistrue, so a fresh replica does not receive production traffic until warm-up has had its chance, avoiding slow or failed first requests (ADR-025). Note the deliberate split from liveness: readiness is what holds traffic back, while/alivestays narrow so a dependency outage never restarts the container (see HealthCheckTags). - Walkthrough:
private int _isReady(WarmupReadinessGate.cs:12), 0 or 1. Using anintwithVolatile.ReadandInterlocked.Exchangerather than aboolplus a lock gives lock-free, correctly published reads and writes.IsReady => Volatile.Read(ref _isReady) == 1(:15): the volatile read prevents a CPU from returning a stale cached value, which matters because the writer is a background thread and the readers are probe requests on the thread pool.internal void MarkReady() => Interlocked.Exchange(ref _isReady, 1)(:18): idempotent, safe to call twice, and the doc comment says so. - Why it's built this way: Sealed, so no subclass can reinterpret readiness.
MarkReady()isinternal(:18), so no external caller can prematurely open the gate; onlyWarmupHostedService, in the same assembly, may. The type carries no "not ready again" transition on purpose: readiness here means "warm-up has run", a startup fact rather than a live health signal, and the live signals are the separate dependency checks that also sit on/health/ready. - Where it's used: Registered as a singleton by
AddWarmupReadiness(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:139); opened in thefinallyofWarmupHostedService.ExecuteAsync(Warmup/WarmupHostedService.cs:58); read byWarmupReadinessHealthCheck.CheckHealthAsync(Warmup/WarmupReadinessHealthCheck.cs:14), which is registered as the"warmup"check taggedHealthCheckTags.Ready(Extensions.cs:144-145) and surfaced at/health/ready(Extensions.Health.cs:143-179). Covered by WarmupReadinessGateTests.
OpenIdConnectMetadataWarmupTask
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/OpenIdConnectMetadataWarmupTask.cs:25· Level 1 · class (sealed, internal, partial)
- What it is: The one built-in IWarmupTask. It pre-fetches the OIDC discovery document on startup, warming the network path so the first authenticated request does not hit a cold connection.
- Depends on: IWarmupTask (implements);
IHttpClientFactory,IConfiguration, andILogger<T>(BCL and DI). - Concept introduced:
[Rubric §29, Resilience & Business Continuity]. The doc comment (OpenIdConnectMetadataWarmupTask.cs:6-13) names the failure mode precisely: without warm-up, the JWT bearer middleware fetches{authority}/.well-known/openid-configurationlazily on the first authenticated request, and on a CPU-throttled idle ACA Consumption replica that fetch can stretch past the client timeout, the textbook "first request fails, second succeeds" pattern. Pre-fetching warms DNS, TCP, TLS, and theHttpClientpool. The honest caveat is stated in the type's own remarks (:14-20): the middleware'sConfigurationManagercaches discovery state separately, so it still performs its own fetch on the first request; the intent is that the fetch now runs over a warm connection and completes in single-digit milliseconds. - Walkthrough: A primary constructor injects
IHttpClientFactory,IConfiguration, andILogger<OpenIdConnectMetadataWarmupTask>(:21-24).Name => "OpenIdConnectMetadata"(:26).ExecuteAsync(:28) readsAuthentication:JwtBearer:Authority(:30) and returns immediately when it is unset (:31-34), so a non-authenticating host pays nothing. It then builds the discovery URI by trimming a trailing slash and appending/.well-known/openid-configuration(:36-39), logging a warning and returning if the result is not a valid absolute URI (:41-42). Finally it creates a client from the factory under the task type's own name (:45) and issues aGET(:46), logging the status code (:48). Both log lines are source-generated[LoggerMessage]partial methods (:51-57): EventId 1 at Warning for the invalid authority, EventId 2 at Information for the fetch. - Why it's built this way:
internal sealed partial. Internal because it is wired by the framework'sAddWarmupReadinessrather than by consumers,partialfor the[LoggerMessage]source generator, sealed by default policy. ReusingIHttpClientFactoryis the load-bearing detail: the warm-up exercises exactly the connection pool (and the tunedSocketsHttpHandlerfrom HttpResilienceDefaults) that the real auth path will use, so the warmth transfers. It reads the same configuration key the AppHost's JWKS discovery wiring injects, which is what makes the task self-configuring rather than needing its own settings class. ADR-025 records both the decision and the middleware-cache caveat. - Where it's used: Registered as an
IWarmupTasksingleton byAddWarmupReadiness(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:142), so every host that callsAddServiceDefaultsgets it; executed in parallel with any host-registered tasks by WarmupHostedService. - Caveats / not-in-source: The HTTP call passes no explicit timeout of its own. It is bounded twice from outside: by the shared Polly total-request timeout that
ConfigureHttpClientDefaultsapplies to every factory client (Extensions.cs:73, 90 seconds from HttpResilienceDefaults,MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:21), and by the runner's 120-second per-task ceiling (Warmup/WarmupHostedService.cs:42). A non-2xx discovery response is logged at Information like any other status (:48) rather than treated as a failure, so a 404 authority warms the connection and reports success.
SelfHttpWarmupTaskBase
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/SelfHttpWarmupTaskBase.cs:28· Level 1 · class (public, abstract, partial)
- What it is: The shared base class for the second family of warm-up tasks: once the server is listening, replay a short list of this host's own hot read paths against its own Kestrel endpoint. A derived task supplies only a name and the paths; every mechanism (waiting for the server, resolving the port, pinning the HTTP version, deciding what counts as failure, keeping failure non-fatal) lives here (
SelfHttpWarmupTaskBase.cs:11-22). - Depends on: IWarmupTask (implements). Its five primary-constructor parameters are all ASP.NET Core or hosting abstractions:
IServerplusIServerAddressesFeature(the actual bound address),IConfiguration(theASPNETCORE_URLSfallback),IHostEnvironment(the Testing short-circuit),IHostApplicationLifetime(theApplicationStartedwait), andILogger(:28-33). It creates its ownSocketsHttpHandlerandHttpClient(:111-117) rather than taking anIHttpClientFactory. - Concept introduced, self-request warm-up, and the template-method shape. The built-in OIDC task warms one outbound connection; this one warms the inbound path, which is where the cold-start cost of an idle, CPU-throttled replica actually lives: ingress connection, Kestrel, output cache, routing, authentication, the controller, EF Core, SQL (
:12-15).[Rubric §12, Performance & Scalability]assesses whether latency is predictable, and the whole point here is to move first-request JIT and query-plan cost off the first user and onto startup.[Rubric §29, Resilience & Business Continuity]covers the failure posture: every fault path in this class ends in a log line, never in an exception that reaches the runner.[Rubric §2, Design Patterns]is the shape itself, a textbook template method: one concreteExecuteAsync(:93) calling five members a subclass may or must supply (Name:49andWarmupPaths:59abstract;RequestVersion:70,RequestVersionPolicy:77, andRequireSuccessStatusCode:90virtual with defaults).[Rubric §15, Best Practices & Code Quality]is why it exists at all: six services across the two apps ran hand-copied versions of this logic, and the framework tests describe those copies as "the behaviors the per-service copies each had to get right on their own" (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Warmup/SelfHttpWarmupTaskBaseTests.cs:21-26). - Walkthrough, in teaching order.
- Two constants.
public const int DefaultPort = 8080(:39), the containerized default every deployed service listens on, used only when nothing else resolves; andprivate const string TestingEnvironmentName = "Testing"(:46), whose doc comment explains the short-circuit below: an integration test boots the host throughWebApplicationFactory, whose in-memoryTestServernever opens a socket, so a self-HTTP request there could only ever fail (:41-45). - The extension points.
Name(:49) andWarmupPaths(:59) are abstract. TheWarmupPathsdoc comment carries the single most important rule for a derived task (:53-57): the paths must match what real callers issue character for character in their values, not just in their shape, because an output-cache policy that varies by query string keys the entry on the exact URL, so a warmed entry built from different values is an entry nothing ever reads.RequestVersiondefaults toHttpVersion.Version20(:70) andRequestVersionPolicytoHttpVersionPolicy.RequestVersionExact(:77), which together are a pin, not a preference: the h2c prior-knowledge hosts serve HTTP/2 only on cleartext, and a silent downgrade to HTTP/1.1 would be rejected with a 400 "An HTTP/1.x request was sent to an HTTP/2 only endpoint", failing the warm-up on every single startup (:62-69). A host with no inbound gRPC server staysHttp1AndHttp2and overrides both members.RequireSuccessStatusCodedefaults totrue(:90), suiting an anonymous read whose response body is what populates the output cache; a protected endpoint overrides it tofalse, because an unauthenticated self-request against an[Authorize]route gets 401 by design and that refusal still traverses Kestrel, routing, authentication, and the middleware pipeline, which is the JIT cost the warm-up exists to pay down (:80-89). ExecuteAsync(CancellationToken)(:93). First the Testing short-circuit, which returns before anything else and therefore before the server wait (:95-98). ThenWaitForServerStartedAsync(:102), defined at:191-199: it registers a callback onlifetime.ApplicationStartedthat completes aTaskCompletionSource(created withTaskCreationOptions.RunContinuationsAsynchronously,:193-196) and awaits it with.WaitAsync(cancellationToken)(:198). The comment above it states the reason (:189-190): the warm-up runner is a hosted service that starts before Kestrel begins listening, since the web host is the last hosted service, so self-requesting immediately would race the listener.- Building the client. The base address is a
UriBuilderoverhttp,localhost, and the port fromResolveWarmupPort(:104-109); theSocketsHttpHandlerandHttpClientare created locally withdisposeHandler: falseand both disposed byusing(:111-117), and the client carriesDefaultRequestVersionandDefaultVersionPolicyfrom the two virtuals (:115-116). - The replay loop (
:119-133): each path is issued as a relativeGET(:121-123). WhenRequireSuccessStatusCodeis on,EnsureSuccessStatusCode()throws on a non-2xx (:127) and the body is then read to completion (:131), which the comment explains is the point of an output-cache warm-up: the entry is only worth priming if the whole response was produced and transferred (:129-130). When it is off, neither the status check nor the body drain happens, so the 401-profile task pays only the pipeline traversal. A success logs once for the whole task, with the name, the path count, and the base address (:135). - The failure boundary (
:137-146). AnOperationCanceledExceptionis rethrown when the token is actually cancelled (:137-140), so host shutdown is not mistaken for a warm-up failure; every other exception is caught under an explicit#pragma warning disable CA1031whose comment states the policy, warm-up failures are non-fatal by design, log and fall back to lazy warm-up (:141-143), and logged at Warning (:145). Note where thetrystarts (:100): the server wait, the port resolution, and the loop are all inside it, so a bad path list cannot take the host down either. ResolveWarmupPort(IServer, IConfiguration)(:157-166),internal staticso it can be tested directly. It prefers the firsthttp://address from the server'sIServerAddressesFeature(:159-160), which is the only correct answer under Aspire's dynamic ports, falls back toSelectCleartextUrl(configuration["ASPNETCORE_URLS"])(:161), then parses the port by trimming a trailing slash and taking the last colon-delimited segment underCultureInfo.InvariantCulture(:163), and finally falls back toDefaultPortwhen nothing parses (:165).SelectCleartextUrl(string?)(:176-187) picks the cleartext entry out of a possibly semicolon-separatedASPNETCORE_URLSlist (:183), returning the firsthttp://entry or, if there is none, the first entry at all (:185-186). Its doc comment explains why this stays string handling rather thanUriparsing (:168-173): wildcard hosts such as+and*are legal in that variable andUrirejects them.- Two
[LoggerMessage]partial methods (:201-207): EventId 1 at Information for the completed replay, EventId 2 at Warning carrying the exception for the failure, whose message is written for an operator reading a startup log, "first requests may be slow".
- Two constants.
- Why it's built this way:
- An abstract class, where the sibling contract is an interface. IWarmupTask stays a bare interface because warm-up work has no shared mechanism; self-HTTP warm-up is the opposite case, where the mechanism is the entire risk and the per-service part is a string array. Making the shared part inheritable, and the varying part abstract or virtual with a documented default, is what turns six copies into six path lists.
public, unlike its warm-up siblings. WarmupHostedService, WarmupReadinessHealthCheck, and OpenIdConnectMetadataWarmupTask areinternalbecause the framework wires them; this type is public precisely because consumers derive from it in their own assemblies.- Its own handler rather than
IHttpClientFactory. The self-request must be pinned to a specific HTTP version against this host's own listener; a factory client would inherit the globalConfigureHttpClientDefaultspipeline, whose resilience handler and shared primary handler are tuned for outbound service-to-service calls, not for one loopback request at startup. internal staticport resolution. Extracting the resolution into a pure static function is what makes the trickiest logic in the file testable without a running host, and[Rubric §14, Testability]shows up exactly there: five test methods exerciseResolveWarmupPortalone (MMCA.Common/Tests/Hosting/MMCA.Common.Aspire.Tests/Warmup/SelfHttpWarmupTaskBaseTests.cs:68-113), covering the bound-address preference, the HTTPS skip, bothASPNETCORE_URLSfallbacks, and the container default.- The subsystem as a whole is ADR-025, and the HTTP/2-only cleartext endpoints this class must speak to are ADR-012.
- Where it's used: Never registered by the framework. A host derives a task and registers it with
AddWarmupTask<TTask>()(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:160). ADC has three derived tasks: SelfHttpOutputCacheWarmupTask in Conference, which replays a fixed list of anonymous read URLs (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/SelfHttpOutputCacheWarmupTask.cs:66,:62, registered at.../MMCA.ADC.Conference.Service/Program.cs:256), plus a SelfHttpWarmupTask in Engagement (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/SelfHttpWarmupTask.cs:39,:42, registered atProgram.cs:157) and a SelfHttpWarmupTask in Identity (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/SelfHttpWarmupTask.cs:44,:42, registered atProgram.cs:169), both of which overrideRequireSuccessStatusCodetofalsebecause their one path is protected (:49in each). Store has three more of the same shape (IdentityProgram.cs:144, CatalogProgram.cs:162, SalesProgram.cs:157); its Catalog task takes the defaults outright (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/SelfHttpOutputCacheWarmupTask.cs:46,:49), while its Sales task is the one that overrides the version pin as well, staying on HTTP/1.1 withRequestVersionOrLowerbecause that host serves no inbound gRPC (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/SelfHttpOutputCacheWarmupTask.cs:56,:59). Behavior is covered by SelfHttpWarmupTaskBaseTests, which drives a configurable subclass against real Kestrel listeners started asHttp2orHttp1. - Caveats / not-in-source:
- A required-success failure abandons the remaining paths.
EnsureSuccessStatusCodethrows out of the loop into the outer catch (:127,:142), so with the default profile the first bad path ends the run and the later ones are never warmed. - The value-exactness rule is a convention, not a check. Nothing verifies that a derived task's
WarmupPathsmatch the URLs real callers build, so a drifted query string warms a cache entry no caller reads, silently and with a success log. The derived tasks record the mapping in comments. - Not determinable from source: how much first-request latency this actually removes on a CPU-throttled ACA replica. The class documents the cost model it is built against (
:12-15), and the tests prove the requests are issued and the failures are non-fatal, but no benchmark or gate in the repo measures the saving.
- A required-success failure abandons the remaining paths.
WarmupHostedService
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupHostedService.cs:28· Level 1 · class (sealed, internal, partial)
- What it is: The
BackgroundServicethat runs every registered IWarmupTask exactly once on startup, in parallel and each under a per-task timeout, then opens the WarmupReadinessGate. - Depends on: IWarmupTask (the set it runs, injected as
IEnumerable<IWarmupTask>) and WarmupReadinessGate (the gate it opens);BackgroundService,ILogger<T>,Stopwatch, plus the two optional primary-constructor parametersTimeProvider? timeProviderandTimeSpan? taskTimeout(WarmupHostedService.cs:32-33) that back the per-task timeout (BCL). - Concept introduced, fail-open startup gating.
[Rubric §29, Resilience & Business Continuity](the startup readiness gate) and[Rubric §13, Observability & Operability](timing logs per task and overall). The defining design choice, stated in the class doc comment (WarmupHostedService.cs:7-19), is that the gate opens even if tasks fail: a stuck dependency must not keep the replica out of traffic rotation forever (:9-12). The second paragraph of that comment (:13-19) extends fail-open to the harder case: failure was already harmless, but a task that neither completes nor throws used to leaveTask.WhenAllpending forever and the gate closed with it, "strictly worse than serving a cold one", so the per-task ceiling turns hanging into the same log-and-continue path. Both are availability chosen over strict warmth, and ADR-025 calls it the load-bearing decision of the subsystem. - Walkthrough:
- Constructor and timeout state first: the primary constructor (
:28-33) takes the task set, the gate, and the logger, then two optional parameters,TimeProvider? timeProvider = nullandTimeSpan? taskTimeout = null. They exist for testability, and the doc comment says so (:24-27): the override lets tests exercise the timeout path without waiting two minutes, while production always takes the default. The backing fields resolve the defaults once,_timeProvider = timeProvider ?? TimeProvider.System(:44) and_taskTimeout = taskTimeout ?? TimeSpan.FromSeconds(TaskTimeoutSeconds)(:45), over theprivate const int TaskTimeoutSeconds = 120(:42) whose doc comment (:35-41) insists it is a backstop, not a latency budget. ExecuteAsync(CancellationToken stoppingToken)(:47): starts an overallStopwatch(:49), runsTask.WhenAll(tasks.Select(task => RunOneAsync(task, stoppingToken)))(:53-54), and, crucially, opens the gate in afinallyblock,gate.MarkReady()(:58) followed byLogWarmupCompletewith the elapsed milliseconds (:59). A failing or hanging task therefore can never keep the replica permanently unready.RunOneAsync(task, cancellationToken)(:63): times each task with its ownStopwatch(:65), then awaitstask.ExecuteAsync(cancellationToken)(:68) chained through.WaitAsync(_taskTimeout, _timeProvider, cancellationToken)(:69), and logs the completion with the task name and duration (:71). Three catch clauses follow, in order. It rethrowsOperationCanceledExceptionwhen the host is actually stopping (:73-76, thewhen (cancellationToken.IsCancellationRequested)filter), so shutdown is not mistaken for a task failure. ATimeoutExceptionfrom theWaitAsyncceiling is caught and logged at Warning throughLogTaskTimedOutwith the task name, elapsed milliseconds, and_taskTimeout.TotalSeconds(:77-82); the comment there (:79-80) states the outcome plainly: same outcome as a failure, the abandoned task keeps running detached, the gate opens, and the dependency is retried lazily on first use. Every other exception is caught and logged at Warning (:84,:87), with#pragma warning disable CA1031and the comment "warm-up failures must never crash the host" (:83-85) documenting that swallowing a general exception is intentional here.- Four source-generated
[LoggerMessage]methods (:91-105):LogTaskCompleted(:93, EventId 1, Information),LogTaskFailed(:97, EventId 2, Warning, carrying the exception),LogWarmupComplete(:101, EventId 3, Information), andLogTaskTimedOut(:105, EventId 4, Warning, carrying the exception plus the limit in seconds so the log line names the ceiling that fired).
- Constructor and timeout state first: the primary constructor (
- Why it's built this way:
internal sealed partial. Running the tasks withTask.WhenAllrather than sequentially means total warm-up time is the slowest task, not the sum. The finally-open-the-gate pattern is the resilience invariant from IWarmupTask's contract, expressed in the one place that can enforce it, and the per-taskWaitAsyncis what makes that invariant hold against a task that hangs instead of throwing. Distinguishing host cancellation (rethrow) from timeout and from ordinary failure (both log and continue) keeps shutdown clean while making warm-up best-effort. Two details are deliberate: theWaitAsyncoverload takes aTimeProvider, which is why the constructor accepts one, so a test can drive the timeout path without a real wall-clock wait; and 120 seconds is chosen to sit above the 90-second shared Polly total-request timeout that already bounds the built-in OIDC task's HTTP call (HttpResilienceDefaults,MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:21, applied inExtensions.cs:73), so per the constant's own comment (:36-41) a task that reaches this limit is one that bypassed those defaults or is waiting on something that will never arrive. - Where it's used: Registered as a hosted service by
AddWarmupReadiness(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:140), which supplies no values for the two optional parameters, so production runs onTimeProvider.Systemand the 120-second default. Covered by WarmupHostedServiceTests, which constructs the service directly and passes a shorttaskTimeoutto exercise the hanging-task case. - Caveats / not-in-source:
WaitAsyncabandons rather than cancels, so a timed-out task keeps running detached for the life of the host (the comment at:79-80says exactly this); the only token that can stop it is the host'sstoppingTokenat shutdown. The ceiling also bounds the damage rather than removing it: a replica whose warm-up hangs stays out of rotation for the full 120 seconds before it is admitted. And the ceiling is not operator-tunable, sinceTaskTimeoutSecondsis aprivate const(:42) and thetaskTimeoutparameter is reachable only from a direct constructor call, with no configuration binding anywhere in the file.
WarmupReadinessHealthCheck
MMCA.Common.Aspire ·
MMCA.Common.Aspire.Warmup·MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/WarmupReadinessHealthCheck.cs:9· Level 1 · class (sealed, internal)
- What it is: An
IHealthCheckthat reports unhealthy until the WarmupReadinessGate opens. It is registered with thereadytag so it appears on the/health/readyendpoint that ACA readiness probes hit. - Depends on: WarmupReadinessGate (primary-constructor injection);
IHealthCheckandHealthCheckResult(Microsoft.Extensions.Diagnostics.HealthChecks). - Concept introduced:
[Rubric §13, Observability & Operability],[Rubric §29, Resilience & Business Continuity]. This is the bridge between the in-process gate and the hosting platform: the readiness probe's HTTP result is driven by one boolean. The readiness-probe concept itself is taught at WarmupReadinessGate, and the tag vocabulary at HealthCheckTags. - Walkthrough: A single method,
CheckHealthAsync(HealthCheckContext, CancellationToken)(WarmupReadinessHealthCheck.cs:11-16), returningTask.FromResult(gate.IsReady ? HealthCheckResult.Healthy("Warm-up complete.") : HealthCheckResult.Unhealthy("Warm-up in progress.")). It is synchronous under an async signature because reading a volatileintinvolves no I/O;Task.FromResultavoids a state machine entirely. - Why it's built this way:
internal sealed, since the framework wires it. Keeping it trivially cheap (no I/O, no allocation beyond the result) means the platform can poll the readiness endpoint frequently without cost, which matters because probe intervals are measured in seconds. The two description strings are what an operator sees in the/health/readypayload, so they are written for a human reading a probe failure. - Where it's used: Registered as the
"warmup"check taggedHealthCheckTags.ReadybyAddWarmupReadiness(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:144-145); surfaced at/health/readybyMapDefaultEndpoints(Extensions.Health.cs:143-179), whose predicate admits every check tagged neitherlivenoroptional(:154-156). Covered by WarmupReadinessHealthCheckTests.
ForwardedHeadersExtensions
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/ForwardedHeadersExtensions.cs:23· Level 0 · class (static)
- What it is: a two-member static class that gives a gateway host the framework's forwarded-headers wiring: one
extension(IApplicationBuilder)method,UseCommonForwardedHeaders(), and one public factory,CreateForwardedHeadersOptions(), that builds the options both the gateway and the service pipeline use. - Depends on: nothing first-party.
Microsoft.AspNetCore.Builder.IApplicationBuilderandMicrosoft.AspNetCore.HttpOverrides.ForwardedHeadersOptions/ForwardedHeaders(ASP.NET Core). It sits beside the rest of the gateway kit and is consumed alongside GatewayReverseProxyExtensions. - Concept introduced, forwarded headers as a correctness precondition for the edge limiter.
[Rubric §11, Security]assesses whether the app can identify its caller correctly;[Rubric §17, DevOps & Deployment]assesses whether shared request concerns are composed once rather than per host. Behind a cloud reverse proxy the TCP peer is the proxy, not the user. The class doc names the consequence precisely (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/ForwardedHeadersExtensions.cs:13-16): behind Azure Container Apps ingress every connection arrives from the ingress proxy's IP, so an unforwarded gateway collapses the per-client-IP rate-limit partition into one shared window for every real user. That makes this middleware a precondition for GatewayRoutePolicySettings partitioning, not an optional nicety, which is why the doc states the ordering contract explicitly (:29-32): call it first in a gateway pipeline, before the edge rate limiter. - Walkthrough:
extension(IApplicationBuilder app)block (:25). Its single memberUseCommonForwardedHeaders()(:36-41) null-guards the builder (:38) and returnsapp.UseForwardedHeaders(CreateForwardedHeadersOptions())(:40), so it is a one-line delegation to the shared options.CreateForwardedHeadersOptions()(:55-66) is where the policy lives. It enables the three headersXForwardedFor | XForwardedProto | XForwardedHost(:59), then clears both allow-lists:options.KnownProxies.Clear()(:62) andoptions.KnownIPNetworks.Clear()(:63).- Clearing is the load-bearing line, and the doc explains why (
:47-52): cloud reverse proxies front the app from internal IPs that are in neither default allow-list, so leaving the defaults in place makes the middleware ignore every forwarded header it receives and report the ingress IP as the client. The failure mode is silent: the middleware runs, returns 200s, and reports the wrong address. - The class carries a scoped
CA1708suppression (:19-22) with the same justification used elsewhere in the kit: with anextension(T)block inside a static class, the analyzer flags the compiler-generated grouping members as case-colliding (see primer, C#extension(T)types).
- Why it's built this way: service hosts get this step from
UseCommonMiddlewarePipelineinMMCA.Common.API, but a gateway takes none of that package: no controllers, noDbContext, no auth middleware. The doc records that reasoning (:9-17) and the address that follows from it: the one package every MMCA gateway already references, and one whose only runtime dependency is YARP. Without it a gateway hand-rolls the same five lines. This is the gateway half of ADR-088's edge-responsibility set. - Where it's used: both consumer gateways call it as the first middleware after
Build():MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:183(with the ordering rationale in the comment at:119-123) andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:150. In both hosts the edge limiter (app.UseGatewayRateLimiting(), ADCProgram.cs:143, StoreProgram.cs:170) comes later, which is the contract the doc asks for. Covered by ForwardedHeadersExtensionsTests. - Caveats / not-in-source: cleared allow-lists mean the middleware trusts
X-Forwarded-*from any peer. That is safe only when the process is genuinely unreachable except through the platform ingress. Nothing in this file asserts that topology; it is a deployment property. Not determinable from source: whether a given environment actually terminates all inbound traffic at a proxy.
GatewayActiveHealthCheckDefaults
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:180· Level 0 · class (sealed, options)
- What it is: the default active (out-of-band probe) destination health-check block applied to any YARP cluster that declares none. Five init-only properties: whether to apply it at all, the policy name, the probe interval, the per-probe timeout, and the probe path.
- Depends on:
System.ComponentModel.DataAnnotations.RequiredAttribute(BCL) andTimeSpan. Held by GatewayHealthCheckDefaults; materialised into YARP'sActiveHealthCheckConfigby GatewayHealthCheckDefaultsConfigFilter. - Concept introduced, probing liveness and never readiness.
[Rubric §13, Observability & Operability]assesses whether an operator can tell a healthy deployment from an outage. ThePathdoc comment (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:195-199) is the teachable line in this whole family: the probe targets/aliverather than/healthon purpose, because readiness on a downstream flips during its own rolling deployment, and ejecting a destination for that is the gateway reacting to a healthy deployment as if it were an outage. That rule (startup and rollout gates read liveness, never readiness) is the same one HealthCheckTags encodes on the service side. - Walkthrough:
Enabled(:153): defaults to false, the one place this family is off by default. The class doc gives the cost argument (:145-149): an extra probe per destination per interval is real traffic and real cost, and passive checks already eject a destination that is failing the requests the gateway actually cares about.Policy = "ConsecutiveFailures"(:157),[Required](:156): YARP's built-in active policy name.Interval = TimeSpan.FromSeconds(10)(:160) andTimeout = TimeSpan.FromSeconds(5)(:163): the probe cadence and the per-probe budget.Path = "/alive"(:171),[Required](:170).
- Why it's built this way: off by default with every value pre-filled means a host turns active probing on with a single
"Enabled": trueand inherits a sane probe, rather than restating five properties. Both consumer gateways do exactly that and override only the interval: ADC setsEnabled: trueplusInterval: 00:00:30(MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:42-47, with the reasoning in the comment at:36-41), Store the same (MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:26-31). ADC's comment states the gap active probing closes: passive checks only demote a destination after real traffic has already failed against it, so a restarting service keeps absorbing requests until enough of them error. - Where it's used: read by
GatewayHealthCheckDefaultsConfigFilter.BuildActive()(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:74-87), which returnsnullwhenEnabledis false. Covered by GatewayHealthCheckDefaultsConfigFilterTests. - Caveats / not-in-source:
[Required]on a property with a non-null default only fails validation when configuration explicitly supplies an empty string; it cannot catch a mistyped policy name, which YARP resolves at proxy-config load time rather than here.
GatewayClusterRequestProfile
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:82· Level 0 · class (sealed, options)
- What it is: a YARP forwarder request profile expressed in configuration-friendly primitives: HTTP version, version policy, forwarder activity timeout and response-buffering flag, all nullable, plus two
internalparsers that turn the two text properties into their strongly typed forms with a cluster-naming error message. - Depends on:
System.Net.HttpVersionPolicyandSystem.Version(BCL). Held by GatewaySettings as bothClusterRequestDefaultsand the values ofClusterRequestOverrides; merged into YARP'sForwarderRequestConfigby GatewayClusterProfileConfigFilter. - Concept introduced, nullable-means-defer, and text-over-type for fail-fast binding.
[Rubric §29, Resilience, Reliability & Business Continuity],[Rubric §15, Best Practices & Code Quality]. Two design choices are worth reading together. First, every property is nullable and null means "defer to a lower-precedence source" (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:85-87,:61-62). That is what makes the merge in the config filter per property rather than per block: a cluster that states one value keeps inheriting the rest. Second, the version pair is text rather thanVersion/HttpVersionPolicy, and the class doc says why (:47-50): a mistyped value then fails at startup with a message naming the cluster, instead of binding to a silent default. Configuration binders are forgiving by nature, and a silently defaulted HTTP version is exactly the class of bug that only appears as a connection reset in production. This is the ADR-070 fail-fast posture applied to a binder that would otherwise swallow the error. - Walkthrough:
Version(:58), for example"2.0"or"1.1";VersionPolicy(:64), for example"RequestVersionExact"(h2c prior knowledge) or"RequestVersionOrLower";ActivityTimeout(:67), how long a forwarded request may stay idle before the forwarder aborts it;AllowResponseBuffering(:70).ParseVersion(string clusterId)(:76-90): returnsnullwhenVersionis unset (:78-81), otherwiseSystem.Version.TryParse(:83) or anInvalidOperationExceptionwhose message names the cluster and the two valid shapes (:85-87).ParseVersionPolicy(string clusterId)(:96-111): the same shape overEnum.TryParse<HttpVersionPolicy>(..., ignoreCase: true, ...)(:103), with a message listing all three valid policy names (:105-108).- Both parsers are
internal, so they are reachable from the config filter and its tests but are not public API.clusterIdexists purely for the failure message, which the doc comments state on both (:73,:93).
- Why it's built this way: it is the copy-paste eliminator described on GatewaySettings's
ClusterRequestDefaults(:17-21). A gateway fronting services that all speak h2c on cleartext declares the version pair and the activity timeout once, instead of repeating an identicalHttpRequestblock per cluster. The exception thrown from a parser propagates out of the YARP config filter during proxy-config load, so a bad value is a startup failure with the cluster id in it rather than a runtime surprise. - Where it's used: bound from
MmcaGateway:ClusterRequestDefaultsandMmcaGateway:ClusterRequestOverrides:{clusterId}. ADC declares a00:01:40REST activity timeout as the default and a one-hour override for the long-lived SignalR hub clusternotification-hub(MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:28-35); Store declares only the default (MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:23-25). Consumed by GatewayClusterProfileConfigFilter. Covered by GatewayClusterProfileConfigFilterTests and by the binding assertions in AddMmcaGatewayTests. - Caveats / not-in-source: the parsers throw rather than returning a
Result, which is the framework's usual failure carrier. That is deliberate for a startup-path configuration error (there is no caller who could handle it), but it does mean this type does not follow the Result pattern the rest of the codebase does.
GatewayHeaderEncoding
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayHeaderEncoding.cs:14· Level 0 · class (internal, static)
- What it is: a two-member internal helper that makes the gateway's Kestrel decode one request header, the correlation header, as Latin-1 instead of refusing it. One constant,
CorrelationHeaderName, and one method,Apply(KestrelServerOptions). - Depends on: nothing first-party. Externals:
Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions(itsRequestHeaderEncodingSelector) andSystem.Text.Encoding.Latin1(BCL). Installed by GatewayReverseProxyExtensions. Coupled by a repeated string literal, not a reference, to GatewayCorrelationMiddleware, whose promise it exists to keep. - Concept introduced, a server rule that runs before any middleware can.
[Rubric §13, Observability & Operability],[Rubric §29, Resilience, Reliability & Business Continuity]. The class doc names the failure (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayHeaderEncoding.cs:6-12): Kestrel reads request headers as ASCII and answers a non-ASCII byte with an empty 400 andConnection: closebefore any middleware runs. So a correlation middleware that promises to replace an unusable inbound id with a generated one never gets the chance; the request dies at the server layer. Decoding that one header as Latin-1 means every byte decodes, the middleware sees a non-ASCII character, and it forwards and echoes a generated id as documented. Every other header keeps Kestrel's rule. This is the correlation half of ADR-088's edge-responsibility set, made reachable for a malformed caller. - Walkthrough:
CorrelationHeaderName = "X-Correlation-ID"(:20),internal const. Its doc (:16-19) records that this is a twin ofGatewayCorrelationMiddleware.HeaderNamein MMCA.Common.Aspire (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayCorrelationMiddleware.cs:37): the two packages share no reference, so the literal is repeated on purpose.Apply(KestrelServerOptions options)(:27-36): null-guards (:29), captures whatever selector the host already set (:31), then installs a new selector (:32-35) that returnsEncoding.Latin1for the correlation header (comparedOrdinalIgnoreCase) and otherwise defers to the captured selector,null(Kestrel's default) when there was none.
- Why it's built this way: chaining rather than replacing the selector, because
RequestHeaderEncodingSelectoris one slot on the Kestrel options and a host may have set it for its own reasons. The registration inWireis aPostConfigure(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:113-114), so it runs after the host's ownConfigureKestreland wraps that selector instead of being overwritten by it. Narrowing the rule to one header keeps the ASCII guard intact everywhere else. - Where it's used: one production call site,
builder.Services.AddOptions<KestrelServerOptions>().PostConfigure(GatewayHeaderEncoding.Apply)insideGatewayReverseProxyExtensions.Wire(GatewayReverseProxyExtensions.cs:114), so every gateway that callsAddMmcaGatewaygets it. Covered by GatewayHeaderEncodingTests: a non-ASCII correlation header reaches the pipeline (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/GatewayHeaderEncodingTests.cs:29), a non-ASCII byte in any other header is still refused by Kestrel (:39), and the host's own selector keeps deciding every other header (:49). - Caveats / not-in-source: the header-name twin is held together by convention only; nothing in source ties
CorrelationHeaderNametoGatewayCorrelationMiddleware.HeaderNameat compile time, so a rename on one side would silently restore the empty 400 for a non-ASCII correlation value.
GatewayPassiveHealthCheckDefaults
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:162· Level 0 · class (sealed, options)
- What it is: the default passive (in-band) destination health-check block applied to any YARP cluster that declares none. Three init-only properties: enabled, policy name, reactivation period.
- Depends on:
RequiredAttribute(BCL) andTimeSpan. Held by GatewayHealthCheckDefaults; materialised by GatewayHealthCheckDefaultsConfigFilter. Structurally the sibling of GatewayActiveHealthCheckDefaults, which introduces the liveness-probe rule. - Concept introduced, why passive is the default and active is opt-in.
[Rubric §29, Resilience & Business Continuity],[Rubric §31, Cost/FinOps]. The class doc gives the argument in one sentence (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:158-161): YARP watches the forwarded responses it is already making, so passive checking costs no extra traffic, which is why it is on by default while active probing is not. The tradeoff is latency of detection: passive only reacts once real traffic has already failed. A gateway that wants earlier detection turns the active block on and pays for the probes. - Walkthrough:
Enabled = true(:135): the default-on flag, the opposite of its active sibling.Policy = "TransportFailureRate"(:139),[Required](:138): YARP's built-in passive policy.ReactivationPeriod = TimeSpan.FromSeconds(60)(:142): how long an ejected destination stays out before it is retried.
- Why it's built this way: the parent's doc states the gap this closes (
:114-118): YARP ejects a failing destination only when a cluster carries a health-check block, and a gateway assembled from configuration routinely ships without one, so these defaults turn ejection on for every cluster that stayed silent. Turning ejection on by default is safe precisely because passive checking is free; the same reasoning would not justify defaulting active probes on. - Where it's used: read by
GatewayHealthCheckDefaultsConfigFilter.BuildPassive()(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:59-70). Neither consumer gateway overrides it, so both run the built-in defaults; ADC'sProgram.cscomment describes exactly that outcome (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:148-150). - Caveats / not-in-source:
TransportFailureRatehas its own YARP-side thresholds (what failure rate ejects a destination) that are not exposed here. Not determinable from this source: the rate YARP applies when the policy is named without further configuration.
GatewayBypassHeaderTransformProvider
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Transforms·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Transforms/GatewayBypassHeaderTransformProvider.cs:20· Level 0 · class (internal sealed)
- What it is: a second YARP request transform that strips the edge rate limiter's two bypass headers, the trusted-caller key and the synthetic-traffic key, from every proxied request, so the secrets they carry stop at the gateway (
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Transforms/GatewayBypassHeaderTransformProvider.cs:7-11). - Depends on: YARP's
ITransformProvider,TransformBuilderContext, the two validation contexts and theAddRequestTransformextension (:2-3), plusMicrosoft.Extensions.Configuration.IConfiguration(:1). No first-party type: the header names belong to GatewayRateLimitingSettings inMMCA.Common.Aspire, which this package does not reference, so they are read from configuration by key (:13-16). Registered by GatewayReverseProxyExtensions beside GatewayTraceHeaderTransformProvider, which introduced the transform-provider concept. - Concept introduced, a secret that ends at the edge.
[Rubric §11, Security]assesses how credentials and trust boundaries are handled; here the boundary is the gateway itself. The edge limiter lets a caller presenting the right key skip rate limiting (a trusted internal caller, or a load test marked as synthetic traffic). Those keys are shared secrets, and a reverse proxy forwards inbound headers by default, so without this transform every downstream service, sidecar and header log would receive them. The class doc records why removing them is safe: the limiter reads both headers before the proxy runs, so its decisions are unaffected (:10-11). It is the mirror image of the trace-header transform: that one guarantees a header can only have come from the gateway, this one guarantees a header never goes past it. ADR-088 is the gateway charter both transforms sit under. - Walkthrough:
- Three
internal constnames (:23,:26,:29): the limiter's section nameGatewayRateLimiting, and the default header namesX-Internal-Caller-KeyandX-Synthetic-Traffic-Key, "the same default the limiter uses" (:16). - Primary constructor with an optional
IConfiguration(:20,nulluses the defaults per the param doc at:19). The field_headerNamesis resolved once at construction (:31). ResolveHeaderNames(:66-78): readsTrustedCallerHeaderNameandSyntheticTrafficHeaderNamefrom the section (:74-75), each throughNameOrDefault(:80-81), which falls back to the default on a missing or whitespace value and trims a configured one. The pair is passed throughDistinct(StringComparer.OrdinalIgnoreCase)(:76), so a deployment that configures the same name for both removes it once.ValidateRouteandValidateCluster(:35,:43) are empty by design: the transform applies to every route and reads nothing from a route's own transform list (:37-38).Apply(:50-64): null-guards the context (:52), copies the array into a local (:54), and adds a request transform that callsProxyRequest.Headers.Removefor each name (:55-63). There is no enable switch: unlike the trace headers, removal always runs.
- Three
- Why it's built this way: reading the names by configuration key rather than through the settings type keeps
MMCA.Common.Gatewayfree of a reference toMMCA.Common.Aspire(:13-16), at the cost of a string coupling. Resolving the names once in the constructor keeps the per-request delegate to oneRemoveper header. - Where it's used: registered in the private
Wirebody shared by bothAddMmcaGatewayoverloads as.AddTransforms<GatewayBypassHeaderTransformProvider>()(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:120), so every gateway built on the kit strips the two headers. - Caveats / not-in-source: the section name and the two key names are duplicated literals of the limiter's own configuration shape (
:22namesGatewayRateLimitingSettings.SectionNameonly in a doc comment), so a rename on the limiter side would not fail the build here. Not determinable from source alone: which test, if any, pins the two packages' names against each other.
MailDevDefaults
Linked source (compiled into MMCA.Common.Aspire.Hosting and MMCA.Common.Testing.E2E) ·
MMCA.Common.MailDev·MMCA.Common/Source/Build/MailDev/MailDevDefaults.cs:17· Level 0 · class (internal static)
- What it is: two
const intvalues, the host ports the local MailDev container is published on:HttpPort = 1080for the web UI and REST API (MMCA.Common/Source/Build/MailDev/MailDevDefaults.cs:20) andSmtpPort = 1025for the SMTP listener (:23). - Depends on: nothing at all. It is read by the Aspire hosting
Extensions(AddMailDev, which re-exposes the pair asMailDevHttpPortandMailDevSmtpPort) and by the E2E package'sMailDevInbox, which reads the captured inbox from the web port (class doc:3-9). - Concept introduced, a linked source file instead of a shared reference.
[Rubric §15, Best Practices & Code Quality],[Rubric §33, Developer Experience]. Two packages must agree on two integers, and the obvious fix (one package references the other, or both reference a third) would drag a dependency along: the E2E package would depend on the Aspire hosting SDK, or the hosting package on Playwright, "for two integers" (:13-14). So the file sits underSource/Build/and is compiled as aninternaltype into each package through aCompile Include ... Linkitem (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/MMCA.Common.Aspire.Hosting.csproj:12,MMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/MMCA.Common.Testing.E2E.csproj:27), the same pattern asSource/Build/RateLimiting(:11-13). A port move still lands in one edit, and neither package references the other (:15). - Walkthrough:
internal static class(:17) with two documentedpublic const intfields (:19-20,:22-23). Nothing else. - Why it's built this way: the ports are fixed rather than dynamic because a developer opens the MailDev UI by hand and every consumer's SMTP settings are written against the pair (
MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:156-168).constis safe here despite compile-time inlining, because the type isinternaland compiled into each consuming assembly from the same file, so no assembly can hold a stale copy of another's value. - Where it's used:
Extensions.MailDevHttpPortandExtensions.MailDevSmtpPortalias the two values (Extensions.cs:163,:169), andAddMailDevpublishes the container on them as itshttpandsmtpendpoints (Extensions.cs:208-209).MailDevInboxbuilds its default base addresshttp://127.0.0.1:{HttpPort}from the web port (MMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/MailDev/MailDevInbox.cs:33). - Caveats / not-in-source: because the type is
internalin two assemblies, a consumer outside Common sees only the hosting package'sExtensions.MailDevHttpPort/MailDevSmtpPortaliases. Not determinable from this file: whether a consumer's ownSmtp:Portsetting actually matches1025; the hosting doc states it does (Extensions.cs:165-166), but nothing here enforces it.
GatewayTraceHeaderTransformProvider
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Transforms·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Transforms/GatewayTraceHeaderTransformProvider.cs:18· Level 3 · class (sealed)
- What it is: The gateway kit's one request transform. It stamps two headers onto every proxied request,
X-MMCA-Routewith the route id YARP matched andX-MMCA-Clusterwith the cluster it selected, after first removing whatever the client sent under those names. - Depends on: GatewaySettings, injected as
IOptions<GatewaySettings>and reduced immediately to its GatewayTraceHeaderSettings sub-object (GatewayTraceHeaderTransformProvider.cs:18-21). Externals: YARP'sITransformProvider,TransformBuilderContext,TransformRouteValidationContext/TransformClusterValidationContextand theAddRequestTransformextension (Yarp.ReverseProxy.Transforms/.Transforms.Builder,:1-3), plusMicrosoft.Extensions.Options. Registered by GatewayReverseProxyExtensions alongside GatewayClusterProfileConfigFilter and GatewayHealthCheckDefaultsConfigFilter. - Concept introduced, a header a downstream can trust.
[Rubric §11, Security],[Rubric §13, Observability & Operability],[Rubric §7, Microservices Readiness]. There are two ideas here and the second is the one that matters. The first is a YARP extension point: anITransformProvideris asked to contribute transforms into a route's pipeline when that pipeline is built, which is how a gateway adds behaviour to every route without listing it in each route's JSON. The second is the trust question. Correlating a downstream log line back to a gateway route by matching URL path patterns stops working the moment two routes share a prefix, so the proxy stamps the answer it alone knows. But the instant a downstream trusts a header, that header becomes an input an attacker can supply: a client that setsX-MMCA-Route: identity-authitself would have its request attributed to a route it never matched. §11 is the category that cares, and the fix is structural rather than validating: the transform removes both header names before writing its own (:60-61), so the value a service reads can only have come from the gateway. The class doc states the rule directly, "A header a service trusts must be one only the gateway can set" (:11-15). §7 is why the fact is worth having at all: once modules run as separate deployables (ADR-008), route selection is a decision made in one process and consumed in the logs of another. - Walkthrough:
- A primary constructor takes
IOptions<GatewaySettings>and the single field_settingsis initialized tooptions.Value.TraceHeaderswith an inlineArgumentNullExceptionguard (:18-21). The provider therefore holds the trace-header sub-settings only, resolved once at construction: the DI registration suppliesIOptions<GatewaySettings>as a fixedOptions.Create(settings)singleton (GatewayReverseProxyExtensions.cs:90), so there is no reload path to honour. ValidateRoute(:25) andValidateCluster(:33) are deliberately empty, each with a comment saying why (:27-28,:35): the provider is applied to every route unconditionally and reads nothing from the route's own transform list, so there is no operator-supplied parameter that could be mistyped and therefore nothing to validate. YARP requires the two methods; implementing them as no-ops with a stated reason is the honest form.Apply(TransformBuilderContext context)(:40) null-guards the context (:42), then applies the kill switch: when_settings.Enabledis false it returns having added nothing (:44-47). Disabled means no transform in the pipeline at all, not a transform that runs and does nothing.- Four values are hoisted into locals before the transform delegate is created: the two configured header names and the route's
RouteIdandClusterId(:51-54). The comment above them (:49-50) is the rationale: these ids are fixed for the lifetime of this route's transform pipeline, so resolving them per request would be work that can never produce a different answer. The captured locals are what keep the per-request delegate to a few header operations. context.AddRequestTransform(...)(:56) registers the delegate. Inside it: taketransformContext.ProxyRequest.Headers(:58),Removeboth header names (:60-61), thenTryAddWithoutValidationeach id back only when it is non-empty (:63-71), and returnValueTask.CompletedTask(:73). The empty checks are not defensive noise: a direct-response route has no cluster, and the behaviour there is to stamp the route header and leave the cluster header absent rather than emit a blank one.
- A primary constructor takes
- Why it's built this way: Remove-then-add rather than "set" is the whole security property, and doing it inside the request transform (which shapes the outbound message to the destination) rather than in middleware is what guarantees no later stage re-copies the inbound value.
TryAddWithoutValidationskips the header-syntax checks, which matters because route and cluster ids come from operator-authored configuration and a strictAddwould throw inside the proxy pipeline for an id containing an unexpected character. This transform is also a deliberate, documented exception to the gateway kit's own charter: ADR-088 originally declined all request rewriting and was narrowed on 2026-08-27 to allow exactly this one, on the grounds that it stamps which route and cluster YARP selected, "a fact only the proxy knows and one a downstream cannot reconstruct". The declines that still stand are path rewriting, body rewriting and response shaping. - Where it's used: Registered once, in the private
Wirebody shared by bothAddMmcaGatewayoverloads, as.AddTransforms<GatewayTraceHeaderTransformProvider>()(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:103). Both gateway hosts pick it up through that one call:MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:173andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:140. Covered directly by GatewayTraceHeaderTransformProviderTests, whose five cases pin exactly the behaviours above: the happy path (GatewayTraceHeaderTransformProviderTests.cs:18), that a client-supplied value is replaced rather than appended to (:29, asserting a single header value at:39-42), custom header names (:46), thatEnabled = falseleavescontext.RequestTransformsempty (:65-75), and the cluster-less route (:81-88). Its presence in the registration is asserted by AddMmcaGatewayTests (AddMmcaGatewayTests.cs:39), and RecordingHttpForwarderTests models the same stamping in its test double (RecordingHttpForwarderTests.cs:159-169). - Caveats / not-in-source: Neither app's configuration overrides the
MmcaGateway:TraceHeaderssection, so the shipped names are the defaultsX-MMCA-RouteandX-MMCA-Cluster(GatewaySettings.cs:211,:184) andEnabledstays true (GatewaySettings.cs:217). Nothing in this file consumes the headers: what a downstream does with them is out of scope here, and source shows no first-party reader of either name. The settings snapshot is taken in the constructor and theEnabledgate is evaluated when a route's transform pipeline is built, so a configuration change requires a new proxy configuration build, not merely the next request.
GatewayRetrySettings
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:59· Level 0 · class (sealed, options)
- What it is: the opt-in connect-failure retry block, bound from
MmcaGateway:Retry. Three init-only properties: whether the retry is installed, how many extra attempts, and the wait before each. - Depends on:
RangeAttribute(BCL) andTimeSpan. Held by GatewaySettings asRetry; validated by GatewaySettingsValidator; read by GatewayRetryForwarderHttpClientFactory and GatewayConnectRetryHandler; itsEnabledflag decides whether GatewayReverseProxyExtensions installs that factory at all. - Concept introduced, retry only what provably never arrived.
[Rubric §29, Resilience, Reliability & Business Continuity],[Rubric §11, Security]. The class doc draws the line (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:53-58): only a body-less GET or HEAD whose attempt failed with a name resolution, connection or TLS failure is retried; never a POST, never a request with a body, never a response of any status. A connect failure is the one case where the gateway knows the destination did not see the request, so repeating it cannot duplicate a side effect. When the budget is spent the last failure surfaces unchanged, so YARP still answers 502 and the passive health policy (GatewayPassiveHealthCheckDefaults) still counts it: the retry smooths a transient blip without hiding a dead destination from ejection. - Walkthrough:
Enabled(:64): defaults to false. The doc (:60-63) states the consequence of each value: off, YARP's own forwarder client factory stays in use; and a host that registered its ownIForwarderHttpClientFactorymust leave it off.MaxRetryAttempts = 1(:68),[Range(1, 3)](:67): extra attempts after the first one.Delay = TimeSpan.FromMilliseconds(200)(:72),[Range(typeof(TimeSpan), "00:00:00", "00:00:05")](:71): the wait before each extra attempt, at most five seconds.
- Why it's built this way: off by default with sane values pre-filled, the same shape as GatewayActiveHealthCheckDefaults: a host turns it on with one
"Enabled": true. The tight ranges keep the worst-case added latency of a failing GET small (three attempts at five seconds is the ceiling), and they fail at registration because the block is in the validator's nested list (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettingsValidator.cs:55, see that section), per ADR-070. - Where it's used:
GatewayReverseProxyExtensions.Wirebranches onsettings.Retry.Enabled(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:108-111). The factory takes the block fromsettings.Value.Retry(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayRetryForwarderHttpClientFactory.cs:37,:59), and the handler enforcesMaxRetryAttempts(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayConnectRetryHandler.cs:57) and waitsDelayon the injected clock (:70-72). Neither consumer gateway'sappsettings*.jsondeclares aRetryblock, so both run with it off. Covered by AddMmcaGatewayTests (disabled keeps YARP's factory,MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/AddMmcaGatewayTests.cs:107; enabled registers the retrying one,:122; enabled beside a foreign factory throws,:148) and by GatewaySettingsValidationTests. - Caveats / not-in-source: whether a deployed environment sets
MmcaGateway__Retry__Enabledthrough an environment variable is not determinable from source.
GatewayRoutePolicyPartition
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:229· Level 0 · enum
- What it is: a two-value enum naming what a named per-route rate-limiter policy counts requests against:
ClientIp = 0(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:232) orGlobal = 1(:205). - Depends on: nothing. Read by GatewayRoutePolicySettings and, through it, by GatewayRoutePolicyExtensions.
- Concept introduced: none new. It names the two partition strategies for the edge tier of the rate-limiting stack whose settings sibling is GatewayRateLimitingSettings, governed by ADR-019 as extended by ADR-088.
[Rubric §11, Security]: the doc comment onClientIprecords why it is the edge default in one clause (:201): at the edge there is no principal yet, because the gateway deliberately does not validate tokens. Per-IP is the only attribution available before authentication happens downstream. - Walkthrough:
ClientIp = 0is declared first and is therefore the CLR default for the enum, which lines up with GatewayRoutePolicySettings's own explicit default (:215).Global = 1is one window for the whole replica, whoever the caller is, which the doc states plainly (:204). - Why it's built this way: an enum rather than a boolean makes the configuration file self-describing (
"Partition": "ClientIp") and leaves room for a third strategy without a breaking change to the settings shape. Explicit numeric values pin the wire representation so reordering the members later cannot silently change what a persisted integer means. - Where it's used:
GatewayRoutePolicySettings.PartitionKey(IPAddress?)branches on it (:243-246). Both consumer gateways set"Partition": "ClientIp"explicitly on theirauth-tightpolicy rather than relying on the default (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:50,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:34).
GatewayTraceHeaderSettings
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:208· Level 0 · class (sealed, options)
- What it is: the configuration for the two route/cluster trace headers stamped onto each proxied request: whether to stamp them at all, and the name of each. It also owns the two default header-name constants.
- Depends on:
RequiredAttribute(BCL). Held by GatewaySettings and read by GatewayTraceHeaderTransformProvider, which performs the stamping. - Concept introduced, naming the route rather than reconstructing it.
[Rubric §13, Observability & Operability]assesses whether a request can be followed across processes. The class doc gives the motivation (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:204-207): a downstream log line can name the gateway route that produced it without correlating by path pattern. Reconstructing "which route matched" from a path downstream is guesswork the moment two routes share a prefix or a transform rewrote the path; the gateway already knows the answer and simply says it. This is complementary to, not a replacement for, the correlation id GatewayCorrelationMiddleware mints (ADR-041 extended one hop outward by ADR-088): the id answers "which request", these two headers answer "through which edge route". - Walkthrough:
DefaultRouteHeaderName = "X-MMCA-Route"(:181) andDefaultClusterHeaderName = "X-MMCA-Cluster"(:184):const stringdefaults, public so tests and hosts can assert against the names rather than re-typing the literals.Enabled = true(:187): stamping is on by default.RouteHeaderName(:191) andClusterHeaderName(:195), both[Required](:190,:194) and both initialised from the matching constant, so an operator renaming one header does not have to restate the other.
- Why it's built this way: defaults-as-constants plus
[Required]init-only properties is the shape used throughout this settings file. On by default is safe because the headers carry no user data (a route id and a cluster id are both authored by the gateway operator). Renaming is supported becauseX-MMCA-*is an MMCA-specific prefix a host embedding the gateway in a wider estate may need to change. - Where it's used: bound from
MmcaGateway:TraceHeaders; AddMmcaGatewayTests binds a renamed header to prove the section reaches the type (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/AddMmcaGatewayTests.cs:69). Neither consumer gateway overrides the names, so both runX-MMCA-Route/X-MMCA-Cluster, which ADC'sProgram.cscomment describes together with the inbound-value stripping the transform provider performs (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:164-166). - Caveats / not-in-source: this type is configuration only. The stripping of any inbound value, which is what makes a downstream able to trust the headers, lives in GatewayTraceHeaderTransformProvider, not here.
GatewayHealthCheckDefaults
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:149· Level 1 · class (sealed, options)
- What it is: a two-property holder pairing the GatewayPassiveHealthCheckDefaults and GatewayActiveHealthCheckDefaults blocks. It exists so
MmcaGateway:HealthCheckDefaultsmirrors YARP's ownHealthCheckshape one level up. - Depends on: its two child settings types. Held by GatewaySettings (
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:34), read by GatewayHealthCheckDefaultsConfigFilter. - Concept introduced: none new; it is the grouping node for the defaults concept the two children teach.
[Rubric §29, Resilience & Business Continuity]. The class doc carries the argument for the whole family (:114-118): YARP ejects a failing destination only when a cluster carries a health-check block, and a config-driven gateway routinely ships without one, so these defaults turn ejection on for every cluster that stayed silent. That is the difference between a gateway that load-balances onto a dead replica and one that does not, achieved with zero per-cluster configuration. - Walkthrough:
Passive { get; init; } = new()(:122), applied only to clusters with no passive block;Active { get; init; } = new()(:125), off unless the host turns it on. Both are non-nullable with eager defaults, so a host that omits the wholeHealthCheckDefaultssection still gets the passive block. - Why it's built this way: shaping the settings after YARP's own
HealthCheckConfig(Passive plus Active) means an operator reading theMmcaGatewaysection recognises it from theReverseProxysection, and the config filter's merge is a straight per-block copy with no translation table. - Where it's used: GatewayHealthCheckDefaultsConfigFilter reads
_settings.HealthCheckDefaults.Passive(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:61) and.Active(:76).
GatewayRoutePolicySettings
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:242· Level 1 · class (sealed, options)
- What it is: one named fixed-window rate-limiter policy a YARP route can reference through YARP's own
RateLimiterPolicyroute property ("RateLimiterPolicy": "auth-tight"). Four validated init-only properties plus theinternalpartition-key selector that decides what a given request counts against. - Depends on: GatewayRoutePolicyPartition, ClientAddressKey (an internal source file linked into the Gateway package,
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/MMCA.Common.Gateway.csproj:23),System.Net.IPAddress, and theRangeAttributedata annotations (BCL). Held by GatewaySettings; turned into a real limiter by GatewayRoutePolicyExtensions. - Concept introduced, failing open rather than collapsing a partition.
[Rubric §11, Security],[Rubric §14, Testability]. The subtlest member here isPartitionKey, and its doc comment (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:265-270) explains a decision that is easy to get backwards: when the client IP is unresolvable and the policy is per-IP, it returnsnull, meaning no limiter at all. The alternative, bucketing every unattributable request under one shared key, sounds safer but is not: it throttles an in-processTestServer(whereRemoteIpAddressis null for every request) to a standstill, and in production it would let one unattributable caller exhaust the window for all the others. Failing open on an unknown address is a bounded loss; collapsing the partition is an unbounded one. - Walkthrough:
Partition(:245): defaults toGatewayRoutePolicyPartition.ClientIp.PermitLimit = 30(:249),[Range(1, int.MaxValue)](:248): requests allowed per window.WindowSeconds = 60(:253),[Range(1, 3600)](:252): window length, capped at an hour.QueueLimit(:260),[Range(0, 10_000)](:259): defaults to zero, and the doc gives the reason (:255-258): a queue at the edge converts a throttle into latency the caller cannot see the cause of. Rejecting immediately with a 429 is an answer the caller can act on.GlobalPartitionKey = "__global"(:263),internal const: the single key used byPartition = Global, and reused as the (unused) key of the no-limiter partitions inGatewayRoutePolicyExtensions(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:129,:144).PartitionKey(IPAddress? remoteIpAddress)(:273-276),internal: returnsGlobalPartitionKeyfor a global policy, otherwiseClientAddressKey.For(remoteIpAddress)(:276), which isnullwhen the address is unresolvable. The shared key collapses the two ways one client can look like many: an IPv4-mapped address is unmapped to plain IPv4, and an IPv6 address is masked to its /64 prefix (MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:42-65), because an IPv6 subscriber normally holds a whole /64 and could otherwise buy a fresh window per request by rotating the low bits (doc:13-18). Internal rather than private, so the extension can call it per request (RateLimiting/GatewayRoutePolicyExtensions.cs:136) and tests can exercise the selection directly.
- Why it's built this way:
[Range]annotations rather than hand-written guards, becauseAddGatewayRoutePoliciesrunsValidator.ValidateObject(..., validateAllProperties: true)at registration (RateLimiting/GatewayRoutePolicyExtensions.cs:73), so a bad number throws during startup rather than at the first throttled request. That is the ADR-070 fail-fast contract, and the extension's own doc names the ADR (RateLimiting/GatewayRoutePolicyExtensions.cs:55-57). Fixed window rather than sliding or token bucket keeps the configuration two numbers wide, which is what an operator can reason about at the edge. - Where it's used: both consumer gateways declare two policies:
auth-tight, at 30 requests per 60 s with no queue (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:56-61,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:33-38), andwellknown, at 60 per 60 s per client address for the anonymous JWKS and OIDC discovery reads (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:66-70,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:44-49).auth-tightis attached only to the credential-submission routes, split out of the/Authcatch-all so the server-side session refresh is not throttled by it (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:83-86,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:81-83). The Aspire AppHost extensionWithE2eGatewayRateLimitLiftraises theauth-tightPermitLimitto 100000 for E2E runs by injectingMmcaGateway__RateLimiterPolicies__auth-tight__PermitLimit(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:566-568, constants at:87,:119,:126), which is a working demonstration that the whole binding path is environment-overridable. Covered by GatewayRoutePolicyTests. - Caveats / not-in-source: the per-IP partition is only as good as the resolved address, which depends on ForwardedHeadersExtensions having run first. Nothing in this type can detect that it did not.
GatewaySettings
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:13· Level 2 · class (sealed, options)
- What it is: the whole configuration surface of
AddMmcaGateway, bound from theMmcaGatewaysection. Six members: the section-name constant, shared cluster request defaults plus per-cluster overrides, health-check defaults, trace-header settings, the named rate-limiter policies, and the opt-in connect-failure retry. - Depends on: GatewayClusterRequestProfile, GatewayHealthCheckDefaults, GatewayTraceHeaderSettings, GatewayRoutePolicySettings, GatewayRetrySettings. Bound and validated by GatewayReverseProxyExtensions and GatewaySettingsValidator; consumed by GatewayClusterProfileConfigFilter, GatewayHealthCheckDefaultsConfigFilter, GatewayTraceHeaderTransformProvider, GatewayRoutePolicyExtensions and GatewayRetryForwarderHttpClientFactory.
- Concept introduced, a settings section defined by what it refuses to own.
[Rubric §7, Microservices Readiness],[Rubric §15, Best Practices & Code Quality],[Rubric §34, Architecture Governance & Documentation]. The class doc opens with the boundary (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:7-12): nothing here duplicates the YARPReverseProxysection. Routes, clusters and destinations stay where they are, and this section only carries the cross-cutting defaults a gateway would otherwise copy into every cluster by hand. That is the whole design in one sentence, and it is the framework-side expression of ADR-089, whose central finding was that one route table described in three places had already disagreed with itself. A settings type that carried even a partial route list would recreate exactly that failure. It sits beside ADR-088, which enumerates what the gateway does and, deliberately, what it declines to do. - Walkthrough:
SectionName = "MmcaGateway"(:15): the configuration section,constso a host and its tests can name it without a literal.ClusterRequestDefaults(:22), nullable: the profile applied to every cluster that states no value of its own. The doc calls it "the copy-paste eliminator" (:17-21), the shared activity timeout and h2c version pair declared once instead of per cluster.ClusterRequestOverrides(:29-30):IReadOnlyDictionary<string, GatewayClusterRequestProfile>keyed by cluster id, initialised to an empty case-insensitive dictionary (StringComparer.OrdinalIgnoreCase), because cluster ids in configuration are operator-typed. A cluster whose profile genuinely differs states only the properties that differ (:24-28).HealthCheckDefaults(:33): non-nullable with an eagernew(), so the passive defaults apply even when the section is absent entirely.TraceHeaders(:36): likewise eager, so the trace headers are on by default.RateLimiterPolicies(:42-43): keyed by policy name withStringComparer.Ordinal, deliberately case sensitive unlike the cluster overrides, because a route references the policy by exact name through YARP's ownRateLimiterPolicyproperty.Retry(:49): a GatewayRetrySettings block, eagernew()like the other child blocks, but off by default (doc:45-48): a body-less GET or HEAD whose attempt never reached the destination is tried again only when a host opts in.
- Why it's built this way: init-only properties throughout, which is what lets GatewayReverseProxyExtensions hand the whole object to DI as an
IOptions<GatewaySettings>instance rather than mutating one into place (its comment says exactly that,MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:87-89). Every collection and child block has a non-null default, so a gateway that adds the package and configures nothing still gets passive health checks and trace headers (and leaves YARP's own forwarder factory in place, since the retry is off), which is the "useful with zero configuration" posture the whole kit is built around. - Where it's used: bound by
AddMmcaGateway(IConfiguration)with.ValidateDataAnnotations().ValidateOnStart()(GatewayReverseProxyExtensions.cs:63-66). Live sections:MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:27-56andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:22-40. Covered by AddMmcaGatewayTests, which binds a full section from an in-memory configuration (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/AddMmcaGatewayTests.cs:60), asserts the no-section defaults (:90) and bindsMmcaGateway:Retry:Enabled(:127). - Caveats / not-in-source:
ValidateDataAnnotationsvalidates the top-level object only; the nested trace-header, health-check and retry blocks are validated by GatewaySettingsValidator, and the[Range]annotations on the rate-limiter policies are validated explicitly insideAddGatewayRoutePolicies(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:71-74), which is why that loop exists rather than relying on options validation alone.
GatewaySettingsValidator
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettingsValidator.cs:19· Level 3 · class (internal, sealed)
- What it is: the validator for the objects nested inside GatewaySettings: the trace-header settings, both halves of the health-check defaults, and the connect-retry block. It implements
IValidateOptions<GatewaySettings>and also exposes a staticThrowIfInvalidfor registration time. - Depends on: GatewaySettings and, through its
NestedObjectslist (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettingsValidator.cs:50-56), GatewayTraceHeaderSettings, GatewayPassiveHealthCheckDefaults, GatewayActiveHealthCheckDefaults and GatewayRetrySettings. Externals:System.ComponentModel.DataAnnotations(Validator),Microsoft.Extensions.Options(IValidateOptions<T>). Wired by GatewayReverseProxyExtensions. - Concept introduced, validation that follows the object graph.
[Rubric §34, Architecture Governance & Documentation],[Rubric §7, Microservices Readiness]. The class doc states the gap it closes (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettingsValidator.cs:6-11):ValidateDataAnnotationsreads only the attributes onGatewaySettings's own properties and does not recurse, so a blank trace-header name used to pass startup and then throw from every proxied request. This type validates each nested object explicitly, which is the ADR-070 fail-fast configuration contract applied to the gateway (ADR-070, ADR-088). - Walkthrough:
ThrowIfInvalid(GatewaySettings)(:23-29): static; runsValidator.ValidateObject(..., validateAllProperties: true)on each nested object, so the first failure throws aValidationException.Validate(string? name, GatewaySettings options)(:32-48): theIValidateOptionspath. Null-guards, then runsValidator.TryValidateObjecton each nested object and collects every failure asMmcaGateway:{TypeName}: {message}(:42-43). ReturnsValidateOptionsResult.Successwhen none, elseFail(failures)(:47), so a host sees all bad values at once rather than the first.NestedObjects(:50-56), private:TraceHeaders,HealthCheckDefaults.Passive,HealthCheckDefaults.Active,Retry(:52-55). The last entry is what makes an out-of-rangeMaxRetryAttemptsorDelayfail at registration and at start.
- Why it's built this way: two entry points for two moments. The static throwing form fails registration for both
AddMmcaGatewayoverloads (the settings overload never touches the options pipeline), mirroring how the route policies fail fast. TheIValidateOptionsform is registered only by the configuration overload and re-checks the bound value at host start (class doc:12-17). - Where it's used:
GatewayReverseProxyExtensions.cs:70-71(registered viaTryAddEnumerable) and:105(ThrowIfInvalidinsideWire). - Caveats / not-in-source: the type is
internal, so a host cannot reuse it or replace it. Only the four listed nested objects are checked; a new nested settings object added toGatewaySettingsis not validated until it is added toNestedObjects.
GatewayReverseProxyExtensions
MMCA.Common.Gateway ·
MMCA.Common.Gateway·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:35· Level 4 · class (static)
- What it is: the single composition entry point for the gateway kit. Two
AddMmcaGatewayoverloads onIReverseProxyBuilder, one binding fromIConfigurationand one taking already-built settings, over one shared privateWiremethod, plus a privateAddConnectRetrythat swaps in the retrying forwarder factory when the retry is enabled. - Depends on: GatewaySettings, GatewayRetrySettings, GatewaySettingsValidator, GatewayClusterProfileConfigFilter, GatewayHealthCheckDefaultsConfigFilter, GatewayRoutePolicyExtensions, GatewayTraceHeaderTransformProvider, GatewayBypassHeaderTransformProvider, GatewayHeaderEncoding, GatewayRetryForwarderHttpClientFactory. Externals:
Yarp.ReverseProxy(IReverseProxyBuilder,AddConfigFilter,AddTransforms, andIForwarderHttpClientFactory/ForwarderHttpClientFactoryfromYarp.ReverseProxy.Forwarder),KestrelServerOptions,Microsoft.Extensions.Options,Microsoft.Extensions.Configuration. - Concept introduced, a composition root defined by what it declines to load.
[Rubric §7, Microservices Readiness],[Rubric §3, Clean Architecture],[Rubric §34, Architecture Governance & Documentation]. The class doc is explicit (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:24-29): it deliberately does not load the route table.LoadFromConfig, or any otherIProxyConfigProvider, stays the host's call, because which section owns the routes, and whether they come from configuration at all, is a host decision. This method adds behavior on top of whatever config source the host chose. That single restraint is what reconciles a shared framework package with ADR-089's consumer-owned route table, and ADR-088 records the same package boundary from the edge-responsibility side. - Walkthrough:
extension(IReverseProxyBuilder builder)(:37) holding both public overloads.AddMmcaGateway(IConfiguration configuration)(:56-74): null-guards (:58-59), takes theMmcaGatewaysection (:61), registersAddOptions<GatewaySettings>().Bind(section).ValidateDataAnnotations().ValidateOnStart()(:63-66), adds GatewaySettingsValidator as anIValidateOptions<GatewaySettings>throughTryAddEnumerable(:70-71, becauseValidateDataAnnotationsdoes not recurse into the nested objects,:68-69), then callsWirewithsection.Get<GatewaySettings>() ?? new GatewaySettings()(:73). The eagerGet<T>is necessary because the named rate-limiter policies and the retry switch must be read at registration time, before anyIOptions<T>can be resolved.AddMmcaGateway(GatewaySettings settings)(:82-93): for a host composing its settings in code. It registers an explicitIOptions<GatewaySettings>singleton viaOptions.Create(settings)(:90) rather than aConfigure<T>callback, and the inline comment says why (:87-89):GatewaySettingsis init-only by design, since the filters close over it for the process lifetime, so the value has to be supplied whole rather than mutated into place.Wire(IReverseProxyBuilder, GatewaySettings)(:100-121), private, in this order:GatewaySettingsValidator.ThrowIfInvalid(settings)(:105) so both overloads fail fast at registration (a blank trace-header name would otherwise throw fromHeaders.Remove("")on every proxied request,:102-104);AddGatewayRoutePolicies(settings)on the service collection (:106);AddConnectRetryonly whensettings.Retry.Enabled(:108-111);AddOptions<KestrelServerOptions>().PostConfigure(GatewayHeaderEncoding.Apply)(:114), post-configured so it wraps whatever selector the host's ownConfigureKestrelset (:113);- then chains
AddConfigFilter<GatewayClusterProfileConfigFilter>()(:117),AddConfigFilter<GatewayHealthCheckDefaultsConfigFilter>()(:118),AddTransforms<GatewayTraceHeaderTransformProvider>()(:119) andAddTransforms<GatewayBypassHeaderTransformProvider>()(:120), the last of which removes the edge limiter's trusted-caller and synthetic-traffic headers from every proxied request (class doc:21-23).
AddConnectRetry(IServiceCollection)(:130-155), private. It collects the non-keyedIForwarderHttpClientFactoryregistrations by implementation type (:132-135). Anything other than YARP's ownForwarderHttpClientFactoryor the retrying factory, or a registration with no recoverable type (a factory delegate), throws anInvalidOperationExceptionnaming it and telling the operator to keep that factory and setMmcaGateway:Retry:Enabledto false, or remove it (:137-146). An existing retrying registration returns early, so a second call is a no-op (:148-151). Otherwise it addsTimeProvider.SystemwithTryAddSingleton(:153) and registers GatewayRetryForwarderHttpClientFactory as theIForwarderHttpClientFactory(:154); the doc notes this lands afterAddReverseProxy's ownTryAdd, so the last registration wins (:123-127).- The public method's
<remarks>carry the two rules a reader needs (:45-55): the two config filters are independent so their relative order carries no meaning, and this registers services and maps nothing, so the host still callsMapReverseProxy(), andUseRateLimiter()if it declared any named policies.
- Why it's built this way: one entry point rather than a list of opt-in calls means a gateway gets the whole coherent set or none of it, which is what keeps two consumer gateways behaving identically. The two overloads exist because configuration binding and in-code composition are both legitimate: tests and in-process hosts build settings directly, deployed gateways bind a section. Both funnel through
Wire, so there is exactly one list of what the kit installs. The retry is the one piece that replaces a YARP service rather than adding to it, which is whyAddConnectRetryrefuses to overwrite a factory the host composed itself instead of silently winning. The scopedCA1708suppression (:31-34) is the sameextension(T)analyzer false positive documented across the kit. - Where it's used: both consumer gateways chain it between
LoadFromConfigandAddServiceDiscoveryDestinationResolver:MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:172-174(with a summary of what it adds starting at:149) andMMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:159-161(summary starting at:134). Covered by AddMmcaGatewayTests, which asserts that one call registers both config filters and the transform provider (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/AddMmcaGatewayTests.cs:21), that the settings overload makes them resolvable (:43), that a disabled retry keeps YARP's factory (:107), that an enabled one registers the retrying factory (:122), and that an enabled retry beside a foreign factory throws namingMmcaGateway:Retry:Enabled(:148). - Caveats / not-in-source: the configuration overload reads the section twice, once through the options pipeline and once eagerly via
Get<T>. The eager read is the one the named rate-limiter policies and the retry switch come from, so a policy added, or the retry turned on, by a later configuration reload would not be registered. Nothing in source signals that; the overload's contract is a startup-time snapshot.
BrokerResilienceDefaults
MMCA.Common.Shared ·
MMCA.Common.Shared.Resilience·MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/BrokerResilienceDefaults.cs:25· Level 0 · class (static)
- What it is: four
staticproperties that are the single source of truth for the circuit breaker guarding the outbox's broker-publish call: the failure ratio that opens the circuit, the minimum number of attempts before that ratio is judged, the rolling window it is judged over, and how long the circuit stays open. - Depends on: nothing first-party, and nothing beyond
TimeSpan,doubleandint(BCL). Read by OutboxProcessor inMMCA.Common.Infrastructure. It is the deliberate sibling of HttpResilienceDefaults, and the class doc says so (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/BrokerResilienceDefaults.cs:5-7): both live in Shared "so the numbers are reviewable in one place rather than buried as literals inside a background service". - Concept introduced, a breaker that shortens discovery rather than protecting a dependency.
[Rubric §29, Resilience & Business Continuity],[Rubric §12, Performance & Scalability],[Rubric §15, Best Practices & Code Quality]. The usual argument for a circuit breaker is to spare a struggling dependency further load. This one is about the caller's wasted time, and the class doc lays out the arithmetic (:8-17): when the broker is down, every publish in a 50-row batch waits out its own transport timeout before failing, so one cycle can spend minutes doing nothing but timing out, and the retry loop queues the same wait again on the next cycle. The breaker turns the second and later attempts into an immediate rejection. Crucially nothing is lost by failing fast: a row the circuit rejected stays unprocessed, is re-leased for about theBreakDuration, and is retried on a later cycle, and the rejection costs that row no retry, because nothing reached the broker (:12-16). The breaker only changes how long the processor spends rediscovering that the broker is still down. The second half of the doc (:18-23) is the composition rule worth internalising: it is deliberately not paired with a retry strategy, because the outbox already owns retry (RetryCount, exponential backoff with jitter,MaxRetriesthen dead-letter), and a Polly retry inside a publish would multiply against that budget and make a row's effective attempt count an accident of two independent policies. - Walkthrough: four expression-bodied
staticproperties, each carrying its own justification.FailureRatio => 0.5(:33): half the publishes in the window must fail before the circuit opens. Half rather than a lower bar because a partially degraded broker still delivering half its messages is worth continuing to drain (:27-32), and only a clearly one-sided failure rate is evidence that further attempts this cycle are wasted.MinimumThroughput => 10(:41): the minimum publish attempts inside the window before the ratio is evaluated at all. Ten keeps a quiet host, where two attempts an hour is normal traffic, from opening the circuit on a single unlucky pair (:35-40).SamplingDuration => TimeSpan.FromSeconds(30)(:48): the rolling window. Thirty seconds is a few outbox cycles at the default polling interval, long enough that a batch's worth of attempts lands inside one window, short enough that a resolved outage ages out of the statistics quickly (:43-47).BreakDuration => TimeSpan.FromSeconds(15)(:57): how long the circuit stays open before one trial publish is allowed through. Deliberately short, because a rejected publish costs one outbox row a wait of about this long and no retry, not a customer-facing error, so recovery latency matters more here than protecting the broker from one probe (:50-56). The probe is the exception to "no retry": a failed probe did reach the broker, so it counts against the probed row's retry budget like any other failed publish (:54-55).
- Why it's built this way: expression-bodied
staticproperties rather than fields or constants, for the same reason as its sibling:TimeSpancannot be aconst, and a property is evaluated at call time instead of being inlined into the consuming assembly. Living inMMCA.Common.Sharedrather than next to the processor is what makes the four numbers reviewable as a policy: a reader sees the whole breaker in one screen, with each value's justification attached to the member it justifies, without opening a 900-line background service. ADR-009 is the governing decision: resilience is a framework invariant, not a per-call choice. - Where it's used: OutboxProcessor builds its publish pipeline from all four (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:1199-1210, values at:759-762), holds it in an instance field (:99) rather than a static one so parallel test processors cannot open each other's circuit (field doc comment:87-98), and logs an opening throughLogBrokerCircuitOpen(:664). The pipeline also excludesOperationCanceledExceptionfrom the handled set (:763-764), so a host shutdown cancelling a batch mid-flight is not counted as broker unhealthiness. Circuit openings surface as telemetry through theMMCA.Common.Brokermeter that Common.AspireExtensionssubscribes by literal name in itsFrameworkMeterNameslist (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:67). - Caveats / not-in-source: the four values are not configurable. There is no settings class and no configuration key, so tuning them is a framework release. The breaker guards the broker-publish call only, never the database calls, which the processor's field doc states outright (
OutboxProcessor.cs:118-123): a breaker on those would open exactly when the processor most needs to persist retry state.
HttpResilienceDefaults
MMCA.Common.Shared ·
MMCA.Common.Shared.Resilience·MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:12· Level 0 · class (static)
- What it is: eighteen
staticproperties that are the single source of truth for every resilience and socket-handler value the framework's HTTP-based clients use: the outbound-HTTP Polly window (attempt timeout, breaker window, total timeout, retry count), the client-sideRetry-Afterbudget, theSocketsHttpHandlerconnection hygiene (pool lifetime, idle timeout, keep-alive ping delay and timeout), and nineGrpc-prefixed values that are the east-west gRPC path's own timeouts, default unary-call deadline, breaker shape, concurrency ceiling and message-size limit (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:12-136). The class doc's own test of the design is that one file answers "what timeout does this client get" (:3-11). - Depends on: nothing first-party and nothing outside the BCL (
TimeSpan,int,double). All the arrows point at it: the Common.AspireExtensionsservice-defaults bootstrap (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:71-74,116-119), the gRPC server and typed-client DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:50-51,139-140,155-158,192-221), the gRPC client GrpcDefaultDeadlineInterceptor, which readsGrpcCallDeadline(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:47), the UI's AuthenticatedServiceBase andAPIClientregistration, and RetryAfterHeader, which readsMaxRetryAfterWait. - Concept introduced, the shared-constant class as a drift gate. Most of this chapter is about behavior; this type is about agreement. Packages that ship separately have to configure the same Polly and socket numbers, and nothing in the type system makes them match, so the codebase turns the numbers into a third artifact all of them are obliged to read.
[Rubric §29, Resilience & Business Continuity]assesses graceful degradation under partial failure, and the Polly values are the shape of that degradation: how long one attempt gets, how wide a window the breaker judges failures over, how long the caller waits in total, and how many times a single hop retries. ADR-009 is the governing decision, and its first clause is exactly this posture: resilience is a framework invariant, not a per-call choice.[Rubric §12, Performance & Scalability]shows up in the retry arithmetic below, because a retry policy is a load multiplier and multipliers compound per hop rather than adding.[Rubric §31, Cost/FinOps]is why the socket-handler block is here at all instead of being left at the BCL defaults: those four values are tuned for an idle Azure Container Apps replica (:42-59). And[Rubric §15, Best Practices & Code Quality]is the file's entire reason to exist: one edit moves every transport, so separately shipped packages cannot drift apart on a number. - Walkthrough: eighteen expression-bodied
staticproperties in four conceptual blocks.- The outbound-HTTP Polly window, the values handed to
AddStandardResilienceHandler:AttemptTimeout= 30 s (:15): the budget for one individual HTTP attempt.CircuitBreakerSamplingDuration= 60 s (:18): the rolling window the breaker computes its failure ratio over, so a burst is judged against a minute of traffic rather than against the last handful of calls. The gRPC path shares this one value.TotalRequestTimeout= 90 s (:21): the ceiling on the whole logical call including retries. The three numbers nest: a 30 s attempt inside a 90 s total leaves room for the initial attempt, the one retry, and the backoff between them.MaxRetryAttempts= 1 (:32): retries beyond the initial attempt, deliberately one, shared by the HTTP and gRPC paths, and carrying the longest comment in the file (:23-31).
- Why one retry, the part worth internalizing. The Blazor UI already owns user-facing retries: AuthenticatedServiceBase holds a static Polly policy that retries 3 times with exponential backoff (0.5 s, 1 s, 2 s) plus up to 250 ms of jitter on
HttpRequestExceptionor a retryable response status (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:25-41, schedule at:362-364, retry count at:413), which is up to 4 attempts per user action. If every hop underneath also spent a full retry budget, the attempts would multiply instead of adding (4 attempts at the UI over 4 at the next hop is already 16 requests). That is a retry storm, the failure mode where the load a struggling backend receives goes up precisely because it is failing. One transient-fault retry per hop still absorbs a dropped connection while bounding the multiplier. - The one retry never replays a mutation (
:29-30). The value itself is a count; what keeps it safe is how each reader scopes it. The HTTP service defaults calloptions.Retry.DisableFor(HttpMethod.Post, HttpMethod.Patch)(MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:83), because a timed-out attempt may still be running server-side and most hops carry no idempotency key, while GET, PUT, DELETE and the other idempotent verbs keep their retry (the call-site comment atExtensions.cs:76-82explains why it names two verbs instead of usingDisableForUnsafeHttpMethods, which would also switch off PUT and DELETE). The gRPC path cannot use a verb filter at all, since every gRPC call is a POST, so it setsRetry.ShouldHandleto retry only anHttpRequestExceptionwhoseHttpRequestErrorisNameResolutionError,ConnectionErrororSecureConnectionError: a failure to reach the service before the request was sent, such as an ACA replica rollover (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:196-208). An exception raised after the request frames were written is not retried, because the call may already have run. - The
Retry-Afterbudget:MaxRetryAfterWait= 8 s (:40), which equals the longest step of the UI backoff above. A429whoseRetry-Afterasks for more than this is not retried at all and surfaces to the caller at once, so a refused user action costs one request rather than a held connection waiting out the rest of a rate-limit window (:34-39). RetryAfterHeader applies the comparison; both the Aspire pipeline and the UI policy read it. - The socket-handler block, the values handed to
SocketsHttpHandler:PooledConnectionLifetime= 10 min (:46): a pooled connection is recycled on this cadence, which forces DNS to be re-resolved, so an ACA replica rollover is picked up without an app restart.PooledConnectionIdleTimeout= 5 min (:49): idle connections stay pooled that long, so low-traffic inter-service calls skip the TCP plus TLS handshake.KeepAlivePingDelay= 60 s (:56) andKeepAlivePingTimeout= 30 s (:59): the HTTP/2 keep-alive ping interval and the timeout waiting for its acknowledgement. The property doc states the pairing: the framework clients useHttpKeepAlivePingPolicy.WithActiveRequests, so a ping goes out only while a request is in flight (detecting a peer that dies mid-call) and an idle pooled connection is never pinged (:51-55).
- The east-west gRPC block, introduced by a comment that explains why it exists (
:61-72): an in-cluster gRPC call answers in well under a second (production p99 peaks below 800 ms), so the outbound-HTTP 30 s / 90 s budget would hold a caller on a hung peer for a minute and a half. The breaker shape is stated explicitly rather than left at library defaults because an east-west call addresses a peer directly and bypasses the Gateway's active health checks, so the breaker is the only thing that notices a peer going bad. The same comment closes on the deadline: a unary call whose caller set none getsGrpcCallDeadline, which sits below the attempt timeout, so a hung peer ends the call asDeadlineExceeded, and the breaker counts that expiry, and a failinggrpc-status, as a peer failure (:65-72).GrpcAttemptTimeout= 8 s (:79): about ten times the slowest measured east-west p99 (784 ms). The doc records the library constraint thatCircuitBreakerSamplingDurationmust stay at least twice this value (:74-78).GrpcCallDeadline= 5 s (:87): the deadline a typed gRPC client puts on a unary call whose caller set none, about six times the 784 ms p99 and belowGrpcAttemptTimeout, so the call's own deadline, which the peer also receives, ends a hung call before the Polly attempt timeout does. A deadline the caller sets always wins (:81-86).GrpcTotalRequestTimeout= 20 s (:90): two attempts plus the retry backoff.GrpcCircuitBreakerFailureRatio= 0.5 (:96): an in-cluster peer is healthy or hard-down, so a tighter ratio would trip on ordinary replica-rollover blips (:92-95).GrpcCircuitBreakerMinimumThroughput= 10 (:102): keeps a single failed call against a low-traffic service from opening the breaker (:98-101).GrpcCircuitBreakerBreakDuration= 10 s (:108): about one container-replica restart, so recovery is not gated on the breaker (:104-107).GrpcMaxConcurrentCalls= 1000 (:117): the most calls one typed gRPC client runs at once on this replica before the standard handler's concurrency limiter refuses the next. The limiter is always present in that handler; the doc's point is that its ceiling is a stated decision in this file rather than a library default nobody chose, overridable per client throughconfigureResilience(:110-116).GrpcConcurrentCallQueueLimit= 0 (:125): no call over the ceiling waits for a slot. A peer already serving the full ceiling from one replica is saturated, so a queued call would only spend its deadline waiting; refusing at once hands the failure back while the caller still has time to degrade (:118-124).GrpcMaxMessageSize= 4 MiB (:135): the largest message a typed client sends or receives and a gRPC service accepts or returns, the gRPC default receive size stated explicitly on both sides. An oversized reply fails asResourceExhaustedat the sender, where it is logged, rather than after crossing the network; the doc tells an edge that returns a whole data set in one message to page or stream instead of raising the limit (:127-134).
- The outbound-HTTP Polly window, the values handed to
- Why it's built this way:
- The layer rules chose the address.
MMCA.Common.Aspire(Hosting),MMCA.Common.Grpc(Presentation) and the UI packages sit where none may reference the others;Sharedis the one layer all are allowed to depend on, which the class doc states outright (:9-10). Both the Aspire and gRPC project files carry thatProjectReference, and the Aspire one names this type in a comment as the reason it is there at all (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/MMCA.Common.Aspire.csproj:57-59,MMCA.Common/Source/Presentation/MMCA.Common.Grpc/MMCA.Common.Grpc.csproj:21). - One file for both paths. The
Grpc-prefixed members give the east-west path deliberately tighter values than the outbound-HTTP ones, but they live in the same file beside the values they diverge from, and the comment introducing them says which values are the gRPC path's own and which are shared (:61-72). The divergence is therefore a stated decision a reviewer sees in one screen, not drift between packages. - Properties, not fields or constants.
TimeSpancannot be aconstat all, and an expression-bodiedstaticproperty is evaluated at call time rather than inlined into the consuming assembly the way aconst intis at compile time. The flat one-line-per-value shape also keeps the file readable as a ledger. BrokerResilienceDefaults is the same pattern applied to the outbox's broker-publish breaker.
- The layer rules chose the address.
- Where it's used: six framework readers.
AddServiceDefaultsroutes it throughConfigureHttpClientDefaults(Extensions.cs:58), so everyHttpClientin the process inherits it (per the comment opening atExtensions.cs:55): the four Polly values go intoAddStandardResilienceHandler(Extensions.cs:71-74), with the POST/PATCH retry opt-out at:83and aShouldHandlewrapper that refuses a 429 overMaxRetryAfterWaitthroughRetryAfterHeader.ExceedsRetryBudget(:92-97, the call at:94), and the four socket values go intoConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { ... })(Extensions.cs:114-122).AddGrpcServiceDefaults()sets the server'sMaxReceiveMessageSizeandMaxSendMessageSizetoGrpcMaxMessageSize, equal to the typed clients' limits, so a reply too large for the caller fails on the server where it is logged (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:48-51).AddTypedGrpcClient<TClient>(serviceName)sets the channel's message-size limits on both directions fromGrpcMaxMessageSize(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:135-141), re-applies the socket block (:152-160), and builds its resilience handler from theGrpc-prefixed members plus the sharedMaxRetryAttemptsandCircuitBreakerSamplingDuration(:190-212). It widens the breaker predicate through GrpcCircuitBreakerPredicate so a failinggrpc-statusor a deadline expiry counts (:214-216), sizes the handler's concurrency limiter fromGrpcMaxConcurrentCallsandGrpcConcurrentCallQueueLimit(:218-221), then invokes the caller's optionalconfigureResiliencecallback last so a consumer whose edge is legitimately slower can override any of them (:223-224, parameter at:117). It has to restate the socket values: forcing HTTP/2 means overriding the primary handler, which bypasses the wrapper the globalConfigureHttpClientDefaultsinstalled, so the connection-hygiene values must come from the same source of truth (the reasoning is spelled out atDependencyInjection.cs:143-151).- GrpcDefaultDeadlineInterceptor, registered on every typed client by
AddTypedGrpcClient(DependencyInjection.cs:125,132), gives a unary call with no deadlinenow + GrpcCallDeadlineand leaves a caller-set deadline and every streaming call alone (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:7-14,38-47). - AuthenticatedServiceBase does not retry a 429 over
MaxRetryAfterWait(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:290-293, doc at:269-271). - The UI's
APIClientregistration pinsHttpClient.TimeouttoTotalRequestTimeoutinstead of the BCL's 100 s, so the resilience budget rather than the transport decides when to give up (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:152-156).
- Caveats / not-in-source:
- Only the gRPC numbers are pinned by a test. The ADR-009 fitness function ResilienceHandlerTests asserts that
AddTypedGrpcClientwires its handler from these properties (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/ResilienceHandlerTests.cs:68-76), pins the gRPC literals,GrpcCallDeadlineincluded, and the shared retry and sampling values (:178-185), and checks the relationships between them: the call deadline belowGrpcAttemptTimeout(:192-195), the gRPC timeouts below the outbound-HTTP ones with the total covering every attempt (:267-270), and the sampling window at least twiceGrpcAttemptTimeout(:288). The same class asserts the concurrency limiter is sized fromGrpcMaxConcurrentCallsandGrpcConcurrentCallQueueLimit(:329-334) and pins them at 1000 and 0 (:354-357); DependencyInjectionTests checks the server and channel message-size limits againstGrpcMaxMessageSizeand pins it at 4 MiB (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/DependencyInjectionTests.cs:139-140,159-160,164-165). Runtime breaker behavior is covered separately by ResilienceCircuitBreakerFaultInjectionTests, which drives its own short values, and by GrpcCircuitBreakerFaultInjectionTests, which issuesGrpcCircuitBreakerMinimumThroughputfailing calls (agrpc-statusfailure or a hung peer cut by the deadline) and checks whether one more call still reaches the peer, and asserts the deadline sent on the wire falls withinGrpcCallDeadline(MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Resilience/GrpcCircuitBreakerFaultInjectionTests.cs:20-25,74-75). Not determinable from the cited tests: a test that pins the outbound-HTTPAttemptTimeout,TotalRequestTimeoutor socket values at the Aspire call site. - Two handler settings are still duplicated literals rather than centralised here:
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequestsandEnableMultipleHttp2Connections = true(Extensions.cs:120-121,DependencyInjection.cs:154,159). The policy is named in theKeepAlivePingDelaydoc (:51-55) but not held as a value here, and it matters when reading the ping values: underWithActiveRequestsan idle pooled connection is never pinged, so what decides how long it stays pooled isPooledConnectionIdleTimeout, notKeepAlivePingDelay(Extensions.cs:106-111). - The latency figures are measurements recorded in comments. The 784 ms p99 and "below 800 ms" (
:76,:82,:63) are production observations the source states but cannot demonstrate. Not determinable from source: whether they still hold for a given deployment. - The billing claim is a platform statement. The call-site comment says an idle connection sends nothing, which keeps an idle replica on idle-vCPU billing roughly 8x cheaper than active (
Extensions.cs:109-110); that describes how Azure Container Apps meters a replica. Not determinable from source: the code can set a ping interval, it cannot demonstrate how the platform bills it.
- Only the gRPC numbers are pinned by a test. The ADR-009 fitness function ResilienceHandlerTests asserts that
GatewayConnectRetryHandler
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Forwarding·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayConnectRetryHandler.cs:20· Level 1 · class (internal sealed partial)
- What it is: a
DelegatingHandleron the client YARP builds for each cluster that retries a request only when it provably never reached the destination: a body-less GET or HEAD whose attempt failed with a name resolution, connection or TLS failure (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayConnectRetryHandler.cs:5-15). - Depends on: GatewayRetrySettings (the attempt budget and the delay),
TimeProviderfor the delay, andILoggerfor one Warning per retry (:20-23). BCLDelegatingHandler,HttpRequestExceptionandHttpRequestError. Built by GatewayRetryForwarderHttpClientFactory, the only constructor of it in source. - Concept introduced, retry only what cannot have run.
[Rubric §29, Resilience & Business Continuity],[Rubric §11, Security]. A gateway that retries freely can turn one client action into two writes at the destination, because a timed-out or reset attempt may already have been processed. This handler draws the line at the one failure class that proves the destination never saw the request: the connection itself was not established. It is the same rule the gRPC typed client applies with itsShouldHandlefilter (see HttpResilienceDefaults), narrowed further at the edge to GET and HEAD with no body, "the only requests a replay cannot change the meaning of" (:35). A response of any status, any other exception, and a cancellation pass through untouched (:9). When the budget is spent the last exception propagates unchanged, so YARP still answers its usual 502 and the passive health policy still counts one failure (:12-14): the retry absorbs a replica rollover blip without hiding a destination that is really down. ADR-088 is the gateway charter this sits under. - Walkthrough:
SendAsync(:26-33): null-guards the request (:28), then routes a retryable request toSendWithRetryAsyncand everything else straight tobase.SendAsync(:30-32), so a POST pays nothing for the handler's presence.IsRetryable(:36-38):request.Content is nulland the method is GET or HEAD.IsConnectFailure(:41-44):HttpRequestErrorisNameResolutionError,ConnectionErrororSecureConnectionError.SendWithRetryAsync(:46-75): awhile (true)loop aroundbase.SendAsync(:53). Thecatchis an exception filter (:55-58) that matches only a connect failure, whileretries < settings.MaxRetryAttempts, and while the token is not cancelled; any exception the filter rejects is never caught, so it leaves the handler with its original stack. On a match it increments the count and logs (:60-67), then waitssettings.Delayon the injected clock throughTask.Delay(TimeSpan, TimeProvider, CancellationToken)when the delay is positive (:70-73).LogRetrying(:77-86): a source-generated[LoggerMessage]atWarning, naming the method, the destination authority (or(no destination)), theHttpRequestError, and the retry number out of the budget.
- Why it's built this way: an exception filter rather than catch-and-rethrow keeps the final failure byte-identical to what YARP would have seen without the handler, which is what lets the 502 mapping and the passive health count stay unchanged. The injected
TimeProvidermakes the delay testable without real waiting. - Where it's used: wrapped as the outermost handler of every cluster client by GatewayRetryForwarderHttpClientFactory (
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayRetryForwarderHttpClientFactory.cs:64-68), which exists only whenMmcaGateway:Retry:Enabledis true. Covered by GatewayConnectRetryHandlerTests (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/Forwarding/GatewayConnectRetryHandlerTests.cs). - Caveats / not-in-source: the retry is opt-in and off by default (
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:61-65), and neither the ADC nor the Store gateway'sappsettingssets aRetryblock, so in those apps the handler is not installed. Not determinable from source: whether a deployment enables it through environment configuration.
RetryAfterHeader
MMCA.Common.Shared ·
MMCA.Common.Shared.Resilience·MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:15· Level 1 · class (static)
- What it is: both ends of the
Retry-Aftercontract on a429 Too Many Requestsin one static class (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:15-79). The server half,Format(TimeSpan), turns a rejected rate-limit lease's hint into the header value; the client half,TryGetDelay(...)andExceedsRetryBudget(...), reads the header back and decides whether a retry is worth waiting for. - Depends on: HttpResilienceDefaults (
MaxRetryAfterWait), plus BCL only:HttpResponseMessage,HttpStatusCode,TimeProvider,CultureInfo. Read by the rate limiters'OnRejectedwriters inMMCA.Common.API,MMCA.Common.Aspire(GatewayRateLimitingExtensions) andMMCA.Common.UI.Web, and by the retry policies in Aspire'sExtensionsand the UI's AuthenticatedServiceBase. The linked RetryAfterRejection source carries a pinned copy of the server half, because theMMCA.Common.Gatewaypackage references no MMCA project (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:15-17). - Concept introduced, one rule for both sides of a throttle.
[Rubric §29, Resilience & Business Continuity],[Rubric §12, Performance & Scalability],[Rubric §15, Best Practices & Code Quality]. A rate limiter that answers 429 is telling the caller when to come back; a client that retries on its own schedule either hammers a limiter that has not reset or, if it honors a longRetry-After, holds a connection and a user waiting out a full window. The class doc names the fix (:6-14): the server rounding and the client budget live in one place, on pure BCL types, so the API, Aspire and UI.Web limiters and the UI and Aspire retry policies all apply one rule. The budget itself is a numeric policy and so lives with the other numbers in HttpResilienceDefaults; this class is the code that applies it. - Walkthrough:
Format(TimeSpan retryAfter)(:28-32):Math.Max(0d, Math.Ceiling(retryAfter.TotalSeconds)), cast tolongand printed invariantly (:30-31). Whole seconds, rounded up so a client never retries before the window has moved on, never negative. It takes the hint rather than the lease, and the doc gives the packaging reason (:17-25):System.Threading.RateLimitingships in the ASP.NET Core shared framework, which this package, also loaded by Blazor WebAssembly, does not reference. So eachOnRejectedcallback reads the lease metadata itself, and a lease without the hint (a concurrency-limiter rejection) sends the 429 with no header.TryGetDelay(HttpResponseMessage, TimeProvider, out TimeSpan)(:43-64): null-guards both arguments (:45-46), then readsresponse.Headers.RetryAfterin either form. A delta is clamped at zero (:49-53); a date is measured against the suppliedTimeProviderand a date already past becomes a zero delay (:55-60). No usable header returnsfalsewith a zero delay (:62-63). Taking aTimeProviderrather than reading the clock keeps the date branch deterministic under test.ExceedsRetryBudget(HttpResponseMessage?, TimeProvider)(:75-78):trueonly when the response is aTooManyRequests, carries a usableRetry-After, and that delay is greater thanHttpResilienceDefaults.MaxRetryAfterWait(:76-78). Anullresponse (an exception outcome), a 429 without the header, or one at or under the budget is not over budget (doc:66-74).
- Why it's built this way: the predicate returns "do not retry" rather than computing a wait, so each caller keeps its own retry engine and only adds one refusal to it. Aspire wraps the standard handler's existing
ShouldHandleand short-circuits tofalsewhen the budget is exceeded (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:92-97, reasoning at:76-79: the library's on-by-defaultShouldRetryAfterHeaderwould otherwise hold the request for up to a minute); the UI policy treats the same response as non-retryable (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:290-293). Keeping it in Shared is what lets the WebAssembly-loaded UI and the server-side hosts call the same method. - Where it's used: server half called directly by
MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:110; the rate limiters'OnRejectedwriter is the one linked internal sourceRetryAfterRejection, whoseFormatis a copy of this one because the Gateway package references no MMCA project (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:12-18), installed atMMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:451,MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:390,MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:215andMMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:82. Client half atExtensions.cs:94andAuthenticatedServiceBase.cs:290(budget check) andAuthenticatedServiceBase.cs:393(delay read). Covered by RetryAfterHeaderTests, and pinned against the linked copy by GatewayRetryAfterTests (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/RateLimiting/GatewayRetryAfterTests.cs:29). - Caveats / not-in-source: three of the four limiter packages each carry their own near-identical
WithRetryAfterHeaderwrapper aroundFormat(the Gateway copiesFormattoo); onlyFormatis shared, so the wrappers are kept alike by convention. The budget compares against one fixed 8 s value; a caller that wants a different ceiling has no parameter for it.
AdcOutageAppHostFixture
MMCA.ADC.AppHost.OutageTests ·
MMCA.ADC.AppHost.OutageTests·MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageAppHostFixture.cs:17· Level 3 · class (sealed)
- What it is: the collection fixture that boots the real ADC AppHost (SQL Server with four databases, Redis, RabbitMQ, MailDev, the four services, the gateway and the UI) for the dependency-outage tier, and names every resource and endpoint the outage tests address (
MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageAppHostFixture.cs:9-17). - Depends on: AppHostFixtureBase from
MMCA.Common.Testing.Aspire.Fixtures, closed overProjects.MMCA_ADC_AppHost(:17), and the precondition typesAppHostEnvironmentRequirementandAppHostReadinessBudget. Aspire's testing and application-model types (IDistributedApplicationTestingBuilder,ContainerResource,DotnetProjectResource,ContainerLifetimeAnnotation,EnvironmentCallbackAnnotation). Shared through AdcOutageCollection with AdcDependencyOutageTests. - Concept introduced, an outage test needs a stack it is allowed to break.
[Rubric §14, Testability],[Rubric §29, Resilience & Business Continuity]. Resilience claims (a cache or broker outage degrades health but keeps readiness, the outbox holds events until the broker returns) are only proven by stopping a real container under a running stack. That makes the fixture's main job safety: the AppHost declares its containers persistent so a developer keeps their data, and an outage test that stopped those would stop the developer's own containers.UseSessionLifetimeContainers(:112-128) moves every persistent container toContainerLifetime.Sessionthrough Aspire's ownWithLifetime(:114-117), then re-checks and throws if any still reads as persistent (:119-127), so the tier refuses to run rather than touch a developer's data. ADR-117 is the AppHost integration-test base this builds on. - Walkthrough:
- Ten
public constnames (:23-50):sql,redis,rabbitmq, the Identity databaseadc-identitywhose outbox carriesUserRegistered, theidentity,notificationandgatewayresources, Notification's cleartexthttpendpoint (it runsHttp1AndHttp2there, so the plain HTTP/1.1 probe client gets a real answer while the other services are h2c-only,:41-44), and the gateway'shttpsendpoint. Oneprivate constholds the full name of Aspire's experimental persistence annotation (:20). - The constructor clears
ADC_BROKER(:57) so the AppHost selects RabbitMQ (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:98); the doc gives the reason, the Service Bus emulator has no stop-and-start story this tier can assert (:52-56). The base restores the variable on dispose. RequiredEnvironment(:60-63) demands the opt-in variable, Docker and a developer certificate, so a missing precondition makes every test skip rather than hang.Budget(:69-70) allows twelve minutes to start and eight to turn healthy.ResourcesToAwait(:76-77) waits only on Identity, Notification and the gateway, each liveness-gated in the AppHost, so the wait cannot deadlock on a dependency an outage takes away (:72-75).ConfigureBuilder(:86-100) applies the session lifetimes (:90), then shortens the waits: Identity's outbox gets 20 retries, a 1 s backoff base, a 10 s lease and a 1 s polling interval (:92-96), and Notification's health report cache drops to one second (:98-99), each through anEnvironmentCallbackAnnotationadded byAddEnvironment(:154-155).IsPersistent(:137-148) checks both annotations Aspire consults: the lastContainerLifetimeAnnotation(:139), and the last persistence annotation, found by full type name and read by reflection because it is an experimental type; anyModeother thanSessioncounts as persistent (:144-147).ProjectNamed(:150-152) throws when the AppHost declares no project with the name.
- Ten
- Why it's built this way: reading the experimental annotation by name rather than by type avoids taking a compile-time dependency on an Aspire API that is still marked experimental, while still catching a container made persistent through the newer API (
:130-136). The tuned outbox values are what keep a broker-outage scenario inside the test budget: without them a parked event would wait out production backoff before draining. - Where it's used: the collection fixture of AdcOutageCollection, injected into AdcDependencyOutageTests, which reads its resource-name constants for every scenario.
- Caveats / not-in-source: the tier needs a container runtime and the opt-in variable, so it does not run in a default local test pass. The fixture asserts nothing about SQL Server outages; see AdcDependencyOutageTests for why that scenario is absent.
GatewayClusterProfileConfigFilter
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Configuration·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayClusterProfileConfigFilter.cs:25· Level 3 · class (sealed)
- What it is: a YARP
IProxyConfigFilterthat resolves each cluster's forwarder request profile from three sources, per property, and rewrites the cluster only when the resolution actually differs from what it already carried. - Depends on: GatewaySettings via
IOptions<T>and GatewayClusterRequestProfile. Externals:Yarp.ReverseProxy.Configuration.IProxyConfigFilter/ClusterConfig/RouteConfigandYarp.ReverseProxy.Forwarder.ForwarderRequestConfig, plusMicrosoft.Extensions.Options. Registered by GatewayReverseProxyExtensions. - Concept introduced, the proxy config filter as a defaults layer.
[Rubric §2, Design Patterns],[Rubric §29, Resilience, Reliability & Business Continuity]. YARP loads its route table from a config provider and then runs every registeredIProxyConfigFilterover each route and cluster before the table goes live. That hook is a decorator over configuration: it lets a package add behavior to a table it did not author and does not own, which is precisely what makes ADR-089's "the host owns the route table" rule compatible with a shared gateway package. Precedence is per property, not per block, and the class doc calls that out as the point of the type (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayClusterProfileConfigFilter.cs:9-17): a cluster that states one value keeps inheriting the rest. Per-block precedence would force a cluster that only needs a different timeout to also restate its version pair, which is the copy-paste this kit exists to remove. - Walkthrough:
- Primary constructor
(IOptions<GatewaySettings> options)(:25) with the settings snapshotted into a readonly field and null-guarded in the initialiser (:27). The filter closes over the value for the process lifetime, which is why the settings type is init-only. ConfigureClusterAsync(ClusterConfig, CancellationToken)(:33-43): null-guards (:35), callsResolve(:37), then returns the same instance when nothing changed andcluster with { HttpRequest = resolved }otherwise (:39-42).ConfigureRouteAsync(...)(:50-51): returns the route untouched. Routes carry no request profile; only clusters do (:45).Resolve(ClusterConfig)(:59-74),internalso the precedence rules are unit-testable through the filter's own type (:58): reads the cluster's ownHttpRequest(:62), looks up the per-cluster override by id (:64), takesClusterRequestDefaultsas the fallback (:65), and builds oneForwarderRequestConfigfrom four independent resolutions (:67-73).- The four private resolvers are one expression each and all read identically,
own ?? over ?? fallback:ResolveVersion(:82-87),ResolveVersionPolicy(:95-100),ResolveActivityTimeout(:107-111),ResolveAllowResponseBuffering(:118-122). The two version resolvers call the profile'sParseVersion/ParseVersionPolicywith the cluster id, so a bad string fails with the cluster named. IsSameAs(ForwarderRequestConfig?, ForwarderRequestConfig)(:131-142) is the churn guard and the most easily missed subtlety. It substitutesForwarderRequestConfig.Emptyfor an absent block (:136) because, as the inline comment says (:133-135), an absent block and an all-null block mean the same thing to the forwarder, so a cluster that had no profile and gained no defaults must come back untouched rather than acquiring an empty one. It then compares all four properties (:138-141).
- Primary constructor
- Why it's built this way: returning the identical instance when nothing changed is what keeps YARP's config-change detection quiet on every reload (
:124-127). A filter that always returned a new record would make YARP believe the topology changed on every configuration refresh and churn its route table for nothing. The second doc paragraph (:18-22) records the deliberate absence of a downgrade switch: a resolved HTTP/2 version pair is forwarded as stated, and dropping a cluster to HTTP/1.1 is a per-cluster decision expressed in its own profile. - Where it's used: registered by
AddMmcaGatewaythroughbuilder.AddConfigFilter<GatewayClusterProfileConfigFilter>()(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:117). In ADC it replaced the host's own hand-written filter of the same purpose (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:146-148). Covered by GatewayClusterProfileConfigFilterTests. - Caveats / not-in-source: the settings are captured once from
IOptions<T>, notIOptionsMonitor<T>, so a configuration reload changes the route table YARP reloads but not the defaults this filter applies. Restarting the host is the only way to move them.
GatewayHealthCheckDefaultsConfigFilter
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Configuration·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:17· Level 3 · class (sealed)
- What it is: the second YARP
IProxyConfigFilterin the kit. It fills in destination health-check defaults for clusters that declare none, so the proxy actually ejects a failing destination instead of continuing to balance onto it. - Depends on: GatewaySettings via
IOptions<T>, and through it GatewayHealthCheckDefaults with its GatewayPassiveHealthCheckDefaults and GatewayActiveHealthCheckDefaults children. Externals: YARP'sIProxyConfigFilter,ClusterConfig,HealthCheckConfig,PassiveHealthCheckConfig,ActiveHealthCheckConfig. Registered by GatewayReverseProxyExtensions. It shares the config-filter concept introduced by GatewayClusterProfileConfigFilter. - Concept introduced, additive-only defaulting.
[Rubric §29, Resilience & Business Continuity],[Rubric §34, Architecture Governance & Documentation]. The class doc states the invariant (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Configuration/GatewayHealthCheckDefaultsConfigFilter.cs:9-14): a cluster that already states aPassiveblock keeps it verbatim, and the same holds forActive. The filter never edits an operator's explicit choice, it only supplies one where the configuration was silent. That rule is what makes a defaults filter safe to add to an existing gateway: the worst case for a fully configured cluster is that the filter does nothing. Note it is per block, not per property: a cluster that states a partialPassiveblock does not have the missing properties filled in. - Walkthrough:
- Primary constructor and null-guarded settings field (
:17,:19), the same shape as its sibling filter. ConfigureClusterAsync(:25-47): reads the existingHealthCheck(:29), thenexisting?.Passive ?? BuildPassive()(:30) andexisting?.Active ?? BuildActive()(:31). If both resolved to the very same references the cluster already held, it returns the cluster unchanged (:33-36), the same churn guard the profile filter uses, expressed here withReferenceEquals. Otherwise it rebuildsHealthCheckwith the two blocks and carriesAvailableDestinationsPolicyacross unchanged (:44), so an operator's destination-selection choice survives the rewrite.ConfigureRouteAsync(:54-55): routes carry no health-check configuration; returns the route unchanged.BuildPassive()(:59-70): returns aPassiveHealthCheckConfigfrom the settings whenEnabled, elsenull. Returningnullmatters: it means "no passive block", which is different from a block withEnabled = false.BuildActive()(:74-87): the same shape, copyingPolicy,Interval,TimeoutandPath.
- Primary constructor and null-guarded settings field (
- Why it's built this way: two independent filters rather than one, so each owns exactly one YARP config property.
AddMmcaGateway's own doc records the consequence (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:46-50): the profile filter ownsHttpRequest, the health-check filter ownsHealthCheck, and neither reads what the other wrote, so their relative registration order carries no meaning. That is a real simplification: ordered filters would be a hidden coupling nobody would notice until someone reordered them. - Where it's used: registered by
AddMmcaGateway(GatewayReverseProxyExtensions.cs:118). With both consumer gateways enabling active probes in configuration, this filter is what turns that flag into a realActiveHealthCheckConfigon every cluster (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/appsettings.json:42-47,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/appsettings.json:26-31). Covered by GatewayHealthCheckDefaultsConfigFilterTests. - Caveats / not-in-source:
ReferenceEqualson the two blocks is a correct no-op check only becauseBuildPassive/BuildActiveconstruct new objects whenever they run at all, so a rebuilt block is never reference-equal to an existing one. It is an identity check, not an equivalence check, which is a deliberate difference from the profile filter's property-by-propertyIsSameAs.
GatewayRetryForwarderHttpClientFactory
MMCA.Common.Gateway ·
MMCA.Common.Gateway.Forwarding·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayRetryForwarderHttpClientFactory.cs:12· Level 3 · class (internal sealed)
- What it is: YARP's own
ForwarderHttpClientFactory, subclassed to install GatewayConnectRetryHandler as the outermost handler of every cluster client, so a retried attempt runs through the whole inner pipeline again (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/Forwarding/GatewayRetryForwarderHttpClientFactory.cs:7-11). - Depends on: YARP's
ForwarderHttpClientFactoryandForwarderHttpClientContext,ILoggerFactory/ILogger,IOptions<GatewaySettings>from which it keeps only the GatewayRetrySettings block, andTimeProvider(:14-18,:27-39). Registered by GatewayReverseProxyExtensions only when GatewaySettings.Retry.Enabledis true. - Concept introduced, extend the proxy's client factory rather than replace it.
[Rubric §2, Design Patterns],[Rubric §29, Resilience & Business Continuity]. YARP builds oneHttpMessageInvokerper cluster throughIForwarderHttpClientFactory, and its default factory already carries the socket and activity-tracking setup a proxy needs. Overriding the one hookWrapHandlerand delegating tobase.WrapHandlerfirst (:64-68) keeps all of that and adds a single decorator on the outside, so the retry sees each attempt exactly as YARP would have sent it. - Walkthrough:
- Three readonly fields: the retry logger, the retry settings and the clock (
:14,:16,:18). - The
publicconstructor (:27-39), the one the container uses: it passesbasea logger created forForwarderHttpClientFactorythroughCreateYarpLogger(:31,:70-75), so YARP's own factory logging keeps its category, and creates the retry logger under theGatewayConnectRetryHandlercategory (:36). - The
internalconstructor (:49-61) takes one non-genericILoggerand leaves YARP's factory logging off. It isinternalon purpose: the container must see exactly one public constructor, because a host that also registers a non-genericILoggerwould otherwise make the choice ambiguous (:41-45). WrapHandler(:64-68) returns a newGatewayConnectRetryHandlerwhoseInnerHandleris whateverbase.WrapHandlerproduced.
- Three readonly fields: the retry logger, the retry settings and the clock (
- Why it's built this way: registration is guarded so it can never silently displace a factory the host composed.
AddConnectRetry(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:130-155) collects every non-keyedIForwarderHttpClientFactoryregistration, throws anInvalidOperationExceptionnaming the foreign one (or "a factory delegate") when anything other than YARP's default or this type is present (:137-146), returns early when this type is already registered so a second call is idempotent (:148-151), and otherwise addsTimeProvider.SystemwithTryAddSingletonand this factory withAddSingleton(:153-154). The doc explains the plainAddSingleton: it runs afterAddReverseProxy's ownTryAdd, so the last registration wins (:123-126). - Where it's used: the private
Wirebody shared by bothAddMmcaGatewayoverloads callsAddConnectRetrywhensettings.Retry.Enabledis true (GatewayReverseProxyExtensions.cs:108-111). Covered by GatewayRetryForwarderHttpClientFactoryTests and by AddMmcaGatewayTests. - Caveats / not-in-source: the retry budget is bounded by validation attributes on the settings, one to three extra attempts (default one) and a delay of at most five seconds (default 200 ms) (
MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:67-73). Neither the ADC nor the Store gatewayappsettingsfile setsMmcaGateway:Retry, so this factory is not registered in either app as configured in source.
GatewayRoutePolicyExtensions
MMCA.Common.Gateway ·
MMCA.Common.Gateway.RateLimiting·MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:29· Level 3 · class (static)
- What it is: the registration of the named rate-limiter policies a YARP route references by name. One
extension(IServiceCollection)member,AddGatewayRoutePolicies(GatewaySettings), plus theinternal static Partitionhelper that decides what one request counts against and twointernal constitem keys it reads:TrustedInternalCallerItemKey, which exempts a request the edge limiter has already proven trusted, andTrustedCallerVisitorIpItemKey, which re-keys a trusted caller the edge limiter meters per visitor. - Depends on: GatewaySettings, GatewayRoutePolicySettings, the internal
RetryAfterRejection(one source file underMMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:19, compiled into this package by a linkedCompile Include,MMCA.Common/Source/Hosting/MMCA.Common.Gateway/MMCA.Common.Gateway.csproj:24) and RemainingWindowFixedWindowRateLimiter (fromMMCA.Common.RateLimiting). Externals:System.Threading.RateLimiting(RateLimitPartition,FixedWindowRateLimiterOptions,QueueProcessingOrder),Microsoft.AspNetCore.RateLimitingviaAddRateLimiter,HttpContext,System.Net.IPAddress,TimeProvider, andValidatorfrom data annotations. Called by GatewayReverseProxyExtensions. Coupled by string literals, not a reference, to GatewayRateLimitingExtensions, which writes theHttpContext.Itemsentries this type reads. - Concept introduced, named policies as an additive second limiter.
[Rubric §11, Security],[Rubric §17, DevOps & Deployment]. The doc's second paragraph is the operationally important part (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:17-23): these policies are additive to any global limiter the host installs (for exampleMMCA.Common.Aspire.Gateway.AddGatewayRateLimiting, which assignsRateLimiterOptions.GlobalLimiter). ASP.NET Core evaluates the global limiter and the route's named policy independently, so a request must satisfy both. Nothing here overwrites the global limiter, and the two packages stay independent of each other. The division of labour is also worth naming: YARP already knows how to attach a named policy to a route, what it cannot do is create one (:13-16), so this method exists purely to fill that gap without every gateway hand-writing anAddPolicyblock. - Walkthrough:
TrustedInternalCallerItemKey = "MMCA.Common.Gateway.TrustedInternalCaller"(:40),internal const. Its doc (:31-39) is the contract: the edge limiter inMMCA.Common.Aspire(AddGatewayRateLimiting) stamps thisHttpContext.Itemskey withtrueonce a request has proven the trusted-internal-caller secret, and because that limiter is the global limiter it runs before the route policy in the same middleware, so the stamp is present by the timePartitionruns. The two packages do not reference each other, so the literal is repeated on the Aspire side (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:67), which writes it at:242. A host without the edge limiter never stamps it, and every request is then limited as if the key did not exist.TrustedCallerVisitorIpItemKey = "MMCA.Common.Gateway.TrustedCallerVisitorIp"(:49),internal const. Its doc (:42-48): when the edge limiter meters a trusted internal caller per visitor, it stamps this key with the forwarded visitor'sIPAddressinstead (Aspire-side twin atGatewayRateLimitingExtensions.cs:76, written at:248).Partitionthen keys on that address rather than the connecting one, so a visitor's requests through a server-rendered UI host and the same visitor's direct requests share one window.AddGatewayRoutePolicies(GatewaySettings settings)(:61-95) inside theextension(IServiceCollection services)block (:51).- Null-guards both the collection and the settings (
:63-64), then short-circuits when no policies are declared (:66-69), so a gateway with no named policies never callsAddRateLimiterat all. - Validates every policy up front with
Validator.ValidateObject(policy, new ValidationContext(policy), validateAllProperties: true)(:71-74). This runs before any registration, so an out-of-rangePermitLimitthrows at registration rather than at the first throttled request. The doc names the governing decision (:56-57), ADR-070 fail-fast. - Calls
AddRateLimiter(:76), setsRejectionStatusCode = StatusCodes.Status429TooManyRequests(:78), and wraps the existingOnRejectedcallback withRetryAfterRejection.WithRetryAfterHeader(options.OnRejected)(:82), so a 429 from a named policy carries aRetry-Afterheader in whole seconds whenever the rejecting lease has a retry-after hint (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42-52). The comment above it (:80-81) records why it chains rather than assigns:OnRejectedis one shared slot onRateLimiterOptions, and the edge limiter inMMCA.Common.Aspireinstalls the same header writer (the same linked source,MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:390), so each registration wraps the one before it. It then registers oneoptions.AddPolicy<string>(name, ...)per entry (:92), skipping blank names (:86-89).var captured = policy(:91) is the loop-variable capture guard that keeps each registered delegate bound to its own policy.
- Null-guards both the collection and the settings (
Partition(HttpContext, GatewayRoutePolicySettings, TimeProvider? timeProvider = null)(:113-155),internalso the partition-key selection is unit-testable (:112). The optional clock (:116, doc:108-110) only feeds the window's remaining-time hint;null, the production path, is the system clock. After its null guards (:118-119) it picks the client address in three steps (:121-134):- a visitor address under
TrustedCallerVisitorIpItemKeywins: the trusted caller is metered on the same key the visitor's own request takes (:122-126); - otherwise a
trueunderTrustedInternalCallerItemKeyreturnsRateLimitPartition.GetNoLimiter(GatewayRoutePolicySettings.GlobalPartitionKey)(:127-130). The doc gives the reason (:101-103): this is the same exemption the edge limiter grants, and a server-rendered UI's sign-ins all leave from one address, so without it they would share one per-IP bucket; - otherwise
httpContext.Connection.RemoteIpAddress(:131-134). - With the address chosen, it asks the policy for the key (
:136) and branches (:143-154). Anullkey yieldsRateLimitPartition.GetNoLimiter(...), the fail-open path GatewayRoutePolicySettings explains; otherwiseRateLimitPartition.Get(key, ...)builds a RemainingWindowFixedWindowRateLimiter overFixedWindowRateLimiterOptionsfrom the policy'sPermitLimit,WindowSecondsandQueueLimit, withQueueProcessingOrder.OldestFirstandAutoReplenishment = false(:145-154).
- a visitor address under
- Why it's built this way: a fixed window is the only limiter shape exposed, which keeps the configuration surface two numbers wide. The comment above the return (
:138-142) explains the wrapper: the framework'sGetFixedWindowLimiteralways reports the whole window as itsRetry-After, so the wrapper reports the time actually left in it.AutoReplenishmentis off because the wrapper forces it and because the middleware's partitioned endpoint limiter replenishes every partition on its own timer, whichGetFixedWindowLimiteralready relied on by turning the flag off itself.RejectionStatusCodeis set here rather than left to the host so a throttled request is a 429 regardless of which package installed the limiter, and theRetry-Afterwriter is chained in for the same reason: the caller learns when to come back whichever limiter refused it. The class carries the same scopedCA1708suppression as the otherextension(T)classes in the kit (:25-28). - Where it's used: called from
GatewayReverseProxyExtensions.Wire(MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewayReverseProxyExtensions.cs:106), so bothAddMmcaGatewayoverloads register it. In the consumer gateways the resultingauth-tightpolicy is enforced by the singleapp.UseGatewayRateLimiting()call that also serves the global edge limiter (MMCA.ADC/Source/Hosts/MMCA.ADC.Gateway/Program.cs:203with the explanation just above it at:201,MMCA.Store/Source/Hosts/MMCA.Store.Gateway/Program.cs:191). Covered by GatewayRoutePolicyTests and GatewayRoutePolicyRetryAfterTests. - Caveats / not-in-source:
AddRateLimiteris additive, so calling it from both this method and a host's own global-limiter registration is safe, but nothing here detects a host that declared policies and then forgotUseRateLimiter(). In that case the policies are registered and simply never applied, with no error. Both item keys rest on two copies of one string literal each (GatewayRoutePolicyExtensions.cs:40and:49,GatewayRateLimitingExtensions.cs:67and:76); source shows nothing that ties them together at compile time, so a rename on one side would silently end the exemption (or the per-visitor keying) on the named policies while the edge limiter kept applying it.
AdcOutageCollection
MMCA.ADC.AppHost.OutageTests ·
MMCA.ADC.AppHost.OutageTests·MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageCollection.cs:9· Level 4 · class (sealed)
- What it is: the xUnit collection definition that shares one AdcOutageAppHostFixture across the outage tests, with parallelization off (
MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcOutageCollection.cs:8-9). - Depends on: xUnit's
ICollectionFixture<T>and[CollectionDefinition], closed over AdcOutageAppHostFixture. - Concept introduced, serialize what shares a breakable dependency.
[Rubric §14, Testability]. An outage test stops a container the whole stack shares, so nothing else may run against the AppHost while a dependency is down (:3-7).DisableParallelization = true(:8) is what turns that rule into a guarantee rather than a hope. - Walkthrough:
[CollectionDefinition(Name, DisableParallelization = true)](:8) on an empty sealed class implementingICollectionFixture<AdcOutageAppHostFixture>(:9), with one constant,Name = "adc-outage"(:12), that test classes join with[Collection]. - Why it's built this way: a named constant rather than a repeated string keeps the definition and every
[Collection]attribute in step at compile time. One fixture per collection means the AppHost boots once for the whole tier, which matters given its twelve-minute start budget. - Where it's used:
[Collection(AdcOutageCollection.Name)]on AdcDependencyOutageTests (MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcDependencyOutageTests.cs:21). - Caveats / not-in-source: none beyond the fixture's own preconditions.
AdcDependencyOutageTests
MMCA.ADC.AppHost.OutageTests ·
MMCA.ADC.AppHost.OutageTests·MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcDependencyOutageTests.cs:22· Level 5 · class (sealed)
- What it is: ADC's dependency-outage tier: two scenarios that stop a real container under the running ADC stack and assert what Notification's probes answer while it is down and after it returns (
MMCA.ADC/Tests/Integration/MMCA.ADC.AppHost.OutageTests/AdcDependencyOutageTests.cs:7-13). - Depends on: the shipped DependencyOutageTestBase<TFixture> (
:22-23) with DependencyOutageScenario and DependencyOutageKind fromMMCA.Common.Testing.Aspire.Outages; AdcOutageAppHostFixture through AdcOutageCollection (:21); AwesomeAssertions. - Concept introduced, degradation as an asserted contract.
[Rubric §29, Resilience & Business Continuity],[Rubric §14, Testability]. Each scenario opens with the base's baseline (both probes 200), stops one container, and asserts that a cache or broker outage fails health but keeps readiness, because those checks are tagged optional, then starts it again and asserts recovery (:8-12). The broker scenario adds the outbox half of the story: an event raised during the outage must be parked, then drained once the broker is back. The remarks record the deliberate gap: there is no SQL Server outage scenario, because an Aspire start recreates a stopped container with empty databases and the services migrate only at start, so a "recovered" readiness would be asserted on services whose schema is gone (:14-18). - Walkthrough:
RedisOutage_KeepsReadiness_FailsHealth(:25-42): skips with the fixture's reason when it is unavailable (:28-31), then runs aCachescenario againstredis, probingnotificationon itshttpendpoint (:33-39).BrokerOutage_KeepsReadiness_AndIdentityOutboxDrains(:44-63): aBrokerscenario againstrabbitmq, withOutboxDatabaseResourceNameset toadc-identityandDuringOutage = RegisterOneAttendeeAsync(:52-60).RegisterOneAttendeeAsync(:73-97): a client on the gateway'shttpsendpoint (:75-77) posts a fresh registration to/Auth/registerwithapi-version: 1.0(:79-90) and asserts201 Created, because registration writes to Identity's database, which is up during a broker outage (:94-96). That commit parks aUserRegisteredevent in Identity's outbox, which the base asserts pending and then drained (:65-70). The body is the shape the conference-day load test sends (:68-69).
- Why it's built this way: the scenarios are data handed to a shipped base, so the orchestration (baseline, stop, probe, start, recover) lives once in Common and the ADC class only says which container, which service and what to do mid-outage. Going through the gateway for the registration exercises the real edge path rather than calling Identity directly.
- Where it's used: test class; no references outside the defining file.
- Caveats / not-in-source: opt-in and container-dependent through its fixture, so it skips in a default run. Not determinable from source: how often CI runs this tier.
⬅ Common UI Framework (MudBlazor components, theme, base pages) • Index • ADC Conference - Domain Model & Module Contracts ➡