refactor(trash): optimize cascade delete CTE queries and add rigorous edge-case tests

- Extracted recursive CTE cascade update to cascadeStatusToPendingPurge private helper

- Updated emptyTrash and expireTrashedAssets background job to use batch helper

- Added expireTrashedAssets GC test to verify date boundaries and recursive child marking

- Resolved typecast any warning in test
This commit is contained in:
yiling
2026-06-11 16:40:21 +08:00
parent 8bd34904ff
commit 5835c36cb5
3 changed files with 117 additions and 31 deletions
+19 -30
View File
@@ -1033,6 +1033,21 @@ export class AssetService {
}
}
private async cascadeStatusToPendingPurge(rootIds: string[]): Promise<void> {
if (rootIds.length === 0) return
await this.prismaClient.$executeRaw`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ANY(${rootIds})
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM descendant);
`
}
async emptyTrash(projectId: string): Promise<void> {
const trashedRoots = await this.prismaClient.asset.findMany({
where: {
@@ -1043,21 +1058,8 @@ export class AssetService {
select: { id: true },
})
for (const root of trashedRoots) {
await this.prismaClient.$transaction(async (tx) => {
// Use recursive CTE to find all descendants and mark them all as pending_purge
await tx.$executeRaw`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ${root.id}
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM descendant);
`
})
}
const rootIds = trashedRoots.map((r) => r.id)
await this.cascadeStatusToPendingPurge(rootIds)
await this.purgePendingAssets()
await this.purgeUnreferencedStorageKeys()
@@ -1110,21 +1112,8 @@ export class AssetService {
take: 100,
})
for (const root of expiredRoots) {
await this.prismaClient.$transaction(async (tx) => {
// Use recursive CTE to find all descendants and mark them all as pending_purge
await tx.$executeRaw`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ${root.id}
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM descendant);
`
})
}
const rootIds = expiredRoots.map((r) => r.id)
await this.cascadeStatusToPendingPurge(rootIds)
}
/**