From f62df9555a70d604b630fa0794727583df8a99be Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Mon, 7 Sep 2026 19:33:13 +0800 Subject: [PATCH] fix(s3): stream downloadToFile and putObject to prevent OOM on large files (#392) * fix(s3): stream downloadToFile and putObject to prevent OOM on large files * fix(agent): preserve file MIME detection on download_asset and align local download directory creation --- packages/agent/src/activities/ai.test.ts | 28 +++++ packages/agent/src/activities/ai.ts | 10 +- .../agent/src/tools/download-asset.test.ts | 100 +++++++++++++---- packages/agent/src/tools/download-asset.ts | 32 ++++-- packages/api/src/upload.ts | 6 +- packages/core/src/s3/s3.test.ts | 105 ++++++++++++++++++ packages/core/src/s3/s3.ts | 47 +++++--- 7 files changed, 272 insertions(+), 56 deletions(-) diff --git a/packages/agent/src/activities/ai.test.ts b/packages/agent/src/activities/ai.test.ts index 66912080..05edd389 100644 --- a/packages/agent/src/activities/ai.test.ts +++ b/packages/agent/src/activities/ai.test.ts @@ -6,6 +6,7 @@ import { saveAssetEmbeddingsActivity, generateImageEmbeddingActivity, generateVideoChunkEmbeddingActivity, + generateEmbeddingActivity, } from './ai' import { s3Service } from '@shumai/core/src/s3/s3' import { transcodeService } from '@shumai/core' @@ -35,6 +36,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ putObject: vi.fn(), headObject: vi.fn(), listObjects: vi.fn(), + downloadToFile: vi.fn(), }, })) @@ -121,6 +123,32 @@ describe('AI Activities Unit Tests', () => { ) }) + it('should stream video to tmp file via downloadToFile in generateEmbeddingActivity', async () => { + vi.mocked(s3Service.downloadToFile).mockResolvedValue() + + const res = await generateEmbeddingActivity({ + teamId: 't1', + assetId: 'asset-123', + context: { + agent: {}, + asset: { + mediaType: 'video/mp4', + name: 'sample.mp4', + storageKey: { key: 'files/asset-123/video.mp4' }, + media: { proxyType: 'video' }, + }, + }, + }) + + expect(s3Service.downloadToFile).toHaveBeenCalledWith( + 'shumai', + 'files/asset-123/video.mp4', + expect.stringContaining('video-'), + ) + expect(s3Service.getObject).not.toHaveBeenCalledWith('shumai', 'files/asset-123/video.mp4') + expect(res.embeddings.length).toBeGreaterThan(0) + }) + it('should generate text embedding successfully', async () => { const res = await generateTextEmbeddingActivity({ text: 'Search query', diff --git a/packages/agent/src/activities/ai.ts b/packages/agent/src/activities/ai.ts index 3d245544..0983abb0 100644 --- a/packages/agent/src/activities/ai.ts +++ b/packages/agent/src/activities/ai.ts @@ -107,16 +107,16 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true }) } - const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key) - + const bucket = process.env.S3_BUCKET || 'shumai' const results: GeneratedEmbedding[] = [] if (isImage) { + const { buffer: data } = await s3Service.getObject(bucket, key) const embVec = await generateMultimodalEmbedding(ai, data, asset.mediaType) results.push({ embedding: embVec }) } else if (isVideo) { const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`) - fs.writeFileSync(tmpFile, data) + await s3Service.downloadToFile(bucket, key, tmpFile) try { const { stdout } = await execFileAsync('ffprobe', [ @@ -171,7 +171,9 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) } } } finally { - fs.unlinkSync(tmpFile) + if (fs.existsSync(tmpFile)) { + fs.unlinkSync(tmpFile) + } } } diff --git a/packages/agent/src/tools/download-asset.test.ts b/packages/agent/src/tools/download-asset.test.ts index 994c68d0..6b15e6eb 100644 --- a/packages/agent/src/tools/download-asset.test.ts +++ b/packages/agent/src/tools/download-asset.test.ts @@ -30,6 +30,8 @@ vi.mock('@shumai/db', async (importOriginal) => { vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { getObject: vi.fn(), + headObject: vi.fn(), + downloadToFile: vi.fn(), }, })) @@ -104,10 +106,12 @@ describe('downloadAssetTool', () => { }, } as unknown as Asset) - vi.mocked(s3Service.getObject).mockResolvedValue({ - buffer: Buffer.from('fake-proxy-image-bytes'), + vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => { + await fs.promises.writeFile(dest, 'fake-proxy-image-bytes') + }) + vi.mocked(s3Service.headObject).mockResolvedValue({ contentType: 'image/webp', - } as unknown as { buffer: Buffer; contentType: string }) + } as unknown as Awaited>) const tool = createDownloadAssetTool('user-1') const result = await tool.execute('call-1', { assetId: 'asset-img-1', key: null }) @@ -119,11 +123,15 @@ describe('downloadAssetTool', () => { id: 'asset-img-1', }) - expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/sample_photo.webp') - const expectedPath = path.join(piDir, 'asset-img-1_sample_photo.jpg') createdFiles.push(expectedPath) + expect(s3Service.downloadToFile).toHaveBeenCalledWith( + 'shumai', + 'proxy/sample_photo.webp', + expectedPath, + ) + expect(fs.existsSync(expectedPath)).toBe(true) expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-proxy-image-bytes') @@ -155,10 +163,12 @@ describe('downloadAssetTool', () => { }, } as unknown as Asset) - vi.mocked(s3Service.getObject).mockResolvedValue({ - buffer: Buffer.from('fake-version-bytes'), + vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => { + await fs.promises.writeFile(dest, 'fake-version-bytes') + }) + vi.mocked(s3Service.headObject).mockResolvedValue({ contentType: 'image/webp', - } as unknown as { buffer: Buffer; contentType: string }) + } as unknown as Awaited>) const tool = createDownloadAssetTool('user-1') const result = await tool.execute('call-1', { assetId: 'stack-1', key: null }) @@ -169,11 +179,15 @@ describe('downloadAssetTool', () => { include: { storageKey: true }, }) - expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/banana_pig.webp') - const expectedPath = path.join(piDir, 'file-ver-2_banana_pig.png') createdFiles.push(expectedPath) + expect(s3Service.downloadToFile).toHaveBeenCalledWith( + 'shumai', + 'proxy/banana_pig.webp', + expectedPath, + ) + expect(fs.existsSync(expectedPath)).toBe(true) expect(result.details.name).toBe('banana_pig.png') }) @@ -237,7 +251,7 @@ describe('downloadAssetTool', () => { type: 'asset', id: 'asset-in-other-project', }) - expect(s3Service.getObject).not.toHaveBeenCalled() + expect(s3Service.downloadToFile).not.toHaveBeenCalled() }) it('should authorize and download derived artifact key (files//...)', async () => { @@ -246,10 +260,12 @@ describe('downloadAssetTool', () => { } as unknown as Asset) vi.mocked(authzService.hasPermission).mockResolvedValue() - vi.mocked(s3Service.getObject).mockResolvedValue({ - buffer: Buffer.from('fake-screenshot-bytes'), + vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => { + await fs.promises.writeFile(dest, 'fake-screenshot-bytes') + }) + vi.mocked(s3Service.headObject).mockResolvedValue({ contentType: 'image/webp', - } as unknown as { buffer: Buffer; contentType: string }) + } as unknown as Awaited>) const tool = createDownloadAssetTool('user-1') const result = await tool.execute('call-1', { @@ -264,14 +280,15 @@ describe('downloadAssetTool', () => { id: 'ast-123', }) - expect(s3Service.getObject).toHaveBeenCalledWith( - 'shumai', - 'files/ast-123/screenshots/shot_5.0s.webp', - ) - const expectedPath = path.join(piDir, 'shot_5.0s.webp') createdFiles.push(expectedPath) + expect(s3Service.downloadToFile).toHaveBeenCalledWith( + 'shumai', + 'files/ast-123/screenshots/shot_5.0s.webp', + expectedPath, + ) + expect(fs.existsSync(expectedPath)).toBe(true) expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-screenshot-bytes') @@ -290,10 +307,12 @@ describe('downloadAssetTool', () => { } as unknown as StorageKey & { assets: Asset[] }) vi.mocked(authzService.hasPermission).mockResolvedValue() - vi.mocked(s3Service.getObject).mockResolvedValue({ - buffer: Buffer.from('fake-original-photo-bytes'), + vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => { + await fs.promises.writeFile(dest, 'fake-original-photo-bytes') + }) + vi.mocked(s3Service.headObject).mockResolvedValue({ contentType: 'image/png', - } as unknown as { buffer: Buffer; contentType: string }) + } as unknown as Awaited>) const tool = createDownloadAssetTool('user-1') const result = await tool.execute('call-1', { @@ -308,14 +327,47 @@ describe('downloadAssetTool', () => { id: 'asset-photo-1', }) - expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'files/upload-ulid-456/photo.png') - const expectedPath = path.join(piDir, 'photo.png') createdFiles.push(expectedPath) + expect(s3Service.downloadToFile).toHaveBeenCalledWith( + 'shumai', + 'files/upload-ulid-456/photo.png', + expectedPath, + ) + expect(fs.existsSync(expectedPath)).toBe(true) expect(result.details.assetId).toBe('asset-photo-1') }) + + it('should fall back to file MIME detection when headObject returns generic application/octet-stream', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue(null) + vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({ + id: 'sk-2', + key: 'files/upload-ulid-789/graphic.png', + assets: [{ id: 'asset-graphic-1' }], + } as unknown as StorageKey & { assets: Asset[] }) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => { + const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + await fs.promises.writeFile(dest, pngHeader) + }) + vi.mocked(s3Service.headObject).mockResolvedValue({ + contentType: 'application/octet-stream', + } as unknown as Awaited>) + + const tool = createDownloadAssetTool('user-1') + const result = await tool.execute('call-1', { + assetId: null, + key: 'files/upload-ulid-789/graphic.png', + }) + + const expectedPath = path.join(piDir, 'graphic.png') + createdFiles.push(expectedPath) + + expect(result.details.contentType).toBe('image/png') + }) }) describe('resolveAssetIdFromKey helper unit tests', () => { diff --git a/packages/agent/src/tools/download-asset.ts b/packages/agent/src/tools/download-asset.ts index 740a8028..046f1c43 100644 --- a/packages/agent/src/tools/download-asset.ts +++ b/packages/agent/src/tools/download-asset.ts @@ -4,7 +4,7 @@ import { prisma, type User } from '@shumai/db' import { s3Service } from '@shumai/core/src/s3/s3' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { sanitizeFilename } from '@shumai/core/src/utils/filename' -import { getFileMimeType } from '@shumai/core/src/utils/file-mime' +import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime' import * as fs from 'fs' import * as path from 'path' @@ -215,8 +215,15 @@ export function createDownloadAssetTool(userId: string): AgentTool null) + await s3Service.downloadToFile(bucket, mediaKey, targetFilePath) + const stat = await fs.promises + .stat(targetFilePath) + .catch(() => ({ size: objectInfo?.size ?? 0 })) + const contentType = + objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream' + ? objectInfo.contentType + : readFileMimeType(targetFilePath) return { content: [ @@ -230,8 +237,8 @@ export function createDownloadAssetTool(userId: string): AgentTool null) + await s3Service.downloadToFile(bucket, key, targetFilePath) + const stat = await fs.promises + .stat(targetFilePath) + .catch(() => ({ size: objectInfo?.size ?? 0 })) + const contentType = + objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream' + ? objectInfo.contentType + : readFileMimeType(targetFilePath) return { content: [ @@ -268,8 +282,8 @@ export function createDownloadAssetTool(userId: string): AgentTool { }), ) }) + + it('should stream in downloadToFile without buffering or calling transformToByteArray', async () => { + const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') + s3SendSpy.mockClear() + + async function* chunkedBody() { + yield new Uint8Array([1, 2]) + yield new Uint8Array([3, 4]) + } + + const transformSpy = vi.fn() + const mockBody = Object.assign(chunkedBody(), { + transformToByteArray: transformSpy, + }) + + s3SendSpy.mockResolvedValueOnce({ Body: mockBody }) + + const tmpDir = path.join(process.cwd(), 'data-test-download', 'subdir') + const targetPath = path.join(tmpDir, 'downloaded.bin') + + try { + await s3.downloadToFile('test-bucket', 'file.bin', targetPath) + + expect(transformSpy).not.toHaveBeenCalled() + const written = await fs.promises.readFile(targetPath) + expect(Array.from(written)).toEqual([1, 2, 3, 4]) + } finally { + if (fs.existsSync(path.join(process.cwd(), 'data-test-download'))) { + fs.rmSync(path.join(process.cwd(), 'data-test-download'), { + recursive: true, + force: true, + }) + } + } + }) + + it('should clean up partial file if downloadToFile fails midway', async () => { + const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') + s3SendSpy.mockClear() + + async function* failingBody() { + yield new Uint8Array([1, 2]) + throw new Error('Network interruption') + } + + s3SendSpy.mockResolvedValueOnce({ Body: failingBody() }) + + const tmpDir = path.join(process.cwd(), 'data-test-download', 'fail') + const targetPath = path.join(tmpDir, 'downloaded.bin') + + try { + await expect(s3.downloadToFile('test-bucket', 'file.bin', targetPath)).rejects.toThrow( + 'Network interruption', + ) + + expect(fs.existsSync(targetPath)).toBe(false) + } finally { + if (fs.existsSync(path.join(process.cwd(), 'data-test-download'))) { + fs.rmSync(path.join(process.cwd(), 'data-test-download'), { + recursive: true, + force: true, + }) + } + } + }) }) describe('LocalStorageService', () => { @@ -434,6 +499,46 @@ describe('S3Service implementations', () => { expect(size).toBe(11) }) + it('should write Node.js Readable stream in putObject without corrupting to [object Object]', async () => { + const { Readable } = await import('stream') + const stream = Readable.from(['hello ', 'node ', 'stream']) + + await localS3.putObject('test-bucket', 'stream.txt', stream, 17) + + const content = await fs.promises.readFile( + path.join(TEST_BASE_PATH, 'test-bucket', 'stream.txt'), + 'utf8', + ) + expect(content).toBe('hello node stream') + }) + + it('should write Web ReadableStream in putObject', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('web stream content')) + controller.close() + }, + }) + + await localS3.putObject('test-bucket', 'web-stream.txt', stream, 18) + + const content = await fs.promises.readFile( + path.join(TEST_BASE_PATH, 'test-bucket', 'web-stream.txt'), + 'utf8', + ) + expect(content).toBe('web stream content') + }) + + it('should downloadToFile creating destination directory recursively if it does not exist', async () => { + await localS3.putObject('test-bucket', 'source.txt', 'hello download', 14) + const nestedDest = path.join(TEST_BASE_PATH, 'downloads', 'deep', 'nested', 'target.txt') + + await localS3.downloadToFile('test-bucket', 'source.txt', nestedDest) + + const content = await fs.promises.readFile(nestedDest, 'utf8') + expect(content).toBe('hello download') + }) + it('should list objects', async () => { await localS3.putObject('test-bucket', 'dir1/file1.txt', 'abc', 3) await localS3.putObject('test-bucket', 'dir1/file2.txt', 'def', 3) diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 2035cb3e..c90cf885 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -20,6 +20,7 @@ import * as crypto from 'crypto' import * as fs from 'fs' import * as path from 'path' import { Readable } from 'stream' +import { pipeline } from 'stream/promises' import { ulid } from 'ulid' import { LruTtlCache } from '../cache/lru-ttl-cache' import { detectSupportedMimeType } from '../utils/mime' @@ -86,7 +87,7 @@ export interface S3Service { putObject: ( bucket: string, key: string, - body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream, + body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS.ReadableStream, size: number, contentType?: string, ) => Promise @@ -220,10 +221,21 @@ export class S3StorageService implements S3Service { } async downloadToFile(bucket: string, key: string, filePath: string): Promise { + const dir = path.dirname(filePath) + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } + 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) + if (!res.Body) { + return + } + + try { + await pipeline(res.Body as unknown as NodeJS.ReadableStream, fs.createWriteStream(filePath)) + } catch (err) { + await fs.promises.unlink(filePath).catch(() => {}) + throw err } } @@ -485,7 +497,7 @@ export class LocalStorageService implements S3Service { async putObject( bucket: string, key: string, - body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream, + body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS.ReadableStream, _size: number, // eslint-disable-line @typescript-eslint/no-unused-vars _contentType?: string, // eslint-disable-line @typescript-eslint/no-unused-vars ): Promise { @@ -495,18 +507,17 @@ export class LocalStorageService implements S3Service { fs.mkdirSync(dir, { recursive: true }) } - if (body && typeof body === 'object' && 'getReader' in body) { - const file = Bun.file(filePath) - const writer = file.writer() - const reader = (body as ReadableStream).getReader() - while (true) { - const { done, value } = await reader.read() - if (done) break - if (value) { - await writer.write(value) - } + if ( + body && + typeof body === 'object' && + ('pipe' in body || 'getReader' in body || Symbol.asyncIterator in body) + ) { + try { + await pipeline(body as unknown as NodeJS.ReadableStream, fs.createWriteStream(filePath)) + } catch (err) { + await fs.promises.unlink(filePath).catch(() => {}) + throw err } - await writer.end() } else { await Bun.write(filePath, body) } @@ -544,6 +555,10 @@ export class LocalStorageService implements S3Service { } async downloadToFile(bucket: string, key: string, filePath: string): Promise { + const dir = path.dirname(filePath) + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } const srcPath = this.getFilePath(bucket, key) await fs.promises.copyFile(srcPath, filePath) }