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
+255 -62
View File
@@ -1,43 +1,47 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import {
GetObjectCommand,
PutObjectCommand,
UploadPartCommand,
CreateMultipartUploadCommand,
CompleteMultipartUploadCommand,
ListPartsCommand,
AbortMultipartUploadCommand,
} from '@aws-sdk/client-s3'
import { buildContentDisposition, LocalStorageService, S3StorageService } from './s3'
// Mock Bun S3Client
const s3ClientConstructorSpy = vi.fn()
const s3FileSpy = vi.fn()
const s3WriteSpy = vi.fn()
const s3DeleteSpy = vi.fn()
const s3ListSpy = vi.fn()
const s3ExistsSpy = vi.fn()
const s3PresignSpy = vi.fn()
const s3SendSpy = vi.fn()
const getSignedUrlSpy = vi.fn()
vi.mock('bun', () => {
vi.mock('@aws-sdk/client-s3', async (importOriginal) => {
const actual = await importOriginal<typeof import('@aws-sdk/client-s3')>()
return {
...actual,
S3Client: class {
constructor(params: unknown) {
s3ClientConstructorSpy(params)
}
file = s3FileSpy.mockReturnValue({
size: Promise.resolve(123),
exists: vi.fn().mockResolvedValue(true),
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(10)),
type: 'text/plain',
})
write = s3WriteSpy.mockResolvedValue({})
delete = s3DeleteSpy.mockResolvedValue({})
list = s3ListSpy.mockResolvedValue({ contents: [], isTruncated: false })
exists = s3ExistsSpy.mockResolvedValue(true)
presign = s3PresignSpy.mockReturnValue('http://presigned-url')
send = s3SendSpy
},
}
})
vi.mock('@aws-sdk/s3-request-presigner', () => {
return {
getSignedUrl: vi.fn((client, command, options) => getSignedUrlSpy(client, command, options)),
}
})
describe('S3Service implementations', () => {
beforeEach(async () => {
vi.clearAllMocks()
getSignedUrlSpy.mockReset()
delete process.env.PRESIGNED_URL_EXPIRES_IN
s3PresignSpy.mockReturnValue('http://presigned-url')
getSignedUrlSpy.mockResolvedValue('http://presigned-url')
s3SendSpy.mockResolvedValue({})
})
describe('S3StorageService', () => {
@@ -68,48 +72,53 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
const url = await s3.presign('bucket', 'key', 'GET')
expect(url).toBe('http://presigned-url')
expect(s3PresignSpy).toHaveBeenCalledWith('key', expect.objectContaining({ method: 'GET' }))
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 18000 }),
)
})
it('should cache GET presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
s3PresignSpy.mockReturnValueOnce('http://presigned-url-1')
s3PresignSpy.mockReturnValueOnce('http://presigned-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET')
const url2 = await s3.presign('bucket', 'key', 'GET')
expect(url1).toBe('http://presigned-url-1')
expect(url2).toBe('http://presigned-url-1')
expect(s3PresignSpy).toHaveBeenCalledTimes(1)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
})
it('should NOT cache PUT presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockReset()
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-1')
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://unique-put-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://unique-put-url-2')
const url1 = await s3.presign('bucket', 'key', 'PUT')
const url2 = await s3.presign('bucket', 'key', 'PUT')
expect(url1).toBe('http://unique-put-url-1')
expect(url2).toBe('http://unique-put-url-2')
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
})
it('should respect PRESIGNED_URL_EXPIRES_IN env', async () => {
process.env.PRESIGNED_URL_EXPIRES_IN = '10'
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
getSignedUrlSpy.mockClear()
await s3.presign('bucket', 'key', 'GET')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 10 * 3600 }),
)
@@ -120,11 +129,14 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.not.objectContaining({
contentDisposition: expect.anything(),
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
input: expect.not.objectContaining({
ResponseContentDisposition: expect.anything(),
}),
}),
expect.anything(),
)
})
@@ -132,11 +144,14 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true)
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
contentDisposition: 'attachment',
input: expect.objectContaining({
ResponseContentDisposition: 'attachment',
}),
}),
expect.anything(),
)
})
@@ -144,11 +159,15 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, 'foo.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
contentDisposition: 'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
input: expect.objectContaining({
ResponseContentDisposition:
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
}),
}),
expect.anything(),
)
})
@@ -156,34 +175,35 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, '报告.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
// Non-ASCII names are conveyed only via filename* (percent-encoded),
// keeping the header value pure ASCII (RFC 7230).
contentDisposition: "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.png",
input: expect.objectContaining({
ResponseContentDisposition: "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.png",
}),
}),
expect.anything(),
)
})
it('should not cache download presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
s3PresignSpy.mockReturnValueOnce('http://download-url-1')
s3PresignSpy.mockReturnValueOnce('http://download-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://download-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://download-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET', true)
const url2 = await s3.presign('bucket', 'key', 'GET', true)
expect(url1).toBe('http://download-url-1')
expect(url2).toBe('http://download-url-2')
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
})
it('should handle ReadableStream in putObject by wrapping in Response', async () => {
it('should handle ReadableStream in putObject', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3WriteSpy.mockClear()
s3SendSpy.mockClear()
const stream = new ReadableStream({
start(controller) {
@@ -194,25 +214,198 @@ describe('S3Service implementations', () => {
await s3.putObject('test-bucket', 'file.txt', stream, 14, 'text/plain')
expect(s3WriteSpy).toHaveBeenCalledWith(
'file.txt',
expect.any(Response),
expect.objectContaining({ bucket: 'test-bucket', type: 'text/plain' }),
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
ContentType: 'text/plain',
ContentLength: 14,
}),
}),
)
})
it('should handle ArrayBuffer in putObject', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3WriteSpy.mockClear()
s3SendSpy.mockClear()
const arrayBuffer = new TextEncoder().encode('array buffer content').buffer
await s3.putObject('test-bucket', 'file.txt', arrayBuffer, 20, 'text/plain')
expect(s3WriteSpy).toHaveBeenCalledWith(
'file.txt',
arrayBuffer,
expect.objectContaining({ bucket: 'test-bucket', type: 'text/plain' }),
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
ContentType: 'text/plain',
ContentLength: 20,
}),
}),
)
})
it('should presign multipart operations correctly', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
// PUT part
await s3.presignMultipart('bucket', 'key', {
method: 'PUT',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
partNumber: 1,
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(UploadPartCommand),
expect.anything(),
)
// PUT single
await s3.presignMultipart('bucket', 'key', {
method: 'PUT',
key: 'key',
fileId: 'file-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(PutObjectCommand),
expect.anything(),
)
// POST create multipart
await s3.presignMultipart('bucket', 'key', {
method: 'POST',
key: 'key',
fileId: 'file-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(CreateMultipartUploadCommand),
expect.anything(),
)
// POST complete multipart
await s3.presignMultipart('bucket', 'key', {
method: 'POST',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(CompleteMultipartUploadCommand),
expect.anything(),
)
// GET list parts
await s3.presignMultipart('bucket', 'key', {
method: 'GET',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(ListPartsCommand),
expect.anything(),
)
// DELETE abort multipart
await s3.presignMultipart('bucket', 'key', {
method: 'DELETE',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(AbortMultipartUploadCommand),
expect.anything(),
)
// Expect GET without uploadId to throw
await expect(
s3.presignMultipart('bucket', 'key', {
method: 'GET',
key: 'key',
fileId: 'file-1',
}),
).rejects.toThrow('List parts requires uploadId')
// Expect DELETE without uploadId to throw
await expect(
s3.presignMultipart('bucket', 'key', {
method: 'DELETE',
key: 'key',
fileId: 'file-1',
}),
).rejects.toThrow('Abort multipart upload requires uploadId')
})
it('should stream in uploadFileToKey', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3SendSpy.mockClear()
const tmpFile = path.join(process.cwd(), 'data-test-stream.txt')
fs.writeFileSync(tmpFile, 'streaming content from file')
try {
await s3.uploadFileToKey(tmpFile, 'test/key.txt', 'text/plain')
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'test/key.txt',
ContentType: 'text/plain',
ContentLength: 27,
Body: expect.any(fs.ReadStream),
}),
}),
)
// Wait for stream to open and close before unlinking
const callArg = s3SendSpy.mock.calls[0]?.[0]
const stream = callArg?.input?.Body as fs.ReadStream | undefined
if (stream) {
if (!stream.destroyed) {
await new Promise((resolve) => {
if (stream.pending) {
stream.once('open', resolve)
} else {
resolve(null)
}
})
stream.destroy()
await new Promise((resolve) => {
stream.once('close', resolve)
})
}
}
} finally {
if (fs.existsSync(tmpFile)) {
fs.unlinkSync(tmpFile)
}
}
})
it('should abort multipart upload in S3', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3SendSpy.mockClear()
await s3.abortMultipartUpload('test-bucket', 'file.txt', 'upload-123')
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
UploadId: 'upload-123',
}),
}),
)
})
})
+254 -75
View File
@@ -1,8 +1,25 @@
import { ObjectInfo } from '@shumai/dtos'
import { S3Client } from 'bun'
import { ObjectInfo, S3SignRequest } from '@shumai/dtos'
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
HeadObjectCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
ListObjectsV2Command,
ListObjectsV2CommandOutput,
CopyObjectCommand,
CreateMultipartUploadCommand,
UploadPartCommand,
ListPartsCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { Readable } from 'stream'
import { ulid } from 'ulid'
import { LruTtlCache } from '../cache/lru-ttl-cache'
import { detectSupportedMimeType } from '../utils/mime'
@@ -94,6 +111,12 @@ export interface S3Service {
download?: boolean,
filename?: string,
) => Promise<string>
presignMultipart: (
bucket: string,
key: string,
request: S3SignRequest,
) => Promise<{ url: string }>
abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise<void>
}
export class S3StorageService implements S3Service {
@@ -111,39 +134,59 @@ export class S3StorageService implements S3Service {
this.client = new S3Client({
region,
endpoint,
accessKeyId,
secretAccessKey,
bucket,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle: true,
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
})
this.bucket = bucket
}
async getObjectSize(bucket: string, key: string): Promise<number> {
return await this.client.size(key, { bucket })
const res = await this.client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
return res.ContentLength ?? 0
}
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream,
_size: number,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS.ReadableStream,
size: number,
contentType?: string,
): Promise<void> {
const payload =
body && typeof body === 'object' && 'getReader' in body
? new Response(body as ReadableStream)
: body
await this.client.write(key, payload, {
bucket,
type: contentType,
})
let payload: string | Uint8Array | Buffer | NodeJS.ReadableStream = ''
if (body && typeof body === 'object' && 'getReader' in body) {
// Convert web ReadableStream to Node stream without buffering into memory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload = Readable.fromWeb(body as any)
} else if (body && typeof body === 'object' && 'pipe' in body) {
payload = body as NodeJS.ReadableStream
} else if (body instanceof ArrayBuffer) {
payload = Buffer.from(body)
} else if (typeof body === 'string' || body instanceof Uint8Array || Buffer.isBuffer(body)) {
payload = body
}
await this.client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
// AWS SDK v3 PutObjectCommandInput types differ slightly between Node and Web streams
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Body: payload as any,
ContentLength: size > 0 ? size : undefined,
ContentType: contentType,
}),
)
}
async getObject(bucket: string, key: string): Promise<S3Object> {
const file = this.client.file(key, { bucket })
const arrayBuffer = await file.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
let contentType = file.type
const res = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
const bytes = await res.Body?.transformToByteArray()
const buffer = bytes ? Buffer.from(bytes) : Buffer.alloc(0)
let contentType = res.ContentType
if (!contentType || contentType === 'application/octet-stream') {
const detected = detectSupportedMimeType(buffer)
if (detected) {
@@ -167,20 +210,26 @@ export class S3StorageService implements S3Service {
destBucket: string,
destKey: string,
): Promise<void> {
const sourceFile = this.client.file(sourceKey, { bucket: sourceBucket })
await this.client.write(destKey, sourceFile, { bucket: destBucket })
await this.client.send(
new CopyObjectCommand({
CopySource: `${sourceBucket}/${sourceKey}`,
Bucket: destBucket,
Key: destKey,
}),
)
}
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
const file = this.client.file(key, { bucket })
await Bun.write(filePath, file)
const res = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
const bytes = await res.Body?.transformToByteArray()
if (bytes) {
await Bun.write(filePath, bytes)
}
}
async deleteObject(bucket: string, key: string): Promise<number> {
try {
const exists = await this.client.exists(key, { bucket })
if (!exists) return 0
await this.client.delete(key, { bucket })
await this.client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }))
return 1
} catch {
return 0
@@ -189,27 +238,35 @@ export class S3StorageService implements S3Service {
async deletePrefix(bucket: string, prefix: string): Promise<number> {
const keys = await this.listObjects(bucket, prefix)
if (keys.length > 0) {
await Promise.all(keys.map((key) => this.deleteObject(bucket, key)))
if (keys.length === 0) return 0
const chunkSize = 1000
for (let i = 0; i < keys.length; i += chunkSize) {
const batch = keys.slice(i, i + chunkSize)
await this.client.send(
new DeleteObjectsCommand({
Bucket: bucket,
Delete: {
Objects: batch.map((k) => ({ Key: k })),
Quiet: true,
},
}),
)
}
return keys.length
}
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
const file = this.client.file(key, { bucket })
const exists = await file.exists()
if (!exists) {
throw new Error(`NoSuchKey: The specified key does not exist.`)
}
// Bun.S3File doesn't expose lastModified or eTag directly in a way that matches ObjectInfo easily
// but we can try to get them if available. For now, using defaults for fields not provided.
return {
key,
size: await file.size,
lastModified: new Date(), // Bun doesn't expose this yet via S3File
contentType: file.type || 'application/octet-stream',
eTag: '',
try {
const res = await this.client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
return {
key,
size: res.ContentLength ?? 0,
lastModified: res.LastModified ?? new Date(),
contentType: res.ContentType || 'application/octet-stream',
eTag: res.ETag || '',
}
} catch (err: unknown) {
throw new Error(`NoSuchKey: The specified key does not exist.`, { cause: err })
}
}
@@ -219,21 +276,24 @@ export class S3StorageService implements S3Service {
let continuationToken: string | undefined = undefined
while (isTruncated) {
const response = await this.client.list({
prefix,
continuationToken,
})
const response: ListObjectsV2CommandOutput = await this.client.send(
new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
ContinuationToken: continuationToken,
}),
)
if (response.contents) {
for (const item of response.contents) {
if (item.key) {
keys.push(item.key)
if (response.Contents) {
for (const item of response.Contents) {
if (item.Key) {
keys.push(item.Key)
}
}
}
isTruncated = response.isTruncated || false
continuationToken = response.nextContinuationToken
isTruncated = response.IsTruncated || false
continuationToken = response.NextContinuationToken
}
return keys
@@ -246,10 +306,17 @@ export class S3StorageService implements S3Service {
}
async uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void> {
await this.client.write(key, Bun.file(filePath), {
bucket: this.bucket,
type: contentType,
})
const file = Bun.file(filePath)
const stream = fs.createReadStream(filePath)
await this.client.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: stream,
ContentLength: file.size,
ContentType: contentType,
}),
)
}
async presign(
@@ -261,37 +328,125 @@ export class S3StorageService implements S3Service {
): Promise<string> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
// Cache time is 2/3 of expire time, rounded to minute
const cacheMinutes = Math.round((expireHours * 60 * 2) / 3)
const cacheTtlMs = cacheMinutes * 60 * 1000
const cacheKey = `${bucket}:${key}`
const cacheTtlMs = expiresInSeconds * 1000
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
if (cached) return cached
if (cached) {
return cached
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options: any = {
bucket,
expiresIn: expiresInSeconds,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
method: method as any,
}
let url: string
if (download) {
options.contentDisposition = buildContentDisposition(filename)
if (method === 'GET') {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
ResponseContentDisposition: download ? buildContentDisposition(filename) : undefined,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'PUT') {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'DELETE') {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presign: ${method}`)
}
const url = this.client.presign(key, options)
if (method === 'GET' && !download) {
this.presignCache.set(cacheKey, url, cacheTtlMs)
}
return url
}
async presignMultipart(
bucket: string,
key: string,
request: S3SignRequest,
): Promise<{ url: string }> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
let url: string
if (request.method === 'PUT') {
if (request.uploadId && request.partNumber != null) {
const command = new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
PartNumber: request.partNumber,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'POST') {
if (request.uploadId) {
const command = new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new CreateMultipartUploadCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'GET') {
if (!request.uploadId) {
throw new Error('List parts requires uploadId')
}
const command = new ListPartsCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (request.method === 'DELETE') {
if (!request.uploadId) {
throw new Error('Abort multipart upload requires uploadId')
}
const command = new AbortMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presignMultipart: ${request.method}`)
}
return { url }
}
async abortMultipartUpload(bucket: string, key: string, uploadId: string): Promise<void> {
await this.client.send(
new AbortMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
}),
)
}
}
export class LocalStorageService implements S3Service {
@@ -527,9 +682,33 @@ export class LocalStorageService implements S3Service {
}
return url
}
async presignMultipart(
bucket: string,
key: string,
request: S3SignRequest,
): Promise<{ url: string }> {
if (request.method === 'PUT') {
return { url: `${this.endpoint}${signLocalUrl(bucket, key)}` }
}
const url = await this.presign(bucket, key, request.method)
return { url }
}
async abortMultipartUpload(
bucket: string,
key: string,
_uploadId: string, // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
await this.deleteObject(bucket, key)
}
}
const storageBackend = process.env.STORAGE_BACKEND || 'local'
export function getStorageBackend(): 's3' | 'local' {
return (process.env.STORAGE_BACKEND as 's3' | 'local') || 'local'
}
const storageBackend = getStorageBackend()
const port = process.env.SHUMAI_SERVER_PORT || '3000'
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || `http://localhost:${port}`
+294 -1
View File
@@ -4,12 +4,16 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { uploadService } from './upload'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, WorkflowTaskType } from '@shumai/db'
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),
},
}))
@@ -615,4 +619,293 @@ describe('UploadService', () => {
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()
})
})
})
+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()