feat(m8): SSE hub + realtime chat with mentions, tests, e2e
- SseHub (project-scoped client mgmt + broadcast, implements SseBroadcaster) with SSE-formatted payload; singleton getSseHub - ChatRepository (message CRUD, soft-delete, search, pagination, project isolation) + ChatService (membership permission, send/edit/delete, @email mention -> mention notification, SSE broadcast of created/updated/deleted) - SSE stream endpoint (ReadableStream + heartbeat + abort cleanup, membership) - Chat message API routes (history/send/edit/delete) - ChatWindow client (EventSource auto-reconnect, history fetch, realtime append/update/delete), chat page, ProjectNav チャット link - SseEvent type now carries ChatMessage for chat events - Unit (SseHub, ChatRepository, ChatService) + integration chat-sse-broadcast + e2e chat-sse (two contexts realtime)
This commit is contained in:
68
tests/e2e/chat-sse.spec.ts
Normal file
68
tests/e2e/chat-sse.spec.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
function unique(prefix: string): string {
|
||||
return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1_000_000)}`;
|
||||
}
|
||||
|
||||
async function registerAndLogin(page: Page, email: string, name: string) {
|
||||
await page.goto('/login');
|
||||
await page.getByRole('button', { name: '新規登録はこちら' }).click();
|
||||
await page.getByLabel('表示名').fill(name);
|
||||
await page.getByLabel('メールアドレス').fill(email);
|
||||
await page.getByLabel('パスワード').fill('password123');
|
||||
await page.getByRole('button', { name: '登録する' }).click();
|
||||
await expect(page).toHaveURL(/\/dashboard/);
|
||||
}
|
||||
|
||||
test.describe('chat (SSE realtime)', () => {
|
||||
test('a message sent in one context is received in another via SSE', async ({
|
||||
browser,
|
||||
}) => {
|
||||
const ownerEmail = unique('owner') + '@example.com';
|
||||
const memberEmail = unique('member') + '@example.com';
|
||||
|
||||
// メンバーを先に登録(UIで作成+ログイン)
|
||||
const memberContext = await browser.newContext();
|
||||
const memberPage = await memberContext.newPage();
|
||||
await registerAndLogin(memberPage, memberEmail, 'Member');
|
||||
|
||||
// オーナー登録+プロジェクト作成
|
||||
const ownerContext = await browser.newContext();
|
||||
const ownerPage = await ownerContext.newPage();
|
||||
await registerAndLogin(ownerPage, ownerEmail, 'Owner');
|
||||
await ownerPage.getByLabel('プロジェクト名').fill(unique('Proj'));
|
||||
await ownerPage.getByRole('button', { name: '新規プロジェクト' }).click();
|
||||
await expect(ownerPage).toHaveURL(/\/projects\/\d+$/);
|
||||
const projectId = Number(ownerPage.url().match(/\/projects\/(\d+)/)![1]);
|
||||
|
||||
// メンバーをプロジェクトに追加(オーナーセッション)
|
||||
const addRes = await ownerPage.request.post(
|
||||
`/api/projects/${projectId}/members`,
|
||||
{ data: { email: memberEmail, role: 'member' } }
|
||||
);
|
||||
expect(addRes.ok()).toBeTruthy();
|
||||
|
||||
// 両者チャット画面を開く(SSE接続)
|
||||
await ownerPage.goto(`/projects/${projectId}/chat`);
|
||||
await memberPage.goto(`/projects/${projectId}/chat`);
|
||||
await expect(ownerPage.getByTestId('chat-form')).toBeVisible();
|
||||
await expect(memberPage.getByTestId('chat-form')).toBeVisible();
|
||||
|
||||
// オーナーがメッセージ送信
|
||||
const text = unique('hello');
|
||||
await ownerPage.getByTestId('chat-input').fill(text);
|
||||
await ownerPage.getByTestId('chat-send').click();
|
||||
|
||||
// メンバー側にSSE経由でリアルタイム表示される
|
||||
await expect(
|
||||
memberPage.getByTestId('chat-messages').getByText(text)
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
// オーナー自身にも表示される
|
||||
await expect(
|
||||
ownerPage.getByTestId('chat-messages').getByText(text)
|
||||
).toBeVisible();
|
||||
|
||||
await ownerContext.close();
|
||||
await memberContext.close();
|
||||
});
|
||||
});
|
||||
92
tests/integration/chat-sse-broadcast.test.ts
Normal file
92
tests/integration/chat-sse-broadcast.test.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { createMigratedTestDb } from '@/tests/helpers/db';
|
||||
import type { SqliteDatabase } from '@/lib/db/sqlite';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { ProjectRepository } from '@/repositories/ProjectRepository';
|
||||
import { ProjectMemberRepository } from '@/repositories/ProjectMemberRepository';
|
||||
import { ChatRepository } from '@/repositories/ChatRepository';
|
||||
import { NotificationRepository } from '@/repositories/NotificationRepository';
|
||||
import { NotificationService } from '@/services/NotificationService';
|
||||
import { ChatService } from '@/services/ChatService';
|
||||
import { SseHub, type SseClient } from '@/lib/sse/hub';
|
||||
|
||||
describe('chat → SSE broadcast (integration)', () => {
|
||||
let db: SqliteDatabase;
|
||||
let service: ChatService;
|
||||
let hub: SseHub;
|
||||
let projectId: number;
|
||||
let authorId: number;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createMigratedTestDb();
|
||||
hub = new SseHub();
|
||||
const users = new UserRepository(db);
|
||||
authorId = users.create({
|
||||
name: 'A',
|
||||
email: 'a@example.com',
|
||||
passwordHash: 'h',
|
||||
}).id;
|
||||
projectId = new ProjectRepository(db).create({
|
||||
name: 'P',
|
||||
ownerId: authorId,
|
||||
}).id;
|
||||
const members = new ProjectMemberRepository(db);
|
||||
members.add(projectId, authorId, 'admin');
|
||||
service = new ChatService(
|
||||
new ChatRepository(db),
|
||||
members,
|
||||
users,
|
||||
new NotificationService(new NotificationRepository(db)),
|
||||
hub
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => db.close());
|
||||
|
||||
function subscribe(projectId: number): SseClient & { received: string[] } {
|
||||
const received: string[] = [];
|
||||
const client: SseClient & { received: string[] } = {
|
||||
received,
|
||||
enqueue: (c) => received.push(c),
|
||||
close: () => undefined,
|
||||
};
|
||||
hub.addClient(projectId, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
it('a subscribed client receives the created message event in SSE format', () => {
|
||||
const client = subscribe(projectId);
|
||||
|
||||
const message = service.sendMessage(authorId, projectId, 'hello realtime');
|
||||
|
||||
expect(client.received).toHaveLength(1);
|
||||
const raw = client.received[0];
|
||||
expect(raw).toMatch(/^data: .+\n\n$/);
|
||||
const parsed = JSON.parse(raw.replace(/^data: /, '').replace(/\n\n$/, ''));
|
||||
expect(parsed.type).toBe('chat.message.created');
|
||||
expect(parsed.data.message.id).toBe(message.id);
|
||||
expect(parsed.data.message.body).toBe('hello realtime');
|
||||
});
|
||||
|
||||
it('a client in another project does not receive the message', () => {
|
||||
const otherClient = subscribe(99999);
|
||||
|
||||
service.sendMessage(authorId, projectId, 'hello');
|
||||
|
||||
expect(otherClient.received).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('delete broadcasts a deleted event with the message id', () => {
|
||||
const client = subscribe(projectId);
|
||||
const message = service.sendMessage(authorId, projectId, 'to be deleted');
|
||||
client.received.length = 0;
|
||||
|
||||
service.deleteMessage(authorId, message.id);
|
||||
|
||||
const parsed = JSON.parse(
|
||||
client.received[0].replace(/^data: /, '').replace(/\n\n$/, '')
|
||||
);
|
||||
expect(parsed.type).toBe('chat.message.deleted');
|
||||
expect(parsed.data.id).toBe(message.id);
|
||||
});
|
||||
});
|
||||
92
tests/unit/lib/sse/hub.test.ts
Normal file
92
tests/unit/lib/sse/hub.test.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { SseHub, type SseClient } from '@/lib/sse/hub';
|
||||
|
||||
function makeClient(): SseClient & { received: string[] } {
|
||||
const received: string[] = [];
|
||||
return {
|
||||
received,
|
||||
enqueue: (chunk: string) => received.push(chunk),
|
||||
close: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
describe('SseHub', () => {
|
||||
let hub: SseHub;
|
||||
|
||||
beforeEach(() => {
|
||||
hub = new SseHub();
|
||||
});
|
||||
|
||||
it('adds and counts clients per project', () => {
|
||||
hub.addClient(1, makeClient());
|
||||
hub.addClient(1, makeClient());
|
||||
hub.addClient(2, makeClient());
|
||||
|
||||
expect(hub.getClientCount(1)).toBe(2);
|
||||
expect(hub.getClientCount(2)).toBe(1);
|
||||
expect(hub.getClientCount(999)).toBe(0);
|
||||
});
|
||||
|
||||
it('removes a client', () => {
|
||||
const c = makeClient();
|
||||
hub.addClient(1, c);
|
||||
hub.removeClient(1, c);
|
||||
expect(hub.getClientCount(1)).toBe(0);
|
||||
});
|
||||
|
||||
it('broadcasts only to clients of the target project', () => {
|
||||
const a1 = makeClient();
|
||||
const a2 = makeClient();
|
||||
const b1 = makeClient();
|
||||
hub.addClient(1, a1);
|
||||
hub.addClient(1, a2);
|
||||
hub.addClient(2, b1);
|
||||
|
||||
hub.broadcast(1, {
|
||||
type: 'chat.message.created',
|
||||
data: { projectId: 1, message: { id: 1 } as never },
|
||||
});
|
||||
|
||||
expect(a1.received).toHaveLength(1);
|
||||
expect(a2.received).toHaveLength(1);
|
||||
expect(b1.received).toHaveLength(0);
|
||||
expect(a1.received[0]).toContain('chat.message.created');
|
||||
});
|
||||
|
||||
it('broadcast payload is SSE formatted (data: ...\\n\\n)', () => {
|
||||
const c = makeClient();
|
||||
hub.addClient(1, c);
|
||||
hub.broadcast(1, {
|
||||
type: 'chat.message.deleted',
|
||||
data: { projectId: 1, id: 5 },
|
||||
});
|
||||
|
||||
expect(c.received[0]).toMatch(/^data: .+\n\n$/);
|
||||
const parsed = JSON.parse(
|
||||
c.received[0].replace(/^data: /, '').replace(/\n\n$/, '')
|
||||
);
|
||||
expect(parsed.type).toBe('chat.message.deleted');
|
||||
expect(parsed.data.id).toBe(5);
|
||||
});
|
||||
|
||||
it('does nothing when there are no clients for the project', () => {
|
||||
expect(() =>
|
||||
hub.broadcast(42, {
|
||||
type: 'note.updated',
|
||||
data: { projectId: 42 },
|
||||
})
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('removes a client that throws on enqueue', () => {
|
||||
const broken: SseClient = {
|
||||
enqueue: () => {
|
||||
throw new Error('disconnected');
|
||||
},
|
||||
close: () => undefined,
|
||||
};
|
||||
hub.addClient(1, broken);
|
||||
hub.broadcast(1, { type: 'note.updated', data: { projectId: 1 } });
|
||||
expect(hub.getClientCount(1)).toBe(0);
|
||||
});
|
||||
});
|
||||
85
tests/unit/repositories/ChatRepository.test.ts
Normal file
85
tests/unit/repositories/ChatRepository.test.ts
Normal file
@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { createMigratedTestDb } from '@/tests/helpers/db';
|
||||
import type { SqliteDatabase } from '@/lib/db/sqlite';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { ProjectRepository } from '@/repositories/ProjectRepository';
|
||||
import { ProjectMemberRepository } from '@/repositories/ProjectMemberRepository';
|
||||
import { ChatRepository } from '@/repositories/ChatRepository';
|
||||
|
||||
describe('ChatRepository', () => {
|
||||
let db: SqliteDatabase;
|
||||
let repo: ChatRepository;
|
||||
let projectId: number;
|
||||
let authorId: number;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createMigratedTestDb();
|
||||
repo = new ChatRepository(db);
|
||||
authorId = new UserRepository(db).create({
|
||||
name: 'A',
|
||||
email: 'a@example.com',
|
||||
passwordHash: 'h',
|
||||
}).id;
|
||||
projectId = new ProjectRepository(db).create({
|
||||
name: 'P',
|
||||
ownerId: authorId,
|
||||
}).id;
|
||||
new ProjectMemberRepository(db).add(projectId, authorId, 'admin');
|
||||
});
|
||||
|
||||
afterEach(() => db.close());
|
||||
|
||||
it('creates and finds a message', () => {
|
||||
const m = repo.create({ projectId, authorId, body: 'hello' });
|
||||
expect(repo.findMessageById(m.id)?.body).toBe('hello');
|
||||
});
|
||||
|
||||
it('lists messages newest first with total', () => {
|
||||
repo.create({ projectId, authorId, body: 'first' });
|
||||
repo.create({ projectId, authorId, body: 'second' });
|
||||
const { items, total } = repo.findMessages(projectId);
|
||||
expect(total).toBe(2);
|
||||
expect(items[0].body).toBe('second');
|
||||
});
|
||||
|
||||
it('excludes soft-deleted messages', () => {
|
||||
const m = repo.create({ projectId, authorId, body: 'x' });
|
||||
repo.delete(m.id);
|
||||
expect(repo.findMessageById(m.id)).toBeNull();
|
||||
expect(repo.findMessages(projectId).total).toBe(0);
|
||||
});
|
||||
|
||||
it('isolates messages by project', () => {
|
||||
repo.create({ projectId, authorId, body: 'mine' });
|
||||
const p2 = new ProjectRepository(db).create({
|
||||
name: 'P2',
|
||||
ownerId: authorId,
|
||||
}).id;
|
||||
repo.create({ projectId: p2, authorId, body: 'theirs' });
|
||||
expect(repo.findMessages(projectId).total).toBe(1);
|
||||
expect(repo.findMessages(p2).total).toBe(1);
|
||||
});
|
||||
|
||||
it('searches messages by body', () => {
|
||||
repo.create({ projectId, authorId, body: 'hello world' });
|
||||
repo.create({ projectId, authorId, body: 'goodbye' });
|
||||
expect(repo.findMessages(projectId, { search: 'hello' }).total).toBe(1);
|
||||
expect(repo.findMessages(projectId, { search: 'nope' }).total).toBe(0);
|
||||
});
|
||||
|
||||
it('paginates messages', () => {
|
||||
for (let i = 0; i < 5; i++)
|
||||
repo.create({ projectId, authorId, body: `m${i}` });
|
||||
expect(
|
||||
repo.findMessages(projectId, { page: 1, pageSize: 2 }).items
|
||||
).toHaveLength(2);
|
||||
expect(repo.findMessages(projectId, { page: 1, pageSize: 2 }).total).toBe(
|
||||
5
|
||||
);
|
||||
});
|
||||
|
||||
it('updates a message body', () => {
|
||||
const m = repo.create({ projectId, authorId, body: 'x' });
|
||||
expect(repo.update(m.id, 'edited')?.body).toBe('edited');
|
||||
});
|
||||
});
|
||||
138
tests/unit/services/ChatService.test.ts
Normal file
138
tests/unit/services/ChatService.test.ts
Normal file
@ -0,0 +1,138 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { createMigratedTestDb } from '@/tests/helpers/db';
|
||||
import type { SqliteDatabase } from '@/lib/db/sqlite';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { ProjectRepository } from '@/repositories/ProjectRepository';
|
||||
import { ProjectMemberRepository } from '@/repositories/ProjectMemberRepository';
|
||||
import { ChatRepository } from '@/repositories/ChatRepository';
|
||||
import { NotificationRepository } from '@/repositories/NotificationRepository';
|
||||
import { NotificationService } from '@/services/NotificationService';
|
||||
import { ChatService } from '@/services/ChatService';
|
||||
import { SseHub, type SseClient } from '@/lib/sse/hub';
|
||||
import { ForbiddenError, NotFoundError, ValidationError } from '@/lib/errors';
|
||||
|
||||
function makeClient(): SseClient & { received: string[] } {
|
||||
const received: string[] = [];
|
||||
return { received, enqueue: (c) => received.push(c), close: () => undefined };
|
||||
}
|
||||
|
||||
describe('ChatService', () => {
|
||||
let db: SqliteDatabase;
|
||||
let service: ChatService;
|
||||
let hub: SseHub;
|
||||
let projectId: number;
|
||||
let authorId: number;
|
||||
let memberId: number;
|
||||
let outsiderId: number;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createMigratedTestDb();
|
||||
hub = new SseHub();
|
||||
const users = new UserRepository(db);
|
||||
authorId = users.create({
|
||||
name: 'A',
|
||||
email: 'a@example.com',
|
||||
passwordHash: 'h',
|
||||
}).id;
|
||||
memberId = users.create({
|
||||
name: 'M',
|
||||
email: 'm@example.com',
|
||||
passwordHash: 'h',
|
||||
}).id;
|
||||
outsiderId = users.create({
|
||||
name: 'O',
|
||||
email: 'o@example.com',
|
||||
passwordHash: 'h',
|
||||
}).id;
|
||||
projectId = new ProjectRepository(db).create({
|
||||
name: 'P',
|
||||
ownerId: authorId,
|
||||
}).id;
|
||||
const members = new ProjectMemberRepository(db);
|
||||
members.add(projectId, authorId, 'admin');
|
||||
members.add(projectId, memberId, 'member');
|
||||
service = new ChatService(
|
||||
new ChatRepository(db),
|
||||
members,
|
||||
users,
|
||||
new NotificationService(new NotificationRepository(db)),
|
||||
hub
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => db.close());
|
||||
|
||||
it('sends a message and broadcasts chat.message.created', () => {
|
||||
const client = makeClient();
|
||||
hub.addClient(projectId, client);
|
||||
|
||||
const message = service.sendMessage(authorId, projectId, 'hello');
|
||||
|
||||
expect(message.body).toBe('hello');
|
||||
expect(client.received).toHaveLength(1);
|
||||
expect(client.received[0]).toContain('chat.message.created');
|
||||
});
|
||||
|
||||
it('forbids a non-member from sending', () => {
|
||||
expect(() => service.sendMessage(outsiderId, projectId, 'hi')).toThrow(
|
||||
ForbiddenError
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an empty message', () => {
|
||||
expect(() => service.sendMessage(authorId, projectId, ' ')).toThrow(
|
||||
ValidationError
|
||||
);
|
||||
});
|
||||
|
||||
it('notifies a mentioned project member (@email) but not the sender', () => {
|
||||
service.sendMessage(authorId, projectId, `hi @m@example.com`);
|
||||
|
||||
expect(new NotificationRepository(db).countUnreadByUser(memberId)).toBe(1);
|
||||
expect(new NotificationRepository(db).countUnreadByUser(authorId)).toBe(0);
|
||||
});
|
||||
|
||||
it('does not notify a mentioned non-member', () => {
|
||||
service.sendMessage(authorId, projectId, `hi @o@example.com`);
|
||||
expect(new NotificationRepository(db).countUnreadByUser(outsiderId)).toBe(
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
it('only the author can edit their message', () => {
|
||||
const m = service.sendMessage(authorId, projectId, 'x');
|
||||
expect(() => service.editMessage(memberId, m.id, 'hacked')).toThrow(
|
||||
ForbiddenError
|
||||
);
|
||||
const updated = service.editMessage(authorId, m.id, 'edited');
|
||||
expect(updated.body).toBe('edited');
|
||||
});
|
||||
|
||||
it('broadcasts chat.message.updated on edit', () => {
|
||||
const client = makeClient();
|
||||
hub.addClient(projectId, client);
|
||||
const m = service.sendMessage(authorId, projectId, 'x');
|
||||
client.received.length = 0;
|
||||
service.editMessage(authorId, m.id, 'edited');
|
||||
expect(client.received[0]).toContain('chat.message.updated');
|
||||
});
|
||||
|
||||
it('admin can delete another member message; broadcasts deleted', () => {
|
||||
const client = makeClient();
|
||||
hub.addClient(projectId, client);
|
||||
const m = service.sendMessage(memberId, projectId, 'x');
|
||||
client.received.length = 0;
|
||||
service.deleteMessage(authorId, m.id); // authorId is admin
|
||||
expect(client.received[0]).toContain('chat.message.deleted');
|
||||
expect(() => service.getHistory(memberId, projectId)).not.toThrow();
|
||||
});
|
||||
|
||||
it('non-admin non-author cannot delete', () => {
|
||||
const m = service.sendMessage(authorId, projectId, 'x');
|
||||
expect(() => service.deleteMessage(memberId, m.id)).toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError for a non-existent message', () => {
|
||||
expect(() => service.deleteMessage(authorId, 99999)).toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user