NestJS中文文档
教程 / 用 Node.js 发送邮件并运行后台任务
已译 191/191

用 Node.js 发送邮件并运行后台任务

使用 NestJS 和 BullMQ 在 Node.js 中发送邮件并运行后台任务:重试、绝不重复发出的邮件、定时任务,以及干净的关闭。

本教程为 JWT 教程的笔记 API 加上邮件:注册之后发送一封欢迎邮件,以及每晚把每位用户当天改动过的笔记汇总成一份摘要。这些邮件都由 BullMQ 队列发出,因此没有任何请求需要等待邮件服务器。发送一封邮件只是一次调用;难的是在后台可靠地把它发出去:任务不能在数据库与队列之间丢失,执行两次的任务不能发送两次,定时任务在 API 无论有多少个实例时都只能执行一次,部署也不能把一次发送切成两半。

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

  • 使用 @nestjs/mail 发送邮件:邮件类渲染经过转义的 HTML,开发环境下写入控制台,生产环境下通过 SMTP 发送。
  • 每封邮件都从 BullMQ 队列发出,带重试与指数退避,已完成的任务按你设定的时间表清理。
  • 用 事务性发件箱 把欢迎邮件从注册事务交给队列,因此崩溃或 Redis 故障都不会把它弄丢,Redis 宕机时注册也不会失败。
  • 每封邮件只发送一次,即使它的任务在同一时刻执行了两次。
  • 用 @nestjs/schedule 把晚间摘要排入队列,并借助 @nestjs/locks 让它在应用的单个实例上执行。
  • 部署停止进程时,把正在发送的邮件发完;需要时,把工作进程放进独立的进程运行。
  • 在针对 PostgreSQL 和 Redis 的测试中验证上述全部行为。

它从使用 Node.js 构建带 JWT 认证的 REST API 的 API 出发:那个 API 让用户登录,并通过 Drizzle 把他们的笔记保存在 PostgreSQL 中。本教程不再重复解释这些部分。它没有新增端点;下面是这些邮件,以及添加每封邮件的小节:

邮件 发送时机 小节
欢迎邮件 POST /auth/sign-up 提交成功时 把欢迎邮件交给队列
摘要 每天 18:00 UTC,发给当天改动过笔记的每位用户 在单个实例上发送摘要
提示

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

从 JWT API 开始

创建项目,安装 JWT 教程用到的包,再加上本教程新增的五个:邮件模块、BullMQ 及其 Nest 模块与 Redis 客户端、发件箱、调度器和锁:

$ npm i -g @nestjs/cli
$ nest new notes-api --minimal
$ cd notes-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
$ npm i --save @nestjs/mail @nestjs/bullmq bullmq ioredis @nestjs/outbox @nestjs/schedule @nestjs/locks
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite

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

  • src/main.ts 和 drizzle.config.ts
  • src/auth/、src/users/、src/notes/ 和 src/health/ 下的所有内容,以及 src/database/schema.ts
  • test/refresh-token.store.e2e-spec.ts

略去 JWT 教程的 drizzle/ 目录,因为后续步骤会修改 schema 并为它整体生成一个迁移;也略去 test/notes.e2e-spec.ts,它把应用跑在 PGlite 上:从现在起应用还需要 Redis,而本教程末尾的测试会针对这两个服务器运行应用。把测试脚本加到 package.json:

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

BullMQ 把任务保存在 Redis 中。在 JWT 教程的 PostgreSQL 容器旁边再运行一个:

$ docker run -d --name notes-redis -p 6379:6379 redis:7

把它的 URL 加到 .env,放在 DATABASE_URL 和 JWT_SECRET 旁边:

REDIS_URL=redis://localhost:6379

配置 schema 增加 Redis URL 和邮件设置。需要 SMTP_URL 却缺失时,应用会在启动阶段停下,而不是等到第一封邮件才失败:

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

export const envSchema = z
  .object({
    NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
    PORT: z.coerce.number().int().default(3000),
    DATABASE_URL: z.url(),
    // 用于签名访问令牌:至少 32 字节。
    JWT_SECRET: z.string().min(32),
    // 允许调用 API 的浏览器来源,以逗号分隔。默认为空。
    CORS_ORIGINS: z
      .string()
      .default('')
      .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
      .pipe(z.array(z.url())),
    // 队列的任务和锁。路径中的数据库编号:redis://host:6379/1
    REDIS_URL: z.url(),
    // `log` 把每封邮件写入控制台而不发送。
    MAIL_TRANSPORT: z.enum(['log', 'smtp']).default('log'),
    SMTP_URL: z.url().optional(),
    MAIL_FROM: z.string().default('Notes <notes@example.com>'),
  })
  .refine((env) => env.MAIL_TRANSPORT !== 'smtp' || env.SMTP_URL, {
    message: 'SMTP_URL is required when MAIL_TRANSPORT is "smtp"',
    path: ['SMTP_URL'],
  });

export type Env = z.infer<typeof envSchema>;

schema 中新增一张表,位于 notes 之后。每一行都是工作进程发出的一封邮件,以使它唯一的值作为键;后续小节会解释它的列:

src/database/schema.ts
// ...

// 工作进程发出的每封邮件一行,以使它唯一的值作为键:
// `welcome-<user id>`,或 `digest-<user id>-<day>`。
export const sentEmails = pgTable('sent_emails', {
  key: text('key').primaryKey(),
  userId: uuid('user_id')
    .notNull()
    .references(() => users.id, { onDelete: 'cascade' }),
  // 工作进程接手这封邮件的时间;5 分钟后另一个工作进程可以接手。
  claimedAt: at('claimed_at').notNull().defaultNow(),
  // 邮件服务器接受之前为 null。
  sentAt: at('sent_at'),
});

像 JWT 教程那样生成迁移并应用它:

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

根模块注册本教程新增的全部内容。每个部分都会在使用它的小节中解释:

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 { BullModule } from '@nestjs/bullmq';
import { DrizzleModule, getDrizzleToken } from '@nestjs/drizzle';
import { LocksModule } from '@nestjs/locks';
import { MailModule } from '@nestjs/mail';
import { createObserveModule } from '@nestjs/observe';
import { OutboxModule, OutboxStorage } from '@nestjs/outbox';
import { fromDrizzle, PostgresOutboxStore } from '@nestjs/outbox/postgres';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { EmailsModule } from './emails/emails.module.js';
import { mailTransport } from './emails/mail-transport.js';
import { HealthModule } from './health/health.module.js';
import { NotesModule } from './notes/notes.module.js';
import { RedisLockStore } from './redis/redis-lock.store.js';
import { RedisModule } from './redis/redis.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: 'notes-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: 'notes-api',
          audience: 'notes-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    ThrottlerModule.forRoot([
      // 按 IP 地址,作用于每条路由。
      { name: 'default', ttl: minutes(1), limit: 100 },
      // 按邮箱和 IP 地址,作用于请求体中指明账号的地方。
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    MailModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        transport: mailTransport(config.get('MAIL_TRANSPORT', { infer: true }), config.get('SMTP_URL', { infer: true })),
        from: config.get('MAIL_FROM', { infer: true }),
      }),
    }),
    BullModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        connection: { url: config.get('REDIS_URL', { infer: true }) },
      }),
    }),
    OutboxModule.forRoot(),
    ScheduleModule.forRoot(),
    LocksModule.forRoot(),
    RedisModule,
    UsersModule,
    AuthModule,
    NotesModule,
    EmailsModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    {
      // 发件箱的消息,放在应用的数据库中,使用它们自己的 schema(nest_outbox)。
      provide: PostgresOutboxStore,
      inject: [getDrizzleToken(), OutboxStorage],
      useFactory: (db: NodePgDatabase, outboxStorage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
    },
    // @OnOneInstance() 的锁,保存在 Redis 中。
    RedisLockStore,
  ],
})
export class AppModule {}
  • MailModule 负责发送邮件(编写邮件)。
  • BullModule.forRootAsync() 根据 REDIS_URL 把 BullMQ 连接到 Redis。URL 路径中的数据库编号(例如 redis://localhost:6379/1)能让这些任务与服务器上的其他内容隔离开。
  • OutboxModule 和 PostgresOutboxStore 把欢迎邮件从注册事务带到队列(把欢迎邮件交给队列)。
  • ScheduleModule、LocksModule、RedisModule 和 RedisLockStore 让摘要在单个实例上运行(在单个实例上发送摘要)。

编写邮件

MailModule 接受一个 transport(传输方式,即邮件离开应用的方式)和一个默认发件人。从环境中选择 transport,这样同一份构建可以在任何地方运行:

src/emails/mail-transport.ts
import { LogMailTransport, SmtpTransport, type MailTransport } from '@nestjs/mail';

/** 开发环境用 `log`:每封邮件都写入控制台。生产环境用 `smtp`。 */
export function mailTransport(kind: 'log' | 'smtp', smtpUrl?: string): MailTransport {
  return kind === 'smtp'
    ? new SmtpTransport({ url: smtpUrl!, pool: true }) // smtp://user:password@smtp.example.com:587
    : new LogMailTransport();
}

LogMailTransport 把每封邮件写入控制台,收件人和主题记在 log 级别,正文记在 debug 级别,并且不发送任何内容,这正是开发期间你想要的。SmtpTransport 自己实现 SMTP 协议,在 587 端口要求 STARTTLS,设置 pool: true 时会复用连接。在生产环境中发送 介绍了它的选项以及各 HTTP 服务商的 transport(Resend、Postmark、SendGrid、SES),其中任何一个都可以在这里取代它。

一封邮件就是一个 邮件类:一个提供者,其 render() 把带类型的数据转换为主题和正文。欢迎邮件接收用户:

src/emails/welcome.mail.ts
import { Injectable } from '@nestjs/common';
import { html, type Mailable } from '@nestjs/mail';
import type { User } from '../users/user.js';

@Injectable()
export class WelcomeMail implements Mailable<User> {
  render(user: User) {
    return {
      subject: 'Welcome to Notes',
      // `html` 会转义它插入的每个值。
      html: html`
        <p>Hi ${user.email},</p>
        <p>your account is ready. On the days you change notes, we'll send you a digest of them in the evening.</p>
      `,
    };
  }
}

摘要接收日期和当天改动过的笔记标题:

src/emails/digest.mail.ts
import { Injectable } from '@nestjs/common';
import { html, type Mailable } from '@nestjs/mail';

export interface Digest {
  /** UTC 日期,格式为 YYYY-MM-DD。 */
  day: string;
  titles: string[];
}

@Injectable()
export class DigestMail implements Mailable<Digest> {
  render({ day, titles }: Digest) {
    return {
      subject: `Your notes on ${day}`,
      // 标题是用户输入:`html` 会转义它们,因此标题无法注入标记。
      html: html`
        <p>You changed ${titles.length} ${titles.length === 1 ? 'note' : 'notes'} today:</p>
        <ul>
          ${titles.map((title) => html`<li>${title}</li>`)}
        </ul>
      `,
    };
  }
}

html 标签模板会转义它插入的每个值,所以标题为 <script> 的笔记到了邮件里会变成 &lt;script&gt;;而由嵌套 html 模板组成的数组(例如列表项)会按原样插入。邮件模块根据 HTML 推导出纯文本部分。较长的邮件也可以放在模板文件里,由 FileTemplateEngine 在每封邮件共享的布局中渲染:参见 编写订单确认邮件。

把邮件加入队列

邮件服务器接受一条消息要花几百毫秒,有时要几秒,有时干脆宕机。这些都不该发生在请求里。API 改为把 任务(job)加入队列,由 工作进程(worker)在后台发送邮件,服务器失败时重试。

生产者是一个小的提供者。每个任务携带的是 id,而不是邮箱地址,因此工作进程在运行时读取用户,始终发送到当前地址:

src/emails/email.jobs.ts
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import type { JobsOptions, Queue } from 'bullmq';

export const EMAILS_QUEUE = 'emails';

// 每种任务携带的内容:id,而不是用户的邮箱地址,因为地址可能在任务运行前改变。
export interface WelcomeJob {
  userId: string;
}
export interface DigestJob {
  userId: string;
  /** UTC 日期,格式为 YYYY-MM-DD。 */
  day: string;
}

/** 使一封邮件唯一的东西:它的任务 id、它在 `sent_emails` 中的行,以及它的幂等键。 */
export const welcomeKey = (userId: string) => `welcome-${userId}`;
export const digestKey = (userId: string, day: string) => `digest-${userId}-${day}`;

const jobOptions = {
  // 10 次尝试,间隔 2 秒且逐次翻倍:最后一次大约在首次之后 17 分钟执行。
  attempts: 10,
  backoff: { type: 'exponential', delay: 2_000 },
  // 已完成的任务保留下来以便查看:成功的保留一天,失败的保留一周。
  // 没有这些设置,Redis 会永远保留每个任务。
  removeOnComplete: { age: 24 * 3600, count: 10_000 },
  removeOnFail: { age: 7 * 24 * 3600 },
} satisfies JobsOptions;

@Injectable()
export class EmailJobs {
  constructor(@InjectQueue(EMAILS_QUEUE) private readonly queue: Queue) {}

  async welcome(userId: string): Promise<void> {
    const data: WelcomeJob = { userId };
    // id 已存在的任务不会被再次添加。
    await this.queue.add('welcome', data, { ...jobOptions, jobId: welcomeKey(userId) });
  }

  async digests(day: string, userIds: string[]): Promise<void> {
    await this.queue.addBulk(
      userIds.map((userId) => ({
        name: 'digest',
        data: { userId, day } satisfies DigestJob,
        opts: { ...jobOptions, jobId: digestKey(userId, day) },
      })),
    );
  }
}
  • attempts 与 backoff。 工作进程抛出错误时任务就算失败,BullMQ 会在退避时间之后再次运行它:2 秒、4 秒、8 秒,以此类推,十次尝试大约跨越 17 分钟。按你对邮件服务商故障的预期来设定。最后一次尝试之后,任务移入失败集合。
  • removeOnComplete 与 removeOnFail。 默认情况下 BullMQ 会把每个已完成的任务永远留在 Redis 中。这里已完成的任务一天后清除(或只保留最近的 10,000 个),失败的任务一周后清除,足够查看。时间以秒为单位。
  • jobId。 每封邮件都有一个键,例如 welcome-<user id>。把它用作任务的 id,当第一个任务仍在 Redis 中时,重复添加同一封邮件就变成空操作。一旦 removeOnComplete 把它清除,同一个 id 又能被再次添加,所以仅靠任务 id 并不能让邮件唯一:每封邮件只发送一次 中是由 sent_emails 表来保证的。BullMQ 拒绝整数 id,也拒绝大多数含 : 的 id,因此这里用短横线。

这些选项在每次 add() 时传入,而不是作为队列的默认值,这样它们就紧挨着所适用的任务。任务选项 列出了其他选项,例如 delay 和 priority。

功能模块注册队列,以及后续小节中的提供者:

src/emails/emails.module.ts
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { UsersModule } from '../users/users.module.js';
import { DigestMail } from './digest.mail.js';
import { DigestRepository } from './digest.repository.js';
import { DigestScheduler } from './digest.scheduler.js';
import { EMAILS_QUEUE, EmailJobs } from './email.jobs.js';
import { EmailProcessor } from './email.processor.js';
import { SentEmailsRepository } from './sent-emails.repository.js';
import { WelcomeMail } from './welcome.mail.js';
import { WelcomeMailHandler } from './welcome-mail.handler.js';

@Module({
  imports: [BullModule.registerQueue({ name: EMAILS_QUEUE }), UsersModule],
  providers: [
    EmailJobs,
    // 设置 MAIL_WORKER=off 时,本进程只添加任务,把执行留给其他进程。
    ...(process.env.MAIL_WORKER === 'off' ? [] : [EmailProcessor]),
    WelcomeMail,
    DigestMail,
    DigestRepository,
    SentEmailsRepository,
    DigestScheduler,
    WelcomeMailHandler,
  ],
  exports: [EmailJobs],
})
export class EmailsModule {}

把欢迎邮件交给队列

注册流程会插入用户。欢迎任务应该加在哪里?

  • 在数据库事务内、提交之前: Redis 不属于这个事务。工作进程可能在提交前就取走任务,然后找不到用户。或者任务添加之后事务回滚,于是有人为一个并不存在的账号收到了欢迎邮件。
  • 在提交之后: 任务总能找到用户。但这两次写入仍然分属两个系统,没有任何东西把它们绑在一起。提交与 queue.add() 之间若发生崩溃或部署,邮件就丢了;而 Redis 宕机时,注册会为一个已经创建的账号返回 500,用户可能再试一次。

对欢迎邮件而言,第二种做法加上捕获并记录错误,可能就足够了。当任务绝不能丢失时,请使用 事务性发件箱。outbox.add() 把一条消息写入同一数据库中的表,与用户处于同一个事务,因此两者要么都提交,要么都不提交。随后由中继进程把已提交的消息交给处理器,并带退避地重试,直到成功:

src/auth/credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { Outbox } from '@nestjs/outbox';
import type { NodePgDatabase, NodePgTransaction } from 'drizzle-orm/node-postgres';
import type { UserSignedUp } from '../emails/welcome-mail.handler.js';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class CredentialsService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly usersRepository: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
    private readonly outbox: Outbox<NodePgTransaction<{}>>,
  ) {}

  async register(email: string, password: string): Promise<User> {
    const passwordHash = await this.passwordHasher.hash(password);
    const user = await this.db.transaction(async (tx) => {
      const user = await this.usersRepository.create(email, passwordHash, tx);
      if (!user) {
        throw new ConflictException('Email already registered');
      }
      // 同一个事务:消息与用户一起提交,或者都不提交。
      await this.outbox.add<UserSignedUp>(tx, { topic: 'user.signed-up', payload: { userId: user.id } });
      return user;
    });
    this.outbox.notify(); // 现在就交给队列,而不是等下一次轮询
    return user;
  }

  /** 用户;邮箱或密码不正确时为 `null`。 */
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // 账号不存在时,verify() 会校验一个假哈希,
    // 使响应时间不泄露哪些邮箱已注册。
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found) {
      return null;
    }
    if (this.passwordHasher.needsRehash(found.passwordHash)) {
      await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
    }
    return found.user;
  }
}

UsersRepository.create() 接受事务,因此插入就在事务中执行:

src/users/users.repository.ts
// ...
  /** 新用户;邮箱已被占用时为 `null`。把事务作为 `db` 传入即可在其中插入。 */
  async create(email: string, passwordHash: string, db: Pick<NodePgDatabase, 'insert'> = this.db): Promise<User | null> {
    // 一条语句:使用同一邮箱的两次注册不可能都成功。
    const [user] = await db
      .insert(users)
      .values({ email: normalize(email), passwordHash })
      .onConflictDoNothing({ target: users.email })
      .returning(columns);
    return user ?? null;
  }

处理器在提交之后运行,并添加任务:

src/emails/welcome-mail.handler.ts
import { Injectable } from '@nestjs/common';
import { OnOutboxMessage } from '@nestjs/outbox';
import { EmailJobs } from './email.jobs.js';

export interface UserSignedUp {
  userId: string;
}

@Injectable()
export class WelcomeMailHandler {
  constructor(private readonly emailJobs: EmailJobs) {}

  // 注册提交之后运行。Redis 宕机时,发件箱会带退避地重试。
  @OnOutboxMessage('user.signed-up', { consumer: 'welcome-mail' })
  async queueWelcome({ userId }: UserSignedUp) {
    await this.emailJobs.welcome(userId);
  }
}
  • 无需创建任何东西。 在根模块中注册的 PostgresOutboxStore 把消息保存在自己的 schema nest_outbox 中,在非生产环境下它于启动时创建并迁移该 schema。在生产环境中,把它的迁移作为发布步骤执行:npx @nestjs/outbox migrate,与 npx drizzle-kit migrate 并列(参见 把消息保存在你的数据库中)。
  • 传事务,绝不传数据库。 outbox.add() 拒绝数据库本身,因为对它的写入会自行提交。
  • notify() 在提交之后立刻唤醒中继进程。没有它,消息会在下一次轮询时(一秒之后)才发出。
  • Redis 宕机只是延迟,不是错误。 当 queue.add() 失败或挂起时,中继把每次尝试计为失败,并带退避地重试,默认 20 次,跨越 30 到 60 分钟。注册早已返回 201。始终不成功的消息会移入发件箱的死信(参见 重试与死信队列)。
  • 两次无害。 中继至少投递一次,处理器的收件箱(consumer)会跳过大多数重复。漏过来的那一次添加的是一个 id 已存在的任务,BullMQ 会忽略它。

每封邮件只发送一次

一个任务可能执行不止一次。BullMQ 会重试失败的任务,即使它的邮件在失败之前已经发出;当工作进程停止续租它的锁时(例如崩溃之后,或事件循环长时间停顿之后),BullMQ 会再次运行该任务。生产者也可能把同一封邮件添加两次:发件箱至少投递一次,而摘要在其任务被清除之后可能再次入队。这些情况都不能让用户收到第二封邮件。

sent_emails 表按键记录每封邮件。工作进程发送之前,用一条条件语句 认领(claim)这封邮件,并在邮件服务器接受之后把它记为已发送:

src/emails/sent-emails.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, isNull, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { sentEmails } from '../database/schema.js';

export class EmailInProgressError extends Error {}

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

  /**
   * 除非该键对应的邮件已经发送,否则运行 `send`。两个工作进程同时运行同一封邮件
   * 时,其中一个发送它;另一个抛出 EmailInProgressError,而它的重试会发现邮件
   * 已发送。
   */
  async sendOnce(key: string, userId: string, send: () => Promise<unknown>): Promise<'sent' | 'already sent'> {
    if (!(await this.claim(key, userId))) {
      const [row] = await this.db.select({ sentAt: sentEmails.sentAt }).from(sentEmails).where(eq(sentEmails.key, key));
      if (row?.sentAt) {
        return 'already sent';
      }
      throw new EmailInProgressError(`Email ${key} is being sent by another worker`);
    }
    try {
      await send();
    } catch (error) {
      // 归还认领,这样任务的重试可以再次取得它。
      await this.db.delete(sentEmails).where(and(eq(sentEmails.key, key), isNull(sentEmails.sentAt)));
      throw error;
    }
    await this.db.update(sentEmails).set({ sentAt: sql`now()` }).where(eq(sentEmails.key, key));
    return 'sent';
  }

  /** 一条语句:插入认领,或接管崩溃的工作进程留下的认领。 */
  private async claim(key: string, userId: string): Promise<boolean> {
    const claimed = await this.db
      .insert(sentEmails)
      .values({ key, userId })
      .onConflictDoUpdate({
        target: sentEmails.key,
        set: { claimedAt: sql`now()` },
        setWhere: sql`${sentEmails.sentAt} is null and ${sentEmails.claimedAt} < now() - interval '5 minutes'`,
      })
      .returning({ key: sentEmails.key });
    return claimed.length === 1;
  }
}
  • 认领是一条语句。 INSERT ... ON CONFLICT DO UPDATE ... WHERE 插入该行,或接管 5 分钟内无人完成的认领。两个工作进程争抢同一封邮件时,PostgreSQL 只让其中一个插入该行;另一个的语句会等这次插入提交,然后什么也不改。若先 SELECT 检查该行再 INSERT,两者都会通过:本教程末尾的测试展示了这一点。
  • 落败者不发送。 若邮件已标记为已发送,它的任务以 already sent 完成。若仍在发送中,任务抛出错误,BullMQ 几秒后的重试会发现它已发送。
  • 失败的发送会归还认领。 任务的下一次尝试会重新认领。否则,拒绝第一次尝试的邮件服务器会留下一个认领,把之后每一次重试阻塞 5 分钟。
  • 发送期间不保持任何事务打开。 认领自行提交,因此发送在邮件服务器耗时的整个期间不占用数据库连接,也不持有行锁。
  • 仍会留下一个窗口。 如果工作进程在邮件服务器接受邮件之后、UPDATE 之前崩溃,就会留下一个没有 sent_at 的认领。五分钟后重试会再次发送它,但带着相同的 idempotencyKey(见下文),因此重复邮件携带相同的 Message-ID,Gmail 等接收方据此把它丢弃。走 Resend 时,这个键就是服务商强制执行的幂等键。这已经是电子邮件能达到的、最接近「恰好一次」的程度。

工作进程是一个 处理器(processor):一个继承 WorkerHost 的提供者,BullMQ 对每个任务调用它的 process()(参见 消费者):

src/emails/email.processor.ts
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { MailError, Mailer } from '@nestjs/mail';
import { UnrecoverableError, type Job } from 'bullmq';
import { UsersRepository } from '../users/users.repository.js';
import { DigestMail } from './digest.mail.js';
import { DigestRepository } from './digest.repository.js';
import { digestKey, EMAILS_QUEUE, welcomeKey, type DigestJob, type WelcomeJob } from './email.jobs.js';
import { SentEmailsRepository } from './sent-emails.repository.js';
import { WelcomeMail } from './welcome.mail.js';

const sendOptions = (key: string) => ({
  // BullMQ 会重试任务:每次运行只尝试一次。
  retry: false as const,
  // 同一封邮件的重发保留它的 Message-ID。
  idempotencyKey: key,
  // 远短于 5 分钟的认领,因此没有哪次发送会比认领活得更久。
  signal: AbortSignal.timeout(60_000),
});

// 每个运行该工作进程的进程中,同时最多处理 5 个任务。
@Processor(EMAILS_QUEUE, { concurrency: 5 })
export class EmailProcessor extends WorkerHost {
  constructor(
    private readonly mailer: Mailer,
    private readonly usersRepository: UsersRepository,
    private readonly digestRepository: DigestRepository,
    private readonly sentEmails: SentEmailsRepository,
  ) {
    super();
  }

  async process(job: Job): Promise<string> {
    try {
      switch (job.name) {
        case 'welcome':
          return await this.welcome(job.data);
        case 'digest':
          return await this.digest(job.data);
        default:
          throw new UnrecoverableError(`Unknown job ${job.name}`);
      }
    } catch (error) {
      // 被拒绝的地址在下一次尝试也不会被接受:现在就让任务失败。
      if (error instanceof MailError && error.permanent) {
        throw new UnrecoverableError(error.message);
      }
      throw error;
    }
  }

  private async welcome({ userId }: WelcomeJob) {
    const user = await this.usersRepository.findById(userId);
    if (!user) {
      return 'user deleted';
    }
    const key = welcomeKey(userId);
    return this.sentEmails.sendOnce(key, userId, () =>
      this.mailer.send(WelcomeMail, { to: user.email, data: user, ...sendOptions(key) }),
    );
  }

  private async digest({ userId, day }: DigestJob) {
    const user = await this.usersRepository.findById(userId);
    const titles = await this.digestRepository.titlesOn(userId, day);
    if (!user || titles.length === 0) {
      return 'nothing to send';
    }
    const key = digestKey(userId, day);
    return this.sentEmails.sendOnce(key, userId, () =>
      this.mailer.send(DigestMail, { to: user.email, data: { day, titles }, ...sendOptions(key) }),
    );
  }
}
  • retry: false。 邮件模块默认对瞬时故障重试三次。BullMQ 已经在重试任务,跨越分钟而不是秒;两层都重试会让次数相乘。
  • idempotencyKey 就是邮件的键。邮件模块据此推导 Message-ID 头,因此同一封邮件的重发携带相同的值。
  • signal 在一分钟后中止发送,任务的重试会再试一次。认领持续 5 分钟,因此它必须比最长的一次发送更久:否则一次 SMTP 交换仅传输消息数据就可能长达 5 分钟,而第二个工作进程会在第一个仍在发送时接管认领。
  • UnrecoverableError 是 BullMQ 提供的:抛出它的任务立即失败,不再消耗剩余的尝试次数。permanent 标志被设置的邮件错误,例如 5xx SMTP 应答(550 User unknown),在下一次尝试同样不会成功。其他所有错误——4xx 应答、超时或连接中断——都会带退避地重试。
  • concurrency: 5 让一个进程同时发送五封邮件。每个运行该工作进程的进程再加五。
  • 用户在任务运行时读取。 期间被删除的用户什么也收不到,改了地址的用户会收到发往新地址的邮件。

在单个实例上发送摘要

每天 18:00 UTC,每位当天改动过笔记的用户都会收到一份摘要。两个查询,一个确定谁收到摘要,一个取摘要内容:

src/emails/digest.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, gte, lt } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { notes } from '../database/schema.js';

/** `date` 的 UTC 日期,格式为 YYYY-MM-DD。 */
export const utcDay = (date: Date) => date.toISOString().slice(0, 10);

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

  /** 在 `day` 改动过笔记的用户。 */
  async authorsOn(day: string): Promise<string[]> {
    const rows = await this.db.selectDistinct({ ownerId: notes.ownerId }).from(notes).where(changedOn(day));
    return rows.map((row) => row.ownerId);
  }

  /** 用户在 `day` 改动过的笔记标题,最早的在前。 */
  async titlesOn(userId: string, day: string): Promise<string[]> {
    const rows = await this.db
      .select({ title: notes.title })
      .from(notes)
      .where(and(eq(notes.ownerId, userId), changedOn(day)))
      .orderBy(asc(notes.updatedAt))
      .limit(50);
    return rows.map((row) => row.title);
  }
}

function changedOn(day: string) {
  const start = new Date(`${day}T00:00:00Z`);
  const end = new Date(start.getTime() + 24 * 3600 * 1000);
  return and(gte(notes.updatedAt, start), lt(notes.updatedAt, end));
}

定时任务为每位用户排入一个邮件任务。入队很快,之后每份摘要都有自己的重试:邮件服务器拒绝某个地址,不会拖慢别人的摘要:

src/emails/digest.scheduler.ts
import { Injectable, Logger } from '@nestjs/common';
import { OnOneInstance } from '@nestjs/locks';
import { Cron } from '@nestjs/schedule';
import { DigestRepository, utcDay } from './digest.repository.js';
import { EmailJobs } from './email.jobs.js';

@Injectable()
export class DigestScheduler {
  private readonly logger = new Logger(DigestScheduler.name);

  constructor(
    private readonly digestRepository: DigestRepository,
    private readonly emailJobs: EmailJobs,
  ) {}

  // 每天 18:00 UTC,在应用的单个实例上执行。
  @Cron(process.env.DIGEST_CRON ?? '0 18 * * *', { name: 'daily-digest', timeZone: 'UTC' })
  @OnOneInstance({ key: 'mail:daily-digest' })
  async enqueueDigests(): Promise<number> {
    const day = utcDay(new Date());
    const userIds = await this.digestRepository.authorsOn(day);
    // 每位用户一个任务:缓慢或失败的发送不会拖慢别人的摘要。
    await this.emailJobs.digests(day, userIds);
    this.logger.log(`Digests of ${day}: ${userIds.length} queued`);
    return userIds.length;
  }
}

@nestjs/schedule 会在应用的每个实例上运行该方法。有三个实例,就会有三个实例查询笔记并排入相同的任务。任务 id 会让多出来的任务变成空操作,但这项工作仍会执行三次;而对于没有天然键的任务(例如调用另一个服务),它会真的执行三次。@OnOneInstance() 让该方法只在一个实例上运行:调度最先触发的那个实例取得该任务的租约,在运行期间持续续租,并在每次触发时执行,其余实例跳过自己的触发。若持有者死亡,另一个实例会在租约过期后的第一次触发时接管,也就是 30 秒之后。让每个任务只在一个实例上运行 解释了租约,以及为什么错过的触发不会被补做。

cron 表达式来自 process.env.DIGEST_CRON,在文件加载时读取,早于 ConfigModule 读取 .env。请像 试一试 小节那样,在进程的环境中设置它,以便不必等到晚上就能看到摘要。

各实例通过共享的 锁存储(lock store)就谁持有租约达成一致。@nestjs/locks 定义了契约 LockStore,在你注册一个实现之前把锁保存在内存中,而内存锁只能排除同一进程内的调用者:当 NODE_ENV 设为 production 时,它会拒绝以这种方式启动。这个 API 已经有 Redis,所以锁存储用 Redis 上的存储 中的那个,配一个独立的 ioredis 客户端:

src/redis/redis.module.ts
import { Global, Inject, Module, type OnApplicationShutdown } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Redis } from 'ioredis';
import type { Env } from '../config.js';

export const REDIS = Symbol('REDIS');

@Global()
@Module({
  providers: [
    {
      provide: REDIS,
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => new Redis(config.get('REDIS_URL', { infer: true })),
    },
  ],
  exports: [REDIS],
})
export class RedisModule implements OnApplicationShutdown {
  constructor(@Inject(REDIS) private readonly redis: Redis) {}

  // 在 onModuleDestroy() 之后,此时运行中的任务已结束并归还锁。
  async onApplicationShutdown() {
    await this.redis.quit();
  }
}

锁存储在该客户端上实现 LockStore:

src/redis/redis-lock.store.ts
import { Inject, Injectable } from '@nestjs/common';
import { LocksStorage, type LockAcquireResult, type LockStore } from '@nestjs/locks';
import type { Redis } from 'ioredis';
import { REDIS } from './redis.module.js';

// 无人持有时取得锁,按 Redis 的时钟过期,并从一个永不回退的计数器
// 取一个围栏令牌(fencing token)。返回该令牌,或 0。
const ACQUIRE = `
if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then
  return redis.call('INCR', KEYS[2])
end
return 0
`;

// 如果锁仍是我们的,就续租。
const RENEW = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('PEXPIRE', KEYS[1], ARGV[2])
end
return 0
`;

// 如果锁仍是我们的,就删除它。
const RELEASE = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0
`;

/** 围栏计数器所在的位置;任何锁的键都不能与它同名。 */
const FENCING_COUNTER = 'locks:fencing-token';

@Injectable()
export class RedisLockStore implements LockStore {
  constructor(
    @Inject(REDIS) private readonly redis: Redis,
    storage: LocksStorage,
  ) {
    storage.registerSource(this);
  }

  async acquire(key: string, owner: string, ttl: number): Promise<LockAcquireResult> {
    const token = Number(await this.redis.eval(ACQUIRE, 2, this.key(key), FENCING_COUNTER, owner, ttl));
    return token > 0 ? { acquired: true, fencingToken: token } : { acquired: false };
  }

  async renew(key: string, owner: string, ttl: number): Promise<boolean> {
    return (await this.redis.eval(RENEW, 1, this.key(key), owner, ttl)) === 1;
  }

  async release(key: string, owner: string): Promise<boolean> {
    return (await this.redis.eval(RELEASE, 1, this.key(key), owner)) === 1;
  }

  private key(key: string) {
    return `locks:key:${key}`;
  }
}

每个方法都是一个 Lua 脚本,Redis 会原子地执行它:无论多少个实例在同一时刻尝试获取租约,只有一个能拿到。请为那个 Redis 开启持久化并设置 maxmemory-policy noeviction:被淘汰的锁就是丢失的锁,而围栏计数器绝不能回退。RedisLockStore 在根模块中注册,紧挨着发件箱的存储。

在不丢失邮件的前提下关闭

部署会用 SIGTERM 停止每个旧实例。来自 JWT 教程的 main.ts 已经调用了 app.enableShutdownHooks(),本教程的每个部分都用到它启用的钩子:

  1. 在第一阶段,BullMQ 的工作进程关闭:它们不再接受新任务,并等待正在运行的任务完成。摘要的租约被归还,因此另一个实例的下一次触发无需等待 30 秒就能取得它;发件箱中继则完成它正在发布的内容。
  2. 在最后阶段,队列关闭它们的 Redis 连接,锁存储的客户端退出,数据库连接池结束。正在收尾的任务所需的任何东西,都不会在它完成之前被关闭。

平台会等待这个过程,但不会永远等:Kubernetes 默认在 SIGTERM 之后 30 秒发送 SIGKILL(terminationGracePeriodSeconds)。请把它设得比你最长的任务还久。任务执行到一半被杀的进程不会丢失任何东西:BullMQ 会察觉该任务的锁已过期,并在另一个工作进程上重新运行它(参见 BullMQ 文档中的 停滞任务),而可能已经发出的那封邮件由 sent_emails 负责。

在工作进程自己的进程中运行

到目前为止,一切都在一个进程中运行:API、工作进程、中继和调度器。这是个好的开始。一旦发送邮件开始与请求争抢 CPU,或者你想分别扩缩容这两者,就把工作进程放进自己的进程。应用上下文会运行相同的模块,但不带 HTTP 服务器:

src/worker.ts
import { NestFactory } from '@nestjs/core';
import { AppModule, ObserveInstrument } from './app.module.js';

// 同一个应用,但不带 HTTP 服务器:它运行邮件任务、发件箱中继和摘要。
const app = await NestFactory.createApplicationContext(AppModule, { instrument: ObserveInstrument });
app.enableShutdownHooks();

为它往 package.json 中加一个脚本:

"start:worker": "node dist/worker"

然后用 MAIL_WORKER=off 启动 API 实例,这会让 EmailProcessor 不出现在 EmailsModule 中(它在模块文件加载时读取,和 DIGEST_CRON 一样,所以要设在环境里),再用 npm run start:worker 启动工作进程。API 实例添加任务,工作进程发送它们。发件箱中继和摘要调度器可以运行在任一种进程中:中继通过 PostgreSQL 中的租约分摊工作,而摘要无论在哪种进程中都只在一个实例上运行。

试一试

构建并启动应用,把摘要改成每十秒一次而不是每晚一次(六字段表达式以秒开头):

$ npm run build
$ DIGEST_CRON='*/10 * * * * *' npm run start:prod

启动时,发件箱和锁会记录各自的存储,首次启动时发件箱的存储会创建它的 schema:

LOG [OutboxModule] OutboxStorage: PostgresOutboxStore
LOG [LocksModule] LocksStorage: RedisLockStore
LOG [OutboxModule] PostgresOutboxStore: migrated schema "nest_outbox" to version 1.

注册。响应会在任何邮件发出之前返回(令牌已缩写):

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}

片刻之后,工作进程发送欢迎邮件,日志 transport 把它写入控制台:

LOG [LogMailTransport] "Welcome to Notes" to ada@example.com
DEBUG [LogMailTransport] Hi ada@example.com,

your account is ready. On the days you change notes, we'll send you a digest of them in the evening.

添加两条笔记,其中一条的标题里带标记:

$ TOKEN=eyJhbGciOiJIUzI1NiIs...
$ curl localhost:3000/notes -H "Authorization: Bearer $TOKEN" --json '{"title":"Plan the trip"}'
$ curl localhost:3000/notes -H "Authorization: Bearer $TOKEN" --json '{"title":"Fix the <script> tag"}'

下一次触发时,该实例取得摘要的租约,并把 Ada 的摘要排入队列。纯文本部分按 Ada 所写的原样显示标题;在 HTML 部分中,标题被转义了:

LOG [Locks] DigestScheduler.enqueueDigests runs on this instance (lease "mail:daily-digest:owner", fencing token 1)
LOG [DigestScheduler] Digests of 2026-11-19: 1 queued
LOG [LogMailTransport] "Your notes on 2026-11-19" to ada@example.com
DEBUG [LogMailTransport] You changed 2 notes today:

- Plan the trip
- Fix the <script> tag

从另一个终端启动第二个实例。它的触发被跳过,因为第一个实例持有租约:

$ PORT=3001 DIGEST_CRON='*/10 * * * * *' npm run start:prod
DEBUG [Locks] Skipped DigestScheduler.enqueueDigests: it runs on another instance
DEBUG [Locks] Skipped DigestScheduler.enqueueDigests: it runs on another instance

第一个实例每十秒继续把 Ada 的摘要入队,却没有第二份摘要发出:任务的 id 仍在 Redis 中,所以 BullMQ 不会再次添加它,该任务只运行了一次。每封邮件都只发送了一次:

$ docker exec notes-db psql -U postgres -d notes -c "SELECT key, sent_at FROM sent_emails"
                          key                           |            sent_at
--------------------------------------------------------+-------------------------------
 welcome-43a07bfa-3964-429c-b940-1d592c4d0f6a           | 2026-11-19 22:15:13.292295+00
 digest-43a07bfa-3964-429c-b940-1d592c4d0f6a-2026-11-19 | 2026-11-19 22:15:20.026325+00

最后,停掉 Redis 再注册一次。注册依然成功,和之前一样快:

$ docker stop notes-redis
$ curl -s -o /dev/null -w '%{http_code} in %{time_total}s\n' localhost:3000/auth/sign-up --json '{"email":"grace@example.com","password":"correct horse battery"}'
201 in 0.434314s

发件箱无法把消息交给队列,于是重试。摘要的触发也失败了,因为锁存储没有应答,于是被跳过;ioredis 还会记录被拒绝的连接。再次启动 Redis,欢迎邮件就发出了:

WARN [OutboxRelay] Retrying user.signed-up 01a1f5e1-0d77-7110-8846-f7efc7ed9ad8 in 772ms (attempt 1 of 20 failed): OutboxPublishTimeoutError: Publish did not settle within 10000ms
ERROR [Scheduler] Error: DigestScheduler.enqueueDigests did not run: the lock store failed (RedisLockStore.acquire() for the lock "mail:daily-digest:owner" did not answer within 10000ms (storeTimeout))
$ docker start notes-redis
LOG [LogMailTransport] "Welcome to Notes" to grace@example.com

测试它

测试让真实的应用连接真实的 PostgreSQL 服务器——通过连接池,使同一任务的两次运行真正竞争——以及真实的 Redis,BullMQ 在其中运行任务。只替换投递环节:来自 @nestjs/mail 的 InMemoryMailTransport 保留它收到的每封邮件,并提供查找某一封的辅助方法,failNext() 则让下一次发送失败(参见 测试)。用一个小的子类还能把下一次发送挂起不放,就像缓慢的邮件服务器那样。

Vitest 配置把应用指向测试自己的 Redis 数据库,并把摘要的时间表移到一个测试运行期间永远不会到来的日期,因为测试会自己调用它:

vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
      // 测试自己的 Redis 数据库:它们会清空它。
      REDIS_URL: process.env.TEST_REDIS_URL ?? 'redis://localhost:6379/15',
      // 2 月 29 日凌晨 3 点:测试会自己运行摘要。
      DIGEST_CRON: '0 3 29 2 *',
    },
  },
});

这些测试检查欢迎邮件、同一任务同时运行三次、重试与被拒、两个实例上的摘要,以及关闭流程:

test/emails.e2e-spec.ts
import { setTimeout as sleep } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getQueueToken } from '@nestjs/bullmq';
import { getDrizzleToken } from '@nestjs/drizzle';
import { InMemoryMailTransport, MailSmtpError, MailTransport, type MailMessage } from '@nestjs/mail';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import type { Queue } from 'bullmq';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Redis } from 'ioredis';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { sentEmails, users } from '../src/database/schema.js';
import { DigestMail } from '../src/emails/digest.mail.js';
import { DigestScheduler } from '../src/emails/digest.scheduler.js';
import { EMAILS_QUEUE, EmailJobs, welcomeKey } from '../src/emails/email.jobs.js';
import { WelcomeMail } from '../src/emails/welcome.mail.js';

/** 保留邮件,并能像缓慢的邮件服务器那样把下一次发送挂起不放。 */
class Mailbox extends InMemoryMailTransport {
  private gate?: { started: () => void; released: Promise<void> };

  holdNext() {
    let started!: () => void;
    let release!: () => void;
    const sending = new Promise<void>((resolve) => (started = resolve));
    this.gate = { started, released: new Promise((resolve) => (release = resolve)) };
    return { sending, release };
  }

  override async send(message: MailMessage) {
    const gate = this.gate;
    this.gate = undefined;
    gate?.started();
    await gate?.released;
    return super.send(message);
  }
}

// 带连接池的真实 PostgreSQL,使同一任务的两次运行真正竞争。
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('Emails (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  const mailbox = new Mailbox();
  let app: NestNodeApplication;
  let queue: Queue;

  /** 应用的一个实例,使用自己的连接池。多个实例共享队列和锁。 */
  async function start() {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(drizzle({ client: new Pool({ connectionString: url }) }))
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .overrideProvider(MailTransport)
      .useValue(mailbox)
      .compile();
    const instance = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await instance.init();
    return instance;
  }

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, refresh_tokens CASCADE`);
    await db.execute(sql`DROP SCHEMA IF EXISTS nest_outbox CASCADE`); // 存储会重新创建它
    // 上次运行残留的任务和锁会在启动时被处理。
    const redis = new Redis(process.env.REDIS_URL!);
    await redis.flushdb();
    await redis.quit();
    app = await start();
    queue = app.get<Queue>(getQueueToken(EMAILS_QUEUE));
  });

  afterAll(() => db.$client.end());
  beforeEach(() => mailbox.clear());

  let clients = 0;

  async function signUp(email: string) {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      remoteAddress: `10.0.0.${++clients}`, // 注册按 IP 地址限速
    });
    expect(res.statusCode).toBe(201);
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  /** 直接插入的用户,因此不会为他们排入欢迎任务。 */
  async function createUser(email: string) {
    const [user] = await db.insert(users).values({ email, passwordHash: 'unused' }).returning();
    return user.id;
  }

  /** 等待任务完成并返回它。 */
  function finished(id: string) {
    return vi.waitUntil(
      async () => {
        const job = await queue.getJob(id);
        return job?.finishedOn ? job : undefined;
      },
      { timeout: 10_000 },
    );
  }

  it('sends a welcome email after sign-up, outside the request', async () => {
    await signUp('ada@example.com');

    const mail = await vi.waitUntil(() => mailbox.find({ to: 'ada@example.com', mail: WelcomeMail }));
    expect(mail.subject).toBe('Welcome to Notes');
  });

  it('sends one email, however many times its job runs at once', async () => {
    const userId = await createUser('bob@example.com');
    const { sending, release } = mailbox.holdNext(); // 第一次发送会花一点时间
    const options = { attempts: 3, backoff: { type: 'fixed', delay: 500 } };

    // 任务的三个副本:一次重新投递,或第一个任务被清除后又添加的任务。
    const jobs = await Promise.all([1, 2, 3].map(() => queue.add('welcome', { userId }, options)));
    await sending;
    await sleep(200); // 另外两个副本在此期间运行
    release();
    const results = await Promise.all(jobs.map((job) => finished(job.id!)));

    expect(results.map((job) => job.returnvalue).sort()).toEqual(['already sent', 'already sent', 'sent']);
    expect(results.map((job) => job.attemptsMade).sort()).toEqual([1, 2, 2]); // 两个副本等待了第一个
    expect(mailbox.filter({ to: 'bob@example.com' })).toHaveLength(1);
  });

  it('retries a send that failed', async () => {
    mailbox.failNext(new MailSmtpError('DATA', { code: 451, text: 'Try again later' }));
    const userId = await createUser('carol@example.com');

    await app.get(EmailJobs).welcome(userId);
    const job = await finished(welcomeKey(userId));

    expect(job.attemptsMade).toBe(2); // 2 秒后的第二次尝试把它发了出去
    mailbox.assertSent({ to: 'carol@example.com', mail: WelcomeMail });
  });

  it('fails a send that the mail server refuses, without retrying', async () => {
    mailbox.failNext(new MailSmtpError('RCPT TO', { code: 550, text: 'User unknown' }));
    const userId = await createUser('nobody@example.com');

    await app.get(EmailJobs).welcome(userId);
    const job = await finished(welcomeKey(userId));

    expect(await job.getState()).toBe('failed');
    expect(job.attemptsMade).toBe(1);
    const claims = await db.select().from(sentEmails).where(eq(sentEmails.userId, userId));
    expect(claims).toEqual([]); // 已归还:以后可以再次发送
  });

  it('queues the digests on one instance, and escapes what users wrote', async () => {
    const dave = await signUp('dave@example.com');
    await app.inject({ method: 'POST', url: '/notes', headers: dave, payload: { title: 'Fix <script> tag' } });
    const other = await start();

    // 两个实例的调度器在同一时刻触发。
    const runs = await Promise.all([app, other].map((instance) => instance.get(DigestScheduler).enqueueDigests()));
    await other.close();

    expect(runs.filter((run) => run !== undefined)).toEqual([1]); // 另一个实例跳过了它
    const mail = await vi.waitUntil(() => mailbox.find({ to: 'dave@example.com', mail: DigestMail }));
    expect(mail.html).toContain('<li>Fix &lt;script&gt; tag</li>');
  });

  it('finishes the email in flight before it shuts down', async () => {
    const { sending, release } = mailbox.holdNext();
    const userId = await createUser('erin@example.com');
    await app.get(EmailJobs).welcome(userId);
    await sending;

    let closed = false;
    const closing = app.close().then(() => (closed = true));
    await sleep(500);
    expect(closed).toBe(false); // 正在等待工作进程的任务
    release();
    await closing;

    mailbox.assertSent({ to: 'erin@example.com' });
    const [claim] = await db.select().from(sentEmails).where(eq(sentEmails.userId, userId));
    expect(claim.sentAt).not.toBeNull();
  });
});
  • 任务的副本会竞争。 第一个副本的发送被挂起不放,因此另外两个在它进行中时运行:它们发现已被认领,第一次尝试失败,而它们的重试发现邮件已发送。attemptsMade 表明竞争确实发生了。
  • 重试测试使用应用自己的任务选项。 451 应答是瞬时的,因此任务在 2 秒退避后再次运行,第二次尝试把邮件发了出去。
  • 两个实例,一次摘要运行。 两个实例的调度器同时触发,只有其中一个调用真正运行;另一个未运行就返回。
  • 关闭会等待进行中的任务,并且在 close() 完成之前,该邮件的行已被标记为已发送。

创建测试数据库,并用测试自己的 Redis 数据库编号运行测试,因为测试会清空它。两个测试文件使用同一个数据库,因此它们一个接一个地运行:

$ docker exec notes-db psql -U postgres -c "CREATE DATABASE notes_test"
$ TEST_DATABASE_URL=postgres://postgres:notes@localhost:5432/notes_test TEST_REDIS_URL=redis://localhost:6379/1 npm run test:e2e -- --no-file-parallelism

 Test Files  2 passed (2)
      Tests  11 passed (11)

把 sendOnce() 中的认领换成先 SELECT 该行、发送之后再 INSERT,「无论任务同时运行多少次都只发送一封邮件」这条测试就会失败:三个副本中有两个发出了邮件。

生产环境检查清单

JWT 教程 检查清单 中的一切都适用。针对邮件和任务,尤其注意:

  • 通过真实的 transport 发送。 设置 MAIL_TRANSPORT=smtp 和 SMTP_URL,或换成某个 HTTP 服务商的 transport。当 NODE_ENV=production 时,邮件模块会在启动时警告 LogMailTransport 不投递邮件。为发信域配置 SPF、DKIM 和 DMARC;邮件章节的检查清单 涵盖其余内容。
  • 为 Redis 开启持久化并设置 maxmemory-policy noeviction。 队列的任务和锁都存放在那里。被淘汰的任务就是一封永远发不出的邮件,而被淘汰的锁会让第二个实例也去运行摘要。
  • 在部署时应用发件箱的迁移,用 npx @nestjs/outbox migrate,与 npx drizzle-kit migrate 并列。当 NODE_ENV=production 时,存储不会在启动时迁移,并在其 schema 落后时拒绝启动。npx @nestjs/outbox status 可在 CI 中检查。
  • 让宽限期长于最长的任务,这样部署的 SIGTERM 能让正在发送的邮件发完。
  • 监控失败集合与死信。 用尽尝试次数的任务会在 BullMQ 的失败集合中保留一周,发件箱无法交出的消息会移入它的死信。对两者都设置告警。
  • 清理会增长的数据。 sent_emails 每封邮件增加一行,发件箱的收件箱每条消息增加一行:用定时任务删除旧行,保留的时间要长于任何重投窗口。笔记增多之后,为摘要的查询给 notes.updated_at 建索引。
  • 按服务商允许的速率发送。 BullMQ 的工作进程可以接受限速(参见 BullMQ 文档中的 限速);仅靠 concurrency 只能限制并行发送的数量,不能限制每秒发送量。
  • 为生产环境准备它自己的 Observe 密钥对,从项目的 API Keys 页面取得,作为 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET 放进 API 和工作进程的环境:start:prod 和 start:worker 不会加载 .env。NestJS Observe 随后会把邮件任务和摘要的 cron 运行记录为任务,在它们的耗时旁边给出队列等待时间、尝试次数和失败原因;而 任务静默(job silence)规则会在某个具名任务(例如摘要)超过你允许的时长没有上报时告警。imports 中 ObserveModule 位于 BullModule 之前,因此部署 SIGTERM 时仍在运行的任务也会被上报(参见 关闭)。

接下来

  • 用本教程搭好的邮件来验证邮箱地址和重置密码:认证。
  • 把邮件翻译成每位用户的语言:用客户的语言发送。
  • 在 PostgreSQL 而不是 Redis 上运行任务:可插拔后端。
  • 了解发件箱提供什么保证,以及它的中继如何在实例之间分摊工作:发件箱。
  • 避免长时间运行的定时任务与自身重叠,并为其写入加上围栏:分布式锁。