Mail: timeout per stap met fase en verstreken tijd in het log

De SMTP-verzender gaf alle stappen samen een tijdsbudget; nu krijgt elke stap (verbinden met STARTTLS,
inloggen, versturen) zijn eigen volledige timeout. Bij een timeout noemt de code de stap
(timeout_connect, timeout_auth, timeout_send) en toont het log per stap de verstreken milliseconden.
TimeoutSeconds blijft instelbaar (standaard 10), bereik nu 1 tot 120. Infra-doc met veiligheidsmodus,
timeout en leeswijzer voor het journal.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 01:30:16 +01:00
co-authored by Claude Sonnet 5.5
parent 892c548931
commit 190deb0da8
13 changed files with 168 additions and 22 deletions
@@ -113,6 +113,7 @@ public class MailSoftFailureTests
[InlineData("Email:FromName", "", "Email:FromName")]
[InlineData("Email:Smtp:Port", "70000", "Email:Smtp:Port")]
[InlineData("Email:Smtp:TimeoutSeconds", "0", "Email:Smtp:TimeoutSeconds")]
[InlineData("Email:Smtp:TimeoutSeconds", "121", "Email:Smtp:TimeoutSeconds")]
[InlineData("Email:Smtp:Password", "", "Email:Smtp:Password")]
[InlineData("Email:LogoUrl", "javascript:x", "Email:LogoUrl")]
[InlineData("App:PublicBaseUrl", "", "App:PublicBaseUrl")]
@@ -25,8 +25,12 @@ internal sealed class StubSmtpServer : IDisposable
/// <param name="silent">Accept connections but never answer (to provoke the timeout).</param>
/// <param name="rejectMailFrom">Reply to MAIL FROM with this full line (for example "553 5.7.1 ...").</param>
/// <param name="rejectRcpt">Reply to RCPT TO with this full line.</param>
public StubSmtpServer(bool silent = false, string? rejectMailFrom = null, string? rejectRcpt = null)
private readonly string? _stallAt;
/// <param name="stallAt">"auth" advertises AUTH PLAIN and then never answers the login; "send" never answers MAIL FROM.</param>
public StubSmtpServer(bool silent = false, string? rejectMailFrom = null, string? rejectRcpt = null, string? stallAt = null)
{
_stallAt = stallAt;
_silent = silent;
_rejectMailFrom = rejectMailFrom;
_rejectRcpt = rejectRcpt;
@@ -47,7 +51,13 @@ internal sealed class StubSmtpServer : IDisposable
await writer.WriteLineAsync("220 stub ESMTP");
while (await reader.ReadLineAsync() is { } line)
{
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) await writer.WriteLineAsync("250 stub");
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase))
{
if (_stallAt == "auth") { await writer.WriteLineAsync("250-stub"); await writer.WriteLineAsync("250 AUTH PLAIN"); }
else await writer.WriteLineAsync("250 stub");
}
else if (line.StartsWith("AUTH", StringComparison.OrdinalIgnoreCase) && _stallAt == "auth") await Task.Delay(TimeSpan.FromSeconds(30));
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase) && _stallAt == "send") await Task.Delay(TimeSpan.FromSeconds(30));
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync(_rejectMailFrom ?? "250 ok"); }
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync(_rejectRcpt ?? "250 ok"); }
else if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
@@ -137,7 +147,7 @@ public class SmtpEmailSenderTests
var started = DateTime.UtcNow;
var result = await Sender(server.Port, timeoutSeconds: 1).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.Timeout));
result.Should().Be(MailSendResult.Fail(MailSendResult.TimeoutConnect));
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10));
}
@@ -59,6 +59,9 @@ public class SmtpFailureTests(ITestOutputHelper output)
.Should().Be(MailSendResult.Rejected);
SmtpFailure.Classify(new AuthenticationException("bad pw-secret"), none).Should().Be(MailSendResult.AuthFailed);
SmtpFailure.Classify(new TimeoutException(), none).Should().Be(MailSendResult.Timeout);
SmtpFailure.Classify(new TimeoutException(), none, SmtpFailure.PhaseConnect).Should().Be(MailSendResult.TimeoutConnect);
SmtpFailure.Classify(new TimeoutException(), none, SmtpFailure.PhaseAuth).Should().Be(MailSendResult.TimeoutAuth);
SmtpFailure.Classify(new OperationCanceledException(), none, SmtpFailure.PhaseSend).Should().Be(MailSendResult.TimeoutSend);
SmtpFailure.Classify(new OperationCanceledException(), none).Should().Be(MailSendResult.Timeout);
SmtpFailure.Classify(new SocketException(), none).Should().Be(MailSendResult.ConnectionFailed);
SmtpFailure.Classify(new InvalidOperationException(), none).Should().Be(MailSendResult.Unknown);
@@ -96,6 +99,77 @@ public class SmtpFailureTests(ITestOutputHelper output)
public class SmtpSenderDiagnosticsTests
{
private static (SmtpEmailSender Sender, LogCapture Logs) SenderWith(StubSmtpServer server, int timeoutSeconds, string username = "")
{
var logs = new LogCapture();
var factory = LoggerFactory.Create(b => b.AddProvider(logs));
var sender = new SmtpEmailSender(
Options.Create(new EmailOptions
{
FromAddress = "no-reply@slpsoftware.nl", FromName = "Site",
Smtp = { Host = "127.0.0.1", Port = server.Port, EnableSsl = false, Username = username, Password = username.Length > 0 ? "pw-secret-9" : "", TimeoutSeconds = timeoutSeconds }
}),
factory.CreateLogger<SmtpEmailSender>());
return (sender, logs);
}
[Fact]
public async Task ATimeoutWhileConnecting_IsNamedAsSuch_WithTheElapsedTimeOfThatPhase()
{
using var server = new StubSmtpServer(silent: true);
var (sender, logs) = SenderWith(server, timeoutSeconds: 1);
var result = await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.TimeoutConnect));
var line = logs.Entries.Single(e => e.Level == LogLevel.Warning).Message;
line.Should().Contain("code=timeout_connect").And.Contain("phase=connect").And.Contain("timeout_per_phase_s=1");
System.Text.RegularExpressions.Regex.Match(line, @"connect=(\d+)ms\(failed\)").Groups[1].Value
.Should().NotBeEmpty();
long.Parse(System.Text.RegularExpressions.Regex.Match(line, @"connect=(\d+)ms").Groups[1].Value).Should().BeInRange(800, 5000);
}
[Fact]
public async Task ATimeoutDuringTheLogin_IsNamedAsSuch_AndShowsTheFinishedConnectPhase()
{
using var server = new StubSmtpServer(stallAt: "auth");
var (sender, logs) = SenderWith(server, timeoutSeconds: 1, username: "user-secret-9");
var result = await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.TimeoutAuth));
var line = logs.Entries.Single(e => e.Level == LogLevel.Warning).Message;
line.Should().Contain("code=timeout_auth").And.Contain("phase=auth");
line.Should().MatchRegex(@"connect=\d+ms ").And.MatchRegex(@"auth=\d+ms\(failed\)");
line.Should().NotContain("user-secret-9").And.NotContain("pw-secret-9");
}
[Fact]
public async Task ATimeoutWhileSending_IsNamedAsSuch()
{
using var server = new StubSmtpServer(stallAt: "send");
var (sender, logs) = SenderWith(server, timeoutSeconds: 1);
var result = await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.TimeoutSend));
logs.Entries.Single(e => e.Level == LogLevel.Warning).Message.Should().Contain("phase=send").And.MatchRegex(@"send=\d+ms\(failed\)");
}
[Fact]
public async Task EachPhaseGetsItsOwnFullTimeout_NotOneSharedBudget()
{
// The login stalls for one full timeout; the connect before it already used part of its own. With one shared
// budget the login would have been cut short: here it must run its whole second.
using var server = new StubSmtpServer(stallAt: "auth");
var (sender, logs) = SenderWith(server, timeoutSeconds: 1, username: "u");
await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
var line = logs.Entries.Single(e => e.Level == LogLevel.Warning).Message;
long.Parse(System.Text.RegularExpressions.Regex.Match(line, @"auth=(\d+)ms").Groups[1].Value).Should().BeGreaterThanOrEqualTo(900);
}
private static (SmtpEmailSender Sender, LogCapture Logs) Sender(StubSmtpServer server)
{
var logs = new LogCapture();