Add queued email and Firebase push delivery
This commit is contained in:
1 parent
c96eb155ae
commit
599237dd2c
22 files changed
+497
-8
No files matched your search
@@ -0,0 +1,121 @@
|
||||
using System.Data;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Infrastructure.Email;
|
||||
using Helpdesk.Infrastructure.Notifications;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Background;
|
||||
|
||||
internal sealed partial class NotificationDispatcher(
|
||||
IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger<NotificationDispatcher> logger,
|
||||
FirebasePushSender? push = null) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2);
|
||||
private readonly bool emailEnabled = email is not LoggingEmailSender;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!emailEnabled && push is null)
|
||||
return;
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await DeliverNextAsync(stoppingToken))
|
||||
continue;
|
||||
}
|
||||
catch (Exception failure) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
LogDispatchFailure(failure.GetType().Name);
|
||||
}
|
||||
|
||||
await Task.Delay(PollInterval, clock, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> DeliverNextAsync(CancellationToken ct)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var rows = await db.NotificationDeliveries.FromSql($"""
|
||||
SELECT * FROM notification_delivery
|
||||
WHERE status = 'PENDING' AND next_attempt_at <= {now}
|
||||
AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH'))
|
||||
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
""").ToListAsync(ct);
|
||||
if (rows.SingleOrDefault() is not { } delivery)
|
||||
return false;
|
||||
|
||||
var recipient = await (
|
||||
from notification in db.Notifications.AsNoTracking()
|
||||
join user in db.Users on notification.UserId equals user.Id
|
||||
where notification.Id == delivery.NotificationId
|
||||
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
||||
).SingleAsync(ct);
|
||||
|
||||
if (!recipient.IsActive)
|
||||
delivery.Skip();
|
||||
else if (delivery.Channel == DeliveryChannel.Email)
|
||||
{
|
||||
if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled)
|
||||
await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct);
|
||||
else
|
||||
delivery.Skip();
|
||||
}
|
||||
else
|
||||
{
|
||||
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await email.SendAsync(address, notification.Title, notification.Message, ct);
|
||||
delivery.RecordSent(clock.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
catch (EmailDeliveryException failure)
|
||||
{
|
||||
delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendPushAsync(
|
||||
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
|
||||
{
|
||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
||||
if (tokens.Length == 0)
|
||||
{
|
||||
delivery.Skip();
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await push!.SendAsync(notification, tokens, ct);
|
||||
foreach (var invalidToken in result.InvalidTokens)
|
||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (result.Sent)
|
||||
delivery.RecordSent(now);
|
||||
else
|
||||
delivery.RecordFailure(now, result.FailureReason, result.Retryable);
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")]
|
||||
private partial void LogDispatchFailure(string failureType);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Infrastructure.Background;
|
||||
using Helpdesk.Infrastructure.Email;
|
||||
using Helpdesk.Infrastructure.Files;
|
||||
using Helpdesk.Infrastructure.Notifications;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -37,11 +38,15 @@ public static class DependencyInjection
|
||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
|
||||
var firebaseCredentials = configuration["Firebase:ServiceAccountJson"];
|
||||
if (!string.IsNullOrWhiteSpace(firebaseCredentials))
|
||||
services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials));
|
||||
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||
|
||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||
services.AddHostedService<AdminSeeder>();
|
||||
services.AddHostedService<AuthTokenCleanupService>();
|
||||
services.AddHostedService<NotificationDispatcher>();
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILo
|
||||
if (!MailboxAddress.TryParse(to, out var recipient))
|
||||
{
|
||||
LogDeliveryFailure("InvalidRecipient");
|
||||
throw new EmailDeliveryException();
|
||||
throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false);
|
||||
}
|
||||
|
||||
var settings = options.Value;
|
||||
@@ -48,7 +48,13 @@ internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILo
|
||||
OperationCanceledException))
|
||||
{
|
||||
LogDeliveryFailure(exception.GetType().Name);
|
||||
throw new EmailDeliveryException();
|
||||
if (exception is SmtpCommandException command)
|
||||
{
|
||||
var status = (int)command.StatusCode;
|
||||
throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600);
|
||||
}
|
||||
|
||||
throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="BCrypt.Net-Next" />
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="FirebaseAdmin" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using FirebaseAdmin;
|
||||
using FirebaseAdmin.Messaging;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Google.Apis.Auth.OAuth2.Responses;
|
||||
using Helpdesk.Domain;
|
||||
using Notification = Helpdesk.Domain.Notifications.Notification;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Notifications;
|
||||
|
||||
internal sealed record PushDeliveryResult(bool Sent, bool Retryable, string FailureReason, IReadOnlyList<string> InvalidTokens);
|
||||
|
||||
internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
||||
{
|
||||
public static FirebasePushSender Create(string serviceAccountJson)
|
||||
{
|
||||
ServiceAccountCredential credential;
|
||||
try
|
||||
{
|
||||
credential = CredentialFactory.FromJson<ServiceAccountCredential>(serviceAccountJson);
|
||||
}
|
||||
catch (Exception exception) when (
|
||||
exception is ArgumentException or InvalidOperationException or CryptographicException or Newtonsoft.Json.JsonException)
|
||||
{
|
||||
throw new InvalidOperationException("Nastavte platný JSON klíče servisního účtu Firebase.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(credential.ProjectId))
|
||||
throw new InvalidOperationException("Klíč servisního účtu Firebase musí obsahovat project_id.");
|
||||
|
||||
var app = FirebaseApp.Create(new AppOptions
|
||||
{
|
||||
Credential = credential.ToGoogleCredential(),
|
||||
ProjectId = credential.ProjectId,
|
||||
});
|
||||
return new FirebasePushSender(app);
|
||||
}
|
||||
|
||||
public async Task<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
||||
{
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture),
|
||||
};
|
||||
if (notification.IssueId is int issueId)
|
||||
data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture);
|
||||
if (notification.ProposalId is int proposalId)
|
||||
data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
var invalidTokens = new List<string>();
|
||||
var sent = false;
|
||||
var retryable = false;
|
||||
var reason = "FCM_NO_ACCEPTED_DEVICE";
|
||||
|
||||
foreach (var batch in tokens.Chunk(500))
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await messaging.SendEachForMulticastAsync(new MulticastMessage
|
||||
{
|
||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
||||
Tokens = batch,
|
||||
#pragma warning restore CS0618
|
||||
Notification = new FirebaseAdmin.Messaging.Notification
|
||||
{
|
||||
Title = notification.Title,
|
||||
Body = notification.Message,
|
||||
},
|
||||
Data = data,
|
||||
}, timeout.Token);
|
||||
|
||||
sent |= result.SuccessCount > 0;
|
||||
for (var i = 0; i < result.Responses.Count; i++)
|
||||
{
|
||||
if (result.Responses[i].Exception is not { } failure)
|
||||
continue;
|
||||
if (IsInvalidToken(failure))
|
||||
invalidTokens.Add(batch[i]);
|
||||
|
||||
if (!retryable)
|
||||
reason = FailureReason(failure);
|
||||
retryable |= IsRetryable(failure);
|
||||
}
|
||||
}
|
||||
catch (FirebaseMessagingException failure)
|
||||
{
|
||||
if (!retryable)
|
||||
reason = FailureReason(failure);
|
||||
retryable |= IsRetryable(failure);
|
||||
}
|
||||
catch (TokenResponseException)
|
||||
{
|
||||
return new PushDeliveryResult(sent, true, "FCM_AUTHENTICATION_FAILED", invalidTokens);
|
||||
}
|
||||
catch (Exception failure) when (!ct.IsCancellationRequested &&
|
||||
failure is HttpRequestException or IOException or OperationCanceledException)
|
||||
{
|
||||
return new PushDeliveryResult(sent, true, $"FCM_{failure.GetType().Name}", invalidTokens);
|
||||
}
|
||||
}
|
||||
|
||||
return new PushDeliveryResult(sent, retryable, reason, invalidTokens);
|
||||
}
|
||||
|
||||
private static bool IsInvalidToken(FirebaseMessagingException failure) =>
|
||||
failure.MessagingErrorCode == MessagingErrorCode.Unregistered ||
|
||||
(failure.MessagingErrorCode == MessagingErrorCode.InvalidArgument &&
|
||||
failure.Message.Contains("registration token", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static bool IsRetryable(FirebaseMessagingException failure) =>
|
||||
failure.MessagingErrorCode is MessagingErrorCode.Unavailable or MessagingErrorCode.Internal or MessagingErrorCode.QuotaExceeded ||
|
||||
failure.ErrorCode is ErrorCode.Unavailable or ErrorCode.Internal or ErrorCode.ResourceExhausted or ErrorCode.DeadlineExceeded;
|
||||
|
||||
private static string FailureReason(FirebaseMessagingException failure) =>
|
||||
$"FCM_{failure.MessagingErrorCode?.ToCode() ?? failure.ErrorCode.ToCode()}";
|
||||
|
||||
public void Dispose() => app.Delete();
|
||||
}
|
||||
@@ -86,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
||||
var pushDevice = modelBuilder.Entity<PushDevice>();
|
||||
pushDevice.ToTable("push_device");
|
||||
pushDevice.Property(x => x.FcmToken).HasMaxLength(512);
|
||||
pushDevice.HasIndex(x => x.FcmToken).IsUnique();
|
||||
}
|
||||
|
||||
public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) =>
|
||||
Database.ExecuteSqlInterpolatedAsync($"""
|
||||
INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token})
|
||||
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id)
|
||||
""", ct);
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||
{
|
||||
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||
|
||||
@@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati
|
||||
b.ToTable("notification_delivery");
|
||||
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
||||
b.Property(x => x.LastError).HasMaxLength(1000);
|
||||
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user