@yarlisai/idempotency
幂等操作原语 — 原子键声明、结果重放、TTL 过期与清理。
适用于 webhook、轮询器以及任何必须且只能执行一次的操作的幂等原语 — 包括原子键声明、结果存储与重放、重试释放、TTL 过期以及过期键清理。
安装
npm install @yarlisai/idempotency源码:packages/idempotency ·
npm ·
CHANGELOG
设计理念
@yarlisai/idempotency 遵循端口/适配器契约:使用方依赖 IdempotencyProvider 端口,并在运行时实例化适配器。v1 版本随附两个适配器:
postgres— 基于 drizzle 实现,支持可选的兼容 Redis 的缓存快速路径。调用方注入自己的db、idempotency_key表引用以及and/eq/lt操作符,因此本包不会额外捆绑drizzle-orm或ioredis的副本。memory— 带 TTL 的进程内 Map,适用于测试和单实例部署。
使用方法
import { createIdempotencyClient } from '@yarlisai/idempotency'
import { and, eq, lt } from 'drizzle-orm'
const webhookIdempotency = createIdempotencyClient({
adapter: 'postgres',
db,
table: idempotencyKey,
operators: { and, eq, lt },
namespace: 'webhook',
ttlSeconds: 60 * 60 * 24 * 7,
})
const claim = await webhookIdempotency.atomicallyClaim('stripe', event.id)
if (!claim.claimed) return // duplicate delivery本包的 README 提供了完整的快速入门指南。mybotbox-platform 本身即为参考消费方 — apps/sat/lib/idempotency/ 展示了每个调用点如何使用端口而非直接访问数据库。