From 91ae34d415b3cd30039c646e55867d5eab5ea23f Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Thu, 24 Jul 2025 17:39:14 +0800 Subject: [PATCH] :zap: Optimized last active flush handler --- .../Handlers/LastActiveFlushHandler.cs | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/DysonNetwork.Pass/Handlers/LastActiveFlushHandler.cs b/DysonNetwork.Pass/Handlers/LastActiveFlushHandler.cs index 4d96e99..870c19d 100644 --- a/DysonNetwork.Pass/Handlers/LastActiveFlushHandler.cs +++ b/DysonNetwork.Pass/Handlers/LastActiveFlushHandler.cs @@ -12,11 +12,14 @@ public class LastActiveInfo public Instant SeenAt { get; set; } } -public class LastActiveFlushHandler(IServiceProvider serviceProvider) : IFlushHandler +public class LastActiveFlushHandler(IServiceProvider srp, ILogger logger) + : IFlushHandler { public async Task FlushAsync(IReadOnlyList items) { - using var scope = serviceProvider.CreateScope(); + logger.LogInformation("Flushing {Count} LastActiveInfo items...", items.Count); + + using var scope = srp.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Remove duplicates by grouping on (sessionId, accountId), taking the most recent SeenAt @@ -26,29 +29,27 @@ public class LastActiveFlushHandler(IServiceProvider serviceProvider) : IFlushHa .ToList(); // Build dictionaries so we can match session/account IDs to their new "last seen" timestamps - var sessionIdMap = distinctItems + var sessionMap = distinctItems .GroupBy(x => x.Session.Id) .ToDictionary(g => g.Key, g => g.Last().SeenAt); - var accountIdMap = distinctItems + var accountMap = distinctItems .GroupBy(x => x.Account.Id) .ToDictionary(g => g.Key, g => g.Last().SeenAt); - // Update sessions using native EF Core ExecuteUpdateAsync - foreach (var kvp in sessionIdMap) - { - await db.AuthSessions - .Where(s => s.Id == kvp.Key) - .ExecuteUpdateAsync(s => s.SetProperty(x => x.LastGrantedAt, kvp.Value)); - } - - // Update account profiles using native EF Core ExecuteUpdateAsync - foreach (var kvp in accountIdMap) - { - await db.AccountProfiles - .Where(a => a.AccountId == kvp.Key) - .ExecuteUpdateAsync(a => a.SetProperty(x => x.LastSeenAt, kvp.Value)); - } + var now = SystemClock.Instance.GetCurrentInstant(); + + var updatingSessions = sessionMap.Select(x => x.Key).ToList(); + var sessionUpdates = await db.AuthSessions + .Where(s => updatingSessions.Contains(s.Id)) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.LastGrantedAt, now)); + logger.LogInformation("Updated {Count} auth sessions according to LastActiveInfo", sessionUpdates); + + var updatingAccounts = accountMap.Select(x => x.Key).ToList(); + var profileUpdates = await db.AccountProfiles + .Where(a => updatingAccounts.Contains(a.AccountId)) + .ExecuteUpdateAsync(a => a.SetProperty(x => x.LastSeenAt, now)); + logger.LogInformation("Updated {Count} account profiles according to LastActiveInfo", profileUpdates); } }