node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

Haunting EPIPE errors

Open StanleyP opened this issue 1 year ago • 1 comments
trafficstars

Hello, I have node-http-proxy proxying HTTP POST requests with big payload (MBs) to upstream haproxy which upon 401 (Unauthorized) error responds early without reading the body and closes connection. This causes EPIPE error in node-http-proxy, no response is returned to the client and the whole node-http-proxy instance shuts down. I need to return the error from haproxy to the client.

I'm trying to ignore EPIPE errors by monkey-patching _write and _writev methods on proxyReq socket in web-incoming.js

...
    // Enable developers to modify the proxyReq before headers are sent
    proxyReq.on('socket', function(socket) {
      const socketWriteOrig = socket._write;
      socket._write = (data, encoding, callback) => {
        return socketWriteOrig.call(socket, data, encoding, (err) => {
          if(err && err.code == 'EPIPE') {
            if(callback) callback();
            return;
          }
          if(callback) callback(err); else throw err;
        });
      }
      const socketWritevOrig = socket._writev;
      socket._writev = (data, callback) => {
        return socketWritevOrig.call(socket, data, (err) => {
          if(err && err.code == 'EPIPE') {
            if(callback) callback();
            return;
          }
          if(callback) callback(err); else throw err;
        });
      }
      if(server && !proxyReq.getHeader('expect')) {
        server.emit('proxyReq', proxyReq, req, res, options);
      }
    });
...

This "patch" improves the behaviour of node-http-proxy a lot, but still I occasionally get empty response.

Any ideas how to handle EPIPE correctly or improve my "monkey-patch"?

Here is my node-http-proxy instance:

httpProxy
  .createProxyServer({target:'http://localhost:8008',xfwd:false,ws:true})
  .listen(8007);

StanleyP avatar Aug 13 '24 16:08 StanleyP

To handle a EPIPE correctly you can check IOError/OSError and check for errno.EPIPE, Close stderr when handling EPIPE to prevent cascading errors and cleanup resources. For monkey patch check this that was there on the stackoverflow https://stackoverflow.com/questions/9747086/can-i-monkey-patch-nilclass-to-return-nil-for-missing-methods

ravin00 avatar Oct 29 '24 20:10 ravin00