Skip to content

Commit 75a375b

Browse files
nshkiCopilot
andcommitted
fix(hub): keep index counts consistent
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88d7ad2d-de3c-4d5a-95fc-ced290856050
1 parent 22d8d3d commit 75a375b

2 files changed

Lines changed: 109 additions & 19 deletions

File tree

‎hub/server/repositories/prototype-index/find-repository-index/index.ts‎

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import type { Prisma } from "../../../generated/prisma/client.ts"
1+
import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts"
22

33
const pageSize = 24
44

55
export async function findRepositoryIndex(
6-
database: Pick<Prisma.TransactionClient, "prototype" | "repository">,
6+
database: Pick<PrismaClient, "$transaction" | "prototype" | "repository">,
77
repositoryId: string,
88
) {
99
const repository = await database.repository.findFirst({
@@ -19,24 +19,28 @@ export async function findRepositoryIndex(
1919
replica: false,
2020
branchName: { notIn: [repository.defaultBranch, "replica/install-workflow"] },
2121
}
22-
const [records, totalCount] = await Promise.all([
23-
database.prototype.findMany({
24-
where,
25-
orderBy: [{ registeredAt: "desc" }, { id: "desc" }],
26-
take: pageSize,
27-
select: {
28-
id: true,
29-
repositoryId: true,
30-
name: true,
31-
description: true,
32-
branchName: true,
33-
author: {
34-
select: { id: true, profile: { select: { login: true, name: true, provider: true } } },
22+
// Keep the count and cards from the same database snapshot.
23+
const [records, totalCount] = await database.$transaction(
24+
[
25+
database.prototype.findMany({
26+
where,
27+
orderBy: [{ registeredAt: "desc" }, { id: "desc" }],
28+
take: pageSize,
29+
select: {
30+
id: true,
31+
repositoryId: true,
32+
name: true,
33+
description: true,
34+
branchName: true,
35+
author: {
36+
select: { id: true, profile: { select: { login: true, name: true, provider: true } } },
37+
},
3538
},
36-
},
37-
}),
38-
database.prototype.count({ where }),
39-
])
39+
}),
40+
database.prototype.count({ where }),
41+
],
42+
{ isolationLevel: "RepeatableRead" },
43+
)
4044
const currentRepository = await database.repository.findFirst({
4145
where: { id: repositoryId, removedAt: null, defaultBranch: repository.defaultBranch },
4246
select: { id: true },

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

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,92 @@ describe("real product index", () => {
424424
})
425425
})
426426

427+
it("keeps the prototype count consistent when a branch is retired during the read", async () => {
428+
const repositoryId = randomUUID()
429+
const prototypeId = randomUUID()
430+
const retiredAt = new Date("2026-11-10T00:00:00Z")
431+
await prisma.repository.create({
432+
data: { id: repositoryId, nameWithOwner: "team/design", defaultBranch: "main" },
433+
})
434+
await prisma.prototype.create({
435+
data: {
436+
id: prototypeId,
437+
repositoryId,
438+
branchName: "prototype/welcome",
439+
name: "Welcome",
440+
registeredAt: new Date(),
441+
},
442+
})
443+
const writer = new pg.Client({ connectionString: getDatabaseUrl() })
444+
onTestFinished(async () => {
445+
await writer.end()
446+
})
447+
await writer.connect()
448+
const query: typeof pg.Client.prototype.query = Reflect.get(pg.Client.prototype, "query")
449+
let retirement: Promise<void> | undefined
450+
function timeQueries(this: pg.Client, config: unknown, values?: unknown, callback?: unknown) {
451+
const sql =
452+
typeof config === "object" && config !== null && "text" in config ? config.text : undefined
453+
if (typeof sql !== "string" || !/\bselect\b/i.test(sql) || !/\bprototypes\b/i.test(sql)) {
454+
return Reflect.apply(query, this, [config, values, callback]) as
455+
Promise<pg.QueryResult> | undefined
456+
}
457+
458+
const done = (
459+
typeof callback === "function"
460+
? callback
461+
: typeof values === "function"
462+
? values
463+
: undefined
464+
) as ((error: Error | null, result?: pg.QueryResult) => void) | undefined
465+
function read(this: pg.Client) {
466+
return Reflect.apply(query, this, [
467+
config,
468+
typeof values === "function" ? undefined : values,
469+
]) as Promise<pg.QueryResult>
470+
}
471+
let result: Promise<pg.QueryResult>
472+
if (!retirement) {
473+
const firstRead = read.call(this)
474+
retirement = firstRead.then(async () => {
475+
await writer.query("UPDATE prototypes SET branch_deleted_at = $1 WHERE id = $2", [
476+
retiredAt,
477+
prototypeId,
478+
])
479+
})
480+
result = retirement.then(() => firstRead)
481+
} else {
482+
result = retirement.then(() => read.call(this))
483+
}
484+
if (!done) return result
485+
void result.then(
486+
(rows) => done(null, rows),
487+
(error: unknown) => done(error instanceof Error ? error : new Error(String(error))),
488+
)
489+
}
490+
// Keep the database reads real while the branch changes.
491+
const timing = vi
492+
.spyOn(pg.Client.prototype, "query")
493+
.mockImplementation(
494+
timeQueries as (...args: Parameters<typeof pg.Client.prototype.query>) => void,
495+
)
496+
onTestFinished(() => timing.mockRestore())
497+
498+
const index = await createProductRouteDependencies().findRepositoryIndex(repositoryId)
499+
timing.mockRestore()
500+
501+
expect(index).toMatchObject({
502+
prototypes: [{ id: prototypeId }],
503+
pagination: { totalCount: 1 },
504+
})
505+
expect(
506+
await prisma.prototype.findUnique({
507+
where: { id: prototypeId },
508+
select: { branchDeletedAt: true },
509+
}),
510+
).toEqual({ branchDeletedAt: retiredAt })
511+
}, 8_000)
512+
427513
it("does not return an index when a repository changes during the read", async () => {
428514
const removedId = randomUUID()
429515
const changedId = randomUUID()

0 commit comments

Comments
 (0)