Hmz.Core.Integrations
0.1.0
See the version list below for details.
dotnet add package Hmz.Core.Integrations --version 0.1.0
NuGet\Install-Package Hmz.Core.Integrations -Version 0.1.0
<PackageReference Include="Hmz.Core.Integrations" Version="0.1.0" />
<PackageVersion Include="Hmz.Core.Integrations" Version="0.1.0" />
<PackageReference Include="Hmz.Core.Integrations" />
paket add Hmz.Core.Integrations --version 0.1.0
#r "nuget: Hmz.Core.Integrations, 0.1.0"
#:package Hmz.Core.Integrations@0.1.0
#addin nuget:?package=Hmz.Core.Integrations&version=0.1.0
#tool nuget:?package=Hmz.Core.Integrations&version=0.1.0
Hmz.Core.Integrations
Hmz.Core.Integrations gives every third-party integration the same boundary:
one error model, one place that classifies failures, and the same logs, traces,
metrics and retry rules. It is opt-in and separate from SharedKernel, so an
application without third-party calls does not take its HTTP-resilience
dependency. It grew out of the Monosbase ERPNext integration.
Layers
| Layer | Owner | Purpose |
|---|---|---|
Port (IProductGateway, …) |
Application UseCase | What the use case needs; no HTTP types. |
Typed client (Refit, HttpClient) |
Application Infrastructure | The provider's wire contract. |
IIntegrationErrorAdapter |
Application Infrastructure, one per provider | Reads the provider's error body (code, message) and maps it to an IntegrationErrorKind. |
IIntegrationResponseReader |
Application Infrastructure, one per client library | Reads status and body from the library's error exception (for example Refit ApiException). |
IntegrationExecutor |
Core | Runs the call; classifies every failure into one IntegrationException; logs, traces and counts it. |
AddIntegrationResilience() |
Core | Standard resilience pipeline that retries only calls safe to repeat. |
Use cases map IntegrationErrorKind to their own module error codes and never
parse provider responses. Only IsTransient failures (Unavailable,
RateLimited) should tell a user to retry.
Error model
IntegrationError(Kind, StatusCode, ProviderCode, Message):
Kind:Duplicate,Validation,MissingRequired,MissingReference,InUse,NotFound,Concurrency,Unauthorized,Forbidden,RateLimited,Unavailable,Unknown.ProviderCode: the provider's own code or exception type, for diagnostics and for the adapter's mapping.Message: sanitized, bounded provider message for diagnostics only.
IntegrationException adds Provider, Operation and Category
(UpstreamResponse, Transport, Timeout, Contract). Its message never
contains the response body.
How the executor classifies a failure:
| Failure | Category | Error |
|---|---|---|
Error response read by an IIntegrationResponseReader |
UpstreamResponse |
Adapter Classify(status, body) |
| Transport exception inside the client exception | Transport |
Unavailable, 503 |
JsonException anywhere in the chain |
Contract |
Unavailable, 502 |
Polly TimeoutRejectedException, TimeoutException, unrequested cancellation |
Timeout |
Unavailable, 503 |
HttpRequestException |
Transport |
Adapter status mapping (503 when no status) |
IOException, SocketException |
Transport |
Unavailable, 503 |
Caller cancellation, IntegrationException, anything else |
— | Rethrown unchanged |
Usage
// Infrastructure DI
services.AddIntegrationResponseReader<RefitApiExceptionReader>();
services.AddSingleton<PaymentsErrorAdapter>();
services.AddRefitClient<IPaymentsApi>()
.ConfigureHttpClient(client => client.BaseAddress = options.BaseUrl)
.AddIntegrationResilience(resilience => resilience.MaxRetryAttempts = 3);
// Gateway
public sealed class PaymentsGateway(IPaymentsApi api, IntegrationExecutor executor, PaymentsErrorAdapter adapter)
: IPaymentsGateway
{
public Task<Charge> ChargeAsync(ChargeRequest request, CancellationToken ct) =>
executor.ExecuteAsync(
new IntegrationCall(adapter, "charge.create", new Dictionary<string, object?> { ["OrderId"] = request.OrderId }),
token => api.CreateChargeAsync(request, token),
ct);
}
A response the caller checks itself (for example a typed IApiResponse) is
classified with executor.Reject(call, statusCode, body), which logs and
returns the exception to throw.
Adapters
Derive from IntegrationErrorAdapter and override only what the provider
changes:
ReadError(body): the provider's error code and message (never throw).KindForProviderCode(code): the kind for a known code, ornull.KindForStatus(status): the status fallback, when the provider uses statuses differently (ERPNext reports business failures as 417).
IntegrationDiagnostics.Sanitize(body, properties) produces the safe
diagnostic message: single line, credential-like values redacted, at most
256 characters.
Resilience
AddIntegrationResilience() adds the standard handler with exponential backoff
and jitter (RetryBaseDelay, 2 s by default, doubles per retry), a 15 s
attempt timeout and a 45 s total timeout. GET, HEAD,
OPTIONS, PUT and DELETE are retried; a POST or PATCH only when it carries the
Idempotency-Key header (configurable, or null to never retry them), because
repeating a create would duplicate the record at the provider.
It replaces any resilience handler the client already has. Applications often
add a standard handler to every client with ConfigureHttpClientDefaults;
stacked, that outer pipeline would retry a POST this one refuses to retry
(a failing create reached the provider four times in the test).
Telemetry
Register IntegrationTelemetry.Name (Hmz.Core.Integrations) as an
OpenTelemetry activity source and meter. Each call is a client span tagged
with provider and operation; hmz.integration.calls and
hmz.integration.duration carry provider, operation and outcome (success
or the error kind).
Without a listener the span is not created and the instruments record
nothing, so an application that exports neither pays almost nothing. Log
messages are generated at build time (LoggerMessage), and the debug detail
(the sanitized provider message) is only read when debug logging is on.
Credentials
AddApiKeyCredential(key, headerName) sends a provider API key with every
request: as Authorization: Bearer <key> by default, or in the provider's own
header. The key is read for every request (for example from
IOptionsMonitor<T>), so a rotated key applies without a restart; a request
that already carries the header is left as is.
services.AddHttpClient<LlmClient>()
.AddApiKeyCredential(sp => sp.GetRequiredService<IOptionsMonitor<LlmOptions>>().CurrentValue.ApiKey)
.AddIntegrationResilience();
Extending
Every provider-specific part is a seam, so a special integration plugs in without changes to Core:
| Need | Extension point |
|---|---|
| A provider's own error body, codes or status meanings | Derive from IntegrationErrorAdapter (or implement IIntegrationErrorAdapter for a completely different shape). |
A client library other than Refit or HttpClient |
Implement IIntegrationResponseReader and register it with AddIntegrationResponseReader<T>(). |
| A call the executor must not classify (streaming, polling) | Classify the response yourself with executor.Reject(call, status, body). |
| Different retries, timeouts or a circuit breaker | Set IntegrationResilienceOptions, or configure the IHttpStandardResiliencePipelineBuilder that AddIntegrationResilience() returns. |
| Another credential (OAuth2, HMAC, session cookie) | Add your own DelegatingHandler with AddHttpMessageHandler; ApiKeyCredentialHandler is the pattern. |
| Extra log scope values | Pass them in IntegrationCall.Context (identifiers only). |
Not included yet
OAuth2 client credentials, session cookie and HMAC signing handlers, and
inbound webhook verification are planned next; until then such an
integration keeps its own DelegatingHandler.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Http.Resilience (>= 10.1.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.