diff --git a/docs/requirements/Component-ExternalSystemGateway.md b/docs/requirements/Component-ExternalSystemGateway.md index d316fa93..f0e85574 100644 --- a/docs/requirements/Component-ExternalSystemGateway.md +++ b/docs/requirements/Component-ExternalSystemGateway.md @@ -107,6 +107,7 @@ Scripts choose between two call modes per invocation, mirroring the dual-mode da - Each external system definition specifies a **timeout** (`TimeoutSeconds`) that applies to all method calls on that system. `0` means unset — the gateway's configured `DefaultHttpTimeout` applies instead. Editable via the Central UI External System form ("Timeout (seconds)", helper text "0 = use gateway default") and deployed to sites in the artifact alongside the rest of the definition. - Error classification by HTTP response: - **Transient failures** (connection refused, timeout, HTTP 408, 429, 5xx): Behavior depends on call mode — `CachedCall` buffers for retry; `Call` returns error to script. + - **A connection lost while reading the response body** (headers received, then a reset or truncation — `IOException`/`HttpIOException`/`HttpRequestException` from the body read) is **transient** when the status was a success or a transient code, exactly like a timeout at the same point (ESG-1, 2026-12; before, the raw `IOException` escaped into the script and `CachedCall` buffered nothing). With a permanent status the call stays permanent — losing the error body does not make it retryable. - **Permanent failures** (HTTP 4xx except 408/429): Always returned to the calling script regardless of call mode. Logged to Site Event Logging. For `CachedCall`, the failure is additionally recorded as a terminal `Failed` tracking record — so even a never-buffered cached call has an authoritative status record. - This classification ensures the S&F buffer is not polluted with requests that will never succeed. - **Idempotency note**: `CachedCall` retries may result in duplicate delivery if the external system received the original request but the response was lost. Callers should use `CachedCall` only for operations that are idempotent or where duplicate delivery is acceptable. diff --git a/docs/requirements/Component-NotificationService.md b/docs/requirements/Component-NotificationService.md index b6f07a9c..5e7a20b8 100644 --- a/docs/requirements/Component-NotificationService.md +++ b/docs/requirements/Component-NotificationService.md @@ -144,7 +144,8 @@ A small `SmsErrorClassifier` mirrors the External System Gateway pattern: ### Error Classification (Email) Each `Deliver(...)` call returns one of `success | transient failure | permanent failure`, consistent with the External System Gateway pattern. There is **no synchronous permanent-failure return to the script** — `Send()` returns immediately, before any delivery is attempted. -- **Transient failures** (connection refused, timeout, SMTP 4xx temporary errors): The Notification Outbox moves the row to `Retrying` and schedules another attempt per the SMTP configuration's retry settings. +- **Transient failures** (connection refused, timeout, SMTP 4xx temporary errors, a connection dropped mid-session — MailKit's `IOException`, including one wrapping a `SocketException` — a TLS handshake that failed mid-way, and an OAuth2 token-endpoint outage: no response, HTTP 5xx/408/429, or the token request timing out): The Notification Outbox moves the row to `Retrying` and schedules another attempt per the SMTP configuration's retry settings. (NTF-2, 2026-12: before this the dropped connection, the handshake failure and the token-endpoint outage fell through as unclassified and were parked at once with `RetryCount` 0.) `SmtpErrorClassifier` walks the inner-exception chain for the socket/timeout/IO causes. +- **Broken credentials stay permanent**: a 4xx other than 408/429 from the OAuth2 token endpoint, or a malformed credential triple, parks the row — retrying a bad secret only burns token-endpoint calls. - **Permanent failures** (SMTP 5xx permanent errors, e.g., mailbox not found): The Notification Outbox moves the row to `Parked` with the error in `LastError`. The notification will never deliver, and an operator can review or discard it on the Central UI Notification Outbox page. - Retries exhausted on a transient failure also result in a `Parked` row. - A script observes failures only by calling `Notify.Status(id)` and seeing a `Parked` status — not as a synchronous exception. diff --git a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs index 357b628a..c6f9a8e2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs @@ -396,6 +396,22 @@ public class ExternalSystemClient : IExternalSystemClient throw ErrorClassifier.AsTransient( $"Timeout reading response from {system.Name} after {effectiveTimeout.TotalSeconds:0.##}s", ex); } + catch (Exception ex) when (ex is IOException or HttpRequestException) + { + // ESG-1: headers arrived, then the connection was reset or the body truncated + // (IOException / HttpIOException / HttpRequestException from the stream read). + // Nothing classified it, so a raw IOException escaped into the script and a + // CachedCall buffered nothing. A success or transient status is a transient + // failure — the call never completed. A permanent status stays permanent: + // losing its error body does not make it retryable. + if (response.IsSuccessStatusCode || ErrorClassifier.IsTransient(response.StatusCode)) + { + throw ErrorClassifier.AsTransient( + $"Connection lost reading the response from {system.Name}: {ex.Message}", ex); + } + + body = $"(response body unreadable: {ex.Message})"; + } if (response.IsSuccessStatusCode) { diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs index be61eb67..937203f4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs @@ -199,9 +199,11 @@ public sealed class EmailNotificationDeliveryAdapter : INotificationDeliveryAdap } catch (Exception ex) { - // An unclassified failure — chiefly an OAuth2 token-fetch failure. The - // outbox treats it as permanent: retrying a broken credential burns - // token-endpoint calls. (Mirrors the default-to-permanent stance.) + // An unclassified failure — chiefly a broken OAuth2 credential (a malformed + // credential triple, a 4xx from the token endpoint). The outbox treats it as + // permanent: retrying a broken credential burns token-endpoint calls. A token + // endpoint outage (5xx/408/429, no response, timeout) and a dropped SMTP + // connection are classified transient above (NTF-2) and never reach here. var detail = CredentialRedactor.Scrub(ex.Message, smtpConfig.Credentials); _logger.LogError( "Unclassified failure delivering email to list '{List}' ({ExceptionType}): {Detail}", diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs index ece41c98..f22dcb88 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs @@ -1,6 +1,7 @@ using System.Net.Sockets; using MailKit; using MailKit.Net.Smtp; +using MailKit.Security; namespace ZB.MOM.WW.ScadaBridge.NotificationService; @@ -72,16 +73,44 @@ public static class SmtpErrorClassifier return SmtpErrorClass.Unknown; } - // Protocol errors, a dropped/unavailable service, socket failures and - // timeouts are all retryable — the message has not been rejected. - if (ex is SmtpProtocolException - or ServiceNotConnectedException - or SocketException - or TimeoutException) + // OAuth2 token endpoint (NTF-2): classify the HTTP failure by status. No status means + // the request never got an answer (DNS, connect, reset) — transient; a 5xx/408/429 is + // an outage or throttle — transient; any other 4xx is a broken credential or request + // and stays permanent so a bad secret does not burn token-endpoint calls on retry. + if (ex is HttpRequestException http) + { + return http.StatusCode is not { } status + || (int)status >= 500 + || (int)status is 408 or 429 + ? SmtpErrorClass.Transient + : SmtpErrorClass.Permanent; + } + + // A cancellation the caller did NOT request is a timeout (HttpClient.Timeout on the + // token fetch surfaces as TaskCanceledException) — transient (NTF-2). + if (ex is OperationCanceledException) { return SmtpErrorClass.Transient; } + // Protocol errors, a dropped/unavailable service, socket failures, timeouts, a dropped + // connection (IOException — MailKit's documented connection-loss exception on + // Connect/Authenticate/Send) and a TLS handshake that failed mid-way are all retryable: + // the message has not been rejected (NTF-2). The inner-exception chain is walked + // because MailKit typically wraps the SocketException in an IOException. + for (var e = ex; e is not null; e = e.InnerException) + { + if (e is SmtpProtocolException + or ServiceNotConnectedException + or SocketException + or TimeoutException + or SslHandshakeException + or IOException) + { + return SmtpErrorClass.Transient; + } + } + return SmtpErrorClass.Unknown; } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs index f9f48ea5..c2162454 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs @@ -159,6 +159,55 @@ public class ExternalSystemClientTests : IDisposable Assert.Contains("Transient error", result.ErrorMessage); } + /// + /// ESG-1 regression: the external system sends 200 headers, then drops the connection + /// mid-body. The call is a transient failure — not a raw IOException escaping into the + /// script. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Call_ConnectionLostReadingBody_ReturnsTransientError() + { + var system = new ExternalSystemDefinition("TestAPI", "https://api.example.com", "none") { Id = 1 }; + var method = new ExternalSystemMethod("getData", "GET", "/data") { Id = 1, ExternalSystemDefinitionId = 1 }; + StubResolution(system, method); + + var httpClient = new HttpClient(new BodyFailsHandler(HttpStatusCode.OK, new IOException("connection reset mid-body"))); + _httpClientFactory.CreateClient(Arg.Any()).Returns(httpClient); + + var client = new ExternalSystemClient( + _httpClientFactory, _repository, + NullLogger.Instance); + + var result = await client.CallAsync("TestAPI", "getData"); + + Assert.False(result.Success); + Assert.Contains("Transient error", result.ErrorMessage); + } + + /// ESG-1: a permanent status whose error body is unreadable stays permanent. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Call_Permanent400WithUnreadableBody_StaysPermanent() + { + var system = new ExternalSystemDefinition("TestAPI", "https://api.example.com", "none") { Id = 1 }; + var method = new ExternalSystemMethod("getData", "GET", "/data") { Id = 1, ExternalSystemDefinitionId = 1 }; + StubResolution(system, method); + + var httpClient = new HttpClient(new BodyFailsHandler(HttpStatusCode.BadRequest, new HttpIOException(HttpRequestError.ResponseEnded))); + _httpClientFactory.CreateClient(Arg.Any()).Returns(httpClient); + + var client = new ExternalSystemClient( + _httpClientFactory, _repository, + NullLogger.Instance); + + var result = await client.CallAsync("TestAPI", "getData"); + + Assert.False(result.Success); + Assert.DoesNotContain("Transient error", result.ErrorMessage); + Assert.Contains("400", result.ErrorMessage); + } + /// Verifies that an HTTP 400 response is returned as a permanent error. /// A task that represents the asynchronous operation. [Fact] @@ -1239,6 +1288,30 @@ public class ExternalSystemClientTests : IDisposable /// /// Test helper: mock HTTP message handler. /// + /// Answers with the given status, then fails the body read with error. + private sealed class BodyFailsHandler(HttpStatusCode statusCode, Exception error) : HttpMessageHandler + { + /// + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(new HttpResponseMessage(statusCode) { Content = new StreamContent(new FailingStream(error)) }); + + private sealed class FailingStream(Exception error) : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => 0; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw error; + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + => ValueTask.FromException(error); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + } + private class MockHttpMessageHandler : HttpMessageHandler { private readonly HttpStatusCode _statusCode; diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs index 9bbc8762..0738a6ff 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs @@ -206,6 +206,30 @@ public class EmailNotificationDeliveryAdapterTests Assert.Equal(DeliveryResult.TransientFailure, outcome.Result); } + /// + /// NTF-2 regression: the relay drops the connection during DATA (MailKit throws IOException) + /// or the OAuth2 token endpoint answers 503 — both are retried, not parked with RetryCount 0. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Deliver_ConnectionDropAndTokenEndpointOutage_ReturnTransient() + { + SetupHappyPath(); + _smtpClient + .SendAsync(Arg.Any(), Arg.Any>(), + Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new IOException("connection reset during DATA")); + var dropped = await CreateAdapter().DeliverAsync(MakeNotification()); + Assert.Equal(DeliveryResult.TransientFailure, dropped.Result); + + _smtpClient + .SendAsync(Arg.Any(), Arg.Any>(), + Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new HttpRequestException("503", null, System.Net.HttpStatusCode.ServiceUnavailable)); + var outage = await CreateAdapter().DeliverAsync(MakeNotification()); + Assert.Equal(DeliveryResult.TransientFailure, outage.Result); + } + /// Verifies that an unclassified exception returns a permanent failure. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs index 78d48090..dca3e630 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs @@ -102,14 +102,64 @@ public class SmtpErrorClassifierTests SmtpErrorClassifier.Classify(new OperationCanceledException(), cts.Token)); } - /// Verifies that an operation cancellation without a requested cancellation is classified as unknown. + /// + /// NTF-2: a cancellation the caller did not request is a timeout (HttpClient.Timeout on the + /// OAuth2 token fetch surfaces as TaskCanceledException) and is transient. Before NTF-2 it + /// was Unknown, which the outbox adapter parks as permanent. + /// [Fact] - public void Classify_OperationCanceledWithoutRequestedCancellation_IsUnknown() + public void Classify_OperationCanceledWithoutRequestedCancellation_IsTransient() { - // Not a recognised SMTP error, and cancellation was not requested. Assert.Equal( - SmtpErrorClass.Unknown, + SmtpErrorClass.Transient, SmtpErrorClassifier.Classify(new OperationCanceledException(), CancellationToken.None)); + Assert.Equal( + SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new TaskCanceledException("HttpClient.Timeout"), CancellationToken.None)); + } + + /// NTF-2: a dropped connection (MailKit's documented IOException) is transient, wrapped or not. + [Fact] + public void Classify_IOException_IsTransient_IncludingAWrappedSocketException() + { + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new IOException("connection reset"), CancellationToken.None)); + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify( + new IOException("Unable to read data", new SocketException((int)SocketError.ConnectionReset)), + CancellationToken.None)); + // An unrecognised wrapper whose cause is a socket failure is unwrapped too. + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify( + new InvalidOperationException("wrapper", new TimeoutException()), CancellationToken.None)); + } + + /// NTF-2: a TLS handshake that failed mid-way (relay restarting) is transient. + [Fact] + public void Classify_SslHandshakeException_IsTransient() + { + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new MailKit.Security.SslHandshakeException("handshake failed"), CancellationToken.None)); + } + + /// + /// NTF-2: OAuth2 token-endpoint failures are classified by HTTP status — no status (network), + /// 5xx, 408 and 429 are transient; any other 4xx (a broken credential) is permanent. + /// + /// The token endpoint's status, or null for a network failure. + /// The expected classification. + [Theory] + [InlineData(null, SmtpErrorClass.Transient)] + [InlineData(503, SmtpErrorClass.Transient)] + [InlineData(500, SmtpErrorClass.Transient)] + [InlineData(408, SmtpErrorClass.Transient)] + [InlineData(429, SmtpErrorClass.Transient)] + [InlineData(400, SmtpErrorClass.Permanent)] + [InlineData(401, SmtpErrorClass.Permanent)] + public void Classify_TokenEndpointHttpRequestException_ByStatus(int? status, SmtpErrorClass expected) + { + var ex = new HttpRequestException("token endpoint", null, (System.Net.HttpStatusCode?)status); + Assert.Equal(expected, SmtpErrorClassifier.Classify(ex, CancellationToken.None)); } /// Verifies that an unrecognised exception is classified as unknown.