diff --git a/backend/src/services/__tests__/export.test.ts b/backend/src/services/__tests__/export.test.ts index d654b0ad..b4f0aeda 100644 --- a/backend/src/services/__tests__/export.test.ts +++ b/backend/src/services/__tests__/export.test.ts @@ -4,6 +4,7 @@ import { createAesGcmFieldEncryption, createCsvExportService, createInMemoryCsvExportStore, + csvLines, escapeCsvCell, formatCsvCell, rowsToCsv, @@ -227,6 +228,64 @@ describe('createCsvExportService.download', () => { }); }); +describe('streaming CSV generation (issue #2268)', () => { + const COLUMNS_PLAIN = [ + { key: 'plan', header: 'Plan', pii: false }, + { key: 'amount', header: 'Amount', pii: false }, + ]; + const ROWS_PLAIN = [ + { plan: 'pro', amount: '1999' }, + { plan: 'starter', amount: '' }, + ]; + + it('yields the header and one chunk per row, matching rowsToCsv', () => { + const chunks = [...csvLines(COLUMNS_PLAIN, ROWS_PLAIN)]; + + expect(chunks).toHaveLength(3); + expect(chunks[0]).toBe('Plan,Amount\r\n'); + expect(chunks[1]).toBe('pro,1999\r\n'); + expect(chunks.join('')).toBe(rowsToCsv(COLUMNS_PLAIN, ROWS_PLAIN)); + }); + + it('streams decrypted rows lazily and returns download metadata', async () => { + const { service } = makeService(); + await service.create({ ownerId: 'user-1', columns: COLUMNS, rows: ROWS }); + + const iterator = service.stream('export-1'); + const header = await iterator.next(); + expect(header.done).toBe(false); + expect(header.value).toBe('Email,Full name,Plan,Amount\r\n'); + + const chunks: string[] = []; + let next = await iterator.next(); + while (!next.done) { + chunks.push(next.value); + next = await iterator.next(); + } + + expect(chunks).toHaveLength(2); + expect(chunks[0]).toContain('alice@example.com'); + expect(next.value.rowCount).toBe(2); + expect(next.value.filename).toBe('subtrackr-export.csv'); + expect(header.value + chunks.join('')).toBe((await service.download('export-1')).content); + }); + + it('propagates decryption failures while streaming', async () => { + const { service, store } = makeService(); + await service.create({ ownerId: 'user-1', columns: COLUMNS, rows: ROWS }); + const stranger = createCsvExportService({ + store, + encryption: createAesGcmFieldEncryption({ masterKey: Buffer.alloc(32, 9) }), + }); + + await expect(async () => { + for await (const _chunk of stranger.stream('export-1')) { + // drain the stream + } + }).rejects.toMatchObject({ code: 'UNKNOWN_KEY' }); + }); +}); + describe('createCsvExportService.remove', () => { it('deletes the export and reports it', async () => { const { service, store, metrics } = makeService(); diff --git a/backend/src/services/export.ts b/backend/src/services/export.ts index 7a79772d..c4acac1c 100644 --- a/backend/src/services/export.ts +++ b/backend/src/services/export.ts @@ -150,12 +150,25 @@ export function formatCsvCell(value: CsvCellValue): string { return String(value); } -export function rowsToCsv(columns: StoredCsvColumn[], rows: Array>): string { - const lines = [columns.map((column) => escapeCsvCell(column.header)).join(',')]; +/** + * Yield one CRLF-terminated CSV record at a time. Consumers that write to a + * socket or a file can keep only a single row in memory instead of one string + * per row plus a second joined copy of the whole export. + */ +export function* csvLines( + columns: StoredCsvColumn[], + rows: Iterable> +): Generator { + yield `${columns.map((column) => escapeCsvCell(column.header)).join(',')}\r\n`; for (const row of rows) { - lines.push(columns.map((column) => escapeCsvCell(formatCsvCell(row[column.key]))).join(',')); + yield `${columns.map((column) => escapeCsvCell(formatCsvCell(row[column.key]))).join(',')}\r\n`; } - return `${lines.join('\r\n')}\r\n`; +} + +export function rowsToCsv(columns: StoredCsvColumn[], rows: Array>): string { + let content = ''; + for (const line of csvLines(columns, rows)) content += line; + return content; } export function safeCsvFilename(filename: string | undefined): string { @@ -272,9 +285,19 @@ export interface CsvExportServiceOptions { defaultExpiresInMinutes?: number; } +/** Metadata returned once a streamed download has been fully consumed. */ +export interface CsvStreamResult { + filename: string; + contentType: string; + rowCount: number; + downloadedAt: number; +} + export interface CsvExportService { create(request: CsvExportRequest): Promise; download(exportId: string): Promise; + /** Decrypt and emit CSV records lazily, one row at a time. */ + stream(exportId: string): AsyncGenerator; getSummary(exportId: string): Promise; remove(exportId: string): Promise; } @@ -357,6 +380,58 @@ export function createCsvExportService(options: CsvExportServiceOptions = {}): C metrics?.increment?.(`${METRIC_PREFIX}.${name}`, 1, tags); }; + const validatedRecord = async (exportId: string): Promise => { + const record = await store.get(exportId); + if (!record) { + emit('not_found'); + throw new CsvExportError('NOT_FOUND', 'Export not found'); + } + if (now() > record.expiresAt) { + emit('expired'); + await store.delete?.(exportId); + throw new CsvExportError('EXPIRED', 'Export has expired'); + } + if (checksumFor(record.columns, record.rows) !== record.checksum) { + emit('integrity_failed'); + throw new CsvExportError('INTEGRITY_ERROR', 'Export payload failed its checksum'); + } + return record; + }; + + async function* streamCsv(exportId: string): AsyncGenerator { + const startedAt = now(); + const record = await validatedRecord(exportId); + yield `${record.columns.map((column) => escapeCsvCell(column.header)).join(',')}\r\n`; + try { + for (const storedRow of record.rows) { + const cells: string[] = []; + for (const column of record.columns) { + const cell = storedRow[column.key] ?? ''; + const plaintext = + column.pii && cell !== '' + ? await encryption.decrypt(parseEncryptedCell(cell)) + : cell; + cells.push(escapeCsvCell(plaintext)); + } + yield `${cells.join(',')}\r\n`; + } + } catch (error) { + log.error?.('CSV export decryption failed', { exportId }); + emit('decryption_failed'); + throw error; + } + const downloadedAt = now(); + log.info?.('CSV export downloaded', { exportId, ownerId: record.ownerId }); + emit('downloaded'); + metrics?.timing?.(`${METRIC_PREFIX}.download`, Math.max(0, downloadedAt - startedAt)); + return { + filename: record.filename, + contentType: 'text/csv; charset=utf-8', + rowCount: record.rowCount, + downloadedAt, + }; + } + return { async create(request: CsvExportRequest): Promise { const startedAt = now(); @@ -419,53 +494,28 @@ export function createCsvExportService(options: CsvExportServiceOptions = {}): C }, async download(exportId: string): Promise { - const startedAt = now(); - const record = await store.get(exportId); - if (!record) { - emit('not_found'); - throw new CsvExportError('NOT_FOUND', 'Export not found'); - } - if (now() > record.expiresAt) { - emit('expired'); - await store.delete?.(exportId); - throw new CsvExportError('EXPIRED', 'Export has expired'); - } - if (checksumFor(record.columns, record.rows) !== record.checksum) { - emit('integrity_failed'); - throw new CsvExportError('INTEGRITY_ERROR', 'Export payload failed its checksum'); + // Backwards-compatible buffered API: collects the same chunks a streaming + // caller would write straight to the response body. + const iterator = streamCsv(exportId); + let content = ''; + let chunk = await iterator.next(); + while (!chunk.done) { + content += chunk.value; + chunk = await iterator.next(); } - - const plaintextRows: Array> = []; - try { - for (const storedRow of record.rows) { - const plaintextRow: Record = {}; - for (const column of record.columns) { - const cell = storedRow[column.key] ?? ''; - plaintextRow[column.key] = - column.pii && cell !== '' ? await encryption.decrypt(parseEncryptedCell(cell)) : cell; - } - plaintextRows.push(plaintextRow); - } - } catch (error) { - log.error?.('CSV export decryption failed', { exportId }); - emit('decryption_failed'); - throw error; - } - - const downloadedAt = now(); - log.info?.('CSV export downloaded', { exportId, ownerId: record.ownerId }); - emit('downloaded'); - metrics?.timing?.(`${METRIC_PREFIX}.download`, Math.max(0, downloadedAt - startedAt)); + const meta = chunk.value; return { exportId, - filename: record.filename, - contentType: 'text/csv; charset=utf-8', - content: rowsToCsv(record.columns, plaintextRows), - rowCount: record.rowCount, - downloadedAt, + filename: meta.filename, + contentType: meta.contentType, + content, + rowCount: meta.rowCount, + downloadedAt: meta.downloadedAt, }; }, + stream: streamCsv, + async getSummary(exportId: string): Promise { const record = await store.get(exportId); if (!record) throw new CsvExportError('NOT_FOUND', 'Export not found');