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)
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier;
|
||||
|
||||
/// <summary>
|
||||
/// Makes "the request was never sent" observable (DLM-1). The handler built here owns the TCP
|
||||
/// connect through <see cref="SocketsHttpHandler.ConnectCallback"/> and wraps every connect
|
||||
/// failure — refusal, DNS, an unreachable/black-holed host, the <see cref="SocketsHttpHandler.ConnectTimeout"/>
|
||||
/// firing — in <see cref="ConnectPhaseException"/>, which <see cref="SocketsHttpHandler"/> 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 <c>OUTCOME_UNKNOWN</c>.
|
||||
/// </summary>
|
||||
internal static class ConnectPhase
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// The connect timeout for a given overall request timeout: <see cref="DefaultConnectTimeout"/>,
|
||||
/// but never more than half the overall budget, so it always fires first on a black-holed host.
|
||||
/// </summary>
|
||||
/// <param name="overall">The overall request timeout.</param>
|
||||
/// <returns>The connect timeout to use.</returns>
|
||||
public static TimeSpan ConnectTimeoutFor(TimeSpan overall)
|
||||
{
|
||||
var half = overall / 2;
|
||||
return half < DefaultConnectTimeout ? half : DefaultConnectTimeout;
|
||||
}
|
||||
|
||||
/// <summary>Creates a handler whose connect failures carry <see cref="ConnectPhaseException"/>.</summary>
|
||||
/// <param name="connectTimeout">The TCP connect timeout.</param>
|
||||
/// <returns>The configured handler.</returns>
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="error"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="error">The failure from <c>HttpClient.SendAsync</c>.</param>
|
||||
/// <returns><c>true</c> when the request was never sent.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks a failure that happened while opening the TCP connection — nothing was sent.</summary>
|
||||
/// <param name="message">The failure description.</param>
|
||||
/// <param name="inner">The underlying connect failure.</param>
|
||||
internal sealed class ConnectPhaseException(string message, Exception inner) : Exception(message, inner);
|
||||
@@ -6,9 +6,10 @@ namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier;
|
||||
/// <summary>
|
||||
/// <see cref="IRecipeSender"/> over a real <see cref="HttpClient"/>: POSTs the recipe payload to
|
||||
/// <c>{baseUrl}/api/DelmiaRecipeDownload</c> with the <c>X-API-Key</c> 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
|
||||
/// <see cref="ConnectPhase"/>) permits another URL; timeouts and other transport failures after
|
||||
/// the connection was up have an uncertain application outcome.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 };
|
||||
/// <summary>
|
||||
/// A connect-phase failure — refused, DNS, unreachable/black-holed host (DLM-1, via the
|
||||
/// <see cref="RelayConnectPhase"/> handler's marker) — never sent the request.
|
||||
/// </summary>
|
||||
private static bool KnownNotDispatched(HttpRequestException error) => RelayConnectPhase.WasNotSent(error);
|
||||
|
||||
private static IResult OutcomeUnknown() => Results.Json(new
|
||||
{
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
|
||||
|
||||
/// <summary>
|
||||
/// Standby-relay copy of the DelmiaNotifier's <c>ConnectPhase</c> (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 <see cref="SocketsHttpHandler.ConnectCallback"/> and wraps every connect
|
||||
/// failure — refusal, DNS, an unreachable/black-holed host, the <see cref="SocketsHttpHandler.ConnectTimeout"/>
|
||||
/// firing — in <see cref="RelayConnectPhaseException"/>, which <see cref="SocketsHttpHandler"/> 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 <c>OUTCOME_UNKNOWN</c>.
|
||||
/// </summary>
|
||||
internal static class RelayConnectPhase
|
||||
{
|
||||
/// <summary>
|
||||
/// Default TCP connect timeout. Well below the relay's <c>StandbyForwardTimeout</c>, so a powered-off
|
||||
/// peer fails as a connect failure (and the next peer is tried) instead of eating the whole budget.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Creates a handler whose connect failures carry <see cref="RelayConnectPhaseException"/>.</summary>
|
||||
/// <param name="connectTimeout">The TCP connect timeout.</param>
|
||||
/// <returns>The configured handler.</returns>
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="error"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="error">The failure from <c>HttpClient.SendAsync</c>.</param>
|
||||
/// <returns><c>true</c> when the request was never sent.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks a failure that happened while opening the TCP connection — nothing was sent.</summary>
|
||||
/// <param name="message">The failure description.</param>
|
||||
/// <param name="inner">The underlying connect failure.</param>
|
||||
internal sealed class RelayConnectPhaseException(string message, Exception inner) : Exception(message, inner);
|
||||
@@ -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<IStandbyRequestForwarder, HttpStandbyRequestForwarder>();
|
||||
|
||||
// N1: the ApiMethod consumer of the script-artifact invalidation bus.
|
||||
|
||||
Reference in New Issue
Block a user