fix(notify,esg): classify dropped SMTP connections, OAuth2 token-endpoint outages and body-read connection loss as transient (NTF-2, ESG-1, WP4 task 4.6)
This commit is contained in:
@@ -159,6 +159,55 @@ public class ExternalSystemClientTests : IDisposable
|
||||
Assert.Contains("Transient error", result.ErrorMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<string>()).Returns(httpClient);
|
||||
|
||||
var client = new ExternalSystemClient(
|
||||
_httpClientFactory, _repository,
|
||||
NullLogger<ExternalSystemClient>.Instance);
|
||||
|
||||
var result = await client.CallAsync("TestAPI", "getData");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Contains("Transient error", result.ErrorMessage);
|
||||
}
|
||||
|
||||
/// <summary>ESG-1: a permanent status whose error body is unreadable stays permanent.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<string>()).Returns(httpClient);
|
||||
|
||||
var client = new ExternalSystemClient(
|
||||
_httpClientFactory, _repository,
|
||||
NullLogger<ExternalSystemClient>.Instance);
|
||||
|
||||
var result = await client.CallAsync("TestAPI", "getData");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.DoesNotContain("Transient error", result.ErrorMessage);
|
||||
Assert.Contains("400", result.ErrorMessage);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an HTTP 400 response is returned as a permanent error.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -1239,6 +1288,30 @@ public class ExternalSystemClientTests : IDisposable
|
||||
/// <summary>
|
||||
/// Test helper: mock HTTP message handler.
|
||||
/// </summary>
|
||||
/// <summary>Answers with the given status, then fails the body read with <c>error</c>.</summary>
|
||||
private sealed class BodyFailsHandler(HttpStatusCode statusCode, Exception error) : HttpMessageHandler
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override Task<HttpResponseMessage> 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<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromException<int>(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;
|
||||
|
||||
+24
@@ -206,6 +206,30 @@ public class EmailNotificationDeliveryAdapterTests
|
||||
Assert.Equal(DeliveryResult.TransientFailure, outcome.Result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Deliver_ConnectionDropAndTokenEndpointOutage_ReturnTransient()
|
||||
{
|
||||
SetupHappyPath();
|
||||
_smtpClient
|
||||
.SendAsync(Arg.Any<string>(), Arg.Any<IEnumerable<string>>(),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.ThrowsAsync(new IOException("connection reset during DATA"));
|
||||
var dropped = await CreateAdapter().DeliverAsync(MakeNotification());
|
||||
Assert.Equal(DeliveryResult.TransientFailure, dropped.Result);
|
||||
|
||||
_smtpClient
|
||||
.SendAsync(Arg.Any<string>(), Arg.Any<IEnumerable<string>>(),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.ThrowsAsync(new HttpRequestException("503", null, System.Net.HttpStatusCode.ServiceUnavailable));
|
||||
var outage = await CreateAdapter().DeliverAsync(MakeNotification());
|
||||
Assert.Equal(DeliveryResult.TransientFailure, outage.Result);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an unclassified exception returns a permanent failure.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -102,14 +102,64 @@ public class SmtpErrorClassifierTests
|
||||
SmtpErrorClassifier.Classify(new OperationCanceledException(), cts.Token));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an operation cancellation without a requested cancellation is classified as unknown.</summary>
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>NTF-2: a dropped connection (MailKit's documented IOException) is transient, wrapped or not.</summary>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>NTF-2: a TLS handshake that failed mid-way (relay restarting) is transient.</summary>
|
||||
[Fact]
|
||||
public void Classify_SslHandshakeException_IsTransient()
|
||||
{
|
||||
Assert.Equal(SmtpErrorClass.Transient,
|
||||
SmtpErrorClassifier.Classify(new MailKit.Security.SslHandshakeException("handshake failed"), CancellationToken.None));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="status">The token endpoint's status, or null for a network failure.</param>
|
||||
/// <param name="expected">The expected classification.</param>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an unrecognised exception is classified as unknown.</summary>
|
||||
|
||||
Reference in New Issue
Block a user