feat(upload): S3 multipart upload with offline resume and wake lock (#391)

* feat(upload): implement S3 multipart upload with offline resume and wake lock

* fix(upload): harden S3 sign and abort authorization, await confirmation, and clean up failed multipart uploads

* fix(webui): resume multipart upload on network recovery and log online event

* fix(webui): remove offline and online toast notifications
This commit is contained in:
Yiling-J
2026-09-07 16:49:00 +08:00
committed by GitHub
parent 62e86b703e
commit 67b767f1e8
23 changed files with 2157 additions and 419 deletions
+169 -4
View File
@@ -1,13 +1,17 @@
import { assetService } from '@shumai/core/src/asset/asset'
import { PaginatedData, PaginationParams, paginateQuery } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getStorageBackend, s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, Prisma, TaskStatus, prisma } from '@shumai/db'
import {
AbortUploadRequest,
AbortUploadResponse,
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
S3SignRequest,
S3SignResponse,
TaskInfo,
} from '@shumai/dtos'
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
@@ -16,6 +20,7 @@ import { ulid } from 'ulid'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { getProxyType, isHtmlDocument, isOfficeDocument } from '@shumai/core/src/utils/mime'
import { logger } from '@shumai/core/src/logger'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
@@ -62,7 +67,7 @@ export class UploadService {
const isParentFile = parentAsset.type === AssetType.file
const targetParentId = isParentFile ? parentAsset.parentId! : parentAsset.id
const createdAssets: { tempId: string; assetId: string }[] = []
const createdAssets: { tempId: string; assetId: string; key?: string }[] = []
await this.prismaClient.$transaction(async (tx) => {
const ids = await this.createAssetsRecursively(
@@ -95,6 +100,7 @@ export class UploadService {
return {
taskId: task.id,
presignedUrls: presignedUrls,
storageBackend: getStorageBackend(),
createdAssets: createdAssets,
}
}
@@ -107,7 +113,7 @@ export class UploadService {
parentId: string,
files: FileNode[],
presignedUrls: PresignedUrl[],
createdAssets: { tempId: string; assetId: string }[],
createdAssets: { tempId: string; assetId: string; key?: string }[],
): Promise<string[]> {
const firstFile = await tx.asset.findFirst({
where: { parentId },
@@ -152,6 +158,7 @@ export class UploadService {
createdAssets.push({
tempId: file.id,
assetId: newAsset.id,
key: key || undefined,
})
if (assetType === AssetType.folder && parentId) {
@@ -202,7 +209,30 @@ export class UploadService {
if (!key) throw new Error('Asset has no key')
if (req.errorMessage) {
await this.prismaClient.asset.delete({ where: { id: asset.id } })
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(() => {})
}
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
if (t) {
const updatedTask = await this.prismaClient.task.update({
@@ -373,6 +403,141 @@ export class UploadService {
return { data: infos, pageInfo }
}
async signS3Upload(teamId: string, userId: string, req: S3SignRequest): Promise<S3SignResponse> {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.fileId },
include: {
storageKey: true,
project: true,
},
})
if (!asset) {
throw new Error('Asset not found')
}
if (asset.status !== AssetStatus.uploading) {
throw new Error('Asset is not currently uploading')
}
if (asset.project?.teamId !== teamId) {
throw new Error('Asset does not belong to team')
}
const key = asset.storageKey?.key
if (!key) {
throw new Error('Asset has no storage key')
}
if (req.key && req.key !== key) {
throw new Error('Requested key does not match asset storage key')
}
if (req.method === 'GET' || req.method === 'DELETE') {
if (!req.uploadId) {
throw new Error('Operation requires uploadId')
}
}
if (req.uploadId) {
if (asset.uploadId && asset.uploadId !== req.uploadId) {
throw new Error('Upload ID does not match asset upload ID')
}
if (!asset.uploadId) {
await this.prismaClient.asset.update({
where: { id: asset.id },
data: { uploadId: req.uploadId },
})
}
}
const result = await s3Service.presignMultipart(bucket, key, req)
return { url: result.url }
}
async abortUpload(
teamId: string,
userId: string,
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: {
storageKey: true,
project: true,
},
})
if (!asset) {
return { success: true }
}
if (asset.status !== AssetStatus.uploading) {
throw new Error('Asset is not currently uploading')
}
if (asset.taskId !== taskId) {
throw new Error('Asset does not belong to specified task')
}
if (asset.project?.teamId !== teamId) {
throw new Error('Asset does not belong to specified team')
}
const key = asset.storageKey?.key
if (req.key && key && req.key !== key) {
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(() => {})
}
if (taskId) {
const remaining = await this.prismaClient.asset.count({
where: { taskId, status: AssetStatus.uploading },
})
if (remaining === 0) {
await this.prismaClient.task
.update({
where: { id: taskId },
data: { status: TaskStatus.failed },
})
.catch(() => {})
}
}
return { success: true }
}
}
export const uploadService = new UploadService()