English
The SignalR connection
Step 1. The connection's life cycle
Why. The hub of topic 14 sends eleven kinds of events to the groups of a user's chats. The client needs exactly one connection per signed-in browser tab — not one per page — that:
- starts when the user signs in and stops when they sign out;
- authenticates with the current access token, also when it reconnects an hour later;
- reconnects by itself after network failures, and keeps trying even when SignalR's own reconnect attempts are used up;
- tells the stores after a reconnect that they may have missed events.
@microsoft/signalr (topic 15) is the official client. HubConnectionBuilder creates a connection that negotiates the best transport — WebSockets, with Server-Sent Events and long polling as fall-backs — and calls the handlers registered with connection.on(name, handler) when the server invokes a client method.
Do. Create the service:
ts
import { Injectable, effect, inject, signal, untracked } from '@angular/core';
import {
HubConnection,
HubConnectionBuilder,
HubConnectionState,
LogLevel,
} from '@microsoft/signalr';
import { Subject } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { MessageDto } from '../api/models';
export type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
/** Server → client events of the /hubs/chat hub. */
export type HubEvent =
| { type: 'messageCreated'; message: MessageDto }
| { type: 'messageUpdated'; message: MessageDto }
| { type: 'messageDeleted'; chatId: string; messageId: string }
| { type: 'messagesRead'; chatId: string; userId: string; lastReadMessageId: string }
| { type: 'membersAdded'; chatId: string; userIds: string[] }
| { type: 'memberRemoved'; chatId: string; userId: string }
| { type: 'chatUpdated'; chatId: string }
| { type: 'chatDeleted'; chatId: string }
| { type: 'typing'; chatId: string; userId: string }
| { type: 'userOnline'; userId: string }
| { type: 'userOffline'; userId: string; lastSeenAt: string };
const TYPING_THROTTLE_MS = 3_000;
const RETRY_DELAYS_MS = [0, 2_000, 5_000, 10_000, 30_000];
/**
* The SignalR connection. It runs while the user is signed in, reconnects on its own, and after a
* reconnect emits `connected` with `reconnected: true` so stores can fetch what they missed.
*/
@Injectable({ providedIn: 'root' })
export class RealtimeService {
private readonly auth = inject(AuthService);
private connection: HubConnection | null = null;
private retryTimer: ReturnType<typeof setTimeout> | undefined;
private attempt = 0;
private everConnected = false;
private readonly lastTypingSent = new Map<string, number>();
readonly state = signal<ConnectionState>('disconnected');
readonly events = new Subject<HubEvent>();
/** Fires on every (re)connect; `reconnected` is true when there may be a gap to fill. */
readonly connected = new Subject<{ reconnected: boolean }>();
constructor() {
effect(() => {
const signedIn = this.auth.isAuthenticated();
untracked(() => (signedIn ? this.start() : void this.stop()));
});
}
/** Tells the chat's other members that the user is typing, at most once every 3 seconds. */
sendTyping(chatId: string): void {
const now = Date.now();
if (now - (this.lastTypingSent.get(chatId) ?? 0) < TYPING_THROTTLE_MS || !this.isConnected()) {
return;
}
this.lastTypingSent.set(chatId, now);
this.connection!.invoke('Typing', chatId).catch(() => undefined);
}
/** Which of these users are online right now (empty while disconnected). */
async getOnlineUsers(userIds: string[]): Promise<string[]> {
if (!userIds.length || !this.isConnected()) {
return [];
}
try {
return await this.connection!.invoke<string[]>('GetOnlineUsers', userIds);
} catch {
return [];
}
}
private isConnected(): boolean {
return this.connection?.state === HubConnectionState.Connected;
}
private start(): void {
if (this.connection) {
return;
}
const connection = new HubConnectionBuilder()
.withUrl('/hubs/chat', {
accessTokenFactory: async () => (await this.auth.getValidToken()) ?? '',
})
.withAutomaticReconnect([0, 2_000, 5_000, 10_000, 20_000, 30_000])
.configureLogging(LogLevel.Warning)
.build();
const emit = (event: HubEvent) => this.events.next(event);
connection.on('MessageCreated', (message: MessageDto) =>
emit({ type: 'messageCreated', message }),
);
connection.on('MessageUpdated', (message: MessageDto) =>
emit({ type: 'messageUpdated', message }),
);
connection.on('MessageDeleted', (chatId: string, messageId: string) =>
emit({ type: 'messageDeleted', chatId, messageId }),
);
connection.on('MessagesRead', (chatId: string, userId: string, lastReadMessageId: string) =>
emit({ type: 'messagesRead', chatId, userId, lastReadMessageId }),
);
connection.on('MembersAdded', (chatId: string, userIds: string[]) =>
emit({ type: 'membersAdded', chatId, userIds }),
);
connection.on('MemberRemoved', (chatId: string, userId: string) =>
emit({ type: 'memberRemoved', chatId, userId }),
);
connection.on('ChatUpdated', (chatId: string) => emit({ type: 'chatUpdated', chatId }));
connection.on('ChatDeleted', (chatId: string) => emit({ type: 'chatDeleted', chatId }));
connection.on('Typing', (chatId: string, userId: string) =>
emit({ type: 'typing', chatId, userId }),
);
connection.on('UserOnline', (userId: string) => emit({ type: 'userOnline', userId }));
connection.on('UserOffline', (userId: string, lastSeenAt: string) =>
emit({ type: 'userOffline', userId, lastSeenAt }),
);
connection.onreconnecting(() => this.state.set('reconnecting'));
connection.onreconnected(() => {
this.state.set('connected');
this.connected.next({ reconnected: true });
});
connection.onclose(() => {
// Automatic reconnect gave up (or the server is down): keep trying while signed in.
if (this.connection === connection) {
this.state.set('disconnected');
this.scheduleRetry(connection);
}
});
this.connection = connection;
this.attempt = 0;
void this.connect(connection);
}
private async connect(connection: HubConnection): Promise<void> {
if (this.connection !== connection) {
return;
}
this.state.set(this.everConnected ? 'reconnecting' : 'connecting');
try {
await connection.start();
if (this.connection !== connection) {
return;
}
const reconnected = this.everConnected;
this.everConnected = true;
this.attempt = 0;
this.state.set('connected');
this.connected.next({ reconnected });
} catch {
if (this.connection === connection) {
this.state.set('disconnected');
this.scheduleRetry(connection);
}
}
}
private scheduleRetry(connection: HubConnection): void {
clearTimeout(this.retryTimer);
const delay = RETRY_DELAYS_MS[Math.min(++this.attempt, RETRY_DELAYS_MS.length - 1)];
this.retryTimer = setTimeout(() => void this.connect(connection), delay);
}
private async stop(): Promise<void> {
clearTimeout(this.retryTimer);
const connection = this.connection;
this.connection = null;
this.everConnected = false;
this.lastTypingSent.clear();
this.state.set('disconnected');
await connection?.stop().catch(() => undefined);
}
}The connection:
effectonisAuthenticatedstarts the connection after sign-in and stops it after sign-out.untrackedkeepsstartandstop— which set thestatesignal — out of the effect's dependencies.accessTokenFactoryis called by SignalR for every (re)connect; it returnsgetValidToken()of topic 16, which refreshes a token that is about to expire. Browsers cannot send headers with WebSocket requests, so SignalR puts the token into theaccess_tokenquery parameter, which the API accepts on/hubspaths only (topic 14).withAutomaticReconnect([0, 2_000, 5_000, 10_000, 20_000, 30_000])retries after a lost connection with these delays. While it does,onreconnectingsets the state to'reconnecting';onreconnectedsets'connected'and emitsconnectedwithreconnected: true.onclosefires when the automatic attempts are exhausted (or the first connection never came up). The service then keeps retrying with its own schedule,RETRY_DELAYS_MS, as long as the user is signed in. The checkthis.connection === connectionignores callbacks of a connection that has already been replaced or stopped.connectemitsconnectedwithreconnected: trueif the service has ever been connected before in this session. A first connection is not a gap; every later one is.configureLogging(LogLevel.Warning)keeps the browser console quiet unless something goes wrong.
The events:
HubEventis a discriminated union: one object type per hub method, each with a literaltypeand its own fields — the TypeScript mirror ofIChatClient(topic 14). The service registers a handler for each method name and turns its arguments into oneHubEvent, published on theeventsSubject. Consumers subscribe once andswitchonevent.type; inside eachcase, TypeScript knows exactly which fields exist, and a mistyped field is a compile error.connectedis a second Subject for the "(re)connected" signal, andstatea signal for the screen: the shell shows a banner while it is notconnected(chapter 3).
The client methods:
sendTyping(chatId)invokes the hub'sTypingat most once every three seconds per chat — the throttling thatDocs/Realtime.mdasks for — and only while connected. Errors (for example after leaving the chat) are ignored.getOnlineUsers(userIds)invokesGetOnlineUsersand returns the ids that are online, or an empty list while disconnected.
Why a Subject and not a signal for events
A signal holds a current value; if two events arrive in the same tick, a reader sees only the last one. Hub events are things that happen — every one of them must be applied. An RxJS Subject delivers every value to every subscriber, synchronously, in order. Signals are then the result: the stores apply the events to their state signals, and the screen follows.
Handshake before the groups
The server adds a connection to the chat groups in OnConnectedAsync, which runs after the handshake (topic 14). Events sent in that short window — and everything sent while the client was offline — never reach this connection. That is why the client must not rely on events alone: after every reconnect it fetches what it missed over HTTP (next chapter).
Step 2. A fake for the tests
Why. The stores' tests must push events without a server. A fake with the same public shape — the state signal, the events and connected Subjects, mock functions for the two methods — lets a test call realtime.events.next({ type: 'messageCreated', … }) and watch the store react.
Do. Complete the shared fakes (new lines in green). The file is now final:
ts
import { signal } from '@angular/core';
import { Subject } from 'rxjs';
import { MessageDto, MyProfileDto, UserSummaryDto } from '../app/core/api/models';
import { ConnectionState, HubEvent } from '../app/core/realtime/realtime.service';
export const ME: MyProfileDto = {
id: '00000000-0000-7000-8000-00000000000a',
userName: 'alice',
email: '[email protected]',
displayName: 'Alice',
bio: null,
hasAvatar: false,
createdAt: '2026-11-01T10:00:00Z',
};
export const BOB: UserSummaryDto = {
id: '00000000-0000-7000-8000-00000000000b',
userName: 'bob',
displayName: 'Bob',
hasAvatar: false,
};
/** A stand-in for RealtimeService: tests push hub events through `events`. */
export function fakeRealtime() {
return {
state: signal<ConnectionState>('connected'),
events: new Subject<HubEvent>(),
connected: new Subject<{ reconnected: boolean }>(),
sendTyping: vi.fn(),
getOnlineUsers: vi.fn(async () => [] as string[]),
};
}
export function fakeAuth(user: MyProfileDto | null = ME) {
return {
user: signal(user),
sessionEpoch: signal(0),
isAuthenticated: signal(!!user),
};
}
/** Message ids sort like the server's UUIDv7 ids: by the number given. */
export function messageId(n: number): string {
return `00000000-0000-7000-8000-${n.toString().padStart(12, '0')}`;
}
export function message(n: number, overrides: Partial<MessageDto> = {}): MessageDto {
return {
id: messageId(n),
chatId: 'chat-1',
sender: BOB,
body: `message ${n}`,
replyToMessageId: null,
createdAt: new Date(Date.UTC(2026, 10, 10, 12, 0, n)).toISOString(),
editedAt: null,
isDeleted: false,
attachments: [],
...overrides,
};
}
/** Lets pending promise callbacks (firstValueFrom, async/await) run. */
export function settle(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}vi.fn(async () => [] as string[]) is a mock whose calls return a promise of an empty list; the type assertion tells TypeScript the element type of the empty array.
Check
npm run build and npm test -- --watch=false succeed with 38 tests. Nothing injects RealtimeService yet, so no connection is opened; the next chapter changes that.