From ae5d72a8700cc67596aa5e19f3760dbdbdac73be Mon Sep 17 00:00:00 2001 From: Satya Rohith Date: Fri, 13 Sep 2024 14:10:22 +0530 Subject: [PATCH] feat: use buffer, introduce flushHeaders, flushBody --- ext/node/polyfills/_http_outgoing.ts | 38 +++++++++++++++++++++------- ext/node/polyfills/http.ts | 6 ++++- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/ext/node/polyfills/_http_outgoing.ts b/ext/node/polyfills/_http_outgoing.ts index e8b438f908..2e8729ba9d 100644 --- a/ext/node/polyfills/_http_outgoing.ts +++ b/ext/node/polyfills/_http_outgoing.ts @@ -491,8 +491,34 @@ Object.defineProperties( return ret; }, + _flushBody() { + const socket = this.socket; + const outputLength = this.outputData.length; + if (socket && socket.writable && outputLength > 0) { + console.log("flushing body"); + for (let i = 0; i < outputLength; i++) { + const { data, encoding, callback } = this.outputData[i]; + this._writeRaw(data, encoding, callback); + } + this.outputData = []; + } + }, + + /** Right after socket is ready, we need to writeHeader() to setup the request and + * client. This is invoked by onSocket(). */ + _flushHeaders() { + console.log("flushHeaders"); + if (this.socket) { + if (!this._headerSent && this._header !== null) { + this._writeHeader(); + this._headerSent = true; + } + } + }, + // deno-lint-ignore no-explicit-any _send(data: any, encoding?: string | null, callback?: () => void) { + console.log("writing data:", data, "socket:", this.socket); if (this.socket) { if (!this._headerSent && this._header !== null) { this._writeHeader(); @@ -500,15 +526,8 @@ Object.defineProperties( } return this._writeRaw(data, encoding, callback); } else { - this.on("socket", (socket) => { - socket.on("connect", () => { - if (!this._headerSent && this._header !== null) { - this._writeHeader(); - this._headerSent = true; - } - return this._writeRaw(data, encoding, callback); - }); - }); + console.log("pushing data to outputData"); + this.outputData.push({ data, encoding, callback }); } }, @@ -522,6 +541,7 @@ Object.defineProperties( encoding?: string | null, callback?: () => void, ) { + console.log("_writeRaw invoked:", data.length); if (typeof data === "string") { data = Buffer.from(data, encoding); } diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index 5b884c7369..f94720cb4c 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -599,7 +599,11 @@ class ClientRequest extends OutgoingMessage { nextTick(() => { this.socket = socket; this.emit("socket", socket); - console.trace("onSocket invoked", socket); + // Flush the internal buffers once socket is assigned. + // Note: the order is important, as the headers flush + // sets up the request. + this._flushHeaders(); + this._flushBody(); }); }