private async Task HandleMessageAsync(IClient client, string text, IRealm realm, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(text)) { return; } var message = JsonConvert.DeserializeObject <Message>(text); await realm.HandleMessageAsync(client, message, cancellationToken); }
private async Task PruneExpiredMessagesAsync(IRealm realm, CancellationToken stoppingToken) { var clientIds = realm.GetClientIdsWithQueue(); var now = DateTime.UtcNow; var maxDiff = TimeSpan.FromSeconds(10); var seenMap = new Dictionary <string, bool>(); foreach (var clientId in clientIds) { var messageQueue = realm.GetMessageQueueById(clientId); if (messageQueue == null) { continue; } var lastReadDiff = now - messageQueue.GetReadTimestamp(); if (lastReadDiff < maxDiff) { continue; } var messages = messageQueue.GetAll(); foreach (var message in messages) { var seenKey = $"{message.Source}_{message.Destination};"; if (!seenMap.TryGetValue(seenKey, out var seen) || !seen) { var sourceClient = realm.GetClient(message.Source); await realm.HandleMessageAsync(sourceClient, Message.Create(MessageType.Expire, string.Empty), stoppingToken); seenMap[seenKey] = true; } } realm.ClearMessageQueue(clientId); } _logger.LogInformation($"Pruned expired messages for {seenMap.Keys.Count} peers."); }