Українська
Сховище повідомлень
Крок 1. Одне сховище на відкритий чат
Навіщо. ChatsStore є singleton: список чатів один. А повідомлення належать одному відкритому чату. Тому сторінка розмови надає власний MessagesStore (providers: [MessagesStore] у її @Component, розділ 4): Angular створює екземпляр для сторінки й знищує його разом зі сторінкою, як scoped-сервіс в ASP.NET Core, у якого область дії – компонент. Клас позначено простим @Injectable(), без providedIn: 'root'.
Правила сховища:
- Повідомлення зберігаються від найстаріших до найновіших, у порядку на екрані, хоча API повертає сторінки від найновіших (тема 11).
- Повідомлення об’єднуються за ідентифікатором. Те саме повідомлення може надійти двічі – як відповідь на
POSTі (з теми 20) як подія хаба – а з’явитися має один раз. - Надсилання оптимістичне. Повідомлення з’являється одразу зі спінером (pending) і тимчасовим ідентифікатором; коли сервер відповідає, його копія замінює тимчасову. Якщо надсилання не вдалося, повідомлення лишається на екрані як failed з кнопками «Retry» і «Delete».
- Запізнілі відповіді відкидаються. Якщо користувач перемкнув чат, поки сторінка завантажувалась, відповідь для старого чату не повинна потрапити в новий.
Що зробити. Створіть сховище. Рядки, що застосовують події хаба й надолужують пропущене після перепідключення, з’являться в темі 20; до того один рядок імпорту коротший (жовтий).
ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { AttachmentDto, MessageDto, compareIds } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { ChatsStore } from './chats.store';
/** A message on screen. Messages being sent have `localState` and a temporary id. */
export type ChatMessage = MessageDto & { localState?: 'pending' | 'failed' };
export const PAGE_SIZE = 50;
let localIds = 0;
/**
* The open chat's messages, oldest first. History is keyset paged (`before=` for older pages,
* `after=` to fill the gap after a reconnect), and hub events are merged in by id so nothing shows
* twice. Provided by the conversation page, so each open chat gets its own instance state.
*/
@Injectable()
export class MessagesStore {
private readonly api = inject(MessagesApi);
private readonly chatsApi = inject(ChatsApi);
private readonly chats = inject(ChatsStore);
private readonly auth = inject(AuthService);
private olderCursor: string | null = null;
/** Bumped on every chat switch so late responses for the previous chat are dropped. */
private generation = 0;
private lastMarkedRead: string | null = null;
readonly chatId = signal<string | null>(null);
readonly messages = signal<ChatMessage[]>([]);
readonly loading = signal(false);
readonly loadingOlder = signal(false);
readonly hasOlder = signal(false);
readonly error = signal<unknown>(null);
/** Read positions of other members, from live MessagesRead events. */
readonly readBy = signal<Readonly<Record<string, string>>>({});
readonly byId = computed(() => new Map(this.messages().map((m) => [m.id, m])));
/** The newest message the server knows about (not a pending one). */
readonly lastConfirmed = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState) return list[i];
}
return null;
});
/** The newest message that can be a read position (the server rejects deleted ones). */
readonly lastReadable = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState && !list[i].isDeleted) return list[i];
}
return null;
});
/** The newest message any other member has read. */
readonly peerReadUpTo = computed(() => {
const ids = Object.values(this.readBy());
return ids.length ? ids.reduce((max, id) => (id > max ? id : max)) : null;
});
async open(chatId: string): Promise<void> {
this.generation++;
this.chatId.set(chatId);
this.messages.set([]);
this.readBy.set({});
this.olderCursor = null;
this.hasOlder.set(false);
this.lastMarkedRead = null;
this.error.set(null);
await this.loadInitial();
}
async loadInitial(): Promise<void> {
const chatId = this.chatId();
if (!chatId) {
return;
}
const generation = this.generation;
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list(chatId, { limit: PAGE_SIZE }));
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} catch (error) {
if (generation === this.generation) {
this.error.set(error);
}
} finally {
if (generation === this.generation) {
this.loading.set(false);
}
}
}
async loadOlder(): Promise<void> {
const chatId = this.chatId();
if (!chatId || !this.olderCursor || this.loadingOlder()) {
return;
}
const generation = this.generation;
this.loadingOlder.set(true);
try {
const page = await firstValueFrom(
this.api.list(chatId, { before: this.olderCursor, limit: PAGE_SIZE }),
);
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} finally {
if (generation === this.generation) {
this.loadingOlder.set(false);
}
}
}
/** Sends a message, showing it at once as pending. */
async send(body: string, attachments: AttachmentDto[], replyToMessageId?: string | null) {
const chatId = this.chatId();
const me = this.auth.user();
if (!chatId || !me) {
return;
}
const localId = `local-${++localIds}`;
const pending: ChatMessage = {
id: localId,
chatId,
sender: {
id: me.id,
userName: me.userName,
displayName: me.displayName,
hasAvatar: me.hasAvatar,
},
body,
replyToMessageId: replyToMessageId ?? null,
createdAt: new Date().toISOString(),
isDeleted: false,
attachments,
localState: 'pending',
};
this.messages.update((list) => [...list, pending]);
await this.deliver(pending);
}
/** Sends a failed message again. */
async retry(localId: string): Promise<void> {
const message = this.byId().get(localId);
if (message?.localState === 'failed') {
this.replace(localId, { ...message, localState: 'pending' });
await this.deliver(message);
}
}
discard(localId: string): void {
this.messages.update((list) => list.filter((m) => m.id !== localId));
}
async edit(messageId: string, body: string): Promise<void> {
const updated = await firstValueFrom(this.api.edit(messageId, body));
this.upsert(updated);
}
async delete(messageId: string): Promise<void> {
await firstValueFrom(this.api.delete(messageId));
this.markDeleted(messageId);
}
/** Moves the read position to the newest message (once per message). */
async markRead(): Promise<void> {
const chatId = this.chatId();
const last = this.lastReadable();
if (!chatId || !last || last.id === this.lastMarkedRead) {
return;
}
this.lastMarkedRead = last.id;
this.chats.markReadLocally(chatId);
try {
await firstValueFrom(this.chatsApi.markRead(chatId, last.id));
} catch {
this.lastMarkedRead = null;
}
}
private async deliver(pending: ChatMessage): Promise<void> {
const generation = this.generation;
try {
const sent = await firstValueFrom(
this.api.send(pending.chatId, {
body: pending.body || null,
replyToMessageId: pending.replyToMessageId,
attachmentIds: pending.attachments.map((a) => a.id),
}),
);
if (generation !== this.generation) {
return;
}
// The hub event may have arrived first; either way keep exactly one copy.
this.messages.update((list) =>
merge(
list.filter((m) => m.id !== pending.id),
[sent],
),
);
this.chats.noteOwnMessage(sent);
} catch (error) {
if (generation === this.generation) {
this.replace(pending.id, { ...pending, localState: 'failed' });
}
throw error;
}
}
private upsert(message: MessageDto): void {
this.messages.update((list) => merge(list, [message]));
}
private replace(id: string, message: ChatMessage): void {
this.messages.update((list) => list.map((m) => (m.id === id ? message : m)));
}
private markDeleted(messageId: string): void {
this.messages.update((list) =>
list.map((m) =>
m.id === messageId ? { ...m, isDeleted: true, body: null, attachments: [] } : m,
),
);
}
}
/**
* Merges server messages into the list: replaces ones with the same id, keeps confirmed messages
* ordered by id, and keeps pending messages at the end.
*/
export function merge(current: ChatMessage[], incoming: MessageDto[]): ChatMessage[] {
if (!incoming.length) {
return current;
}
const confirmed = new Map(current.filter((m) => !m.localState).map((m) => [m.id, m]));
for (const message of incoming) {
confirmed.set(message.id, message);
}
const pending = current.filter((m) => m.localState);
return [...[...confirmed.values()].sort((a, b) => compareIds(a.id, b.id)), ...pending];
}ChatMessage– цеMessageDtoз необов’язковимlocalState: 'pending' | 'failed'. Очікувані повідомлення мають ідентифікатори на кшталтlocal-1, що ніколи не збігаються з UUID сервера.byId,lastConfirmed,lastReadable,peerReadUpTo– обчислювані подання (computed): таблиця пошуку, найновіше повідомлення, про яке знає сервер, найновіше повідомлення, яке може бути позицією прочитання (API відхиляє видалені), і те, до якого місця дочитали інші учасники.readByлишається порожнім, доки тема 20 не заповнить його з подійMessagesRead.generationзростає під кожнимopen(). Кожен асинхронний метод запам’ятовує покоління на початку й ігнорує свій результат, якщо покоління тим часом змінилося – простий і явний спосіб скасування.open(chatId)скидає стан і завантажує найновішу сторінку;loadOlder()завантажує сторінкуbeforeнайстарішого курсору. Обидва методи розвертають сторінку й об’єднують її з наявними повідомленнями.send(body, attachments, replyToMessageId)будує очікуване повідомлення з профілю поточного користувача, додає його в кінець і викликаєdeliver.deliverнадсилає запит; в разі успіху видаляє очікувану копію, об’єднує повідомлення сервера й кажеChatsStoreпідняти чат нагору (noteOwnMessage); в разі невдачі позначає повідомлення як failed і повторно викидає помилку, щоб викликач показав сповіщення (toast).retry(localId)надсилає невдале повідомлення ще раз;discardвидаляє його.editіdeleteчекають на сервер, а потім оновлюють список. Вони не оптимістичні: редагування чи видалення, які сервер відхилив (чуже повідомлення, чат, який користувач залишив), не повинні здаватися виконаними.markRead()надсилає найновіше повідомлення, яке можна прочитати, як позицію прочитання, але лише один раз для кожного повідомлення (lastMarkedRead), і одразу прибирає значок непрочитаного в списку (markReadLocally). Якщо запит не вдався, наступний виклик спробує знову.merge(current, incoming)– експортована чиста функція: підтверджені повідомлення потрапляють уMapза ідентифікатором (тож новіша копія замінює старішу), сортуються за ідентифікатором – ідентифікатори UUIDv7 сортуються за часом – а очікувані лишаються в кінці в порядку надсилання.
Оптимістичні оновлення
Оптимістичний інтерфейс показує очікуваний результат до підтвердження сервером, бо сервер майже завжди підтверджує. Завдяки цьому месенджер відчувається миттєвим навіть у повільній мережі. Ціна – шлях збою: клієнт мусить уміти показати «цього не сталося» й запропонувати повторити. Chatex надсилає повідомлення оптимістично – там збій легко показати біля повідомлення, – а редагує й видаляє песимістично, бо мовчазний відкат збивав би з пантелику.
Крок 2. Тестування сховища
Навіщо. У сховища багато шляхів – посторінкове завантаження, надсилання, збої, повторні спроби, запізнілі відповіді, позиції прочитання, – і кожен легко зламати під час рефакторингу. Тести замінюють API та ChatsStore імітаціями (mock) і керують сховищем безпосередньо.
Що зробити. Створіть специфікацію. Тести подій хаба й перепідключень додадуться до неї в темі 20 разом із довшим рядком імпорту (жовтий).
ts
import { TestBed } from '@angular/core/testing';
import { Subject, of, throwError } from 'rxjs';
import { BOB, ME, fakeAuth, message, messageId } from '../../testing/fakes';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { MessageDto, PageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { ChatsStore } from './chats.store';
import { MessagesStore, merge } from './messages.store';
describe('MessagesStore', () => {
let store: MessagesStore;
let api: {
list: ReturnType<typeof vi.fn>;
send: ReturnType<typeof vi.fn>;
edit: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
};
let chats: {
markReadLocally: ReturnType<typeof vi.fn>;
noteOwnMessage: ReturnType<typeof vi.fn>;
};
let chatsApi: { markRead: ReturnType<typeof vi.fn> };
const page = (items: MessageDto[], nextCursor: string | null = null): PageDto<MessageDto> => ({
items,
nextCursor,
});
const ids = () => store.messages().map((m) => m.id);
beforeEach(() => {
api = { list: vi.fn(), send: vi.fn(), edit: vi.fn(), delete: vi.fn() };
chats = { markReadLocally: vi.fn(), noteOwnMessage: vi.fn() };
chatsApi = { markRead: vi.fn(() => of(undefined)) };
TestBed.configureTestingModule({
providers: [
MessagesStore,
{ provide: MessagesApi, useValue: api },
{ provide: ChatsApi, useValue: chatsApi },
{ provide: ChatsStore, useValue: chats },
{ provide: AuthService, useValue: fakeAuth() },
],
});
store = TestBed.inject(MessagesStore);
});
async function openWith(newestFirst: MessageDto[], cursor: string | null = null) {
api.list.mockReturnValueOnce(of(page(newestFirst, cursor)));
await store.open('chat-1');
}
it('shows the newest page oldest first', async () => {
await openWith([message(3), message(2), message(1)], 'cursor-1');
expect(api.list).toHaveBeenCalledWith('chat-1', { limit: 50 });
expect(ids()).toEqual([messageId(1), messageId(2), messageId(3)]);
expect(store.hasOlder()).toBe(true);
});
it('prepends older pages using the cursor', async () => {
await openWith([message(4), message(3)], 'cursor-1');
api.list.mockReturnValueOnce(of(page([message(2), message(1)])));
await store.loadOlder();
expect(api.list).toHaveBeenLastCalledWith('chat-1', { before: 'cursor-1', limit: 50 });
expect(ids()).toEqual([1, 2, 3, 4].map(messageId));
expect(store.hasOlder()).toBe(false);
});
it('shows a sent message at once and swaps in the server copy', async () => {
await openWith([message(1)]);
const response = new Subject<MessageDto>();
api.send.mockReturnValueOnce(response);
const sending = store.send('hello', []);
expect(store.messages().at(-1)).toMatchObject({ body: 'hello', localState: 'pending' });
const sent = message(2, {
body: 'hello',
sender: { ...BOB, id: ME.id, displayName: ME.displayName },
});
response.next(sent);
response.complete();
await sending;
expect(ids()).toEqual([messageId(1), messageId(2)]);
expect(store.messages().some((m) => m.localState)).toBe(false);
expect(chats.noteOwnMessage).toHaveBeenCalledWith(sent);
});
it('marks a message failed when sending fails, and can retry it', async () => {
await openWith([]);
api.send.mockReturnValueOnce(throwError(() => new Error('offline')));
await expect(store.send('hi', [])).rejects.toThrow('offline');
const failed = store.messages()[0];
expect(failed.localState).toBe('failed');
api.send.mockReturnValueOnce(of(message(5, { body: 'hi' })));
await store.retry(failed.id);
expect(ids()).toEqual([messageId(5)]);
});
it('marks the newest message read once', async () => {
await openWith([message(2), message(1)]);
await store.markRead();
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledTimes(1);
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(2));
expect(chats.markReadLocally).toHaveBeenCalledWith('chat-1');
});
it('never uses a deleted message as the read position', async () => {
await openWith([message(2, { isDeleted: true, body: null }), message(1)]);
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(1));
});
it('drops responses for a chat that is no longer open', async () => {
const slow = new Subject<PageDto<MessageDto>>();
api.list.mockReturnValueOnce(slow);
const first = store.open('chat-1');
api.list.mockReturnValueOnce(of(page([message(7, { chatId: 'chat-2' })])));
await store.open('chat-2');
slow.next(page([message(1)]));
slow.complete();
await first;
expect(ids()).toEqual([messageId(7)]);
});
});
describe('merge', () => {
it('orders by id and keeps pending messages last', () => {
const pending = { ...message(0), id: 'local-1', localState: 'pending' as const };
const merged = merge([message(3), pending], [message(1), message(3, { body: 'new' })]);
expect(merged.map((m) => m.id)).toEqual([messageId(1), messageId(3), 'local-1']);
expect(merged[1].body).toBe('new');
});
});providers: [MessagesStore, …]реєструє саме сховище, бо воно не надається в корені.api.list.mockReturnValueOnce(of(page))відповідає лише на наступний виклик, тож тест може задати послідовність сторінок.- «shows a sent message at once» використовує
Subjectяк HTTP-відповідь: тест перевіряє стан очікування до відповіді сервера, а потім подає відповідь черезnextіcomplete. - «marks a message failed» повертає
throwError(...), очікує, щоsendвідхилиться, а потім успішно повторює спробу. - «drops responses for a chat that is no longer open» відкриває чат 1 з повільною відповіддю, відкриває чат 2 і лише потім дозволяє відповіді чату 1 надійти: сховище має показувати лише повідомлення чату 2.
mergeтестується окремо, як чиста функція.
Перевірка
powershell
npm test -- --watch=false --include src/app/state/messages.store.spec.ts Test Files 1 passed (1)
Tests 8 passed (8)