-
Notifications
You must be signed in to change notification settings - Fork 4
fix(FIR-50188): memory leak in streaming #148
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 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e2418bc
fix memory leak
ptiurin a21575a
add extended test
ptiurin db40625
fix test
ptiurin 9173f55
verify no performance degradation
ptiurin cb498af
fix test
ptiurin 4309567
bump timeout a little
ptiurin f5df9a2
use different output
ptiurin 91b3e62
refactor out readline
ptiurin d65edcc
Add sum verification to tests
ptiurin 38a92c9
remove duplicate resume
ptiurin a499607
rename threshold
ptiurin 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,76 +1,221 @@ | ||
| import { Readable } from "stream"; | ||
| import JSONbig from "json-bigint"; | ||
| import readline from "readline"; | ||
| import { | ||
| getNormalizedMeta, | ||
| normalizeResponseRowStreaming | ||
| } from "../normalizeResponse"; | ||
| import { Response } from "node-fetch"; | ||
| import { ExecuteQueryOptions } from "../../types"; | ||
| import { ExecuteQueryOptions, Row } from "../../types"; | ||
| import { Meta } from "../../meta"; | ||
|
|
||
| export class ServerSideStream extends Readable { | ||
| private meta: Meta[] = []; | ||
| private readonly pendingRows: Row[] = []; | ||
| private finished = false; | ||
| private processingData = false; | ||
| private inputPaused = false; | ||
| private readonly maxPendingRows = 5; // Limit pending rows to prevent memory buildup | ||
| private lineBuffer = ""; | ||
| private sourceStream: NodeJS.ReadableStream | null = null; | ||
|
|
||
| constructor( | ||
| private readonly response: Response, | ||
| private readonly executeQueryOptions: ExecuteQueryOptions | ||
| ) { | ||
| super({ objectMode: true }); | ||
| const readLine = readline.createInterface({ | ||
| input: response.body, | ||
| crlfDelay: Infinity | ||
| this.setupInputStream(); | ||
| } | ||
|
|
||
| private setupInputStream() { | ||
| this.sourceStream = this.response.body; | ||
|
|
||
| if (!this.sourceStream) { | ||
| this.destroy(new Error("Response body is null or undefined")); | ||
| return; | ||
| } | ||
|
|
||
| this.sourceStream.on("data", (chunk: Buffer) => { | ||
| this.handleData(chunk); | ||
| }); | ||
|
|
||
| this.sourceStream.on("end", () => { | ||
| this.handleInputEnd(); | ||
| }); | ||
|
|
||
| this.sourceStream.on("error", (err: Error) => { | ||
| this.destroy(err); | ||
| }); | ||
| } | ||
|
|
||
| private handleData(chunk: Buffer) { | ||
| // Convert chunk to string and add to line buffer | ||
| this.lineBuffer += chunk.toString(); | ||
|
|
||
| // Process complete lines | ||
| let lineStart = 0; | ||
| let lineEnd = this.lineBuffer.indexOf("\n", lineStart); | ||
|
|
||
| while (lineEnd !== -1) { | ||
| const line = this.lineBuffer.slice(lineStart, lineEnd); | ||
| this.processLine(line.trim()); | ||
|
|
||
| const lineParser = (line: string) => { | ||
| try { | ||
| if (line.trim()) { | ||
| const parsed = JSONbig.parse(line); | ||
| if (parsed) { | ||
| if (parsed.message_type === "DATA") { | ||
| this.processData(parsed); | ||
| } else if (parsed.message_type === "START") { | ||
| this.meta = getNormalizedMeta(parsed.result_columns); | ||
| this.emit("meta", this.meta); | ||
| } else if (parsed.message_type === "FINISH_SUCCESSFULLY") { | ||
| this.push(null); | ||
| } else if (parsed.message_type === "FINISH_WITH_ERRORS") { | ||
| this.destroy( | ||
| new Error( | ||
| `Result encountered an error: ${parsed.errors | ||
| .map((error: { description: string }) => error.description) | ||
| .join("\n")}` | ||
| ) | ||
| ); | ||
| } | ||
| } else { | ||
| this.destroy(new Error(`Result row could not be parsed: ${line}`)); | ||
| lineStart = lineEnd + 1; | ||
| lineEnd = this.lineBuffer.indexOf("\n", lineStart); | ||
| } | ||
|
|
||
| // Keep remaining partial line in buffer | ||
| this.lineBuffer = this.lineBuffer.slice(lineStart); | ||
|
|
||
| // Apply backpressure if we have too many pending rows | ||
| if ( | ||
| this.pendingRows.length > this.maxPendingRows && | ||
| this.sourceStream && | ||
| !this.inputPaused && | ||
| !this.processingData | ||
| ) { | ||
| this.sourceStream.pause(); | ||
| this.inputPaused = true; | ||
| } | ||
| } | ||
|
|
||
| private handleInputEnd() { | ||
| // Process any remaining line in buffer | ||
| if (this.lineBuffer.trim()) { | ||
| this.processLine(this.lineBuffer.trim()); | ||
| this.lineBuffer = ""; | ||
| } | ||
|
|
||
| this.finished = true; | ||
| this.tryPushPendingData(); | ||
| } | ||
|
|
||
| private processLine(line: string) { | ||
| if (!line) return; | ||
|
|
||
| try { | ||
| const parsed = JSONbig.parse(line); | ||
| if (parsed) { | ||
| if (parsed.message_type === "DATA") { | ||
| this.handleDataMessage(parsed); | ||
| } else if (parsed.message_type === "START") { | ||
| this.meta = getNormalizedMeta(parsed.result_columns); | ||
| this.emit("meta", this.meta); | ||
| } else if (parsed.message_type === "FINISH_SUCCESSFULLY") { | ||
| this.finished = true; | ||
| this.tryPushPendingData(); | ||
| } else if (parsed.message_type === "FINISH_WITH_ERRORS") { | ||
| // Ensure source stream is resumed before destroying to prevent hanging | ||
| if (this.sourceStream && this.inputPaused) { | ||
| this.sourceStream.resume(); | ||
| this.inputPaused = false; | ||
| } | ||
| this.destroy( | ||
| new Error( | ||
| `Result encountered an error: ${parsed.errors | ||
| .map((error: { description: string }) => error.description) | ||
| .join("\n")}` | ||
| ) | ||
| ); | ||
| } | ||
| } catch (err) { | ||
| this.destroy(err); | ||
| } else { | ||
| this.destroy(new Error(`Result row could not be parsed: ${line}`)); | ||
| } | ||
| }; | ||
| readLine.on("line", lineParser); | ||
|
|
||
| readLine.on("close", () => { | ||
| this.push(null); | ||
| }); | ||
| } catch (err) { | ||
| this.destroy(err); | ||
| } | ||
| } | ||
|
|
||
| private processData(parsed: { data: any[] }) { | ||
| private handleDataMessage(parsed: { data: unknown[] }) { | ||
| if (parsed.data) { | ||
| // Process rows one by one to handle backpressure properly | ||
| const normalizedData = normalizeResponseRowStreaming( | ||
| parsed.data, | ||
| this.executeQueryOptions, | ||
| this.meta | ||
| ); | ||
| for (const data of normalizedData) { | ||
| this.emit("data", data); | ||
|
|
||
| // Add to pending rows buffer | ||
| this.pendingRows.push(...normalizedData); | ||
|
|
||
| // Try to push data immediately if not already processing | ||
| if (!this.processingData) { | ||
| this.tryPushPendingData(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private tryPushPendingData() { | ||
| if (this.processingData || this.destroyed) { | ||
| return; | ||
| } | ||
|
|
||
| this.processingData = true; | ||
|
|
||
| while (this.pendingRows.length > 0) { | ||
| const row = this.pendingRows.shift(); | ||
| const canContinue = this.push(row); | ||
|
|
||
| // If pending rows dropped below threshold, resume the source stream | ||
| if ( | ||
| this.pendingRows.length <= this.maxPendingRows / 4 && | ||
| this.sourceStream && | ||
| this.inputPaused | ||
| ) { | ||
| this.sourceStream.resume(); | ||
| this.inputPaused = false; | ||
| } | ||
|
|
||
| // If push returns false, stop pushing and wait for _read to be called | ||
| if (!canContinue) { | ||
| this.processingData = false; | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| // If we've finished processing all data and the server indicated completion | ||
| if (this.finished && this.pendingRows.length === 0) { | ||
| this.push(null); | ||
| this.processingData = false; | ||
| return; | ||
| } | ||
|
|
||
| this.processingData = false; | ||
| } | ||
|
|
||
| _read() { | ||
| /* _read method requires implementation, even if data comes from other sources */ | ||
| // Called when the stream is ready for more data | ||
| if (!this.processingData && this.pendingRows.length > 0) { | ||
| this.tryPushPendingData(); | ||
| } | ||
|
|
||
| // Also resume source stream if it was paused and we have capacity | ||
| if ( | ||
| this.sourceStream && | ||
| this.inputPaused && | ||
| this.pendingRows.length < this.maxPendingRows / 2 | ||
bogdantruta-firebolt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ) { | ||
| this.sourceStream.resume(); | ||
| this.inputPaused = false; | ||
| } | ||
| } | ||
|
|
||
| _destroy(err: Error | null, callback: (error?: Error | null) => void) { | ||
| if (this.sourceStream) { | ||
| // Resume stream if paused to ensure proper cleanup | ||
| if (this.inputPaused) { | ||
| this.sourceStream.resume(); | ||
| this.inputPaused = false; | ||
| } | ||
|
|
||
| // Only call destroy if it exists (for Node.js streams) | ||
| const destroyableStream = this.sourceStream as unknown as { | ||
| destroy?: () => void; | ||
| }; | ||
| if (typeof destroyableStream.destroy === "function") { | ||
| destroyableStream.destroy(); | ||
| } | ||
| this.sourceStream = null; | ||
| } | ||
| callback(err); | ||
| } | ||
| } | ||
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.