-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathworkspace-file-manager.ts
More file actions
652 lines (577 loc) · 18.5 KB
/
workspace-file-manager.ts
File metadata and controls
652 lines (577 loc) · 18.5 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/**
* Workspace file storage system
* Files uploaded at workspace level persist indefinitely and are accessible across all workflows
*/
import { db } from '@sim/db'
import { workspaceFiles } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, isNull, sql } from 'drizzle-orm'
import {
checkStorageQuota,
decrementStorageUsage,
incrementStorageUsage,
} from '@/lib/billing/storage'
import {
downloadFile,
hasCloudStorage,
uploadFile,
} from '@/lib/uploads/core/storage-service'
import { getFileMetadataByKey, insertFileMetadata } from '@/lib/uploads/server/metadata'
import { isUuid, sanitizeFileName } from '@/executor/constants'
import type { UserFile } from '@/executor/types'
const logger = createLogger('WorkspaceFileStorage')
export type WorkspaceFileScope = 'active' | 'archived' | 'all'
export class FileConflictError extends Error {
readonly code = 'FILE_EXISTS' as const
constructor(name: string) {
super(`A file named "${name}" already exists in this workspace`)
}
}
export interface WorkspaceFileRecord {
id: string
workspaceId: string
name: string
key: string
path: string // Full serve path including storage type
url?: string // Presigned URL for external access (optional, regenerated as needed)
size: number
type: string
uploadedBy: string
deletedAt?: Date | null
uploadedAt: Date
}
/**
* Workspace file key pattern: workspace/{workspaceId}/{timestamp}-{random}-{filename}
*/
const WORKSPACE_KEY_PATTERN = /^workspace\/([a-f0-9-]{36})\/(\d+)-([a-z0-9]+)-(.+)$/
/**
* Check if a key matches workspace file pattern
* Format: workspace/{workspaceId}/{timestamp}-{random}-{filename}
*/
export function matchesWorkspaceFilePattern(key: string): boolean {
if (!key || key.startsWith('/api/') || key.startsWith('http')) {
return false
}
return WORKSPACE_KEY_PATTERN.test(key)
}
/**
* Parse workspace file key to extract workspace ID
* Format: workspace/{workspaceId}/{timestamp}-{random}-{filename}
* @returns workspaceId if key matches pattern, null otherwise
*/
export function parseWorkspaceFileKey(key: string): string | null {
if (!matchesWorkspaceFilePattern(key)) {
return null
}
const match = key.match(WORKSPACE_KEY_PATTERN)
if (!match) {
return null
}
const workspaceId = match[1]
return isUuid(workspaceId) ? workspaceId : null
}
/**
* Generate workspace-scoped storage key with explicit prefix
* Format: workspace/{workspaceId}/{timestamp}-{random}-{filename}
*/
export function generateWorkspaceFileKey(workspaceId: string, fileName: string): string {
const timestamp = Date.now()
const random = Math.random().toString(36).substring(2, 9)
const safeFileName = sanitizeFileName(fileName)
return `workspace/${workspaceId}/${timestamp}-${random}-${safeFileName}`
}
/**
* Upload a file to workspace-scoped storage
*/
export async function uploadWorkspaceFile(
workspaceId: string,
userId: string,
fileBuffer: Buffer,
fileName: string,
contentType: string
): Promise<UserFile> {
logger.info(`Uploading workspace file: ${fileName} for workspace ${workspaceId}`)
const exists = await fileExistsInWorkspace(workspaceId, fileName)
if (exists) {
throw new Error(`A file named "${fileName}" already exists in this workspace`)
}
const quotaCheck = await checkStorageQuota(userId, fileBuffer.length)
if (!quotaCheck.allowed) {
throw new Error(quotaCheck.error || 'Storage limit exceeded')
}
const storageKey = generateWorkspaceFileKey(workspaceId, fileName)
let fileId = `wf_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
try {
logger.info(`Generated storage key: ${storageKey}`)
const metadata: Record<string, string> = {
originalName: fileName,
uploadedAt: new Date().toISOString(),
purpose: 'workspace',
userId: userId,
workspaceId: workspaceId,
}
const uploadResult = await uploadFile({
file: fileBuffer,
fileName: storageKey, // Use the full storageKey as fileName
contentType,
context: 'workspace',
preserveKey: true, // Don't add timestamp prefix
customKey: storageKey, // Explicitly set the key
metadata, // Pass metadata for cloud storage consistency
})
logger.info(`Upload returned key: ${uploadResult.key}`)
const usingCloudStorage = hasCloudStorage()
if (!usingCloudStorage) {
const metadataRecord = await insertFileMetadata({
id: fileId,
key: uploadResult.key,
userId,
workspaceId,
context: 'workspace',
originalName: fileName,
contentType,
size: fileBuffer.length,
})
fileId = metadataRecord.id
logger.info(`Stored metadata in database for local file: ${uploadResult.key}`)
} else {
const existing = await getFileMetadataByKey(uploadResult.key, 'workspace')
if (!existing) {
logger.warn(`Metadata not found for cloud file ${uploadResult.key}, inserting...`)
const metadataRecord = await insertFileMetadata({
id: fileId,
key: uploadResult.key,
userId,
workspaceId,
context: 'workspace',
originalName: fileName,
contentType,
size: fileBuffer.length,
})
fileId = metadataRecord.id
} else {
fileId = existing.id
logger.info(`Using existing metadata record for cloud file: ${uploadResult.key}`)
}
}
logger.info(`Successfully uploaded workspace file: ${fileName} with key: ${uploadResult.key}`)
try {
await incrementStorageUsage(userId, fileBuffer.length)
} catch (storageError) {
logger.error(`Failed to update storage tracking:`, storageError)
}
const { getServePathPrefix } = await import('@/lib/uploads')
const pathPrefix = getServePathPrefix()
const serveUrl = `${pathPrefix}${encodeURIComponent(uploadResult.key)}?context=workspace`
return {
id: fileId,
name: fileName,
size: fileBuffer.length,
type: contentType,
url: serveUrl, // Use authenticated serve URL (enforces context)
key: uploadResult.key,
context: 'workspace',
}
} catch (error) {
logger.error(`Failed to upload workspace file ${fileName}:`, error)
throw new Error(
`Failed to upload file: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Track a file that was already uploaded to workspace S3 as a chat-scoped upload.
* Links the existing workspaceFiles metadata record (created by the storage service
* during upload) to the chat by setting chatId and context='mothership'.
* Falls back to inserting a new record if none exists for the key.
*/
export async function trackChatUpload(
workspaceId: string,
userId: string,
chatId: string,
s3Key: string,
fileName: string,
contentType: string,
size: number
): Promise<void> {
const updated = await db
.update(workspaceFiles)
.set({ chatId, context: 'mothership' })
.where(and(eq(workspaceFiles.key, s3Key), eq(workspaceFiles.workspaceId, workspaceId), isNull(workspaceFiles.deletedAt)))
.returning({ id: workspaceFiles.id })
if (updated.length > 0) {
logger.info(`Linked existing file record to chat: ${fileName} for chat ${chatId}`)
return
}
const fileId = `wf_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
await db.insert(workspaceFiles).values({
id: fileId,
key: s3Key,
userId,
workspaceId,
context: 'mothership',
chatId,
originalName: fileName,
contentType,
size,
})
logger.info(`Tracked chat upload: ${fileName} for chat ${chatId}`)
}
/**
* Check if a file with the same name already exists in workspace
*/
export async function fileExistsInWorkspace(
workspaceId: string,
fileName: string
): Promise<boolean> {
try {
const existing = await db
.select()
.from(workspaceFiles)
.where(
and(
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.originalName, fileName),
eq(workspaceFiles.context, 'workspace'),
isNull(workspaceFiles.deletedAt)
)
)
.limit(1)
return existing.length > 0
} catch (error) {
logger.error(`Failed to check file existence for ${fileName}:`, error)
return false
}
}
/**
* Look up a single active workspace file by its original name.
* Returns the record if found, or null otherwise.
*/
export async function getWorkspaceFileByName(
workspaceId: string,
fileName: string
): Promise<WorkspaceFileRecord | null> {
try {
const files = await db
.select()
.from(workspaceFiles)
.where(
and(
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.originalName, fileName),
eq(workspaceFiles.context, 'workspace'),
isNull(workspaceFiles.deletedAt)
)
)
.limit(1)
if (files.length === 0) return null
const { getServePathPrefix } = await import('@/lib/uploads')
const pathPrefix = getServePathPrefix()
const file = files[0]
return {
id: file.id,
workspaceId: file.workspaceId || workspaceId,
name: file.originalName,
key: file.key,
path: `${pathPrefix}${encodeURIComponent(file.key)}?context=workspace`,
size: file.size,
type: file.contentType,
uploadedBy: file.userId,
deletedAt: file.deletedAt,
uploadedAt: file.uploadedAt,
}
} catch (error) {
logger.error(`Failed to get workspace file by name "${fileName}":`, error)
return null
}
}
/**
* List all files for a workspace
*/
export async function listWorkspaceFiles(
workspaceId: string,
options?: { scope?: WorkspaceFileScope }
): Promise<WorkspaceFileRecord[]> {
try {
const { scope = 'active' } = options ?? {}
const files = await db
.select()
.from(workspaceFiles)
.where(
scope === 'all'
? and(eq(workspaceFiles.workspaceId, workspaceId), eq(workspaceFiles.context, 'workspace'))
: scope === 'archived'
? and(
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace'),
sql`${workspaceFiles.deletedAt} IS NOT NULL`
)
: and(
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace'),
isNull(workspaceFiles.deletedAt)
)
)
.orderBy(workspaceFiles.uploadedAt)
const { getServePathPrefix } = await import('@/lib/uploads')
const pathPrefix = getServePathPrefix()
return files.map((file) => ({
id: file.id,
workspaceId: file.workspaceId || workspaceId, // Use query workspaceId as fallback (should never be null for workspace files)
name: file.originalName,
key: file.key,
path: `${pathPrefix}${encodeURIComponent(file.key)}?context=workspace`,
size: file.size,
type: file.contentType,
uploadedBy: file.userId,
deletedAt: file.deletedAt,
uploadedAt: file.uploadedAt,
}))
} catch (error) {
logger.error(`Failed to list workspace files for ${workspaceId}:`, error)
return []
}
}
/**
* Get a specific workspace file
*/
export async function getWorkspaceFile(
workspaceId: string,
fileId: string,
options?: { includeDeleted?: boolean }
): Promise<WorkspaceFileRecord | null> {
try {
const { includeDeleted = false } = options ?? {}
const files = await db
.select()
.from(workspaceFiles)
.where(
includeDeleted
? and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace')
)
: and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace'),
isNull(workspaceFiles.deletedAt)
)
)
.limit(1)
if (files.length === 0) return null
const { getServePathPrefix } = await import('@/lib/uploads')
const pathPrefix = getServePathPrefix()
const file = files[0]
return {
id: file.id,
workspaceId: file.workspaceId || workspaceId, // Use query workspaceId as fallback (should never be null for workspace files)
name: file.originalName,
key: file.key,
path: `${pathPrefix}${encodeURIComponent(file.key)}?context=workspace`,
size: file.size,
type: file.contentType,
uploadedBy: file.userId,
deletedAt: file.deletedAt,
uploadedAt: file.uploadedAt,
}
} catch (error) {
logger.error(`Failed to get workspace file ${fileId}:`, error)
return null
}
}
/**
* Download workspace file content
*/
export async function downloadWorkspaceFile(fileRecord: WorkspaceFileRecord): Promise<Buffer> {
logger.info(`Downloading workspace file: ${fileRecord.name}`)
try {
const buffer = await downloadFile({
key: fileRecord.key,
context: 'workspace',
})
logger.info(
`Successfully downloaded workspace file: ${fileRecord.name} (${buffer.length} bytes)`
)
return buffer
} catch (error) {
logger.error(`Failed to download workspace file ${fileRecord.name}:`, error)
throw new Error(
`Failed to download file: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Update a workspace file's content (re-uploads to same storage key)
*/
export async function updateWorkspaceFileContent(
workspaceId: string,
fileId: string,
userId: string,
content: Buffer
): Promise<WorkspaceFileRecord> {
logger.info(`Updating workspace file content: ${fileId} for workspace ${workspaceId}`)
const fileRecord = await getWorkspaceFile(workspaceId, fileId)
if (!fileRecord) {
throw new Error('File not found')
}
const sizeDiff = content.length - fileRecord.size
if (sizeDiff > 0) {
const quotaCheck = await checkStorageQuota(userId, sizeDiff)
if (!quotaCheck.allowed) {
throw new Error(quotaCheck.error || 'Storage limit exceeded')
}
}
try {
const metadata: Record<string, string> = {
originalName: fileRecord.name,
uploadedAt: new Date().toISOString(),
purpose: 'workspace',
userId,
workspaceId,
}
await uploadFile({
file: content,
fileName: fileRecord.key,
contentType: fileRecord.type,
context: 'workspace',
preserveKey: true,
customKey: fileRecord.key,
metadata,
})
await db
.update(workspaceFiles)
.set({ size: content.length })
.where(
and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace')
)
)
if (sizeDiff !== 0) {
try {
if (sizeDiff > 0) {
await incrementStorageUsage(userId, sizeDiff)
} else {
await decrementStorageUsage(userId, Math.abs(sizeDiff))
}
} catch (storageError) {
logger.error(`Failed to update storage tracking:`, storageError)
}
}
logger.info(`Successfully updated workspace file content: ${fileRecord.name}`)
return {
...fileRecord,
size: content.length,
}
} catch (error) {
logger.error(`Failed to update workspace file content ${fileId}:`, error)
throw new Error(
`Failed to update file content: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Rename a workspace file (updates the display name in the database)
*/
export async function renameWorkspaceFile(
workspaceId: string,
fileId: string,
newName: string
): Promise<WorkspaceFileRecord> {
logger.info(`Renaming workspace file: ${fileId} to "${newName}" in workspace ${workspaceId}`)
const trimmedName = newName.trim()
if (!trimmedName) {
throw new Error('File name cannot be empty')
}
const fileRecord = await getWorkspaceFile(workspaceId, fileId)
if (!fileRecord) {
throw new Error('File not found')
}
if (fileRecord.name === trimmedName) {
return fileRecord
}
const exists = await fileExistsInWorkspace(workspaceId, trimmedName)
if (exists) {
throw new FileConflictError(trimmedName)
}
const updated = await db
.update(workspaceFiles)
.set({ originalName: trimmedName })
.where(
and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace')
)
)
.returning({ id: workspaceFiles.id })
if (updated.length === 0) {
throw new Error('File not found or could not be renamed')
}
logger.info(`Successfully renamed workspace file ${fileId} to "${trimmedName}"`)
return {
...fileRecord,
name: trimmedName,
}
}
/**
* Soft delete a workspace file.
*/
export async function deleteWorkspaceFile(workspaceId: string, fileId: string): Promise<void> {
logger.info(`Deleting workspace file: ${fileId}`)
try {
const fileRecord = await getWorkspaceFile(workspaceId, fileId)
if (!fileRecord) {
throw new Error('File not found')
}
await db
.update(workspaceFiles)
.set({ deletedAt: new Date() })
.where(
and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace'),
isNull(workspaceFiles.deletedAt)
)
)
logger.info(`Successfully archived workspace file: ${fileRecord.name}`)
} catch (error) {
logger.error(`Failed to delete workspace file ${fileId}:`, error)
throw new Error(
`Failed to delete file: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Restore a soft-deleted workspace file.
*/
export async function restoreWorkspaceFile(workspaceId: string, fileId: string): Promise<void> {
logger.info(`Restoring workspace file: ${fileId}`)
const fileRecord = await getWorkspaceFile(workspaceId, fileId, { includeDeleted: true })
if (!fileRecord) {
throw new Error('File not found')
}
if (!fileRecord.deletedAt) {
throw new Error('File is not archived')
}
const { getWorkspaceWithOwner } = await import('@/lib/workspaces/permissions/utils')
const ws = await getWorkspaceWithOwner(workspaceId)
if (!ws || ws.archivedAt) {
throw new Error('Cannot restore file into an archived workspace')
}
await db
.update(workspaceFiles)
.set({ deletedAt: null })
.where(
and(
eq(workspaceFiles.id, fileId),
eq(workspaceFiles.workspaceId, workspaceId),
eq(workspaceFiles.context, 'workspace')
)
)
logger.info(`Successfully restored workspace file: ${fileRecord.name}`)
}