From c15bd210f71938df582fe7616fc8879bbf1ddea6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:01:59 -0500 Subject: [PATCH] fix(delmia,inbound): a connect-phase failure (unreachable host, connect timeout) fails over to the next URL/peer instead of OUTCOME_UNKNOWN (DLM-1, WP4 task 4.7) --- docs/components/DelmiaNotifier.md | 2 +- docs/requirements/Component-InboundAPI.md | 6 +- .../ConnectPhase.cs | 84 +++++++++++++++++++ .../HttpRecipeSender.cs | 17 ++-- .../Program.cs | 8 +- .../README.md | 17 ++-- .../HttpStandbyRequestForwarder.cs | 14 +++- .../RelayConnectPhase.cs | 74 ++++++++++++++++ .../ServiceCollectionExtensions.cs | 6 +- .../HttpRecipeSenderTests.cs | 82 ++++++++++++++++++ .../StandbyRequestForwardingTests.cs | 27 ++++++ 11 files changed, 317 insertions(+), 20 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs create mode 100644 src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs diff --git a/docs/components/DelmiaNotifier.md b/docs/components/DelmiaNotifier.md index 8ad3c5c7..7e706aab 100644 --- a/docs/components/DelmiaNotifier.md +++ b/docs/components/DelmiaNotifier.md @@ -28,7 +28,7 @@ The spec for this component is the project `README.md` plus `docs/plans/2026-06- | Kind | Raised when | Loop behaviour | |---|---|---| -| `ConnectFailed` | `HttpRequestException` with `HttpRequestError.NameResolutionError`, or an inner `SocketException` with `ConnectionRefused` | Try the next URL | +| `ConnectFailed` | Any failure while opening the TCP connection — refusal, name resolution, unreachable/powered-off host, or the connect timeout (`min(5 s, TimeoutSeconds / 2)`) firing — recognised by the `ConnectPhaseException` marker the client's `ConnectCallback` puts in the exception chain (DLM-1); also the legacy `NameResolutionError` / `ConnectionRefused` shapes | Try the next URL | | `StandbyRejected` | HTTP 503 whose `X-ScadaBridge-Standby` header is exactly `1` | Try the next URL | | `OutcomeUnknown` | Any other `HttpRequestException`, or a timeout (`OperationCanceledException` not caused by the caller's token) | Stop; return `NO` with `OUTCOME_UNKNOWN: the request may have been applied; verify before retrying.` | | `Connected` | Any HTTP response not matched above | Stop; the node's answer is final | diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index e2bc85b8..52826d71 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -148,7 +148,7 @@ The `sbk__` design already supports zero-downtime rotation — a | `VALIDATION_FAILED` | 400 | Parameter validation failed (missing required field, wrong type, undeclared field). | | `BODY_TOO_LARGE` | 413 | Request body exceeded `MaxRequestBodyBytes`. | | `STANDBY_NODE` | 503 | Request hit a standby central node that could not relay it: no `StandbyForwardPeerEndpoints` configured, or the request was already relayed once (loop guard — neither node is active, e.g. mid-failover). Carries the `X-ScadaBridge-Standby: 1` response header. | -| `ACTIVE_NODE_UNREACHABLE` | 503 | Every configured peer refused before execution or failed with proven name-resolution/connection-refusal errors. | +| `ACTIVE_NODE_UNREACHABLE` | 503 | Every configured peer refused before execution or failed while opening the connection (refusal, name resolution, unreachable host, 5 s connect timeout). | | `OUTCOME_UNKNOWN` | 502 | A relay timed out or lost its response after possible execution; it does not replay the request. Verify the operation before retrying. | | `TIMEOUT` | 500 | The method script exceeded its execution timeout. | | `SITE_UNREACHABLE` | 500 | The target site did not respond to the routed request within the routing timeout (no contact / down / partitioned) — typed from the routed Ask expiring (`AskTimeoutException`), never inferred from an error-message substring. A `Success=false` response means the site answered and is classified `SCRIPT_ERROR`. | @@ -374,7 +374,7 @@ A standby now **relays** the request to the active peer instead (`InboundApiEndp - **Configuration.** `ScadaBridge:InboundApi:StandbyForwardPeerEndpoints` — the HTTP base URL(s) of the *other* central node(s), e.g. `["http://scadabridge-central-b:5000"]` on central-a. Empty (default) keeps the old 503 behaviour. `StandbyForwardTimeout` (default 60 s) is the total relay budget and should exceed the longest method timeout plus network overhead. Validated at startup (absolute http/https URLs, positive timeout). Note the standby discovers the active peer from **appsettings**, not from cluster state — the Akka member address carries the remoting port, not the HTTP port — the options snapshot is read per relay. - **Pure relay.** Method, path, query string, body and credentials travel unchanged; hop-by-hop/Host/forwarding-provenance headers are excluded and authenticated provenance is rebuilt, so the **active node** authenticates the caller's own `Authorization`/`X-API-Key` credential, applies its own body cap and method timeout, and writes the audit row. The peer's status, `Content-Type` and body are replayed unchanged. The serving node owns its `ApiInbound` row; the originating standby retains a failure row when no peer serves or the outcome is uncertain. Verified internal standby refusals are not duplicated. - **Order of checks.** The body-size cap (HTTP 413) runs before audit reads and the active-node check, so a standby never buffers or relays a body the active node would refuse. A relaying standby skips the audit middleware's request/response capture entirely; the body is read once, by the forwarder (bounded by `MaxRequestBodyBytes`), so it can be re-sent to a second peer. On the node that executes, request bodies up to the 1 MiB cap are buffered in memory (`EnableBuffering` with the cap as threshold), not spilled to a temp file. The relay proof (`X-ScadaBridge-Relay`) carries a random nonce, is signed fresh per peer attempt, and is **single-use** within its 300 s window: the receiver keeps a bounded `(ExecutionId, nonce)` set and treats a repeat (or a nonce-less proof from an older peer) as unverified — the request still runs, but a captured proof cannot re-stamp ExecutionId/IP. -- **Peer selection.** The standby knows only that it is *not* active. It tries the peers in order and accepts the first response that is not a standby refusal; a peer answering 503 with `X-ScadaBridge-Standby: 1`, proven name-resolution failure, or connection refusal permits trying the next peer. Timeout or ambiguous response loss returns 502 `OUTCOME_UNKNOWN` without replay. A 503 *without* the marker is the active node's own answer and is replayed, not retried. All peers failing → 503 `ACTIVE_NODE_UNREACHABLE`. +- **Peer selection.** The standby knows only that it is *not* active. It tries the peers in order and accepts the first response that is not a standby refusal; a peer answering 503 with `X-ScadaBridge-Standby: 1`, or any failure while opening the TCP connection (refusal, name resolution, unreachable/powered-off host, the relay client's 5 s connect timeout — DLM-1, 2026-12; recognised by a marker the relay handler's `ConnectCallback` puts in the exception chain), permits trying the next peer. Before DLM-1 a powered-off peer held the relay for the whole 60 s `StandbyForwardTimeout` and ended in 502 `OUTCOME_UNKNOWN`. Timeout or ambiguous response loss returns 502 `OUTCOME_UNKNOWN` without replay. A 503 *without* the marker is the active node's own answer and is replayed, not retried. All peers failing → 503 `ACTIVE_NODE_UNREACHABLE`. - **One-hop loop guard.** Every relayed request carries `X-ScadaBridge-Forwarded: `. A standby never relays a request that already carries it — it answers 503 `STANDBY_NODE` with the marker header — so a pair in which neither node is active (a transient during failover) bounces at most one hop and never ping-pongs. The active node ignores the header and serves the request normally. - **Still not a retry layer.** The relay makes one HTTP attempt per peer and does not retry a peer that answered; at-least-once callers keep their own retry loop and the idempotent-method authoring note above still applies. @@ -412,6 +412,6 @@ A serving peer owns the inbound audit for its success or method failure. The ori Relays overwrite caller-supplied provenance with an HMAC signed envelope using a domain-separated key derived from `ApiKeyPepper`. Both centrals must share that server secret. The envelope binds the original verified remote address, execution ID, timestamp, method, path/query, content type, caller credentials, and bounded body digest. The receiver accepts it for at most five minutes and only when the request binding matches. Unsigned loop markers and forwarded-address headers confer no identity trust; missing or invalid proof uses the receiver's verified remote address. Forwarding remains one hop. Use TLS between peers when network confidentiality is required. -`StandbyForwardTimeout` is one budget across permitted attempts and response consumption. Only explicit pre-execution standby rejection, name-resolution failure, or connection refusal permits another peer. Timeout or response loss returns HTTP 502 `OUTCOME_UNKNOWN`: verify the operation before manually retrying because it may already have applied. This avoids blindly replaying non-idempotent methods. +`StandbyForwardTimeout` is one budget across permitted attempts and response consumption. Only explicit pre-execution standby rejection or a connect-phase failure (refusal, name resolution, unreachable host, connect timeout) permits another peer. Timeout or response loss returns HTTP 502 `OUTCOME_UNKNOWN`: verify the operation before manually retrying because it may already have applied. This avoids blindly replaying non-idempotent methods. `SkipBodyCapture` suppresses request/response summaries and all exception message/detail text, including stashed script exceptions; retain status/category and request metadata for diagnosis. Error text can quote payload values and is subject to the same privacy boundary as the body. diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs new file mode 100644 index 00000000..d5ce0ec8 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs @@ -0,0 +1,84 @@ +using System.Net.Http; +using System.Net.Sockets; + +namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier; + +/// +/// Makes "the request was never sent" observable (DLM-1). The handler built here owns the TCP +/// connect through and wraps every connect +/// failure — refusal, DNS, an unreachable/black-holed host, the +/// firing — in , which keeps in the +/// exception chain it surfaces. A failure carrying the marker happened before any byte of the request +/// was written, so trying the next base URL is safe. Anything without it (a reset or timeout after the +/// connection was up) may have reached the server and stays OUTCOME_UNKNOWN. +/// +internal static class ConnectPhase +{ + /// + /// Default TCP connect timeout. Well below the notifier's overall request timeout, so a powered-off + /// node fails as a connect failure (and the next URL is tried) instead of eating the whole budget. + /// + public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5); + + /// + /// The connect timeout for a given overall request timeout: , + /// but never more than half the overall budget, so it always fires first on a black-holed host. + /// + /// The overall request timeout. + /// The connect timeout to use. + public static TimeSpan ConnectTimeoutFor(TimeSpan overall) + { + var half = overall / 2; + return half < DefaultConnectTimeout ? half : DefaultConnectTimeout; + } + + /// Creates a handler whose connect failures carry . + /// The TCP connect timeout. + /// The configured handler. + public static SocketsHttpHandler CreateHandler(TimeSpan connectTimeout) => new() + { + ConnectTimeout = connectTimeout, + ConnectCallback = async (context, ct) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(context.DnsEndPoint, ct).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) + { + socket.Dispose(); + throw new ConnectPhaseException( + $"could not connect to {context.DnsEndPoint.Host}:{context.DnsEndPoint.Port}: {ex.Message}", ex); + } + }, + }; + + /// + /// True when provably failed before the request was sent: the connect + /// marker is in its chain, or (handlers built without the marker) DNS failed or the connection + /// was refused. + /// + /// The failure from HttpClient.SendAsync. + /// true when the request was never sent. + public static bool WasNotSent(Exception error) + { + for (var e = error; e is not null; e = e.InnerException) + { + if (e is ConnectPhaseException) + return true; + if (e is HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError }) + return true; + if (e is HttpRequestException { InnerException: SocketException { SocketErrorCode: SocketError.ConnectionRefused } }) + return true; + } + + return false; + } +} + +/// Marks a failure that happened while opening the TCP connection — nothing was sent. +/// The failure description. +/// The underlying connect failure. +internal sealed class ConnectPhaseException(string message, Exception inner) : Exception(message, inner); diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs index cc756f3d..4ec786c8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs @@ -6,9 +6,10 @@ namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier; /// /// over a real : POSTs the recipe payload to /// {baseUrl}/api/DelmiaRecipeDownload with the X-API-Key header. A reachable server -/// response is final except for the explicit pre-execution standby marker. Only proven -/// connection refusal/name resolution failures permit another URL; timeouts and other -/// transport failures have an uncertain application outcome. +/// response is final except for the explicit pre-execution standby marker. Only a proven +/// connect-phase failure (refused, name resolution, unreachable host, connect timeout — see +/// ) permits another URL; timeouts and other transport failures after +/// the connection was up have an uncertain application outcome. /// internal sealed class HttpRecipeSender(HttpClient http, string apiKey) : IRecipeSender { @@ -41,12 +42,18 @@ internal sealed class HttpRecipeSender(HttpClient http, string apiKey) : IRecipe } catch (HttpRequestException ex) { - var knownNotSent = ex.HttpRequestError == HttpRequestError.NameResolutionError - || ex.InnerException is System.Net.Sockets.SocketException { SocketErrorCode: System.Net.Sockets.SocketError.ConnectionRefused }; + // DLM-1: any connect-phase failure (refused, DNS, unreachable/black-holed host) is + // "not sent", so the next URL is tried; a failure after the send stays unknown. + var knownNotSent = ConnectPhase.WasNotSent(ex); return new AttemptOutcome(knownNotSent ? AttemptKind.ConnectFailed : AttemptKind.OutcomeUnknown, 0, null, ex.Message); } catch (OperationCanceledException ex) when (!ct.IsCancellationRequested) { + // The handler's ConnectTimeout firing on a powered-off node surfaces as a + // cancellation carrying the connect marker: nothing was sent (DLM-1). + if (ConnectPhase.WasNotSent(ex)) + return new AttemptOutcome(AttemptKind.ConnectFailed, 0, null, "connect timeout: " + ex.Message); + // A missing response does not prove the node failed to apply the request. return new AttemptOutcome(AttemptKind.OutcomeUnknown, 0, null, "timeout: " + ex.Message); } diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs index 6db080d5..8c752d60 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs @@ -51,7 +51,13 @@ internal static class Program log.Write("api key source: " + apiKeySource); - using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(cfg.ScadaBridge.TimeoutSeconds) }; + // DLM-1: a connect-timeout-bounded handler that marks connect-phase failures, so a + // powered-off node fails over to the next URL instead of reporting OUTCOME_UNKNOWN. + var overall = TimeSpan.FromSeconds(cfg.ScadaBridge.TimeoutSeconds); + // Strictly inside the overall timeout, so the connect timeout (which keeps the marker) + // always fires before HttpClient.Timeout (which does not) on an unanswered SYN. + var connectTimeout = ConnectPhase.ConnectTimeoutFor(overall); + using var http = new HttpClient(ConnectPhase.CreateHandler(connectTimeout)) { Timeout = overall }; var sender = new LoggingRecipeSender(new HttpRecipeSender(http, apiKey), log); log.Write($"notifying {baseUrls.Length} URL(s) for machine {parse.Payload!.MachineCode}"); diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md index 86dcfb4c..1d422b79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md @@ -54,9 +54,14 @@ WWNotifier.exe -m Z28061 -d "C:\recipes\job.nc" -w WO12345 -p PN-7788 -s 0100 -u ## Delivery semantics -The notifier retries only when a request is known not to have executed: connection refusal, -name-resolution failure, or the server's explicit standby rejection. A connection reset after -sending or a response timeout returns `OUTCOME_UNKNOWN` without replay. Operators must verify +The notifier retries only when a request is known not to have executed: any failure to open the +TCP connection (refusal, name resolution, an unreachable or powered-off host, or the connect +timeout — `min(5 s, TimeoutSeconds / 2)` — firing on an unanswered SYN), or the server's explicit +standby rejection. A connection reset after sending or a response timeout returns `OUTCOME_UNKNOWN` +without replay. (DLM-1, 2026-12: before, a powered-off first node waited out the whole timeout and +reported `OUTCOME_UNKNOWN` without ever trying the healthy second node; the client now owns the +connect through `SocketsHttpHandler.ConnectCallback` and marks every connect-phase failure, so the +"not sent" case is provable.) Operators must verify an uncertain result before manually retrying. Idempotent method implementations remain useful because callers can deliberately retry, but the notifier does not blindly repeat ambiguous sends. @@ -76,8 +81,8 @@ Placed next to the exe (copied to the output on build/publish): ``` - **`BaseUrls`** — comma-separated failover list of **base URLs only**; the app appends - `/api/DelmiaRecipeDownload`. URLs are tried in order after proven DNS/connection refusal or - explicit standby rejection. Other HTTP responses are final; ambiguous transport errors return + `/api/DelmiaRecipeDownload`. URLs are tried in order after a proven connect-phase failure + (refused, DNS, unreachable host, connect timeout) or explicit standby rejection. Other HTTP responses are final; ambiguous transport errors return `NO` + `OUTCOME_UNKNOWN` without trying another URL. - **`TimeoutSeconds`** — per-attempt HTTP timeout (default `30`). - **`LogPath`** — optional diagnostic log file, relative to the exe. Omit to log to stderr only. @@ -155,6 +160,6 @@ bash docker/verify-delmia-notifier.sh # runs the managed build from a scratc ### Safe failover -The notifier advances to the next configured URL after a proven connection refusal/name-resolution failure, or HTTP 503 carrying the server's exact `X-ScadaBridge-Standby: 1` pre-execution marker. A generic 503 or business rejection is final. Both centrals may therefore be listed even when their internal standby-forwarding peer lists are absent. +The notifier advances to the next configured URL after a proven connect-phase failure (refusal, name resolution, unreachable host, connect timeout), or HTTP 503 carrying the server's exact `X-ScadaBridge-Standby: 1` pre-execution marker. A generic 503 or business rejection is final. Both centrals may therefore be listed even when their internal standby-forwarding peer lists are absent. A timeout or other response loss is reported as `OUTCOME_UNKNOWN` with a failed result and no automatic replay: the first node may already have applied the download. Verify the operation before manually retrying. Configure trusted central endpoints; the standby marker is a server protocol contract, not permission to retry arbitrary HTTP errors. diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs index 3b90c39f..c5b4f963 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs @@ -146,6 +146,12 @@ public sealed class HttpStandbyRequestForwarder : IStandbyRequestForwarder { throw; // caller went away — nothing to answer } + catch (OperationCanceledException ex) when (!deadline.IsCancellationRequested && RelayConnectPhase.WasNotSent(ex)) + { + // DLM-1: the connect timeout fired on a powered-off/black-holed peer — nothing was + // sent, so the next peer is safe to try. + _logger.LogWarning(ex, "Inbound relay could not connect to {Peer} (connect timeout); trying next peer", peer); + } catch (OperationCanceledException) { _logger.LogWarning("Inbound relay deadline expired after dispatch to {Peer}; outcome uncertain", peer); @@ -199,9 +205,11 @@ public sealed class HttpStandbyRequestForwarder : IStandbyRequestForwarder return request; } - private static bool KnownNotDispatched(HttpRequestException error) - => error.HttpRequestError == HttpRequestError.NameResolutionError - || error.InnerException is System.Net.Sockets.SocketException { SocketErrorCode: System.Net.Sockets.SocketError.ConnectionRefused }; + /// + /// A connect-phase failure — refused, DNS, unreachable/black-holed host (DLM-1, via the + /// handler's marker) — never sent the request. + /// + private static bool KnownNotDispatched(HttpRequestException error) => RelayConnectPhase.WasNotSent(error); private static IResult OutcomeUnknown() => Results.Json(new { diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs new file mode 100644 index 00000000..520fc1e9 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs @@ -0,0 +1,74 @@ +using System.Net.Http; +using System.Net.Sockets; + +namespace ZB.MOM.WW.ScadaBridge.InboundAPI; + +/// +/// Standby-relay copy of the DelmiaNotifier's ConnectPhase (the notifier is a separate, +/// dependency-free client tool, so the two cannot share it). Makes "the request was never sent" +/// observable (DLM-1). The handler built here owns the TCP +/// connect through and wraps every connect +/// failure — refusal, DNS, an unreachable/black-holed host, the +/// firing — in , which keeps in the +/// exception chain it surfaces. A failure carrying the marker happened before any byte of the request +/// was written, so trying the next base URL is safe. Anything without it (a reset or timeout after the +/// connection was up) may have reached the active peer and stays OUTCOME_UNKNOWN. +/// +internal static class RelayConnectPhase +{ + /// + /// Default TCP connect timeout. Well below the relay's StandbyForwardTimeout, so a powered-off + /// peer fails as a connect failure (and the next peer is tried) instead of eating the whole budget. + /// + public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5); + + /// Creates a handler whose connect failures carry . + /// The TCP connect timeout. + /// The configured handler. + public static SocketsHttpHandler CreateHandler(TimeSpan connectTimeout) => new() + { + ConnectTimeout = connectTimeout, + ConnectCallback = async (context, ct) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(context.DnsEndPoint, ct).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) + { + socket.Dispose(); + throw new RelayConnectPhaseException( + $"could not connect to {context.DnsEndPoint.Host}:{context.DnsEndPoint.Port}: {ex.Message}", ex); + } + }, + }; + + /// + /// True when provably failed before the request was sent: the connect + /// marker is in its chain, or (handlers built without the marker) DNS failed or the connection + /// was refused. + /// + /// The failure from HttpClient.SendAsync. + /// true when the request was never sent. + public static bool WasNotSent(Exception error) + { + for (var e = error; e is not null; e = e.InnerException) + { + if (e is RelayConnectPhaseException) + return true; + if (e is HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError }) + return true; + if (e is HttpRequestException { InnerException: SocketException { SocketErrorCode: SocketError.ConnectionRefused } }) + return true; + } + + return false; + } +} + +/// Marks a failure that happened while opening the TCP connection — nothing was sent. +/// The failure description. +/// The underlying connect failure. +internal sealed class RelayConnectPhaseException(string message, Exception inner) : Exception(message, inner); diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs index 3b9d4087..acf0fd42 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs @@ -42,8 +42,12 @@ public static class ServiceCollectionExtensions // named client has no HttpClient.Timeout of its own — the forwarder's per-attempt // CTS (InboundApiOptions.StandbyForwardTimeout) is the single deadline, so a // long-running method on the active node is not cut off by a second, hidden cap. + // DLM-1: the primary handler bounds the TCP connect (5 s) and marks connect-phase + // failures, so a powered-off peer is "not dispatched" (next peer / 503 + // ACTIVE_NODE_UNREACHABLE) rather than a 60 s wait ending in 502 OUTCOME_UNKNOWN. services.AddHttpClient(HttpStandbyRequestForwarder.HttpClientName) - .ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan); + .ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan) + .ConfigurePrimaryHttpMessageHandler(() => RelayConnectPhase.CreateHandler(RelayConnectPhase.DefaultConnectTimeout)); services.AddSingleton(); // N1: the ApiMethod consumer of the script-artifact invalidation bus. diff --git a/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs index f8abfa64..acab5cb4 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs @@ -102,4 +102,86 @@ public class HttpRecipeSenderTests Assert.Equal(AttemptKind.Connected, outcome.Kind); Assert.Equal(500, outcome.StatusCode); } + + /// + /// DLM-1 regression: a powered-off / black-holed node (TEST-NET-1 never answers the SYN) is a + /// connect failure — the next URL is tried — not OUTCOME_UNKNOWN. On a host without a default + /// route the connect fails fast instead; both carry the connect marker. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_BlackHoledHost_IsConnectFailed_NotOutcomeUnknown() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500))) + { + Timeout = TimeSpan.FromSeconds(10), + }; + var sender = new HttpRecipeSender(http, "sbk_x"); + + var outcome = await sender.SendAsync("http://192.0.2.1:8083", Payload, CancellationToken.None); + + Assert.Equal(AttemptKind.ConnectFailed, outcome.Kind); + } + + /// DLM-1: with the real handler a refused connection is still a connect failure. + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_RefusedWithRealHandler_IsConnectFailed() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromSeconds(5))); + var outcome = await new HttpRecipeSender(http, "sbk_x").SendAsync("http://127.0.0.1:1", Payload, CancellationToken.None); + Assert.Equal(AttemptKind.ConnectFailed, outcome.Kind); + } + + /// + /// DLM-1: the notifier moves past a black-holed first URL to the second one instead of stopping + /// at OUTCOME_UNKNOWN (both are unreachable here, so the run reports a connect failure for all). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_BlackHoledFirstUrl_TriesTheNextUrl() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500))) + { + Timeout = TimeSpan.FromSeconds(10), + }; + var tried = new List(); + var sender = new RecordingSender(new HttpRecipeSender(http, "sbk_x"), tried); + + var outcome = await Notifier.RunAsync(["http://192.0.2.1:8083", "http://127.0.0.1:1"], Payload, sender, CancellationToken.None); + + Assert.False(outcome.Ok); + Assert.Equal(2, tried.Count); + Assert.DoesNotContain("OUTCOME_UNKNOWN", outcome.Reason); + } + + /// DLM-1: a failure after the connection was up (no marker) stays outcome-unknown. + [Fact] + public void DLM1_WasNotSent_RequiresTheConnectMarker() + { + Assert.True(ConnectPhase.WasNotSent(new TaskCanceledException("canceled", + new TimeoutException("connect timeout", new ConnectPhaseException("x", new OperationCanceledException()))))); + Assert.False(ConnectPhase.WasNotSent(new TaskCanceledException("HttpClient.Timeout", + new TimeoutException("A task was canceled.", new TaskCanceledException())))); + Assert.False(ConnectPhase.WasNotSent(new HttpRequestException(HttpRequestError.ResponseEnded, "ended", + new IOException("reset")))); + } + + /// ConnectTimeoutFor stays strictly inside the overall timeout. + [Fact] + public void ConnectTimeoutFor_IsCappedAtHalfTheOverallTimeout() + { + Assert.Equal(TimeSpan.FromSeconds(5), ConnectPhase.ConnectTimeoutFor(TimeSpan.FromSeconds(30))); + Assert.Equal(TimeSpan.FromSeconds(1.5), ConnectPhase.ConnectTimeoutFor(TimeSpan.FromSeconds(3))); + } + + private sealed class RecordingSender(IRecipeSender inner, List tried) : IRecipeSender + { + /// + public Task SendAsync(string baseUrl, RecipeDownload payload, CancellationToken ct) + { + tried.Add(baseUrl); + return inner.SendAsync(baseUrl, payload, ct); + } + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs index ebda7dbe..e8b4b006 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs @@ -297,6 +297,33 @@ public class StandbyRequestForwardingTests AssertStatus(result, StatusCodes.Status503ServiceUnavailable); } + /// + /// DLM-1 regression: a powered-off / black-holed peer (TEST-NET-1 never answers the SYN) is a + /// not-dispatched connect failure with the production handler — the relay moves on and, with + /// every peer unreachable, answers 503 ACTIVE_NODE_UNREACHABLE instead of a 60 s wait ending + /// in 502 OUTCOME_UNKNOWN. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Forwarder_BlackHoledPeer_IsNotDispatched_TriesNextPeer() + { + using var handler = RelayConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500)); + var forwarder = new HttpStandbyRequestForwarder( + new FakeHttpClientFactory(handler), + new StaticOptionsMonitor(new InboundApiOptions + { + StandbyForwardPeerEndpoints = ["http://192.0.2.1:5000", "http://127.0.0.1:1"], + StandbyForwardTimeout = TimeSpan.FromSeconds(20), + }), + NullLogger.Instance); + + var sw = System.Diagnostics.Stopwatch.StartNew(); + var result = await forwarder.ForwardAsync(BuildRequestContext("{}"), CancellationToken.None); + + AssertStatus(result, StatusCodes.Status503ServiceUnavailable); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(15), $"took {sw.Elapsed}"); + } + /// Verifies that a peer timeout returns an uncertain result without trying the next peer. /// A task that represents the asynchronous operation. [Fact]