Skip to content

Commit 322f24f

Browse files
nshkiCopilot
andcommitted
refactor(hub): simplify index snapshot coverage
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 88d7ad2d-de3c-4d5a-95fc-ced290856050
1 parent 75a375b commit 322f24f

2 files changed

Lines changed: 35 additions & 60 deletions

File tree

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts"
33
const pageSize = 24
44

55
export async function findRepositoryIndex(
6-
database: Pick<PrismaClient, "$transaction" | "prototype" | "repository">,
6+
database: Pick<PrismaClient, "$transaction" | "repository">,
77
repositoryId: string,
88
) {
99
const repository = await database.repository.findFirst({
@@ -20,9 +20,9 @@ export async function findRepositoryIndex(
2020
branchName: { notIn: [repository.defaultBranch, "replica/install-workflow"] },
2121
}
2222
// Keep the count and cards from the same database snapshot.
23-
const [records, totalCount] = await database.$transaction(
24-
[
25-
database.prototype.findMany({
23+
const { records, totalCount } = await database.$transaction(
24+
async (transaction) => {
25+
const records = await transaction.prototype.findMany({
2626
where,
2727
orderBy: [{ registeredAt: "desc" }, { id: "desc" }],
2828
take: pageSize,
@@ -36,9 +36,10 @@ export async function findRepositoryIndex(
3636
select: { id: true, profile: { select: { login: true, name: true, provider: true } } },
3737
},
3838
},
39-
}),
40-
database.prototype.count({ where }),
41-
],
39+
})
40+
const totalCount = await transaction.prototype.count({ where })
41+
return { records, totalCount }
42+
},
4243
{ isolationLevel: "RepeatableRead" },
4344
)
4445
const currentRepository = await database.repository.findFirst({

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

Lines changed: 27 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { describe, expect, it, onTestFinished, vi } from "vitest"
77

88
import { createApp } from "../../../create-app"
99
import { prisma } from "../../../integrations/prisma"
10+
import { findRepositoryIndex } from "../../../repositories/prototype-index/find-repository-index"
1011
import { getDatabaseUrl } from "../../../../test/database/get-database-url"
1112
import type { AuthenticationRouteDependencies } from "../auth/types"
1213
import { createProductRouteDependencies } from "../product/create-product-route-dependencies"
@@ -441,62 +442,39 @@ describe("real product index", () => {
441442
},
442443
})
443444
const writer = new pg.Client({ connectionString: getDatabaseUrl() })
444-
onTestFinished(async () => {
445-
await writer.end()
446-
})
445+
onTestFinished(() => writer.end())
447446
await writer.connect()
448-
const query: typeof pg.Client.prototype.query = Reflect.get(pg.Client.prototype, "query")
449447
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>
448+
async function readWhileRetiring<Result>(read: () => Promise<Result>) {
472449
if (!retirement) {
473-
const firstRead = read.call(this)
450+
const firstRead = read()
474451
retirement = firstRead.then(async () => {
475452
await writer.query("UPDATE prototypes SET branch_deleted_at = $1 WHERE id = $2", [
476453
retiredAt,
477454
prototypeId,
478455
])
479456
})
480-
result = retirement.then(() => firstRead)
481-
} else {
482-
result = retirement.then(() => read.call(this))
457+
await retirement
458+
return firstRead
483459
}
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-
)
460+
await retirement
461+
return read()
489462
}
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()
463+
const reader = prisma.$extends({
464+
query: {
465+
prototype: {
466+
findMany({ args, query }) {
467+
return readWhileRetiring(() => query(args))
468+
},
469+
count({ args, query }) {
470+
return readWhileRetiring(() => query(args))
471+
},
472+
},
473+
},
474+
})
475+
// Prisma does not type an extended client as the base client.
476+
const database = reader as unknown as Parameters<typeof findRepositoryIndex>[0]
477+
const index = await findRepositoryIndex(database, repositoryId)
500478

501479
expect(index).toMatchObject({
502480
prototypes: [{ id: prototypeId }],
@@ -508,7 +486,7 @@ describe("real product index", () => {
508486
select: { branchDeletedAt: true },
509487
}),
510488
).toEqual({ branchDeletedAt: retiredAt })
511-
}, 8_000)
489+
})
512490

513491
it("does not return an index when a repository changes during the read", async () => {
514492
const removedId = randomUUID()
@@ -569,14 +547,10 @@ describe("real product index", () => {
569547
},
570548
},
571549
})
572-
vi.spyOn(prisma.prototype, "findMany").mockImplementation((args) =>
573-
reader.prototype.findMany(args),
574-
)
575-
const product = createProductRouteDependencies()
576-
577-
const removedIndex = await product.findRepositoryIndex(removedId)
550+
const database = reader as unknown as Parameters<typeof findRepositoryIndex>[0]
551+
const removedIndex = await findRepositoryIndex(database, removedId)
578552
changeRepository = changeDefaultBranch
579-
const changedIndex = await product.findRepositoryIndex(changedId)
553+
const changedIndex = await findRepositoryIndex(database, changedId)
580554

581555
expect(prototypeIds).toEqual([removedPrototypeId, changedPrototypeId])
582556
expect(

0 commit comments

Comments
 (0)