Skip to content

Commit

Permalink
Prune inactive users from the activity tracker
Browse files Browse the repository at this point in the history
  • Loading branch information
OoLunar authored and Instellate committed Nov 17, 2023
1 parent 84a8ee0 commit aad9eeb
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/UserActivityTracker.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace NotifierRedirecter;

public sealed class UserActivityTracker
{
private static readonly TimeSpan _activityTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan _cleanupInterval = TimeSpan.FromMinutes(5);

/// <summary>
/// Tracks the user's last activity within a channel.
/// </summary>
private readonly ConcurrentDictionary<ulong, (ulong ChannelId, DateTimeOffset LastActivity)> _tracker = new();

public UserActivityTracker() => _ = CleanupInactiveUsersAsync();

public void UpdateUser(ulong userId, ulong channelId) => this._tracker.AddOrUpdate(userId, (channelId, DateTimeOffset.UtcNow), (_, _) => (channelId, DateTimeOffset.UtcNow));
public async ValueTask<bool> IsActiveAsync(ulong userId, ulong channelId)
{
Expand All @@ -21,4 +25,20 @@ public async ValueTask<bool> IsActiveAsync(ulong userId, ulong channelId)
await Task.Delay(_activityTimeout);
return this._tracker.TryGetValue(userId, out (ulong ChannelId, DateTimeOffset LastActivity) value) && value.ChannelId == channelId && value.LastActivity > DateTimeOffset.UtcNow.AddSeconds(-15);
}

public async Task CleanupInactiveUsersAsync()
{
PeriodicTimer timer = new(_cleanupInterval);
while (await timer.WaitForNextTickAsync())
{
foreach ((ulong userId, (ulong _, DateTimeOffset LastActivity)) in this._tracker)
{
// If the user hasn't done anything since the last cleanup interval, remove them from the tracker.
if (LastActivity < DateTimeOffset.UtcNow.Add(-_cleanupInterval))
{
this._tracker.TryRemove(userId, out _);
}
}
}
}
}

0 comments on commit aad9eeb

Please sign in to comment.