njs icon indicating copy to clipboard operation
njs copied to clipboard

Add support for a fetch-like API for TCP (and UDP) sockets.

Open jo-carter opened this issue 1 year ago • 2 comments

In a similar fashion to OpenResty's ngx.socket.tcp

My use-case for this would be for interacting (populating) Memcached directly from NJS (in a non-hack way). Of course there would be many other use-cases - for various TCP/UDP services.

jo-carter avatar Apr 25 '24 23:04 jo-carter

Thanks for the feature. But do you know how to do TCP in current njs?

zizifn avatar Oct 05 '24 05:10 zizifn

@zizifn It cannot be done properly with njs directly at present.

The hack way to do it with njs is to make a http fetch (or via a subrequest + proxy_pass) request to a local Stream Context Virtual Server that contains a js_filter script, and have that script then manipulate request into whatever the protocol should be (and likewise back-translate to response to http) - which sort of works for simple protocols - see memcached.

However, I wouldn't recommend using this approach if you have other options...

jo-carter avatar Oct 05 '24 13:10 jo-carter

An API for talking to Unix Domain Socket would be nice as well. I was trying to replace some lua script which talks to journald (through /run/systemd/journal/socket, a SOCK_DGRAM socket) but it's not possible.

-- Error handling omitted for presentation
local sock = ngx.socket.udp()
local ok, err = sock:setpeername("unix:/run/systemd/journal/socket")
local message = "PRIORITY=5\nMESSAGE_ID=...\nMESSAGE=..."\n"
local res, err = sock:send(message)

randomstuff avatar Jan 12 '25 19:01 randomstuff