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
+95
View File
@@ -1996,5 +1996,100 @@ describe('AssetService — natural sort by name', () => {
'files/project2-trashed/',
)
})
it('should do nothing and not throw when there are no trashed assets', async () => {
const team = await prisma.team.create({ data: { name: 'Empty Test Team' } })
const project = await prisma.project.create({
data: { name: 'Empty Test Project', teamId: team.id },
})
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
})
})
describe('expireTrashedAssets', () => {
it('should only purge root assets that have been in the trash for > 30 days and their descendants', async () => {
const team = await prisma.team.create({ data: { name: 'GC Team' } })
const project = await prisma.project.create({
data: { name: 'GC Project', teamId: team.id },
})
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
const fortyDaysAgo = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000)
const twentyDaysAgo = new Date(Date.now() - 20 * 24 * 60 * 60 * 1000)
// 1. Root expired folder (> 30 days)
const folderExpired = await prisma.asset.create({
data: {
name: 'Expired Folder',
type: AssetType.folder,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project.id } },
creator: { connect: { id: user.id } },
deletedAt: fortyDaysAgo,
},
})
// Child of expired folder
const childOfExpired = await prisma.asset.create({
data: {
name: 'Child of Expired',
type: AssetType.file,
status: 'uploaded',
isDeleted: true,
project: { connect: { id: project.id } },
parent: { connect: { id: folderExpired.id } },
creator: { connect: { id: user.id } },
},
})
// 2. Root active folder (<= 30 days)
const folderActive = await prisma.asset.create({
data: {
name: 'Active Folder',
type: AssetType.folder,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project.id } },
creator: { connect: { id: user.id } },
deletedAt: twentyDaysAgo,
},
})
// Child of active folder
const childOfActive = await prisma.asset.create({
data: {
name: 'Child of Active',
type: AssetType.file,
status: 'uploaded',
isDeleted: true,
project: { connect: { id: project.id } },
parent: { connect: { id: folderActive.id } },
creator: { connect: { id: user.id } },
},
})
// Act
await (
assetService as unknown as { expireTrashedAssets: () => Promise<void> }
).expireTrashedAssets()
// Assert
const expiredDb = await prisma.asset.findUnique({ where: { id: folderExpired.id } })
const childExpiredDb = await prisma.asset.findUnique({ where: { id: childOfExpired.id } })
const activeDb = await prisma.asset.findUnique({ where: { id: folderActive.id } })
const childActiveDb = await prisma.asset.findUnique({ where: { id: childOfActive.id } })
// The expired folder and its child should be marked as pending_purge
expect(expiredDb?.status).toBe('pending_purge')
expect(childExpiredDb?.status).toBe('pending_purge')
// The active folder and its child should remain 'trashed' and 'uploaded' respectively
expect(activeDb?.status).toBe('trashed')
expect(childActiveDb?.status).toBe('uploaded')
})
})
})
+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)
}
/**
@@ -838,7 +838,9 @@ export function FileBrowser({
<Button
variant="destructive"
size="sm"
disabled={isEmptyingTrash || (folders.length === 0 && displayedFiles.length === 0)}
disabled={
isEmptyingTrash || (folders.length === 0 && displayedFiles.length === 0)
}
onClick={() => setIsEmptyTrashDialogOpen(true)}
className="h-8 px-3 text-xs font-medium bg-destructive/10 text-destructive border border-destructive/20 hover:bg-destructive hover:text-destructive-foreground transition-all duration-200"
>