feat(transcode): stream uploads and transcode output to prevent memory crashes on large files

This commit is contained in:
yiling
2026-07-29 21:22:49 +08:00
parent 7949c1572a
commit 9a4f8d67c3
5 changed files with 41 additions and 21 deletions
+4 -1
View File
@@ -94,11 +94,14 @@ describe('S3 API', () => {
const res = await app.request('/files/b1/test.webp', {
method: 'PUT',
headers: {
'content-length': body.byteLength.toString(),
},
body,
})
expect(res.status).toBe(200)
expect(await res.text()).toBe('OK')
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.any(Buffer), body.byteLength)
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.anything(), body.byteLength)
})
})
+3 -2
View File
@@ -18,10 +18,11 @@ const route = new Hono()
.put('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
const body = await c.req.arrayBuffer()
const contentLength = parseInt(c.req.header('content-length') || '0', 10)
try {
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength)
return c.text('OK')
} catch (e: unknown) {
const error = e as Error
+6 -9
View File
@@ -26,9 +26,8 @@ export const localUploadRoute = new Hono().put(
}
const contentType = c.req.header('Content-Type')
let buffer: Buffer
let size: number
let finalContentType = contentType
const contentLength = parseInt(c.req.header('Content-Length') || '0', 10)
if (contentType?.includes('multipart/form-data')) {
const body = await c.req.parseBody()
@@ -36,17 +35,15 @@ export const localUploadRoute = new Hono().put(
if (!file) {
return c.text('No file uploaded', 400)
}
buffer = Buffer.from(await file.arrayBuffer())
size = file.size
const buffer = Buffer.from(await file.arrayBuffer())
const size = file.size
finalContentType = file.type || 'application/octet-stream'
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
} else {
const arrayBuffer = await c.req.arrayBuffer()
buffer = Buffer.from(arrayBuffer)
size = arrayBuffer.byteLength
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength, finalContentType)
}
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
return c.json({ success: true })
},
)
+19 -3
View File
@@ -37,7 +37,7 @@ export interface S3Service {
putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream,
size: number,
contentType?: string,
): Promise<void>
@@ -282,7 +282,7 @@ export class LocalStorageService implements S3Service {
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream,
_size: number, // eslint-disable-line @typescript-eslint/no-unused-vars
_contentType?: string, // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
@@ -291,7 +291,23 @@ export class LocalStorageService implements S3Service {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
await fs.promises.writeFile(filePath, body)
if (body && typeof body === 'object' && 'getReader' in body) {
const file = Bun.file(filePath)
const writer = file.writer()
const reader = (body as ReadableStream<Uint8Array>).getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) {
writer.write(value)
}
}
await writer.end()
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await Bun.write(filePath, body as any)
}
}
async getObject(bucket: string, key: string): Promise<S3Object> {
@@ -257,8 +257,9 @@ export async function transcodeVideoActivity(
disableAudio,
})
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'video/mp4')
const stat = fs.statSync(outputFile)
const stream = Bun.file(outputFile).stream()
await s3Service.putObject(bucket, key, stream, stat.size, 'video/mp4')
return { ...params.videoSpec, key }
} catch (err) {
@@ -315,8 +316,9 @@ export async function transcodeAudioActivity(
bitrate: '128k',
})
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'video/mp4')
const stat = fs.statSync(outputFile)
const stream = Bun.file(outputFile).stream()
await s3Service.putObject(bucket, key, stream, stat.size, 'video/mp4')
return { width: 0, height: 0, key }
} catch (err) {
@@ -531,8 +533,9 @@ export async function generatePdfProxyActivity(
await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
}
const buffer = fs.readFileSync(pdfFilePath)
await s3Service.putObject(bucket, pdfProxyKey, buffer, buffer.length, 'application/pdf')
const stat = fs.statSync(pdfFilePath)
const stream = Bun.file(pdfFilePath).stream()
await s3Service.putObject(bucket, pdfProxyKey, stream, stat.size, 'application/pdf')
return { pdfProxyKey, pdfFilePath }
} catch (err) {