NestJS中文文档
教程 / 用 Node.js 构建实时聊天后端
已译 191/191

用 Node.js 构建实时聊天后端

使用 NestJS 和 Socket.IO,在 Node.js 中构建实时聊天后端:带认证的 WebSocket、房间、存于 PostgreSQL 的消息历史,以及在线状态。

这个聊天应用有带成员的房间,有通过 WebSocket 实时到达并存进 PostgreSQL 的消息,有客户端通过 REST 分页翻阅的历史,还有在线状态与正在输入提示。聊天后端看起来很简单,直到你追问边界上的事:用户离开了房间却还开着标签页,消息广播之后就丢在重启里,令牌在连接中途过期,客户端一秒发来一千条消息。本教程的时间就花在这些地方。

到教程结束时,这个 API 将能够:

  • 接受用与 REST 路由相同的访问令牌登录的 Socket.IO 连接,并在连接所用令牌过期时关闭每一个连接。
  • 在广播之前把每条消息存入 PostgreSQL,并且在每处理一条消息时,用存储它的同一条语句校验发送者确实是该房间的成员。
  • 用 Zod schema 校验客户端发来的每条消息,并以客户端能据以行动的状态码回应拒绝。
  • 通过 REST 提供某个房间的历史,一次一页,采用键集分页。
  • 显示谁打开了某个房间,以及谁正在输入。
  • 限制每个用户发送消息的速度。
  • 在端到端测试中用真实的 Socket.IO 客户端、针对一个正在监听的服务器,证明上述全部能力。

它从 构建带 JWT 认证的 REST API 的 API 出发:那个 API 用访问令牌和刷新令牌让用户登录,用 Zod 校验请求,并通过 Drizzle 把数据保存在 PostgreSQL 中。本教程不再重复解释这些部分。

下面是端点与 WebSocket 事件,以及添加它们的小节:

端点或事件 小节
POST /auth/sign-up、POST /auth/token、POST /auth/token/refresh、POST /auth/token/revoke、GET /me、GET /health/live、GET /health/ready 从 JWT API 开始
POST /rooms、GET /rooms、POST /rooms/:id/members、DELETE /rooms/:id/members/me、GET /rooms/:id/messages 通过 REST 暴露房间与历史
客户端发送的 join、leave、message 和 typing 事件;服务器发送的 message、presence、typing 和 exception 事件 添加 WebSocket 网关
提示

完成后的应用位于 GitHub:nestjs/example-realtime-chat,其中包含测试和 CI 工作流。

从 JWT API 开始

创建项目,并安装本教程用到的全部依赖。它们是 JWT 教程的那些包,再加上带 Socket.IO 平台的 @nestjs/websockets,以及供测试使用的 socket.io-client:

$ npm i -g @nestjs/cli
$ nest new chat-api --minimal
$ cd chat-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/throttler @nestjs/swagger @nestjs/terminus @nestjs/websockets @nestjs/platform-socket.io socket.io
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite @electric-sql/pglite socket.io-client

然后从 已完成的 JWT 教程 原样取来这些文件:

  • src/config.ts、src/main.ts、drizzle.config.ts 和 vitest.config.e2e.ts
  • src/auth/、src/users/ 和 src/health/ 下的全部内容
  • test/refresh-token.store.e2e-spec.ts

不要 src/notes/,也不要 JWT 教程的 drizzle/ 文件夹:本应用的第一个迁移来自它自己的 schema,见下一节。凡是按笔记命名的地方都改成聊天:JwtAuth 中的 realm('chat'),以及 main.ts 中 OpenAPI 文档的标题。再把测试脚本加入 package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts"

最后,像 JWT 教程那样,把数据库 URL 和一个 JWT_SECRET 写进 .env,并使用聊天应用自己的数据库:

$ docker run -d --name chat-db -e POSTGRES_PASSWORD=chat -e POSTGRES_DB=chat -p 5432:5432 postgres:17

它的 URL 写进 .env,紧挨签名密钥:

DATABASE_URL=postgres://postgres:chat@localhost:5432/chat
# 用以下命令生成:openssl rand -base64 32
JWT_SECRET=

设计数据库模式

整个数据库模式就在一个文件里。用户和刷新令牌来自 JWT 教程:

src/database/schema.ts
import { bigint, boolean, index, jsonb, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const rooms = pgTable('rooms', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: text('name').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const roomMembers = pgTable(
  'room_members',
  {
    roomId: uuid('room_id')
      .notNull()
      .references(() => rooms.id, { onDelete: 'cascade' }),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    joinedAt: at('joined_at').notNull().defaultNow(),
  },
  (table) => [
    // 以房间打头:「该用户是否属于这个房间?」只需一次索引查找。
    primaryKey({ columns: [table.roomId, table.userId] }),
    // 用于「该用户的房间」。
    index('room_members_user_id_idx').on(table.userId),
  ],
);

export const messages = pgTable(
  'messages',
  {
    // 来自序列而非 UUID:id 随时间增长,因此「id X 之前」就是一页历史。
    id: bigint('id', { mode: 'number' }).primaryKey().generatedAlwaysAsIdentity(),
    roomId: uuid('room_id')
      .notNull()
      .references(() => rooms.id, { onDelete: 'cascade' }),
    authorId: uuid('author_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    body: text('body').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  // 服务于历史查询:某个房间的消息,最新优先,从任意 id 开始。
  (table) => [index('messages_room_id_id_idx').on(table.roomId, table.id)],
);

// @nestjs/authentication 为刷新令牌保存的内容,按其 SHA-256 存储。
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // 族中任一令牌被撤销时,整个族都被撤销。
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type Room = typeof rooms.$inferSelect;
export type Message = typeof messages.$inferSelect;
  • 房间成员是一张表,以房间和用户为键。 每条消息都要校验它,因此这次校验是对主键的一次查找,而主键以房间打头。第二个索引服务于「该用户的房间」。
  • 消息 id 来自序列,而非 gen_random_uuid()。它们随消息写入而增长,因此「id 120 之前的消息」是一页定义明确的历史,按 id 排序就是按数据库存下它们的顺序排序。UUID 不会那样排序。
  • (room_id, id) 联合建索引。 历史查询从某个给定 id 向下读取一个房间的消息,这次读取就是这个索引上的一段扫描,无论房间的历史增长到多长。

生成迁移并应用它(参见迁移):

$ npx drizzle-kit generate --name=chat
$ npx drizzle-kit migrate

管理房间与成员

客户端通过 REST 和通过 socket 发送的一切内容,其 schema 如下:

src/chat/chat.schemas.ts
import { z } from 'zod';

// 通过 REST

export const createRoomSchema = z.object({
  name: z.string().trim().min(1).max(100),
});
export type CreateRoomDto = z.infer<typeof createRoomSchema>;

export const addMemberSchema = z.object({
  email: z.email(),
});
export type AddMemberDto = z.infer<typeof addMemberSchema>;

export const historyQuerySchema = z.object({
  // 客户端手里最旧的消息 id;要取最新一页时省略它。
  before: z.coerce.number().int().positive().optional(),
  limit: z.coerce.number().int().min(1).max(100).default(50),
});
export type HistoryQuery = z.infer<typeof historyQuerySchema>;

// 通过 socket

export const roomRefSchema = z.object({
  roomId: z.uuid(),
});
export type RoomRef = z.infer<typeof roomRefSchema>;

export const sendMessageSchema = z.object({
  roomId: z.uuid(),
  body: z.string().trim().min(1).max(4_000),
});
export type SendMessageDto = z.infer<typeof sendMessageSchema>;

房间的任何成员都能按邮箱把另一个用户加进来,任何成员也都能离开。该服务把已登录用户的 id 作为第一个参数,与 JWT 教程的笔记服务一致:

src/chat/rooms.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { roomMembers, rooms, users, type Room } from '../database/schema.js';

@Injectable()
export class RoomsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** 创建一个房间,创建者是第一个成员。 */
  create(userId: string, name: string): Promise<Room> {
    return this.db.transaction(async (tx) => {
      const [room] = await tx.insert(rooms).values({ name }).returning();
      await tx.insert(roomMembers).values({ roomId: room.id, userId });
      return room;
    });
  }

  findMine(userId: string): Promise<Room[]> {
    return this.db
      .select({ id: rooms.id, name: rooms.name, createdAt: rooms.createdAt })
      .from(rooms)
      .innerJoin(roomMembers, eq(roomMembers.roomId, rooms.id))
      .where(eq(roomMembers.userId, userId))
      .orderBy(asc(rooms.name), asc(rooms.id));
  }

  /** 成员按邮箱添加另一个用户。重复添加同一成员不会有任何变化。 */
  async addMember(userId: string, roomId: string, email: string): Promise<void> {
    // 一条语句:调用者必须是成员,且该用户必须存在。
    const added = await this.db
      .insert(roomMembers)
      .select((qb) =>
        qb
          .select({ roomId: roomMembers.roomId, userId: users.id })
          .from(roomMembers)
          .innerJoin(users, eq(users.email, normalize(email)))
          .where(this.membership(userId, roomId)),
      )
      .onConflictDoNothing()
      .returning({ userId: roomMembers.userId });
    if (added.length === 0) {
      // 没有添加成功:查清原因,以便确定状态码。
      await this.assertMember(userId, roomId);
      const [user] = await this.db
        .select({ id: users.id })
        .from(users)
        .where(eq(users.email, normalize(email)));
      if (!user) {
        throw new NotFoundException('User not found');
      }
      // 否则,他们本来就是成员。
    }
  }

  async leave(userId: string, roomId: string): Promise<void> {
    const left = await this.db
      .delete(roomMembers)
      .where(this.membership(userId, roomId))
      .returning({ userId: roomMembers.userId });
    if (left.length === 0) {
      notFound();
    }
  }

  /** 除非用户是成员,否则返回 404:别人的房间与不存在的房间一样「找不到」。 */
  async assertMember(userId: string, roomId: string): Promise<void> {
    const [member] = await this.db
      .select({ one: sql`1` })
      .from(roomMembers)
      .where(this.membership(userId, roomId));
    if (!member) {
      notFound();
    }
  }

  private membership(userId: string, roomId: string) {
    return and(eq(roomMembers.roomId, roomId), eq(roomMembers.userId, userId));
  }
}

function notFound(): never {
  throw new NotFoundException('Room not found');
}

const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
  • 添加成员是一条 INSERT ... SELECT。 它插入的行来自调用者自己的成员记录,再与邮箱所指的用户连接。当调用者不是成员,或不存在这样的用户时,SELECT 找不到任何行,也就什么都没插入,于是在校验与写入之间不存在答案可能改变的瞬间。ON CONFLICT DO NOTHING 让重复添加某个用户成为空操作,而不是 500。
  • 只有插入失败时才付出第二次查询的代价。 当什么都没插入时,addMember() 再查一遍以决定状态码:调用者不在的房间返回 404,未知邮箱返回 404,而用户本来就是成员时返回 204。
  • 别人的房间就是 404,与不存在的房间给出相同答案,因此房间 id 不会泄露。
  • 离开是一条把成员条件写进 WHERE 子句的 DELETE,它的返回结果说明本来是否存在可以结束的成员关系。

存储消息并分页

消息由自己的服务处理。发布时会校验成员关系,而存储它就是同一条语句:

src/chat/messages.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, desc, eq, lt, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { messages, roomMembers, type Message } from '../database/schema.js';
import type { HistoryQuery } from './chat.schemas.js';
import { RoomsService } from './rooms.service.js';

export interface MessagePage {
  /** 最新优先。 */
  messages: Message[];
  /** 作为 `before` 传给下一更旧的一页;在最旧的一页上为 `null`。 */
  nextBefore: number | null;
}

@Injectable()
export class MessagesService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly roomsService: RoomsService,
  ) {}

  /** 存储一条消息,前提是其作者是该房间的成员。 */
  async post(authorId: string, roomId: string, body: string): Promise<Message> {
    // 成员记录是插入的来源:非成员发出的消息,
    // 或作者刚离开那一刻发出的消息,都不会插入任何行。
    const [message] = await this.db
      .insert(messages)
      .select((qb) =>
        qb
          .select({ roomId: roomMembers.roomId, authorId: roomMembers.userId, body: sql<string>`${body}`.as('body') })
          .from(roomMembers)
          .where(and(eq(roomMembers.roomId, roomId), eq(roomMembers.userId, authorId))),
      )
      .returning();
    if (!message) {
      throw new NotFoundException('Room not found');
    }
    return message;
  }

  /** 某个房间的一页历史,早于 `before`。 */
  async history(userId: string, roomId: string, { before, limit }: HistoryQuery): Promise<MessagePage> {
    await this.roomsService.assertMember(userId, roomId);
    const rows = await this.db
      .select()
      .from(messages)
      .where(and(eq(messages.roomId, roomId), before ? lt(messages.id, before) : undefined))
      .orderBy(desc(messages.id))
      // 比要求的多取一行:它是否返回,说明了是否还有更旧的一页。
      .limit(limit + 1);
    const page = rows.slice(0, limit);
    return { messages: page, nextBefore: rows.length > limit ? page[page.length - 1].id : null };
  }
}
  • 成员记录是插入的来源。 INSERT INTO messages ... SELECT ... FROM room_members WHERE room_id = $1 AND user_id = $2 对成员插入一行,对其他人一行都不插。用户在消息还在路上时离开房间,那么这条消息要么在 DELETE 提交之前就发布出去,要么什么都插不进去:不存在那种刚通过、此刻却已过期的校验。
  • 历史是一页键集分页。 WHERE room_id = $1 AND id < $before ORDER BY id DESC LIMIT n 从客户端手里最旧的那条消息开始,沿 (room_id, id) 索引从那里往下走。若用 OFFSET,就得先把每一条更新的消息读出来再丢掉,而且用户往回翻时只要有人发消息,位置就会偏移一格。
  • 它比一页多要一行。 那一行是否返回,说明了是否还有更旧的一页,因此 nextBefore 在最后一页为 null,而不是指向一个空页。
  • 读取历史会先校验成员关系,作为一次单独的查询。这是读操作:在校验与查询之间没有任何写入,也就没有会被撤销的东西。

添加 WebSocket 网关

网关 处理客户端通过 socket 发来的消息。本教程用的是由 @nestjs/platform-socket.io 提供的 Socket.IO,而不是 ws 库:

  • 访问令牌放在握手里。 浏览器无法在 WebSocket 连接上设置 Authorization 头。Socket.IO 客户端改为在握手的 auth 载荷中发送令牌,JwtBearerProvider 从那里读取它,因此网关用的是与 REST 路由相同的令牌、相同的 JwtAuth 提供者来让用户登录。
  • 房间是内建的。 Socket.IO 为每个房间维护一组 socket,并能向某个房间广播,这正是聊天房间需要的。
  • 确认也是内建的。 客户端发出消息后,会收到服务器针对这条消息的应答,此处就是已存储的消息,带上了它的 id。
  • 它通过适配器横向扩展,如运行多个实例 所述。

装上 @nestjs/platform-socket.io 之后,即使使用 Node 适配器,Nest 也会在 HTTP 服务器的端口上、以 /socket.io/ 为路径提供 Socket.IO。main.ts 无需任何改动。

谁打开了哪个房间,按 socket 记在内存里,这样开着两个标签页的用户要等关掉第二个标签页时才算离线:

src/chat/presence.service.ts
import { Injectable } from '@nestjs/common';

/** 在本实例上,谁打开了每个房间:房间 id,然后 socket id,然后用户 id。 */
@Injectable()
export class PresenceService {
  private readonly rooms = new Map<string, Map<string, string>>();

  /** 这是否是该用户在该房间里的第一个 socket。 */
  add(roomId: string, socketId: string, userId: string): boolean {
    const sockets = this.rooms.get(roomId) ?? new Map<string, string>();
    this.rooms.set(roomId, sockets);
    const first = !this.has(sockets, userId);
    sockets.set(socketId, userId);
    return first;
  }

  /** 移除一个 socket。如果它是该用户在该房间的最后一个 socket,则返回该用户。 */
  remove(roomId: string, socketId: string): string | undefined {
    const sockets = this.rooms.get(roomId);
    const userId = sockets?.get(socketId);
    if (!sockets || !userId) {
      return undefined;
    }
    sockets.delete(socketId);
    this.prune(roomId, sockets);
    return this.has(sockets, userId) ? undefined : userId;
  }

  /** 移除某个用户的所有 socket。返回其本来是否有 socket。 */
  removeUser(roomId: string, userId: string): boolean {
    const sockets = this.rooms.get(roomId);
    if (!sockets || !this.has(sockets, userId)) {
      return false;
    }
    for (const [socketId, user] of sockets) {
      if (user === userId) {
        sockets.delete(socketId);
      }
    }
    this.prune(roomId, sockets);
    return true;
  }

  online(roomId: string): string[] {
    return [...new Set(this.rooms.get(roomId)?.values())];
  }

  private has(sockets: Map<string, string>, userId: string): boolean {
    return [...sockets.values()].includes(userId);
  }

  private prune(roomId: string, sockets: Map<string, string>) {
    if (sockets.size === 0) {
      this.rooms.delete(roomId);
    }
  }
}

网关如下:

src/chat/chat.gateway.ts
import { UseFilters } from '@nestjs/common';
import { CurrentUser, WsAuthenticator, type JwtClaims } from '@nestjs/authentication';
import { Throttle, seconds } from '@nestjs/throttler';
import {
  ConnectedSocket,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  type OnGatewayConnection,
} from '@nestjs/websockets';
import type { Server, Socket } from 'socket.io';
import type { User } from '../users/user.js';
import { ChatExceptionFilter } from './chat-exception.filter.js';
import { roomRefSchema, sendMessageSchema, type RoomRef, type SendMessageDto } from './chat.schemas.js';
import { MessagesService } from './messages.service.js';
import { PresenceService } from './presence.service.js';
import { RoomsService } from './rooms.service.js';

/** 聊天房间对应的 socket.io 房间:它打开的 socket,接收它的消息。 */
const roomChannel = (roomId: string) => `room:${roomId}`;
/** 某个用户在每个实例上的所有 socket。 */
const userChannel = (userId: string) => `user:${userId}`;

@UseFilters(new ChatExceptionFilter())
@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection {
  @WebSocketServer()
  private readonly server: Server;

  constructor(
    private readonly wsAuthenticator: WsAuthenticator,
    private readonly roomsService: RoomsService,
    private readonly messagesService: MessagesService,
    private readonly presence: PresenceService,
  ) {}

  async handleConnection(client: Socket) {
    // 最先注册:socket.io 会在 "disconnect" 之前清空 `client.rooms`。
    client.on('disconnecting', () => this.closeRooms(client));
    // 除非握手携带有效的访问令牌,否则关闭连接(并返回 null)。
    const auth = await this.wsAuthenticator.authenticateConnection(client);
    if (!auth) {
      return;
    }
    const { id } = auth.user as User;
    client.data.userId = id;
    await client.join(userChannel(id));
    // 连接的寿命与其访问令牌相同。客户端随后
    // 用新的令牌重连,就像它会随请求发送一个令牌那样。
    const { exp } = auth.session as JwtClaims;
    if (exp) {
      const expiry = setTimeout(() => client.disconnect(true), exp * 1000 - Date.now());
      client.on('disconnect', () => clearTimeout(expiry));
    }
  }

  /** 打开一个房间:该 socket 接收它的消息、正在输入和在线状态。 */
  @SubscribeMessage('join')
  async join(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef,
  ) {
    await this.roomsService.assertMember(userId, roomId);
    await client.join(roomChannel(roomId));
    if (this.presence.add(roomId, client.id, userId)) {
      client.to(roomChannel(roomId)).emit('presence', { roomId, userId, online: true });
    }
    return { roomId, online: this.presence.online(roomId) };
  }

  /** 在这个 socket 上关闭一个房间。该用户仍然是成员。 */
  @SubscribeMessage('leave')
  async leave(@ConnectedSocket() client: Socket, @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef) {
    await client.leave(roomChannel(roomId));
    this.wentAway(roomId, this.presence.remove(roomId, client.id));
    return { roomId };
  }

  @Throttle({ default: { limit: 10, ttl: seconds(10) } })
  @SubscribeMessage('message')
  async message(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: sendMessageSchema }) { roomId, body }: SendMessageDto,
  ) {
    // 先存储,后广播:没有人会看到一条可能被重启弄丢的消息。
    const message = await this.messagesService.post(userId, roomId, body);
    client.to(roomChannel(roomId)).emit('message', message);
    // 确认:发送者由此得知消息的 id。
    return message;
  }

  @SubscribeMessage('typing')
  typing(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef,
  ) {
    // 只来自打开过该房间的 socket,那里已经校验过成员关系。
    if (client.rooms.has(roomChannel(roomId))) {
      client.to(roomChannel(roomId)).emit('typing', { roomId, userId });
    }
  }

  /** 用户在通过 REST 离开房间之后:他已打开的 socket 停止接收该房间的消息。 */
  removeFromRoom(roomId: string, userId: string) {
    this.server.in(userChannel(userId)).socketsLeave(roomChannel(roomId));
    if (this.presence.removeUser(roomId, userId)) {
      this.wentAway(roomId, userId);
    }
  }

  private closeRooms(client: Socket) {
    for (const channel of client.rooms) {
      if (channel.startsWith('room:')) {
        const roomId = channel.slice('room:'.length);
        this.wentAway(roomId, this.presence.remove(roomId, client.id));
      }
    }
  }

  private wentAway(roomId: string, userId: string | undefined) {
    if (userId) {
      this.server.to(roomChannel(roomId)).emit('presence', { roomId, userId, online: false });
    }
  }
}
  • 握手用 WsAuthenticator 认证。 Nest 不在 handleConnection() 上运行任何守卫。authenticateConnection() 运行与守卫相同的凭证提供者,并断开没有有效访问令牌的 socket。参见 GraphQL 与 WebSocket。客户端会看到自己的 connect 事件,随后是一个 disconnect,原因为 io server disconnect。
  • 每条消息都会再次认证。 全局认证守卫会为每个 @SubscribeMessage() 处理器运行,正如为每个路由运行一样,@CurrentUser('id') 读取该条消息的用户。Nest 在处理某个 socket 的消息之前不会等待 handleConnection(),因此握手本身不是一道关口:守卫才是。
  • 连接的寿命与其访问令牌相同。 令牌只在握手时校验过一次,而 socket 可以一开就是好几天。当令牌的 exp 过去时,一个定时器会断开它,客户端则用新令牌重连,正如试一试 所示。没有这个定时器,令牌已过期的 socket 发出的每条消息都会得到 401,而它只要还开着,就会继续收到该房间的消息。
  • 成员关系在每条消息上校验,而不只在 join 时校验。 join 在 socket 进入房间频道之前校验,因此只有成员才会收到某个房间的消息。但客户端可以向任意房间 id 发送 message,无论是否加入过,所以 post() 会在存储消息的那条语句里再校验一次。
  • 消息先存储,再广播。 如果进程在这两步之间死掉,这条消息仍在历史里,每个客户端重连时都能找到它。反过来的顺序则会让房间看到一条可能被重启弄丢的消息。
  • 发送者收到确认,其他人收到广播。 client.to(channel) 会送达房间里除发送者之外的所有 socket,包括发送者的其他标签页。两者携带的是同一条消息,带 id。
  • 正在输入只转发,不存储。 一个正在输入事件在几秒之后就毫无价值,所以它从不进数据库。它只从已加入该房间、并通过成员关系校验的 socket 转发。
  • 通过 REST 离开会把该用户的 socket 一律清出房间。 每个 socket 在连接时都会加入属于其用户的频道,因此 removeFromRoom() 能触达某个用户的所有 socket,若有适配器,还能触达每个实例上的。

Nest 的 WebSocket 异常过滤器只把 WsException 的消息发给客户端。其他任何异常到达客户端时都是「Internal server error」:各服务为 REST 路由抛出的 NotFoundException,以及校验管道的 BadRequestException。携带对象的 WsException,例如认证守卫的 401,发送时会丢掉那个说明它在应答哪条消息的 cause。网关的过滤器让每一次拒绝都具有相同的形状(参见异常过滤器):

src/chat/chat-exception.filter.ts
import { type ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets';

/**
 * 把每一次拒绝作为 "exception" 事件发给客户端,带上状态码、消息,
 * 以及它所拒绝的事件和载荷,使客户端能分辨是哪条消息失败了。
 */
@Catch(HttpException, WsException)
export class ChatExceptionFilter extends BaseWsExceptionFilter {
  catch(exception: HttpException | WsException, host: ArgumentsHost) {
    const ws = host.switchToWs();
    const cause = { pattern: ws.getPattern(), data: ws.getData() };
    super.catch(new WsException({ status: 'error', ...bodyOf(exception), cause }), host);
  }
}

function bodyOf(exception: HttpException | WsException): object {
  if (exception instanceof WsException) {
    const error = exception.getError();
    return typeof error === 'string' ? { message: error } : error;
  }
  // 各服务的异常,以及校验管道的异常,客户端
  // 本来会以 "Internal server error" 收到它们。
  const response = exception.getResponse();
  return typeof response === 'string' ? { statusCode: exception.getStatus(), message: response } : response;
}

JWT 教程中的全局 StandardSchemaValidationPipe 会依据 schema 校验 @MessageBody(),就像它校验 @Body() 一样,因此格式错误的消息永远不会到达处理器。被拒绝的消息得不到确认。客户端改为收到一个 exception 事件,其 cause 指明了它所拒绝的事件和载荷:

{
  "status": "error",
  "message": ["body: Too small: expected string to have >=1 characters"],
  "error": "Bad Request",
  "statusCode": 400,
  "cause": { "pattern": "message", "data": { "roomId": "5122632a-7885-4d6a-a7b8-8f03f54a4a98", "body": "   " } }
}

通过 REST 暴露房间与历史

创建房间、添加成员和读取历史都是普通请求,留在 REST 上:它们不需要打开的连接,并且保留了 JWT 教程的校验、限流和 OpenAPI 文档。

src/chat/rooms.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Query } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { z } from 'zod';
import { ChatGateway } from './chat.gateway.js';
import {
  addMemberSchema,
  createRoomSchema,
  historyQuerySchema,
  type AddMemberDto,
  type CreateRoomDto,
  type HistoryQuery,
} from './chat.schemas.js';
import { MessagesService } from './messages.service.js';
import { RoomsService } from './rooms.service.js';

const roomId = { schema: z.uuid() };

@Controller('rooms')
export class RoomsController {
  constructor(
    private readonly roomsService: RoomsService,
    private readonly messagesService: MessagesService,
    private readonly chatGateway: ChatGateway,
  ) {}

  @Post()
  create(@CurrentUser('id') userId: string, @Body({ schema: createRoomSchema }) { name }: CreateRoomDto) {
    return this.roomsService.create(userId, name);
  }

  @Get()
  findMine(@CurrentUser('id') userId: string) {
    return this.roomsService.findMine(userId);
  }

  @Post(':id/members')
  @HttpCode(204)
  addMember(
    @CurrentUser('id') userId: string,
    @Param('id', roomId) id: string,
    @Body({ schema: addMemberSchema }) { email }: AddMemberDto,
  ) {
    return this.roomsService.addMember(userId, id, email);
  }

  @Delete(':id/members/me')
  @HttpCode(204)
  async leave(@CurrentUser('id') userId: string, @Param('id', roomId) id: string) {
    await this.roomsService.leave(userId, id);
    this.chatGateway.removeFromRoom(id, userId);
  }

  @Get(':id/messages')
  history(
    @CurrentUser('id') userId: string,
    @Param('id', roomId) id: string,
    @Query({ schema: historyQuerySchema }) query: HistoryQuery,
  ) {
    return this.messagesService.history(userId, id, query);
  }
}

POST /rooms/:id/members 和 DELETE /rooms/:id/members/me 返回 204 No Content:客户端已经知道改了什么。离开会调用网关,因此用户已打开的 socket 立刻停止接收该房间的消息,而不用等到下次重连。

src/chat/chat.module.ts
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway.js';
import { MessagesService } from './messages.service.js';
import { PresenceService } from './presence.service.js';
import { RoomsController } from './rooms.controller.js';
import { RoomsService } from './rooms.service.js';

@Module({
  controllers: [RoomsController],
  providers: [ChatGateway, RoomsService, MessagesService, PresenceService],
})
export class ChatModule {}

对消息限流

JWT 教程的全局 ThrottlerGuard 对网关消息同样运行,它的 default 限流器也是如此。在 WebSocket 之上,它用来计数的「请求」是 socket,而 socket 没有 ip,于是所有客户端的消息会共用一个计数器:一个吵闹的用户就能挡住所有人。给 default 限流器一个按用户统计网关消息的追踪器。限流一章的 WebSocket 小节用一个守卫子类做到这一点;而 getTracker 选项同样能拿到 ExecutionContext(参见配置),不用子类也能做到:

src/chat/throttler-tracker.ts
import type { ExecutionContext } from '@nestjs/common';
import { normalizeIp } from '@nestjs/throttler';

/**
 * 限流器据此计数。在 WebSocket 之上,`req` 就是 socket,它没有 `ip`:
 * 没有这个,所有客户端的消息会共用一个计数器。
 */
export function tracker(req: Record<string, any>, context: ExecutionContext): string {
  if (context.getType() === 'ws') {
    // 握手时登录的用户;在拿到用户之前则是地址。
    return req.data.userId ?? normalizeIp(req.handshake.address);
  }
  return normalizeIp(req.ip);
}

client.data.userId 在 handleConnection() 中设置,此时握手已通过认证。有了这个追踪器,每个网关事件都按用户计入 default 限制的每分钟 100 次,join、leave 和 typing 也在内。message 有自己更紧的限制,来自其处理器上的 @Throttle():每 10 秒 10 条。第 11 条消息会得到一个状态码为 429 的 exception 事件,过滤器会连同限流器的消息一起转发它。

根模块,包含聊天模块和追踪器:

src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { ChatModule } from './chat/chat.module.js';
import { tracker } from './chat/throttler-tracker.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最前,以便最后关闭,仍能上报其他模块做过的事。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前为空:此时 SDK 不发送任何内容。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'chat-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'chat-api',
          audience: 'chat-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    ThrottlerModule.forRoot([
      // 每个路由按 IP 地址计数,聊天网关上按用户计数。
      { name: 'default', ttl: minutes(1), limit: 100, getTracker: tracker },
      // 在请求体指明账户之处,按邮箱和 IP 地址计数。
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ChatModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}

运行多个实例

以上全部内容都运行在单个实例上。放到负载均衡器后面的多个实例上时,有三样东西是每进程一份的,就不够用了:

  • 广播。 client.to(channel).emit() 只触达连接在本实例上的 socket。Redis 适配器 在实例之间共享广播和 socketsLeave(),因此 removeFromRoom() 无论用户的 socket 连在哪里都能触达。正如那一章所警告的,光有 Redis 还不够:Socket.IO 客户端以 HTTP 长轮询起步,其请求必须全部到达同一个实例。要么在负载均衡器上使用粘性会话,要么像本教程的客户端那样用 transports: ['websocket'] 连接。
  • 在线状态。 PresenceService 只知道本实例的 socket。要跨实例显示谁在线,可以把同样的映射放进 Redis,并为每个实例设一个过期时间,让崩溃实例的 socket 消失;也可以用 Socket.IO 的 fetchSockets()(Redis 适配器支持它)去问每一个实例。
  • 限流。 限流器在内存中计数,所以每个实例各算各的。改用共享的存储,例如 Redis。

消息本身不需要做什么:它们在 PostgreSQL 里,每个实例读到的都是同一份历史。

试一试

Socket.IO 在 WebSocket 之上讲自己的协议,所以 curl 无法加入房间。scripts/ 里的一个小客户端可以。它用访问令牌连接,加入房间,打印服务器发来的内容,并把你输入的每一行作为一条消息发出去:

scripts/chat.ts
// 用于试用聊天的终端客户端:TOKEN=<访问令牌> node scripts/chat.ts <房间 id>
import { createInterface } from 'node:readline';
import { io } from 'socket.io-client';

const roomId = process.argv[2];
const socket = io(process.env.CHAT_URL ?? 'http://localhost:3000', {
  // 访问令牌,JwtBearerProvider 会从握手中读取它。
  auth: { token: process.env.TOKEN },
  // 直接走 WebSocket,不先做长轮询。
  transports: ['websocket'],
});

const print = (event: string) => (data: unknown) => console.log(event, JSON.stringify(data));

socket.on('connect', () => {
  // 房间是按连接打开的:每次重连之后都要重新打开。
  socket.emit('join', { roomId }, print('joined'));
});
socket.on('message', print('message'));
socket.on('presence', print('presence'));
socket.on('typing', print('typing'));
socket.on('exception', print('exception'));
socket.on('disconnect', print('disconnect'));

// 每一行都是一条消息。
for await (const body of createInterface({ input: process.stdin })) {
  socket.emit('typing', { roomId });
  try {
    print('sent')(await socket.timeout(5000).emitWithAck('message', { roomId, body }));
  } catch {
    // 被拒绝了:"exception" 事件会说明原因。
  }
}
socket.close();

Node.js 22.18 及更高版本可以直接运行这样的 TypeScript 文件。启动应用:

$ npm run start

注册 Ada 和 Bob,以及不会进入房间的 Eve。Ada 创建一个房间并把 Bob 加进来(下面以及后文的令牌、id 和时间戳都做了截短):

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"hpJMLcGsMXSATrZ2...","expiresIn":900}
$ ADA=eyJhbGciOiJIUzI1NiIs...
$ BOB=eyJhbGciOiJIUzI1NiIs...
$ EVE=eyJhbGciOiJIUzI1NiIs...
$ curl localhost:3000/rooms -H "Authorization: Bearer $ADA" --json '{"name":"general"}'
{"id":"5122632a-7885-4d6a-a7b8-8f03f54a4a98","name":"general","createdAt":"2026-11-19T22:08:55.613Z"}
$ ROOM=5122632a-7885-4d6a-a7b8-8f03f54a4a98
$ curl -i localhost:3000/rooms/$ROOM/members -H "Authorization: Bearer $ADA" --json '{"email":"bob@example.com"}'
HTTP/1.1 204 No Content
$ curl localhost:3000/rooms -H "Authorization: Bearer $BOB"
[{"id":"5122632a-7885-4d6a-a7b8-8f03f54a4a98","name":"general","createdAt":"2026-11-19T22:08:55.613Z"}]

在第二个终端里,Bob 打开这个房间。在第一个终端里,Ada 也打开它,并输入一条消息,Bob 作答(没有事件名的行就是他们各自输入的内容):

Bob 的终端:

$ TOKEN=$BOB node scripts/chat.ts $ROOM
joined {"roomId":"5122632a-...","online":["7154be3b-..."]}
presence {"roomId":"5122632a-...","userId":"092e1b0b-...","online":true}
typing {"roomId":"5122632a-...","userId":"092e1b0b-..."}
message {"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}
Hi Ada
sent {"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}

Ada 的终端:

$ TOKEN=$ADA node scripts/chat.ts $ROOM
joined {"roomId":"5122632a-...","online":["7154be3b-...","092e1b0b-..."]}
Hi Bob
sent {"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}
typing {"roomId":"5122632a-...","userId":"7154be3b-..."}
message {"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}

每条消息到达对方时,与发送者在确认里收到的对象完全相同,包括 id。

Eve 不是成员。她的令牌有效,因此可以连接,但她无法打开该房间,也无法向它发布消息:

$ TOKEN=$EVE node scripts/chat.ts $ROOM
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"join","data":{"roomId":"5122632a-..."}}}
Let me in
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"message","data":{"roomId":"5122632a-...","body":"Let me in"}}}

历史:每页一条消息,最新优先。nextBefore 就是下一页的 before,在最后一页为 null:

$ curl "localhost:3000/rooms/$ROOM/messages?limit=1" -H "Authorization: Bearer $ADA"
{"messages":[{"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}],"nextBefore":2}
$ curl "localhost:3000/rooms/$ROOM/messages?limit=1&before=2" -H "Authorization: Bearer $ADA"
{"messages":[{"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}],"nextBefore":null}
$ curl "localhost:3000/rooms/$ROOM/messages?limit=1" -H "Authorization: Bearer $EVE"
{"message":"Room not found","error":"Not Found","statusCode":404}

Bob 通过 REST 离开房间,客户端还在运行。Ada 的客户端看到他离开,而 Bob 的下一条消息被拒绝,拒绝它的正是那条存储消息的 INSERT ... SELECT:

$ curl -i -X DELETE localhost:3000/rooms/$ROOM/members/me -H "Authorization: Bearer $BOB"
HTTP/1.1 204 No Content

在 Ada 的终端里:

presence {"roomId":"5122632a-...","userId":"7154be3b-...","online":false}

在 Bob 的终端里:

Still here?
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"message","data":{"roomId":"5122632a-...","body":"Still here?"}}}

真实客户端还要处理连接的结束:当访问令牌过期时,服务器断开该 socket,客户端则通过 REST 刷新令牌并重新连接。把 auth 写成函数,Socket.IO 会在每次连接尝试之前索取令牌:

const socket = io('https://chat.example.com', {
  // 每次连接尝试之前都会调用,因此重连时发送的是当前令牌。
  auth: (send) => send({ token: accessToken }),
  transports: ['websocket'],
});

socket.on('disconnect', async (reason) => {
  // 服务器在访问令牌过期时结束该连接。
  if (reason === 'io server disconnect') {
    await refreshTokens(); // POST /auth/token/refresh, which sets accessToken
    socket.connect();
  }
});

重连之后 connect 处理器会再次运行,并再次打开各个房间:房间是按连接加入的,不是按用户。消息到达的顺序可能与 id 顺序不同,因此客户端按 id 排序显示,并丢弃已经拥有的消息,例如先前通过历史取到、随后又实时收到的同一条。

测试它

测试用 app.listen(0) 在一个空闲端口上启动真实应用,并像浏览器那样用 socket.io-client 连接它。数据库是 PGlite,与 JWT 教程的测试相同:聊天所保证的东西来自单条语句,而不是并发事务如何交错,因此单连接就能忠实地测试它。

test/chat.e2e-spec.ts
import { createHmac } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { io, type Socket } from 'socket.io-client';
import { AppModule, ObserveInstrument } from '../src/app.module.js';

describe('Chat (e2e)', () => {
  const pglite = new PGlite(); // 进程内的 PostgreSQL:无需启动服务器
  let app: NestNodeApplication;
  let url: string;
  const sockets: Socket[] = [];

  beforeAll(async () => {
    const db = drizzle({ client: pglite });
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    // 与 main.ts 一样做仪器化,使 NestJS Observe 能看到网关的处理器。
    const moduleRef = await Test.createTestingModule(
      { imports: [AppModule] },
      { instrument: ObserveInstrument },
    )
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // 默认代价下的 scrypt 每次哈希占用 128 MiB、耗时数百毫秒。
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    // 空闲端口上的真实服务器:socket 像任何客户端一样连接它。
    await app.listen(0);
    url = await app.getUrl();
  });

  afterEach(() => {
    for (const socket of sockets.splice(0)) {
      socket.disconnect();
    }
  });

  afterAll(async () => {
    await app.close();
    await pglite.close();
  });

  let clients = 0;

  /** 注册一个用户,返回其 id、其请求的头,以及其访问令牌。 */
  async function signUp(name: string) {
    const signedUp = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email: `${name}@example.com`, password: 'correct horse battery' },
      // 注册按 IP 地址限流:每个用户都从自己的地址注册。
      remoteAddress: `10.0.0.${++clients}`,
    });
    const { accessToken } = signedUp.json<{ accessToken: string }>();
    const headers = { authorization: `Bearer ${accessToken}` };
    const { id } = (await app.inject({ method: 'GET', url: '/me', headers })).json<{ id: string }>();
    return { id, headers, accessToken };
  }

  /** 一个房间,创建者和其余用户都是成员。 */
  async function createRoom(creator: Awaited<ReturnType<typeof signUp>>, ...members: string[]) {
    const res = await app.inject({
      method: 'POST',
      url: '/rooms',
      headers: creator.headers,
      payload: { name: 'general' },
    });
    const { id } = res.json<{ id: string }>();
    for (const name of members) {
      const added = await app.inject({
        method: 'POST',
        url: `/rooms/${id}/members`,
        headers: creator.headers,
        payload: { email: `${name}@example.com` },
      });
      expect(added.statusCode).toBe(204);
    }
    return id;
  }

  /** 与 API 自己签发的类似的一个访问令牌,两秒内过期。 */
  function shortLivedToken(sub: string) {
    const now = Math.floor(Date.now() / 1000);
    const encode = (part: object) => Buffer.from(JSON.stringify(part)).toString('base64url');
    const claims = { sub, iss: 'chat-api', aud: 'chat-api', iat: now, exp: now + 2 };
    const unsigned = `${encode({ alg: 'HS256', typ: 'JWT' })}.${encode(claims)}`;
    return `${unsigned}.${createHmac('sha256', process.env.JWT_SECRET!).update(unsigned).digest('base64url')}`;
  }

  /** 一个 socket.io 客户端,如浏览器打开的那样,访问令牌放在握手里。 */
  function open(token: string): Socket {
    const socket = io(url, { auth: { token }, transports: ['websocket'] });
    sockets.push(socket);
    return socket;
  }

  function connect(token: string): Promise<Socket> {
    const socket = open(token);
    return new Promise((resolve) => socket.on('connect', () => resolve(socket)));
  }

  /** 该 socket 接下来收到的 `event`。 */
  function next<T = any>(socket: Socket, event: string): Promise<T> {
    return new Promise((resolve) => socket.once(event, resolve));
  }

  /** 发送一条消息并等待服务器的确认。 */
  function send(socket: Socket, event: string, data: unknown) {
    return socket.timeout(2000).emitWithAck(event, data);
  }

  it('disconnects a client without a valid access token', async () => {
    const socket = open('not-a-token');
    expect(await next(socket, 'disconnect')).toBe('io server disconnect');
  });

  it('stores a message, then delivers it to the room', async () => {
    const ada = await signUp('ada');
    const bob = await signUp('bob');
    const roomId = await createRoom(ada, 'bob');
    const adaSocket = await connect(ada.accessToken);
    const bobSocket = await connect(bob.accessToken);
    await send(adaSocket, 'join', { roomId });
    const joined = await send(bobSocket, 'join', { roomId });
    expect(joined.online.sort()).toEqual([ada.id, bob.id].sort());

    const received = next(bobSocket, 'message');
    const ack = await send(adaSocket, 'message', { roomId, body: 'Hi Bob' });

    expect(await received).toEqual(ack);
    expect(ack).toMatchObject({ roomId, authorId: ada.id, body: 'Hi Bob' });
    const history = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: bob.headers });
    expect(history.json().messages).toEqual([ack]);
  });

  it("refuses a non-member's message, and stores nothing", async () => {
    const carol = await signUp('carol');
    const eve = await signUp('eve');
    const roomId = await createRoom(carol);
    const eveSocket = await connect(eve.accessToken);

    const refused = next(eveSocket, 'exception');
    eveSocket.emit('message', { roomId, body: 'Let me in' });

    expect(await refused).toEqual({
      status: 'error',
      statusCode: 404,
      message: 'Room not found',
      error: 'Not Found',
      cause: { pattern: 'message', data: { roomId, body: 'Let me in' } },
    });
    const history = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: carol.headers });
    expect(history.json().messages).toEqual([]);
    expect(
      (await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: eve.headers })).statusCode,
    ).toBe(404);
  });

  it('checks the membership on every message, not only on join', async () => {
    const dan = await signUp('dan');
    const fay = await signUp('fay');
    const roomId = await createRoom(dan, 'fay');
    const danSocket = await connect(dan.accessToken);
    const faySocket = await connect(fay.accessToken);
    await send(danSocket, 'join', { roomId });
    const cameOnline = next(danSocket, 'presence');
    await send(faySocket, 'join', { roomId });
    expect(await cameOnline).toEqual({ roomId, userId: fay.id, online: true });

    const wentOffline = next(danSocket, 'presence');
    const left = await app.inject({ method: 'DELETE', url: `/rooms/${roomId}/members/me`, headers: fay.headers });
    expect(left.statusCode).toBe(204);
    expect(await wentOffline).toEqual({ roomId, userId: fay.id, online: false });

    // Fay 的 socket 仍然连着,也仍然指名这个房间。
    const refused = next(faySocket, 'exception');
    faySocket.emit('message', { roomId, body: 'Still here?' });
    expect(await refused).toMatchObject({ statusCode: 404 });

    // 而且它不再收到该房间的消息。
    const delivered: unknown[] = [];
    faySocket.on('message', (message) => delivered.push(message));
    await send(danSocket, 'message', { roomId, body: 'Bye Fay' });
    await send(faySocket, 'leave', { roomId }); // Fay 连接上的一次往返
    expect(delivered).toEqual([]);
  });

  it('disconnects a client when its access token expires', async () => {
    const kim = await signUp('kim');
    const socket = open(shortLivedToken(kim.id));

    await next(socket, 'connect');
    expect(await next(socket, 'disconnect')).toBe('io server disconnect');
  });

  it('validates messages with the Zod schema', async () => {
    const gus = await signUp('gus');
    const roomId = await createRoom(gus);
    const socket = await connect(gus.accessToken);

    const refused = next(socket, 'exception');
    socket.emit('message', { roomId, body: '   ' });

    expect(await refused).toMatchObject({
      statusCode: 400,
      message: ['body: Too small: expected string to have >=1 characters'],
    });
  });

  it('pages through the history, newest first', async () => {
    const hal = await signUp('hal');
    const roomId = await createRoom(hal);
    const socket = await connect(hal.accessToken);
    const sent: number[] = [];
    for (const body of ['one', 'two', 'three', 'four', 'five']) {
      sent.push((await send(socket, 'message', { roomId, body })).id);
    }

    const ids: number[] = [];
    let before: number | null | undefined;
    do {
      const query = before ? `?limit=2&before=${before}` : '?limit=2';
      const page = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages${query}`, headers: hal.headers });
      const { messages, nextBefore } = page.json<{ messages: { id: number }[]; nextBefore: number | null }>();
      ids.push(...messages.map((message) => message.id));
      before = nextBefore;
    } while (before);

    expect(ids).toEqual(sent.reverse());
  });

  it('limits how fast each user sends messages', async () => {
    const ivy = await signUp('ivy');
    const jon = await signUp('jon');
    const roomId = await createRoom(ivy, 'jon');
    const ivySocket = await connect(ivy.accessToken);
    const jonSocket = await connect(jon.accessToken);

    const refused = next(ivySocket, 'exception');
    for (let i = 1; i <= 11; i++) {
      ivySocket.emit('message', { roomId, body: `Message ${i}` });
    }

    expect(await refused).toMatchObject({ statusCode: 429 });
    // 另一个用户的消息单独计数。
    expect(await send(jonSocket, 'message', { roomId, body: 'Hello' })).toMatchObject({ body: 'Hello' });
  });
});
  • createTestingModule() 接受 instrument 选项(自 @nestjs/testing 12.6.3 起),正如 main.ts 中的 NestFactory.create() 一样。没有它,网关的处理器就在未仪器化的情况下运行,NestJS Observe 会为每个无法追踪的事件记一条错误。
  • open() 在连接之前就返回 socket,因此第一个测试从头开始就在监听 disconnect。被服务器拒绝的 socket,可能在 connect 上 await 之后的代码运行之前就收到它的 disconnect。
  • send() 给确认设了超时。被拒绝的消息永远等不到确认,因此若不设超时,期待确认的测试会挂起而不是失败。
  • shortLivedToken() 按 API 的 accessToken 选项所用的方式签发令牌(HS256,chat-api 的签发方与受众,测试的 JWT_SECRET),它在握手后两秒内过期。

连同 JWT 教程的刷新令牌存储测试一起运行,使用它们自己的数据库:

$ docker exec chat-db psql -U postgres -c "CREATE DATABASE chat_test"
$ TEST_DATABASE_URL=postgres://postgres:chat@localhost:5432/chat_test npm run test:e2e

 Test Files  2 passed (2)
      Tests  13 passed (13)

若改用普通的 insert(messages).values() 而不是 INSERT ... SELECT 来存储消息,会有两个测试失败:非成员的消息被存下并广播出去,已离开用户的消息也是如此。若去掉限流器的追踪器,限流测试会失败:Jon 的第一条消息被拒绝,因为 Ivy 用光了他们共用的计数器。

生产环境检查清单

JWT 教程检查清单 中的一切都适用。针对聊天,另需特别注意:

  • 在需要多实例之前就规划好。 运行多个实例 里的 Redis 适配器、共享在线状态和共享限流存储,在第二个实例出现之前添加,比之后再补更容易。
  • 预期每次部署都会让所有客户端重连。 关闭钩子已开启,因此部署时的 SIGTERM 会随应用一起关闭所有打开的连接。客户端看到的是 transport close,而非 io server disconnect,Socket.IO 会自行把它们重连到仍在运行的实例上,在那里重新打开各自的房间。要为这波握手突发留足实例容量。
  • 自行结束被封禁或被删除用户的连接。 守卫会拒绝他们的下一条消息,但一个开着的 socket 会继续收到其所在房间的消息,直到访问令牌过期,最晚可达 15 分钟之后。断开该用户频道里的 socket,就像 removeFromRoom() 把它们清出房间那样。
  • 限制单个客户端能发送的量。 Zod schema 把消息上限设为 4,000 个字符,限流器则限制速率。IoAdapter 还限制同一客户端的消息能同时处理多少条(参见限制)。
  • 如果 Web 应用使用长轮询,就放行它的来源。 WebSocket 连接不受 CORS 约束,但 Socket.IO 的长轮询请求受:如果客户端不是用 transports: ['websocket'] 连接,就给 @WebSocketGateway() 传一个带 Web 应用来源的 cors 选项。
  • 让历史查询留在索引上。 messages_room_id_id_idx 服务于每一页。若历史还要按别的东西过滤,例如按作者或搜索,就需要自己的索引,或者一个搜索引擎。
  • 给生产环境单独一套 Observe 密钥对,从项目的 API Keys 页面获取,作为平台环境中的 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET:start:prod 不会加载 .env。于是 NestJS Observe 会把每个由 @SubscribeMessage() 处理的消息作为一条 ws 协议的请求上报,其操作 id 由网关类名与模式组成,例如 ChatGateway:message。连接与断开不上报(参见WebSocket 网关)。

下一步

  • 在请求之外通过邮件或推送通知未连接的成员:邮件 和队列。
  • 给房间配上所有者与版主,并按房间校验权限:授权。
  • 在实例之间共享广播:适配器。
  • 在生产环境查看缓慢的历史分页与被拒绝的消息:可观测性。
  • 在同样的基座上构建电商后端:构建电商后端。