mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-18 05:15:06 +00:00
Harden push notification delivery
Keep encrypted message content out of push payloads and improve cross-platform notification data. Add token registration validation and per-session unregister support, batch and deduplicate sends, remove only confirmed unregistered tokens, and protect queued retries with leases. Add delivery tests and document the push API and Firebase setup.
This commit is contained in:
@@ -15,7 +15,9 @@ public class MessageReadingService : IMessageReadingService
|
||||
private readonly ILogger<MessageReadingService> _logger;
|
||||
private readonly INowDateTimeProvider _dateTimeProvider;
|
||||
|
||||
public MessageReadingService(GovorDbContext dbContext, ILogger<MessageReadingService> logger,
|
||||
public MessageReadingService(
|
||||
GovorDbContext dbContext,
|
||||
ILogger<MessageReadingService> logger,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
namespace Govor.Application.Interfaces.PushNotifications.Models;
|
||||
|
||||
public record SendPushResult(int SuccessCount, int FailureCount, IEnumerable<string> FailedTokens);
|
||||
/// <param name="SuccessCount">Tokens accepted by the provider.</param>
|
||||
/// <param name="FailureCount">All failed sends, including retryable errors.</param>
|
||||
/// <param name="FailedTokens">Only permanently unregistered tokens that can safely be deleted.</param>
|
||||
public record SendPushResult(int SuccessCount, int FailureCount, IEnumerable<string> FailedTokens);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using FirebaseAdmin.Messaging;
|
||||
using Govor.Application.Interfaces.PushNotifications;
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -8,9 +7,11 @@ namespace Govor.Application.PushNotifications.Providers;
|
||||
public class FirebasePushProvider : IPushNotificationProvider
|
||||
{
|
||||
private readonly ILogger<FirebasePushProvider> _logger;
|
||||
public FirebasePushProvider(ILogger<FirebasePushProvider> logger)
|
||||
private readonly FirebaseMessaging? _messaging;
|
||||
public FirebasePushProvider(ILogger<FirebasePushProvider> logger, FirebaseMessaging? messaging = null)
|
||||
{
|
||||
_logger = logger;
|
||||
_messaging = messaging;
|
||||
}
|
||||
|
||||
public string Name => "FCM";
|
||||
@@ -21,14 +22,14 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
|
||||
try
|
||||
{
|
||||
string response = await FirebaseMessaging.DefaultInstance.SendAsync(msg);
|
||||
await (_messaging ?? FirebaseMessaging.DefaultInstance).SendAsync(msg);
|
||||
return new SendPushResult(1, 0, []);
|
||||
}
|
||||
catch (FirebaseMessagingException ex)
|
||||
{
|
||||
if (IsInvalidTokenError(ex))
|
||||
{
|
||||
_logger.LogError(ex, "FCM send failed");
|
||||
_logger.LogInformation("FCM registration is no longer valid");
|
||||
return new SendPushResult(0, 1, [token]);
|
||||
}
|
||||
|
||||
@@ -38,6 +39,7 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
|
||||
public async Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
|
||||
{
|
||||
tokens = tokens.Distinct().ToArray();
|
||||
if (tokens.Count == 0)
|
||||
return new SendPushResult(0, 0, []);
|
||||
|
||||
@@ -65,20 +67,14 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
Body = message.Body,
|
||||
},
|
||||
Data = message.Data,
|
||||
Android = message.ChannelId != null ? new AndroidConfig
|
||||
{
|
||||
Priority = Priority.High,
|
||||
Notification = new AndroidNotification
|
||||
{
|
||||
ChannelId = message.ChannelId ?? "chat_messages",
|
||||
Tag = message.Tag,
|
||||
}
|
||||
} : null
|
||||
Android = BuildAndroidConfig(message),
|
||||
Apns = BuildApnsConfig(message),
|
||||
Webpush = BuildWebpushConfig(message)
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(multicastMsg);
|
||||
var response = await (_messaging ?? FirebaseMessaging.DefaultInstance).SendEachForMulticastAsync(multicastMsg);
|
||||
|
||||
var failedTokens = new List<string>();
|
||||
|
||||
@@ -118,25 +114,37 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
Body = pm.Body
|
||||
},
|
||||
Data = pm.Data,
|
||||
Token = token
|
||||
Token = token,
|
||||
Android = BuildAndroidConfig(pm),
|
||||
Apns = BuildApnsConfig(pm),
|
||||
Webpush = BuildWebpushConfig(pm)
|
||||
};
|
||||
|
||||
if (pm.ChannelId is not null)
|
||||
{
|
||||
msg.Android = new AndroidConfig
|
||||
{
|
||||
Priority = Priority.High,
|
||||
Notification = new AndroidNotification
|
||||
{
|
||||
ChannelId = pm.ChannelId,
|
||||
Tag = pm.Tag,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
private static AndroidConfig BuildAndroidConfig(PushMessage message) => new()
|
||||
{
|
||||
Priority = Priority.High,
|
||||
Notification = new AndroidNotification
|
||||
{
|
||||
ChannelId = string.IsNullOrWhiteSpace(message.ChannelId) ? "chat_messages" : message.ChannelId,
|
||||
Tag = message.Tag,
|
||||
Sound = "default"
|
||||
}
|
||||
};
|
||||
|
||||
private static ApnsConfig BuildApnsConfig(PushMessage message) => new()
|
||||
{
|
||||
Headers = new Dictionary<string, string> { ["apns-push-type"] = "alert", ["apns-priority"] = "10" },
|
||||
Aps = new Aps { Sound = "default", ThreadId = string.IsNullOrEmpty(message.Tag) ? null : message.Tag }
|
||||
};
|
||||
|
||||
private static WebpushConfig BuildWebpushConfig(PushMessage message) => new()
|
||||
{
|
||||
Notification = new WebpushNotification { Tag = message.Tag }
|
||||
};
|
||||
|
||||
private static bool IsInvalidTokenError(FirebaseMessagingException ex)
|
||||
{
|
||||
return ex.MessagingErrorCode is MessagingErrorCode.Unregistered;
|
||||
|
||||
@@ -9,11 +9,11 @@ public class NullPushProvider : IPushNotificationProvider
|
||||
|
||||
public Task<SendPushResult> SendToTokenAsync(string token, PushMessage message)
|
||||
{
|
||||
return Task.FromResult(new SendPushResult(0, 0, []));
|
||||
return Task.FromResult(new SendPushResult(1, 0, []));
|
||||
}
|
||||
|
||||
public Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
|
||||
{
|
||||
return Task.FromResult(new SendPushResult(0, 0, []));
|
||||
return Task.FromResult(new SendPushResult(tokens.Count, 0, []));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,10 +40,11 @@ public class PushNotificationService : IPushNotificationService
|
||||
|
||||
public async Task<Result<Unit, Error>> SendToUsersAsync(IEnumerable<Guid> userIds, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null)
|
||||
{
|
||||
if (userIds == null || !userIds.Any())
|
||||
var recipients = userIds?.Distinct().ToArray();
|
||||
if (recipients is null || recipients.Length == 0)
|
||||
return Result.Failure(Error.Failure("Push.InvalidArgs", "User IDs collection cannot be empty."));
|
||||
|
||||
var tokensResult = await _tokenService.GetUsersStringsActiveTokensAsync(userIds);
|
||||
var tokensResult = await _tokenService.GetUsersStringsActiveTokensAsync(recipients);
|
||||
if (tokensResult.IsFailure)
|
||||
return Result.Failure(tokensResult.Error);
|
||||
|
||||
@@ -69,15 +70,7 @@ public class PushNotificationService : IPushNotificationService
|
||||
var message = CreateMessage(title, body, channelId, tag, data);
|
||||
var result = await _provider.SendToTokenAsync(token, message);
|
||||
|
||||
if (result.FailureCount > 0)
|
||||
{
|
||||
await _tokenService.RemoveTokensAsync(result.FailedTokens);
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for session {SessionId}", result.FailureCount, sessionId);
|
||||
}
|
||||
|
||||
if (result.FailureCount > result.FailedTokens.Count())
|
||||
return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily."));
|
||||
return Result.Success();
|
||||
return await HandleResultAsync(result, [token]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -88,26 +81,49 @@ public class PushNotificationService : IPushNotificationService
|
||||
|
||||
private async Task<Result<Unit, Error>> SendMulticastInternalAsync(List<string> tokens, string title, string body, string channelId, string tag, Dictionary<string, string>? data, string targetInfo)
|
||||
{
|
||||
try
|
||||
Error? failure = null;
|
||||
var message = CreateMessage(title, body, channelId, tag, data);
|
||||
// FCM accepts at most 500 tokens per call. Process batches independently so a
|
||||
// failed batch does not prevent unrelated devices from receiving a message.
|
||||
foreach (var batch in tokens.Distinct().Chunk(500))
|
||||
{
|
||||
var message = CreateMessage(title, body, channelId, tag, data);
|
||||
var result = await _provider.SendMulticastAsync(tokens, message);
|
||||
|
||||
if (result.FailureCount > 0)
|
||||
try
|
||||
{
|
||||
await _tokenService.RemoveTokensAsync(result.FailedTokens);
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for target: {Target}", result.FailureCount, targetInfo);
|
||||
var result = await _provider.SendMulticastAsync(batch, message);
|
||||
var handled = await HandleResultAsync(result, batch);
|
||||
if (handled.IsFailure)
|
||||
failure ??= handled.Error;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Push batch failed for target {Target}", targetInfo);
|
||||
failure ??= Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily.");
|
||||
}
|
||||
}
|
||||
|
||||
if (result.FailureCount > result.FailedTokens.Count())
|
||||
return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily."));
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
return failure is null ? Result.Success() : Result.Failure(failure);
|
||||
}
|
||||
|
||||
private async Task<Result<Unit, Error>> HandleResultAsync(SendPushResult result, IReadOnlyList<string> tokens)
|
||||
{
|
||||
// Only a permanent registration failure authorizes deleting a token. Provider
|
||||
// outages, malformed payloads and authentication errors must leave tokens intact.
|
||||
var invalid = result.FailedTokens.Distinct().Intersect(tokens).ToArray();
|
||||
if (invalid.Length > 0)
|
||||
{
|
||||
_logger.LogError(ex, "Error occurred during push notification multicast sending to {Target}", targetInfo);
|
||||
return Result.Failure(ex);
|
||||
var removed = await _tokenService.RemoveTokensAsync(invalid);
|
||||
if (removed.IsFailure)
|
||||
return Result.Failure(removed.Error);
|
||||
_logger.LogInformation("Removed {Count} unregistered push tokens", invalid.Length);
|
||||
}
|
||||
|
||||
if (result.SuccessCount + result.FailureCount != tokens.Count || result.FailureCount > invalid.Length)
|
||||
{
|
||||
_logger.LogWarning("Push delivery incomplete: {SuccessCount} accepted, {FailureCount} failed, {InvalidCount} unregistered",
|
||||
result.SuccessCount, result.FailureCount, invalid.Length);
|
||||
return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily."));
|
||||
}
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
private static PushMessage CreateMessage(string title, string body, string channelId, string tag, Dictionary<string, string>? data)
|
||||
|
||||
@@ -130,8 +130,6 @@ public class PushTokenService : IPushTokenService
|
||||
.Where(t => tokens.Contains(t.Token))
|
||||
.ExecuteDeleteAsync();
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -145,7 +143,7 @@ public class PushTokenService : IPushTokenService
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token) || token.Length > 512 || string.IsNullOrWhiteSpace(platform) || platform.Length > 50)
|
||||
{
|
||||
return Result<Unit, Error>.Failure(Error.Failure("PushToken.Empty", "Push token cannot be empty."));
|
||||
return Result<Unit, Error>.Failure(Error.Validation("PushToken.Invalid", "Token and platform are required and must not exceed 512 and 50 characters respectively."));
|
||||
}
|
||||
|
||||
if (!await _context.UserSessions.AnyAsync(s => s.Id == sessionId && s.UserId == userId &&
|
||||
|
||||
@@ -34,10 +34,14 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
{
|
||||
if (reactionId == Guid.Empty)
|
||||
return Result.Failure<MessageReactionState>(Error.Validation("Reaction.InvalidId", "A reaction ID is required."));
|
||||
|
||||
var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
|
||||
if (message is null) return Result.Failure<MessageReactionState>(Missing());
|
||||
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
@@ -45,9 +49,11 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
// Same lock order as channel policy changes; serialize reaction decisions with policy writes.
|
||||
await context.ChatGroups.Where(g => g.Id == message.RecipientId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.ReactionMode, g => g.ReactionMode));
|
||||
|
||||
if (await context.Messages.Where(m => m.Id == messageId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion)) == 0)
|
||||
return Result.Failure<MessageReactionState>(Missing());
|
||||
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
|
||||
@@ -56,10 +62,13 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
{
|
||||
item = await context.ReactionItems.AsNoTracking()
|
||||
.FirstOrDefaultAsync(r => r.Id == reactionId && r.IsEnabled && r.Pack.IsEnabled);
|
||||
if (item is null) return Result.Failure<MessageReactionState>(Error.NotFound("Reaction.NotAvailable", "Reaction is not available."));
|
||||
if (item is null)
|
||||
return Result.Failure<MessageReactionState>(Error.NotFound("Reaction.NotAvailable", "Reaction is not available."));
|
||||
|
||||
var channel = message.RecipientType == RecipientType.Group
|
||||
? await context.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == message.RecipientId && g.IsChannel)
|
||||
: null;
|
||||
|
||||
if (channel is not null && (channel.ReactionMode == ChannelReactionMode.None ||
|
||||
(channel.ReactionMode == ChannelReactionMode.Selected && !await context.ChannelAllowedReactions
|
||||
.AnyAsync(r => r.GroupId == channel.Id && r.ReactionId == item.Id))))
|
||||
@@ -82,7 +91,9 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion + 1));
|
||||
}
|
||||
var state = (await StateAsync(messageId, userId))! with { Changed = changed };
|
||||
|
||||
await transaction.CommitAsync();
|
||||
|
||||
return Result.Success(state);
|
||||
});
|
||||
}
|
||||
@@ -105,6 +116,7 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
{
|
||||
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group))
|
||||
return Result.Failure<ChannelReactionPolicy>(Denied());
|
||||
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable);
|
||||
|
||||
Reference in New Issue
Block a user