h2non/rocky

Getting target server in middleware when using balance

kacperzuk opened this issue · 3 comments

It'd be great if it'd be possible to check which target is actually used for request with balance, at least for response middleware. Maybe through rocky.options.target, like this:

const proxy = require("rocky")();
const http = require("http");

proxy
  .get("/")
  .balance(["http://127.0.0.1:3001", "http://127.0.0.1:3002"])
  .useResponse((req, res, next) => {
    // currently it returns undefined, I'd like to see here :3001 or :3002 URL
    console.log(req.rocky.options.target);
    next();
  });
proxy.listen(3000);

// target servers
http.createServer((req, res) => {
  res.write("Server on :3001");
  res.end();
}).listen(3001);
http.createServer((req, res) => {
  res.write("Server on :3002");
  res.end();
}).listen(3002);

I think that's what happens under the hood, except that it's set on cloned request.

h2non commented

Request object is deeply cloned to avoid side-effects, so that's not possible with the existent interface and implementation. I've plans to change that in the future and use a specific interface for phase specific config, but the hard thing is the propagation across multiple phases and scopes of the middleware levels.

As alternative, I've just supported another way to do that, relying in the response in other to expose the state of the forward phase. Take a look to my latest commit and try it. I don't mind to support that.

Test code:

const proxy = require("rocky")();
const http = require("http");

proxy
  .get("/")
  .balance(["http://127.0.0.1:3001", "http://127.0.0.1:3002"])
  .useResponse((req, res, next) => {
    console.log(res.rocky.options.target)
    next();
  });
proxy.listen(3000);

// target servers
http.createServer((req, res) => {
  res.write("Server on :3001");
  res.end();
}).listen(3001);
http.createServer((req, res) => {
  res.write("Server on :3002");
  res.end();
}).listen(3002);

That works great, having it on response is just as good :)

h2non commented

Done! Same as before, just update rocky via npm!