On Thu, 27 Apr 2017 12:49:02 GMT, Ľudovít Lučenič wrote:

My vibe.d-based web server application serves currently as an augmented proxy (or a mediator) between a set of application logic servers (listening on TCP sockets) and users' browsers (receiving data via websockets).

In particular, the use case goes as follows:

  • after a user logs in in a browser,
  • a TCP connection is established from vibe.d server to one of the end servers,
  • that server verifies the credentials and
  • the user is supplied an HTML page with session-based web socket establishment code,
  • in turn, the browser creates that websocket connection to my vibe.d server,
  • the websocket handling function notifies the other task, so that it can start resending data from the TCP connection,
  • this websocket handling function then resends data to the browser,
  • finally, the user sees online updated data (sent from the end server) in the browser.

As I need to manage the connection status of both tied connections (ws, tcp) in various places while processing data from either end, it would be beneficial to have these (both) connections served within a single thread by different fibers, so they can shared TLS data. As I do not see a way how to make vibe.d open a websocket connection in a specific thread (the one of the already established TCP connection to an end server), I would go with a passing of the websocket over to the end server connection handling task and setting up the handling of the websocket with runTask() from there to stay in the same thread.

What is a proper way how to pass a websocket connection to another task in a different thread?

Thank you very much in advance for hints of any kind.
Ľudovít

TCP connections generally can't be safely moved between threads. It might work for some of the back ends by accident, but it can't be relied upon, since they are embedded in a thread-specific data structure.

Since the web socket connection is an incoming one, the only way to control the accepting thread would be to open up one port for each thread. So when a page gets served from the first thread, it might generate code to connect to ws://server:81, while the second one connects to ws://server:82.

Generally, if possible, I'd always favor a multi-process approach instead of a multi-threaded one. So instead of using the distribute option, HTTPServerSettings.reusePort would be used, and then n processes could all listen on the same port. However, that would require to make the application completely state-less and to move any session related data to a separate database/cache, so that may be a performance issue.

If the multiple-port suggestion isn't feasible for some reason, it would be possible to build in a way to move incoming connections between threads before the internal management structures have been built (using an additional pre-connection callback). That would require a bit of work, but could be added to vibe-core/eventcore.