Using a cosocket as an upstream for a TCP stream

29 views
Skip to first unread message

Nikolay Amiantov

unread,
Mar 10, 2025, 8:26:12 PMMar 10
to openresty-en
Hi all,

I'm trying to implement a TCP service that:
* Prereads some data, then based on it;
* Connects to one of the upstreams;
* Sends a custom header to the upstream.

I then want it to continue using the upstream socket as if I used `proxy_pass` on it, forwarding data in both directions.

The way I see now is to use `content_by_lua_block` and:
* Spawn two uthreads, and in both;
* Read from the opposing sockets and forward the data.

However, it feels like I'm reimplementing what Nginx usually does in Lua. Moreover, there is (I think) no way to block on a socket until any data is available and read it. A workaround could be to `receive(1)` followed by `receiveany(buffer_size)`, but reading a single byte first feels even less effective.

Are there any better ways than that? If I read the example correctly, njs supports injecting data into the stream like this using `js_filter`: https://nginx.org/en/docs/stream/ngx_stream_js_module.html . However, it doesn't seem to support Redis, which I also need. I briefly thought of using both on different request stages, but this is a bit too much ;)

Cheers,
Nikolay.
Reply all
Reply to author
Forward
0 new messages