Українська
Хаб чату
Крок 1. Плавний перехід у режим офлайн
Навіщо. Перезавантаження сторінки закриває старе з’єднання й за секунду відкриває нове. Якби «офлайн» оголошували в мить закриття останнього з’єднання, кожне перезавантаження змушувало б користувача блимати «поза мережею» й «у мережі» для всіх його контактів. Тому оголошення чекає пільговий період (типово 5 секунд) і скасовується, якщо користувач за цей час повернувся.
Що зробити.
cs
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using Chatex.Core.Chats;
using Chatex.Core.Users;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Options;
namespace Chatex.Api.Hubs;
/// <summary>
/// Announces that a user went offline, but only after a grace period, so a page reload or a short network drop
/// does not make them flicker offline and back.
/// </summary>
internal sealed partial class PresenceService(
PresenceTracker tracker,
IHubContext<ChatHub, IChatClient> hub,
IServiceScopeFactory scopeFactory,
IOptions<PresenceOptions> options,
TimeProvider timeProvider,
IHostApplicationLifetime lifetime,
ILogger<PresenceService> logger)
{
// The latest pending check per user. A newer disconnect replaces it, so only the last one broadcasts.
private readonly ConcurrentDictionary<Guid, object> _pending = new();
/// <summary>Called when the user's last connection closed. Runs in the background.</summary>
public void ScheduleOffline(Guid userId)
{
var ticket = new object();
_pending[userId] = ticket;
_ = Task.Run(() => GoOfflineAsync(userId, ticket));
}
private async Task GoOfflineAsync(Guid userId, object ticket)
{
var cancellationToken = lifetime.ApplicationStopping;
try
{
var grace = TimeSpan.FromSeconds(options.Value.OfflineGraceSeconds);
if (grace > TimeSpan.Zero)
{
await Task.Delay(grace, timeProvider, cancellationToken);
}
if (!_pending.TryRemove(new KeyValuePair<Guid, object>(userId, ticket)) || tracker.IsOnline(userId))
{
return;
}
await using var scope = scopeFactory.CreateAsyncScope();
var profiles = scope.ServiceProvider.GetRequiredService<IProfileService>();
var chats = scope.ServiceProvider.GetRequiredService<IChatService>();
var lastSeenAt = await profiles.TouchLastSeenAsync(userId, cancellationToken);
var chatIds = await chats.GetMyChatIdsAsync(userId, cancellationToken);
if (chatIds.Count > 0)
{
await hub.Clients.Groups(chatIds.Select(ChatHub.GroupName).ToList()).UserOffline(userId, lastSeenAt);
}
}
catch (Exception) when (cancellationToken.IsCancellationRequested)
{
// Shutting down; nobody is left to tell.
}
catch (Exception ex)
{
LogOfflineFailed(ex, userId);
}
}
[LoggerMessage(Level = LogLevel.Error, Message = "Failed to announce that user {UserId} went offline.")]
private partial void LogOfflineFailed(Exception exception, Guid userId);
}
internal sealed class PresenceOptions
{
public const string Section = "Presence";
/// <summary>How long a user stays online after their last connection closes.</summary>
[Range(0, 300)]
public int OfflineGraceSeconds { get; set; } = 5;
}- Квиток на кожне відключення:
ScheduleOfflineзберігає для користувача новий об’єкт і запускає перевірку у фоні (Task.Run, без очікування – хаб не повинен чекати 5 секунд). Новіше відключення замінює квиток, тож повідомляти може лише остання перевірка:TryRemove(KeyValuePair(userId, ticket))вдається, лише якщо квиток досі поточний. Task.Delay(grace, timeProvider, …)чекає за впровадженим годинником і скасовується, коли застосунок зупиняється.- Усе ще офлайн? Якщо користувач перепідключився впродовж пільгового періоду,
tracker.IsOnlineдорівнюєtrueі нічого не надсилається. - В іншому разі сервіс записує «востаннє в мережі» (тема 9) і надсилає
UserOfflineіз цим часом до груп усіх чатів користувача. Він працює поза запитом, тому створює власну область для сервісів із областю дії. IHubContext<ChatHub, IChatClient>надсилає клієнтам ззовні хаба – це той самий тип, який використовує сповіщувач у наступному розділі.- Помилки записуються в журнал, крім часу завершення роботи, коли нікому вже повідомляти.
Крок 2. Хаб
Що зробити.
cs
using Chatex.Api.Infrastructure;
using Chatex.Core.Chats;
using Chatex.Core.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Chatex.Api.Hubs;
/// <summary>
/// The realtime endpoint at <c>/hubs/chat</c>. Each connection joins a group per chat of its user; services push
/// events through <see cref="SignalRChatNotifier"/>, and the hub itself handles presence and typing.
/// </summary>
[Authorize]
internal sealed class ChatHub(
IChatService chats,
IProfileService profiles,
PresenceTracker tracker,
PresenceService presence) : Hub<IChatClient>
{
public static string GroupName(Guid chatId) => $"chat:{chatId}";
public override async Task OnConnectedAsync()
{
var userId = Context.User!.GetUserId();
var cancellationToken = Context.ConnectionAborted;
// Register before reading the chat list: a member added in between then finds this connection in the
// tracker (SignalRChatNotifier adds it to the group), and one added earlier is already in the list.
var first = tracker.Add(userId, Context.ConnectionId);
var chatIds = await chats.GetMyChatIdsAsync(userId, cancellationToken);
foreach (var chatId in chatIds)
{
await Groups.AddToGroupAsync(Context.ConnectionId, GroupName(chatId), cancellationToken);
}
if (first)
{
await profiles.TouchLastSeenAsync(userId, cancellationToken);
if (chatIds.Count > 0)
{
await Clients.Groups(chatIds.Select(GroupName).ToList()).UserOnline(userId);
}
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var userId = Context.User!.GetUserId();
if (tracker.Remove(userId, Context.ConnectionId))
{
presence.ScheduleOffline(userId);
}
await base.OnDisconnectedAsync(exception);
}
/// <summary>Tells the other members that the caller is typing. Clients call it at most once every 3 seconds.</summary>
public async Task Typing(Guid chatId)
{
var userId = Context.User!.GetUserId();
if (!await chats.IsMemberAsync(chatId, userId, Context.ConnectionAborted))
{
throw new HubException("You are not a member of this chat.");
}
await Clients.OthersInGroup(GroupName(chatId)).Typing(chatId, userId);
}
/// <summary>Returns which of <paramref name="userIds"/> have at least one open connection.</summary>
public Guid[] GetOnlineUsers(Guid[] userIds) =>
(userIds ?? []).Distinct().Where(tracker.IsOnline).ToArray();
}Підключення
OnConnectedAsync виконується для кожного нового з’єднання:
- Спершу зареєструйте з’єднання, потім читайте чати користувача. Коментар пояснює, якого стану гонитви уникає такий порядок: користувач, якого додали до чату в проміжку, знаходить з’єднання в трекері, і сповіщувач додає його до групи; той, кого додали раніше, уже є в списку чатів.
- Вступіть до однієї групи на чат:
Groups.AddToGroupAsync(Context.ConnectionId, "chat:{id}"). - Під час першого з’єднання користувача: запишіть «востаннє в мережі» й оголосіть
UserOnlineдо груп усіх чатів користувача.Clients.Groups(list)надсилає одне повідомлення кільком групам.
Відключення
OnDisconnectedAsync видаляє з’єднання; якщо воно було останнім, сервіс присутності планує перевірку офлайну. SignalR сам вилучає закрите з’єднання зі своїх груп.
Методи, які викликають клієнти
Typing(chatId)перевіряє членство – клієнт міг надіслати будь-який ідентифікатор – і надсилаєTypingіншим у групі чату (OthersInGroup), а не назад відправникові. Той, хто не є учасником, отримуєHubException, повідомлення якого доходить до клієнта.GetOnlineUsers(userIds)відповідає, хто із зазначених користувачів у мережі. Клієнт питає один раз про тих, кого показує, а потім стежить заUserOnline/UserOffline.
Чому хаб тонкий
Екземпляр хаба живе лише один виклик, тому не тримає стану в полях: трекер і сервіс присутності – це singleton, сервіси чатів і профілів мають область дії. Усе, що вирішують бізнес-правила, як і раніше відбувається в Chatex.Core.
Перевірка
dotnet build проходить успішно. Хаб зіставляється в наступному розділі.