-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathroute.ts
More file actions
193 lines (164 loc) · 5.68 KB
/
route.ts
File metadata and controls
193 lines (164 loc) · 5.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { type NextRequest, NextResponse } from 'next/server'
import { createLogger } from '@/lib/logs/console/logger'
import { getPresignedUrl, isUsingCloudStorage, uploadFile } from '@/lib/uploads'
import '@/lib/uploads/setup.server'
import { getSession } from '@/lib/auth'
import {
createErrorResponse,
createOptionsResponse,
InvalidRequestError,
} from '@/app/api/files/utils'
const ALLOWED_EXTENSIONS = new Set([
'pdf',
'doc',
'docx',
'txt',
'md',
'png',
'jpg',
'jpeg',
'gif',
'csv',
'xlsx',
'xls',
'json',
'yaml',
'yml',
])
/**
* Validates file extension against allowlist
*/
function validateFileExtension(filename: string): boolean {
const extension = filename.split('.').pop()?.toLowerCase()
if (!extension) return false
return ALLOWED_EXTENSIONS.has(extension)
}
export const dynamic = 'force-dynamic'
const logger = createLogger('FilesUploadAPI')
export async function POST(request: NextRequest) {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const formData = await request.formData()
const files = formData.getAll('file') as File[]
if (!files || files.length === 0) {
throw new InvalidRequestError('No files provided')
}
const workflowId = formData.get('workflowId') as string | null
const executionId = formData.get('executionId') as string | null
const workspaceId = formData.get('workspaceId') as string | null
const usingCloudStorage = isUsingCloudStorage()
logger.info(`Using storage mode: ${usingCloudStorage ? 'Cloud' : 'Local'} for file upload`)
if (workflowId && executionId) {
logger.info(
`Uploading files for execution-scoped storage: workflow=${workflowId}, execution=${executionId}`
)
} else if (workspaceId) {
logger.info(`Uploading files for workspace-scoped storage: workspace=${workspaceId}`)
}
const uploadResults = []
for (const file of files) {
const originalName = file.name
if (!validateFileExtension(originalName)) {
const extension = originalName.split('.').pop()?.toLowerCase() || 'unknown'
throw new InvalidRequestError(
`File type '${extension}' is not allowed. Allowed types: ${Array.from(ALLOWED_EXTENSIONS).join(', ')}`
)
}
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
// Priority 1: Execution-scoped storage (temporary, 5 min expiry)
if (workflowId && executionId) {
const { uploadExecutionFile } = await import('@/lib/workflows/execution-file-storage')
const userFile = await uploadExecutionFile(
{
workspaceId: workspaceId || '',
workflowId,
executionId,
},
buffer,
originalName,
file.type
)
uploadResults.push(userFile)
continue
}
// Priority 2: Workspace-scoped storage (persistent, no expiry)
if (workspaceId) {
try {
const { uploadWorkspaceFile } = await import('@/lib/uploads/workspace-files')
const userFile = await uploadWorkspaceFile(
workspaceId,
session.user.id,
buffer,
originalName,
file.type || 'application/octet-stream'
)
uploadResults.push(userFile)
continue
} catch (workspaceError) {
// Check error type
const errorMessage =
workspaceError instanceof Error ? workspaceError.message : 'Upload failed'
const isDuplicate = errorMessage.includes('already exists')
const isStorageLimitError =
errorMessage.includes('Storage limit exceeded') ||
errorMessage.includes('storage limit')
logger.warn(`Workspace file upload failed: ${errorMessage}`)
// Determine appropriate status code
let statusCode = 500
if (isDuplicate) statusCode = 409
else if (isStorageLimitError) statusCode = 413
return NextResponse.json(
{
success: false,
error: errorMessage,
isDuplicate,
},
{ status: statusCode }
)
}
}
try {
logger.info(`Uploading file: ${originalName}`)
const result = await uploadFile(buffer, originalName, file.type, file.size)
let presignedUrl: string | undefined
if (usingCloudStorage) {
try {
presignedUrl = await getPresignedUrl(result.key, 24 * 60 * 60) // 24 hours
} catch (error) {
logger.warn(`Failed to generate presigned URL for ${originalName}:`, error)
}
}
const servePath = result.path
const uploadResult = {
name: originalName,
size: file.size,
type: file.type,
key: result.key,
path: servePath,
url: presignedUrl || servePath,
uploadedAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24 hours
}
logger.info(`Successfully uploaded: ${result.key}`)
uploadResults.push(uploadResult)
} catch (error) {
logger.error(`Error uploading ${originalName}:`, error)
throw error
}
}
if (uploadResults.length === 1) {
return NextResponse.json(uploadResults[0])
}
return NextResponse.json({ files: uploadResults })
} catch (error) {
logger.error('Error in file upload:', error)
return createErrorResponse(error instanceof Error ? error : new Error('File upload failed'))
}
}
export async function OPTIONS() {
return createOptionsResponse()
}