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
+4 -1
View File
@@ -48,7 +48,10 @@ public sealed class SmtpOptions
public string Username { get; set; } = "";
public string Password { get; set; } = "";
/// <summary>Connect and send are bounded by this, because mail is sent inside the request.</summary>
/// <summary>
/// Seconds allowed for EACH step (connect including STARTTLS, login, send), 1 to 120, default 10. Mail is sent
/// inside the administrator's request, so the worst case is three times this.
/// </summary>
public int TimeoutSeconds { get; set; } = 10;
}
@@ -32,8 +32,8 @@ public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValid
failures.Add($"Email:FromName is required (1..{EmailAddressRules.MaxDisplayNameLength} characters, no control characters).");
if (options.Smtp.Port is < 1 or > 65535)
failures.Add("Email:Smtp:Port must be between 1 and 65535.");
if (options.Smtp.TimeoutSeconds is < 1 or > 60)
failures.Add("Email:Smtp:TimeoutSeconds must be between 1 and 60.");
if (options.Smtp.TimeoutSeconds is < 1 or > 120)
failures.Add("Email:Smtp:TimeoutSeconds must be between 1 and 120.");
if (!string.IsNullOrEmpty(options.Smtp.Username) && string.IsNullOrEmpty(options.Smtp.Password))
failures.Add("Email:Smtp:Password is required when Email:Smtp:Username is set.");
if (!string.IsNullOrEmpty(options.BrandColor) && !EmailAddressRules.IsValidColour(options.BrandColor))
@@ -6,6 +6,12 @@ public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
public const string Disabled = "disabled";
public const string NotConfigured = "not_configured";
public const string Timeout = "timeout";
/// <summary>Timed out while connecting (TCP, greeting and the STARTTLS upgrade).</summary>
public const string TimeoutConnect = "timeout_connect";
/// <summary>Timed out during the login.</summary>
public const string TimeoutAuth = "timeout_auth";
/// <summary>Timed out while sending the message (MAIL FROM, RCPT TO, DATA).</summary>
public const string TimeoutSend = "timeout_send";
public const string AuthFailed = "auth_failed";
public const string Rejected = "rejected";
/// <summary>The server refused the sender address (MAIL FROM): the From address is not allowed for this account.</summary>
+36 -11
View File
@@ -41,32 +41,57 @@ public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<Smtp
message.Body = new BodyBuilder { HtmlBody = mail.HtmlBody, TextBody = mail.TextBody }.ToMessageBody();
var timeout = TimeSpan.FromSeconds(_options.Smtp.TimeoutSeconds);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
var phases = new List<string>(); // for the log: "connect=120ms auth=4800ms(timeout)"
var phase = SmtpFailure.PhaseConnect;
// Every phase gets its OWN full timeout (a slow login must not eat the time of the send), and the
// time each one took is kept, so a timeout says where it happened and how long that phase ran.
async Task Timed(string name, Func<CancellationToken, Task> action)
{
phase = name;
using var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
source.CancelAfter(timeout);
var clock = System.Diagnostics.Stopwatch.StartNew();
try
{
await action(source.Token);
phases.Add($"{name}={clock.ElapsedMilliseconds}ms");
}
catch
{
phases.Add($"{name}={clock.ElapsedMilliseconds}ms(failed)");
throw;
}
}
try
{
using var client = new SmtpClient { Timeout = (int)timeout.TotalMilliseconds };
await client.ConnectAsync(
// MailKit negotiates STARTTLS inside the connect step, so "connect" covers the TCP connection, the
// greeting and the TLS upgrade together.
await Timed(SmtpFailure.PhaseConnect, ct => client.ConnectAsync(
_options.Smtp.Host,
_options.Smtp.Port,
_options.Smtp.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None,
timeoutSource.Token);
ct));
if (!string.IsNullOrEmpty(_options.Smtp.Username))
await client.AuthenticateAsync(_options.Smtp.Username, _options.Smtp.Password, timeoutSource.Token);
await Timed(SmtpFailure.PhaseAuth, ct => client.AuthenticateAsync(_options.Smtp.Username, _options.Smtp.Password, ct));
await client.SendAsync(message, timeoutSource.Token);
await client.DisconnectAsync(true, timeoutSource.Token);
await Timed(SmtpFailure.PhaseSend, ct => client.SendAsync(message, ct));
await client.DisconnectAsync(true, CancellationToken.None);
return MailSendResult.Ok;
}
catch (Exception ex)
{
var code = SmtpFailure.Classify(ex, cancellationToken);
var code = SmtpFailure.Classify(ex, cancellationToken, phase);
// Never the whole exception text (it can quote addresses or credentials): the type, for a refused
// command its phase and status code, and a redacted, shortened first line of the server's reply.
logger.LogWarning("identity_mail_failed code={Code} detail={Detail} from_domain={FromDomain} smtp_port={Port}",
code, SmtpFailure.Describe(ex), DomainOf(fromAddress), _options.Smtp.Port);
// command its phase and status code, a redacted, shortened first line of the server's reply, and the
// time each phase took.
logger.LogWarning(
"identity_mail_failed code={Code} detail={Detail} phase={Phase} timings=\"{Timings}\" timeout_per_phase_s={TimeoutSeconds} from_domain={FromDomain} smtp_port={Port}",
code, SmtpFailure.Describe(ex), phase, string.Join(" ", phases), _options.Smtp.TimeoutSeconds, DomainOf(fromAddress), _options.Smtp.Port);
return MailSendResult.Fail(code);
}
}
+16 -3
View File
@@ -20,14 +20,18 @@ public static partial class SmtpFailure
{
public const int MaxReplyLength = 120;
public const string PhaseConnect = "connect";
public const string PhaseAuth = "auth";
public const string PhaseSend = "send";
[GeneratedRegex(@"[^\s@<>""'(),;:]+@[^\s@<>""'(),;:]+")]
private static partial Regex AddressPattern();
/// <summary>The short code shown to the administrator; the most specific one the failure allows.</summary>
public static string Classify(Exception ex, CancellationToken callerToken) => ex switch
public static string Classify(Exception ex, CancellationToken callerToken, string? phase = null) => ex switch
{
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
TimeoutException => MailSendResult.Timeout,
OperationCanceledException when !callerToken.IsCancellationRequested => TimeoutCode(phase),
TimeoutException => TimeoutCode(phase),
OperationCanceledException => MailSendResult.Unknown,
AuthenticationException => MailSendResult.AuthFailed,
SslHandshakeException => MailSendResult.TlsFailed,
@@ -43,6 +47,15 @@ public static partial class SmtpFailure
_ => MailSendResult.Unknown
};
/// <summary>"timeout_connect", "timeout_auth" or "timeout_send" when the phase is known, else plain "timeout".</summary>
public static string TimeoutCode(string? phase) => phase switch
{
PhaseConnect => MailSendResult.TimeoutConnect,
PhaseAuth => MailSendResult.TimeoutAuth,
PhaseSend => MailSendResult.TimeoutSend,
_ => MailSendResult.Timeout
};
/// <summary>The log description of a failure: the type, and for a refused command its phase, status code and a redacted first line.</summary>
public static string Describe(Exception ex)
{