# 幂等键

`@nestjs/idempotency` 让路由、GraphQL mutation 与消息处理器都可以安全重试：每个 `Idempotency-Key` 只运行一次处理器，重试拿到的是它的结果。

一家猫粮与宠物用品网店的顾客，在火车上用手机 App 买了一袋三文鱼猫粮和猫砂。App 发出 `POST /orders/ord_1001/pay`。服务器通过支付服务商扣了款，但响应没能回到手机。App 分不清是请求丢了还是响应丢了，于是重试。没有防护时，重试会以两种方式之一出错：

- 它在第一个请求结束之后到达。订单已是 `paid`，于是顾客为一笔已经成功的支付收到一个错误。
- 它在第一个请求仍在等待支付服务商时到达。两个请求都通过了「订单是否仍是 pending？」的检查，卡被扣了两次。

**幂等键**（idempotency key）能同时解决两者。客户端为每次支付尝试生成一个唯一键，并在每次重试时通过 `Idempotency-Key` 头发出。服务器按每个键只运行一次处理器，保存结果，并用该结果回应每一次重试。`@nestjs/idempotency` 用一个装饰器 `@Idempotent()` 为 HTTP 路由、GraphQL mutation 与微服务处理器实现这套机制。它的 HTTP 行为遵循 IETF 的 [Idempotency-Key 头草案](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/)。

在本教程中，你将为支付端点加上幂等，教会手机 App 安全重试，把键迁移到 PostgreSQL（或 Redis），加密保存的凭据，保护 GraphQL mutation，并对发货服务消费的 `order.paid` 事件去重。

#### 前置条件

本教程从店铺的订单 API 出发，它已经具备：

- 一个 `OrdersModule`，含 `OrdersService` 与 `OrdersController`。`Order` 有 `id`、`userId`、`items`、以分为单位的 `total`，以及 `'pending'`、`'paid'`、`'shipped'` 或 `'refunded'` 的 `status`。
- 一个 `PaymentProviderClient`，包装支付服务商的 SDK。卡被拒时抛 402 `HttpException`，服务商宕机时抛 `ServiceUnavailableException`（503）。
- 一个 `AuthGuard`，校验 bearer 令牌并设置 `req.user`（见 [认证](/security/authentication#issue-tokens-to-the-mobile-app)），以及读取它的 `@CurrentUser()` 参数装饰器。
- 全局 `ValidationPipe`，以及一个以 `SHIPPING_SERVICE` 注册的、指向发货服务的 TCP 客户端。
- 数据存放在 PostgreSQL 中，通过 Drizzle 访问，数据库由 `@nestjs/drizzle` 注册（见 [Drizzle](/data/drizzle)）。用的是 TypeORM？[把键存进 PostgreSQL](/reliability/idempotency#store-keys-in-postgresql) 末尾给出了 TypeORM 版本。

这是我们需要保护的方法：

```typescript
@@filename(orders/orders.service)
async pay(orderId: string, user: User, dto: PayOrderDto): Promise<PaymentReceipt> {
  const order = this.ordersRepository.findOwned(orderId, user.id);
  if (order.status !== 'pending') {
    throw new ConflictException(`Order ${order.id} is already ${order.status}`);
  }
  const charge = await this.paymentProviderClient.charge({
    amount: order.total,
    paymentMethod: dto.paymentMethod,
    reference: order.id,
  });
  this.ordersRepository.markPaid(order.id);
  this.shipping.emit('order.paid', {
    eventId: `order-paid:${order.id}`,
    orderId: order.id,
  });

  return {
    orderId: order.id,
    receiptId: charge.id,
    amount: charge.amount,
    cardLast4: charge.cardLast4,
    paidAt: charge.createdAt,
  };
}
```

状态检查本身拦不住重复扣款：两个同时到达的请求都会在任意一个执行到 `markPaid()` 之前看到 `pending`。

安装该包：

```bash
$ npm i --save @nestjs/idempotency
```

#### 让支付端点具备幂等性

在根模块中注册一次 `IdempotencyModule`：

```typescript
@@filename(app.module)
import { Module } from '@nestjs/common';
import { IdempotencyModule } from '@nestjs/idempotency';
import type { User } from './orders/order.js';
import { OrdersModule } from './orders/orders.module.js';

@Module({
  imports: [
    IdempotencyModule.forRoot({
      // 在守卫之后运行，因此 req.user 已设置。键在不同用户之间永不冲突。
      scope: (req: { user?: User }) => req.user?.id,
    }),
    OrdersModule,
  ],
})
export class AppModule {}
```

该模块是全局的。它注册一个应用级拦截器，对没有标记 `@Idempotent()` 的处理器什么都不做，因此其他路由的行为不变。

`scope` 让每个用户的键拥有自己的命名空间。没有它，所有客户端共用一个命名空间，一个用户选的键可能重放另一个用户的凭据。有了它，Alice 与 Bob 都可以发送 `Idempotency-Key: 1`，而永远看不到对方的结果。因为守卫先于拦截器运行，`scope` 执行时 `req.user` 已经设置好，未认证的请求会在用掉一个键之前被拒绝。如果已登录用户调用了没有 `scope` 的 `@Idempotent()` 处理器，模块会记录一条警告，每个处理器只记一次。若共用命名空间是有意为之，例如以服务商事件 id 为键的 webhook，请设 `scope: false`。

现在标记处理器：

```typescript
@@filename(orders/orders.controller)
import { Body, Controller, Param, Post, UseGuards } from '@nestjs/common';
import { Idempotent } from '@nestjs/idempotency';
import { AuthGuard } from '../auth/auth.guard.js';
import { CurrentUser } from '../auth/current-user.decorator.js';
import { PayOrderDto } from './dto/pay-order.dto.js';
import type { User } from './order.js';
import { OrdersService } from './orders.service.js';

@Controller('orders')
@UseGuards(AuthGuard)
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Post(':id/pay')
  @Idempotent({ required: true })
  pay(
    @Param('id') id: string,
    @Body() dto: PayOrderDto,
    @CurrentUser() user: User,
  ) {
    return this.ordersService.pay(id, user, dto);
  }
}
```

`required: true` 会在处理器运行之前，以 400 `IDEMPOTENCY_KEY_REQUIRED` 错误拒绝没有键的请求。没有键的支付无法安全重试，因此拒绝它好过在无保护的情况下扣款。

下面是携带键的请求所经历的过程：

1. 拦截器计算请求的**指纹**（fingerprint）：对 scope、方法、URL（含订单 id）与请求体做 SHA-256 哈希，对象键按排序处理。
2. 它对**记录键**（record key）`<scope>:<key>`（例如 `usr_alice:5e0f6d0e-…`）原子地加锁。若记录已存在，处理器不运行（见下表）。处理器运行期间，拦截器持续续租该锁，因此慢处理器不会因重试而丢锁。
3. 处理器运行。结束时，锁变成一条保存响应的已完成记录：状态码、响应体，以及一份短白名单中的响应头（`Location`、`Content-Type`、`Content-Language`、`Content-Location`、`ETag` 与 `Last-Modified`），前提是处理器或中间件设置过它们。这些头描述的是被保存的响应体，因此带另一个 `Accept-Language` 发来的重试，拿到的仍是已保存响应体的 `Content-Language`。Cookie、CORS 与限流相关的头属于原始请求，永不重放。

此后每个同键请求会得到下列答案之一：

| 情况 | 响应 |
| -------------------------------------- | --------------------------------------------------------------------------------------- |
| 第一个请求仍在运行 | 409 `IDEMPOTENCY_KEY_IN_USE`，带 `Retry-After` 头 |
| 第一个请求已完成 | 已保存的状态与响应体，外加 `Idempotent-Replayed: true`。处理器不运行。 |
| 同键，但请求体或 URL 不同 | 422 `IDEMPOTENCY_KEY_REUSED` |

错误也可以被保存。[调整 TTL 与失败处理](/reliability/idempotency#tune-ttls-and-failure-handling)说明了哪些错误会保存。

由于拦截器是全局的，它运行在你的控制器与处理器的拦截器之外。保存的响应体正是客户端收到的内容，即序列化器与其他拦截器执行之后的产物，而重放会跳过所有这些。管道在它内部运行，因此 `ValidationPipe` 的 400 与任何其他客户端错误一样会被保存。其他全局拦截器则是另一回事，生产检查清单里有说明。

在你[把键存进 PostgreSQL](/reliability/idempotency#store-keys-in-postgresql) 之前，记录保存在内存中，使用的是默认的 `InMemoryIdempotencyStore`。开发时的单实例尚可，但 API 的每个实例都有各自的记录，重启即丢失。当 `NODE_ENV` 为 `production` 时，应用会拒绝以此为最终配置启动，并给出说明如何注册存储的错误。

#### 从手机 App 发送键

服务器只能对客户端一致发送的内容去重。App 遵循两条规则：

- 键在顾客点 **Pay** 时创建，而不是每次请求创建一个。该笔支付的每次重试都发送同一个键，即使 App 被杀掉并重启；因此键要与待处理的支付一起保存。
- 只有在顾客做出新决定时才创建新键，例如卡被拒后换一张卡。用旧键发送不同的请求体是 422。

```typescript
@@filename(mobile/pay-order)
export interface Receipt {
  orderId: string;
  receiptId: string;
  amount: number;
  cardLast4: string;
  paidAt: string;
}

export interface PendingPayment {
  orderId: string;
  paymentMethod: string;
  idempotencyKey: string;
}

export class PaymentError extends Error {
  constructor(
    readonly status: number,
    readonly body: { code?: string; message?: string },
  ) {
    super(body.message ?? `Payment failed with status ${status}`);
  }
}

// 在顾客点「Pay」时调用，并把结果与订单一起保存
// （例如存进 AsyncStorage）。重试（即使 App 重启后）复用它。
export function startPayment(orderId: string, paymentMethod: string): PendingPayment {
  return { orderId, paymentMethod, idempotencyKey: crypto.randomUUID() };
}

export async function payOrder(
  apiUrl: string,
  token: string,
  payment: PendingPayment,
  maxAttempts = 5,
): Promise<Receipt> {
  for (let attempt = 1; ; attempt++) {
    const backoff = 250 * 2 ** (attempt - 1);
    let res: Response;
    try {
      res = await fetch(`${apiUrl}/orders/${payment.orderId}/pay`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Idempotency-Key': payment.idempotencyKey,
        },
        body: JSON.stringify({ paymentMethod: payment.paymentMethod }),
        signal: AbortSignal.timeout(15_000),
      });
    } catch (err) {
      // 没有响应：卡可能已扣也可能没扣。用同一个键再试。
      if (attempt >= maxAttempts) {
        throw err;
      }
      await sleep(backoff);
      continue;
    }
    if (res.ok) {
      return res.json(); // 第一次的结果，即使带 Idempotent-Replayed: true
    }
    const body = await res.json().catch(() => ({})); // 代理的 502 页面不是 JSON
    const retryable =
      res.status >= 500 || // 服务器已释放该键
      res.status === 429 ||
      body.code === 'IDEMPOTENCY_KEY_IN_USE'; // 第一次尝试仍在运行
    if (!retryable || attempt >= maxAttempts) {
      throw new PaymentError(res.status, body);
    }
    const retryAfter = Number(res.headers.get('Retry-After'));
    await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff);
  }
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
```

`crypto.randomUUID()` 在浏览器与 Node.js 中可用。在 React Native 中请使用 UUID 库，例如 `expo-crypto` 的 `randomUUID()`。

下面是 App 可能收到的响应，以及它们对重试意味着什么：

| 响应 | 含义 | 用同一个键重试？ |
| ------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------- |
| 无响应（网络错误、超时） | 卡可能已扣，也可能没扣 | 是 |
| 2xx | 完成。若带 `Idempotent-Replayed: true`，这是第一次尝试的结果 | 否，展示凭据 |
| 409，code 为 `IDEMPOTENCY_KEY_IN_USE` | 第一次尝试仍在运行 | 是，等 `Retry-After` 秒后 |
| 5xx | 本次尝试失败，服务器已释放键 | 是，带退避 |
| 429 | 在处理器运行之前被限流 | 是，等 `Retry-After` 秒后 |
| 422 `IDEMPOTENCY_KEY_REUSED` | 程序缺陷：键被复用于另一个请求 | 否 |
| 其他 4xx：400、402（被拒）、404、409（已支付） | 最终结果。用此键的每次重试都得到同样的答案 | 否。展示错误；新尝试用新键 |

要看 `code`，不能只看状态码。409 也可能表示订单已支付，而那是最终结果。

#### 把键存进 PostgreSQL

内存存储在生产的场景下不够用。进程一停（每次部署或容器被替换），记录就消失，之后到达的重试会再次执行支付。而且一旦 API 跑在多个实例上，落到另一个实例的重试找不到记录，两个实例还可能同时拿到锁。记录需要一个能原子「不存在才创建」的共享存储。

`@nestjs/idempotency` 不附带这样的存储。它定义契约 `IdempotencyStore` 接口，由你在应用的某个提供者中用已有的数据库或 Redis 客户端实现。该接口有四个方法。每个方法先接记录键与 owner，时长以整毫秒传入：

- `acquire(key, owner, fingerprint, lockTtl)` 创建锁，或返回已有记录：进行中，或已带响应完成。它必须是原子的：对同一个空闲键的任意多次并发调用中，有且只有一个可以成功。
- `complete(key, owner, response, ttl)` 在 `owner` 仍持有锁的前提下，把锁变成已完成记录。
- `release(key, owner)` 在 `owner` 仍持有锁的前提下删除锁，好让重试可以再次运行处理器。
- `extend(key, owner, lockTtl)` 在 `owner` 仍持有锁的前提下，把锁的过期时间重置为从现在起 `lockTtl`。处理器运行及其结果写入期间，拦截器每 `lockTtl / 3` 调用它一次。

`owner` 是每次尝试的随机 id，称为栅栏令牌（fencing token）。若某次尝试停止续租（比如它的实例崩溃），而重试在 `lockTtl` 之后接管，那么旧尝试的 `extend()`、`complete()` 或 `release()` 什么都不做，而不会覆盖重试的记录。因此「若 `owner` 仍持有它」必须与写入在同一个原子操作中检查：先单独读一次再写，接管可能插在中间。

本节把这个存储展示两遍：先用 Drizzle（教程的主线），然后在本节末尾的「使用 TypeORM」中，给出同一存储面向 TypeORM 应用的版本。二者取其一。

存储用 Drizzle 把数据放在 PostgreSQL 中，因此记录在它的 Drizzle schema 里有一张表：

```typescript
@@filename(database/schema)
import type { IdempotencyStoredPayload } from '@nestjs/idempotency';
import { bigint, index, json, pgTable, text } from 'drizzle-orm/pg-core';

/** 每条幂等记录一行：进行中的锁，或已完成的响应。 */
export const idempotencyKeys = pgTable(
  'idempotency_keys',
  {
    // 记录键的 SHA-256：键可能长于索引项允许的长度。
    keyHash: text('key_hash').primaryKey(),
    key: text('key').notNull(),
    fingerprint: text('fingerprint').notNull(),
    // 持有锁的那次尝试；记录完成后为 null。
    owner: text('owner'),
    // 进行中时为 null。用 json 而非 jsonb：jsonb 会拒绝字符串中的 "\u0000"。
    response: json('response').$type<IdempotencyStoredPayload>(),
    // 纪元毫秒。
    expiresAt: bigint('expires_at', { mode: 'number' }).notNull(),
  },
  (table) => [index('idempotency_keys_expires_at_idx').on(table.expiresAt)],
);
```

主键是记录键的 SHA-256 哈希，因为记录键（一个 scope、客户端的键，以及 GraphQL 情况下的字段路径）可能长于 PostgreSQL 索引项允许的长度。响应列用 `json` 而不是 `jsonb`，因为 `jsonb` 会拒绝字符串内的 `\u0000`，而响应体可能包含它。用 drizzle-kit 生成迁移，照常用 `npx drizzle-kit migrate` 应用：

```bash
$ npx drizzle-kit generate --name=idempotency
```

```sql
@@filename(drizzle/0000_idempotency.sql)
CREATE TABLE "idempotency_keys" (
	"key_hash" text PRIMARY KEY NOT NULL,
	"key" text NOT NULL,
	"fingerprint" text NOT NULL,
	"owner" text,
	"response" json,
	"expires_at" bigint NOT NULL
);
--> statement-breakpoint
CREATE INDEX "idempotency_keys_expires_at_idx" ON "idempotency_keys" USING btree ("expires_at");
```

存储用 Drizzle 的查询构建器实现每个方法。它通过 `@nestjs/drizzle` 的 `@InjectDrizzle()` 注入数据库，构造函数把存储注册到 `IdempotencyStorage`——一个由 `IdempotencyModule` 导出的注册表：

```typescript
@@filename(idempotency/drizzle-idempotency.store)
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import {
  IdempotencyStorage,
  type IdempotencyAcquireResult,
  type IdempotencyStore,
  type IdempotencyStoredPayload,
} from '@nestjs/idempotency';
import { and, eq, gt, inArray, lte } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { createHash } from 'node:crypto';
import { idempotencyKeys } from '../database/schema.js';

export type Database = NodePgDatabase;

const { keyHash, owner: ownerColumn, expiresAt } = idempotencyKeys;

@Injectable()
export class DrizzleIdempotencyStore implements IdempotencyStore {
  constructor(
    @InjectDrizzle() private readonly db: Database,
    storage: IdempotencyStorage,
  ) {
    storage.registerSource(this);
  }

  async acquire(
    key: string,
    owner: string,
    fingerprint: string,
    lockTtl: number,
  ): Promise<IdempotencyAcquireResult> {
    const hash = hashOf(key);
    // 只有行在下述两条语句之间被释放或过期时，才会有第二轮。
    for (let attempt = 0; attempt < 5; attempt++) {
      const now = Date.now();
      const lock = { fingerprint, owner, response: null, expiresAt: now + lockTtl };
      // 插入锁，或接管已过期的行。在众多并发调用者中，PostgreSQL 只让一个写入，
      // 并针对胜者的行重新检查 `setWhere`：其他调用者拿不到返回行。
      const taken = await this.db
        .insert(idempotencyKeys)
        .values({ keyHash: hash, key, ...lock })
        .onConflictDoUpdate({
          target: keyHash,
          set: lock,
          setWhere: lte(expiresAt, now),
        })
        .returning({ keyHash });
      if (taken.length) {
        return { state: 'acquired' };
      }

      // 别人持有该键：报告他们的锁或记录。
      const [row] = await this.db
        .select()
        .from(idempotencyKeys)
        .where(eq(keyHash, hash));
      if (row && row.expiresAt > now) {
        return row.response === null
          ? { state: 'in-flight', fingerprint: row.fingerprint }
          : { state: 'completed', fingerprint: row.fingerprint, response: row.response };
      }
    }
    throw new Error(`The idempotency record for "${key}" kept changing; try again`);
  }

  async complete(
    key: string,
    owner: string,
    response: IdempotencyStoredPayload,
    ttl: number,
  ): Promise<boolean> {
    const now = Date.now();
    const done = await this.db
      .update(idempotencyKeys)
      .set({ owner: null, response, expiresAt: now + ttl })
      .where(this.ownedBy(key, owner, now))
      .returning({ keyHash });
    return done.length === 1;
  }

  async release(key: string, owner: string): Promise<boolean> {
    const released = await this.db
      .delete(idempotencyKeys)
      .where(this.ownedBy(key, owner, Date.now()))
      .returning({ keyHash });
    return released.length === 1;
  }

  async extend(key: string, owner: string, lockTtl: number): Promise<boolean> {
    const now = Date.now();
    const extended = await this.db
      .update(idempotencyKeys)
      .set({ expiresAt: now + lockTtl })
      .where(this.ownedBy(key, owner, now))
      .returning({ keyHash });
    return extended.length === 1;
  }

  /**
   * 为定时任务删除最多 `limit` 条过期记录。过期记录本来就被忽略，
   * 并会被下一个同键请求复用。
   */
  async prune(limit = 1000): Promise<number> {
    const now = Date.now();
    const expired = this.db
      .select({ keyHash })
      .from(idempotencyKeys)
      .where(lte(expiresAt, now))
      .limit(limit);
    const deleted = await this.db
      .delete(idempotencyKeys)
      // 再检查一次过期：子查询读取之后被接管的行会留下。
      .where(and(inArray(keyHash, expired), lte(expiresAt, now)))
      .returning({ keyHash });
    return deleted.length;
  }

  /** 调用者的锁，前提是它仍持有且尚未过期。 */
  private ownedBy(key: string, owner: string, now: number) {
    return and(eq(keyHash, hashOf(key)), eq(ownerColumn, owner), gt(expiresAt, now));
  }
}

function hashOf(key: string) {
  return createHash('sha256').update(key).digest('hex');
}
```

数据库类型标注为 `NodePgDatabase`，下面的测试把 PGlite 数据库强制转换为它，因为该存储只用到两种驱动共有的查询构建器。每个方法都是 PostgreSQL 原子执行的单条语句，无需事务：

- `acquire()` 用一条 `INSERT ... ON CONFLICT DO UPDATE ... WHERE expires_at <= now` 插入锁，或接管过期行。当多个调用者争抢同一个键时，PostgreSQL 让其中一个写入，并针对胜者的行重新为其他人检查 `WHERE`，于是他们拿不到返回行，转而读取胜者的锁。若该行在这中间消失（被释放或过期），`acquire()` 再来一轮。
- `complete()`、`extend()` 与 `release()` 在写入语句的 `WHERE` 中检查 owner 与锁未过期。它们统计 `returning()` 返回的行数，这在每个 Drizzle 驱动上行为一致。
- 过期行立刻被忽略，下一个同键请求会复用它的行。要删除其余的行，请从定时任务中调用 `prune()`，例如用 `@nestjs/schedule` 的 `@Interval()`。它在 `DELETE` 本身中再次检查过期，因此期间被重试接管的行会保留下来。

过期时间取自各实例的时钟（`Date.now()`），因此要像 NTP 那样保持时钟同步。每个幂等请求会向连接池增加一到两条语句，处理器运行期间还每 `lockTtl / 3` 增加一条 `UPDATE`。

存储是普通提供者。用 `DrizzleModule` 注册数据库（见 [Drizzle](/data/drizzle)），并把存储加入 `AppModule` 的 providers：

```typescript
@@filename(app.module)
import { Module } from '@nestjs/common';
import { DrizzleModule } from '@nestjs/drizzle';
import { IdempotencyModule } from '@nestjs/idempotency';
import { drizzle } from 'drizzle-orm/node-postgres';
import { DrizzleIdempotencyStore } from './idempotency/drizzle-idempotency.store.js';
import type { User } from './orders/order.js';
import { OrdersModule } from './orders/orders.module.js';

@Module({
  imports: [
    DrizzleModule.forRootAsync({
      useFactory: () => ({ drizzle, connection: process.env.DATABASE_URL! }),
    }),
    IdempotencyModule.forRoot({
      scope: (req: { user?: User }) => req.user?.id,
    }),
    OrdersModule,
  ],
  // Nest 创建它时，它会把自己注册到 IdempotencyStorage。
  providers: [DrizzleIdempotencyStore],
})
export class AppModule {}
```

> info **提示** 应用从 `process.env` 读取 `DATABASE_URL`，以及凭据加密之后的 `IDEMPOTENCY_KEYS`。应用通常通过 `@nestjs/config` 加载环境，配合校验 schema 在变量缺失时阻止启动，并向这些工厂注入 `ConfigService`。

启动时，模块会记录它使用的存储 `IdempotencyStorage: DrizzleIdempotencyStore`，随后停止接受注册：

- 一个应用只有一个存储。第二次调用 `registerSource()` 会抛错，并指出两个类名。
- 请在单例提供者的构造函数中注册。注册表会在 `IdempotencyModule` 初始化时锁定，因此更晚注册的存储（在生命周期钩子中、在每个请求中，或在懒加载模块中）会抛错，而不是被默默忽略。
- 没有注册存储时，模块把记录保存在内存中。在生产环境（`NODE_ENV=production`），它会拒绝这样启动，除非你设置 `allowInMemoryStorage: true`，即接受每次重启或部署都忘记这些记录。

每个存储都用同一套契约测试来验证，`@nestjs/idempotency/testing` 以纯测试用例的形式导出，适用于任何测试运行器。它覆盖每个方法、owner 检查、过期，以及在 `concurrent` 下那些「先读后写」的存储会搞错的竞争。示例项目在 PGlite 上对它运行该套件，也在通过 `pg` 连接池的 PostgreSQL 上运行：每个键最多 16 个连接、32 个调用者争抢：

```typescript
@@filename(test/step-3.drizzle-store.spec)
import { PGlite } from '@electric-sql/pglite';
import { IdempotencyStorage } from '@nestjs/idempotency';
import { idempotencyStoreContract } from '@nestjs/idempotency/testing';
import { drizzle as drizzlePglite } from 'drizzle-orm/pglite';
import { migrate as migratePglite } from 'drizzle-orm/pglite/migrator';
import { DrizzleIdempotencyStore, type Database } from '../src/idempotency/drizzle-idempotency.store.js';

const migrationsFolder = new URL('../drizzle', import.meta.url).pathname;
// ...
describe('DrizzleIdempotencyStore on PGlite', () => {
  let pglite: PGlite;
  let store: DrizzleIdempotencyStore;

  beforeAll(async () => {
    pglite = new PGlite();
    const db = drizzlePglite({ client: pglite });
    await migratePglite(db, { migrationsFolder }); // npx drizzle-kit migrate
    store = new DrizzleIdempotencyStore(db as unknown as Database, new IdempotencyStorage());
  });
  afterAll(() => pglite.close());

  describe('the IdempotencyStore contract', () => {
    // 存储会读 Date.now()：只伪造 Date，让驱动保留自己的定时器。
    beforeEach(() => vi.useFakeTimers({ toFake: ['Date'] }));
    afterEach(() => vi.useRealTimers());

    // 所有用例共用一个存储和一张表：每个用例使用自己的键。
    const cases = idempotencyStoreContract(() => store, {
      advanceTime: (ms) => vi.setSystemTime(Date.now() + ms),
      concurrent: true,
    });
    for (const c of cases) {
      it(c.name, c.run);
    }
  });
  // ...
});
```

**使用 TypeORM。** 同一个存储在 ORM 为 TypeORM 的应用中，用同一张表。教程主线仍走 Drizzle：请用这个存储替换上面的那个，而不是与它并存。表是一个实体，每列都声明类型，好让不加载装饰器元数据的 TypeORM CLI 看到与应用相同的 schema：

```typescript
@@filename(typeorm/idempotency-key.entity)
import { Column, Entity, Index, PrimaryColumn } from 'typeorm';

// src/database/schema.ts 中 Drizzle schema 的 idempotency_keys 表，作为实体。
// 每列都声明类型，因此无论是否产出装饰器元数据，实体都加载出同样的结果
// （TypeORM CLI 通过 tsx 运行它，而 tsx 不产出元数据）。

/** 把 `bigint` 列读成数字：TypeORM 会把它返回为字符串。 */
const epochMs = {
  to: (value: number) => value,
  from: (value: string) => Number(value),
};

/** 每条幂等记录一行：进行中的锁，或已完成的响应。 */
@Entity('idempotency_keys')
@Index('idempotency_keys_expires_at_idx', ['expiresAt'])
export class IdempotencyKeyEntity {
  // 记录键的 SHA-256：键可能长于索引项允许的长度。
  @PrimaryColumn({ type: 'text', name: 'key_hash' })
  keyHash: string;

  @Column({ type: 'text' })
  key: string;

  @Column({ type: 'text' })
  fingerprint: string;

  // 持有锁的那次尝试；记录完成后为 null。
  @Column({ type: 'text', nullable: true })
  owner: string | null;

  // 进行中时为 null。用 json 而非 jsonb：jsonb 会拒绝字符串中的 "\u0000"。
  // 类型为 IdempotencyStoredPayload，标注为 `object`：它的 `unknown` 响应体
  // 不符合 TypeORM 的插入类型。
  @Column({ type: 'json', nullable: true })
  response: object | null;

  // 纪元毫秒。
  @Column({ type: 'bigint', name: 'expires_at', transformer: epochMs })
  expiresAt: number;
}
```

TypeORM 会把 `bigint` 列返回为字符串，因此用转换器把 `expiresAt` 读回数字。响应列标注为 `object` 而非 `IdempotencyStoredPayload`，因为负载的 `unknown` 响应体不符合 TypeORM 的插入类型；存储在读取记录时再做强制转换。TypeORM CLI 与 `TypeOrmModule` 共用一套选项，放在一个数据源文件中：

```typescript
@@filename(typeorm/data-source)
import { DataSource, type DataSourceOptions } from 'typeorm';
import { IdempotencyKeyEntity } from './idempotency-key.entity.js';
import { Idempotency1790321611502 } from './migrations/1790321611502-Idempotency.js';

/** 应用的 TypeOrmModule 与 TypeORM CLI 共用的配置。 */
export const dataSourceOptions = {
  type: 'postgres',
  url: process.env.DATABASE_URL,
  entities: [IdempotencyKeyEntity],
  migrations: [Idempotency1790321611502],
} satisfies DataSourceOptions;

// TypeORM CLI 的数据源：`migration:generate` 用它把实体与数据库对比。
export default new DataSource(dataSourceOptions);
```

从实体生成迁移、应用它，并检查实体与数据库是否一致。CLI 需要为数据源文件准备 TypeScript 加载器；这里用 `tsx`：

```bash
$ npx tsx ./node_modules/typeorm/cli.js migration:generate src/typeorm/migrations/Idempotency -d src/typeorm/data-source.ts --pretty
Migration /store/src/typeorm/migrations/1790321611502-Idempotency.ts has been generated successfully.
$ npx tsx ./node_modules/typeorm/cli.js migration:run -d src/typeorm/data-source.ts
$ npx tsx ./node_modules/typeorm/cli.js migration:generate src/typeorm/migrations/Check -d src/typeorm/data-source.ts --check
No changes in database schema were found
```

它写出的迁移 `1790321611502-Idempotency.ts` 就是 Drizzle 迁移里的 `CREATE TABLE` 与 `CREATE INDEX` 语句，数据源的 `migrations` 列出了它。现在写存储，规则与 Drizzle 版相同：

```typescript
@@filename(typeorm/typeorm-idempotency.store)
import { Injectable } from '@nestjs/common';
import {
  IdempotencyStorage,
  type IdempotencyAcquireResult,
  type IdempotencyStore,
  type IdempotencyStoredPayload,
} from '@nestjs/idempotency';
import { createHash } from 'node:crypto';
import { DataSource, MoreThan } from 'typeorm';
import { IdempotencyKeyEntity } from './idempotency-key.entity.js';

/**
 * 通过 TypeORM 把幂等记录保存在 PostgreSQL 中：与 Drizzle 版存储
 * 使用同一张表。每个方法都是单条语句，因此无论多少 API 实例，
 * 这些保证都成立。
 */
@Injectable()
export class TypeOrmIdempotencyStore implements IdempotencyStore {
  constructor(
    private readonly dataSource: DataSource,
    storage: IdempotencyStorage,
  ) {
    storage.registerSource(this);
  }

  async acquire(
    key: string,
    owner: string,
    fingerprint: string,
    lockTtl: number,
  ): Promise<IdempotencyAcquireResult> {
    const hash = hashOf(key);
    // 只有行在下述两条语句之间被释放或过期时，才会有第二轮。
    for (let attempt = 0; attempt < 5; attempt++) {
      const now = Date.now();
      // 插入锁，或接管已过期的行。在众多并发调用者中，PostgreSQL 只让一个写入，
      // 并针对胜者的行重新检查覆盖条件：其他调用者拿不到返回行。
      const { raw } = await this.dataSource
        .createQueryBuilder()
        .insert()
        .into(IdempotencyKeyEntity)
        .values({ keyHash: hash, key, fingerprint, owner, response: null, expiresAt: now + lockTtl })
        .orUpdate(['fingerprint', 'owner', 'response', 'expires_at'], ['key_hash'], {
          overwriteCondition: { where: 'idempotency_keys.expires_at <= :now', parameters: { now } },
        })
        .returning(['keyHash'])
        .updateEntity(false)
        .execute();
      if ((raw as unknown[]).length === 1) {
        return { state: 'acquired' };
      }

      // 别人持有该键：报告他们的锁或记录。
      const row = await this.dataSource.manager.findOneBy(IdempotencyKeyEntity, { keyHash: hash });
      if (row && row.expiresAt > now) {
        return row.response === null
          ? { state: 'in-flight', fingerprint: row.fingerprint }
          : { state: 'completed', fingerprint: row.fingerprint, response: row.response as IdempotencyStoredPayload };
      }
    }
    throw new Error(`The idempotency record for "${key}" kept changing; try again`);
  }

  async complete(
    key: string,
    owner: string,
    response: IdempotencyStoredPayload,
    ttl: number,
  ): Promise<boolean> {
    const now = Date.now();
    const { affected } = await this.dataSource.manager.update(IdempotencyKeyEntity, ownedBy(key, owner, now), {
      owner: null,
      response,
      expiresAt: now + ttl,
    });
    return affected === 1;
  }

  async release(key: string, owner: string): Promise<boolean> {
    const { affected } = await this.dataSource.manager.delete(IdempotencyKeyEntity, ownedBy(key, owner, Date.now()));
    return affected === 1;
  }

  async extend(key: string, owner: string, lockTtl: number): Promise<boolean> {
    const now = Date.now();
    const { affected } = await this.dataSource.manager.update(IdempotencyKeyEntity, ownedBy(key, owner, now), {
      expiresAt: now + lockTtl,
    });
    return affected === 1;
  }

  /**
   * 为定时任务删除最多 `limit` 条过期记录。过期记录本来就被忽略，
   * 并会被下一个同键请求复用。
   */
  async prune(limit = 1000): Promise<number> {
    const expired = this.dataSource.manager
      .createQueryBuilder(IdempotencyKeyEntity, 'expired')
      .select('expired.keyHash')
      .where('expired.expiresAt <= :now')
      .limit(limit);
    const { affected } = await this.dataSource
      .createQueryBuilder()
      .delete()
      .from(IdempotencyKeyEntity)
      .where(`key_hash IN (${expired.getQuery()})`)
      // 再检查一次过期：子查询读取之后被接管的行会留下。
      .andWhere('expires_at <= :now', { now: Date.now() })
      .execute();
    return affected ?? 0;
  }
}

/** 调用者的锁，前提是它仍持有且尚未过期。 */
function ownedBy(key: string, owner: string, now: number) {
  return { keyHash: hashOf(key), owner, expiresAt: MoreThan(now) };
}

function hashOf(key: string) {
  return createHash('sha256').update(key).digest('hex');
}
```

- **`acquire()`** 是同样的 `INSERT ... ON CONFLICT DO UPDATE ... WHERE expires_at <= now`，通过插入查询构建器写出：`orUpdate()` 列出接管时会覆盖的列，其 `overwriteCondition` 选项就是 `WHERE`，而 `returning()` 只把行返回给写入的那个调用者。
- **`complete()`、`extend()` 与 `release()`** 是实体管理器上的 `update()` 与 `delete()`，条件里带 owner 与 `MoreThan(now)`，并读取 `affected`。绝不要用 `save()`：它先读行，接管可能插在中间。
- **`prune()`** 用 select 查询构建器构造挑选过期行的子查询，并把它的 SQL 放进 `DELETE` 的 `WHERE` 中，紧挨着过期检查。

存储注入 `TypeOrmModule` 提供的 `DataSource`。用数据源的选项注册模块来替代 `DrizzleModule`，并用存储替代 `DrizzleIdempotencyStore`：

```typescript
@@filename(typeorm/app.module)
import { Module } from '@nestjs/common';
import { IdempotencyModule } from '@nestjs/idempotency';
import { TypeOrmModule } from '@nestjs/typeorm';
import type { User } from '../orders/order.js';
import { OrdersModule } from '../orders/orders.module.js';
import { dataSourceOptions } from './data-source.js';
import { TypeOrmIdempotencyStore } from './typeorm-idempotency.store.js';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      // CLI 使用的实体与迁移；迁移在部署时运行（`migration:run`）。
      useFactory: () => ({ ...dataSourceOptions, url: process.env.DATABASE_URL }),
    }),
    IdempotencyModule.forRoot({
      scope: (req: { user?: User }) => req.user?.id,
    }),
    OrdersModule,
  ],
  // Nest 创建它时，它会把自己注册到 IdempotencyStorage。
  providers: [TypeOrmIdempotencyStore],
})
export class AppModule {}
```

契约套件在它上面原样运行。TypeORM 通过 `pg` 连接，因此该套件需要 PostgreSQL 服务器，没有时会跳过。还多一个用例检查实体与迁移是否一致，也就是 `migration:generate --check` 所检查的内容：

```typescript
@@filename(test/typeorm-idempotency.store.spec)
import { IdempotencyStorage } from '@nestjs/idempotency';
import { idempotencyStoreContract } from '@nestjs/idempotency/testing';
import { DataSource } from 'typeorm';
import { startPostgres } from '../../../test-support/postgres.js';
import { dataSourceOptions } from '../src/typeorm/data-source.js';
import { TypeOrmIdempotencyStore } from '../src/typeorm/typeorm-idempotency.store.js';
// ...
const { postgres, reason } = await startPostgres();
afterAll(() => postgres?.stop());

describe.skipIf(!postgres)(`TypeOrmIdempotencyStore on PostgreSQL${postgres ? '' : ` (skipped: ${reason})`}`, () => {
  let dataSource: DataSource;
  let url: string;
  let store: TypeOrmIdempotencyStore;

  beforeAll(async () => {
    url = await postgres!.createDatabase('idempotency_typeorm_store');
    dataSource = await new DataSource({ ...dataSourceOptions, url, poolSize: 16 }).initialize();
    await dataSource.runMigrations(); // npx typeorm migration:run
    store = new TypeOrmIdempotencyStore(dataSource, new IdempotencyStorage());
  });
  afterAll(() => dataSource?.destroy());

  describe('the IdempotencyStore contract', () => {
    // 存储会读 Date.now()：只伪造 Date，让驱动保留自己的定时器。
    beforeEach(() => vi.useFakeTimers({ toFake: ['Date'] }));
    afterEach(() => vi.useRealTimers());

    // 所有用例共用一个存储和一张表：每个用例使用自己的键。
    // 每场竞争 32 个调用者，最多 16 个连接。
    const cases = idempotencyStoreContract(() => store, {
      advanceTime: (ms) => vi.setSystemTime(Date.now() + ms),
      concurrent: { callers: 32 },
    });
    for (const c of cases) {
      it(c.name, c.run);
    }
  });

  it('has a migration that matches the entity (what `migration:generate --check` checks)', async () => {
    const { upQueries } = await dataSource.driver.createSchemaBuilder().log();
    expect(upQueries.map((query) => query.query)).toEqual([]);
  });
  // ...
});
```

`startPostgres()` 是一个测试辅助函数，在 PostgreSQL 服务器上创建一个一次性数据库；没有服务器时跳过该套件。示例还在同一个数据库上运行了两个 TypeORM `AppModule` 实例，一个扣款，另一个返回 409。

> info **提示** 用的是 Prisma？教程之后的[存储契约](/reliability/idempotency#the-store-contract)说明了 Prisma 如何表达这些语句。用同一套件检查你的存储。

#### 改用 Redis 存键

如果你的 API 已经在跑 Redis，它可以把记录放在那里而不是 PostgreSQL。Redis 很适合这个存储：一条记录是一个小哈希，Redis 自己会让它过期，因此不需要清理任务；而热键（例如某个客户端每秒重试同一笔支付）只需一次内存往返，而不是主数据库上的行锁。代价是要多跑、多保护、多备份一个存储，并且必须配置 Redis 永不驱逐这些记录（见生产检查清单）。

每个方法都是一段 Lua 脚本，由 Redis 原子执行：

```typescript
@@filename(idempotency/redis-idempotency.store)
import { Inject, Injectable } from '@nestjs/common';
import {
  IdempotencyStorage,
  type IdempotencyAcquireResult,
  type IdempotencyStore,
  type IdempotencyStoredPayload,
} from '@nestjs/idempotency';
import { REDIS } from '../redis/redis.module.js';

/** 这个存储需要的唯一一个 ioredis 方法。 */
export interface RedisClient {
  eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
}

// 不存在记录时创建锁。否则在同一次往返中返回记录。
const ACQUIRE = `
if redis.call('EXISTS', KEYS[1]) == 0 then
  redis.call('HSET', KEYS[1], 'state', 'in-flight', 'fp', ARGV[1], 'owner', ARGV[2])
  redis.call('PEXPIRE', KEYS[1], ARGV[3])
  return {1}
end
local r = redis.call('HMGET', KEYS[1], 'state', 'fp', 'resp')
return {0, r[1], r[2], r[3]}
`;

// 把我们的锁变为已完成记录，除非被另一次尝试接管。
const COMPLETE = `
if redis.call('HGET', KEYS[1], 'owner') ~= ARGV[1] then return 0 end
redis.call('HSET', KEYS[1], 'state', 'completed', 'resp', ARGV[2])
redis.call('HDEL', KEYS[1], 'owner')
redis.call('PEXPIRE', KEYS[1], ARGV[3])
return 1
`;

// 删除锁，但仅当它仍属于我们。
const RELEASE = `
if redis.call('HGET', KEYS[1], 'owner') == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0
`;

// 在处理器运行期间续租我们的锁，但仅当它仍属于我们。
const EXTEND = `
if redis.call('HGET', KEYS[1], 'owner') ~= ARGV[1] then return 0 end
redis.call('PEXPIRE', KEYS[1], ARGV[2])
return 1
`;

type AcquireReply =
  | [1]
  | [0, 'in-flight' | 'completed', string, string | null];

@Injectable()
export class RedisIdempotencyStore implements IdempotencyStore {
  constructor(
    @Inject(REDIS) private readonly redis: RedisClient,
    storage: IdempotencyStorage,
  ) {
    storage.registerSource(this);
  }

  async acquire(
    key: string,
    owner: string,
    fingerprint: string,
    lockTtl: number,
  ): Promise<IdempotencyAcquireResult> {
    const reply = (await this.redis.eval(
      ACQUIRE, 1, this.key(key), fingerprint, owner, lockTtl,
    )) as AcquireReply;
    if (reply[0] === 1) {
      return { state: 'acquired' };
    }
    const [, state, storedFingerprint, response] = reply;
    return state === 'completed'
      ? { state, fingerprint: storedFingerprint, response: JSON.parse(response!) }
      : { state, fingerprint: storedFingerprint };
  }

  async complete(
    key: string,
    owner: string,
    response: IdempotencyStoredPayload,
    ttl: number,
  ): Promise<boolean> {
    const done = await this.redis.eval(
      COMPLETE, 1, this.key(key), owner, JSON.stringify(response), ttl,
    );
    return done === 1;
  }

  async release(key: string, owner: string): Promise<boolean> {
    const released = await this.redis.eval(RELEASE, 1, this.key(key), owner);
    return released === 1;
  }

  async extend(key: string, owner: string, lockTtl: number): Promise<boolean> {
    const extended = await this.redis.eval(EXTEND, 1, this.key(key), owner, lockTtl);
    return extended === 1;
  }

  private key(key: string) {
    return `idem:${key}`;
  }
}
```

每条记录是 `idem:<scope>:<key>` 处的一个哈希，字段为 `state`、`fp`（指纹）、`owner` 与 `resp`（以 JSON 保存的响应）。哈希自行过期：进行中时在最后一次续租后 `lockTtl`，完成后在 `ttl` 之后，因此不需要清理任务。每段脚本只碰一个键，所以该存储也能用于 Redis Cluster。Redis 会原子执行脚本，但后续命令失败时不会回滚脚本已做的写入。例如 `PEXPIRE` 会拒绝不足一毫秒的小数，若它在 `HSET` 之后失败，就会留下一个永不过期的锁。正因如此，拦截器传给存储的是整毫秒。

Nest 注入 Redis 客户端，构造函数注册存储，与 PostgreSQL 版一样。一个应用只有一个存储，因此由 `RedisIdempotencyStore` 在 `AppModule` 中取代另一个：

```typescript
@@filename(app.module)
import { Module } from '@nestjs/common';
import { IdempotencyModule } from '@nestjs/idempotency';
import { RedisIdempotencyStore } from './idempotency/redis-idempotency.store.js';
import type { User } from './orders/order.js';
import { OrdersModule } from './orders/orders.module.js';
import { RedisModule } from './redis/redis.module.js';

@Module({
  imports: [
    RedisModule,
    IdempotencyModule.forRoot({
      scope: (req: { user?: User }) => req.user?.id,
    }),
    OrdersModule,
  ],
  providers: [RedisIdempotencyStore],
})
export class AppModule {}
```

`RedisModule` 代表你应用的 Redis 模块：一个全局模块，在 `REDIS` 令牌下提供 ioredis 客户端，例如 `useFactory: () => new Redis(process.env.REDIS_URL!)`，并在 `onApplicationShutdown()` 中调用 `quit()` 关闭它——此时该包已处理完在途请求。`RedisClient` 只要求 `eval()`，ioredis 的 `Redis` 实例本身就提供。启动时日志行为 `IdempotencyStorage: RedisIdempotencyStore`，PostgreSQL 版的注册表规则同样适用：一个存储，从构造函数注册。

示例项目也对该存储运行契约套件：

```typescript
@@filename(test/step-4.redis-store.spec)
import { idempotencyStoreContract } from '@nestjs/idempotency/testing';
// ...
describe('RedisIdempotencyStore, the IdempotencyStore contract (on FakeRedis)', () => {
  let redis: FakeRedis;
  const cases = idempotencyStoreContract(
    () => {
      redis = new FakeRedis();
      return new RedisIdempotencyStore(redis, new IdempotencyStorage());
    },
    // Redis 按自己的时钟让键过期：伪造实现的时钟。
    { advanceTime: (ms) => redis.advance(ms), concurrent: true },
  );
  for (const c of cases) {
    it(c.name, c.run);
  }
});
```

> info **提示** 本教程的示例项目没有 Redis 服务器，因此它的测试针对一个在进程内用 JavaScript 实现同样四段脚本的伪实现运行。这覆盖了存储的逻辑与读取响应的方式，但不覆盖 Lua 本身。在依赖该存储之前，请针对真实 Redis（例如容器中的）运行契约套件。不提供 `advanceTime` 时，套件会等待真实过期，约需十秒。

后续步骤的模块清单中展示的是 `DrizzleIdempotencyStore`。用 Redis 时改为注册 `RedisIdempotencyStore`：加密、发货服务与调优选项的行为相同；开启加密后，`resp` 字段保存密封信封，而不是 `response` 列。

#### 加密保存的凭据

保存的响应就是整张凭据：支付服务商的凭据 id、金额，以及卡的末四位。它们以明文躺在 `idempotency_keys` 中，出现在每一次备份与每一次数据库导出里，因此要在静态时加密记录。

加密密钥是机密，应用应在启动时读取，而不是在 `app.module.ts` 被导入时，因此改用 `forRootAsync()`。存储保持不变，仍是 `AppModule` 中自我注册的提供者，工厂返回选项：

```typescript
@@filename(app.module)
IdempotencyModule.forRootAsync({
  useFactory: () => ({
    scope: (req: { user?: User }) => req.user?.id,
    encryption: {
      // 最新的在前：用第一个密钥密封，用其中任意一个打开。
      keys: process.env.IDEMPOTENCY_KEYS!.split(','),
    },
  }),
}),
```

用 `openssl rand -base64 32` 生成密钥，并以 `IDEMPOTENCY_KEYS` 存入你的密钥管理服务。开启加密后，`response` 列保存的是密封信封 `v1.<keyId>.<iv>.<ciphertext>.<tag>`，而不是凭据：

- 记录用 AES-256-GCM 加密，每条记录使用随机 IV。
- 指纹保持明文。存储需要比较它，而且它本身就是哈希。
- 记录键随数据一起被认证，因此复制到另一个用户键下的记录会打开失败，而不会在那里被重放。
- 开启加密期间，明文记录会被拒绝，因此任何对表有写权限的人都无法植入响应。
- 字符串密钥至少 32 个字符，并通过 HKDF-SHA256 扩展。对上面那种随机机密来说没问题，但它不是口令哈希，因此不要使用人选的密码。较短的密钥，或首尾带空格的密钥（`IDEMPOTENCY_KEYS=new, old` 会拆出第二个以空格开头的密钥），会让应用在启动时停止，并给出指出它的错误。

请在端点保存第一条记录之前就开启加密。它会双向改变记录格式：切换之前保存的明文记录（如同关闭加密之后保存的密封记录）在过期前都会打开失败，其重放会得到下文所述的 500。

要在不破坏重放的前提下轮换密钥：

1. 生成新密钥并部署 `IDEMPOTENCY_KEYS=old-key,new-key`。各实例仍用旧密钥密封记录，但已能打开用新密钥密封的记录。
2. 等所有实例都跑上该配置后，部署 `IDEMPOTENCY_KEYS=new-key,old-key`。新记录用新密钥密封，旧记录仍可打开。滚动部署期间，尚未重启的实例得益于第一步，已能打开新记录。
3. 等 `ttl` 过去（48 小时，见[调整 TTL 与失败处理](/reliability/idempotency#tune-ttls-and-failure-handling)），所有用旧密钥密封的记录都已过期。部署 `IDEMPOTENCY_KEYS=new-key`。

如果过早移除某个密钥，用该密钥密封的记录在重放时会**失败关闭**（fail closed）。客户端收到 500 `IDEMPOTENCY_RECORD_UNREADABLE` 错误，失败被记录，处理器不会再次运行：该记录证明卡已被扣款，因此运行处理器可能导致二次扣款。记录过期后该错误消失。

#### 通过 GraphQL 支付

店铺的网站通过 GraphQL mutation 支付。在 `AppModule` 中注册 `GraphQLModule`：

```typescript
@@filename(app.module)
GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: true,
}),
```

然后把 mutation 加到订单解析器中、紧挨着它的查询。在 GraphQL 中，键可以像 REST 一样来自 `Idempotency-Key` 头，也可以来自参数。放在参数里会把键写进 schema，代码生成器与评审者都能看到。它也更适合 GraphQL 客户端——这类客户端通常每个连接设置一次头，而不是每个操作设置一次。`@Idempotent()` 在有 `idempotencyKey` 参数时读取该参数，否则读头，因此解析器只需声明这个参数：

```typescript
@@filename(orders/orders.resolver)
@Mutation(() => PaymentReceipt)
@Idempotent({ required: true })
payOrder(
  @Args('orderId', { type: () => ID }) orderId: string,
  @Args('input') input: PayOrderDto,
  @Args('idempotencyKey') _idempotencyKey: string,
  @CurrentUser() user: User,
) {
  return this.ordersService.pay(orderId, user, input);
}
```

`PayOrderDto` 就是 REST 端点用的那个类，加上 `@InputType()` 与 `@Field()`；`PaymentReceipt` 是一个 `@ObjectType()`，含凭据的各个字段。解析器使用同一个 `AuthGuard`，它从 GraphQL 上下文读取请求。模块的 `scope` 接收同一个请求，因此这里键也是按用户的。该参数是非空 `String`，因此 GraphQL 校验本身就会拒绝缺少它的操作：

```graphql
mutation PayOrder($orderId: ID!, $paymentMethod: String!, $key: String!) {
  payOrder(orderId: $orderId, input: { paymentMethod: $paymentMethod }, idempotencyKey: $key) {
    receiptId
    amount
    cardLast4
    paidAt
  }
}
```

用相同变量重试会返回保存的 `payOrder` 结果，类型与解析器返回的一致，因此 `Date` 字段重放出来仍是 `Date`。记录键会附加字段路径，如 `usr_alice:<key>:payOrder`，因为一个操作可以包含多个 mutation。每个字段各自保存与重放，别名属于路径的一部分，因此重试必须发送同一份文档。

拒绝是该字段上的错误，而不是 HTTP 状态。响应仍是 200，因为同一操作中的其他字段可能已成功；状态与重试延迟在 `extensions` 中（省略 `locations`）：

```json
{
  "errors": [
    {
      "message": "A request with this idempotency key is still being processed.",
      "path": ["payOrder"],
      "extensions": {
        "code": "IDEMPOTENCY_KEY_IN_USE",
        "httpStatus": 409,
        "retryAfter": 2
      }
    }
  ],
  "data": null
}
```

出于同样的原因，GraphQL 重放不会设置 `Idempotent-Replayed` 头。

#### 对 order.paid 事件去重

支付之后，`OrdersService` 发出一个 `order.paid` 事件，发货服务据此安排快递。现实中事件是至少一次投递的。发布方在超时后重试，或代理（RabbitMQ、Kafka、NATS JetStream）重投一条未确认的消息，都可能把同一事件投递两次，顾客就会收到两个包裹。

事件去重需要一个对同一事件的每次投递都相同的 id，因此它由数据推导而来，而不是每次发送时生成。订单只支付一次，所以 `OrdersService` 使用 `order-paid:` 加订单 id。用 `@Idempotent()` 标记[事件处理器](/microservices/basics#event-based)，并把 `keyFrom` 指向该 id：

```typescript
@@filename(shipping/shipping.controller)
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { Idempotent } from '@nestjs/idempotency';
import { ShipmentsService } from './shipments.service.js';

export interface OrderPaidEvent {
  eventId: string;
  orderId: string;
}

@Controller()
export class ShippingController {
  constructor(private readonly shipmentsService: ShipmentsService) {}

  @EventPattern('order.paid')
  @Idempotent({ required: true, keyFrom: { payload: 'eventId' } })
  async onOrderPaid(@Payload() event: OrderPaidEvent) {
    await this.shipmentsService.createFor(event.orderId);
  }
}
```

默认情况下，微服务处理器先读负载的 `idempotencyKey` 属性，再读由 `header` 选项指定的传输头。这里 `keyFrom` 改为读取 `eventId`，而 `required: true` 拒绝没有该字段的事件。

发货服务是独立应用，有自己的数据库和自己的 `IdempotencyModule`，它注册同一个存储类：

```typescript
@@filename(shipping/shipping.module)
import { Module } from '@nestjs/common';
import { DrizzleModule } from '@nestjs/drizzle';
import { IdempotencyModule } from '@nestjs/idempotency';
import { drizzle } from 'drizzle-orm/node-postgres';
import { DrizzleIdempotencyStore } from '../idempotency/drizzle-idempotency.store.js';
import { ShipmentsService } from './shipments.service.js';
import { ShippingController } from './shipping.controller.js';

@Module({
  imports: [
    DrizzleModule.forRootAsync({
      useFactory: () => ({ drizzle, connection: process.env.DATABASE_URL! }),
    }),
    IdempotencyModule.forRoot({
      ttl: '7d', // 代理可能在首次投递很久之后重投
    }),
  ],
  controllers: [ShippingController],
  providers: [ShipmentsService, DrizzleIdempotencyStore],
})
export class ShippingModule {}
```

```typescript
@@filename(shipping/main)
import { NestFactory } from '@nestjs/core';
import { Transport, type MicroserviceOptions } from '@nestjs/microservices';
import { ShippingModule } from './shipping.module.js';

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(ShippingModule, {
    transport: Transport.TCP,
    options: { host: '0.0.0.0', port: 4001 },
  });
  await app.listen();
}
bootstrap();
```

与 API 相比有几处细节不同：

- 没有 `scope`，因为事件 id 在整个系统中唯一。
- `ttl` 是 7 天，因为消息可能在被首次处理很久之后从死信队列回来。
- 记录属于处理器：记录键以处理器的类与方法结尾，如 `order-paid%3Aord_1001:ShippingController.onOrderPaid`。Nest 会为事件运行每一个已注册的处理器，因此 `order.paid` 的第二个处理器（比如发送追踪号邮件的那个）保有自己的记录，并且仍然对每个事件只处理一次。

重复事件按两种方式之一处理：

- 若首次投递已完成，重复事件被跳过。保存的结果被「重放」，而事件没有回复，因此什么都不发生。
- 若首次投递仍在运行，重复事件以 `IDEMPOTENCY_KEY_IN_USE` 被拒绝，Nest 记录该错误。对于会确认消息的传输（如 RabbitMQ 或 Kafka），不要把那次投递确认为已处理。让传输稍后重投，那时它会被跳过。

无论哪种方式，快递只预约一次。HTTP 支付的重试根本不会产生重复事件，因为被重放的请求永远到不了 `OrdersService`。

#### 调整 TTL 与失败处理

默认值只是起点。下面是该 API 的最终配置：

```typescript
@@filename(app.module)
IdempotencyModule.forRootAsync({
  useFactory: () => ({
    scope: (req: { user?: User }) => req.user?.id,
    encryption: {
      // 最新的在前：用第一个密钥密封，用其中任意一个打开。
      keys: process.env.IDEMPOTENCY_KEYS!.split(','),
    },
    // 长于应用重试排队支付的时长（24 小时）。
    ttl: '48h',
    // 崩溃的实例最多阻塞一个键 45 秒。扣款运行期间，
    // 锁每 15 秒续租一次。
    lockTtl: '45s',
    // 客户端在 409 之后等多久再问。
    retryAfter: '2s',
  }),
}),
```

每个时长都接受毫秒数，或 `'45s'`、`'48h'`、`'7d'` 这样的字符串。无法解析的值会让应用在启动时停止，并给出指出该选项的错误。

- **`ttl`**（默认 `'24h'`）是已完成结果可被重放多久。它必须长于客户端持续重试的最长时间。该应用会把离线发起的支付排队最多一天，因此这里设 48 小时。超过 `ttl` 后键被遗忘，重试会重新运行处理器。在这个应用里，那会以 409「已支付」错误结束，而不是二次扣款，但顾客拿不到凭据。
- **`lockTtl`**（默认 `'60s'`）是运行处理器的实例崩溃后，进行中的锁还能存活多久。处理器运行期间，拦截器每 `lockTtl / 3` 续租一次，这里即每 15 秒，所以耗时超过 45 秒的扣款仍持有锁，重试得到 409。一旦续租停止，锁过期，重试接管该键。较短的 `lockTtl` 在崩溃后更快释放键，但续租更频繁。若无法连接存储来续租，拦截器会记录一条锁已丢失的警告。
- **`maxLockHold`**（默认 `'1h'`）是运行中的处理器持续续租锁的最长时间。挂起超过该时间的处理器不再被续租，于是它的锁在 `lockTtl` 后过期，重试可能第二次运行处理器。若处理器确实完成，只有在没有重试接管该键时才保存其结果。
- **`retryAfter`**（默认 `'1s'`）是 409 响应上 `Retry-After` 头的值，以整秒计。卡扣款通常需要一两秒，因此该 API 让客户端等 2 秒，而不是 1 秒后就回查。

`@Idempotent()` 接受 `required`、`ttl`、`lockTtl`、`maxLockHold`、`retryAfter`、`keyFrom`、`scope`、`fingerprint` 与 `storeIf`，它们会为该处理器覆盖模块选项。`fingerprint` 选择重试必须重复什么，例如去掉客户端时间戳的请求体；方法与 URL 始终计入。该装饰器也可用在控制器或解析器类上，此时覆盖会改变状态的处理器：GET 路由与 GraphQL 查询会被跳过，除非它们有自己的 `@Idempotent()`。处理器自身的 `@Idempotent()` 与类上的选项合并，因此类级的 `required: true` 仍适用于只设置 `lockTtl` 的处理器。

`scope` 函数会为每种处理器运行，它接收什么取决于处理器：HTTP 与 GraphQL 收到请求，而微服务处理器收到消息负载。若一个应用用一个 `IdempotencyModule` 同时服务两者，请给 `scope` 传一个对象，在 `http`、`graphql` 与 `rpc` 键下各放一个函数。每个函数按其上下文传入的内容定型，没有对应函数的上下文则不加作用域。

并非所有结果都会被保存。默认情况下，低于 500 的都会：

| 结果 | 默认行为 | 原因 |
| --------------------------------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------- |
| 2xx | 保存并重放 | 支付成功 |
| 4xx `HttpException`（校验 400、被拒 402、404、已支付 409） | 保存，并在每次重放时再次抛出 | 它是确定性的：同一请求得到同一答案 |
| 其他带 4xx `status` 的错误（`AuthorizationError`、403） | 按该状态保存为 Nest 的异常，并重放 | 其所在的包会把它转成该状态 |
| 5xx 或未知错误（支付服务商 503、数据库宕机） | 不保存。键被释放，重试会再次运行 | 大多数失败发生在副作用之前 |
| `StreamableFile`、流、不带 `passthrough` 的 `@Res()` | 不保存。键被释放，并记录警告 | 它们无法被重放 |

被重放的错误会以保存的状态与响应体重建为普通 `HttpException`，并再次经过你的异常过滤器。用 `instanceof` 检查自定义异常类的过滤器，在重放时看到的是基类。

`storeIf` 选项改变这条规则。它接收状态码，以及处理器抛出错误时的错误对象。例如 `storeIf: () => true` 像 Stripe 那样连 5xx 也保存。这对默认规则留下的唯一缺口很重要：**副作用之后**发生的 5xx。若支付服务商扣了卡，随后 `markPaid()` 失败，键会被释放，重试会再次扣款。有三种方式堵住这个缺口：

- 给支付服务商传一个由用户 id 与幂等键推导出的键。多数支付服务商接受自己的幂等键，因此服务商也会去重这次扣款。只用幂等键不够，因为两个用户可以发送同一个键。
- 用 `storeIf` 为该处理器保存 5xx，并让应用在 5xx 之后发起新的尝试。若只想保存扣款之后的失败，请在那里抛出专用异常并检查它：`storeIf: (status, error) => status < 500 || error instanceof ChargeCapturedError`。
- 用[事务性 outbox](/reliability/outbox#prerequisites) 把支付与事件写进同一个事务。

#### 动手试试

启动发货服务，以及配置好 `DATABASE_URL`（已应用迁移）、`IDEMPOTENCY_KEYS` 与支付服务商沙箱的 API。沙箱大约半秒响应。下面的输出已裁剪到相关响应头。

没有键的支付被拒绝：

```bash
$ curl -i localhost:3000/orders/ord_1001/pay \
    -H 'Authorization: Bearer alice-token' \
    --json '{"paymentMethod":"pm_card_visa"}'
HTTP/1.1 400 Bad Request

{"statusCode":400,"error":"Bad Request","code":"IDEMPOTENCY_KEY_REQUIRED","message":"An idempotency key is required for this operation."}
```

第一次带键调用扣了卡：

```bash
$ KEY=$(uuidgen)
$ curl -i localhost:3000/orders/ord_1001/pay \
    -H 'Authorization: Bearer alice-token' \
    -H "Idempotency-Key: $KEY" \
    --json '{"paymentMethod":"pm_card_visa"}'
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8

{"orderId":"ord_1001","receiptId":"ch_0001","amount":4098,"cardLast4":"4242","paidAt":"2026-09-22T11:09:25.813Z"}
```

用同一个键重试得到同一张凭据，连 `paidAt` 都一样，且不会调用支付服务商：

```bash
$ curl -i localhost:3000/orders/ord_1001/pay \
    -H 'Authorization: Bearer alice-token' \
    -H "Idempotency-Key: $KEY" \
    --json '{"paymentMethod":"pm_card_visa"}'
HTTP/1.1 201 Created
Idempotent-Replayed: true
Content-Type: application/json; charset=utf-8

{"orderId":"ord_1001","receiptId":"ch_0001","amount":4098,"cardLast4":"4242","paidAt":"2026-09-22T11:09:25.813Z"}
```

同一个键换一张卡是客户端缺陷：

```bash
$ curl -i localhost:3000/orders/ord_1001/pay \
    -H 'Authorization: Bearer alice-token' \
    -H "Idempotency-Key: $KEY" \
    --json '{"paymentMethod":"pm_card_mastercard"}'
HTTP/1.1 422 Unprocessable Entity

{"statusCode":422,"error":"Unprocessable Entity","code":"IDEMPOTENCY_KEY_REUSED","message":"This idempotency key was already used for a different request."}
```

最后，为另一笔订单用新键同时发两个请求。一个扣款，另一个在支付服务商仍在处理时得到带 `Retry-After: 2` 的 409：

```bash
$ KEY=$(uuidgen)
$ for i in 1 2; do
  curl -s -o /dev/null -w '%{http_code} %header{retry-after}\n' \
    localhost:3000/orders/ord_1002/pay \
    -H 'Authorization: Bearer alice-token' \
    -H "Idempotency-Key: $KEY" \
    --json '{"paymentMethod":"pm_card_visa"}' &
done; wait
409 2
201
```

> info **提示** `--json` 需要 curl 7.82 或更高版本，`-w` 中的 `%header` 需要 curl 7.84 或更高版本。

#### 测试

在端到端测试中，保留应用的真实配置，但用普通的 `InMemoryIdempotencyStore` 覆盖 `DrizzleIdempotencyStore` 提供者。普通实例不会自我注册，因此模块回退到其内存存储；由于 Nest 从不创建 `DrizzleIdempotencyStore`，没有任何东西会查询数据库（node-postgres 连接池在首次查询时才连接，因此 `DrizzleModule` 也不会打开连接）。加密密钥仍来自 `IDEMPOTENCY_KEYS`，因此在测试环境中设置它，例如用 `vitest.config.mts` 中的 `test.env`。

用一个带小延迟的 mock 支付服务商，让两个同时发出的请求重叠：

```typescript
@@filename(test/pay-order.e2e-spec)
import { ValidationPipe, type INestApplication } from '@nestjs/common';
import { InMemoryIdempotencyStore } from '@nestjs/idempotency';
import { Test } from '@nestjs/testing';
import { setTimeout } from 'node:timers/promises';
import { EMPTY } from 'rxjs';
import request from 'supertest';
import type { MockInstance } from 'vitest';
import { AppModule } from '../src/app.module.js';
import { DrizzleIdempotencyStore } from '../src/idempotency/drizzle-idempotency.store.js';
import { SHIPPING_SERVICE } from '../src/orders/orders.service.js';
import { PaymentProviderClient } from '../src/payments/payment-provider.client.js';

describe('POST /orders/:id/pay', () => {
  let app: INestApplication;
  let charge: MockInstance<PaymentProviderClient['charge']>;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(DrizzleIdempotencyStore)
      .useValue(new InMemoryIdempotencyStore())
      .overrideProvider(SHIPPING_SERVICE)
      .useValue({ emit: () => EMPTY })
      .compile();

    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
    await app.listen(0, '127.0.0.1');

    charge = vi.spyOn(app.get(PaymentProviderClient), 'charge').mockImplementation(async (input) => {
      await setTimeout(100); // 慢到足以让重复请求重叠
      return {
        id: 'ch_test',
        amount: input.amount,
        cardLast4: '4242',
        reference: input.reference,
        createdAt: new Date().toISOString(),
      };
    });
  });

  afterEach(() => app.close());

  const pay = (key: string) =>
    request(app.getHttpServer())
      .post('/orders/ord_1001/pay')
      .set('Authorization', 'Bearer alice-token')
      .set('Idempotency-Key', key)
      .send({ paymentMethod: 'pm_card_visa' });

  it('charges once when the app retries', async () => {
    const first = await pay('key-1').expect(201);
    const retry = await pay('key-1').expect(201).expect('Idempotent-Replayed', 'true');

    expect(retry.body).toEqual(first.body);
    expect(charge).toHaveBeenCalledTimes(1);
  });

  it('rejects a duplicate that arrives while the first is in flight', async () => {
    const [a, b] = await Promise.all([pay('key-2'), pay('key-2')]);

    expect([a.status, b.status].sort()).toEqual([201, 409]);
    expect(charge).toHaveBeenCalledTimes(1);
  });
});
```

应用初始化完成后，`app.get(IdempotencyStorage).source` 返回正在使用的存储，此处为内存存储。它的 `peek(key)` 方法返回 `usr_alice:key-1` 这类记录键下的原始记录（`state`、`fingerprint` 与 `response`），可用于「被拒的支付已保存」之类的断言。请单独用[把键存进 PostgreSQL](/reliability/idempotency#store-keys-in-postgresql) 中的契约套件、针对真实服务器测试你自己的存储。若要在端到端测试中保留 Drizzle 存储，请替换 `DrizzleModule` 注册的数据库，使用 `overrideProvider(getDrizzleToken()).useValue(db)`（`getDrizzleToken` 来自 `@nestjs/drizzle`），其中 `db` 是运行在 PGlite 上、已用你的迁移迁移过的 Drizzle 数据库。示例项目就这样测试加密、GraphQL、事件与调优。

测试环境的更多内容见[端到端测试](/fundamentals/testing#end-to-end-testing)。

#### 生产检查清单

- 注册一个共享存储（你的数据库，或 Redis），即使只有一个实例：内存记录在每次重启或部署时丢失，之后的某次重试会再次运行处理器。用 `concurrent` 对它运行契约套件。生产环境下没有存储应用会拒绝启动，除非设置了 `allowInMemoryStorage`。用 Redis 时配置 `maxmemory-policy noeviction`。被提前驱逐的记录就是一次待发生的二次扣款；而且由于每条幂等记录都有 TTL，`volatile-*` 策略也会驱逐它们。
- 对每个涉及资金或会创建顾客会重复感知的资源的端点设 `required: true`。
- 为每个面向客户端的端点设置 `scope`。没有它，一个用户的键可以重放另一个用户的响应。已登录用户调用没有 `scope` 的处理器时，模块会记录警告。
- 让幂等拦截器位于其他全局拦截器之外。全局拦截器按注册顺序运行，而 `AppModule` 的 `APP_INTERCEPTOR` 提供者先于它所导入模块的提供者注册，因此它们运行在幂等拦截器之外，会看到每一次重放。模块在启动时会就它们发出警告。当其中之一是 `ClassSerializerInterceptor` 时，它会拒绝启动，因为重放会把普通对象交给它，从而发出被 `@Exclude()` 隐藏的字段。请在 `main.ts` 中用 `app.useGlobalInterceptors()` 注册这类拦截器，或放在 `IdempotencyModule` 之后导入的模块中。
- 用数据库存储时，通过迁移创建它的表，为它的语句调整连接池大小，保持实例时钟同步，并按计划调用 `prune()`。
- 让 `ttl` 高于客户端的重试窗口。`lockTtl` 只需覆盖崩溃，因为处理器运行期间锁会被续租。
- 关注事件。`IdempotencyEvents` 可注入，其 `events$` 流报告每次重放、每次被拒绝（含 `code`）以及每次锁丢失。同样的事件也发布到 `nestjs:idempotency:replayed`、`nestjs:idempotency:rejected` 与 `nestjs:idempotency:lock-lost` 诊断通道，供追踪工具使用。对 `lock-lost` 设告警：它意味着本次尝试的结果不在存储中，原因是续租失败（存储不可达，或事件循环阻塞超过 `lockTtl`），或是写入结果时存储失败，重试可能再次运行处理器。
- 当响应包含个人或支付数据时开启 `encryption`，并要在端点保存第一条记录之前。把密钥放在密钥管理服务中，按上面三步轮换，且在 `ttl` 过去之前绝不移除密钥。
- 给支付服务商传一个由用户 id 与幂等键推导出的键，以覆盖扣款之后的失败。
- 多个服务共用一个 Redis 时，给每个服务自己的键前缀（存储中的 `idem:`）或自己的数据库。记录键只在一个服务内唯一：两个服务可以各有一个同名处理器类，而客户端可能把同一个键发给两者。
- 把状态检查留在服务中，最好写成带条件的数据库更新。幂等键去重的是同一次尝试的重试，而两次点击创建两个键就是两次尝试。
- 允许浏览器发送该头。对跨源客户端，把 `Idempotency-Key` 加入 CORS 的 `allowedHeaders`，把 `Idempotent-Replayed` 与 `Retry-After` 加入 `exposedHeaders`。
- 让幂等响应保持小。整个响应体都会被保存，而该包目前还没有大小限制。

#### 存储契约

教程用 Drizzle、TypeORM 与 Redis 分别写过存储。本节总结任何 `IdempotencyStore` 必须做什么，供你用其他 ORM 实现时参考。包 README 的「Implementing a store」有每个方法的详细说明。

**注册。** 存储是普通的单例提供者，在构造函数中对可注入的 `IdempotencyStorage` 调用 `registerSource(this)`。注册表会立刻检查形状，拒绝第二次注册（除非传 `replace: true`），并在 `IdempotencyModule` 初始化时锁定，记录所使用的存储。什么都没注册时，模块使用 `InMemoryIdempotencyStore`，它无法在实例间共享，重启即丢记录。`NODE_ENV=production` 时改为启动失败，除非你设置 `allowInMemoryStorage: true`，即接受每次重启或部署都丢记录。

**方法。** 四个方法都是原子的：每个都在决定谁持有键，而「先读再单独写」会让两个请求都运行处理器，这正是该包要防止的二次扣款。它们都不接受你的事务：幂等记录独立写入，绝不作为业务事务的一部分。

| 方法 | 作用 | 如何保持原子 |
| --- | --- | --- |
| `acquire(key, owner, fingerprint, lockTtl)` | 在空闲或已过期的键上加锁，或返回找到的记录 | 一条 insert 在同一条语句中接管过期行，因此众多并发调用者中恰有一个成功；其余读取胜者的记录 |
| `complete(key, owner, response, ttl)` | 把 owner 的有效锁变成已完成记录 | 比较并设置：owner 与过期检查都在写入语句的 `WHERE` 中 |
| `release(key, owner)` | 删除 owner 的有效锁，好让重试可以运行处理器 | 比较并设置，同 `complete()` |
| `extend(key, owner, lockTtl)` | 续租 owner 的有效锁 | 比较并设置，同 `complete()` |

**使用 Prisma。** 以 Drizzle 与 TypeORM 的存储为范本，使用同一张表：

- **`acquire()`** 是一条 `INSERT ... ON CONFLICT (key_hash) DO UPDATE ... WHERE expires_at <= now RETURNING`。Prisma 的 `upsert()` 对更新没有条件，因此用 `$queryRaw`。没有返回行时，像其他存储那样读取记录。
- **`complete()`、`release()` 与 `extend()`** 把 owner 与过期放进 `WHERE` 并统计行数：在 `where` 中用 `keyHash`、`owner` 与 `expiresAt` 上的 `gt: now` 过滤，调用 `updateMany()` 或 `deleteMany()`，判断 `count === 1`。不要用 `findUnique()` 之后 `update()`：它会先读。
- **响应列**在任何 ORM 中都用 `json` 而不是 `jsonb`：`jsonb` 会拒绝字符串内的 `\u0000`，而响应体可能包含它。

**测试它**：用 `@nestjs/idempotency/testing` 的套件，就像 Drizzle、TypeORM 与 Redis 存储所做的那样。`idempotencyStoreContract()` 返回适用于任何测试运行器的用例。`concurrent: true` 让每个键有 16 个调用者竞争；请在带连接池的 PostgreSQL 上运行，那里的调用才真正重叠。`advanceTime` 为过期用例推动存储的时钟，不提供则它们按真实时间等待。

#### 参考

##### 模块选项

`IdempotencyModule.forRoot()` 接受这些选项。`forRootAsync()` 在顶层接受 `isGlobal` 与 `imports`，与 `useFactory`、`useClass` 或 `useExisting` 并列，工厂返回其余部分。除 `header`、`replayHeaders`、`storeTimeout`、`encryption`、`allowInMemoryStorage` 与 `isGlobal` 之外，每个选项都可以在 `@Idempotent()` 中按类或处理器设置，并逐字段合并覆盖模块的配置。

| 选项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `required` | `boolean` | `false` | 以 `IDEMPOTENCY_KEY_REQUIRED` 拒绝没有键的调用。见[让支付端点具备幂等性](/reliability/idempotency#make-the-payment-endpoint-idempotent)。 |
| `scope` | 函数、对象或 `false` | 无 | 键的命名空间，例如用户 id。对象在 `http`、`graphql` 与 `rpc` 下各放一个函数。`false` 表示有意共用一个命名空间。 |
| `ttl` | `Duration` | `'24h'` | 已完成结果可被重放多久。见[调整 TTL 与失败处理](/reliability/idempotency#tune-ttls-and-failure-handling)。 |
| `lockTtl` | `Duration` | `'60s'` | 续租停止后进行中的锁还能存活多久。锁每 `lockTtl / 3` 续租一次。 |
| `maxLockHold` | `Duration` | `'1h'` | 运行中的处理器持续续租锁的最长时间。见[调整 TTL 与失败处理](/reliability/idempotency#tune-ttls-and-failure-handling)。 |
| `retryAfter` | `Duration` | `'1s'` | 随 `IDEMPOTENCY_KEY_IN_USE` 发出的等待时间，以整秒计、向上取整。 |
| `keyFrom` | 来源，或每个上下文一个来源 | 见下文 | 键的来源：`header`、`arg`（GraphQL）、`payload`（微服务），或 `ExecutionContext` 的函数。 |
| `fingerprint` | `(payload, context) => unknown` | 整个负载 | 重试必须重复什么。方法、URL、GraphQL 字段或消息模式，以及 scope 始终计入。 |
| `storeIf` | `(status, error) => boolean` | `status < 500` | 哪些结果被保存并重放。其他结果会释放键。 |
| `header` | `string` | `'Idempotency-Key'` | HTTP 头，GraphQL 也会读取；微服务下为传输头名称。 |
| `replayHeaders` | `string[]` | 无 | 除 `Location`、`Content-Type`、`Content-Language`、`Content-Location`、`ETag` 与 `Last-Modified` 之外要重放的响应头。`Set-Cookie` 与平台为每个响应写入的头会在启动时被拒绝。 |
| `storeTimeout` | `Duration` | `'10s'` | 每次存储调用（`acquire()`、`complete()`、`release()` 与 `extend()`）允许耗时。见[错误](/reliability/idempotency#errors)。 |
| `encryption` | 含 `keys` 的对象 | 关闭 | 对保存的记录做 AES-256-GCM 加密。`keys` 列出 32 字节的 `Buffer` 或至少 32 字符的字符串，最新的在前。见[加密保存的凭据](/reliability/idempotency#encrypt-stored-receipts)。 |
| `allowInMemoryStorage` | `boolean` | `false` | 允许生产应用在未注册存储时启动。 |
| `isGlobal` | `boolean` | `true` | 全局注册模块。 |

每个时长接受毫秒数，或 `'45s'`、`'48h'`、`'7d'` 这样的字符串。

默认情况下键来自这些来源：

| 上下文 | 默认来源 |
| --- | --- |
| HTTP | `Idempotency-Key` 头（`header` 选项） |
| GraphQL | mutation 的 `idempotencyKey` 参数，然后是头 |
| 微服务 | 负载的 `idempotencyKey` 属性，然后是由 `header` 指定的传输头 |

键为 1 到 255 个可打印 ASCII 字符。负载中的数字按其数字串计。

##### 事件

`IdempotencyEvents.events$` 发出每个事件，每个事件也发布到一个诊断通道。每个负载都有 `type`、`context`（`'http'`、`'graphql'` 或 `'rpc'`）、`handler`（如 `OrdersController.pay`）、`key`，以及存在时的 `scope`。

| 类型 | 通道 | 负载类型 | 其他字段 | 时机 |
| --- | --- | --- | --- | --- |
| `replayed` | `nestjs:idempotency:replayed` | `IdempotencyReplayedEvent` | `status` | 重试拿到了保存的结果，或重复事件被跳过 |
| `rejected` | `nestjs:idempotency:rejected` | `IdempotencyRejectedEvent` | `code`、`status` | 调用在处理器运行之前被拒绝。`IDEMPOTENCY_KEY_REQUIRED` 与 `IDEMPOTENCY_KEY_INVALID` 没有 `key`。 |
| `lock-lost` | `nestjs:idempotency:lock-lost` | `IdempotencyLockLostEvent` | `phase`（`'extend'`、`'complete'` 或 `'release'`） | 本次尝试的结果不在存储中，重试可能再次运行处理器 |

`IdempotencyEvent` 是三种负载类型的联合。

##### 错误

拒绝会携带下列代码之一，类型为 `IdempotencyErrorCode`。HTTP 下代码在响应体中。GraphQL 下在字段错误的 `extensions` 中，含 `httpStatus`，409 时还有 `retryAfter`。微服务下 `RpcException` 负载含 `status`、`code`、`statusCode`、`message`，409 时还有 `retryAfter`。

| 代码 | 状态 | 消息 | 原因 |
| --- | --- | --- | --- |
| `IDEMPOTENCY_KEY_REQUIRED` | 400 | An idempotency key is required for this operation. | 没有键，且 `required: true` |
| `IDEMPOTENCY_KEY_INVALID` | 400 | The idempotency key must be 1 to 255 printable ASCII characters. | 键过长、含其他字符，或不是字符串或数字 |
| `IDEMPOTENCY_KEY_IN_USE` | 409，带 `Retry-After` | A request with this idempotency key is still being processed. | 该键的首次调用仍在运行 |
| `IDEMPOTENCY_KEY_REUSED` | 422 | This idempotency key was already used for a different request. | 同一个键搭配了不同的指纹 |
| `IDEMPOTENCY_RECORD_UNREADABLE` | 500 | The stored result for this idempotency key could not be read. | 保存的记录解密失败，例如其密钥已被移除 |

超过 `storeTimeout` 的存储调用会失败。超时的 `acquire()` 以 `IdempotencyStoreTimeoutError`（由 `@nestjs/idempotency` 导出）使请求失败。超时的 `complete()` 或 `release()` 被报告为锁丢失，结果仍会返回给调用方。
