↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Onboarding guide

13. gRPC & Inter-Service Contracts

What this chapter is about. Once the ADC modules stopped sharing a process and became four separate service hosts (Identity, Conference, Engagement, Notification), the in-process method calls between them had to cross a network boundary. Asynchronous, fire-and-forget flows go over the broker via the outbox (see IMessageBus and ADR-003); but some calls need a synchronous answer: "is this session valid to bookmark?", "how many bookmarks does this session have?", "give me the user ids of every attendee", "is this event live right now?". This chapter is the synchronous transport boundary: a tiny, transport-only package (MMCA.Common.Grpc) plus a per-consumer *.Contracts convention that together let a module be lifted out of the monolith and called over gRPC without rewriting a line of application or domain code. The governing decision is ADR-007 (gRPC extraction), with the supporting topology in ADR-008 (YARP service mesh), auth in ADR-004 (JWKS dual-fetch), the executable contract governance in ADR-015, and the concrete Kestrel/HTTP-2 transport profiles in ADR-012. [Rubric §7, Microservices Readiness] is the headline lens here: it assesses whether modules can genuinely be extracted, with explicit, versioned contracts and transport kept at the edge. [Rubric §9, API & Contract Design] is the second, because the goal is that an error looks the same to a caller whether the answer came from an in-process object or a wire hop.

The cast of types in this group is small, and all but one lives in MMCA.Common.Grpc: a transport-only package that, per Clean Architecture, depends on Shared only (it must never couple to Domain, Application, or Infrastructure; see primer §1). There are twenty, and seven of them carry the core transport: DependencyInjection (the registration surface, AddGrpcServiceDefaults() server-side and AddTypedGrpcClient<TClient>(serviceName) client-side, at MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:27), GrpcResultExceptionInterceptor (server-side: turns a failed Result into an RpcException), JwtForwardingClientInterceptor (client-side: forwards the caller's bearer token downstream), ResultGrpcExtensions (the whole Result to RpcException mapping, in both directions), ResultFailureException (the in-band carrier between a service method and that interceptor), GrpcWireFormat (the shared string encodings for timestamps and money, at MMCA.Common/Source/Presentation/MMCA.Common.Grpc/GrpcWireFormat.cs:30), and the lone MMCA.Common.Shared marker ServiceContractAttribute (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ServiceContractAttribute.cs:23), which tags the wire surface of an extracted service. Three more harden every typed client's call path: GrpcDefaultDeadlineInterceptor (a default deadline for a unary call that sets none), GrpcDeadlineObserverHandler (marks a request its own deadline ended), and GrpcCircuitBreakerPredicate (teaches the circuit breaker what a failing gRPC peer looks like). The other ten form the service-token family for calls that have no user token to forward, nine in MMCA.Common.Grpc.Authentication plus one client interceptor: IServiceTokenProvider and its ServiceTokenProvider (with the private CachedToken record), ServiceTokenSettings, ServiceTokenDefaults, the two registration surfaces ServiceTokenServiceCollectionExtensions (with the private DefaultSchemeGuard marker) and ServiceTokenHttpClientBuilderExtensions, ServiceTokenClientInterceptor, and the receiving-side check ServiceCallerClaimsPrincipalExtensions. The concrete .proto definitions and the typed clients they generate do not live here: they live in each consumer's *.Contracts project (ADC's MMCA.ADC.Conference.Contracts, .Engagement.Contracts, .Identity.Contracts, .Notification.Contracts), which this package exists to wire up.

The contract-package convention. Anything whose project name ends in .Contracts is special: Directory.Build.props in all three consuming repos auto-pulls Grpc.Tools, Google.Protobuf, and Grpc.Net.ClientFactory, and compiles every Protos/**/*.proto with GrpcServices="Both" (MMCA.ADC/Directory.Build.props:114-122, mirrored at MMCA.Common/Directory.Build.props:150-157), so a single shared package produces both the server base class and the client stub. The deliberate design choice (ADR-007) is that each .Contracts project also ships a hand-written gRPC adapter that implements the same C# interface the modules already used in-process. Concretely: Conference's code depends on the interface IBookmarkCountService (declared in MMCA.ADC.Engagement.Shared and marked [ServiceContract] at MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/UserSessionBookmarks/IBookmarkCountService.cs:10); the in-process implementation lives in Engagement; the cross-process implementation is BookmarkCountServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Contracts/BookmarkCountServiceGrpcAdapter.cs:14), an internal sealed class holding a generated BookmarkCountServiceClient that translates an interface call into a gRPC call and the proto response back into the C# return type (BookmarkCountServiceGrpcAdapter.cs:22-29). Because both the in-process service and the adapter satisfy the identical interface, swapping monolith for microservice is a registration change, not a rewrite, which is the whole point of the boundary. An adapter carries no deadline of its own: the GrpcDefaultDeadlineInterceptor that every typed client gets gives a unary call with no deadline the five-second HttpResilienceDefaults.GrpcCallDeadline (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:42-47, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:87), below the 8-second attempt timeout, so a hung peer (as opposed to a refusing one) fails fast instead of stalling the caller's inline request. A deadline the caller set wins, and streaming calls are left alone (GrpcDefaultDeadlineInterceptor.cs:7-13). An edge that needs a tighter budget sets its own, as the best-effort live-channel push does with a two-second PushDeadline (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/LiveChannelPublisherGrpcAdapter.cs:35, :49).

How the swap actually happens at the composition root. Each .Contracts project also ships an extension(IServiceCollection) DI helper, for example AddConferenceSessionValidationClient() (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Contracts/DependencyInjection.cs:37), that does two things: (1) calls Common's AddTypedGrpcClient<TClient>(serviceName) to register the generated gRPC client against the named service (DependencyInjection.cs:39), and (2) calls services.Replace(ServiceDescriptor.Scoped<...>()), not TryAdd, to overwrite whatever ISessionBookmarkValidationService is already in the container with the gRPC adapter (DependencyInjection.cs:42). The Replace is deliberate and documented in place (DependencyInjection.cs:27-32, :41): the adapter wins over any registration made before the call. In an extracted host it is in practice the only registration, because that host names only its own module to ModuleLoader, so the peer module and its in-process implementation are never discovered there. Either way, after the call the resolved interface is always the gRPC adapter pointing at the extracted peer. Ordering is not left to chance: each host registers these helpers as steps of the ConfigurePipeline callback it hands to AddMmcaServiceHost, ConfigurePipeline = (pipeline, moduleHost) => pipeline.Register(moduleHost.RegisterModules).Register(s => s.AddConferenceSessionValidationClient())... (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:225-231), which the shared host forwards into services.AddMmcaApplicationPipeline(...) (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:158), so module discovery runs first and the client replacements run after it, in declaration order.

Result over the wire, the outbound half. The codebase's pervasive Result pattern (errors as values, not exceptions; see primer §2) survives the hop intact. On the server, a gRPC service implementation calls the inner C# service, gets back a Result, and calls result.ThrowIfFailure() (from ResultGrpcExtensions, MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:76); see SessionBookmarksGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Grpc/SessionBookmarksGrpcService.cs:40). That guard throws a ResultFailureException (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Exceptions/ResultFailureException.cs:16) carrying the Error list (ResultFailureException.cs:35, :39). The GrpcResultExceptionInterceptor registered by AddGrpcServiceDefaults() catches it for all four server call shapes (unary, server-, client-, and duplex-streaming, at GrpcResultExceptionInterceptor.cs:22, :42, :63, :83), logs it through a source-generated LoggerMessage (GrpcResultExceptionInterceptor.cs:140), and rethrows errors.ToRpcException(). That encoder (ResultGrpcExtensions.cs:105) picks the status from the most severe error rather than the first, via ErrorTypeSeverity.MostSevere (ResultGrpcExtensions.cs:110), so an aggregate built by Result.Combine cannot be downgraded by error ordering; the ErrorType to StatusCode table itself is a FrozenDictionary (ResultGrpcExtensions.cs:41-54) that mirrors the HTTP mapping in ErrorHttpMapping used by ApiControllerBase. Every error is then serialized into the trailers as error-{i}-code, -message, -type, and (when non-empty) -source and -target entries (ResultGrpcExtensions.cs:118-133). Because gRPC text metadata is printable ASCII only, the message, source, and target values are percent-encoded as UTF-8 for every character outside that range and for % itself (ResultGrpcExtensions.cs:294-321), so an accented name or a newline in a validation message cannot break the trailer at the transport; a value that is already plain printable ASCII goes on the wire unchanged (ResultGrpcExtensions.cs:296-299).

Result over the wire, the inbound half. The same class owns the decoder, so the round trip is closed by framework code rather than by hand-rolled parsing in each adapter. Metadata.ToErrors() (ResultGrpcExtensions.cs:159) walks error-{i}-code from index zero and stops at the first gap, matching the contiguous layout the encoder writes, percent-decodes the message, source, and target (ResultGrpcExtensions.cs:177-180, :323-324), and an unrecognized error-{i}-type falls back to ErrorType.Unexpected instead of throwing (ResultGrpcExtensions.cs:285-288), so a newer peer that adds an error type cannot break an older client. On top of that, RpcException.ToResult(cancellationToken) and ToResult<T>(cancellationToken) (ResultGrpcExtensions.cs:212 and :238) hand the caller a failed Result directly. The caller's own cancellation is not a failure: a Cancelled status while the passed token is cancelled is rethrown as OperationCanceledException (ResultGrpcExtensions.cs:252-255). Otherwise structured trailers win when present, and a pure transport fault that carries none (a reset connection, an exceeded deadline, an open breaker) degrades to a single error coded Grpc.{StatusCode} and stamped with the calling member's name via [CallerMemberName] (ResultGrpcExtensions.cs:257-258, :363-372). Its type splits on the status: Unauthenticated, PermissionDenied, and Unimplemented are faults in this service's own credentials, configuration, or deployment that waiting will not cure, so they become ErrorType.Unexpected (HTTP 500 at the edge, where the failure alerts watch); every other status means the peer was down, slow, or unreachable, so it becomes ErrorType.Unavailable (HTTP 503, where a later retry can succeed). Neither is a 400-family type that would blame the caller, and the message is fixed text rather than the RPC status detail, which can name internal hosts and ports (ResultGrpcExtensions.cs:338-379). A client adapter's catch block is therefore one line: return ex.ToResult(cancellationToken); (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Contracts/SessionBookmarkValidationServiceGrpcAdapter.cs:51). That symmetry, one error model over two transports, is the [Rubric §9, API & Contract Design] and [Rubric §29, Resilience, Reliability & Business Continuity] story: error translation is a pipeline concern, written once in the interceptor and its extension pair, not repeated in every method. One sharp edge is documented in the interceptor itself (GrpcResultExceptionInterceptor.cs:103-138): a ResultFailureException built from a message-only constructor carries no errors, so the shared encoder would answer the placeholder detail "Unspecified failure"; the interceptor keeps StatusCode.Internal for that case and substitutes the real message (plus any inner exception's message, GrpcResultExceptionInterceptor.cs:133-137) rather than synthesizing a caller-blaming error, which would map to InvalidArgument.

Values protobuf has no lossless scalar for. Errors are not the only thing both ends must agree on byte for byte. GrpcWireFormat is a static class that writes the two encodings the hand-written services and adapters share, so the format lives in one place rather than in each .proto mapping. Timestamps travel as ISO 8601 round-trip ("O") strings: FormatUtc stamps DateTimeKind.Utc before formatting (GrpcWireFormat.cs:42-43), because SQL Server hands columns back as Unspecified and "O" would otherwise drop the Z, and ParseUtc reads either form, with or without the marker, as UTC on the same instant through AssumeUniversal | AdjustToUniversal (GrpcWireFormat.cs:37, :61-62), which keeps a rolling deploy with an older replica on the other end working. An optional timestamp maps "absent" to the empty string, since proto3 has no null string (FormatUtcOrEmpty / ParseUtcOrNull, GrpcWireFormat.cs:51-52, :71-72). Money travels as an invariant-culture decimal string (GrpcWireFormat.cs:77, :83-84), so a price is never rounded through a double and never misread under a comma-decimal locale. The Parse* methods throw FormatException on a corrupt peer payload, treating it as a fault; an adapter that wants to map a malformed amount to its own answer uses TryParseDecimal instead (GrpcWireFormat.cs:93-94). In ADC the data-subject export edges are the users: Engagement's server writes FormatUtc (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Grpc/UserEngagementExportGrpcService.cs:62) and its adapter reads ParseUtc (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Contracts/UserEngagementExportServiceGrpcAdapter.cs:40), and Notification pairs FormatUtcOrEmpty with ParseUtcOrNull for a notification's read time (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/UserNotificationExportGrpcService.cs:60, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/UserNotificationExportServiceGrpcAdapter.cs:38).

Auth and the network shape. Every typed client wired by AddTypedGrpcClient<TClient> (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:115) gets a JwtForwardingClientInterceptor (DependencyInjection.cs:124, :120) that copies the inbound Authorization header off the current HttpContext onto the outgoing call's metadata, so the caller's JWT rides along to the downstream service and distributed authorization works without each handler threading a token by hand. When the inbound request authenticated without an Authorization header (a SignalR hub connection passes its token as ?access_token=), it forwards the token saved on the authentication ticket instead, read as access_token and rebuilt as a Bearer value, while a header that is present always wins (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/JwtForwardingClientInterceptor.cs:151-159). It forwards nothing outside an HTTP request, for example in a background processor (JwtForwardingClientInterceptor.cs:146-149), and it refuses to overwrite or duplicate an Authorization entry a caller or prior interceptor already set (JwtForwardingClientInterceptor.cs:114-117, :133-136). It forwards only the user's token (JwtForwardingClientInterceptor.cs:28-31); the service-token path below covers a call that has none. The downstream service validates that forwarded token against the issuer's JWKS, not a shared secret (ADR-004; see RsaJwksProvider / IJwksProvider). The server half also sets EnableDetailedErrors = false and adds server reflection (DependencyInjection.cs:46, :48), so tools like grpcurl can introspect the schema without exception detail leaking to callers. [Rubric §11, Security] is touched three times over here: federated JWT validation of user tokens rather than a shared secret, token forwarding that never widens the caller's authority, and detailed errors kept off.

Calls with no user token: service tokens, the calling side. Forwarding covers a call made inside a user's request; a background processor, or an anonymous request that fans out internally, has no user token, and its call would otherwise arrive unauthenticated (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/IServiceTokenProvider.cs:3-8). The answer is a self-minted service token configured by ServiceTokenSettings (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenSettings.cs:18), bound from the one Grpc:ServiceToken section (ServiceTokenSettings.cs:21) by both halves, so the key, issuer, and audience cannot drift between caller and receiver within a deployment. Its Validate fails the host on start unless the Base64 SigningKey decodes to at least 32 bytes, ServiceName is set, and LifetimeMinutes lies between 2 and 60, two being the floor because the provider replaces a token in its last 60 seconds and a one-minute token would never be reused (ServiceTokenSettings.cs:24, :26-33, :65-96); Issuer defaults to mmca-service, Audience to internal-grpc (which must differ from the user tokens' audience, since the audience is what keeps a service token out of the user scheme), and the lifetime to 5 minutes (ServiceTokenSettings.cs:48-57). AddServiceTokenClient(configuration) (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenServiceCollectionExtensions.cs:38) registers ServiceTokenProvider as the singleton IServiceTokenProvider (ServiceTokenServiceCollectionExtensions.cs:43-44), whose GetToken() (IServiceTokenProvider.cs:15) returns an HS256 JWT with sub and svc naming this service and a fresh jti (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenProvider.cs:85-91). The provider caches it as a private CachedToken record (ServiceTokenProvider.cs:105) and replaces it once 60 seconds or less remain (ServiceTokenProvider.cs:26, :76-77), so a token that could expire mid-call is never handed out: readers take the published token without locking, and only a caller inside that refresh window takes the lock and mints, once for everyone waiting (ServiceTokenProvider.cs:52-74). Registering the provider sends nothing by itself. A typed client opts in by chaining .WithServiceToken() from ServiceTokenHttpClientBuilderExtensions onto AddTypedGrpcClient<TClient> (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenHttpClientBuilderExtensions.cs:28), which adds the ServiceTokenClientInterceptor to that client alone (ServiceTokenHttpClientBuilderExtensions.cs:34). Precedence is the user's token, then the service token: the interceptor attaches nothing when the call already carries Authorization or the ambient request holds a user token, and it decides that with the forwarding interceptor's own helpers, so the result does not depend on which of the two runs first (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/ServiceTokenClientInterceptor.cs:85-94, JwtForwardingClientInterceptor.cs:108, :133, :144). It is per client and never global because a server that does not validate service tokens would have to reject one, and a default JwtBearer scheme first fetches its OIDC metadata to do so, which can stall a call while that endpoint is still starting (ServiceTokenClientInterceptor.cs:13-17).

Service tokens, the receiving side. AddServiceTokenAuthentication(configuration) (ServiceTokenServiceCollectionExtensions.cs:69) adds a JwtBearer scheme named by ServiceTokenDefaults.AuthenticationScheme, "ServiceToken" (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenDefaults.cs:16; ServiceTokenServiceCollectionExtensions.cs:76-78). It validates issuer, audience, lifetime, and signature against the shared key, pins the algorithm to HS256 so an algorithm-confusion swap cannot pass, with an explicit 30-second clock skew instead of the library's five minutes so a five-minute token is not honored for ten (ServiceTokenServiceCollectionExtensions.cs:26, :143-164), and fails any token that validates without the svc claim (ServiceTokenDefaults.cs:35; ServiceTokenServiceCollectionExtensions.cs:170-176). It also adds two policies. InternalCaller (ServiceTokenDefaults.cs:22) admits an authenticated caller from either the user scheme or the service scheme (ServiceTokenServiceCollectionExtensions.cs:91-93); ServiceCaller (ServiceTokenDefaults.cs:29) evaluates the service scheme alone and requires the svc claim, so an end-user token is refused outright (ServiceTokenServiceCollectionExtensions.cs:94-97). The service scheme is never made the default, so a service token satisfies only an endpoint that names one of those policies, and a plain [Authorize] endpoint still authenticates users alone. Rather than document the trap, the registration fails the host at startup when the service scheme would end up the default, explicitly or as the lone registered scheme ASP.NET Core promotes, through the start-time validation of the private DefaultSchemeGuard marker options type (ServiceTokenServiceCollectionExtensions.cs:84-88, :120-139, :184). The settings bind and validate once however many of the two halves a host calls (ServiceTokenServiceCollectionExtensions.cs:106-117). An endpoint under InternalCaller still has to tell the two kinds of caller apart, and ServiceCallerClaimsPrincipalExtensions answers that with principal.IsServiceCaller() (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceCallerClaimsPrincipalExtensions.cs:21): true only when an authenticated identity was issued by the ServiceToken scheme and carries a non-empty svc claim (ServiceCallerClaimsPrincipalExtensions.cs:25-28), which works in a principal merged from several schemes because the bearer stamps the scheme name as the identity's AuthenticationType (ServiceTokenServiceCollectionExtensions.cs:161-163). A user token never qualifies, so an InternalCaller edge can let a service through and still hold a user caller to a permission: Identity's verified-user lookup admits a service caller or a user holding TicketsManage (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/VerifiedUserLookupGrpcService.cs:45-47). The shared symmetric key is a deliberate choice for east-west traffic inside one deployment, with no issuer service to call and a key rotation that is one configuration change on every service (ServiceTokenSettings.cs:12-17), in contrast to the JWKS validation of forwarded user tokens. Both consumer apps wire it. In ADC, Engagement registers both halves (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:239, :238) and maps TicketInvitationGrpcService under ServiceCaller (Program.cs:286), Identity registers both halves and maps VerifiedUserLookupGrpcService under InternalCaller (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:137, :146, :344), and Notification registers the receiving half and maps LiveChannelGrpcService under ServiceCaller (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:139, :160); the matching clients opt in with .WithServiceToken() (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Contracts/DependencyInjection.cs:102, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:72, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:51). In Store, Sales registers the calling half (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:147) and opts its CustomerServiceClient in (MMCA.Store/Source/Services/MMCA.Store.Identity.Contracts/DependencyInjection.cs:46), and Identity registers the receiving half and maps CustomersGrpcService under InternalCaller (MMCA.Store/Source/Services/MMCA.Store.Identity.Service/Program.cs:85, :149), where IsServiceCaller() separates the two callers (MMCA.Store/Source/Services/MMCA.Store.Identity.Service/Grpc/CustomersGrpcService.cs:98). [Rubric §11, Security] again: a service identity that is minted, scoped by audience, and admitted only where an endpoint asks for it.

The transport is HTTP/2 cleartext (h2c) with prior knowledge. The client addresses http://{serviceName} (DependencyInjection.cs:118-119), resolved by Aspire service discovery, because Aspire's project-resource discovery does not reliably expose an https key for these peers; the Sonar cleartext warning is suppressed in place with that rationale (DependencyInjection.cs:117). A deliberate SocketsHttpHandler override (DependencyInjection.cs:133-141) forces EnableMultipleHttp2Connections and re-applies the pooled-lifetime and keep-alive values from HttpResilienceDefaults, because the global ConfigureHttpClientDefaults from MMCA.Common.Aspire applies to all HttpClients and its wrapper can defeat HTTP/2 negotiation. On top of that, AddStandardResilienceHandler gives every gRPC client an explicit Polly pipeline sourced entirely from the Grpc-prefixed members of HttpResilienceDefaults (DependencyInjection.cs:151-181): the attempt and total timeouts are the gRPC path's own, 8 and 20 seconds, sized from measured east-west latency rather than taken from the outbound-HTTP 30s/90s (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:79, :90), while the retry budget and the breaker sampling window are shared with the HTTP path (DependencyInjection.cs:155, :170). The retry is narrowed: every gRPC call is a POST, so only a failure to reach the peer before the request was sent is retried, an HttpRequestException whose HttpRequestError is NameResolutionError, ConnectionError, or SecureConnectionError (DNS, the TCP connect, or the TLS handshake during a replica rollover). A status, an attempt timeout, or an HttpRequestException raised after the request frames were written may already have reached the handler and could run the call twice, so none of those is retried (DependencyInjection.cs:157-169). The circuit-breaker values are spelled out (FailureRatio 0.5, MinimumThroughput 10, BreakDuration 10 seconds, at MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:96-108) precisely because an east-west gRPC call bypasses the Gateway's active health checks [Rubric §29, Resilience & Business Continuity]. The breaker's HTTP predicate alone would miss both ways a gRPC peer fails, so GrpcCircuitBreakerPredicate widens it (DependencyInjection.cs:177): it also counts a trailers-only response whose grpc-status is Unavailable, Internal, Unknown, or DeadlineExceeded (never a status the peer's own Result produced, which means the peer is healthy) and a call ended by its own deadline (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Resilience/GrpcCircuitBreakerPredicate.cs:39-55). The deadline case needs help because the client enforces a deadline by cancelling the request, the same signal a caller's own cancellation sends: GrpcDeadlineObserverHandler, added after the resilience handler so it runs inside it once per attempt (DependencyInjection.cs:185), reads the grpc-timeout request header and marks a request cancelled within 50 ms of that budget (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Resilience/GrpcDeadlineObserverHandler.cs:25, :57-72), rethrowing the cancellation unchanged. A failure sent after a response message travels in the HTTP trailers and stays invisible to the breaker (GrpcCircuitBreakerPredicate.cs:28-30). An edge that is legitimately slower passes the optional configureResilience callback, which runs after every default above (DependencyInjection.cs:104-106, :180).

Two Kestrel profiles, per endpoint and not per host (ADR-012). A host that serves inbound gRPC and nothing that needs HTTP/1.1 runs Http2-only on its cleartext endpoint: "Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } } in ADC's Conference, Engagement, and Identity services (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/appsettings.json:9-12), and in Store's Catalog and Identity. A host that must also speak HTTP/1.1 splits protocols across two named endpoints in one process: ADC's Notification keeps Http1AndHttp2 on http (port 8080) for REST, probes, and the SignalR WebSocket upgrade handshake, and declares a second Http2-only grpc endpoint on port 8081 (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/appsettings.json:9-19); Store's Sales host runs that same mixed profile. That second profile is why one client registration names its target "_grpc.notification" rather than "notification" (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:49): Aspire service discovery injects a services__notification__grpc__0 key for the named endpoint, and the _grpc. prefix selects it.

The live topology in ADC. There are ten .proto contracts today under MMCA.ADC/Source/Services/*.Contracts/Protos/, each with a generated client, a hand-written adapter, and a server-side service class; event-live validation has two consumers, so the hosts register eleven client edges. Reading them as consumer to producer: Engagement to Conference for ISessionBookmarkValidationService and IEventLiveValidationService (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:227-228), Engagement to Notification for the best-effort live-channel push (Program.cs:229, replacing the framework's NullLiveChannelPublisher behind ILiveChannelPublisher), Engagement to Identity for verified-user lookup (Program.cs:230), Conference to Engagement for IBookmarkCountService on the speaker dashboard (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:361), Notification to Identity for attendee user ids and Notification to Conference for event-live validation (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:119-120), Identity to Engagement, Notification and Conference for the cross-service data-subject export aggregation (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:288-290), and Identity to Engagement for re-issuing an expired ticket invitation (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:291). Server sides get AddGrpcServiceDefaults() from the shared host (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:167) and are mapped with MapGrpcService<...>(), mostly behind .RequireAuthorization(); Conference keeps its three mappings in ConferenceGrpcEndpoints (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:388, MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/ConferenceGrpcEndpoints.cs:20, :28). The exceptions are the two anonymous edges serving public or internal-ingress reads (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:270, MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/ConferenceGrpcEndpoints.cs:44) and the service-token policies from ServiceTokenDefaults (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:286, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:326, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:167).

The startup-ordering edge worth knowing. Conference and Engagement call each other, so the AppHost gives Engagement a WithReference(conference).WaitFor(conference) but the reverse Conference to Engagement edge only a WithReference with no WaitFor (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:268, :273), because a reciprocal wait would deadlock startup with each service waiting for the other to be healthy. The same reasoning drops the WaitFor on Engagement to Notification (Program.cs:285) and on both Identity edges (Program.cs:295-296); only Notification to Identity keeps one (Program.cs:266). The transient "peer not ready" errors that result self-heal through the resilience pipeline. This is the practical cost ADR-007 calls out: mutual synchronous dependencies need care, and the retry plus circuit breaker is what makes them tolerable.

Governance: the marker is adopted and enforced. ServiceContractAttribute marks a type as part of an extracted service's wire surface. It takes no arguments (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ServiceContractAttribute.cs:22-31) and accepts an interface, class, or struct, but the reference consumers mark the C# service interface only, never an integration-event record or DTO (ServiceContractAttribute.cs:16-18). MMCA.Common itself marks no type, so the rule is a ratchet in the framework repo and bites in a consumer the moment its first contract type is marked. In ADC nine interfaces carry it today (ISessionBookmarkValidationService, IEventLiveValidationService, IBookmarkCountService, IUserEngagementExportService, IUserConferenceExportService, IPendingTicketInvitationService, IAttendeeQueryService, IVerifiedUserLookupService, IUserNotificationExportService), and Store marks its own. Two fitness functions read the attribute by full name (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.Contracts.cs:10): the purity rule, that a contract type must not reach into the producing service's Domain, Application, or Infrastructure (ArchitectureRules.Contracts.cs:32, exposed through ServiceContractPurityTestsBase), and the encapsulation rule, that the class serving a [ServiceContract] interface must not be public (ArchitectureRules.Contracts.cs:80, exposed through ContractImplementationTestsBase), which is why every gRPC adapter above is internal sealed. Alongside them, MicroserviceExtractionTestsBase forbids transport types from leaking into Application, Domain, or Shared: the gRPC and Protobuf runtime, the broker clients the framework's own transports run on (RabbitMQ, Azure Service Bus, Amazon SQS and SNS), and MassTransit, which is banned outright under ADR-118 (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Layering/ArchitectureRules.Transport.cs:14, asserted at ArchitectureRules.Transport.cs:26). Each repo subclasses all three (for example MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Layering/ServiceContractPurityTests.cs:9). That is the executable governance keeping this transport genuinely at the edge [Rubric §34, Architecture Governance & Documentation] and [Rubric §15, Best Practices & Code Quality]. Generated gRPC client classes need no attribute: they are part of the contract surface by virtue of their .proto.

CachedToken

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenProvider.cs:105 · Level 0 · record (private, sealed)

  • What it is: a private nested record inside ServiceTokenProvider holding a minted token and the instant it expires: CachedToken(string Value, DateTimeOffset ExpiresAt) (ServiceTokenProvider.cs:105).
  • Depends on: BCL only.
  • Concept reinforced, immutable value published across threads. Being a record (reference type), the provider can publish it with a single Volatile.Write and readers see either the old or the new token, never a torn pair (ServiceTokenProvider.cs:52-70).
  • Walkthrough: IsFresh compares ExpiresAt - now to the 60-second window (line 76); Mint builds it from the written token string and the exp actually serialized (line 101).
  • Why it's built this way: carrying ExpiresAt next to Value lets the cache age a token without re-parsing the JWT.
  • Where it's used: only inside ServiceTokenProvider.cs.

DefaultSchemeGuard

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenServiceCollectionExtensions.cs:184 · Level 0 · class (private, sealed)

  • What it is: an empty marker class nested in ServiceTokenServiceCollectionExtensions (ServiceTokenServiceCollectionExtensions.cs:184), declared private sealed class DefaultSchemeGuard;. Its doc comment calls it "marker options whose start-time validation runs the default-scheme guard" (line 164).
  • Depends on: nothing; it carries no members.
  • Concept reinforced, fail-fast configuration contract. ADR-070 [Rubric §11, Security]: the options system runs Validate plus ValidateOnStart against it, so the check executes once at host startup (ServiceTokenServiceCollectionExtensions.cs:84-88).
  • Walkthrough: AddOptions<DefaultSchemeGuard>().Validate<IOptions<AuthenticationOptions>>(...) calls ServiceTokenIsNotTheDefaultScheme and, on failure, reports that the ServiceToken scheme must not be the default (lines 78-82).
  • Why it's built this way: a marker type keeps the validation off AuthenticationOptions itself, so reading those options stays free of side effects (comment, lines 76-77).
  • Where it's used: only in AddServiceTokenAuthentication; exercised by ServiceTokenDefaultSchemeGuardTests.

GrpcWireFormat

MMCA.Common.Grpc · MMCA.Common.Grpc · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/GrpcWireFormat.cs:30 · Level 0 · class (static)

  • What it is: the shared string encodings a hand-written gRPC service and its client adapter use for the two values protobuf has no lossless scalar for: UTC timestamps, written as ISO 8601 round-trip ("O") strings, and money, written as invariant-culture decimal strings. Both ends of a contract call these helpers, so the wire format is defined once (doc summary, GrpcWireFormat.cs:4-8).
  • Depends on: System.Globalization (CultureInfo, DateTimeStyles, NumberStyles, BCL, GrpcWireFormat.cs:1) only. Nothing first-party and nothing from Grpc.Core: it is pure string formatting that happens to live in the transport package.
  • Concept introduced, a single wire encoding for non-scalar values. [Rubric §9, API & Contract Design] (assesses whether a contract has one unambiguous wire shape): the format of a timestamp or an amount is part of the contract, so a producer that writes "O" and a consumer that parses with the thread culture would disagree silently; routing both ends through one class removes that choice from every adapter. [Rubric §29, Resilience & Business Continuity] (assesses tolerance of partial failure and mixed-version operation): ParseUtc accepts a timestamp with or without the Z marker because a rolling deploy can leave a replica that still emits the marker-less form on the other end (lines 15-16).
  • Walkthrough: one private constant, then format/parse pairs.
    • UtcStyles (GrpcWireFormat.cs:37) is AssumeUniversal | AdjustToUniversal. The comment above it (lines 32-36) records why: a suffix-less value would otherwise parse as Unspecified, and AssumeUniversal alone yields Local; RoundtripKind is deliberately absent because DateTime.Parse rejects it alongside either Assume* or AdjustToUniversal.
    • FormatUtc(DateTime) (line 42) calls DateTime.SpecifyKind(value, DateTimeKind.Utc) and formats with "O" under CultureInfo.InvariantCulture, so the output always ends in Z. FormatUtcOrEmpty(DateTime?) (line 51) writes the empty string for null, because proto3 has no null string.
    • ParseUtc(string) (line 61) is DateTime.Parse(value, InvariantCulture, UtcStyles), yielding DateTimeKind.Utc on the same instant whether or not the marker was present. ParseUtcOrNull(string?) (line 71) maps the empty string (also what a peer predating the field sends) back to null.
    • FormatDecimal(decimal) (line 77) writes value.ToString(InvariantCulture), keeping the scale (for example 1234.50). ParseDecimal(string) (line 83) parses with NumberStyles.Number under the invariant culture, and TryParseDecimal(string?, out decimal) (line 93) is the non-throwing variant.
  • Why it's built this way: the doc remarks (lines 9-28) give three reasons. SQL Server hands DateTime columns back as Unspecified, and "O" omits the Z for that kind, so FormatUtc stamps Utc before formatting: the stored values are already UTC, so a value is relabelled, never converted. A double would round a price, and the invariant culture on both ends keeps "1234.50" from being read back as a different number under a comma-decimal locale. Finally, ParseUtc and ParseDecimal throw FormatException on a malformed value, treating a corrupt peer payload as a fault; an adapter that wants its own answer for bad input uses TryParseDecimal and decides itself.
  • Where it's used: the ADC export contracts on both sides of the wire. Server side, UserEngagementExportGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Grpc/UserEngagementExportGrpcService.cs:62,69,78) and UserNotificationExportGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/UserNotificationExportGrpcService.cs:58,60) call FormatUtc / FormatUtcOrEmpty; client side, the matching adapters UserEngagementExportServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Contracts/UserEngagementExportServiceGrpcAdapter.cs:40,47,56) and UserNotificationExportServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/UserNotificationExportServiceGrpcAdapter.cs:36,38) call ParseUtc / ParseUtcOrNull. Covered by GrpcWireFormatTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/GrpcWireFormatTests.cs:18).
  • Caveats / not-in-source: none of the usage sites read for this section calls the decimal helpers; their consumers (if any outside ADC) are not determinable from the usage list in hand.

IServiceTokenProvider

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/IServiceTokenProvider.cs:8 · Level 0 · interface

  • What it is: the one-method contract for "give me a token naming this service": string GetToken() (IServiceTokenProvider.cs:15). The doc comment promises a compact JWT valid for at least the next 60 seconds, returned as the token only, without the Bearer prefix (lines 10-14).
  • Depends on: nothing.
  • Concept introduced, a narrow abstraction in front of credential minting. [Rubric §7, Microservices Readiness] (assesses transport concerns behind abstractions) and [Rubric §11, Security].
  • Walkthrough: a single member, GetToken. The caller adds Bearer itself, as ServiceTokenClientInterceptor does.
  • Why it's built this way: the interceptor depends on the interface, so tests substitute a fake without keys or clocks (ServiceTokenClientInterceptorTests).
  • Where it's used: implemented by ServiceTokenProvider, consumed by ServiceTokenClientInterceptor, registered by AddServiceTokenClient (ServiceTokenServiceCollectionExtensions.cs:44) and referenced in DependencyInjection.cs (the AddTypedGrpcClient doc comment, line 64).

JwtForwardingClientInterceptor

MMCA.Common.Grpc · MMCA.Common.Grpc.Interceptors · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/JwtForwardingClientInterceptor.cs:39 · Level 0 · class (sealed)

  • What it is: a gRPC client-side interceptor that copies the inbound Authorization header from the current HttpContext onto every outgoing gRPC call's metadata, so the caller's JWT bearer token rides along to downstream services. When the request authenticated without that header (a SignalR hub connection passes its token as ?access_token=), it forwards the token saved on the authentication ticket instead (class remarks, JwtForwardingClientInterceptor.cs:24-25). It forwards only the user's token: a call with no user token goes out with no Authorization entry unless its client opted into service tokens with ServiceTokenHttpClientBuilderExtensions' WithServiceToken(), which adds ServiceTokenClientInterceptor for that client alone (class remarks, lines 27-36). An Authorization entry the caller already set is never overwritten or duplicated.
  • Depends on: Grpc.Core.Interceptors.Interceptor (the base class) and Grpc.Core call types (NuGet, see primer §3, "Transport"); Microsoft.AspNetCore.Http.IHttpContextAccessor (ASP.NET Core, injected as a primary-constructor parameter, JwtForwardingClientInterceptor.cs:39); IAuthenticateResultFeature and the AuthenticationProperties.GetTokenValue helper (using Microsoft.AspNetCore.Authentication, line 3) for the saved-token fallback. Nothing first-party: it lives in MMCA.Common.Grpc, which by the layer rules depends on Shared only and is pure transport (see primer §1).
  • Concept introduced, gRPC interceptors and token forwarding across a service mesh. [Rubric §7, Microservices Readiness] (assesses whether application code talks to abstractions while transport concerns live at the edges; here, cross-service auth is handled by a transport interceptor, not by every handler threading a token). [Rubric §11, Security] (assesses how credentials propagate; this forwards the bearer token so distributed authorization works end-to-end without re-authenticating at each hop). A gRPC interceptor is the gRPC equivalent of an HTTP DelegatingHandler / ASP.NET middleware: it wraps every call in a pipeline. There are five client call shapes (unary async and blocking, server-streaming, client-streaming, duplex-streaming) and this interceptor overrides all five, so no call variant can bypass token forwarding. It is the client side of the cross-service auth story whose server side is JWKS validation (ADR-004, see RsaJwksProvider).
  • Walkthrough: members in execution order.
    • internal const string AuthorizationHeader = "Authorization" (JwtForwardingClientInterceptor.cs:41), the single header name (internal so ServiceTokenClientInterceptor shares it), and private const string AccessTokenName = "access_token" (line 43), the name under which JwtBearerOptions.SaveToken stores the token on the authentication ticket.
    • The five overrides (AsyncUnaryCall line 46, BlockingUnaryCall line 57, AsyncServerStreamingCall line 68, AsyncClientStreamingCall line 79, AsyncDuplexStreamingCall line 89) each follow the same three-step shape: ArgumentNullException.ThrowIfNull(continuation), build a new context via WithForwardedAuthorization(context), then invoke continuation(...). The two streaming variants whose continuation takes no request argument call continuation(newContext) (lines 85 and 95); the other three pass (request, newContext).
    • WithForwardedAuthorization<TRequest, TResponse> (JwtForwardingClientInterceptor.cs:162-168) is now a thin private wrapper: if HasAuthorization(context) is true it returns the context unchanged, otherwise it calls WithAuthorization(context, ResolveUserAuthorization(httpContextAccessor.HttpContext)).
    • WithAuthorization<TRequest, TResponse>(context, authHeader) (JwtForwardingClientInterceptor.cs:108-123) is the shared internal static helper. If authHeader is null or empty, or the call already carries an Authorization entry, it returns the context unchanged (line 114): the deliberate no-op when there is no HTTP request, for example a background processor or hosted service invoking a gRPC client outside a request. Otherwise it takes the call's existing Options.Headers (or a fresh Metadata via the collection expression [], line 119), does headers.Add(...) (line 120), rebuilds the call options with WithHeaders (line 121), and returns a new ClientInterceptorContext carrying context.Method, context.Host, and the new options (line 122).
    • HasAuthorization<TRequest, TResponse>(context) (JwtForwardingClientInterceptor.cs:133-136) answers whether Options.Headers?.GetValue("Authorization") is non-null, so a prior interceptor or the caller that already set it is never overwritten or duplicated.
    • ResolveUserAuthorization(HttpContext?) (JwtForwardingClientInterceptor.cs:144-160, internal static) picks the value. No HttpContext answers null (lines 146-149). A non-empty inbound Authorization header is returned as-is and always wins (lines 151-155). Otherwise it reads httpContext.Features.Get<IAuthenticateResultFeature>()?.AuthenticateResult?.Properties?.GetTokenValue("access_token") and, when that is non-empty, answers $"Bearer {savedToken}" (lines 157-159). This is what lets a call made from inside a SignalR hub, where the token arrived on the query string rather than in a header, still carry the caller's identity downstream.
  • Why it's built this way: sealing the class and overriding all five call shapes makes token forwarding total, so there is no call shape that silently drops the credential. Doing it in an interceptor rather than at each call site keeps consumer code transport-agnostic, which is exactly the extraction boundary ADR-007 and ADR-008 want. The duplicate-header guard means it composes safely with other interceptors, and the helpers being internal static lets ServiceTokenClientInterceptor reuse the same guard and header write instead of copying them. The saved-token fallback forwards the token the request actually authenticated with, and only when no header is present, so it never overrides an explicit Authorization value.
  • Where it's used: registered automatically by AddTypedGrpcClient<TClient> in this group's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:124,131), so every typed gRPC client an ADC or Store service host builds gets it without explicit wiring.

ServiceTokenDefaults

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenDefaults.cs:9 · Level 0 · class (static)

  • What it is: the four well-known names of the service-token scheme, held as constants so the minting side and the validating side cannot drift: the authentication scheme "ServiceToken" (ServiceTokenDefaults.cs:16), the authorization policies "InternalCaller" (line 22) and "ServiceCaller" (line 29), and the claim type "svc" that carries the calling service's name (line 35).
  • Depends on: nothing; it is four const string members in MMCA.Common.Grpc.
  • Concept introduced, a service-to-service credential kept separate from the user credential. [Rubric §11, Security] (assesses how callers are told apart and how far a credential reaches). The doc comment on the scheme states the key rule: it is never the default scheme, so a service token only authenticates an endpoint that names the scheme, in practice one under InternalCallerPolicy (lines 11-15). InternalCallerPolicy accepts an authenticated caller from either the user JwtBearer scheme or the service scheme (lines 18-21). ServiceCallerPolicy is the service-only variant: the caller must be authenticated by the service scheme and carry the svc claim, and the user JwtBearer scheme is not evaluated, so an end-user token is refused (lines 24-28). A token without the svc claim is not a service token and is refused (lines 31-34).
  • Walkthrough: no behavior, only the four constants above.
  • Why it's built this way: the scheme name is shared by AddServiceTokenAuthentication, the default scheme guard, the two policy registrations and ServiceCallerClaimsPrincipalExtensions, and the claim type is shared by the minting side and the validation event, so one definition removes string drift between them.
  • Where it's used: ServiceTokenServiceCollectionExtensions (registers the scheme and both policies), ServiceCallerClaimsPrincipalExtensions (reads the scheme and claim names), ServiceTokenProvider (writes the claim, ServiceTokenProvider.cs:88), and the ADC service hosts, which map service-only gRPC endpoints under ServiceCallerPolicy (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:286, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:167). Tests: MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/ServiceTokenAuthenticationTests.cs and ServiceCallerPolicyTests.cs (same folder, pins the "ServiceCaller" name at line 41).

ServiceTokenSettings

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenSettings.cs:18 · Level 0 · class (sealed)

  • What it is: the options class bound from the Grpc:ServiceToken section (SectionName, ServiceTokenSettings.cs:21). It carries SigningKey (line 39, Base64 HMAC key shared by every service in the deployment), ServiceName (line 45, the sub and svc claims), Issuer (line 48, default "mmca-service"), Audience (line 54, default "internal-grpc"), and LifetimeMinutes (line 57, default 5). It implements IValidatableObject.
  • Depends on: System.ComponentModel.DataAnnotations (BCL) only.
  • Concept introduced, fail-fast configuration contract. [Rubric §11, Security] (assesses secret and key handling) and the project's fail-fast option pattern (ADR-070; key sourcing: ADR-061). Validate (line 65) yields one ValidationResult per defect, so a misconfigured host fails on start with a message naming the exact problem rather than minting tokens a receiver cannot validate.
  • Walkthrough: SigningKey is checked in three steps: blank (required), not valid Base64 (DecodedLength returns null, line 102), or fewer than the HS256 minimum of 32 bytes (MinimumSigningKeyBytes, line 24). ServiceName must be non-blank. LifetimeMinutes must lie in 2 to 60 (MinimumLifetimeMinutes, line 30, and MaximumLifetimeMinutes, line 33; the check and its message are at lines 93-98). DecodedLength allocates a buffer sized (length + 3) / 4 * 3 and uses Convert.TryFromBase64String (lines 102-106).
  • Why it's built this way: the audience default differs from the user tokens' audience on purpose, because the audience is what keeps a service token out of the user scheme (doc comment, lines 50-53). The five-minute default and 60-minute cap bound the damage of a leaked token. The two-minute floor exists because ServiceTokenProvider replaces a token in its last 60 seconds, so a one-minute token would never be reused and every call would mint (doc comment, lines 26-29).
  • Where it's used: bound and validated once by AddServiceTokenSettings (ServiceTokenServiceCollectionExtensions.cs:106-117), read by ServiceTokenProvider to mint, and covered by ServiceTokenSettingsTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/ServiceTokenSettingsTests.cs).

GrpcDefaultDeadlineInterceptor

MMCA.Common.Grpc · MMCA.Common.Grpc.Interceptors · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:16 · Level 1 · class (internal, sealed)

  • What it is: a client-side gRPC Interceptor that gives a unary call with no deadline the framework default, HttpResilienceDefaults.GrpcCallDeadline (five seconds, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:87). A deadline the caller set, DateTime.MaxValue included, is left as it is, and streaming calls are not touched (doc comment, GrpcDefaultDeadlineInterceptor.cs:7-14).
  • Depends on: HttpResilienceDefaults (via using MMCA.Common.Shared.Resilience, line 3); TimeProvider (BCL, injected as a primary-constructor parameter, line 16); Grpc.Core and Grpc.Core.Interceptors (NuGet, lines 1-2).
  • Concept introduced, a default deadline on every east-west call. [Rubric §29, Resilience & Business Continuity] (assesses whether a hung dependency can hold a caller). Without a deadline, a typed client waits on a hung peer until the HTTP attempt timeout, and each adapter would have to carry its own deadline constant. A gRPC deadline is also sent to the peer, so the server side can stop work the caller has given up on.
  • Walkthrough: two overrides, one per unary shape. AsyncUnaryCall (line 19) and BlockingUnaryCall (line 29) null-check continuation and pass the request on with WithDefaultDeadline(context) (lines 25 and 35). The private WithDefaultDeadline (line 38) returns the context unchanged when context.Options.Deadline is already set (line 42); otherwise it builds a new ClientInterceptorContext with the same method and host and context.Options.WithDeadline(timeProvider.GetUtcNow().UtcDateTime + HttpResilienceDefaults.GrpcCallDeadline) (lines 44-47). The streaming overrides are not overridden, so they keep the base pass-through.
  • Why it's built this way: the five-second default sits below the eight-second GrpcAttemptTimeout (HttpResilienceDefaults.cs:79), so the call's own deadline ends a hung call first and the call fails as DeadlineExceeded, which the circuit breaker counts as a peer failure (comment, HttpResilienceDefaults.cs:69-72). It is about six times the slowest measured east-west p99 of 784ms (doc comment, HttpResilienceDefaults.cs:82-85). The clock comes from TimeProvider so tests can pin "now". Streams are exempt because a stream may legitimately stay open far longer than one unary budget.
  • Where it's used: registered as a singleton and attached as a client interceptor on every typed client by AddTypedGrpcClient in this group's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:125,132); covered by GrpcDefaultDeadlineInterceptorTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/GrpcDefaultDeadlineInterceptorTests.cs).

ServiceCallerClaimsPrincipalExtensions

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceCallerClaimsPrincipalExtensions.cs:9 · Level 1 · class (static)

  • What it is: a C# extension(ClaimsPrincipal) block (see primer §4) with one method, IsServiceCaller() (ServiceCallerClaimsPrincipalExtensions.cs:21), that answers whether the current caller is another service presenting a service token rather than an end user.
  • Depends on: ServiceTokenDefaults (the scheme name and the svc claim type) and System.Security.Claims.ClaimsPrincipal (BCL).
  • Concept introduced, telling a service caller apart inside a merged principal. [Rubric §11, Security] (assesses how callers are told apart). An endpoint under InternalCallerPolicy authenticates both the user scheme and the service scheme, so HttpContext.User can hold identities from either. Checking for the svc claim alone does not say which scheme produced it; the method also checks the identity's AuthenticationType.
  • Walkthrough: null-checks the principal (line 23), then returns true when any identity is authenticated, has AuthenticationType equal (ordinal) to ServiceTokenDefaults.AuthenticationScheme, and carries a non-blank svc claim (lines 25-28). The AuthenticationType match works because ConfigureServiceTokenBearer sets TokenValidationParameters.AuthenticationType to the scheme name (ServiceTokenServiceCollectionExtensions.cs:163), so a service identity is stamped with it.
  • Why it's built this way: a user token never qualifies (doc comment, lines 13-19), so an edge can let a service through and still hold a user caller to a permission check. That is the shape the Identity edges use: !caller.IsServiceCaller() combined with the permission checks, so only a user caller lacking the permission is refused (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/AttendeesGrpcService.cs:81-86).
  • Where it's used: ADC gRPC services in the Engagement and Identity hosts: MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Grpc/TicketInvitationGrpcService.cs:40, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/AttendeesGrpcService.cs:81 and MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/VerifiedUserLookupGrpcService.cs:45; tested against a real endpoint in ServiceCallerPolicyTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/ServiceCallerPolicyTests.cs:164,223).

ServiceTokenClientInterceptor

MMCA.Common.Grpc · MMCA.Common.Grpc.Interceptors · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/ServiceTokenClientInterceptor.cs:28 · Level 1 · class (sealed)

  • What it is: a gRPC client interceptor that, for a call carrying no user token, attaches this service's own token as Authorization: Bearer {token}. It is added per client by WithServiceToken(), never globally.
  • Depends on: JwtForwardingClientInterceptor (reuses its internal static HasAuthorization, ResolveUserAuthorization and WithAuthorization), IServiceTokenProvider (the token source), and IHttpContextAccessor; both injected through the primary constructor (ServiceTokenClientInterceptor.cs:28-30).
  • Concept reinforced, interceptors for cross-service auth. [Rubric §11, Security] (assesses how a call proves who is making it when no user is involved, such as a background job).
  • Walkthrough: the five call-shape overrides (AsyncUnaryCall line 33, BlockingUnaryCall line 43, AsyncServerStreamingCall line 53, AsyncClientStreamingCall line 63, AsyncDuplexStreamingCall line 72) each null-check the continuation and pass WithServiceAuthorization(context). That helper (line 80) returns the context unchanged when the call already has an Authorization entry or a user token resolves from the ambient request (lines 85-89). Otherwise it calls serviceTokenProvider.GetToken() (line 91) and hands Bearer {token}, or null for an empty token, to JwtForwardingClientInterceptor.WithAuthorization (lines 92-94).
  • Why it's built this way: the user's identity always wins over the service's, so a user-initiated call is never silently escalated to a service call. Reusing the jwt interceptor's helpers keeps one definition of "already has an Authorization entry".
  • Where it's used: added by WithServiceToken() (ServiceTokenHttpClientBuilderExtensions.cs:34); tested in MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/ServiceTokenClientInterceptorTests.cs.

ServiceTokenProvider

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenProvider.cs:23 · Level 1 · class (sealed)

  • What it is: the IServiceTokenProvider implementation. It mints an HS256 JWT naming this service and caches it, handing out the same token until its last 60 seconds (RefreshWindow, ServiceTokenProvider.cs:26).
  • Depends on: ServiceTokenSettings (via IOptions), TimeProvider (the clock), ServiceTokenDefaults (the svc claim type), and System.IdentityModel.Tokens.Jwt (NuGet). The constructor builds SigningCredentials once from the Base64 key with SecurityAlgorithms.HmacSha256 (lines 39-48).
  • Concept introduced, a double-checked token cache. [Rubric §11, Security] (assesses short-lived credentials) and [Rubric §29, Resilience & Business Continuity] (a token that could expire mid-call is never handed out).
  • Walkthrough: GetToken() (line 52) reads the published _cached with Volatile.Read; if IsFresh (line 76: ExpiresAt - now > RefreshWindow) it returns without locking. Otherwise it takes the Lock _gate (line 61), re-checks in case another caller minted while it waited, and only then Mints and publishes with Volatile.Write. Mint (line 79) truncates now to whole seconds, because JWT times are whole seconds and the cache must age the token by the exp actually written, then adds LifetimeMinutes. The claims are sub, svc, a fresh jti, and iat (lines 85-91); the token carries the issuer, audience, notBefore and expires from the settings (lines 93-99), and the result is stored as a CachedToken (line 101).
  • Why it's built this way: registered as a singleton, so one cache per process serves every outgoing call; readers never contend, and only a caller inside the refresh window takes the lock, once for everyone waiting (class remarks, lines 16-22).
  • Where it's used: registered by AddServiceTokenClient (ServiceTokenServiceCollectionExtensions.cs:44) and consumed by ServiceTokenClientInterceptor; tested in ServiceTokenProviderTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/ServiceTokenProviderTests.cs).

ServiceTokenHttpClientBuilderExtensions

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenHttpClientBuilderExtensions.cs:11 · Level 2 · class (static)

  • What it is: a C# extension(IHttpClientBuilder) block (see primer §4) with one method, WithServiceToken() (ServiceTokenHttpClientBuilderExtensions.cs:28), that opts a single typed gRPC client into service tokens.
  • Depends on: ServiceTokenClientInterceptor and Grpc.Net.ClientFactory (AddInterceptor, InterceptorScope.Client).
  • Concept introduced, per-client opt-in. [Rubric §11, Security] (assesses least privilege). Chain it onto AddTypedGrpcClient<TClient> (DependencyInjection) only for a client whose server validates service tokens (AddServiceTokenAuthentication); leave it off every other client, since a server that does not validate them would have to reject the token (doc comment, lines 14-19).
  • Walkthrough: null-checks the builder (line 30), calls AddHttpContextAccessor() (line 32), registers TryAddTransient<ServiceTokenClientInterceptor>() (line 33), and returns builder.AddInterceptor<ServiceTokenClientInterceptor>(InterceptorScope.Client) (line 34), so the builder chains on.
  • Why it's built this way: the interceptor attaches to that client alone (see ADR-007). The host must also call AddServiceTokenClient; without it the client fails to resolve on first use, naming the missing IServiceTokenProvider (remarks, lines 21-24).
  • Where it's used: tested in ServiceTokenHttpClientBuilderExtensionsTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/ServiceTokenHttpClientBuilderExtensionsTests.cs).

ServiceTokenServiceCollectionExtensions

MMCA.Common.Grpc · MMCA.Common.Grpc.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Authentication/ServiceTokenServiceCollectionExtensions.cs:23 · Level 2 · class (static)

  • What it is: the registration surface for both ends of service tokens, as an extension(IServiceCollection) block (ADR-106): AddServiceTokenClient(IConfiguration) (ServiceTokenServiceCollectionExtensions.cs:38) for a caller, and AddServiceTokenAuthentication(IConfiguration) (line 69) for a receiver. It also holds the internal ServiceTokenClockSkew field (line 26), 30 seconds.
  • Depends on: ServiceTokenSettings, ServiceTokenDefaults, IServiceTokenProvider / ServiceTokenProvider, DefaultSchemeGuard, and ASP.NET Core JwtBearer, authorization and options.
  • Concept introduced, fail-fast hosting for a security rule. [Rubric §11, Security] (assesses whether an unsafe configuration can start) and ADR-070.
  • Walkthrough: AddServiceTokenClient binds the settings, TryAddSingleton(TimeProvider.System) and TryAddSingleton<IServiceTokenProvider, ServiceTokenProvider>() (lines 42-44). AddServiceTokenAuthentication (line 69) binds the settings (line 73), adds the ServiceToken JwtBearer scheme (line 76), configures it from the validated settings (lines 77-78), registers the default-scheme guard with ValidateOnStart (lines 84-88), and adds two policies (lines 90-97): the InternalCaller policy over the user scheme plus the service scheme with RequireAuthenticatedUser, and the ServiceCaller policy over the service scheme alone with RequireAuthenticatedUser and RequireClaim("svc"). The private AddServiceTokenSettings (line 106) returns early when a DataAnnotationValidateOptions<ServiceTokenSettings> is already registered (line 108), then binds Grpc:ServiceToken with ValidateDataAnnotations().ValidateOnStart() (lines 113-116), so a bad section reports each problem once. ServiceTokenIsNotTheDefaultScheme (line 120) is false if any of the four default-scheme slots is ServiceToken, or if no default is set and ServiceToken is the lone registered scheme (ASP.NET Core promotes a lone scheme to default). ConfigureServiceTokenBearer (line 141) validates issuer, audience, lifetime and signing key, sets ClockSkew to ServiceTokenClockSkew (line 152), pins ValidAlgorithms to HS256 against algorithm-confusion (line 159), sets AuthenticationType to the scheme name so IsServiceCaller can tell a service identity apart from a user identity in a merged principal (lines 161-163), and its OnTokenValidated event fails the context when the svc claim is missing or blank (lines 166-180).
  • Why it's built this way: the guard exists because a service token that became the default scheme would satisfy every plain [Authorize] endpoint. The check runs once at startup via a marker options type, so reading AuthenticationOptions stays free of side effects. The clock skew is set explicitly because the library default is five minutes, under which a token minted for the default five-minute lifetime would be accepted for ten; 30 seconds covers clock drift between in-cluster hosts (comment, lines 149-151). The separate ServiceCaller policy exists for endpoints no end user should reach: since the user scheme is not evaluated, a user token cannot satisfy it. See ADR-007.
  • Where it's used: the ADC service hosts. AddServiceTokenAuthentication is called by the Engagement, Identity and Notification hosts (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:245, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:137, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:139), and AddServiceTokenClient by the Engagement and Identity hosts (Program.cs:239 and Program.cs:153 respectively). The tests ServiceTokenAuthenticationTests, ServiceTokenDefaultSchemeGuardTests and ServiceCallerPolicyTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Authentication/) exercise it.

GrpcResultExceptionInterceptor

MMCA.Common.Grpc · MMCA.Common.Grpc.Interceptors · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcResultExceptionInterceptor.cs:19 · Level 3 · class (sealed, partial)

  • What it is: a server-side gRPC Interceptor that catches ResultFailureException thrown by service implementations and rethrows it as an RpcException carrying the correct StatusCode and structured error trailers, across all four server-handler shapes (unary, server-streaming, client-streaming, duplex).
  • Depends on: ResultFailureException (Level 2); ToRpcException from ResultGrpcExtensions (Level 3, called as exception.Errors.ToRpcException() at GrpcResultExceptionInterceptor.cs:130); Grpc.Core.Interceptors.Interceptor and Grpc.Core (NuGet); Microsoft.Extensions.Logging.ILogger<T> (injected as a primary-constructor parameter, line 19).
  • Concept reinforced, error translation as a cross-cutting concern, symmetric with the HTTP layer. [Rubric §7, Microservices Readiness] (assesses that error handling is symmetric across HTTP and gRPC) and [Rubric §9, API & Contract Design] (error translation lives in one interceptor, not re-coded in every service method). The doc comment (lines 11-13) names the parallel explicitly: this "mirrors the behavior of ApiControllerBase.HandleFailure for HTTP responses". [Rubric §13, Observability & Operability] also applies: every caught failure is logged with the gRPC method name before it is translated, so a failing east-west call is visible on the producing side even though the caller only sees a status code.
  • Walkthrough: four override methods, one per server-handler shape, then one shared translator.
    • UnaryServerHandler (line 22), ServerStreamingServerHandler (line 42), ClientStreamingServerHandler (line 63), and DuplexStreamingServerHandler (line 83) all have an identical body: null-check continuation and context, await continuation(...) with ConfigureAwait(false) (library code that must not capture a synchronization context), and catch (ResultFailureException ex) { LogResultFailure(logger, context.Method, ex); throw ToTransportException(ex); }.
    • ToTransportException(ResultFailureException) (lines 126-138) is the shared decision. When the exception carries errors, it delegates to exception.Errors.ToRpcException() (line 130) and the structured trailers come with it. When it carries none, which is what the CA1032 message-only constructors produce, that mapping would answer the placeholder detail "Unspecified failure" and the real Message would be lost, so this method instead builds new RpcException(new Status(StatusCode.Internal, detail)) (line 137), where detail is the exception message with the inner exception's message appended after ": " when there is one (lines 133-135). The remarks (lines 107-123) explain why the empty case is not solved by synthesizing a 400-family error (such as Error.Validation): that family maps to StatusCode.InvalidArgument, which would blame the caller for a server-side fault, so the empty case keeps StatusCode.Internal and replaces only the detail.
    • LogResultFailure (lines 140-141) is a source-generated [LoggerMessage] partial method at LogLevel.Information with the template "gRPC method {Method} returned a result failure". That is why the class is partial: the generator emits the body. It is the allocation-free, high-performance logging idiom (no boxing, no format-string parsing at the call site).
  • Why it's built this way: covering all four handler shapes means every gRPC operation, including the streaming ones, gets uniform Result-failure surfacing. Keeping it in an interceptor is the §9 point: the translation lives in one place, so a change to the error wire shape (see ResultGrpcExtensions) is made once. Logging at Information rather than Error is deliberate for a domain failure: a rejected command is an expected outcome, not a fault.
  • Where it's used: registered by AddGrpcServiceDefaults() in this group's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:41,45), which adds it to the gRPC server pipeline of every extracted service host. Its live counterparts are the gRPC service implementations that call result.ThrowIfFailure(), for example SessionBookmarksGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Grpc/SessionBookmarksGrpcService.cs:40,65) and EventLiveValidationGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Grpc/EventLiveValidationGrpcService.cs:46,74,103,131).

ResultGrpcExtensions

MMCA.Common.Grpc · MMCA.Common.Grpc · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:35 · Level 3 · class (static)

  • What it is: the extension members that bridge Result and Result<T> to gRPC's transport model (RpcException, StatusCode, Metadata trailers). It is both an encoder (server side: ThrowIfFailure, ToRpcException) and a matching decoder (client side: ToErrors, ToResult, ToResult<T>), plus the ErrorType to StatusCode lookup table.
  • Depends on: Error, ErrorType, ErrorTypeSeverity, Result and Result<T> (all via using MMCA.Common.Shared.Abstractions, ResultGrpcExtensions.cs:8); ResultFailureException (Level 2); Grpc.Core (NuGet); System.Collections.Frozen, System.Globalization, System.Runtime.CompilerServices, and System.Text (StringBuilder, Rune, for trailer escaping) (BCL, ResultGrpcExtensions.cs:1-5).
  • Concept introduced, a symmetric wire codec for the Result pattern. [Rubric §9, API & Contract Design] (assesses consistent error shapes across protocols) and [Rubric §7, Microservices Readiness] (the Result pattern behaves identically over HTTP and gRPC). Where ErrorHttpMapping maps ErrorType to HTTP status codes, ErrorTypeToStatusCode here (lines 37-54) maps it to gRPC StatusCode: Validation and Invariant to InvalidArgument; NotFound to NotFound; Conflict to Aborted; Unauthorized to Unauthenticated; Forbidden to PermissionDenied; UnprocessableEntity to FailedPrecondition; Unexpected to Internal; TooManyRequests to ResourceExhausted; Unavailable to Unavailable (lines 44-53). A FrozenDictionary is the right tool: built once at static init, then read-only and lookup-optimized. The genuinely new idea in this type is that the encoding is round-trippable: the failure is written into trailers in a shape the decoder can reverse, so a caller ends up holding the same Result it would have held in-process. [Rubric §29, Resilience, Reliability & Business Continuity] follows from that: both halves of the codec live here, so the wire shape has exactly one definition.
  • Walkthrough: the class is a set of C# extension(T) blocks (see primer §4), which is why it carries a file-level [SuppressMessage] for CA1708 (lines 31-34): with multiple extension blocks in one static class the analyzer flags the compiler-generated grouping members as case-colliding, a false positive.
    • extension(ErrorType errorType) (line 56) contributes ToGrpcStatusCode() (line 63): GetValueOrDefault(errorType, StatusCode.InvalidArgument), so an unmapped error type still produces a valid status.
    • extension(Result result) (line 67) contributes ThrowIfFailure() (line 76), the guard a gRPC service method calls first: null-check, then if (result.IsFailure) throw new ResultFailureException(result.Errors) (lines 79-82).
    • extension(IReadOnlyList<Error> errors) (line 86) contributes ToRpcException() (line 105), the encoder. The status code comes from ErrorTypeSeverity.MostSevere(errors).Type.ToGrpcStatusCode() (line 110), falling back to StatusCode.Internal for an empty list; the Status.Detail is the joined "Code: Message" summary or the literal "Unspecified failure" (lines 113-115). It then walks every error and writes structured trailing metadata: error-{i}-code, error-{i}-message, and error-{i}-type always (lines 121-123), plus error-{i}-source and error-{i}-target only when non-empty (lines 124-132). Every key is built with CultureInfo.InvariantCulture so the wire form cannot vary by locale. The code, message, source, and target values pass through EscapeTrailerValue (lines 121, 122, 126, 131); only the type, an enum name, is written as is (line 123). It returns new RpcException(new Status(statusCode, detail), trailers) (line 135).
    • extension(Metadata? trailers) (line 139) contributes ToErrors() (line 159), the exact inverse. Null or empty trailers decode to [] (lines 161-164). Otherwise it loops from index zero, reading and percent-decoding error-{i}-code and stopping at the first missing code (lines 171-175), which matches the contiguous layout the encoder writes; message, source, and target are percent-decoded through Unescape too, a missing message decodes to the empty string, and a missing source or target to null (lines 177-180), mirroring the encoder's omission rule.
    • extension(RpcException exception) (line 190) contributes ToResult(CancellationToken) (line 212) and ToResult<T>(CancellationToken) (line 239), which close the round trip. Both return Result.Failure(...) over the private DecodeFailure (line 250). That helper first rethrows the caller's own cancellation: a StatusCode.Cancelled call whose cancellationToken is cancelled becomes an OperationCanceledException (lines 252-255), because a cancelled caller is not a failed peer. Otherwise it returns the decoded trailer errors when there are any, or a single TransportError(exception, source) when there are none (lines 257-258). Both overloads also take a [CallerMemberName] string source = "" parameter, so the synthesized transport error is stamped with the calling adapter method's name for free.
    • The private helpers close the file. ErrorFactories (lines 266-279) is a second FrozenDictionary mapping each ErrorType to its Error factory method, documented (lines 261-265) as a lookup table rather than a switch so adding an error type stays a one-line entry instead of pushing the decoder past the cyclomatic-complexity ceiling [Rubric §15, Best Practices & Code Quality]. ParseErrorType (line 285) does a case-sensitive Enum.TryParse and falls back to ErrorType.Unexpected (line 288). EscapeTrailerValue (line 294) returns the value unchanged when every character is verbatim-safe, otherwise walks it rune by rune and writes each byte of a non-verbatim rune's UTF-8 encoding as %XX; IsVerbatimTrailerChar (line 321) defines verbatim-safe as printable ASCII (' ' to '~') except % itself, so the decoder can tell an escape from a literal. Unescape (line 324) is Uri.UnescapeDataString, with null staying null. BuildError (line 328) dispatches through the factory table and falls back to Error.Unexpected (line 331). TransportError (line 364) builds the stand-in error coded $"Grpc.{exception.StatusCode}": Error.Unexpected with TransportRejectedMessage (line 379) for Unauthenticated, PermissionDenied and Unimplemented, and Error.Unavailable with TransportUnavailableMessage (line 376) for every other status (lines 365-373).
  • Why it's built this way: four decisions are worth naming.
    1. The most severe error picks the status, not the first one (line 110). The encoder ranks the list through ErrorTypeSeverity (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:72, ties keep the earliest error), the same ranking the HTTP edge uses, so an aggregate built by Result.Combine cannot be downgraded by error ordering: an Unauthorized travelling behind a Validation still answers Unauthenticated. Ranking picks the status only; all errors still travel in the trailers.
    2. The decoder degrades rather than throws. An unrecognized error-{i}-type falls back to ErrorType.Unexpected (line 288) instead of raising, so a newer peer that adds an error type cannot break an older client, and an RpcException with no structured trailers at all (a reset connection, an exceeded deadline) still reaches the caller as a Result failure rather than an exception (lines 333-373). The stand-in is never a 400-family type (remarks, lines 338-363): a fault with no trailers never came from the peer's own Result, so it says nothing about the end user's request. Two kinds remain. Unauthenticated, PermissionDenied and Unimplemented are faults in this service's own credentials, configuration or deployment that waiting does not cure, so they become ErrorType.Unexpected (HTTP 500 at the edge, which the failure alerts watch). Every other status means the peer was down, slow, unreachable or broken, or the client gave up on it (an expired deadline, or an open circuit breaker reported as Internal), so it becomes ErrorType.Unavailable (HTTP 503, where retrying later can succeed). The message is fixed text, never Status.Detail, because the edge writes an error's message into the Problem Details a browser receives and a transport detail can name internal hosts and ports; the status stays in the code and the detail on the client call's trace span. That is the [Rubric §29, Resilience & Business Continuity] angle: the client-side programming model never changes shape because the network misbehaved, and a peer outage is not reported as the caller's mistake.
    3. Trailers carry the full error list, not a flattened string, so the client reconstructs real Error objects with their original Code, Message, Type, Source, and Target. This is what makes the Result pattern survive the hop intact (ADR-007).
    4. Trailer values are percent-encoded, not passed raw (doc comment, lines 97-102). gRPC text metadata is printable ASCII only, so an accented character or a newline in an error code, message, source or target would break the trailer at the transport. Escaping only what needs it means a plain-ASCII value without % goes on the wire unchanged, and the decoder's Unescape restores the original string exactly, so the round trip holds for any text in those four fields. The type is the one value written as is, because it is always an ErrorType enum name.
  • Where it's used: ThrowIfFailure is called by the gRPC service implementations in each service project, for example SessionBookmarksGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Grpc/SessionBookmarksGrpcService.cs:40); ToRpcException is called by GrpcResultExceptionInterceptor (GrpcResultExceptionInterceptor.cs:130); ToResult and ToResult<T> are called by the client-side adapters in the *.Contracts projects, passing the call's cancellationToken, for example SessionBookmarkValidationServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Contracts/SessionBookmarkValidationServiceGrpcAdapter.cs:51,77).

DependencyInjection

MMCA.Common.Grpc · MMCA.Common.Grpc · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:27 · Level 4 · class (static)

  • What it is: the gRPC infrastructure registration class. It is a C# extension(IServiceCollection) block (line 29, see primer §4) exposing two methods: AddGrpcServiceDefaults() for the server side and AddTypedGrpcClient<TClient>(string serviceName, Action<HttpStandardResilienceOptions>? configureResilience = null) for the client side. Its class-level <remarks> (lines 17-26) states the package's job in one place: this is the extraction boundary for a module lifted out of the modular monolith, it carries transport concerns only, and consuming modules keep the generated protobuf types out of their application and domain code behind a hand-written adapter that is the module's Anti-Corruption Layer.

  • Depends on: GrpcResultExceptionInterceptor (Level 3), JwtForwardingClientInterceptor (Level 0; it forwards only the user's token, and a client that opts in with WithServiceToken() gets this service's own token from ServiceTokenClientInterceptor when there is none, see the doc comment at DependencyInjection.cs:71-74), and HttpResilienceDefaults (via using MMCA.Common.Shared.Resilience, DependencyInjection.cs:7), whose Grpc-prefixed members carry the east-west values; Grpc.Net.ClientFactory, Microsoft.Extensions.Http.Resilience (Polly, DependencyInjection.cs:4, which also supplies HttpStandardResilienceOptions and the ResilienceHandler type the method strips), and the Microsoft.Extensions.DependencyInjection helpers (NuGet and BCL).

  • Concept reinforced, wiring the gRPC extraction boundary with resilience and h2c. [Rubric §7, Microservices Readiness] (ADR-007: gRPC transport for synchronous inter-service calls, wired so consumer code stays transport-agnostic) and [Rubric §29, Resilience & Business Continuity] (ADR-009: a standard Polly pipeline of timeout, retry, and circuit breaker on every outbound gRPC client). [Rubric §11, Security] appears twice here in a form worth noticing: detailed errors are switched off so internal exception text never leaks over the wire, and the transport is cleartext h2c by design for in-cluster east-west calls, which is why the S5332 analyzer is suppressed with an explicit justification (lines 128 and 133, its justification text pointing back at the class-level extraction boundary remarks) rather than silently.

  • Walkthrough

    • AddGrpcServiceDefaults() (line 39): TryAddSingleton<GrpcResultExceptionInterceptor>() (line 41), then AddGrpc(...) (lines 43-52), whose options add the GrpcResultExceptionInterceptor, set EnableDetailedErrors = false, and set both MaxReceiveMessageSize and MaxSendMessageSize to HttpResilienceDefaults.GrpcMaxMessageSize (lines 50-51; 4 MiB, MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:135), then AddGrpcReflection() (line 54) so tools such as grpcurl can introspect the schema. Returns services for chaining.
    • AddTypedGrpcClient<TClient>(string serviceName, Action<HttpStandardResilienceOptions>? configureResilience = null) (lines 115-118) does six things in order. First it validates the name (ArgumentException.ThrowIfNullOrWhiteSpace, line 120) and registers AddHttpContextAccessor(), TryAddSingleton(TimeProvider.System), TryAddTransient<JwtForwardingClientInterceptor>(), TryAddSingleton<GrpcDefaultDeadlineInterceptor>() and TryAddTransient<GrpcDeadlineObserverHandler>() (lines 122-126). Second it calls AddGrpcClient<TClient> with the address new Uri($"http://{serviceName}") (lines 129-130), resolved by Aspire service discovery, and attaches .AddInterceptor<JwtForwardingClientInterceptor>(InterceptorScope.Client) (line 131) and .AddInterceptor<GrpcDefaultDeadlineInterceptor>(InterceptorScope.Client) (line 132), so a unary call whose caller set no deadline gets HttpResilienceDefaults.GrpcCallDeadline (doc comment, lines 85-86). Third, through ConfigureChannel (lines 137-141), it sets the channel's MaxReceiveMessageSize and MaxSendMessageSize to the same GrpcMaxMessageSize the server uses, rather than leaving the gRPC defaults (4 MiB receive, unlimited send; comment, lines 135-136). Fourth it forces the primary handler to a SocketsHttpHandler (lines 152-160) with EnableMultipleHttp2Connections = true and the connection-hygiene values re-applied from HttpResilienceDefaults: PooledConnectionLifetime (10 minutes), PooledConnectionIdleTimeout (5 minutes), KeepAlivePingDelay (60 seconds), KeepAlivePingTimeout (30 seconds), and KeepAlivePingPolicy = WithActiveRequests (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:46,49,56,59). Fifth, through ConfigureAdditionalHttpMessageHandlers (lines 171-180), it removes every ResilienceHandler already in the client's handler list, walking it backwards: those are the outbound-HTTP pipeline AddServiceDefaults() puts on every factory client, and because this action is registered before the gRPC pipeline it never removes that one (comment, lines 162-170). Sixth it layers AddStandardResilienceHandler back on (lines 190-225), setting every knob from HttpResilienceDefaults (lines 192-194, 209-212 and 220-221): the east-west path's own GrpcAttemptTimeout (8 seconds) and GrpcTotalRequestTimeout (20 seconds), tighter than the outbound-HTTP 30s/90s pair; the shared MaxRetryAttempts (one retry beyond the initial attempt); an explicit circuit breaker (the shared 60-second CircuitBreakerSamplingDuration, then GrpcCircuitBreakerFailureRatio 0.5, GrpcCircuitBreakerMinimumThroughput 10, GrpcCircuitBreakerBreakDuration 10 seconds); and the pipeline's concurrency limiter, PermitLimit = GrpcMaxConcurrentCalls (1000) with QueueLimit = GrpcConcurrentCallQueueLimit (0, so a call over the ceiling is refused at once rather than queued) (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:18,32,79,90,96,102,108,117,125). The retry is narrowed by options.Retry.ShouldHandle (lines 203-208) to an HttpRequestException whose HttpRequestError is NameResolutionError, ConnectionError, or SecureConnectionError: only a failure to reach the service before the request was sent is retried. The breaker's ShouldHandle is widened by GrpcCircuitBreakerPredicate.Extend(...) (lines 214-216), because a gRPC peer fails as HTTP 200 with a grpc-status, or hangs until the call's deadline cancels the request, and the HTTP predicate sees neither. Last, configureResilience?.Invoke(options) (line 224) runs the caller's per-client override after every default, so it only needs to set what differs (the parameter doc, lines 108-113, gives a longer AttemptTimeout for a legitimately slow edge as the example, and warns to keep CircuitBreaker.SamplingDuration at least twice the attempt timeout because the resilience library validates it when the client is first resolved). After the resilience handler it adds GrpcDeadlineObserverHandler with AddHttpMessageHandler (lines 227-229), so it runs inside the pipeline once per attempt and marks a request whose deadline expired for the breaker predicate. It returns the original IHttpClientBuilder (line 230), not the resilience-pipeline builder, so callers can keep chaining.
  • Why it's built this way: six deliberate decisions live here, each documented inline and each worth reading before changing anything.

    1. h2c (HTTP/2 cleartext) over http://{serviceName}, not HTTPS (doc comment, lines 62-70). Aspire's project-resource endpoint discovery from launchSettings.json does not reliably create a services__<name>__https__0 discovery key, and the resolver silently falls back to http regardless of the requested scheme. The target service must therefore serve HTTP/2 on its cleartext endpoint (Kestrel:EndpointDefaults:Protocols = "Http2") or Kestrel rejects the frames with HTTP_1_1_REQUIRED. The per-host transport choices are ADR-012.
    2. The explicit SocketsHttpHandler (comment, lines 143-151). The global ConfigureHttpClientDefaults from MMCA.Common.Aspire applies to all HttpClient instances including this gRPC one, and its standard resilience pipeline can wrap the primary handler in a way that defeats HTTP/2 negotiation. Setting SocketsHttpHandler explicitly bypasses that wrapper for the gRPC client only, which is precisely why the pooled-lifetime and keep-alive values have to be re-applied from the same HttpResilienceDefaults source of truth: the override drops whatever the global default had set.
    3. The east-west values are stated explicitly, not left at the library defaults (comment at lines 182-189, values at HttpResilienceDefaults.cs:79-125). The timeouts are sized from measured gRPC latency: GrpcAttemptTimeout is about ten times the slowest measured east-west p99 (784ms), so the outbound-HTTP 30s/90s budget would hold a caller on a hung peer far too long (HttpResilienceDefaults.cs:61-64,74-79). The breaker shape is explicit because an east-west gRPC 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 retry budget and the sampling window, by contrast, are shared with the HTTP path so the two cannot drift, and a consumer whose edge is legitimately slower overrides per client through configureResilience rather than by changing the defaults.
    4. The retry predicate is replaced, not left at the default (comment at lines 196-202). Every gRPC call is an HTTP POST, so the standard handler's unsafe-method opt-out would switch the retry off entirely. Instead only an HttpRequestException whose HttpRequestError is NameResolutionError, ConnectionError, or SecureConnectionError (failures before the request was sent, for example during an ACA replica rollover) is retried. A returned status, an attempt timeout, or an HttpRequestException raised after the request frames were written (ResponseEnded, a protocol error, or Unknown wrapping a connection reset) may already have reached the handler, and replaying it could run the call twice. That keeps the single retry safe for non-idempotent calls [Rubric §29, Resilience & Business Continuity].
    5. The gRPC pipeline is the client's only resilience pipeline (comment, lines 162-170; doc comment, lines 79-82). AddServiceDefaults() puts the outbound-HTTP standard pipeline on every factory client through ConfigureHttpClientDefaults, this one included, which would stack a second breaker and concurrency limiter at library defaults around the gRPC one. The defaults' handler actions run before the client's own, so the handlers present when the stripping action runs are exactly the defaults', and registering it before AddStandardResilienceHandler means it never removes the gRPC pipeline. The comment names this as what RemoveAllResilienceHandlers() does, written against the stable ConfigureAdditionalHttpMessageHandlers because that helper is still experimental. The remaining pipeline's limiter is then sized explicitly (lines 218-221): 1000 concurrent calls per client per replica and no queue, because a peer already serving the full ceiling is saturated and a queued call would only spend its deadline waiting (HttpResilienceDefaults.cs:110-125).
    6. Message-size limits are equal on both sides (lines 50-51 server, 137-141 client). Both directions use GrpcMaxMessageSize, 4 MiB, the gRPC default receive size stated explicitly, so a reply too large for the caller fails as ResourceExhausted at the sender, the server, where it is logged, rather than after the bytes crossed the network (comment, lines 48-49; HttpResilienceDefaults.cs:127-135). An edge that returns a whole data set in one message is bounded by it, and the source's guidance is to page or stream rather than raise the limit.

    The doc comment is explicit that application code should not consume the generated client directly (lines 88-98): register a hand-written adapter implementing the consuming module's own C# interface contract (the doc comment's example is IProductVariantService) that delegates to the typed gRPC client. That adapter is the module's Anti-Corruption Layer: the one place where the peer's wire model (the generated protobuf types) is translated into the module's own interface contract and domain types, so the peer's contract never leaks inward past it. The source names the pattern and cites ADR-007 (lines 96-97). Extraction itself follows the Strangler Fig route (lines 99-104, ADR-008): the new service host is stood up beside the modular monolith, the typed client and its Anti-Corruption Layer adapter move traffic to it, and the in-process path is retired last.

  • Where it's used: each extracted service host calls AddGrpcServiceDefaults() server-side (ADC's Conference, Engagement, Identity, and Notification Program.cs, and Store's Catalog, Identity, and Sales Program.cs); each consumer wires AddTypedGrpcClient<TClient>("<servicename>") indirectly through the per-contract DI helper in the matching *.Contracts project, for example MMCA.ADC/Source/Services/MMCA.ADC.Conference.Contracts/DependencyInjection.cs:39,66,93.

  • Caveats / not-in-source: many classes across the framework and the modules are named DependencyInjection (one per package or module); this section is specifically the MMCA.Common.Grpc one. The _typemap.tsv anchor for the bare name is owned by another group, so link to this one as #dependencyinjection from within this chapter only.

GrpcDeadlineObserverHandler

MMCA.Common.Grpc · MMCA.Common.Grpc.Resilience · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Resilience/GrpcDeadlineObserverHandler.cs:16 · Level 0 · class (internal sealed, DelegatingHandler)

  • What it is: an HTTP message handler on every typed gRPC client that tells the circuit breaker when a call ended because its own deadline expired, as opposed to the caller cancelling it.
  • Depends on: System.Net.Http.DelegatingHandler and System.TimeProvider (BCL) only. It is read by GrpcCircuitBreakerPredicate through the static DeadlineExpired helper.
  • Concept introduced, telling a deadline apart from a cancellation. [Rubric §7, Microservices Readiness] (resilient synchronous calls between extracted services). The gRPC client enforces a call deadline by cancelling the underlying HTTP request, which is exactly the signal a caller's own cancellation sends (GrpcDeadlineObserverHandler.cs:6-8). To the resilience pipeline the two look alike, yet only one of them says the peer is unwell: a hung peer should open the breaker, a user who navigated away should not. The client writes its budget into the grpc-timeout request header, so this handler reads that budget, times the call from its first attempt, and when a cancellation arrives after the budget is spent it stamps a flag on the request for the breaker to read (lines 9-11). The cancellation itself is rethrown unchanged, so the caller still sees StatusCode.DeadlineExceeded (lines 12-13).
  • Walkthrough:
    • TimeoutHeader (line 18) is the literal "grpc-timeout".
    • Tolerance (line 25) is 50 ms: how far short of its budget a cancelled request still counts as an expired deadline, covering the gap between the client stamping the header and the request reaching this handler, plus the header's whole-unit rounding (doc comment lines 20-24).
    • DeadlineExpiredKey (line 27) is an HttpRequestOptionsKey<bool> named "MMCA.Common.Grpc.DeadlineExpired"; DeadlineExpired(HttpRequestMessage?) (line 32) answers whether this handler set it, and is null-safe.
    • CallStartedKey (line 29) is an HttpRequestOptionsKey<long> named "MMCA.Common.Grpc.CallStarted": the timestamp of the call's first attempt.
    • TryParseTimeout (line 39) parses the header per the gRPC over HTTP/2 wire format: 2 to 9 characters, an unsigned digit run (NumberStyles.None, invariant culture), then one unit char. TicksPerUnit (line 99) maps H, M, S, m, u to ticks, n to zero (nanoseconds are smaller than a tick, so line 51 divides by TimeSpan.NanosecondsPerTick instead), and any other unit to null, which fails the parse.
    • SendAsync (line 56): with no header, or an unparseable one, the request passes straight through (lines 60-64). Otherwise it takes its start time from CallStarted(request) (line 69), sends, and an exception filter catches OperationCanceledException only when GetElapsedTime(started) >= budget - Tolerance (line 74), sets the flag (line 76), and rethrows with throw; (line 77). An early cancellation is never caught at all.
    • CallStarted (line 86) returns the stamp under CallStartedKey when an earlier attempt left one (lines 88-91); otherwise it reads timeProvider.GetTimestamp() and stamps it on the request (lines 93-94). The header is stamped once per call and resent unchanged by a retry, so the budget is measured from the first attempt: a retried attempt cut by the call deadline has had only what the first attempt and the backoff left of it (comment lines 66-68).
  • Why it's built this way: the flag and the start stamp ride on HttpRequestMessage.Options because that is the one object this handler, its later attempts and the Polly breaker can all reach (the predicate gets it back through ResilienceContext.GetRequestMessage(); the pipeline resends the same request message on a retry, doc comment lines 82-84), so no ambient state is needed. Timing each attempt from its own start would let a retried attempt, killed by the call deadline, look like an early caller cancellation and escape the breaker. Using an exception filter rather than a catch-and-rethrow leaves the stack untouched in the common (caller-cancelled) case. Timing through an injected TimeProvider makes the boundary testable with a fake clock.
  • Where it's used: registered by AddTypedGrpcClient<TClient> in the Grpc DependencyInjection, which adds TimeProvider.System with TryAddSingleton (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:123), the handler with TryAddTransient (line 126), and attaches it with AddHttpMessageHandler (line 229) after AddStandardResilienceHandler (line 190), so it runs inside the resilience pipeline, once per attempt (comment lines 227-228). Its flag is read by GrpcCircuitBreakerPredicate (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Resilience/GrpcCircuitBreakerPredicate.cs:46-49). The budget it reads is normally the one GrpcDefaultDeadlineInterceptor sets when a call carries no deadline of its own (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:42-47). Covered by GrpcDeadlineObserverHandlerTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Resilience/GrpcDeadlineObserverHandlerTests.cs) and, inside a real resilience pipeline, by GrpcDeadlineObserverPipelineTests (MMCA.Common/Tests/Presentation/MMCA.Common.Grpc.Tests/Resilience/GrpcDeadlineObserverPipelineTests.cs).
  • Caveats / not-in-source: a caller that cancels inside the last 50 ms of the budget is counted as a deadline by design (doc comment line 23). Because the budget runs from the first attempt, a caller that cancels a retried attempt late in the call's budget is likewise counted as a deadline.

ServiceContractAttribute

MMCA.Common.Shared · MMCA.Common.Shared.Abstractions · MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ServiceContractAttribute.cs:23 · Level 0 · class (sealed attribute)

  • What it is: an attribute marking a type, in practice a cross-module service interface, as part of a service's wire contract: the surface a module that can run as its own service publishes, satisfied in-process by the owning module and across the network by a gRPC adapter in the service's *.Contracts project (ServiceContractAttribute.cs:4-7).
  • Depends on: System.Attribute (BCL) only.
  • Concept introduced, explicit service contracts plus attribute-driven governance. [Rubric §7, Microservices Readiness] (assesses explicit, versioned contracts and extractability) and [Rubric §9, API & Contract Design] (versioned contracts). When a module is lifted into its own service (ADR-007), the interface consumers depend on is tagged [ServiceContract] so the wire surface is identifiable by tooling. That identification is what makes [Rubric §34, Architecture Governance & Documentation] apply: the invariant stated in the attribute's own doc comment (ServiceContractAttribute.cs:8-14) is not advisory, it is executed as a fitness function. ArchitectureRules.ServiceContractsDoNotDependOnServiceInternals (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.Contracts.cs:32) scans every assembly the repo's architecture map registers, selects the types that carry the marker (.HaveAttribute(ServiceContractAttributeFullName), line 44, matched by the full type name string held in ServiceContractAttributeFullName, line 10), and asserts none of them depends on the producing service's Domain, Application, or Infrastructure namespaces. A second rule, ServiceContractImplementationsAreNotPublic (ArchitectureRules.Contracts.cs:80), walks the same marker in the other direction (through the private CarriesServiceContractAttribute, line 135): a type implementing a [ServiceContract] interface must not itself be public, because the interface is the published surface, not the implementation.
  • Walkthrough: [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] (ServiceContractAttribute.cs:22) constrains where it can be applied and keeps it off derived types. The body is a single parameterless constructor (line 28): the attribute carries no data at all, it is a pure marker.
  • Why it's built this way: an attribute is the lightest way to mark membership in a category that tooling and tests then enforce, and the marker is deliberately attribute-driven rather than layer-driven. The remarks on ServiceContractPurityTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Layering/ServiceContractPurityTestsBase.cs:9-11) explain why: no repo registers a Layer.Contracts entry in its architecture map today, so a layer-iterating rule would pass vacuously forever, while scanning every mapped assembly for the marker catches contract types wherever they actually live (in practice, in each module's *.Shared project). The base class is also honest about the empty case (lines 12-18), and so is the attribute's own doc comment (ServiceContractAttribute.cs:12-14): a repo that marks no type passes without asserting anything, and MMCA.Common itself ships no [ServiceContract] type, so within the framework the rule is a ratchet that bites the moment a first contract type is marked. It complements, and does not replace, the transport- and layer-purity rules (ADR-015) that guard the same boundary from the layer side.
  • Where it's used: the marker is applied in the consumer repos, not in MMCA.Common, and only to interfaces (no integration-event record or DTO carries it, ServiceContractAttribute.cs:16-18). Thirteen interfaces carry it today. In ADC (nine): IAttendeeQueryService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:16), IVerifiedUserLookupService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IVerifiedUserLookupService.cs:15), IBookmarkCountService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/UserSessionBookmarks/IBookmarkCountService.cs:10), IPendingTicketInvitationService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/Tickets/Invitations/IPendingTicketInvitationService.cs:13), IUserEngagementExportService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/Exports/IUserEngagementExportService.cs:13), ISessionBookmarkValidationService (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Sessions/ISessionBookmarkValidationService.cs:10), IEventLiveValidationService (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Events/Live/IEventLiveValidationService.cs:13), IUserConferenceExportService (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Exports/IUserConferenceExportService.cs:13), and IUserNotificationExportService (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/UserNotifications/IUserNotificationExportService.cs:13). In Store (four): IProductVariantService (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Shared/Products/IProductVariantService.cs:33), IUserCatalogExportService (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Shared/Exports/IUserCatalogExportService.cs:19), ICustomerService (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Shared/Customers/ICustomerService.cs:25), and IUserSalesExportService (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Exports/IUserSalesExportService.cs:20). The rules that read the marker are surfaced to each repo through ServiceContractPurityTestsBase (ServiceContractPurityTestsBase.cs:20-26) and ContractImplementationTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Contracts/ContractImplementationTestsBase.cs:20,34), which Common, ADC, Store, and Helpdesk each subclass in their architecture-test project.
  • Caveats / not-in-source: generated gRPC client and server classes are not marked; the doc comment (ServiceContractAttribute.cs:18-19) states they are part of the contract surface by virtue of being declared in a .proto file, so the attribute is not needed on them. The attribute carries no version: contract versioning is not expressed through it, and nothing in this group negotiates a wire-level contract version.

GrpcCircuitBreakerPredicate

MMCA.Common.Grpc · MMCA.Common.Grpc.Resilience · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Resilience/GrpcCircuitBreakerPredicate.cs:32 · Level 1 · class (internal static)

  • What it is: the widening step that teaches a typed gRPC client's HTTP circuit breaker the two ways a gRPC peer actually fails: a failing grpc-status on an HTTP 200 response, and an expired call deadline.
  • Depends on: GrpcDeadlineObserverHandler (its DeadlineExpired flag); Polly (CircuitBreakerPredicateArguments<T>, Outcome<T>, ResilienceContext) and Grpc.Core.StatusCode (NuGet).
  • Concept introduced, a gRPC-aware circuit breaker. [Rubric §7, Microservices Readiness] (resilient inter-service calls). The standard HTTP breaker counts a transport exception, an attempt timeout and a 5xx, 408 or 429 response (GrpcCircuitBreakerPredicate.cs:9-11). A gRPC peer slips past all of those: a failed unary call answers HTTP 200 with the status in the response headers (a trailers-only response), and a hung peer is cut by the call's own deadline, which reaches the HTTP layer as a plain cancellation (lines 13-22). Without this widening a peer that is down or hanging would never open the breaker. The rule for what counts is "is the peer itself unwell": only Unavailable, Internal, Unknown and DeadlineExceeded count, while statuses the peer's own Result produced (NotFound, InvalidArgument, PermissionDenied, Aborted, FailedPrecondition, ResourceExhausted) mean a healthy peer and never count (lines 15-19).
  • Walkthrough:
    • StatusHeader (line 30) is the literal "grpc-status".
    • Extend(httpPredicate) (line 35) returns a new predicate: when IsPeerFailure holds it answers true, otherwise it defers to the breaker's existing HTTP predicate (lines 37-39), so nothing the HTTP default counts is lost.
    • IsPeerFailure(Outcome, ResilienceContext) (line 42) is true for a failing status, or for an OperationCanceledException whose request GrpcDeadlineObserverHandler marked as deadline-expired, fetched through context.GetRequestMessage() (lines 43-45).
    • IsFailingStatus (line 47) reads the first grpc-status header value, parses it with NumberStyles.None and invariant culture, and matches the four peer-failure codes (line 51).
  • Why it's built this way: wrapping the existing predicate instead of replacing it keeps every HTTP rule intact and keeps the caller's configureResilience override able to replace the whole thing, because that override runs after the widening (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/DependencyInjection.cs:216-224). Counting only a marked cancellation keeps caller cancellations (a closed page, a shutdown) from tripping the breaker.
  • Where it's used: AddTypedGrpcClient<TClient> in the Grpc DependencyInjection assigns options.CircuitBreaker.ShouldHandle = GrpcCircuitBreakerPredicate.Extend(options.CircuitBreaker.ShouldHandle) (DependencyInjection.cs:216), after setting the gRPC breaker values from HttpResilienceDefaults (lines 170-173).
  • Caveats / not-in-source: a status sent after a response message (a mid-stream failure) travels in the HTTP trailers, which arrive after the pipeline has returned, so the breaker cannot see it; a unary failure never takes that shape (lines 24-26).

ResultFailureException

MMCA.Common.Grpc · MMCA.Common.Grpc.Exceptions · MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Exceptions/ResultFailureException.cs:16 · Level 2 · class (sealed)

  • What it is: a typed exception that carries the IReadOnlyList<Error> from a failing Result. gRPC service implementations raise it indirectly via result.ThrowIfFailure(); the GrpcResultExceptionInterceptor catches it and translates it into an RpcException with the right status code and structured error trailers.
  • Depends on: Error (via using MMCA.Common.Shared.Abstractions, ResultFailureException.cs:1); System.Exception (BCL).
  • Concept introduced, bridging the Result pattern across the gRPC transport. [Rubric §9, API & Contract Design] (assesses consistent error shapes across transports) and [Rubric §7, Microservices Readiness] (the gRPC extraction boundary). gRPC has no native "return a failure value": failures travel as RpcException plus a status code. So the Result pattern (taught in primer §2 and G01) is adapted to the wire by smuggling the failure through a single exception type, internal to the transport edge, whose payload is the original Error list, so the interceptor can rebuild the exact same Code/Message/Type/Source/Target fields a consumer would have seen over HTTP. This mirrors the HTTP side: where REST maps Result failures to RFC 9457 Problem Details in ApiControllerBase, gRPC maps them to RpcException.
  • Walkthrough: four constructors. The three standard Exception constructors (parameterless line 19, message line 24, message plus inner exception line 30) each set Errors = [] and exist only to satisfy CA1032, the analyzer that requires the full exception constructor set (stated at line 18). The meaningful one is ResultFailureException(IReadOnlyList<Error> errors) (line 35), whose message is built by the private BuildMessage (line 41): it joins the errors as "Code: Message" pairs, or answers the literal "Result failure" when the list is empty. Errors (line 39) is a get-only property, documented as empty for the three CA1032 constructors.
  • Why it's built this way: using a single, dedicated exception rather than throwing arbitrary exceptions lets the server interceptor catch exactly one type and translate it deterministically; anything else propagating out is a genuine fault. The XML doc (lines 11-14) is explicit that service code should not throw this directly, it should call result.ThrowIfFailure() from ResultGrpcExtensions, which keeps the throw site uniform and guarantees the Errors-carrying constructor is the one used.
  • Where it's used: thrown by ThrowIfFailure() and UnwrapOrThrow<T>() in ResultGrpcExtensions (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:81,81); caught by GrpcResultExceptionInterceptor in all four server-handler shapes.
  • Caveats / not-in-source: the three CA1032 constructors produce an instance with no errors, and that case is not free downstream. The interceptor treats it specially (see GrpcResultExceptionInterceptor.cs:126-138) because the normal encoder would otherwise flatten the message away; prefer the IReadOnlyList<Error> constructor, which is what ThrowIfFailure uses.

⬅ API Hosting, Middleware, Idempotency & DTO/Contract Mapping • Index • Module System, Composition & Configuration ➡