Merge pull request #78 from shumaiOne/feat/bun-s3-migration

feat(s3): migrate to bun native s3 and add filename support
This commit is contained in:
Yiling-J
2026-06-08 21:46:14 +08:00
committed by GitHub
8 changed files with 202 additions and 215 deletions
+7 -27
View File
@@ -110,8 +110,6 @@
"name": "@shumai/core",
"version": "0.1.0",
"dependencies": {
"@aws-sdk/client-s3": "^3.1031.0",
"@aws-sdk/s3-request-presigner": "^3.1031.0",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@sinclair/typebox": "^0.34.49",
@@ -292,10 +290,6 @@
"@aws-crypto/crc32": ["@aws-crypto/crc32@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg=="],
"@aws-crypto/crc32c": ["@aws-crypto/crc32c@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag=="],
"@aws-crypto/sha1-browser": ["@aws-crypto/sha1-browser@5.2.0", "", { "dependencies": { "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg=="],
"@aws-crypto/sha256-browser": ["@aws-crypto/sha256-browser@5.2.0", "", { "dependencies": { "@aws-crypto/sha256-js": "^5.2.0", "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw=="],
"@aws-crypto/sha256-js": ["@aws-crypto/sha256-js@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA=="],
@@ -306,12 +300,8 @@
"@aws-sdk/client-bedrock-runtime": ["@aws-sdk/client-bedrock-runtime@3.1048.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/credential-provider-node": "^3.972.42", "@aws-sdk/eventstream-handler-node": "^3.972.16", "@aws-sdk/middleware-eventstream": "^3.972.12", "@aws-sdk/middleware-websocket": "^3.972.19", "@aws-sdk/token-providers": "3.1048.0", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ=="],
"@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.1058.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/credential-provider-node": "^3.972.48", "@aws-sdk/middleware-bucket-endpoint": "^3.972.17", "@aws-sdk/middleware-expect-continue": "^3.972.14", "@aws-sdk/middleware-flexible-checksums": "^3.974.23", "@aws-sdk/middleware-location-constraint": "^3.972.11", "@aws-sdk/middleware-sdk-s3": "^3.972.44", "@aws-sdk/middleware-ssec": "^3.972.11", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-AfED3hhaBZ121NuiBImgnlF98kQRMk6hGPMGfj/Oo1hSaoMFRzM+N4nlICCasUSM2R8QaIRZRYGpZ3fy0ilGZQ=="],
"@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="],
"@aws-sdk/crc64-nvme": ["@aws-sdk/crc64-nvme@3.972.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-P+QGozmXn2mZZI7sDgk+aUm+RTI61MPSFB+Ir2vjEjEbEsE4e7hYtzrDvAUxZy9ko81h53e11+F/GYlvwDkaOQ=="],
"@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-n1EbJ98yvPWWdHZZv8bRBMqqDQJrtgtxyJ4xLy2Uqrh25BCOZQ7nnS1CsFXvuH8r0b0KVHDZEGEH5FxmEMP8jg=="],
"@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.43", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-TT76RN1NkI9WoyZqCNxOw6/WBMF7pYOTJcXbMokNFU+euSG40Kaf/t/FhDACVZWP+43wEM6ZynIPIkzS1wR1iA=="],
@@ -330,26 +320,12 @@
"@aws-sdk/eventstream-handler-node": ["@aws-sdk/eventstream-handler-node@3.972.18", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-QPQhwY/fstR8fMZFWrsJRNoTP6D1RjRPHGRX7u9/VkF3opCsvD0oXPz6qzkX94SchzvuS5vyFZbJbPcMEs2Jeg=="],
"@aws-sdk/middleware-bucket-endpoint": ["@aws-sdk/middleware-bucket-endpoint@3.972.17", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-lbDmWuHenc+kiwCNrxz4MyN6nkxCWyTXPIWuspJN0ibziu+8CXci7vI1bK9MAkwy8cwJOEXNu0gBM5S0uTGRIg=="],
"@aws-sdk/middleware-eventstream": ["@aws-sdk/middleware-eventstream@3.972.14", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-DoZ4djVj/74XQ6M/IwxuKh543tTvLCL7u1Dx+VDHMgW9yGNrFSJJ1l0LrUQRaekic5CB12wUiiOoHL0VI6H0gg=="],
"@aws-sdk/middleware-expect-continue": ["@aws-sdk/middleware-expect-continue@3.972.14", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-3TNFEVGO4sWZj9TEXOCZLzGEctXHnaO4fk2EQ8KVaboTbwHmEPEQrm17Xb9koImUIXEw0sgi2xtHjg7LuTS3rA=="],
"@aws-sdk/middleware-flexible-checksums": ["@aws-sdk/middleware-flexible-checksums@3.974.23", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@aws-crypto/crc32c": "5.2.0", "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/crc64-nvme": "^3.972.9", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-4nPKARo2lfKvQGUt2fPA5NlS/mEohckdxpuC9ecbjVfj7B7NFFYHeTg+Bf5BEQwdn3yRfUIzFiEkPp8Yuaw3wA=="],
"@aws-sdk/middleware-location-constraint": ["@aws-sdk/middleware-location-constraint@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-hkfspNUP4criAH6ton6BGKgnm5dZx+7bUOy1YqlTfejDeUPAM23D81q/IX+hdlS3KUsfwGz5ADTqZWKBEUpf4A=="],
"@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.44", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-8HQsRg1NpX8vR4vNl1E8pyLnqZroq9VSL2vZQVSgBqp6wv6365LzYD08/c9FFh/9FTg7YRc7aTtEmXF0ir/pqg=="],
"@aws-sdk/middleware-ssec": ["@aws-sdk/middleware-ssec@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-7PQvGNhtveKlvVqNahqWx5yrwxP7ecwAoB1dYBf8eKwfo2tzzCbNnW+q2nO3N066ktQaB4iBQbDRWtizm+amoQ=="],
"@aws-sdk/middleware-websocket": ["@aws-sdk/middleware-websocket@3.972.23", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-F0d4A9pJFiwljyKgSwU1Z5n+CXSv8bp+V5SthbS2rftB8wBN9z1K2Yyv3xbeK0AM2T0g4q6Ptf0shFF+oQZyiA=="],
"@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="],
"@aws-sdk/s3-request-presigner": ["@aws-sdk/s3-request-presigner@3.1058.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-IRgNfn8U3zfsZ0JkpmwjS59R/XyHMHxpuwW6HVuJhik+FsbClhNkujEO0w1WqJvXrF4FX+7qIAwUrvlwNvaZ7Q=="],
"@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="],
"@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1048.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA=="],
@@ -1014,7 +990,7 @@
"@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="],
"@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA=="],
"@smithy/signature-v4": ["@smithy/signature-v4@5.4.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-Ojg4B6oIDlIr1R86xCDJt1zJWnYa0VINmqdjfe9qxWjdRivHalZ3iSlQgVqYbW0MdpFOC5XfHEWsnbmdnpIILQ=="],
@@ -2674,8 +2650,14 @@
"@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="],
"@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1056.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-81duvlltQlsfn5K+o8zILcystBRdbT1G2JJYVCML5NZHBz4CL/zf+sAemCtBh/uh6RQUMyInGeZLQ7/8igZhbA=="],
"@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="],
"@earendil-works/pi-agent-core/@earendil-works/pi-ai": ["@earendil-works/pi-ai@0.78.0", "", { "dependencies": { "@anthropic-ai/sdk": "0.91.1", "@aws-sdk/client-bedrock-runtime": "3.1048.0", "@google/genai": "1.52.0", "@mistralai/mistralai": "2.2.1", "@smithy/node-http-handler": "4.7.3", "http-proxy-agent": "7.0.2", "https-proxy-agent": "7.0.6", "openai": "6.26.0", "partial-json": "0.1.7", "typebox": "1.1.38" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-q0hUrvT6ngT6cgBX0oIbzfQfmzztgdkZobP8OTL+sCOOBlnG6+1YRt8g7zO9CC/4NdeYEqa7uGqWdQhH0fjCLA=="],
"@earendil-works/pi-agent-core/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
@@ -3084,8 +3066,6 @@
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"@earendil-works/pi-agent-core/@earendil-works/pi-ai/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
+41 -2
View File
@@ -1,5 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { s3Service } from '@shumai/core/src/s3/s3'
import { Hono } from 'hono'
const { mockServeStatic } = vi.hoisted(() => ({
@@ -14,6 +13,7 @@ vi.mock('hono/bun', () => ({
describe('S3 API', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.resetModules()
})
it('GET /files/* calls serveStatic with correct options', async () => {
@@ -39,10 +39,49 @@ 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
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let onFoundCallback: ((path: string, c: any) => void) | undefined
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockServeStatic.mockImplementationOnce((options: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onFoundCallback = (options as any).onFound
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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', {
+7
View File
@@ -8,6 +8,13 @@ const route = new Hono()
serveStatic({
root: './data',
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
onFound: (_path, c) => {
const filename = c.req.query('filename')
if (filename) {
const safeFilename = filename.replace(/["\r\n]/g, '_')
c.header('Content-Disposition', `attachment; filename="${safeFilename}"`)
}
},
}),
)
.put('/:bucket/:key{.+}', async (c) => {
-2
View File
@@ -8,8 +8,6 @@
"dependencies": {
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@aws-sdk/client-s3": "^3.1031.0",
"@aws-sdk/s3-request-presigner": "^3.1031.0",
"@sinclair/typebox": "^0.34.49",
"adm-zip": "^0.5.17",
"better-auth": "1.6.11",
+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 -130
View File
@@ -1,17 +1,7 @@
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'
import * as path from 'path'
import { ulid } from 'ulid'
import { LruTtlCache } from '../cache/lru-ttl-cache'
@@ -64,7 +54,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 +79,36 @@ 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
return await this.client.size(key, { bucket })
}
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 +118,22 @@ 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 })
await Bun.write(filePath, file)
}
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 +147,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 +170,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 +197,39 @@ 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, Bun.file(filePath), {
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}`)
// 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,
}
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 +435,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
}
}
+20 -20
View File
@@ -1,26 +1,26 @@
import { prisma } from '@shumai/db'
import { ulid } from 'ulid'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { s3Service } from '@shumai/core/src/s3/s3'
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 {
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
TaskInfo,
} from '@shumai/dtos'
import {
AssetStatus,
AssetType,
Prisma,
TaskStatus,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
AssetType,
Prisma,
TaskStatus,
WorkflowTaskStatus,
WorkflowTaskType,
prisma,
} from '@shumai/db'
import { PaginationParams, paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
import { VideoTranscoder, ImageTranscoder } from '@shumai/transcode'
import {
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
TaskInfo,
} from '@shumai/dtos'
import { ImageTranscoder, VideoTranscoder } from '@shumai/transcode'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}