feat(s3): migrate to bun native s3 and add filename support

This commit is contained in:
yiling
2026-06-08 19:35:46 +08:00
parent dc1595f120
commit f96f687be4
5 changed files with 170 additions and 163 deletions
+37 -1
View File
@@ -14,6 +14,7 @@ vi.mock('hono/bun', () => ({
describe('S3 API', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.resetModules()
})
it('GET /files/* calls serveStatic with correct options', async () => {
@@ -39,10 +40,45 @@ describe('S3 API', () => {
}
})
it('GET /files/* with filename query parameter sets Content-Disposition header', async () => {
// We need to capture the onFound callback from serveStatic options
let onFoundCallback: Function | undefined
mockServeStatic.mockImplementationOnce((options: any) => {
onFoundCallback = options.onFound
return (c: any) => c.text('static-file')
})
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
// First, verify onFound is called through the mock
await app.request('/files/b1/test.webp?filename=my-file.txt')
expect(onFoundCallback).toBeDefined()
// Test the callback directly
const mockContext = {
req: {
query: (key: string) => (key === 'filename' ? 'my-file.txt' : undefined),
},
header: vi.fn(),
}
if (onFoundCallback) {
onFoundCallback('/files/b1/test.webp', mockContext)
expect(mockContext.header).toHaveBeenCalledWith(
'Content-Disposition',
'attachment; filename="my-file.txt"',
)
}
})
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
const { s3Service: service } = await import('@shumai/core/src/s3/s3')
const mockPut = vi.spyOn(service, 'putObject').mockResolvedValue(undefined)
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const mockPut = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
const body = new TextEncoder().encode('test-data')
const res = await app.request('/files/b1/test.webp', {
+6
View File
@@ -8,6 +8,12 @@ const route = new Hono()
serveStatic({
root: './data',
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
onFound: (_path, c) => {
const filename = c.req.query('filename')
if (filename) {
c.header('Content-Disposition', `attachment; filename="${filename}"`)
}
},
}),
)
.put('/:bucket/:key{.+}', async (c) => {
+11 -1
View File
@@ -824,6 +824,7 @@ export class AssetService {
process.env.S3_BUCKET || 'shumai',
info.media.original.key,
'GET',
a.name,
)
}
}
@@ -1548,9 +1549,18 @@ export class AssetService {
const key = latestVersion.storageKey?.key
if (media && key) {
const fileName =
a.type === AssetType.version_stack && (a.name === '' || !a.name)
? latestVersion.name
: a.name
media.original = {
key,
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
downloadUrl: await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
key,
'GET',
fileName,
),
filesizeInBytes: latestVersion.sizeByte,
codec: '', // TODO: extract from metadata if needed
}
+52 -33
View File
@@ -3,36 +3,41 @@ import * as fs from 'fs'
import * as path from 'path'
import { LocalStorageService, S3StorageService } from './s3'
// Mock the AWS SDK
// Mock Bun S3Client
const s3ClientConstructorSpy = vi.fn()
vi.mock('@aws-sdk/client-s3', () => {
const s3FileSpy = vi.fn()
const s3WriteSpy = vi.fn()
const s3DeleteSpy = vi.fn()
const s3ListSpy = vi.fn()
const s3ExistsSpy = vi.fn()
const s3PresignSpy = vi.fn()
vi.mock('bun', () => {
return {
S3Client: class {
constructor(params: unknown) {
s3ClientConstructorSpy(params)
}
send = vi.fn().mockResolvedValue({})
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')
},
HeadObjectCommand: class {},
PutObjectCommand: class {},
GetObjectCommand: class {},
ListObjectsV2Command: class {},
}
})
vi.mock('@aws-sdk/s3-request-presigner', () => {
return {
getSignedUrl: vi.fn().mockResolvedValue('http://presigned-url'),
}
})
describe('S3Service implementations', () => {
beforeEach(async () => {
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
vi.mocked(getSignedUrl).mockReset()
vi.mocked(getSignedUrl).mockResolvedValue('http://presigned-url')
vi.clearAllMocks()
delete process.env.PRESIGNED_URL_EXPIRES_IN
s3PresignSpy.mockReturnValue('http://presigned-url')
})
describe('S3StorageService', () => {
@@ -64,56 +69,65 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
const url = await s3.presign('bucket', 'key', 'GET')
expect(url).toBe('http://presigned-url')
expect(s3PresignSpy).toHaveBeenCalledWith('key', expect.objectContaining({ method: 'GET' }))
})
it('should cache GET presign URLs', async () => {
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
vi.mocked(getSignedUrl).mockClear()
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://presigned-url-1')
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://presigned-url-2')
s3PresignSpy.mockClear()
s3PresignSpy.mockReturnValueOnce('http://presigned-url-1')
s3PresignSpy.mockReturnValueOnce('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(vi.mocked(getSignedUrl)).toHaveBeenCalledTimes(1)
expect(s3PresignSpy).toHaveBeenCalledTimes(1)
})
it('should NOT cache PUT presign URLs', async () => {
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
vi.mocked(getSignedUrl).mockClear()
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://put-url-1')
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://put-url-2')
s3PresignSpy.mockReset()
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-1')
s3PresignSpy.mockReturnValueOnce('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://put-url-1')
expect(url2).toBe('http://put-url-2')
expect(vi.mocked(getSignedUrl)).toHaveBeenCalledTimes(2)
expect(url1).toBe('http://unique-put-url-1')
expect(url2).toBe('http://unique-put-url-2')
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
})
it('should respect PRESIGNED_URL_EXPIRES_IN env', async () => {
process.env.PRESIGNED_URL_EXPIRES_IN = '10'
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
vi.mocked(getSignedUrl).mockClear()
s3PresignSpy.mockClear()
await s3.presign('bucket', 'key', 'GET')
expect(vi.mocked(getSignedUrl)).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.objectContaining({ expiresIn: 10 * 3600 }),
)
delete process.env.PRESIGNED_URL_EXPIRES_IN
})
it('should pass filename to presign', async () => {
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
await s3.presign('bucket', 'key', 'GET', 'test.txt')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.objectContaining({
contentDisposition: 'attachment; filename="test.txt"',
}),
)
})
})
describe('LocalStorageService', () => {
@@ -168,6 +182,11 @@ describe('S3Service implementations', () => {
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
})
it('should generate a local presign URL with filename', async () => {
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', 'original.txt')
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?filename=original.txt')
})
it('should throw an error for unsupported presign methods', async () => {
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
})
+64 -128
View File
@@ -1,14 +1,5 @@
import { ObjectInfo } from '@shumai/dtos'
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { S3Client } from 'bun'
import * as crypto from 'crypto'
import * as fs from 'fs'
import { readFileSync, statSync } from 'fs'
@@ -64,7 +55,7 @@ export interface S3Service {
listObjects(bucket: string, prefix: string): Promise<string[]>
uploadFile(filePath: string, contentType: string): Promise<string>
uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void>
presign(bucket: string, key: string, method: string): Promise<string>
presign(bucket: string, key: string, method: string, filename?: string): Promise<string>
}
export class S3StorageService implements S3Service {
@@ -89,54 +80,37 @@ export class S3StorageService implements S3Service {
this.client = new S3Client({
region,
endpoint: fullEndpoint,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle: false,
accessKeyId,
secretAccessKey,
bucket,
})
this.bucket = bucket
}
async getObjectSize(bucket: string, key: string): Promise<number> {
const command = new HeadObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
return response.ContentLength || 0
const file = this.client.file(key, { bucket })
return await file.size
}
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
size: number,
_size: number,
contentType?: string,
): Promise<void> {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: body,
ContentLength: size,
ContentType: contentType,
await this.client.write(key, body, {
bucket,
type: contentType,
})
await this.client.send(command)
}
async getObject(bucket: string, key: string): Promise<S3Object> {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
if (!response.Body) {
throw new Error('Empty response body')
}
const byteArray = await response.Body.transformToByteArray()
const file = this.client.file(key, { bucket })
const arrayBuffer = await file.arrayBuffer()
return {
buffer: Buffer.from(byteArray),
contentType: response.ContentType || 'application/octet-stream',
buffer: Buffer.from(arrayBuffer),
contentType: file.type || 'application/octet-stream',
}
}
@@ -146,54 +120,23 @@ export class S3StorageService implements S3Service {
destBucket: string,
destKey: string,
): Promise<void> {
const command = new CopyObjectCommand({
Bucket: destBucket,
Key: destKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
CopySource: `${sourceBucket}/${sourceKey}`,
})
await this.client.send(command)
const sourceFile = this.client.file(sourceKey, { bucket: sourceBucket })
await this.client.write(destKey, sourceFile, { bucket: destBucket })
}
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
if (!response.Body) {
throw new Error('Empty response body')
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const stream = response.Body as any
const writeStream = fs.createWriteStream(filePath)
await new Promise((resolve, reject) => {
stream
.pipe(writeStream)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.on('error', (err: any) => {
writeStream.close()
reject(err)
})
.on('finish', () => {
writeStream.close()
resolve(null)
})
})
const file = this.client.file(key, { bucket })
const arrayBuffer = await file.arrayBuffer()
await fs.promises.writeFile(filePath, Buffer.from(arrayBuffer))
}
async deleteObject(bucket: string, key: string): Promise<number> {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
try {
await this.client.send(command)
const exists = await this.client.exists(key, { bucket })
if (!exists) return 0
await this.client.delete(key, { bucket })
return 1
} catch {
// If object doesn't exist, we return 0
return 0
}
}
@@ -207,17 +150,20 @@ export class S3StorageService implements S3Service {
}
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
const command = new HeadObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
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: response.ContentLength || 0,
lastModified: response.LastModified || new Date(),
contentType: response.ContentType || 'application/octet-stream',
eTag: response.ETag || '',
size: await file.size,
lastModified: new Date(), // Bun doesn't expose this yet via S3File
contentType: file.type || 'application/octet-stream',
eTag: '',
}
}
@@ -227,23 +173,21 @@ export class S3StorageService implements S3Service {
let continuationToken: string | undefined = undefined
while (isTruncated) {
const command: ListObjectsV2Command = new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
ContinuationToken: continuationToken,
const response = await this.client.list({
prefix,
continuationToken,
})
const response = await this.client.send(command)
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
@@ -256,50 +200,38 @@ export class S3StorageService implements S3Service {
}
async uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void> {
const fileStats = statSync(filePath)
const fileContent = readFileSync(filePath)
const command = new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: fileContent,
ContentLength: fileStats.size,
ContentType: contentType,
await this.client.write(key, fileContent, {
bucket: this.bucket,
type: contentType,
})
await this.client.send(command)
}
async presign(bucket: string, key: string, method: string): Promise<string> {
async presign(bucket: string, key: string, method: string, filename?: string): 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 cacheKey = `${bucket}:${key}:${filename || ''}`
if (method === 'GET') {
const cached = this.presignCache.get(cacheKey)
if (cached) return cached
}
let command: GetObjectCommand | PutObjectCommand
if (method === 'GET') {
command = new GetObjectCommand({
Bucket: bucket,
Key: key,
})
} else if (method === 'PUT') {
command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
} else {
throw new Error(`Invalid method: ${method}`)
const options: any = {
bucket,
expiresIn: expiresInSeconds,
method: method as any,
}
const url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
if (filename) {
options.contentDisposition = `attachment; filename="${filename}"`
}
const url = this.client.presign(key, options)
if (method === 'GET') {
this.presignCache.set(cacheKey, url, cacheTtlMs)
@@ -505,14 +437,18 @@ export class LocalStorageService implements S3Service {
await fs.promises.copyFile(filePath, destPath)
}
async presign(bucket: string, key: string, method: string): Promise<string> {
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
if (method !== 'GET' && method !== 'PUT') {
throw new Error(`Invalid method: ${method}`)
}
if (method === 'PUT') {
return `${this.endpoint}${signLocalUrl(bucket, key)}`
}
return `${this.endpoint}/files/${bucket}/${key}`
let url = `${this.endpoint}/files/${bucket}/${key}`
if (filename) {
url += `?filename=${encodeURIComponent(filename)}`
}
return url
}
}