-
Notifications
You must be signed in to change notification settings - Fork 3.6k
feat(tables): background import for large CSVs with live progress #4861
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
Open
TheodoreSpeaks
wants to merge
10
commits into
staging
Choose a base branch
from
feat/1-million-table
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+20,642
−353
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
077e1d0
feat(tables): background import for large CSVs with live progress
TheodoreSpeaks 136d369
fix(tables): address review — import heartbeat, overlap guard, column…
TheodoreSpeaks 9284acc
Merge remote-tracking branch 'origin/staging' into feat/1-million-table
TheodoreSpeaks db9cdc8
fix(tables): guard sync import overlap, scope fileKey to workspace, d…
TheodoreSpeaks 6993ae9
fix(tables): stream large CSV imports from storage instead of bufferi…
TheodoreSpeaks b5c9813
test(tables): fix async-import route tests for workspace-scoped fileK…
TheodoreSpeaks 1a20d57
fix(tables): append imports start after existing rows; reconcile miss…
TheodoreSpeaks 6d2f62a
fix(tables): delete the uploaded CSV from storage after the import fi…
TheodoreSpeaks b19b9d8
fix(tables): validate replace before deleting rows; ignore stale repl…
TheodoreSpeaks 7cec012
fix(tables): bind import worker to its importId (no stale-worker clob…
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
137 changes: 137 additions & 0 deletions
137
apps/sim/app/api/table/[tableId]/import-async/route.test.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,137 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { hybridAuthMockFns } from '@sim/testing' | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import type { TableDefinition } from '@/lib/table' | ||
|
|
||
| const { mockCheckAccess, mockMarkTableImporting, mockRunTableImport } = vi.hoisted(() => ({ | ||
| mockCheckAccess: vi.fn(), | ||
| mockMarkTableImporting: vi.fn(), | ||
| mockRunTableImport: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@sim/utils/id', () => ({ | ||
| generateId: vi.fn().mockReturnValue('import-id-xyz'), | ||
| generateShortId: vi.fn().mockReturnValue('short-id'), | ||
| })) | ||
| vi.mock('@/lib/table/service', () => ({ markTableImporting: mockMarkTableImporting })) | ||
| vi.mock('@/lib/table/import-runner', () => ({ runTableImport: mockRunTableImport })) | ||
| vi.mock('@/lib/core/utils/background', () => ({ | ||
| runDetached: (_label: string, work: () => Promise<unknown>) => { | ||
| void work() | ||
| }, | ||
| })) | ||
| vi.mock('@/app/api/table/utils', async () => { | ||
| const { NextResponse } = await import('next/server') | ||
| return { | ||
| checkAccess: mockCheckAccess, | ||
| accessError: (result: { status: number }) => | ||
| NextResponse.json({ error: 'denied' }, { status: result.status }), | ||
| } | ||
| }) | ||
|
|
||
| import { POST } from '@/app/api/table/[tableId]/import-async/route' | ||
|
|
||
| function buildTable(overrides: Partial<TableDefinition> = {}): TableDefinition { | ||
| return { | ||
| id: 'tbl_1', | ||
| name: 'People', | ||
| description: null, | ||
| schema: { columns: [{ name: 'name', type: 'string' }] }, | ||
| metadata: null, | ||
| rowCount: 0, | ||
| maxRows: 1_000_000, | ||
| workspaceId: 'workspace-1', | ||
| createdBy: 'user-1', | ||
| archivedAt: null, | ||
| createdAt: new Date(), | ||
| updatedAt: new Date(), | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| function makeRequest(body: unknown, tableId = 'tbl_1') { | ||
| const req = new NextRequest(`http://localhost:3000/api/table/${tableId}/import-async`, { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json' }, | ||
| body: JSON.stringify(body), | ||
| }) | ||
| return POST(req, { params: Promise.resolve({ tableId }) }) | ||
| } | ||
|
|
||
| const validBody = { | ||
| workspaceId: 'workspace-1', | ||
| fileKey: 'workspace/workspace-1/123-data.csv', | ||
| fileName: 'data.csv', | ||
| mode: 'append', | ||
| } | ||
|
|
||
| describe('POST /api/table/[tableId]/import-async', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({ | ||
| success: true, | ||
| userId: 'user-1', | ||
| authType: 'session', | ||
| }) | ||
| mockCheckAccess.mockResolvedValue({ ok: true, table: buildTable() }) | ||
| mockMarkTableImporting.mockResolvedValue(undefined) | ||
| mockRunTableImport.mockResolvedValue(undefined) | ||
| }) | ||
|
|
||
| it('marks the table importing and kicks off the worker with mode + mapping', async () => { | ||
| const response = await makeRequest({ | ||
| ...validBody, | ||
| mode: 'replace', | ||
| mapping: { Name: 'name' }, | ||
| createColumns: ['Extra'], | ||
| }) | ||
| const data = await response.json() | ||
|
|
||
| expect(response.status).toBe(200) | ||
| expect(data.data).toEqual({ tableId: 'tbl_1', importId: 'import-id-xyz' }) | ||
| expect(mockMarkTableImporting).toHaveBeenCalledWith('tbl_1', 'import-id-xyz') | ||
| expect(mockRunTableImport).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| tableId: 'tbl_1', | ||
| mode: 'replace', | ||
| delimiter: ',', | ||
| mapping: { Name: 'name' }, | ||
| createColumns: ['Extra'], | ||
| }) | ||
| ) | ||
| }) | ||
|
|
||
| it('returns 401 when unauthenticated', async () => { | ||
| hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({ success: false }) | ||
| const response = await makeRequest(validBody) | ||
| expect(response.status).toBe(401) | ||
| expect(mockMarkTableImporting).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('returns the access error status when access is denied', async () => { | ||
| mockCheckAccess.mockResolvedValue({ ok: false, status: 403 }) | ||
| const response = await makeRequest(validBody) | ||
| expect(response.status).toBe(403) | ||
| expect(mockRunTableImport).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('returns 400 when the target table is archived', async () => { | ||
| mockCheckAccess.mockResolvedValue({ ok: true, table: buildTable({ archivedAt: new Date() }) }) | ||
| const response = await makeRequest(validBody) | ||
| expect(response.status).toBe(400) | ||
| expect(mockRunTableImport).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('returns 400 on workspace mismatch', async () => { | ||
| const response = await makeRequest({ ...validBody, workspaceId: 'other-ws' }) | ||
| expect(response.status).toBe(400) | ||
| }) | ||
|
|
||
| it('returns 400 for an invalid mode', async () => { | ||
| const response = await makeRequest({ ...validBody, mode: 'bogus' }) | ||
| expect(response.status).toBe(400) | ||
| }) | ||
| }) |
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,91 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { generateId } from '@sim/utils/id' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { importIntoTableAsyncContract } from '@/lib/api/contracts/tables' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' | ||
| import { runDetached } from '@/lib/core/utils/background' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { runTableImport } from '@/lib/table/import-runner' | ||
| import { markTableImporting } from '@/lib/table/service' | ||
| import { accessError, checkAccess } from '@/app/api/table/utils' | ||
|
|
||
| const logger = createLogger('TableImportIntoAsync') | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| interface RouteParams { | ||
| params: Promise<{ tableId: string }> | ||
| } | ||
|
|
||
| export const POST = withRouteHandler(async (request: NextRequest, { params }: RouteParams) => { | ||
| const requestId = generateRequestId() | ||
|
|
||
| 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(importIntoTableAsyncContract, request, { params }) | ||
| if (!parsed.success) return parsed.response | ||
| const { tableId } = parsed.data.params | ||
| const { workspaceId, fileKey, fileName, mode, mapping, createColumns } = parsed.data.body | ||
|
|
||
| const access = await checkAccess(tableId, userId, 'write') | ||
| if (!access.ok) return accessError(access, requestId, tableId) | ||
| const { table } = access | ||
|
|
||
| if (table.workspaceId !== workspaceId) { | ||
| return NextResponse.json({ error: 'Invalid workspace ID' }, { status: 400 }) | ||
| } | ||
| // The fileKey is client-supplied — ensure it points at this workspace's storage prefix so a | ||
| // caller can't import another workspace's uploaded object. | ||
| if (!fileKey.startsWith(`workspace/${workspaceId}/`)) { | ||
| return NextResponse.json({ error: 'Invalid file key for workspace' }, { status: 400 }) | ||
| } | ||
| if (table.archivedAt) { | ||
| return NextResponse.json({ error: 'Cannot import into an archived table' }, { status: 400 }) | ||
| } | ||
| // Reject overlapping imports: a second worker would insert at colliding row positions. | ||
| if (table.importStatus === 'importing') { | ||
| return NextResponse.json( | ||
| { error: 'An import is already in progress for this table' }, | ||
| { status: 409 } | ||
| ) | ||
| } | ||
|
|
||
| const ext = fileName.split('.').pop()?.toLowerCase() | ||
| if (ext !== 'csv' && ext !== 'tsv') { | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| return NextResponse.json({ error: 'Only CSV and TSV files are supported' }, { status: 400 }) | ||
| } | ||
| const delimiter = ext === 'tsv' ? '\t' : ',' | ||
|
|
||
| const importId = generateId() | ||
| await markTableImporting(tableId, importId) | ||
|
|
||
| runDetached('table-import', () => | ||
| runTableImport({ | ||
| importId, | ||
| tableId, | ||
| workspaceId, | ||
| userId, | ||
| fileKey, | ||
| fileName, | ||
| delimiter, | ||
| mode, | ||
| mapping, | ||
| createColumns, | ||
| }) | ||
| ) | ||
|
cursor[bot] marked this conversation as resolved.
|
||
|
|
||
| logger.info(`[${requestId}] Async CSV import into existing table started`, { | ||
| tableId, | ||
| importId, | ||
| mode, | ||
| fileName, | ||
| }) | ||
| return NextResponse.json({ success: true, data: { tableId, importId } }) | ||
| }) | ||
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.