Contact: mail via achtergrondservice met claim, backoff en maximum (CMS-U5)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -38,9 +38,41 @@ public class ContactOptions
|
||||
|
||||
public ContactCaptchaOptions Captcha { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Where the notification mail for a genuine message goes. Supply it through the environment
|
||||
/// (<c>Contact__RecipientEmail</c>); it is never part of committed configuration and never exposed to a client.
|
||||
/// </summary>
|
||||
public string? RecipientEmail { get; set; }
|
||||
|
||||
public ContactMailOptions Mail { get; set; } = new();
|
||||
|
||||
public string EffectiveSiteId => string.IsNullOrWhiteSpace(SiteId) ? "default" : SiteId.Trim();
|
||||
}
|
||||
|
||||
/// <summary>How the background sender works (section <c>Contact:Mail</c>).</summary>
|
||||
public class ContactMailOptions
|
||||
{
|
||||
/// <summary>How often the sender looks for mail that is due, besides being woken by a new message.</summary>
|
||||
public int SweepSeconds { get; set; } = 120;
|
||||
|
||||
/// <summary>Automatic attempts per message; after that it stays failed until an administrator resends.</summary>
|
||||
public int MaxAttempts { get; set; } = 6;
|
||||
|
||||
/// <summary>Wait before attempt n+1 after attempt n failed (the last value repeats). Default 5 min, 15 min, 1 h, 6 h, 24 h.</summary>
|
||||
public int[] BackoffMinutes { get; set; } = [5, 15, 60, 360, 1440];
|
||||
|
||||
/// <summary>A claimed message is not claimed again by another instance for this long.</summary>
|
||||
public int ClaimMinutes { get; set; } = 5;
|
||||
|
||||
public int BatchSize { get; set; } = 20;
|
||||
|
||||
public TimeSpan BackoffAfter(int attempts)
|
||||
{
|
||||
var steps = BackoffMinutes is { Length: > 0 } ? BackoffMinutes : [5];
|
||||
return TimeSpan.FromMinutes(Math.Max(1, steps[Math.Clamp(attempts - 1, 0, steps.Length - 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactCaptchaOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
@@ -44,7 +44,10 @@ public class ContactModule : IModule
|
||||
services.AddScoped<IContactSubmissionService, ContactSubmissionService>();
|
||||
services.AddSingleton<IContactTokenService, ContactTokenService>();
|
||||
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
|
||||
services.AddScoped<IContactMailSender, NoOpContactMailSender>();
|
||||
// Mail: the request only stores and signals; the background service sends (and retries) with the host's mail pieces.
|
||||
services.AddScoped<IContactMailSender, ContactMailSender>();
|
||||
services.AddSingleton<IContactMailSignal, ContactMailSignal>();
|
||||
services.AddHostedService<ContactMailService>();
|
||||
// Gate: the form is open only if the host switch AND the CMS switch are on. The host switch
|
||||
// is asked first, so with it off the database is never touched.
|
||||
services.AddSingleton<ContactSettingsCache>();
|
||||
|
||||
@@ -28,6 +28,10 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
|
||||
entity.Property(e => e.MailError).HasMaxLength(100);
|
||||
entity.Property(e => e.RetentionUntil).IsRequired();
|
||||
|
||||
// The claim of the background sender: two instances that try to claim the same message at once
|
||||
// cannot both succeed (the second update finds a different value and affects no row).
|
||||
entity.Property(e => e.NextMailAttemptAt).IsConcurrencyToken();
|
||||
|
||||
entity.HasIndex(e => new { e.SiteId, e.Status, e.ReceivedAt });
|
||||
entity.HasIndex(e => e.RetentionUntil);
|
||||
});
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Modules.Contact.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Migrations
|
||||
{
|
||||
[DbContext(typeof(ContactDbContext))]
|
||||
[Migration("20261110141855_ContactMailClaim")]
|
||||
partial class ContactMailClaim
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 64);
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasMaxLength(254)
|
||||
.HasColumnType("varchar(254)");
|
||||
|
||||
b.Property<int>("MailAttempts")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("MailError")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<string>("MailStatus")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("varchar(2000)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<DateTimeOffset?>("NextMailAttemptAt")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<DateTimeOffset>("ReceivedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<DateTimeOffset>("RetentionUntil")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("SiteId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RetentionUntil");
|
||||
|
||||
b.HasIndex("SiteId", "Status", "ReceivedAt");
|
||||
|
||||
b.ToTable("ContactMessages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<Guid>("UpdatedByUserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("ContactSettings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
|
||||
{
|
||||
b.Property<string>("SiteId")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<Guid>("Key")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<int>("StatusCode")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("SiteId", "Key");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.ToTable("ContactIdempotency", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ContactMailClaim : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ namespace SlpModularCms.Modules.Contact.Migrations
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<DateTimeOffset?>("NextMailAttemptAt")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<DateTimeOffset>("ReceivedAt")
|
||||
|
||||
@@ -37,13 +37,14 @@ public record ContactMessageDetail(
|
||||
string MailStatus,
|
||||
int MailAttempts,
|
||||
string? MailError,
|
||||
DateTimeOffset RetentionUntil);
|
||||
DateTimeOffset RetentionUntil,
|
||||
DateTimeOffset? NextMailAttemptAt = null);
|
||||
|
||||
/// <summary>Body of PATCH /contact-messages/{id}. Nullable so a missing field is reported in our own shape.</summary>
|
||||
public record UpdateContactMessageStatusRequest(string? Status);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed);
|
||||
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed, string? MailError = null);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
|
||||
|
||||
@@ -28,6 +28,16 @@ public interface IContactRepository
|
||||
|
||||
Task<ContactSettings?> GetSettingsAsync(CancellationToken cancellationToken);
|
||||
void Add(ContactSettings settings);
|
||||
|
||||
// ---- background mail ----
|
||||
|
||||
/// <summary>
|
||||
/// Unread (<c>New</c>) messages whose mail is due: pending or failed, fewer than <paramref name="maxAttempts"/>
|
||||
/// attempts, and no next-attempt time in the future. Oldest first. Read, archived and spam messages are never mailed
|
||||
/// automatically.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<ContactMessage>> GetDueForMailAsync(
|
||||
string siteId, DateTimeOffset now, int maxAttempts, int take, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class ContactRepository(ContactDbContext context) : IContactRepository
|
||||
@@ -94,6 +104,18 @@ public class ContactRepository(ContactDbContext context) : IContactRepository
|
||||
|
||||
public void Add(ContactSettings settings) => context.ContactSettings.Add(settings);
|
||||
|
||||
public async Task<IReadOnlyList<ContactMessage>> GetDueForMailAsync(
|
||||
string siteId, DateTimeOffset now, int maxAttempts, int take, CancellationToken cancellationToken)
|
||||
=> await context.ContactMessages
|
||||
.Where(m => m.SiteId == siteId
|
||||
&& m.Status == ContactMessageStatus.New
|
||||
&& (m.MailStatus == ContactMailStatus.Pending || m.MailStatus == ContactMailStatus.Failed)
|
||||
&& m.MailAttempts < maxAttempts
|
||||
&& (m.NextMailAttemptAt == null || m.NextMailAttemptAt <= now))
|
||||
.OrderBy(m => m.ReceivedAt)
|
||||
.Take(take)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
public async Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var total = 0;
|
||||
|
||||
@@ -131,21 +131,44 @@ public sealed class ContactAdminService(
|
||||
throw new ContactResendNotAllowedException();
|
||||
}
|
||||
|
||||
var outcome = await mailSender.SendAsync(message, cancellationToken);
|
||||
if (outcome != ContactMailOutcome.Skipped)
|
||||
// A manual resend ignores the backoff and the maximum of the automatic attempts.
|
||||
var result = await mailSender.SendAsync(message, cancellationToken);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
message.MailAttempts++;
|
||||
message.MailStatus = outcome == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
case ContactMailOutcome.Sent:
|
||||
message.MailAttempts++;
|
||||
message.MailStatus = ContactMailStatus.Sent;
|
||||
message.MailError = null;
|
||||
message.NextMailAttemptAt = null;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
break;
|
||||
|
||||
case ContactMailOutcome.Failed:
|
||||
message.MailAttempts++;
|
||||
message.MailStatus = ContactMailStatus.Failed;
|
||||
message.MailError = result.ErrorCode;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Nothing could be attempted (mail off / no recipient): show why, count nothing.
|
||||
if (result.ErrorCode is not null && message.MailError != result.ErrorCode)
|
||||
{
|
||||
message.MailError = result.ErrorCode;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, outcome);
|
||||
logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, result.Outcome);
|
||||
return new ContactResendResult(
|
||||
ContactStatusNames.Of(message.MailStatus), message.MailAttempts, outcome == ContactMailOutcome.Sent);
|
||||
ContactStatusNames.Of(message.MailStatus), message.MailAttempts, result.Outcome == ContactMailOutcome.Sent,
|
||||
result.Outcome == ContactMailOutcome.Sent ? null : message.MailError);
|
||||
}
|
||||
|
||||
private static ContactMessageDetail ToDetail(ContactMessage m) => new(
|
||||
m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, m.Message,
|
||||
ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus),
|
||||
m.MailAttempts, m.MailError, m.RetentionUntil);
|
||||
m.MailAttempts, m.MailError, m.RetentionUntil, m.NextMailAttemptAt);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Mails the notification of a stored message to the site owner, using the host's own mail
|
||||
/// pieces (sender, renderer, effective site sender). The owner can simply reply: the visitor is
|
||||
/// the Reply-To. Nothing the visitor typed ends up in the subject or in any header except
|
||||
/// Reply-To, and no address, name or text is ever logged: only the message id and a short code.
|
||||
/// </summary>
|
||||
public sealed class ContactMailSender(
|
||||
IEmailSender sender,
|
||||
IMailTemplateRenderer renderer,
|
||||
ILanguageResolver languages,
|
||||
ISiteSettingsService siteSettings,
|
||||
IMailAvailability availability,
|
||||
IOptions<EmailOptions> email,
|
||||
IOptions<AppMailOptions> app,
|
||||
IOptions<ContactOptions> contact,
|
||||
ILogger<ContactMailSender> logger) : IContactMailSender
|
||||
{
|
||||
public string? NotReadyReason()
|
||||
{
|
||||
if (!availability.IsEnabled)
|
||||
{
|
||||
return ContactMailResult.Disabled;
|
||||
}
|
||||
|
||||
return EmailAddressRules.IsValidAddress(contact.Value.RecipientEmail) ? null : ContactMailResult.RecipientNotConfigured;
|
||||
}
|
||||
|
||||
public async Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken)
|
||||
{
|
||||
var notReady = NotReadyReason();
|
||||
if (notReady is not null)
|
||||
{
|
||||
return new ContactMailResult(ContactMailOutcome.Skipped, notReady);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(cancellationToken);
|
||||
var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/');
|
||||
var language = languages.Resolve(null);
|
||||
var dutch = language == MailLanguages.Dutch;
|
||||
|
||||
var model = new MailModel(
|
||||
SiteName: fromName,
|
||||
LogoUrl: ResolveLogo(baseUrl, email.Value.LogoUrl),
|
||||
BrandColor: string.IsNullOrWhiteSpace(email.Value.BrandColor) ? null : email.Value.BrandColor,
|
||||
LogoDarkUrl: ResolveLogo(baseUrl, email.Value.LogoDarkUrl),
|
||||
Details:
|
||||
[
|
||||
new MailDetail(dutch ? "Naam" : "Name", message.Name),
|
||||
new MailDetail(dutch ? "E-mailadres" : "E-mail address", message.Email),
|
||||
new MailDetail(dutch ? "Onderwerp" : "Subject", message.Subject),
|
||||
new MailDetail(dutch ? "Bericht" : "Message", message.Message),
|
||||
]);
|
||||
|
||||
var rendered = renderer.Render(MailKind.ContactMessage, language, model);
|
||||
var result = await sender.SendAsync(
|
||||
new OutgoingMail(
|
||||
contact.Value.RecipientEmail!.Trim(), rendered.Subject, rendered.Html, rendered.Text,
|
||||
fromAddress, fromName,
|
||||
ReplyToAddress: message.Email,
|
||||
ReplyToName: EmailAddressRules.IsValidDisplayName(message.Name) ? message.Name : null),
|
||||
cancellationToken);
|
||||
|
||||
if (result.Sent)
|
||||
{
|
||||
logger.LogInformation("contact_mail_sent message={MessageId}", message.Id);
|
||||
return ContactMailOutcome.Sent;
|
||||
}
|
||||
|
||||
logger.LogWarning("contact_mail_failed message={MessageId} code={Code}", message.Id, result.ErrorCode);
|
||||
return new ContactMailResult(ContactMailOutcome.Failed, result.ErrorCode ?? MailSendResult.Unknown);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Type only: the exception text could quote addresses or content.
|
||||
logger.LogWarning("contact_mail_failed message={MessageId} code={Code} exception={ExceptionType}",
|
||||
message.Id, MailSendResult.Unknown, ex.GetType().Name);
|
||||
return new ContactMailResult(ContactMailOutcome.Failed, MailSendResult.Unknown);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ResolveLogo(string baseUrl, string? logoUrl)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(logoUrl)) return null;
|
||||
return logoUrl.StartsWith('/') ? baseUrl + logoUrl : logoUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Sends the notification mails in the background, so a visitor never waits for SMTP. It wakes when a message was
|
||||
/// stored and on a fixed sweep, picks the unread messages whose mail is due, claims each one (so two instances never
|
||||
/// mail the same message), sends it and records the outcome. A failure is retried with a growing wait up to a maximum;
|
||||
/// after that the message stays failed until an administrator resends it. While mail cannot be sent at all (mail off,
|
||||
/// no valid recipient) nothing is attempted and nothing is counted: the reason is shown on the message instead.
|
||||
/// While the module is disabled it does nothing and never touches the database.
|
||||
/// </summary>
|
||||
public class ContactMailService(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IContactMailSignal signal,
|
||||
IOptions<ContactOptions> options,
|
||||
TimeProvider time,
|
||||
ILogger<ContactMailService> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await SweepAsync(stoppingToken);
|
||||
|
||||
try
|
||||
{
|
||||
await signal.WaitAsync(TimeSpan.FromSeconds(Math.Max(5, options.Value.Mail.SweepSeconds)), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One pass. Returns the number of messages that were attempted.</summary>
|
||||
internal async Task<int> SweepAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = options.Value;
|
||||
if (!settings.Enabled)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using var scope = scopeFactory.CreateAsyncScope();
|
||||
var repository = scope.ServiceProvider.GetRequiredService<IContactRepository>();
|
||||
var sender = scope.ServiceProvider.GetRequiredService<IContactMailSender>();
|
||||
var mail = settings.Mail;
|
||||
var siteId = settings.EffectiveSiteId;
|
||||
var now = time.GetUtcNow();
|
||||
|
||||
var due = await repository.GetDueForMailAsync(siteId, now, mail.MaxAttempts, mail.BatchSize, cancellationToken);
|
||||
if (due.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Mail cannot be sent at all: say why on the messages, count nothing, retry nothing in a loop.
|
||||
var notReady = sender.NotReadyReason();
|
||||
if (!string.IsNullOrEmpty(notReady))
|
||||
{
|
||||
foreach (var message in due.Where(m => m.MailError != notReady))
|
||||
{
|
||||
message.MailError = notReady;
|
||||
}
|
||||
|
||||
await TrySaveAsync(repository, cancellationToken);
|
||||
return 0;
|
||||
}
|
||||
|
||||
var attempted = 0;
|
||||
foreach (var message in due)
|
||||
{
|
||||
// Claim first. The next-attempt time is a concurrency token: a second instance holding the old
|
||||
// value fails to save here and skips the message.
|
||||
// Whole seconds: the column keeps no fractions, and the value must read back exactly as written
|
||||
// because it is the concurrency token of the save that records the outcome.
|
||||
var claimUntil = now + TimeSpan.FromMinutes(Math.Max(1, mail.ClaimMinutes));
|
||||
message.NextMailAttemptAt = new DateTimeOffset(claimUntil.Ticks - claimUntil.Ticks % TimeSpan.TicksPerSecond, claimUntil.Offset);
|
||||
try
|
||||
{
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var result = await sender.SendAsync(message, cancellationToken);
|
||||
attempted++;
|
||||
Record(message, result, mail, time.GetUtcNow());
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
if (attempted > 0)
|
||||
{
|
||||
logger.LogInformation("Contact mail: {Count} message(s) attempted", attempted);
|
||||
}
|
||||
|
||||
return attempted;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Type only: the message could quote addresses.
|
||||
logger.LogError("Contact mail sweep failed ({ExceptionType})", ex.GetType().Name);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies the outcome of one automatic attempt to the message.</summary>
|
||||
internal static void Record(ContactMessage message, ContactMailResult result, ContactMailOptions mail, DateTimeOffset now)
|
||||
{
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case ContactMailOutcome.Sent:
|
||||
message.MailStatus = ContactMailStatus.Sent;
|
||||
message.MailError = null;
|
||||
message.MailAttempts++;
|
||||
message.NextMailAttemptAt = null;
|
||||
break;
|
||||
|
||||
case ContactMailOutcome.Failed:
|
||||
message.MailStatus = ContactMailStatus.Failed;
|
||||
message.MailError = result.ErrorCode;
|
||||
message.MailAttempts++;
|
||||
// After the last allowed attempt there is no next one; an administrator can still resend.
|
||||
message.NextMailAttemptAt = message.MailAttempts >= mail.MaxAttempts ? null : now + mail.BackoffAfter(message.MailAttempts);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Skipped: nothing was attempted, so nothing is counted; try again at the next sweep.
|
||||
message.MailError = result.ErrorCode;
|
||||
message.NextMailAttemptAt = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task TrySaveAsync(IContactRepository repository, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
// Another instance changed the same rows; the next sweep sorts it out.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,25 +22,67 @@ public sealed class NullCaptchaVerifier : ICaptchaVerifier
|
||||
|
||||
public enum ContactMailOutcome
|
||||
{
|
||||
/// <summary>No mail was attempted (no sender available yet); the message stays pending.</summary>
|
||||
/// <summary>No mail was attempted (mail is off or no recipient is configured); nothing is counted.</summary>
|
||||
Skipped,
|
||||
Sent,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the notification mail for a genuine message. Called after the message is stored; a
|
||||
/// failure must never fail the request. The real implementation arrives with the mail unit.
|
||||
/// What one send came to. <see cref="ErrorCode"/> is a short code only (for example
|
||||
/// <c>auth_failed</c>, <c>disabled</c>, <c>recipient_not_configured</c>), never an address or text.
|
||||
/// </summary>
|
||||
public readonly record struct ContactMailResult(ContactMailOutcome Outcome, string? ErrorCode = null)
|
||||
{
|
||||
public const string Disabled = "disabled";
|
||||
public const string RecipientNotConfigured = "recipient_not_configured";
|
||||
|
||||
public static implicit operator ContactMailResult(ContactMailOutcome outcome) => new(outcome);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mails the notification for a stored message. Used by the background sender and by the administrator's
|
||||
/// resend; it never throws into its caller.
|
||||
/// </summary>
|
||||
public interface IContactMailSender
|
||||
{
|
||||
Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken);
|
||||
/// <summary>Null (or empty) when mail can be sent now, otherwise the short reason code.</summary>
|
||||
string? NotReadyReason();
|
||||
|
||||
Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class NoOpContactMailSender : IContactMailSender
|
||||
/// <summary>Wakes the background mail sender after a message was stored, so the mail goes out within seconds.</summary>
|
||||
public interface IContactMailSignal
|
||||
{
|
||||
public Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken)
|
||||
=> Task.FromResult(ContactMailOutcome.Skipped);
|
||||
void Notify();
|
||||
Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class ContactMailSignal : IContactMailSignal
|
||||
{
|
||||
private readonly System.Threading.Channels.Channel<bool> _channel =
|
||||
System.Threading.Channels.Channel.CreateBounded<bool>(new System.Threading.Channels.BoundedChannelOptions(1)
|
||||
{
|
||||
FullMode = System.Threading.Channels.BoundedChannelFullMode.DropWrite,
|
||||
});
|
||||
|
||||
public void Notify() => _channel.Writer.TryWrite(true);
|
||||
|
||||
/// <summary>Returns when notified or when the timeout passes, whichever is first.</summary>
|
||||
public async Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
using var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
source.CancelAfter(timeout);
|
||||
try
|
||||
{
|
||||
await _channel.Reader.ReadAsync(source.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// timeout: the periodic sweep
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -22,7 +22,7 @@ public sealed class ContactSubmissionService(
|
||||
IContactRepository repository,
|
||||
IContactTokenService tokens,
|
||||
ICaptchaVerifier captcha,
|
||||
IContactMailSender mailSender,
|
||||
IContactMailSignal mailSignal,
|
||||
IOptions<ContactOptions> options,
|
||||
TimeProvider time,
|
||||
ILogger<ContactSubmissionService> logger) : IContactSubmissionService
|
||||
@@ -115,6 +115,7 @@ public sealed class ContactSubmissionService(
|
||||
{
|
||||
message = NewMessage(request, siteId, now, ContactMessageStatus.New, ContactMailStatus.Pending,
|
||||
now.AddMonths(o.RetentionMonths));
|
||||
message.NextMailAttemptAt = now; // due at once; the background sender picks it up
|
||||
}
|
||||
|
||||
if (message is not null)
|
||||
@@ -150,11 +151,11 @@ public sealed class ContactSubmissionService(
|
||||
return new SubmissionResult.Received();
|
||||
}
|
||||
|
||||
// 6. Mail, only for genuine messages and only after the message is safely stored. A mail
|
||||
// problem never fails the request.
|
||||
if (outcome == Outcome.Genuine && message is not null)
|
||||
// 6. Mail: the visitor never waits for SMTP. A genuine message is stored as pending and due now; the
|
||||
// background sender is woken and mails it within seconds (and retries on failure).
|
||||
if (outcome == Outcome.Genuine)
|
||||
{
|
||||
await TryMailAsync(message, cancellationToken);
|
||||
mailSignal.Notify();
|
||||
}
|
||||
|
||||
Log(outcome, siteId);
|
||||
@@ -163,27 +164,6 @@ public sealed class ContactSubmissionService(
|
||||
|
||||
private const int StatusCodes202 = 202;
|
||||
|
||||
private async Task TryMailAsync(ContactMessage message, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await mailSender.SendAsync(message, cancellationToken);
|
||||
if (result == ContactMailOutcome.Skipped)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
message.MailAttempts++;
|
||||
message.MailStatus = result == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Type only: the exception message could carry addresses or content.
|
||||
logger.LogError("Notification mail for a contact message failed ({ExceptionType})", ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static ContactMessage NewMessage(
|
||||
ContactMessageRequest request, string siteId, DateTimeOffset now,
|
||||
ContactMessageStatus status, ContactMailStatus mailStatus, DateTimeOffset retentionUntil) => new()
|
||||
|
||||
Reference in New Issue
Block a user