import { describe, expect, it, vi, beforeEach } from 'vitest' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { uploadService } from './upload' import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg' import { turntableService } from '@shumai/core/src/turntable/turntable' import { s3Service } from '@shumai/core/src/s3/s3' import { AssetStatus, AssetType, TaskStatus, WorkflowTaskType } from '@shumai/db' vi.mock('@shumai/core/src/s3/s3', () => ({ getStorageBackend: vi.fn().mockReturnValue('s3'), s3Service: { presign: vi.fn().mockResolvedValue('http://presigned-url.com'), getObjectSize: vi.fn().mockResolvedValue(100), presignMultipart: vi.fn().mockResolvedValue({ url: 'http://signed-multipart-url.com' }), abortMultipartUpload: vi.fn().mockResolvedValue(undefined), deleteObject: vi.fn().mockResolvedValue(1), }, })) describe('UploadService', () => { setupTestDbHooks() let userId: string let teamId: string let projectId: string let parentId: string beforeEach(async () => { const user = await prisma.user.create({ data: { name: 'test', email: 'test-upload@example.com' }, }) userId = user.id const team = await prisma.team.create({ data: { name: 'team' } }) teamId = team.id const project = await prisma.project.create({ data: { name: 'project', teamId }, }) projectId = project.id const parent = await prisma.asset.create({ data: { name: 'parent', type: AssetType.folder, projectId, status: AssetStatus.uploaded, }, }) parentId = parent.id }) it('should create an upload task', async () => { const req = { parentId: parentId, files: [ { name: 'file1.txt', id: '1', size: 100, type: 'file', mediaType: 'video/mp4', children: [], }, { name: 'folder1', id: '2', type: 'folder', size: 0, children: [ { name: 'file2.txt', id: '3', size: 200, type: 'file', mediaType: 'image/png', children: [], }, ], }, { name: '.hidden', id: '4', size: 100, type: 'file', children: [] }, ], } const resp = await uploadService.createUploadTask(userId, req) expect(resp.taskId).toBeDefined() expect(resp.presignedUrls).toHaveLength(2) const task = await prisma.task.findUnique({ where: { id: resp.taskId } }) expect(task?.name).toBe('2 Items') expect(task?.total).toBe(2) const file1 = await prisma.asset.findFirst({ where: { name: 'file1.txt' } }) expect(file1?.mediaType).toBe('video/mp4') const file2 = await prisma.asset.findFirst({ where: { name: 'file2.txt' } }) expect(file2?.mediaType).toBe('image/png') const hidden = await prisma.asset.findFirst({ where: { name: '.hidden' } }) expect(hidden).toBeNull() }) it('should correctly increment fileCount for parent folders when uploading folders', async () => { const req = { parentId: parentId, files: [ { name: 'folder1', id: '1', type: 'folder' as const, size: 0, children: [ { name: 'folder2', id: '2', type: 'folder' as const, size: 0, children: [], }, { name: 'file1.txt', id: '3', type: 'file' as const, size: 100, mediaType: 'text/plain', children: [], }, ], }, ], } await uploadService.createUploadTask(userId, req) // parentId folder should have folder1 as a direct child const parent = await prisma.asset.findUnique({ where: { id: parentId } }) expect(parent?.fileCount).toBe(1) // folder1 should have folder2 and file1.txt as direct children // folder2 is a folder, so it is counted immediately. // file1.txt is a file, so it is counted after confirmFileUpload. const folder1 = await prisma.asset.findFirst({ where: { name: 'folder1' } }) expect(folder1?.parentId).toBe(parentId) expect(folder1?.fileCount).toBe(1) const folder2 = await prisma.asset.findFirst({ where: { name: 'folder2' } }) expect(folder2?.parentId).toBe(folder1?.id) expect(folder2?.fileCount).toBe(0) const file1 = await prisma.asset.findFirst({ where: { name: 'file1.txt' } }) expect(file1?.parentId).toBe(folder1?.id) expect(file1?.status).toBe(AssetStatus.uploading) // Confirm upload for file1.txt const task = await prisma.task.findFirst({ where: { total: 1 } }) await uploadService.confirmFileUpload(userId, task!.id, { fileId: file1!.id, }) const folder1After = await prisma.asset.findUnique({ where: { id: folder1!.id } }) expect(folder1After?.fileCount).toBe(2) }) it('should confirm file upload and create transcode tasks for video', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'video.mp4', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key' }, create: { key: 'test-key' }, }, }, mediaType: 'video/mp4', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) // For video/image, status remains 'uploaded' while transcoding is pending expect(updatedAsset?.status).toBe(AssetStatus.uploaded) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_video }, }) expect(workflowTask).toBeDefined() expect(workflowTask?.payload).toEqual({ projectId: projectId, transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off', threads: 0, sprite: true, poster: true, hlsEnabled: false, }, }) }) it('should pass custom transcode.threads and videoResolutions from team settings to transcode task', async () => { await prisma.team.update({ where: { id: teamId }, data: { settings: { transcode: { videoStrategy: 'multi', videoResolutions: ['720p', '1080p'], hardwareAcceleration: 'auto', threads: 12, }, }, }, }) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'video-custom-threads.mp4', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-threads' }, create: { key: 'test-key-threads' }, }, }, }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_video }, }) expect(workflowTask).toBeDefined() expect(workflowTask?.payload).toEqual({ projectId: projectId, transcode: { videoStrategy: 'multi', videoResolutions: ['720p', '1080p'], hardwareAcceleration: 'auto', threads: 12, sprite: true, poster: true, hlsEnabled: false, }, }) }) it('should confirm file upload and create transcode tasks for image', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'image.png', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key' }, create: { key: 'test-key' }, }, }, mediaType: 'image/png', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_image }, }) expect(workflowTask).toBeDefined() expect(workflowTask?.payload).toEqual({ projectId: projectId, transcode: { thumbnail: true, }, }) }) it('should confirm file upload for non-media files', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'file.json', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key' }, create: { key: 'test-key' }, }, }, mediaType: 'application/json', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.status).toBe(AssetStatus.processed) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_video }, }) expect(workflowTask).toBeNull() }) it('should confirm file upload and create transcode_pdf for office document when Gotenberg is available', async () => { vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'document.docx', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key' }, create: { key: 'test-key' }, }, }, mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(workflowTask).toBeDefined() }) it('should mark asset processed without creating transcode_pdf for office document when Gotenberg is unavailable', async () => { vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'document.docx', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key' }, create: { key: 'test-key' }, }, }, mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.status).toBe(AssetStatus.processed) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(workflowTask).toBeNull() }) it('should confirm file upload and create transcode_pdf for HTML document when Gotenberg is available', async () => { vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'index.html', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-html-1' }, create: { key: 'test-key-html-1' }, }, }, mediaType: 'text/html', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(workflowTask).toBeDefined() }) it('should mark asset processed without creating transcode_pdf for HTML document when Gotenberg is unavailable', async () => { vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'index.html', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-html-2' }, create: { key: 'test-key-html-2' }, }, }, mediaType: 'text/html', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.status).toBe(AssetStatus.processed) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(workflowTask).toBeNull() }) it('should create transcode_pdf for office documents when Gotenberg is configured in team settings without global env', async () => { vi.restoreAllMocks() vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { const url = String(input) if (url.includes('/health')) { return new Response(JSON.stringify({ status: 'up' }), { status: 200 }) } return new Response('Not Found', { status: 404 }) }) const originalEnv = process.env.GOTENBERG_URL delete process.env.GOTENBERG_URL try { await prisma.team.update({ where: { id: teamId }, data: { settings: { gotenberg: { url: 'http://gotenberg.local:3000', }, }, }, }) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'report.docx', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-doc-team-settings' }, create: { key: 'test-key-doc-team-settings' }, }, }, mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(workflowTask).not.toBeNull() // Test HTML document as well const htmlTask = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const htmlAsset = await prisma.asset.create({ data: { name: 'index.html', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-html-team-settings' }, create: { key: 'test-key-html-team-settings' }, }, }, mediaType: 'text/html', }, }) await uploadService.confirmFileUpload(userId, htmlTask.id, { fileId: htmlAsset.id }) const htmlWorkflowTask = await prisma.workflowTask.findFirst({ where: { assetId: htmlAsset.id, type: WorkflowTaskType.transcode_pdf }, }) expect(htmlWorkflowTask).not.toBeNull() } finally { if (originalEnv !== undefined) { process.env.GOTENBERG_URL = originalEnv } } }) it('should confirm file upload and create transcode_3d for 3D model when turntable is available', async () => { vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(true) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'robot.glb', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-3d-1' }, create: { key: 'test-key-3d-1' }, }, }, mediaType: 'model/gltf-binary', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_3d }, }) expect(workflowTask).toBeDefined() expect(workflowTask?.payload).toEqual({ projectId: projectId, transcode: { sprite: true, poster: true, }, }) }) it('should mark asset processed without creating transcode_3d for 3D model when turntable is unavailable', async () => { vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(false) const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'robot.glb', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-3d-2' }, create: { key: 'test-key-3d-2' }, }, }, mediaType: 'model/gltf-binary', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.status).toBe(AssetStatus.processed) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_3d }, }) expect(workflowTask).toBeNull() }) it('should confirm file upload and resolve empty mediaType using Bun resolver for audio', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'audio.mp3', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-audio-empty' }, create: { key: 'test-key-audio-empty' }, }, }, mediaType: '', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.mediaType).toBe('audio/mpeg') expect(updatedAsset?.status).toBe(AssetStatus.uploaded) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_video }, }) expect(workflowTask).toBeDefined() }) it('should confirm file upload and resolve application/octet-stream mediaType using Bun resolver for audio', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const asset = await prisma.asset.create({ data: { name: 'song.wav', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: parentId } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'test-key-audio-octet' }, create: { key: 'test-key-audio-octet' }, }, }, mediaType: 'application/octet-stream', }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id }) const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } }) expect(updatedAsset?.mediaType).toBe('audio/x-wav') expect(updatedAsset?.status).toBe(AssetStatus.uploaded) const workflowTask = await prisma.workflowTask.findFirst({ where: { assetId: asset.id, type: WorkflowTaskType.transcode_video }, }) expect(workflowTask).toBeDefined() }) it('should create a version stack when parentId is a file', async () => { // Create an existing file const fileA = await prisma.asset.create({ data: { name: 'fileA.txt', type: AssetType.file, projectId, parentId, status: AssetStatus.processed, sizeByte: 1000, }, }) const req = { parentId: fileA.id, files: [ { name: 'fileA_v2.txt', id: 'v2', size: 2000, type: 'file' as const, mediaType: 'text/plain', children: [], }, ], } const resp = await uploadService.createUploadTask(userId, req) expect(resp.taskId).toBeDefined() // Should have created a version stack const stack = await prisma.asset.findFirst({ where: { type: AssetType.version_stack, parentId }, }) expect(stack).toBeDefined() expect(stack?.fileCount).toBe(1) // Only fileA is "uploaded", the new one is still "uploading" expect(Number(stack?.sizeByte)).toBe(1000) // The new asset should be inside the stack const newAsset = await prisma.asset.findFirst({ where: { taskId: resp.taskId, parentId: stack!.id }, }) expect(newAsset).toBeDefined() expect(newAsset?.status).toBe(AssetStatus.uploading) }) it('should correctly update counts when confirming a version in a stack', async () => { // Create a stack with one existing file const stack = await prisma.asset.create({ data: { name: '', type: AssetType.version_stack, projectId, parentId, status: AssetStatus.uploaded, fileCount: 1, sizeByte: 1000, }, }) await prisma.asset.create({ data: { name: 'v1.txt', type: AssetType.file, projectId, parentId: stack.id, status: AssetStatus.processed, sizeByte: 1000, }, }) // Create an uploading asset in that stack const task = await prisma.task.create({ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' }, }) const fileV2 = await prisma.asset.create({ data: { name: 'v2.txt', type: AssetType.file, project: { connect: { id: projectId } }, parent: { connect: { id: stack.id } }, status: AssetStatus.uploading, storageKey: { connectOrCreate: { where: { key: 'v2-key' }, create: { key: 'v2-key' }, }, }, sizeByte: 2000, }, }) vi.spyOn(s3Service, 'getObjectSize').mockResolvedValue(2000) // Manually set parent folder size to match initial stack size for realistic aggregation await prisma.asset.update({ where: { id: parentId }, data: { sizeByte: 1000 }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: fileV2.id }) const updatedStack = await prisma.asset.findUnique({ where: { id: stack.id } }) expect(updatedStack?.fileCount).toBe(2) expect(Number(updatedStack?.sizeByte)).toBe(3000) // Verify parent folder size (initially 1000 from stack) const parentFolder = await prisma.asset.findUnique({ where: { id: parentId } }) expect(Number(parentFolder?.sizeByte)).toBe(3000) }) it('should list upload tasks', async () => { const task = await prisma.task.create({ data: { creatorId: userId, total: 3, uploaded: 1, type: 'upload', name: 'test-upload-task', }, }) const result = await uploadService.listUploadTasks(userId, { first: 10 }) 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 () => { const req = { parentId: parentId, files: [ { name: 'song.wma', id: '1', size: 100, type: 'file' as const, mediaType: 'video/x-ms-wma', children: [], }, { name: 'other_song.WMA', id: '2', size: 200, type: 'file' as const, mediaType: 'video/x-ms-asf', children: [], }, ], } const resp = await uploadService.createUploadTask(userId, req) expect(resp.taskId).toBeDefined() const song1 = await prisma.asset.findFirst({ where: { name: 'song.wma' } }) expect(song1?.mediaType).toBe('audio/x-ms-wma') const song2 = await prisma.asset.findFirst({ where: { name: 'other_song.WMA' } }) expect(song2?.mediaType).toBe('audio/x-ms-asf') }) describe('signS3Upload', () => { it('should sign multipart request and store uploadId on asset', async () => { const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/video.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'video.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, status: AssetStatus.uploading, }, }) const res = await uploadService.signS3Upload(teamId, userId, { key: 'files/test/video.mp4', method: 'PUT', uploadId: 'upload-id-xyz', partNumber: 1, fileId: asset.id, }) expect(res.url).toBe('http://signed-multipart-url.com') const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id }, }) expect(updatedAsset?.uploadId).toBe('upload-id-xyz') }) it('should reject signing if requested key does not match asset storage key', async () => { const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/video.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'video.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, status: AssetStatus.uploading, }, }) await expect( uploadService.signS3Upload(teamId, userId, { key: 'files/unauthorized/other.mp4', method: 'PUT', fileId: asset.id, }), ).rejects.toThrow('Requested key does not match asset storage key') }) it('should reject signing if asset is not in uploading status', async () => { const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/video.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'video.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, status: AssetStatus.uploaded, }, }) await expect( uploadService.signS3Upload(teamId, userId, { key: 'files/test/video.mp4', method: 'PUT', fileId: asset.id, }), ).rejects.toThrow('Asset is not currently uploading') }) it('should reject signing if asset belongs to another 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 storageKey = await prisma.storageKey.create({ data: { key: 'files/test/other.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'other.mp4', type: AssetType.file, projectId: otherProject.id, storageKeyId: storageKey.id, status: AssetStatus.uploading, }, }) await expect( uploadService.signS3Upload(teamId, userId, { key: 'files/test/other.mp4', method: 'PUT', fileId: asset.id, }), ).rejects.toThrow('Asset does not belong to team') }) }) describe('abortUpload', () => { it('should abort multipart upload, delete asset, and fail task', async () => { const task = await prisma.task.create({ data: { creatorId: userId, type: 'upload', name: 'task-1', total: 1, status: TaskStatus.uploading, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/abort.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'abort.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, taskId: task.id, uploadId: 'upload-abc', status: AssetStatus.uploading, }, }) const res = await uploadService.abortUpload(teamId, userId, task.id, { fileId: asset.id, uploadId: 'upload-abc', key: 'files/test/abort.mp4', }) expect(res.success).toBe(true) expect(s3Service.abortMultipartUpload).toHaveBeenCalledWith( expect.anything(), 'files/test/abort.mp4', 'upload-abc', ) const deletedAsset = await prisma.asset.findUnique({ where: { id: asset.id }, }) expect(deletedAsset).toBeNull() const updatedTask = await prisma.task.findUnique({ where: { id: task.id }, }) expect(updatedTask?.status).toBe(TaskStatus.failed) }) it('should reject aborting if asset taskId does not match', async () => { const task = await prisma.task.create({ data: { creatorId: userId, type: 'upload', name: 'task-1', total: 1, status: TaskStatus.uploading, }, }) const otherTask = await prisma.task.create({ data: { creatorId: userId, type: 'upload', name: 'other-task', total: 1, status: TaskStatus.uploading, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/abort-mismatch.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'abort-mismatch.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, taskId: otherTask.id, uploadId: 'upload-abc', status: AssetStatus.uploading, }, }) await expect( uploadService.abortUpload(teamId, userId, task.id, { fileId: asset.id, uploadId: 'upload-abc', key: 'files/test/abort-mismatch.mp4', }), ).rejects.toThrow('Asset does not belong to specified task') }) it('should delete object from storage when aborting single/local upload without uploadId', async () => { const task = await prisma.task.create({ data: { creatorId: userId, type: 'upload', name: 'task-2', total: 1, status: TaskStatus.uploading, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/single.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'single.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, taskId: task.id, status: AssetStatus.uploading, }, }) const res = await uploadService.abortUpload(teamId, userId, task.id, { fileId: asset.id, key: 'files/test/single.mp4', }) expect(res.success).toBe(true) expect(s3Service.deleteObject).toHaveBeenCalledWith( expect.anything(), 'files/test/single.mp4', ) const deletedAsset = await prisma.asset.findUnique({ where: { id: asset.id }, }) expect(deletedAsset).toBeNull() }) }) describe('confirmFileUpload with errorMessage', () => { it('should abort multipart upload in S3 and delete asset on failure', async () => { const task = await prisma.task.create({ data: { creatorId: userId, type: 'upload', name: 'task-err', total: 1, status: TaskStatus.uploading, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'files/test/fail.mp4' }, }) const asset = await prisma.asset.create({ data: { name: 'fail.mp4', type: AssetType.file, projectId, storageKeyId: storageKey.id, taskId: task.id, uploadId: 'upload-fail-id', status: AssetStatus.uploading, }, }) await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id, errorMessage: 'Network failed', }) expect(s3Service.abortMultipartUpload).toHaveBeenCalledWith( expect.anything(), 'files/test/fail.mp4', 'upload-fail-id', ) const deletedAsset = await prisma.asset.findUnique({ where: { id: asset.id }, }) 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() }) }) })