Skip to content

Commit d04b353

Browse files
Ben ThomasCopilot
authored andcommitted
fix(hub): harden review conversation races
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent f0896fd commit d04b353

5 files changed

Lines changed: 137 additions & 16 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { describe, expect, it, vi } from "vitest"
2+
3+
import { createReviewCommentService } from "."
4+
5+
describe("createReviewCommentService()", () => {
6+
it("returns a conflict after bounded transaction retries are exhausted", async () => {
7+
const transaction = vi.fn().mockRejectedValue({ originalCode: "40001" })
8+
const service = createReviewCommentService({ $transaction: transaction })
9+
10+
await expect(
11+
service.deleteComment({
12+
repositoryId: "4bb7f30d-d68e-45c7-b15f-a5e1bcd6ac43",
13+
prototypeId: "ddcbd25d-72b4-45be-9324-677b4ca04dac",
14+
commentId: 1,
15+
actor: {
16+
userId: "1d92c847-f217-4c48-9824-e25d4a36f821",
17+
login: "mona",
18+
name: "Mona",
19+
},
20+
}),
21+
).rejects.toMatchObject({
22+
code: "conflict",
23+
message: "The review thread changed. Try again.",
24+
})
25+
expect(transaction).toHaveBeenCalledTimes(3)
26+
})
27+
})

‎hub/server/domains/review-comments/create-review-comment-service/index.ts‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts"
2+
import { classifyPrismaTransactionError } from "../../../integrations/prisma/classify-transaction-error/index.ts"
23
import { createReviewCommentRepository } from "../../../repositories/review-comments/create-review-comment-repository/index.ts"
34
import type { ReviewPersistenceFailure } from "../../../repositories/review-comments/types.ts"
5+
import { runWithBoundedRetries } from "../../identity/run-with-bounded-retries/index.ts"
46
import { ReviewCommentError } from "../errors.ts"
57
import { parseReviewAnchor } from "../parse-review-anchor/index.ts"
68
import { parseReviewBody } from "../parse-review-body/index.ts"
@@ -38,6 +40,20 @@ function persistenceError(reason: ReviewPersistenceFailure): ReviewCommentError
3840
}
3941
}
4042

43+
async function runReviewMutation<Result>(operation: () => Promise<Result>): Promise<Result> {
44+
try {
45+
return await runWithBoundedRetries(
46+
() => operation(),
47+
(error) => classifyPrismaTransactionError(error) === "retryable",
48+
)
49+
} catch (error) {
50+
if (classifyPrismaTransactionError(error) === "retryable") {
51+
throw new ReviewCommentError("conflict", "The review thread changed. Try again.")
52+
}
53+
throw error
54+
}
55+
}
56+
4157
export function createReviewCommentService(
4258
database: Pick<PrismaClient, "$transaction">,
4359
): ReviewCommentService {
@@ -49,37 +65,33 @@ export function createReviewCommentService(
4965
return result.value.map(serializeReviewThread)
5066
},
5167
async createThread(input) {
52-
const result = await repository.createThread({
53-
...input,
54-
body: parseReviewBody(input.body),
55-
anchor: parseReviewAnchor(input.anchor) as unknown as Prisma.InputJsonValue,
56-
})
68+
const body = parseReviewBody(input.body)
69+
const anchor = parseReviewAnchor(input.anchor) as unknown as Prisma.InputJsonValue
70+
const result = await runReviewMutation(() =>
71+
repository.createThread({ ...input, body, anchor }),
72+
)
5773
if (!result.ok) throw persistenceError(result.reason)
5874
return serializeReviewThread(result.value)
5975
},
6076
async createReply(input) {
61-
const result = await repository.createReply({
62-
...input,
63-
body: parseReviewBody(input.body),
64-
})
77+
const body = parseReviewBody(input.body)
78+
const result = await runReviewMutation(() => repository.createReply({ ...input, body }))
6579
if (!result.ok) throw persistenceError(result.reason)
6680
return serializeReviewThread(result.value)
6781
},
6882
async editComment(input) {
69-
const result = await repository.editComment({
70-
...input,
71-
body: parseReviewBody(input.body),
72-
})
83+
const body = parseReviewBody(input.body)
84+
const result = await runReviewMutation(() => repository.editComment({ ...input, body }))
7385
if (!result.ok) throw persistenceError(result.reason)
7486
return serializeReviewThread(result.value)
7587
},
7688
async deleteComment(input) {
77-
const result = await repository.deleteComment(input)
89+
const result = await runReviewMutation(() => repository.deleteComment(input))
7890
if (!result.ok) throw persistenceError(result.reason)
7991
return serializeReviewThread(result.value)
8092
},
8193
async setResolution(input) {
82-
const result = await repository.setResolution(input)
94+
const result = await runReviewMutation(() => repository.setResolution(input))
8395
if (!result.ok) throw persistenceError(result.reason)
8496
return serializeReviewThread(result.value)
8597
},

‎hub/server/repositories/review-comments/types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Prisma } from "../../generated/prisma/client.ts"
33
export const reviewThreadInclude = {
44
prototype: { select: { id: true, name: true, branchName: true } },
55
build: { select: { number: true } },
6-
comments: { orderBy: [{ createdAt: "asc" }, { id: "asc" }] },
6+
comments: { orderBy: { publicId: "asc" } },
77
resolutionEvents: { orderBy: { sequence: "asc" } },
88
} satisfies Prisma.ReviewThreadInclude
99

‎hub/server/routes/api/repositories/prototypes/review-comments/get/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ export function get(
2727
identifiers.repositoryId,
2828
identifiers.prototypeId,
2929
)
30+
const final = await readReviewSession(request, session)
31+
if (!final || final.membershipId !== current.membershipId) {
32+
response.status(401).json({ error: "Sign in to continue." })
33+
return
34+
}
3035
const comments = threads
3136
.flatMap((thread) => presentReviewThreadComments(thread, current.userId))
3237
.sort(

‎hub/server/routes/api/review-comments/index.db.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,33 @@ describe("review comments API", () => {
203203
})
204204
})
205205

206+
it("does not return review data after the session is revoked during the read", async () => {
207+
const target = await createReviewTarget()
208+
const member = await createMember("mona", "Mona")
209+
const restore = vi.fn().mockResolvedValue(member)
210+
211+
await withServer(restore, async (baseUrl) => {
212+
const createdResponse = await fetch(`${baseUrl}${target.path}`, {
213+
method: "POST",
214+
headers: sessionHeaders,
215+
body: JSON.stringify({
216+
review_comment: {
217+
build_number: target.build.number,
218+
body: "Do not return this after revocation.",
219+
anchor,
220+
},
221+
}),
222+
})
223+
expect(createdResponse.status).toBe(201)
224+
restore.mockReset().mockResolvedValueOnce(member).mockResolvedValueOnce(null)
225+
226+
const response = await fetch(`${baseUrl}${target.path}`, { headers: sessionHeaders })
227+
228+
expect(response.status).toBe(401)
229+
expect(await response.json()).toEqual({ error: "Sign in to continue." })
230+
})
231+
})
232+
206233
it("allows only the stable author UUID to edit or delete a comment", async () => {
207234
const target = await createReviewTarget()
208235
const author = await createMember("mona", "Mona")
@@ -379,4 +406,54 @@ describe("review comments API", () => {
379406
})
380407
})
381408
})
409+
410+
it("returns the reply created by this request when timestamps do not preserve insertion order", async () => {
411+
const target = await createReviewTarget()
412+
const member = await createMember("mona", "Mona")
413+
const restore = vi.fn().mockResolvedValue(member)
414+
415+
await withServer(restore, async (baseUrl) => {
416+
const createdResponse = await fetch(`${baseUrl}${target.path}`, {
417+
method: "POST",
418+
headers: sessionHeaders,
419+
body: JSON.stringify({
420+
review_comment: {
421+
build_number: target.build.number,
422+
body: "Root",
423+
anchor,
424+
},
425+
}),
426+
})
427+
const created = (await createdResponse.json()) as { comments: { id: number }[] }
428+
const root = created.comments[0]
429+
if (!root) throw new Error("Expected a root comment")
430+
const repliesPath = `${target.path}/${root.id}/replies`
431+
const firstResponse = await fetch(`${baseUrl}${repliesPath}`, {
432+
method: "POST",
433+
headers: sessionHeaders,
434+
body: JSON.stringify({ review_comment: { body: "First reply" } }),
435+
})
436+
const first = (await firstResponse.json()) as { comments: { id: number }[] }
437+
const firstReply = first.comments[0]
438+
if (!firstReply) throw new Error("Expected a reply")
439+
await prisma.reviewComment.update({
440+
where: { publicId: firstReply.id },
441+
data: { createdAt: new Date("2099-01-01T00:00:00Z") },
442+
})
443+
444+
const secondResponse = await fetch(`${baseUrl}${repliesPath}`, {
445+
method: "POST",
446+
headers: sessionHeaders,
447+
body: JSON.stringify({ review_comment: { body: "Second reply" } }),
448+
})
449+
450+
expect(secondResponse.status).toBe(201)
451+
expect(await secondResponse.json()).toMatchObject({
452+
comments: [
453+
{ kind: "reply", body: "Second reply", rootId: root.id },
454+
{ kind: "root", id: root.id },
455+
],
456+
})
457+
})
458+
})
382459
})

0 commit comments

Comments
 (0)