English
The chat hub
Step 1. Going offline gracefully
Why. Reloading a page closes the old connection and opens a new one a second later. If "offline" were announced the moment the last connection closed, every reload would make the user flicker offline and back for all their contacts. So the announcement waits a grace period (5 seconds by default) and is dropped if the user came back in the meantime.
Do.
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;
}- A ticket per disconnect:
ScheduleOfflinestores a new object for the user and starts the check in the background (Task.Run, not awaited — the hub must not wait 5 seconds). A newer disconnect replaces the ticket, so only the latest check may broadcast:TryRemove(KeyValuePair(userId, ticket))succeeds only if the ticket is still the current one. Task.Delay(grace, timeProvider, …)waits with the injected clock and is cancelled when the application stops.- Still offline? If the user reconnected during the grace period,
tracker.IsOnlineistrueand nothing is sent. - Otherwise the service records "last seen" (topic 9) and sends
UserOfflinewith that time to the groups of all the user's chats. It runs outside a request, so it creates its own scope for the scoped services. IHubContext<ChatHub, IChatClient>sends to clients from outside the hub — the same type the notifier uses in the next chapter.- Errors are logged, except during shutdown, when nobody is left to tell.
Step 2. The hub
Do.
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();
}Connecting
OnConnectedAsync runs for every new connection:
- Register the connection first, then read the user's chats. The comment explains the race this order avoids: a user added to a chat in between finds the connection in the tracker and is added to the group by the notifier; one added before is already in the chat list.
- Join one group per chat:
Groups.AddToGroupAsync(Context.ConnectionId, "chat:{id}"). - On the first connection of the user: record "last seen" and announce
UserOnlineto the groups of all the user's chats.Clients.Groups(list)sends one message to several groups.
Disconnecting
OnDisconnectedAsync removes the connection; if it was the last one, the presence service schedules the offline check. SignalR removes a closed connection from its groups by itself.
Methods clients call
Typing(chatId)checks membership — a client could send any id — and sendsTypingto the others in the chat's group (OthersInGroup), not back to the sender. A non-member gets aHubException, whose message reaches the client.GetOnlineUsers(userIds)answers which of the given users are online. The client asks once for the users it shows and then followsUserOnline/UserOffline.
Why the hub is thin
A hub instance lives for one call only, so it keeps no state in fields: the tracker and the presence service are singletons, the chat and profile services scoped. Everything the business rules decide still happens in Chatex.Core.
Check
dotnet build succeeds. The hub is mapped in the next chapter.