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:
Artemy
2026-10-17 19:53:34 +07:00
parent 9aa7e017e2
commit e060b2bcbb
21 changed files with 16353 additions and 132 deletions
@@ -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)