English
The hub contract and connections
Step 1. SignalR in short
Why. HTTP is request–response: the browser asks, the server answers. A messenger needs the opposite direction too — the server must tell Bob about Alice's message without Bob asking. ASP.NET Core SignalR keeps one connection per browser tab open (a WebSocket, or a fallback transport) and lets the server call methods on clients and clients call methods on the server. The C# course explains the basics in SignalR: hubs, Clients, groups, the .NET and JavaScript clients.
Chatex uses three ideas of SignalR:
- A hub at
/hubs/chat— the endpoint clients connect to. - Groups — named sets of connections. Each chat has a group
chat:{id}; every connection of every member joins the groups of the user's chats (Fig. 14.2). An event for a chat goes to its group only, so outsiders never receive it. - A strongly typed hub
Hub<IChatClient>— the events are methods of an interface, so the compiler checks their names and arguments.
Fig. 14.2. Every connection joins the group of each chat of its user
Step 2. What clients receive
Why. The events are a contract with the Angular client (topic 20), which subscribes to them by name. An interface makes the contract explicit and checked.
Do. Create the folder Hubs:
cs
using Chatex.Core.Messages;
namespace Chatex.Api.Hubs;
/// <summary>
/// Events the server pushes to clients of <see cref="ChatHub"/>. Chat events go to the group <c>chat:{chatId}</c>,
/// so only current members receive them. The frontend is coded against these names and arguments.
/// </summary>
public interface IChatClient
{
Task MessageCreated(MessageDto message);
Task MessageUpdated(MessageDto message);
Task MessageDeleted(Guid chatId, Guid messageId);
/// <summary>A member's read position moved forward. Not sent for channels.</summary>
Task MessagesRead(Guid chatId, Guid userId, Guid lastReadMessageId);
/// <summary>Users joined or were added, including everyone in a newly created chat.</summary>
Task MembersAdded(Guid chatId, Guid[] userIds);
/// <summary>A user left or was removed. The removed user receives it too, then stops getting the chat's events.</summary>
Task MemberRemoved(Guid chatId, Guid userId);
/// <summary>Title, description, handle, avatar or member roles changed; refetch the chat.</summary>
Task ChatUpdated(Guid chatId);
Task ChatDeleted(Guid chatId);
/// <summary>Someone else in the chat is typing. Expire the indicator after about 5 seconds.</summary>
Task Typing(Guid chatId, Guid userId);
/// <summary>A user who shares a chat with you opened their first connection.</summary>
Task UserOnline(Guid userId);
/// <summary>A user who shares a chat with you closed their last connection and did not return within the grace period.</summary>
Task UserOffline(Guid userId, DateTimeOffset lastSeenAt);
}Eight events mirror the eight methods of IChatNotifier (topic 10); three more belong to the hub itself: Typing, UserOnline, UserOffline. The comments tell the client what to do with each — for example, expire a typing indicator after about five seconds.
Step 3. Who is online
Why. A user is online while they have at least one open connection — a laptop tab and a phone count separately, and closing one of them must not make the user look offline. The server needs, per user, the set of their connection ids:
- to announce "online" on the first connection and "offline" after the last one closes;
- to put a user's open connections into a new chat's group at once when the user is added (next chapter).
Chatex runs as one process, so this set can live in memory. With several servers, the connections would be spread over them, and a shared store or a SignalR backplane (such as Redis) would be needed — a deliberate simplification that the README of Chatex states ("in-memory presence, one process, no backplane").
Do.
cs
using System.Collections.Concurrent;
namespace Chatex.Api.Hubs;
/// <summary>
/// The open hub connections of each user, in memory. One process, so no backplane is needed.
/// A user is online while they have at least one connection (tabs and devices count separately).
/// </summary>
internal sealed class PresenceTracker
{
private readonly ConcurrentDictionary<Guid, HashSet<string>> _connections = new();
/// <summary>Adds the connection; returns true when it is the user's first one.</summary>
public bool Add(Guid userId, string connectionId)
{
while (true)
{
var set = _connections.GetOrAdd(userId, _ => []);
lock (set)
{
// Remove may have emptied and dropped this set after GetOrAdd returned it; then retry with a fresh one.
if (_connections.TryGetValue(userId, out var current) && ReferenceEquals(current, set))
{
set.Add(connectionId);
return set.Count == 1;
}
}
}
}
/// <summary>Removes the connection; returns true when it was the user's last one.</summary>
public bool Remove(Guid userId, string connectionId)
{
if (!_connections.TryGetValue(userId, out var set))
{
return false;
}
lock (set)
{
if (!set.Remove(connectionId) || set.Count > 0)
{
return false;
}
_connections.TryRemove(new KeyValuePair<Guid, HashSet<string>>(userId, set));
return true;
}
}
public IReadOnlyList<string> GetConnections(Guid userId)
{
if (!_connections.TryGetValue(userId, out var set))
{
return [];
}
lock (set)
{
return [.. set];
}
}
public bool IsOnline(Guid userId)
{
if (!_connections.TryGetValue(userId, out var set))
{
return false;
}
lock (set)
{
return set.Count > 0;
}
}
}ConcurrentDictionary<Guid, HashSet<string>>: the dictionary is thread-safe, the sets are not, so every access to a set happens insidelock (set).- The retry loop in
Addhandles a race: betweenGetOrAddandlock, another thread may remove the user's last connection and drop the set from the dictionary. The checkReferenceEquals(current, set)sees that and retries with a fresh set. TryRemove(KeyValuePair)removes the entry only if it still holds this set — a newer set from a concurrentAddis left alone.[.. set]copies the set under the lock, so callers get a snapshot they can enumerate safely.
Step 4. The user id of a connection
Why. SignalR identifies users by Context.UserIdentifier, which by default comes from the NameIdentifier claim. Topic 12 kept the original claim names of the token (MapInboundClaims = false), so the user id is in sub. A small provider tells SignalR where to look.
Do.
cs
using Microsoft.AspNetCore.SignalR;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Chatex.Api.Hubs;
/// <summary>
/// Makes <c>Context.UserIdentifier</c> and <c>Clients.User(id)</c> use the access token's <c>sub</c> claim.
/// The default provider reads NameIdentifier, which is absent because the JWT handler keeps the raw claim names.
/// </summary>
internal sealed class SubClaimUserIdProvider : IUserIdProvider
{
public string? GetUserId(HubConnectionContext connection) =>
connection.User?.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;
}Check
dotnet build succeeds.