122 lines
4.7 KiB
C#
122 lines
4.7 KiB
C#
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);
|
|
}
|