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:
@@ -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 |
|
||||
|
||||
@@ -148,7 +148,7 @@ The `sbk_<keyId>_<secret>` 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: <relaying host>`. 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -102,4 +102,86 @@ public class HttpRecipeSenderTests
|
||||
Assert.Equal(AttemptKind.Connected, outcome.Kind);
|
||||
Assert.Equal(500, outcome.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>DLM-1: with the real handler a refused connection is still a connect failure.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>DLM-1: a failure after the connection was up (no marker) stays outcome-unknown.</summary>
|
||||
[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"))));
|
||||
}
|
||||
|
||||
/// <summary>ConnectTimeoutFor stays strictly inside the overall timeout.</summary>
|
||||
[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<string> tried) : IRecipeSender
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<AttemptOutcome> SendAsync(string baseUrl, RecipeDownload payload, CancellationToken ct)
|
||||
{
|
||||
tried.Add(baseUrl);
|
||||
return inner.SendAsync(baseUrl, payload, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,6 +297,33 @@ public class StandbyRequestForwardingTests
|
||||
AssertStatus(result, StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<InboundApiOptions>(new InboundApiOptions
|
||||
{
|
||||
StandbyForwardPeerEndpoints = ["http://192.0.2.1:5000", "http://127.0.0.1:1"],
|
||||
StandbyForwardTimeout = TimeSpan.FromSeconds(20),
|
||||
}),
|
||||
NullLogger<HttpStandbyRequestForwarder>.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}");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a peer timeout returns an uncertain result without trying the next peer.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user