-
Notifications
You must be signed in to change notification settings - Fork 3.7k
fix(tables): sniff CSV delimiter and capture the real header row on import #5888
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
+533
−40
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a9aae1b
fix(tables): sniff CSV delimiter and capture the real header row on i…
waleedlatif1 a6cc15c
fix(tables): rank CSV delimiter by row consistency and bound the peek…
waleedlatif1 33286cf
fix(tables): score CSV delimiter by width*consistency and dedupe headers
waleedlatif1 3811a5d
fix(tables): keep the final row when sniffing a complete CSV
waleedlatif1 4312df9
fix(tables): keep the double-cast annotation adjacent to its cast
waleedlatif1 e642274
fix(tables): observe EOF at the exact sniff-window boundary
waleedlatif1 35156cc
test(tables): use sleep helper instead of raw setTimeout promise
waleedlatif1 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { Readable } from 'node:stream' | ||
| import { | ||
| CSV_DELIMITER_SNIFF_BYTES, | ||
| type CsvDelimiter, | ||
| detectCsvDelimiter, | ||
| } from '@/lib/table/import' | ||
|
|
||
| export interface SniffedCsvStream { | ||
| delimiter: CsvDelimiter | ||
| /** | ||
| * The full file contents, replayed from byte zero. Use this in place of the | ||
| * source stream — the source has already been partially consumed. | ||
| */ | ||
| stream: Readable | ||
| } | ||
|
|
||
| /** | ||
| * Reads the head of a CSV/TSV stream, sniffs its field separator, then returns a | ||
| * stream that replays the buffered head followed by the untouched remainder. | ||
| * | ||
| * Memory is bounded: it buffers only the source chunks needed to reach the | ||
| * {@link CSV_DELIMITER_SNIFF_BYTES} window (one chunk past it, at worst), and the | ||
| * detection sample it copies is capped at exactly that window regardless of how | ||
| * large a single upstream chunk is. Those buffered chunks are then replayed | ||
| * *by reference* — never re-copied — so a multi-GB import stays O(sniff window) | ||
| * plus the single in-flight chunk. {@link detectCsvDelimiter} drops any partial | ||
| * trailing line, so no newline trimming is needed here. | ||
| */ | ||
| export async function sniffCsvDelimiterFromStream( | ||
| source: Readable, | ||
| fallback: CsvDelimiter = ',' | ||
| ): Promise<SniffedCsvStream> { | ||
| const reader = source[Symbol.asyncIterator]() | ||
| const chunks: Buffer[] = [] | ||
| let size = 0 | ||
| let exhausted = false | ||
|
|
||
| // Read until the buffered size *exceeds* the window (not just reaches it) or the stream ends. | ||
| // The `<=` is deliberate: a file whose size is exactly the window must still trigger one more | ||
| // read so EOF is observed and `exhausted` becomes true — otherwise it would be misjudged as a | ||
| // truncated prefix and disagree with the buffered callers (which pass complete for that size). | ||
| while (size <= CSV_DELIMITER_SNIFF_BYTES) { | ||
| const next = await reader.next() | ||
| if (next.done) { | ||
| exhausted = true | ||
| break | ||
| } | ||
| const chunk = Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value as Uint8Array) | ||
| chunks.push(chunk) | ||
| size += chunk.length | ||
| } | ||
|
|
||
| // Copy at most the sniff window for detection — `Buffer.concat`'s length arg truncates, | ||
| // so an oversized final chunk can't inflate this allocation past CSV_DELIMITER_SNIFF_BYTES. | ||
| const sample = Buffer.concat(chunks, Math.min(size, CSV_DELIMITER_SNIFF_BYTES)) | ||
| // `exhausted` (the loop stopped on end-of-stream, never on exceeding the window) means the whole | ||
| // file fit in the window, so its last row must count even without a trailing newline. Otherwise | ||
| // the sample is a truncated prefix whose final line may be partial and should be dropped. | ||
| const delimiter = await detectCsvDelimiter(sample, fallback, { complete: exhausted }) | ||
|
|
||
| const stream = Readable.from( | ||
| (async function* replay() { | ||
| // Replay the already-read chunks by reference (no re-copy), then drain the rest. | ||
| for (const chunk of chunks) yield chunk | ||
| if (exhausted) return | ||
| while (true) { | ||
| const next = await reader.next() | ||
| if (next.done) return | ||
| yield next.value | ||
| } | ||
| })() | ||
| ) | ||
|
|
||
| // `Readable.from` closes the generator on destroy, which returns the source | ||
| // iterator — but an early destroy of the wrapper before the generator is | ||
| // pulled would otherwise leak the source's socket. | ||
| stream.on('close', () => source.destroy()) | ||
|
|
||
| return { delimiter, stream } | ||
| } |
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.