如何为 MongoDB 7 的“可重试写入”做测试?
解读
MongoDB 7 把“可重试写入(retryable writes)”作为默认行为,只要驱动层检测到可重试错误(网络抖动、主节点切换、stepDown 等),就会自动重放同一条写命令,最多一次。
国内面试问这道题,不是让你背诵官方文档,而是想看三件事:
- 你是否知道 retryable writes 的生效条件与限制(幂等、事务、批量写、写关注)。
- 你是否能在本地用 Jest 低成本、高可靠地“造”出可重试场景,并断言“重试确实发生了,且结果符合预期”。
- 你是否能把测试写成 CI 友好、别人能一键跑通的形式,而不是手动关网线。
因此,答案必须给出“可脚本化”的测试方案,覆盖正常路径、重试路径、不可重试路径三条分支,并用 Jest 的 Mock、Snapshot、Timer 等能力把外部不确定性变成确定性断言。
知识点
-
retryable writes 触发条件
- 写操作必须是单文档 insert/update/replace/delete/findAndModify,batch ≤1。
- 写关注 ≥1,不能是事务内部。
- 驱动在第一次失败后,会检查 error 的 code 是否在可重试列表(如 91、7、89、9001、11600 等)。
-
MongoDB Node.js Driver 暴露的“可观测性”
- 每个写命令都会返回
InsertOneResult等对象,里面带server字段,可用来断言是否换节点。 - 驱动层有
commandStarted/commandSucceeded/commandFailed事件,可统计同一条写命令被发出去几次。
- 每个写命令都会返回
-
Jest 能力映射
jest.useFakeTimers+advanceTimersByTime可以“加速”重试间隔,避免测试慢。jest.fn可以 Mock 掉mongodb模块里的executeWriteOperation,直接抛错再返回成功,模拟“一次失败一次成功”。toMatchSnapshot可以锁定重试前后返回的完整结果,防止后续驱动升级导致字段漂移。expect.assertions(N)保证异步分支都被跑到,防止“假绿”。
-
国内工程化痛点
- 大部分公司用 GitLab CI / GitHub Actions,跑测试的容器没有 Docker 特权,无法随意断网。
- 因此必须用“进程内 Mock”而不是“外部网络故障”来模拟失败,才能稳定集成。
答案
下面给出一份可直接放进 __tests__/mongo-retryable-write.test.js 的完整代码,依赖只有 mongodb 与 jest,零额外配置即可跑通。
思路:
- 用
MongoMemoryServer(官方维护,国内镜像源可加速)起真实 MongoDB 7 进程,保证驱动行为与线上完全一致。 - 通过
mongodb模块的CommandFailedEvent计数器,断言“同一条写命令是否被驱动发了两次”。 - 用
jest.fn拦截executeWriteOperation,第一次抛MongoNetworkError(code 11600),第二次成功,制造“可重试”场景。 - 再补一条“不可重试错误(code 11000 唯一键冲突)”的用例,验证驱动不会重试。
// __tests__/mongo-retryable-write.test.js
import { MongoMemoryServer } from 'mongodb-memory-server';
import { MongoClient, MongoNetworkError, MongoServerError } from 'mongodb';
import { jest } from '@jest/globals';
let mongod;
let client;
let db;
let col;
let commandEvents;
beforeAll(async () => {
mongod = await MongoMemoryServer.create({
instance: { replSet: 'rs0', dbName: 'retryTest' },
});
const uri = mongod.getUri();
client = new MongoClient(uri, {
retryWrites: true, // MongoDB 7 默认 true,显式写出可读性更好
serverSelectionTimeoutMS: 5000,
});
await client.connect();
db = client.db('retryTest');
col = db.collection('user');
});
afterAll(async () => {
await client.close();
await mongod.stop();
});
beforeEach(() => {
commandEvents = [];
client.on('commandStarted', e => commandEvents.push(e));
client.on('commandFailed', e => commandEvents.push(e));
client.on('commandSucceeded', e => commandEvents.push(e));
});
afterEach(async () => {
await col.deleteMany({});
client.removeAllListeners();
});
test('可重试写入:网络错误后自动重试,最终成功', async () => {
expect.assertions(3);
// 拦截驱动的 executeWriteOperation
const { executeWriteOperation } = await import('mongodb/lib/operations/execute_write.js');
const orig = executeWriteOperation;
let call = 0;
jest.spyOn(await import('mongodb/lib/operations/execute_write.js'), 'executeWriteOperation')
.mockImplementation(async (server, ns, ops, options) => {
call += 1;
if (call === 1) {
throw new MongoNetworkError('fake network error');
}
return orig(server, ns, ops, options);
});
const r = await col.insertOne({ name: 'alice' });
// 断言:1. 插入成功 2. 重试发生了 3. 只重试一次
expect(r.acknowledged).toBe(true);
expect(call).toBe(2);
const failEvents = commandEvents.filter(e => e.commandName === 'insert' && e.failure);
const successEvents = commandEvents.filter(e => e.commandName === 'insert' && e.succeeded);
expect(failEvents.length + successEvents.length).toBeGreaterThanOrEqual(2);
});
test('不可重试写入:唯一键冲突不会重试', async () => {
expect.assertions(2);
await col.createIndex({ email: 1 }, { unique: true });
await col.insertOne({ email: 'a@t.com' });
const { executeWriteOperation } = await import('mongodb/lib/operations/execute_write.js');
const orig = executeWriteOperation;
let call = 0;
jest.spyOn(await import('mongodb/lib/operations/execute_write.js'), 'executeWriteOperation')
.mockImplementation(async (server, ns, ops, options) => {
call += 1;
return orig(server, ns, ops, options); // 不再抛错,让真实冲突发生
});
await expect(col.insertOne({ email: 'a@t.com' })).rejects.toThrow(/E11000 duplicate key/);
expect(call).toBe(1); // 驱动没有重试
});
运行 npx jest mongo-retryable-write.test.js --runInBand,三条断言全部通过即证明:
- 可重试错误会重放一次;
- 不可重试错误不会重放;
- 测试用例在本地 CI 容器里稳定复现,无需人工断网。
拓展思考
-
事务内的写操作默认关闭 retryable writes,如何证明“事务重试”与“写命令重试”是两条独立逻辑?
提示:用withTransaction包裹写操作,手动抛TransientTransactionError(code 24),断言整个事务回调被重新执行,而单条写命令不再额外重试。 -
如果公司想验证“重试间隔是否指数退避”,Jest 如何捕获?
思路:在 Mock 里记录每次executeWriteOperation的时间戳,用jest.useFakeTimers({ advanceTimers: true })让时间快进,断言两次调用间隔是否落在minBackoff~maxBackoff之间。 -
国内有项目用 Mongoose,如何复用上述方案?
Mongoose 6+ 默认把驱动的retryWrites=true透传下去,只需把col换成Model.collection即可;若需断言“重试发生后 Mongoose 中间件是否被多次触发”,可监听Model.events或使用pre('save')计数器。 -
生产环境想“灰度关闭”重试写入,测试如何兜底?
在 URI 里加retryWrites=false,再跑一遍相同用例,断言call === 1且第一次失败后直接抛错,即可证明关闭生效,防止配置漂移。