mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 04:44:28 +00:00
feat(upload): allow canceling in-progress upload tasks from sidebar (#511)
* feat(upload): allow canceling in-progress upload tasks from sidebar * fix(upload): resolve concurrent confirmation race and store counter issues on cancellation * fix(webui): immediately remove cancelled upload files from file list view
This commit is contained in:
@@ -797,6 +797,7 @@ describe('UploadService', () => {
|
||||
expect(result.data).toHaveLength(1)
|
||||
expect(result.data[0].id).toBe(task.id)
|
||||
expect(result.data[0].name).toBe('test-upload-task')
|
||||
expect(result.data[0].status).toBe(TaskStatus.pending)
|
||||
})
|
||||
|
||||
it('should correct the mediaType for .wma files that browser incorrectly reports as video', async () => {
|
||||
@@ -1120,4 +1121,262 @@ describe('UploadService', () => {
|
||||
expect(deletedAsset).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cancelUploadTask', () => {
|
||||
it('cancels uploading assets, leaves uploaded assets and folders intact, and marks task failed', async () => {
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: userId,
|
||||
type: 'upload',
|
||||
name: 'multi-file-task',
|
||||
total: 3,
|
||||
uploaded: 1,
|
||||
status: TaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// 1. A folder created by the task
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder',
|
||||
type: AssetType.folder,
|
||||
projectId,
|
||||
parentId,
|
||||
taskId: task.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. An asset already finished uploading
|
||||
const finishedKey = await prisma.storageKey.create({ data: { key: 'files/test/done.mp4' } })
|
||||
const finishedAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'done.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
storageKeyId: finishedKey.id,
|
||||
taskId: task.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// 3. An incomplete multipart asset
|
||||
const multipartKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/test/part.mp4' },
|
||||
})
|
||||
const multipartAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'part.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
storageKeyId: multipartKey.id,
|
||||
taskId: task.id,
|
||||
uploadId: 'upload-multipart-cancel',
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
// 4. An incomplete single PUT asset
|
||||
const singleKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/test/single.mp4' },
|
||||
})
|
||||
const singleAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'single.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
storageKeyId: singleKey.id,
|
||||
taskId: task.id,
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await uploadService.cancelUploadTask(teamId, userId, task.id)
|
||||
expect(res).toEqual({ success: true })
|
||||
|
||||
// Incomplete assets deleted
|
||||
expect(await prisma.asset.findUnique({ where: { id: multipartAsset.id } })).toBeNull()
|
||||
expect(await prisma.storageKey.findUnique({ where: { id: multipartKey.id } })).toBeNull()
|
||||
expect(await prisma.asset.findUnique({ where: { id: singleAsset.id } })).toBeNull()
|
||||
expect(await prisma.storageKey.findUnique({ where: { id: singleKey.id } })).toBeNull()
|
||||
|
||||
// S3 cleanup called
|
||||
expect(s3Service.abortMultipartUpload).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'files/test/part.mp4',
|
||||
'upload-multipart-cancel',
|
||||
)
|
||||
expect(s3Service.deleteObject).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'files/test/single.mp4',
|
||||
)
|
||||
|
||||
// Completed asset and folder remain intact
|
||||
expect(await prisma.asset.findUnique({ where: { id: finishedAsset.id } })).not.toBeNull()
|
||||
expect(await prisma.storageKey.findUnique({ where: { id: finishedKey.id } })).not.toBeNull()
|
||||
expect(await prisma.asset.findUnique({ where: { id: folder.id } })).not.toBeNull()
|
||||
|
||||
// Task status updated to failed
|
||||
const updatedTask = await prisma.task.findUnique({ where: { id: task.id } })
|
||||
expect(updatedTask?.status).toBe(TaskStatus.failed)
|
||||
expect(updatedTask?.uploaded).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects cancellation if the caller is not the task creator', async () => {
|
||||
const otherUser = await prisma.user.create({
|
||||
data: {
|
||||
email: 'other@example.com',
|
||||
name: 'Other User',
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: otherUser.id,
|
||||
type: 'upload',
|
||||
name: 'other-task',
|
||||
total: 1,
|
||||
status: TaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(uploadService.cancelUploadTask(teamId, userId, task.id)).rejects.toThrow(
|
||||
'Unauthorized to cancel this upload task',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws when task does not exist', async () => {
|
||||
await expect(
|
||||
uploadService.cancelUploadTask(teamId, userId, 'non-existent-task'),
|
||||
).rejects.toThrow('Upload task not found')
|
||||
})
|
||||
|
||||
it('throws when task assets belong to a different team', async () => {
|
||||
const otherTeam = await prisma.team.create({
|
||||
data: { name: 'Other Team' },
|
||||
})
|
||||
const otherProject = await prisma.project.create({
|
||||
data: { name: 'Other Project', teamId: otherTeam.id },
|
||||
})
|
||||
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: userId,
|
||||
type: 'upload',
|
||||
name: 'wrong-team-task',
|
||||
total: 1,
|
||||
status: TaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'wrong-team-file.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: otherProject.id,
|
||||
taskId: task.id,
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(uploadService.cancelUploadTask(teamId, userId, task.id)).rejects.toThrow(
|
||||
'Task does not belong to specified team',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws when task is already completed and preserves completed status', async () => {
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: userId,
|
||||
type: 'upload',
|
||||
name: 'completed-task',
|
||||
total: 1,
|
||||
uploaded: 1,
|
||||
status: TaskStatus.completed,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(uploadService.cancelUploadTask(teamId, userId, task.id)).rejects.toThrow(
|
||||
'Cannot cancel a completed upload task',
|
||||
)
|
||||
|
||||
const refreshed = await prisma.task.findUnique({ where: { id: task.id } })
|
||||
expect(refreshed?.status).toBe(TaskStatus.completed)
|
||||
})
|
||||
|
||||
it('preserves an asset and its storage if it was confirmed uploaded concurrently', async () => {
|
||||
const task = await prisma.task.create({
|
||||
data: {
|
||||
creatorId: userId,
|
||||
type: 'upload',
|
||||
name: 'race-task',
|
||||
total: 2,
|
||||
uploaded: 0,
|
||||
status: TaskStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
const confirmedAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'race-confirmed.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
create: { key: 'files/test/race-confirmed.mp4' },
|
||||
},
|
||||
},
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
const cancelledAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'race-cancelled.mp4',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
task: { connect: { id: task.id } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
create: { key: 'files/test/race-cancelled.mp4' },
|
||||
},
|
||||
},
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
// Simulate concurrent confirm: update status to uploaded
|
||||
await prisma.asset.update({
|
||||
where: { id: confirmedAsset.id },
|
||||
data: { status: AssetStatus.uploaded },
|
||||
})
|
||||
|
||||
const deleteObjectSpy = vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(1)
|
||||
|
||||
await uploadService.cancelUploadTask(teamId, userId, task.id)
|
||||
|
||||
// Confirmed asset must still exist in DB
|
||||
const dbConfirmed = await prisma.asset.findUnique({ where: { id: confirmedAsset.id } })
|
||||
expect(dbConfirmed).not.toBeNull()
|
||||
expect(dbConfirmed?.status).toBe(AssetStatus.uploaded)
|
||||
|
||||
// Cancelled asset must be deleted
|
||||
const dbCancelled = await prisma.asset.findUnique({ where: { id: cancelledAsset.id } })
|
||||
expect(dbCancelled).toBeNull()
|
||||
|
||||
// S3 deleteObject was called for the cancelled asset, but NOT for the confirmed asset
|
||||
expect(deleteObjectSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'files/test/race-cancelled.mp4',
|
||||
)
|
||||
expect(deleteObjectSpy).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'files/test/race-confirmed.mp4',
|
||||
)
|
||||
|
||||
deleteObjectSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AssetStatus, AssetType, Prisma, TaskStatus, prisma } from '@shumai/db'
|
||||
import {
|
||||
AbortUploadRequest,
|
||||
AbortUploadResponse,
|
||||
CancelUploadTaskResponse,
|
||||
ConfirmFileUploadRequest,
|
||||
CreateUploadTaskRequest,
|
||||
CreateUploadTaskResponse,
|
||||
@@ -210,30 +211,7 @@ export class UploadService {
|
||||
if (!key) throw new Error('Asset has no key')
|
||||
|
||||
if (req.errorMessage) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
if (asset.uploadId && key) {
|
||||
try {
|
||||
await s3Service.abortMultipartUpload(bucket, key, asset.uploadId)
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, key, uploadId: asset.uploadId },
|
||||
'Failed to abort multipart upload on confirm error',
|
||||
)
|
||||
}
|
||||
} else if (key) {
|
||||
try {
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
} catch (err) {
|
||||
logger.warn({ err, key }, 'Failed to delete storage object on confirm error')
|
||||
}
|
||||
}
|
||||
|
||||
await this.prismaClient.asset.delete({ where: { id: asset.id } }).catch(() => {})
|
||||
if (asset.storageKeyId) {
|
||||
await this.prismaClient.storageKey
|
||||
.delete({ where: { id: asset.storageKeyId } })
|
||||
.catch(() => {})
|
||||
}
|
||||
await this.discardUploadingAsset(asset)
|
||||
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
|
||||
if (t) {
|
||||
const updatedTask = await this.prismaClient.task.update({
|
||||
@@ -250,6 +228,10 @@ export class UploadService {
|
||||
return
|
||||
}
|
||||
|
||||
if (asset.status !== AssetStatus.uploading) {
|
||||
throw new Error('Asset is not in uploading status')
|
||||
}
|
||||
|
||||
const size = await s3Service.getObjectSize(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
const project = asset.project
|
||||
@@ -425,6 +407,7 @@ export class UploadService {
|
||||
total: t.total || 0,
|
||||
uploaded: t.uploaded,
|
||||
createdAt: t.createdAt.toISOString(),
|
||||
status: t.status,
|
||||
}))
|
||||
|
||||
return { data: infos, pageInfo }
|
||||
@@ -490,7 +473,6 @@ export class UploadService {
|
||||
taskId: string,
|
||||
req: AbortUploadRequest,
|
||||
): Promise<AbortUploadResponse> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.fileId },
|
||||
include: {
|
||||
@@ -520,33 +502,11 @@ export class UploadService {
|
||||
throw new Error('Provided key does not match asset storage key')
|
||||
}
|
||||
|
||||
const uploadId = asset.uploadId || req.uploadId
|
||||
if (asset.uploadId && req.uploadId && asset.uploadId !== req.uploadId) {
|
||||
throw new Error('Provided uploadId does not match asset uploadId')
|
||||
}
|
||||
|
||||
if (uploadId && key) {
|
||||
try {
|
||||
await s3Service.abortMultipartUpload(bucket, key, uploadId)
|
||||
} catch (err) {
|
||||
logger.warn({ err, key, uploadId }, 'Failed to abort multipart upload in S3')
|
||||
}
|
||||
} else if (key) {
|
||||
try {
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
} catch (err) {
|
||||
logger.warn({ err, key }, 'Failed to delete object from storage')
|
||||
}
|
||||
}
|
||||
|
||||
await this.prismaClient.asset.delete({ where: { id: asset.id } }).catch((err) => {
|
||||
logger.warn({ err, assetId: asset.id }, 'Failed to delete asset on upload abort')
|
||||
})
|
||||
if (asset.storageKeyId) {
|
||||
await this.prismaClient.storageKey
|
||||
.delete({ where: { id: asset.storageKeyId } })
|
||||
.catch(() => {})
|
||||
}
|
||||
await this.discardUploadingAsset(asset, req.uploadId)
|
||||
|
||||
if (taskId) {
|
||||
const remaining = await this.prismaClient.asset.count({
|
||||
@@ -564,6 +524,104 @@ export class UploadService {
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
private async discardUploadingAsset(
|
||||
asset: {
|
||||
id: string
|
||||
uploadId: string | null
|
||||
storageKeyId: string | null
|
||||
storageKey: { key: string } | null
|
||||
},
|
||||
requestedUploadId?: string,
|
||||
): Promise<void> {
|
||||
const deleteResult = await this.prismaClient.asset.deleteMany({
|
||||
where: {
|
||||
id: asset.id,
|
||||
status: AssetStatus.uploading,
|
||||
},
|
||||
})
|
||||
|
||||
if (deleteResult.count === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = asset.storageKey?.key
|
||||
const uploadId = asset.uploadId || requestedUploadId
|
||||
|
||||
if (uploadId && key) {
|
||||
try {
|
||||
await s3Service.abortMultipartUpload(bucket, key, uploadId)
|
||||
} catch (err) {
|
||||
logger.warn({ err, key, uploadId }, 'Failed to abort multipart upload in S3')
|
||||
}
|
||||
} else if (key) {
|
||||
try {
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
} catch (err) {
|
||||
logger.warn({ err, key }, 'Failed to delete object from storage')
|
||||
}
|
||||
}
|
||||
|
||||
if (asset.storageKeyId) {
|
||||
await this.prismaClient.storageKey
|
||||
.delete({ where: { id: asset.storageKeyId } })
|
||||
.catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
async cancelUploadTask(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
taskId: string,
|
||||
): Promise<CancelUploadTaskResponse> {
|
||||
const task = await this.prismaClient.task.findUnique({
|
||||
where: { id: taskId },
|
||||
include: {
|
||||
assets: {
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!task) {
|
||||
throw new Error('Upload task not found')
|
||||
}
|
||||
|
||||
if (task.creatorId !== userId) {
|
||||
throw new Error('Unauthorized to cancel this upload task')
|
||||
}
|
||||
|
||||
if (task.status === TaskStatus.completed) {
|
||||
throw new Error('Cannot cancel a completed upload task')
|
||||
}
|
||||
|
||||
const invalidTeamAsset = task.assets.find(
|
||||
(a) => a.project?.teamId && a.project.teamId !== teamId,
|
||||
)
|
||||
if (invalidTeamAsset) {
|
||||
throw new Error('Task does not belong to specified team')
|
||||
}
|
||||
|
||||
const uploadingAssets = task.assets.filter((a) => a.status === AssetStatus.uploading)
|
||||
|
||||
for (const asset of uploadingAssets) {
|
||||
await this.discardUploadingAsset(asset)
|
||||
}
|
||||
|
||||
await this.prismaClient.task.updateMany({
|
||||
where: {
|
||||
id: taskId,
|
||||
status: { not: TaskStatus.completed },
|
||||
},
|
||||
data: { status: TaskStatus.failed },
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
}
|
||||
|
||||
export const uploadService = new UploadService()
|
||||
|
||||
Reference in New Issue
Block a user