-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(files): stream large CSV previews and add import-as-table #5125
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
4 commits
Select commit
Hold shift + click to select a range
0321342
feat(files): stream large CSV previews and add import-as-table
TheodoreSpeaks 81ca970
fix(files): validate fileId in csv-preview route, guard double-import…
TheodoreSpeaks 56f941c
Merge remote-tracking branch 'origin/staging' into fix/large-table-fi…
TheodoreSpeaks d9de35d
fix(files): scope mothership preview-toggle loading guard to CSV file…
TheodoreSpeaks 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
56 changes: 56 additions & 0 deletions
56
apps/sim/app/api/workspaces/[id]/files/[fileId]/csv-preview/route.ts
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,56 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { getWorkspaceCsvPreviewContract } from '@/lib/api/contracts/workspace-file-table' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { getCsvPreviewSlice } from '@/lib/file-parsers/csv-preview-slice' | ||
| import { getWorkspaceFile } from '@/lib/uploads/contexts/workspace/workspace-file-manager' | ||
| import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' | ||
|
|
||
| const logger = createLogger('WorkspaceCsvPreviewAPI') | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export const GET = withRouteHandler( | ||
| async (request: NextRequest, context: { params: Promise<{ id: string; fileId: string }> }) => { | ||
| const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) | ||
| if (!authResult.success || !authResult.userId) { | ||
| return NextResponse.json({ error: 'Authentication required' }, { status: 401 }) | ||
| } | ||
| const userId = authResult.userId | ||
|
|
||
| const parsed = await parseRequest(getWorkspaceCsvPreviewContract, request, context) | ||
| if (!parsed.success) return parsed.response | ||
| const { id: workspaceId, fileId } = parsed.data.params | ||
| const { key } = parsed.data.query | ||
|
|
||
| const permission = await getUserEntityPermissions(userId, 'workspace', workspaceId) | ||
| if (!permission) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }) | ||
| } | ||
|
|
||
| // Resolve the file record (active, in this workspace) and read from its authoritative key — | ||
| // never the client-supplied one. This rejects archived/deleted files and keys with no live | ||
| // row, matching the access guarantees of /api/files/serve. | ||
| const record = await getWorkspaceFile(workspaceId, fileId) | ||
| if (!record || record.key !== key) { | ||
| return NextResponse.json({ error: 'File not found' }, { status: 404 }) | ||
| } | ||
|
|
||
| const slice = await getCsvPreviewSlice({ | ||
| key: record.key, | ||
| context: 'workspace', | ||
| signal: request.signal, | ||
| }) | ||
|
|
||
| logger.info('CSV preview served', { | ||
| workspaceId, | ||
| rows: slice.rows.length, | ||
| truncated: slice.truncated, | ||
| }) | ||
|
|
||
| return NextResponse.json({ success: true, ...slice }) | ||
| } | ||
| ) |
68 changes: 68 additions & 0 deletions
68
apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/csv-import.ts
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,68 @@ | ||
| 'use client' | ||
|
|
||
| import { useCallback, useEffect, useRef } from 'react' | ||
| import { generateId } from '@sim/utils/id' | ||
| import { useRouter } from 'next/navigation' | ||
| import { toast } from '@/components/emcn' | ||
| import { CSV_PREVIEW_MAX_ROWS } from '@/lib/api/contracts/workspace-file-table' | ||
| import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace' | ||
| import { useImportFileAsTable } from '@/hooks/queries/tables' | ||
| import { useImportTrayStore } from '@/stores/table/import-tray/store' | ||
|
|
||
| export type CsvImportFileDescriptor = Pick<WorkspaceFileRecord, 'key' | 'name'> | ||
|
|
||
| /** | ||
| * Wires the "Import as a table" affordance for a capped CSV preview. When the preview is | ||
| * `truncated`, raises a one-time warning toast whose action kicks off a background import of the | ||
| * existing workspace file — no re-upload, source preserved — and navigates to the new table. | ||
| */ | ||
| export function useCsvTruncationImport( | ||
| workspaceId: string, | ||
| file: CsvImportFileDescriptor, | ||
| truncated: boolean | ||
| ) { | ||
| const router = useRouter() | ||
| const importFile = useImportFileAsTable() | ||
|
|
||
| // Guards against a double-tap on the toast action kicking off two parallel imports of the same | ||
| // file. Reset once the kickoff settles so a failed import can be retried. | ||
| const importingRef = useRef(false) | ||
|
|
||
| const importAsTable = useCallback(() => { | ||
| if (importingRef.current) return | ||
| importingRef.current = true | ||
| const pendingId = `pending_${generateId()}` | ||
| useImportTrayStore | ||
| .getState() | ||
| .startUpload({ uploadId: pendingId, workspaceId, title: file.name }) | ||
| toast.success(`Importing "${file.name}" as a table`, { | ||
| description: 'This runs in the background.', | ||
| action: { | ||
| label: 'View tables', | ||
| onClick: () => router.push(`/workspace/${workspaceId}/tables`), | ||
| }, | ||
| }) | ||
| importFile.mutate( | ||
| { workspaceId, fileKey: file.key, fileName: file.name }, | ||
| { | ||
| onSettled: () => { | ||
| importingRef.current = false | ||
| useImportTrayStore.getState().endUpload(pendingId) | ||
| }, | ||
| } | ||
| ) | ||
| // importFile.mutate and router are stable references | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [workspaceId, file.key, file.name]) | ||
|
|
||
| // Surface the cap as a warning toast with an import action, once per file. | ||
| const notifiedKeyRef = useRef<string | null>(null) | ||
| useEffect(() => { | ||
| if (!truncated || notifiedKeyRef.current === file.key) return | ||
| notifiedKeyRef.current = file.key | ||
| toast.warning(`Showing the first ${CSV_PREVIEW_MAX_ROWS.toLocaleString()} rows`, { | ||
| description: 'Import this file as a table to view all of its rows.', | ||
| action: { label: 'Import as a table', onClick: importAsTable }, | ||
| }) | ||
| }, [truncated, file.key, importAsTable]) | ||
| } | ||
49 changes: 49 additions & 0 deletions
49
apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/csv-table-preview.tsx
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,49 @@ | ||
| 'use client' | ||
|
|
||
| import { memo } from 'react' | ||
| import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace' | ||
| import { useWorkspaceCsvPreview } from '@/hooks/queries/workspace-file-table' | ||
| import { useCsvTruncationImport } from './csv-import' | ||
| import { DataTable } from './data-table' | ||
| import { PreviewError, PreviewLoadingFrame, resolvePreviewError } from './preview-shared' | ||
|
|
||
| /** | ||
| * Read-only preview for a CSV that is too large to load fully into the editor. Streams only the | ||
| * first {@link CSV_PREVIEW_MAX_ROWS} rows from storage; when there are more, a warning toast offers | ||
| * "Import as a table", which builds a full Table from the file (memory-safe streaming import). | ||
| */ | ||
| export const CsvTablePreview = memo(function CsvTablePreview({ | ||
| file, | ||
| workspaceId, | ||
| }: { | ||
| file: WorkspaceFileRecord | ||
| workspaceId: string | ||
| }) { | ||
| const version = Number(new Date(file.updatedAt)) || file.size | ||
| const { | ||
| data, | ||
| isLoading, | ||
| error: fetchError, | ||
| } = useWorkspaceCsvPreview(workspaceId, file.id, file.key, version) | ||
| useCsvTruncationImport(workspaceId, file, data?.truncated ?? false) | ||
|
|
||
| const error = resolvePreviewError((fetchError as Error | null) ?? null, null) | ||
| if (error) return <PreviewError label='CSV' error={error} /> | ||
| if (isLoading || !data) { | ||
| return <PreviewLoadingFrame className='flex flex-1 flex-col overflow-hidden' /> | ||
| } | ||
|
|
||
| if (data.headers.length === 0) { | ||
| return ( | ||
| <div className='flex h-full items-center justify-center p-6'> | ||
| <p className='text-[13px] text-[var(--text-muted)]'>No data to display</p> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <div className='flex flex-1 flex-col overflow-auto p-6'> | ||
| <DataTable headers={data.headers} rows={data.rows} /> | ||
| </div> | ||
| ) | ||
| }) |
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
2 changes: 1 addition & 1 deletion
2
apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/index.ts
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 |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| export { resolveFileCategory } from './file-category' | ||
| export type { PreviewMode } from './file-viewer' | ||
| export { FileViewer, isPreviewable, isTextEditable } from './file-viewer' | ||
| export { FileViewer, isCsvStreamOnly, isPreviewable, isTextEditable } from './file-viewer' | ||
| export { RICH_PREVIEWABLE_EXTENSIONS } from './preview-panel' |
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.
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.