Skip to content

feat onProxyReqWs async handler#1407

Open
LiranBri wants to merge 8 commits intohttp-party:masterfrom
LiranBri:master
Open

feat onProxyReqWs async handler#1407
LiranBri wants to merge 8 commits intohttp-party:masterfrom
LiranBri:master

Conversation

@LiranBri
Copy link
Copy Markdown

Following issues #490 and #1403, currently the library does not support async handler for the proxyReqWs event for modifying the request before proxying it forward.

This suggested PR solved the problem, without breaking backward compatibility, by introducing a new argument asyncContext which is used as follows:

onProxyReqWs: (proxyReq, req, socket, options, head, asyncContext) =>
      asyncContext(async () => {
        // code ...
        const result = await anyAsyncOperation()
        // code ...
        proxyReq.setHeader('key', result)
      }),

@codecov-io
Copy link
Copy Markdown

Codecov Report

Merging #1407 into master will increase coverage by 0.11%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1407      +/-   ##
==========================================
+ Coverage   92.35%   92.47%   +0.11%     
==========================================
  Files           6        6              
  Lines         314      319       +5     
==========================================
+ Hits          290      295       +5     
  Misses         24       24
Impacted Files Coverage Δ
lib/http-proxy/passes/ws-incoming.js 96.29% <100%> (+0.37%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9bbe486...79fa77c. Read the comment docs.

@LiranBri
Copy link
Copy Markdown
Author

All tests have passed, can we please merge the PR? thanks
@indexzero @jcrugzz @yawnt

roderik added a commit to settlemint-archive/node-http-proxy that referenced this pull request Nov 25, 2021
@asturur
Copy link
Copy Markdown

asturur commented Mar 22, 2022

any development on this PR?

@paulrostorp
Copy link
Copy Markdown

Would love to see this merged !

@paulrostorp
Copy link
Copy Markdown

I've created a patch for this PR as well as one for the typescript types package:

http-proxy+1.18.1.patch:

diff --git a/node_modules/http-proxy/lib/http-proxy/passes/ws-incoming.js b/node_modules/http-proxy/lib/http-proxy/passes/ws-incoming.js
index 270f23f..809ec20 100644
--- a/node_modules/http-proxy/lib/http-proxy/passes/ws-incoming.js
+++ b/node_modules/http-proxy/lib/http-proxy/passes/ws-incoming.js
@@ -76,7 +76,7 @@ module.exports = {
    *
    * @api private
    */
-  stream : function stream(req, socket, options, head, server, clb) {
+  stream : async function stream(req, socket, options, head, server, clb) {
 
     var createHttpHeader = function(line, headers) {
       return Object.keys(headers).reduce(function (head, key) {
@@ -104,9 +104,7 @@ module.exports = {
       common.setupOutgoing(options.ssl || {}, options, req)
     );
 
-    // Enable developers to modify the proxyReq before headers are sent
-    if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
-
+    // It is important to register the event listeners of proxyReq before the first await, so we don't have small period of time in which we lose emitted events
     // Error Handler
     proxyReq.on('error', onOutgoingError);
     proxyReq.on('response', function (res) {
@@ -148,7 +146,23 @@ module.exports = {
       server.emit('proxySocket', proxySocket);  //DEPRECATED.
     });
 
-    return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
+
+    // Enable developers to modify the proxyReq before headers are sent
+    if (server) {
+      // Provides a way for the event handler to communicate back to the emitter when it finishes its async handling
+      let asyncHandler
+      const asyncContext = (callback) => {
+        asyncHandler = callback
+      }
+
+      server.emit('proxyReqWs', proxyReq, req, socket, options, head, asyncContext);
+
+      if (asyncHandler) {
+        await asyncHandler()
+      }
+    }
+
+    proxyReq.end();
 
     function onOutgoingError(err) {
       if (clb) {

@types+http-proxy+1.17.9.patch:

diff --git a/node_modules/@types/http-proxy/index.d.ts b/node_modules/@types/http-proxy/index.d.ts
index ca805df..b674ff8 100755
--- a/node_modules/@types/http-proxy/index.d.ts
+++ b/node_modules/@types/http-proxy/index.d.ts
@@ -208,6 +208,7 @@ declare namespace Server {
         socket: net.Socket,
         options: ServerOptions,
         head: any,
+        asyncContext: (cb: Promise) => void
     ) => void;
     type EconnresetCallback<TError = Error, TIncomingMessage = http.IncomingMessage, TServerResponse = http.ServerResponse> = (
         err: TError,

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Jul 20, 2024

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.50%. Comparing base (9bbe486) to head (36896e3).
Report is 3 commits behind head on master.

❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1407      +/-   ##
==========================================
+ Coverage   92.35%   92.50%   +0.14%     
==========================================
  Files           6        6              
  Lines         314      320       +6     
==========================================
+ Hits          290      296       +6     
  Misses         24       24              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants