-
Notifications
You must be signed in to change notification settings - Fork 3.3k
improvement(uploads): add multipart upload + batching + retries #938
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8ce58f5
File upload retries + multipart uploads
Sg312 e714cb7
Lint
Sg312 9d7758b
FIle uploads
Sg312 73bdfa6
File uploads 2
Sg312 eb692cd
Lint
Sg312 c444a5d
Fix file uploads
Sg312 32aea2b
Add auth to file upload routes
Sg312 503b148
Lint
Sg312 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| import { | ||
| AbortMultipartUploadCommand, | ||
| CompleteMultipartUploadCommand, | ||
| CreateMultipartUploadCommand, | ||
| UploadPartCommand, | ||
| } from '@aws-sdk/client-s3' | ||
| import { getSignedUrl } from '@aws-sdk/s3-request-presigner' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { v4 as uuidv4 } from 'uuid' | ||
| import { getSession } from '@/lib/auth' | ||
| import { createLogger } from '@/lib/logs/console/logger' | ||
| import { getStorageProvider, isUsingCloudStorage } from '@/lib/uploads' | ||
| import { S3_KB_CONFIG } from '@/lib/uploads/setup' | ||
|
|
||
| const logger = createLogger('MultipartUploadAPI') | ||
|
|
||
| interface InitiateMultipartRequest { | ||
| fileName: string | ||
| contentType: string | ||
| fileSize: number | ||
| } | ||
|
|
||
| interface GetPartUrlsRequest { | ||
| uploadId: string | ||
| key: string | ||
| partNumbers: number[] | ||
| } | ||
|
|
||
| interface CompleteMultipartRequest { | ||
| uploadId: string | ||
| key: string | ||
| parts: Array<{ | ||
| ETag: string | ||
| PartNumber: number | ||
| }> | ||
| } | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const session = await getSession() | ||
| if (!session?.user?.id) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const action = request.nextUrl.searchParams.get('action') | ||
|
|
||
| if (!isUsingCloudStorage() || getStorageProvider() !== 's3') { | ||
| return NextResponse.json( | ||
| { error: 'Multipart upload is only available with S3 storage' }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| const { getS3Client } = await import('@/lib/uploads/s3/s3-client') | ||
| const s3Client = getS3Client() | ||
|
|
||
| switch (action) { | ||
| case 'initiate': { | ||
| const data: InitiateMultipartRequest = await request.json() | ||
| const { fileName, contentType } = data | ||
|
|
||
| const safeFileName = fileName.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9.-]/g, '_') | ||
| const uniqueKey = `kb/${uuidv4()}-${safeFileName}` | ||
|
|
||
| const command = new CreateMultipartUploadCommand({ | ||
| Bucket: S3_KB_CONFIG.bucket, | ||
| Key: uniqueKey, | ||
| ContentType: contentType, | ||
| Metadata: { | ||
| originalName: fileName, | ||
| uploadedAt: new Date().toISOString(), | ||
| purpose: 'knowledge-base', | ||
| }, | ||
| }) | ||
|
|
||
| const response = await s3Client.send(command) | ||
|
|
||
| logger.info(`Initiated multipart upload for ${fileName}: ${response.UploadId}`) | ||
|
|
||
| return NextResponse.json({ | ||
| uploadId: response.UploadId, | ||
| key: uniqueKey, | ||
| }) | ||
| } | ||
|
|
||
| case 'get-part-urls': { | ||
| const data: GetPartUrlsRequest = await request.json() | ||
| const { uploadId, key, partNumbers } = data | ||
|
|
||
| const presignedUrls = await Promise.all( | ||
| partNumbers.map(async (partNumber) => { | ||
| const command = new UploadPartCommand({ | ||
| Bucket: S3_KB_CONFIG.bucket, | ||
| Key: key, | ||
| PartNumber: partNumber, | ||
| UploadId: uploadId, | ||
| }) | ||
|
|
||
| const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 }) | ||
| return { partNumber, url } | ||
| }) | ||
| ) | ||
|
|
||
| return NextResponse.json({ presignedUrls }) | ||
| } | ||
|
|
||
| case 'complete': { | ||
| const data: CompleteMultipartRequest = await request.json() | ||
| const { uploadId, key, parts } = data | ||
|
|
||
| const command = new CompleteMultipartUploadCommand({ | ||
| Bucket: S3_KB_CONFIG.bucket, | ||
| Key: key, | ||
| UploadId: uploadId, | ||
| MultipartUpload: { | ||
| Parts: parts.sort((a, b) => a.PartNumber - b.PartNumber), | ||
| }, | ||
| }) | ||
|
|
||
| const response = await s3Client.send(command) | ||
|
|
||
| logger.info(`Completed multipart upload for key ${key}`) | ||
|
|
||
| const finalPath = `/api/files/serve/s3/${encodeURIComponent(key)}` | ||
|
|
||
| return NextResponse.json({ | ||
| success: true, | ||
| location: response.Location, | ||
| path: finalPath, | ||
| key, | ||
| }) | ||
| } | ||
|
|
||
| case 'abort': { | ||
| const data = await request.json() | ||
| const { uploadId, key } = data | ||
|
|
||
| const command = new AbortMultipartUploadCommand({ | ||
| Bucket: S3_KB_CONFIG.bucket, | ||
| Key: key, | ||
| UploadId: uploadId, | ||
| }) | ||
|
|
||
| await s3Client.send(command) | ||
|
|
||
| logger.info(`Aborted multipart upload for key ${key}`) | ||
|
|
||
| return NextResponse.json({ success: true }) | ||
| } | ||
|
|
||
| default: | ||
| return NextResponse.json( | ||
| { error: 'Invalid action. Use: initiate, get-part-urls, complete, or abort' }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| } catch (error) { | ||
| logger.error('Multipart upload error:', error) | ||
| return NextResponse.json( | ||
| { error: error instanceof Error ? error.message : 'Multipart upload failed' }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.