mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 11:29:51 +08:00
fix: 错题更新在事务内复核乐观锁
- 在写事务内重新读取 updatedAt,过期提交返回 409,避免并发编辑静默覆盖。 - 补充事务内复核与并发提交的单元/集成测试。 - Refs: https://github.com/margrop/wrong-notebook/issues/197
This commit is contained in:
@@ -1043,6 +1043,26 @@ describe('/api/error-items', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('事务内复核 expectedUpdatedAt:事务外校验后被并发更新覆盖时返回 409', async () => {
|
||||
const staleUpdatedAt = new Date('2026-01-01T00:00:00.000Z');
|
||||
const freshUpdatedAt = new Date('2026-01-01T00:00:01.000Z');
|
||||
const existingItem = { id: 'e1', userId: 'user-123', updatedAt: staleUpdatedAt };
|
||||
// 事务外预检返回旧版本;角色查询读取归属;事务内复核读到并发提交后的版本
|
||||
mocks.mockPrismaErrorItem.findUnique
|
||||
.mockResolvedValueOnce(existingItem)
|
||||
.mockResolvedValueOnce({ userId: 'user-123', subjectId: null })
|
||||
.mockResolvedValueOnce({ updatedAt: freshUpdatedAt });
|
||||
|
||||
const response = await PUT(new Request('http://localhost/api/error-items/e1', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ questionText: '并发编辑后的正文', expectedUpdatedAt: staleUpdatedAt.toISOString() }),
|
||||
}), { params: Promise.resolve({ id: 'e1' }) });
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
expect((await response.json()).message).toBe('ITEM_UPDATED_BY_OTHER');
|
||||
expect(mocks.mockPrismaErrorItem.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('应该拒绝更新其他用户的错题', async () => {
|
||||
const existingItem = {
|
||||
id: 'error-item-1',
|
||||
|
||||
@@ -413,4 +413,25 @@ describe('错题本共享', () => {
|
||||
})), params(item.id));
|
||||
expect(saved.status).toBe(200);
|
||||
});
|
||||
|
||||
it('同一 expectedUpdatedAt 并发提交时仅一条成功,另一条返回 409', async () => {
|
||||
const { item } = await seedNotebook(alice.id);
|
||||
signInAs(alice);
|
||||
const before = await database.errorItem.findUnique({
|
||||
where: { id: item.id },
|
||||
select: { updatedAt: true },
|
||||
});
|
||||
const expectedUpdatedAt = before!.updatedAt.toISOString();
|
||||
const update = (questionText: string) => UPDATE_ITEM(new Request(`http://localhost/api/error-items/${item.id}`, json({
|
||||
questionText, expectedUpdatedAt,
|
||||
})), params(item.id));
|
||||
|
||||
const [first, second] = await Promise.all([update('并发提交 A'), update('并发提交 B')]);
|
||||
const statuses = [first.status, second.status].sort((a, b) => a - b);
|
||||
expect(statuses).toEqual([200, 409]);
|
||||
const conflictBody = await (first.status === 409 ? first : second).json();
|
||||
expect(conflictBody.message).toBe('ITEM_UPDATED_BY_OTHER');
|
||||
const stored = await database.errorItem.findUnique({ where: { id: item.id }, select: { questionText: true } });
|
||||
expect(['并发提交 A', '并发提交 B']).toContain(stored?.questionText);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -174,7 +174,17 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext
|
||||
logger.info({ id }, 'Updating error item');
|
||||
|
||||
// 将「解析标签 + 更新错题记录(含标签 set/connect)」放入同一事务,保证中途失败不会留下新建的孤立标签或半更新状态
|
||||
const expectedDate = expectedUpdatedAt ? new Date(expectedUpdatedAt) : null;
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
// 乐观锁必须在写事务内复核:事务外校验与写入之间的并发提交会静默覆盖先写入的字段
|
||||
if (expectedDate) {
|
||||
const current = await tx.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: { updatedAt: true },
|
||||
});
|
||||
if (!current || current.updatedAt.getTime() !== expectedDate.getTime()) return null;
|
||||
}
|
||||
|
||||
// 处理 knowledgePoints (标签)
|
||||
if (tagNames !== undefined) {
|
||||
// 推断学科和标签体系
|
||||
@@ -206,6 +216,7 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext
|
||||
});
|
||||
});
|
||||
|
||||
if (!updated) return conflict("ITEM_UPDATED_BY_OTHER");
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
logger.error({ error }, 'Error updating item');
|
||||
|
||||
Reference in New Issue
Block a user