mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-16 20:56:03 +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:
@@ -13,20 +13,34 @@ namespace Govor.API.Controllers;
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
[Route("api/groups/{groupId:guid}/reactions")]
|
||||
public class ChannelReactionsController(IMessageReactionService reactions, ICurrentUserService currentUser,
|
||||
IMapper mapper, IChatNotificationService notifier) : ControllerBase
|
||||
public class ChannelReactionsController(
|
||||
IMessageReactionService reactions,
|
||||
ICurrentUserService currentUser,
|
||||
IMapper mapper,
|
||||
IChatNotificationService notifier) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(Guid groupId) => (await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId))
|
||||
.Map(p => mapper.Map<ChannelReactionPolicyResponse>(p)).ToActionResult();
|
||||
public async Task<IActionResult> Get(Guid groupId) =>
|
||||
(await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId))
|
||||
.Map(p => mapper.Map<ChannelReactionPolicyResponse>(p))
|
||||
.ToActionResult();
|
||||
|
||||
[HttpPut]
|
||||
public async Task<IActionResult> Set(Guid groupId, [FromBody] ChannelReactionPolicyRequest request)
|
||||
{
|
||||
var result = await reactions.SetPolicyAsync(currentUser.GetCurrentUserId(), groupId, request.Mode, request.ReactionIds);
|
||||
if (result.IsFailure) return result.ToActionResult();
|
||||
var result = await reactions.SetPolicyAsync(
|
||||
currentUser.GetCurrentUserId(),
|
||||
groupId,
|
||||
request.Mode,
|
||||
request.ReactionIds);
|
||||
|
||||
if (result.IsFailure)
|
||||
return result.ToActionResult();
|
||||
|
||||
var response = mapper.Map<ChannelReactionPolicyResponse>(result.Value);
|
||||
|
||||
await notifier.NotifyChannelReactionPolicyChangedAsync(response);
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ public class ProfileController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("download/{id}")]
|
||||
public async Task<IActionResult> DowloadProfileByUserId(Guid id)
|
||||
public async Task<IActionResult> DownloadProfileByUserId(Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -15,15 +15,18 @@ public class PushTokensController : Controller
|
||||
private readonly ICurrentUserService _currentUser;
|
||||
private readonly ICurrentUserSessionService _currentSession;
|
||||
private readonly IPushTokenService _pushTokenService;
|
||||
private readonly ILogger<PushTokensController> _logger;
|
||||
|
||||
public PushTokensController(
|
||||
IPushTokenService pushTokenService,
|
||||
ICurrentUserService currentUser,
|
||||
ICurrentUserSessionService currentSession)
|
||||
ICurrentUserSessionService currentSession,
|
||||
ILogger<PushTokensController> logger)
|
||||
{
|
||||
_pushTokenService = pushTokenService;
|
||||
_currentUser = currentUser;
|
||||
_currentSession = currentSession;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("pushes/token/register")]
|
||||
@@ -31,30 +34,22 @@ public class PushTokensController : Controller
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
if (string.IsNullOrEmpty(req.Token) || string.IsNullOrWhiteSpace(req.Platform))
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var currentId = _currentUser.GetCurrentUserId();
|
||||
var currentSessionId = _currentSession.GetUserSessionId();
|
||||
|
||||
var result = await _pushTokenService.AddOrUpdateTokenAsync(
|
||||
userId: currentId,
|
||||
sessionId: currentSessionId,
|
||||
token: req.Token,
|
||||
platform: req.Platform);
|
||||
|
||||
return result.ToActionResult();
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return BadRequest(ex.Message);
|
||||
var result = await _pushTokenService.AddOrUpdateTokenAsync(
|
||||
_currentUser.GetCurrentUserId(), _currentSession.GetUserSessionId(), req.Token, req.Platform);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, "Unexpected Error! Please try again later.");
|
||||
_logger.LogError(ex, "Failed to register push token for the current session");
|
||||
return Problem(statusCode: StatusCodes.Status500InternalServerError,
|
||||
detail: "Push token registration failed. Please try again later.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("pushes/token")]
|
||||
public async Task<IActionResult> UnregisterToken()
|
||||
{
|
||||
var result = await _pushTokenService.DeactivateTokenBySessionAsync(_currentSession.GetUserSessionId());
|
||||
return result.ToActionResult();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,14 @@ public class ChatNotificationService : IChatNotificationService
|
||||
return true;
|
||||
var profile = await _profiles.GetUserProfileAsync(message.SenderId);
|
||||
var title = profile.IsSuccess ? profile.Value.Username : "Govor";
|
||||
var content = message.EncryptedContent ?? string.Empty;
|
||||
var body = content.Length == 0 ? "Attachment" : content[..Math.Min(40, content.Length)];
|
||||
// Message content is encrypted; never send ciphertext or a guessed preview to FCM.
|
||||
var body = "New message";
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["chatId"] = message.RecipientId.ToString(),
|
||||
["messageId"] = message.MessageId.ToString(),
|
||||
["senderId"] = message.SenderId.ToString(),
|
||||
["type"] = "chat_message",
|
||||
["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false"
|
||||
};
|
||||
var push = await _notificationService.SendToUsersAsync(recipients, title, body,
|
||||
|
||||
@@ -6,44 +6,58 @@ using Microsoft.EntityFrameworkCore;
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushDispatcher(GovorDbContext context, IChatNotificationService notifier,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
INowDateTimeProvider dateTimeProvider, ILogger<ChatPushDispatcher> logger = null)
|
||||
{
|
||||
public async Task DispatchAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = dateTimeProvider.Now;
|
||||
var pending = await context.ChatPushNotifications.AsNoTracking()
|
||||
.Where(n => n.NextAttemptAt <= now).OrderBy(n => n.NextAttemptAt)
|
||||
.Take(20).Select(n => n.MessageId).ToListAsync(cancellationToken);
|
||||
.Take(20).Select(n => new { n.MessageId, n.Attempts }).ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var id in pending)
|
||||
foreach (var item in pending)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var id = item.MessageId;
|
||||
now = dateTimeProvider.Now;
|
||||
// Conditional update claims a two-minute lease, including across server instances.
|
||||
// An interrupted worker leaves a retryable row rather than losing the notification.
|
||||
var claimed = await context.ChatPushNotifications
|
||||
.Where(n => n.MessageId == id && n.NextAttemptAt <= now)
|
||||
.Where(n => n.MessageId == id && n.NextAttemptAt <= now && n.Attempts == item.Attempts)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, now.AddMinutes(2))
|
||||
.SetProperty(n => n.Attempts, n => n.Attempts + 1), cancellationToken);
|
||||
if (claimed == 0)
|
||||
continue;
|
||||
|
||||
var message = await context.Messages.AsNoTracking()
|
||||
.Where(m => m.Id == id).Select(m => new UserMessageResponse
|
||||
{
|
||||
MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId,
|
||||
RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent,
|
||||
SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
var delivered = message is null || await notifier.DeliverPushAsync(message);
|
||||
var attempt = item.Attempts + 1;
|
||||
// An old worker must not complete or reschedule a newer worker's lease.
|
||||
var owned = context.ChatPushNotifications.Where(n => n.MessageId == id && n.Attempts == attempt);
|
||||
var delivered = false;
|
||||
try
|
||||
{
|
||||
var message = await context.Messages.AsNoTracking()
|
||||
.Where(m => m.Id == id).Select(m => new UserMessageResponse
|
||||
{
|
||||
MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId,
|
||||
RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent,
|
||||
SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
delivered = message is null || await notifier.DeliverPushAsync(message);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger?.LogError(ex, "Push attempt failed for message {MessageId}; delivery will be retried.", id);
|
||||
}
|
||||
if (delivered)
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.ExecuteDeleteAsync(cancellationToken);
|
||||
await owned.ExecuteDeleteAsync(cancellationToken);
|
||||
else
|
||||
{
|
||||
var attempts = await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.Select(n => n.Attempts).FirstOrDefaultAsync(cancellationToken);
|
||||
var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempts, 9))));
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempt, 9))));
|
||||
await owned
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, retryAt), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs;
|
||||
using Govor.Application.Authentication.JWT;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using Govor.Domain;
|
||||
@@ -201,10 +200,10 @@ app.MapGet("/server/ready", async (GovorDbContext db, CancellationToken cancella
|
||||
}
|
||||
});
|
||||
|
||||
app.MapHub<ChatsHub>("/hubs/chats", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<FriendsHub>("/hubs/friends", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<ProfileHub>("/hubs/profiles", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<PresenceHub>("/hubs/presence", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<ChatsHub>("/hubs/chats");
|
||||
app.MapHub<FriendsHub>("/hubs/friends");
|
||||
app.MapHub<ProfileHub>("/hubs/profiles");
|
||||
app.MapHub<PresenceHub>("/hubs/presence");
|
||||
|
||||
app.MapSwagger()
|
||||
.RequireAuthorization();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Govor.Contracts.Requests;
|
||||
|
||||
public class RegisterPushTokenRequest
|
||||
{
|
||||
public string Token { get; set; }
|
||||
public string Platform { get; set; }
|
||||
}
|
||||
[Required, StringLength(512)]
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
[Required, StringLength(50)]
|
||||
public string Platform { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FirebaseAdmin;
|
||||
using FirebaseAdmin.Messaging;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Google.Apis.Http;
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
using Govor.Application.PushNotifications.Providers;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class FirebasePushProviderTests
|
||||
{
|
||||
private FirebaseApp _app = null!;
|
||||
private FirebasePushProvider _provider = null!;
|
||||
private readonly ConcurrentQueue<JsonElement> _requests = new();
|
||||
private HttpStatusCode _status;
|
||||
private string _response = "";
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_requests.Clear();
|
||||
_status = HttpStatusCode.OK;
|
||||
_response = """{"name":"projects/test/messages/accepted"}""";
|
||||
_app = FirebaseApp.Create(new AppOptions
|
||||
{
|
||||
ProjectId = "test",
|
||||
Credential = GoogleCredential.FromAccessToken("test-access-token"),
|
||||
HttpClientFactory = new StubHttpFactory(async request =>
|
||||
{
|
||||
using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync());
|
||||
_requests.Enqueue(json.RootElement.GetProperty("message").Clone());
|
||||
return new HttpResponseMessage(_status) { Content = new StringContent(_response, Encoding.UTF8, "application/json") };
|
||||
})
|
||||
}, Guid.NewGuid().ToString());
|
||||
_provider = new FirebasePushProvider(NullLogger<FirebasePushProvider>.Instance, FirebaseMessaging.GetMessaging(_app));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _app.Delete();
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public async Task SingleAndMulticastUseEquivalentPlatformPayloads(bool multicast)
|
||||
{
|
||||
var message = new PushMessage { Title = "Alice", Body = "New message", ChannelId = "chat_messages",
|
||||
Tag = "chat_123", Data = new() { ["messageId"] = "123" } };
|
||||
var result = multicast
|
||||
? await _provider.SendMulticastAsync(new[] { "device", "device" }, message)
|
||||
: await _provider.SendToTokenAsync("device", message);
|
||||
Assert.That(result.SuccessCount, Is.EqualTo(1));
|
||||
var sent = _requests.Single();
|
||||
Assert.That(sent.GetProperty("token").GetString(), Is.EqualTo("device"));
|
||||
Assert.That(sent.GetProperty("data").GetProperty("messageId").GetString(), Is.EqualTo("123"));
|
||||
Assert.That(sent.GetProperty("android").GetProperty("priority").GetString(), Is.EqualTo("high"));
|
||||
var android = sent.GetProperty("android").GetProperty("notification");
|
||||
Assert.That(android.GetProperty("channel_id").GetString(), Is.EqualTo("chat_messages"));
|
||||
Assert.That(android.GetProperty("tag").GetString(), Is.EqualTo("chat_123"));
|
||||
var apns = sent.GetProperty("apns");
|
||||
Assert.That(apns.GetProperty("headers").GetProperty("apns-push-type").GetString(), Is.EqualTo("alert"));
|
||||
Assert.That(apns.GetProperty("payload").GetProperty("aps").GetProperty("thread-id").GetString(), Is.EqualTo("chat_123"));
|
||||
Assert.That(sent.GetProperty("webpush").GetProperty("notification").GetProperty("tag").GetString(), Is.EqualTo("chat_123"));
|
||||
}
|
||||
|
||||
[TestCase("UNREGISTERED", HttpStatusCode.NotFound, true)]
|
||||
[TestCase("INVALID_ARGUMENT", HttpStatusCode.BadRequest, false)]
|
||||
[TestCase("SENDER_ID_MISMATCH", HttpStatusCode.Forbidden, false)]
|
||||
public async Task MulticastInvalidatesOnlyUnregisteredTokens(string code, HttpStatusCode status, bool invalid)
|
||||
{
|
||||
_status = status;
|
||||
_response = JsonSerializer.Serialize(new { error = new { code = (int)status, message = "FCM failure",
|
||||
status = status == HttpStatusCode.NotFound ? "NOT_FOUND" : status == HttpStatusCode.BadRequest ? "INVALID_ARGUMENT" : "PERMISSION_DENIED",
|
||||
details = new[] { new Dictionary<string, string> { ["@type"] = "type.googleapis.com/google.firebase.fcm.v1.FcmError", ["errorCode"] = code } } } });
|
||||
|
||||
var result = await _provider.SendMulticastAsync(new[] { "device" }, new PushMessage { Title = "test", Body = "test" });
|
||||
|
||||
Assert.That(result.FailureCount, Is.EqualTo(1));
|
||||
Assert.That(result.FailedTokens, Is.EqualTo(invalid ? new[] { "device" } : Array.Empty<string>()));
|
||||
}
|
||||
|
||||
private sealed class StubHttpFactory(Func<HttpRequestMessage, Task<HttpResponseMessage>> send) : Google.Apis.Http.HttpClientFactory
|
||||
{
|
||||
protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args) => new StubHandler(send);
|
||||
}
|
||||
|
||||
private sealed class StubHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> send) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request);
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ public class NotificationTests
|
||||
Assert.That(_events.Single(e => e.Method == ChatHubConstants.MessageSent).Groups,
|
||||
Is.EqualTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession) }));
|
||||
_push.Verify(p => p.SendToUsersAsync(It.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _db.Bob })),
|
||||
"Alice", "hello", "chat_messages", $"chat_{_db.ChatId}",
|
||||
"Alice", "New message", "chat_messages", $"chat_{_db.ChatId}",
|
||||
It.Is<Dictionary<string, string>?>(data => data != null && data["messageId"] == message.MessageId.ToString())), Times.Once);
|
||||
}
|
||||
|
||||
@@ -99,6 +99,34 @@ public class NotificationTests
|
||||
It.IsAny<Dictionary<string, string>?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MessageReadBeforeRetrySuppressesPush()
|
||||
{
|
||||
var saved = _db.AddMessage();
|
||||
_db.Context.MessageViews.Add(new MessageView
|
||||
{ Id = Guid.NewGuid(), MessageId = saved.Id, UserId = _db.Bob, ViewedAt = DateTime.UtcNow });
|
||||
await _db.Context.SaveChangesAsync();
|
||||
var message = Message();
|
||||
message.MessageId = saved.Id;
|
||||
|
||||
Assert.That(await _notifier.DeliverPushAsync(message), Is.True);
|
||||
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PushDoesNotExposeContentAndKeepsRoutingData()
|
||||
{
|
||||
var message = Message();
|
||||
message.EncryptedContent = "sensitive plaintext or ciphertext";
|
||||
Assert.That(await _notifier.DeliverPushAsync(message), Is.True);
|
||||
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), "Alice", "New message",
|
||||
"chat_messages", $"chat_{_db.ChatId}", It.Is<Dictionary<string, string>?>(data => data != null &&
|
||||
data["type"] == "chat_message" && data["senderId"] == _db.Alice.ToString() &&
|
||||
data["chatId"] == _db.ChatId.ToString() && data["isGroup"] == "false" &&
|
||||
data["messageId"] == message.MessageId.ToString() && !data.Values.Contains(message.EncryptedContent))), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SignalRFailureStillAttemptsPushAndProviderFailureDoesNotFailSavedSend()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
using Govor.Application.PushNotifications;
|
||||
using Govor.Application.PushNotifications.Providers;
|
||||
using Govor.Domain.Common;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class PushDeliveryTests
|
||||
{
|
||||
private Mock<IPushTokenService> _tokens = null!;
|
||||
private Mock<IPushNotificationProvider> _provider = null!;
|
||||
private PushNotificationService _service = null!;
|
||||
private Guid _user;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_user = Guid.NewGuid();
|
||||
_tokens = new Mock<IPushTokenService>(MockBehavior.Strict);
|
||||
_provider = new Mock<IPushNotificationProvider>(MockBehavior.Strict);
|
||||
_service = new PushNotificationService(_provider.Object, _tokens.Object,
|
||||
NullLogger<PushNotificationService>.Instance);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MulticastDeduplicatesAndContinuesAfterOneBatchFails()
|
||||
{
|
||||
var tokens = Enumerable.Range(0, 501).Select(i => $"token-{i}").ToList();
|
||||
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
|
||||
.ReturnsAsync(Result<List<string>, Error>.Success(tokens.Concat(tokens).ToList()));
|
||||
_provider.Setup(p => p.SendMulticastAsync(It.Is<IReadOnlyList<string>>(t => t.Count == 500), It.IsAny<PushMessage>()))
|
||||
.ThrowsAsync(new HttpRequestException("Provider unavailable"));
|
||||
_provider.Setup(p => p.SendMulticastAsync(It.Is<IReadOnlyList<string>>(t => t.Count == 1 && t[0] == "token-500"), It.IsAny<PushMessage>()))
|
||||
.ReturnsAsync(new SendPushResult(1, 0, []));
|
||||
|
||||
var result = await _service.SendToUserAsync(_user, "title", "body", "chat_messages");
|
||||
|
||||
Assert.That(result.IsFailure, Is.True);
|
||||
_provider.VerifyAll();
|
||||
_tokens.Verify(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()), Times.Never);
|
||||
}
|
||||
|
||||
[TestCase(1, true)]
|
||||
[TestCase(2, false)]
|
||||
public async Task OnlyUnregisteredTokensAreRemovedAndTemporaryFailuresRequireRetry(int failures, bool success)
|
||||
{
|
||||
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
|
||||
.ReturnsAsync(Result<List<string>, Error>.Success(["good", "unregistered", "temporary"]));
|
||||
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
|
||||
.ReturnsAsync(new SendPushResult(3 - failures, failures, ["unregistered"]));
|
||||
_tokens.Setup(t => t.RemoveTokensAsync(It.Is<IEnumerable<string>>(t => t.SequenceEqual(new[] { "unregistered" }))))
|
||||
.ReturnsAsync(Govor.Domain.Common.Result.Success());
|
||||
|
||||
var result = await _service.SendToUserAsync(_user, "title", "body", "chat_messages");
|
||||
|
||||
Assert.That(result.IsSuccess, Is.EqualTo(success));
|
||||
_tokens.VerifyAll();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FailedCleanupIsNotAcknowledgedForEitherSingleOrMulticastDelivery()
|
||||
{
|
||||
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
|
||||
.ReturnsAsync(Result<List<string>, Error>.Success(["unregistered"]));
|
||||
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_user))
|
||||
.ReturnsAsync(Result<string?, Error>.Success("unregistered"));
|
||||
_tokens.Setup(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()))
|
||||
.ReturnsAsync(Govor.Domain.Common.Result.Failure(Error.ServerError("Test.Cleanup", "Unavailable")));
|
||||
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
|
||||
.ReturnsAsync(new SendPushResult(0, 1, ["unregistered"]));
|
||||
_provider.Setup(p => p.SendToTokenAsync("unregistered", It.IsAny<PushMessage>()))
|
||||
.ReturnsAsync(new SendPushResult(0, 1, ["unregistered"]));
|
||||
|
||||
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
|
||||
Assert.That((await _service.SendToSessionAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task IncompleteProviderResponseDoesNotLoseTheNotification()
|
||||
{
|
||||
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
|
||||
.ReturnsAsync(Result<List<string>, Error>.Success(["token"]));
|
||||
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
|
||||
.ReturnsAsync(new SendPushResult(0, 0, []));
|
||||
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NoTokensIsSuccessfulWithoutContactingProvider()
|
||||
{
|
||||
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
|
||||
.ReturnsAsync(Result<List<string>, Error>.Success([]));
|
||||
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsSuccess, Is.True);
|
||||
_provider.VerifyNoOtherCalls();
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,56 @@ public class PushReliabilityTests
|
||||
Assert.That(forbidden.Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
}
|
||||
|
||||
[TestCase(true)]
|
||||
[TestCase(false)]
|
||||
public async Task ExpiredWorkerCannotDeleteOrRescheduleANewerLease(bool delivered)
|
||||
{
|
||||
var message = _db.AddMessage();
|
||||
_db.Context.ChatPushNotifications.Add(new Govor.Domain.Models.Messages.ChatPushNotification
|
||||
{ MessageId = message.Id, NextAttemptAt = _now });
|
||||
await _db.Context.SaveChangesAsync();
|
||||
var notifier = new Mock<IChatNotificationService>();
|
||||
var secondWorker = new Mock<IChatNotificationService>();
|
||||
secondWorker.Setup(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).ReturnsAsync(false);
|
||||
DateTime retryAt = default;
|
||||
notifier.Setup(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).Returns(async () =>
|
||||
{
|
||||
_now = _now.AddMinutes(3);
|
||||
using var otherContext = _db.CreateContext();
|
||||
await new ChatPushDispatcher(otherContext, secondWorker.Object, _clock.Object).DispatchAsync();
|
||||
retryAt = (await otherContext.ChatPushNotifications.AsNoTracking().SingleAsync()).NextAttemptAt;
|
||||
_now = _now.AddSeconds(1);
|
||||
return delivered;
|
||||
});
|
||||
|
||||
await new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object).DispatchAsync();
|
||||
|
||||
var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync();
|
||||
Assert.That(pending.Attempts, Is.EqualTo(2));
|
||||
Assert.That(pending.NextAttemptAt, Is.EqualTo(retryAt));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NotificationExceptionDoesNotBlockRemainingMessagesInBatch()
|
||||
{
|
||||
foreach (var _ in Enumerable.Range(0, 2))
|
||||
{
|
||||
var message = _db.AddMessage();
|
||||
_db.Context.ChatPushNotifications.Add(new Govor.Domain.Models.Messages.ChatPushNotification
|
||||
{ MessageId = message.Id, NextAttemptAt = _now });
|
||||
}
|
||||
await _db.Context.SaveChangesAsync();
|
||||
var notifier = new Mock<IChatNotificationService>();
|
||||
notifier.SetupSequence(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()))
|
||||
.ThrowsAsync(new HttpRequestException("offline")).ReturnsAsync(true);
|
||||
|
||||
await new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object).DispatchAsync();
|
||||
|
||||
notifier.Verify(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()), Times.Exactly(2));
|
||||
var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync();
|
||||
Assert.That(pending.NextAttemptAt, Is.EqualTo(_now.AddSeconds(2)));
|
||||
}
|
||||
|
||||
private Guid AddSession(Guid user)
|
||||
{
|
||||
var session = new UserSession { UserId = user, ExpiresAt = _now.AddDays(1), RefreshTokenHash = Guid.NewGuid().ToString() };
|
||||
|
||||
@@ -86,6 +86,43 @@ public class ReadApiTests
|
||||
Assert.That(await count.Content.ReadAsStringAsync(), Does.Contain("\"unreadCount\":0"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PushRegistrationRotationAndUnregisterAffectOnlyTheAuthenticatedSession()
|
||||
{
|
||||
var otherSession = new UserSession { UserId = _db.Bob, ExpiresAt = DateTime.UtcNow.AddDays(1), RefreshTokenHash = "other-device" };
|
||||
_db.Context.UserSessions.Add(otherSession);
|
||||
_db.Context.UserPushTokens.Add(new UserPushToken
|
||||
{ UserId = _db.Bob, UserSessionId = otherSession.Id, Token = "other-device", Platform = "android" });
|
||||
await _db.Context.SaveChangesAsync();
|
||||
Assert.That((await _client.DeleteAsync("/api/pushes/token")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
Authorize();
|
||||
foreach (var token in new[] { "original", "rotated" })
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token, platform = "android" })).StatusCode,
|
||||
Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var registered = await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session);
|
||||
Assert.That(registered.Token, Is.EqualTo("rotated"));
|
||||
foreach (var _ in Enumerable.Range(0, 2))
|
||||
Assert.That((await _client.DeleteAsync("/api/pushes/token")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session)).IsActive, Is.False);
|
||||
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == otherSession.Id)).IsActive, Is.True);
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token = "rotated", platform = "android" })).StatusCode,
|
||||
Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session)).IsActive, Is.True);
|
||||
}
|
||||
|
||||
[TestCase(null, "android")]
|
||||
[TestCase("", "android")]
|
||||
[TestCase(" ", "android")]
|
||||
[TestCase("token", " ")]
|
||||
[TestCase("token", null)]
|
||||
public async Task PushRegistrationRejectsMissingOrBlankFields(string? token, string? platform)
|
||||
{
|
||||
Authorize();
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token, platform })).StatusCode,
|
||||
Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
Assert.That(await _db.Context.UserPushTokens.CountAsync(), Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnonymousAndRefreshTokenCannotUseReadApi()
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+38
-12
@@ -1,29 +1,55 @@
|
||||
# Push-уведомления
|
||||
|
||||
## POST /api/pushes/token/register
|
||||
## Регистрация устройства
|
||||
|
||||
Требуется роль User/Admin. JSON:
|
||||
`POST /api/pushes/token/register` требует access token с ролью User/Admin и действующей сессией. Тело:
|
||||
|
||||
```json
|
||||
{"token":"<FCM registration token>","platform":"Android"}
|
||||
```
|
||||
|
||||
Сервис связывает токен с userId и sid текущего access token, добавляет или обновляет запись. Успех Unit — 204. Пустой token/platform отклоняется 400; тело BadRequest(ModelState) не всегда содержит полезное объяснение.
|
||||
Токен привязывается к `userId` и `sid` из JWT. Передавать эти идентификаторы в запросе не нужно. Одна сессия имеет один токен; повторная регистрация обновляет токен/платформу и активирует запись. При переходе устройства на другой аккаунт токен переносится, старый аккаунт больше не получает push на это устройство.
|
||||
|
||||
При отзыве сессии связанные токены деактивируются. В DI зарегистрирован FirebasePushProvider; credentials читаются при старте приложения.
|
||||
Успех — `204 No Content`. Отсутствующие, пустые и состоящие из пробелов поля отклоняются с `400`; ограничения длины: token — 512, platform — 50 символов. Отозванная или истёкшая сессия не может зарегистрировать токен. Передавайте новый FCM token при его обновлении и заново регистрируйте его после входа в новую сессию.
|
||||
|
||||
## Отправка
|
||||
`DELETE /api/pushes/token` отключает push **только для текущей сессии**, не завершая её. Повторный вызов также возвращает `204`. Другие устройства пользователя продолжают получать уведомления. Повторный POST включает push снова. При отзыве сессии её токены деактивируются; при отправке дополнительно проверяются срок и отзыв сессии.
|
||||
|
||||
Личные сообщения вызывают отправку push собеседнику. title — имя отправителя; body — первые 40 символов EncryptedContent. Data содержит chatId и isGroup ("false"). Это текущая реализация: сервер не расшифровывает содержимое.
|
||||
## Содержимое
|
||||
|
||||
Для E2EE тело push должно быть нейтральным. Для текущего MAUI, отправляющего обычный текст, этот body раскрывает превью сообщения внешнему push-провайдеру.
|
||||
Личный чат уведомляет собеседника; группа/канал — действующих незабаненных участников, кроме отправителя. Перед каждой попыткой сервер исключает прочитавших сообщение. Push не зависит от наличия SignalR-соединения: подключение само по себе не подтверждает, что сообщение прочитано.
|
||||
|
||||
## Доставка
|
||||
`title` содержит имя отправителя (при недоступности профиля — `Govor`), `body` — нейтральное `New message`. Содержимое `EncryptedContent` в Firebase не передаётся, даже если клиент записал туда обычный текст.
|
||||
|
||||
Сохранение сообщения, SignalR и Firebase не образуют единую транзакцию. Ошибка после SaveChanges может дать ошибку Send, хотя сообщение уже записано. Автоматическое повторение без идентификатора клиентской операции может создать дубль. Нужны outbox, дедупликация и обработка недействительных FCM-токенов.
|
||||
Данные для перехода к сообщению (все значения — строки):
|
||||
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
```json
|
||||
{
|
||||
"type": "chat_message",
|
||||
"chatId": "<chat UUID>",
|
||||
"messageId": "<message UUID>",
|
||||
"senderId": "<sender UUID>",
|
||||
"isGroup": "false"
|
||||
}
|
||||
```
|
||||
|
||||
Источник: [Govor.API/Hubs/Infrastructure/ChatNotificationService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs).
|
||||
Для группы/канала `isGroup` равно `"true"`. Android получает канал `chat_messages`, высокий приоритет, стандартный звук и tag `chat_<chatId>`. Клиент должен создать этот канал. iOS получает APNs alert со стандартным звуком и `thread-id` чата; Web — notification tag чата. На iOS нужны корректная APNs-конфигурация проекта Firebase и разрешение уведомлений в приложении.
|
||||
|
||||
## Надёжность
|
||||
|
||||
Сообщение и `ChatPushNotification` сохраняются одним `SaveChanges`. Worker каждые 2 секунды выбирает до 20 задач и получает условную аренду на 2 минуты. После сбоя/перезапуска задача остаётся в БД. Ошибки повторяются с задержкой 2–300 секунд; исключение одной отправки не блокирует остальные сообщения пакета. Номер попытки защищает завершение/перепланирование от старого worker после повторного захвата задачи.
|
||||
|
||||
Токены дедуплицируются и отправляются независимыми пакетами до 500. Удаляются только токены, для которых FCM подтвердил `UNREGISTERED`. Ошибки доступа, неверный payload, `INVALID_ARGUMENT` и временные сбои не удаляют токены. Неполный ответ провайдера или ошибка очистки токенов не считаются успешной доставкой. Отсутствие активных токенов завершает задачу без отправки; последующая регистрация не отправляет старые сообщения задним числом.
|
||||
|
||||
Доставка допускает повторы до принятия провайдером и не подтверждает показ на устройстве. При частичном успехе общий повтор может повторно уведомить уже получившие устройства. Прерывание после принятия FCM до удаления задачи тоже допускает повтор: клиенту следует дедуплицировать события по `messageId`. Tag объединяет уведомления чата, но не заменяет дедупликацию. При удалении сообщения задача удаляется каскадно. Для реакций и изменений профилей/сообществ push сейчас не создаётся.
|
||||
|
||||
## Настройка Firebase
|
||||
|
||||
Включите `Firebase__Enabled=true` и передайте service account через `Firebase__CredentialsJson` либо `Firebase__CredentialsPath`. Также поддерживается путь `GOOGLE_APPLICATION_CREDENTIALS`; путь по умолчанию — `secrets/firebase-adminsdk.json` относительно каталога API. Ключи не должны попадать в репозиторий. При включённом Firebase некорректные credentials останавливают запуск.
|
||||
|
||||
`Firebase__Enabled=false` выбирает NullPushProvider для разработки: реальной доставки нет, задачи считаются обработанными. Это не режим накопления push на время отключения провайдера.
|
||||
|
||||
Изменения не требуют новой миграции; в БД должна быть применена существующая `20261003070406_ReliableChatPush`.
|
||||
|
||||
Проверка: `dotnet test Govor.Server.Tests/Govor.Server.Tests.csproj`. Тесты проверяют HTTP API, SQL-очередь/аренду/retry, обработку ошибок и реальную сериализацию Firebase SDK через подменённый HTTP-транспорт. Для PostgreSQL предусмотрена `TEST_POSTGRES_CONNECTION` на отдельную БД с именем, заканчивающимся `_tests`. Эти тесты не подтверждают доставку на физическое устройство.
|
||||
|
||||
Лимит пакета и классификация ошибок сверены с [документацией отправки FCM](https://firebase.google.com/docs/cloud-messaging/send/admin-sdk) и [кодами ошибок FCM](https://firebase.google.com/docs/cloud-messaging/error-codes).
|
||||
|
||||
Reference in New Issue
Block a user