dabeaz / curio

Good Curio!
Other
4.02k stars 241 forks source link

Can tcp_server report back to the caller? #177

Closed jkbbwr closed 7 years ago

jkbbwr commented 7 years ago

The use case in mind is the ability to find out what port tcp_server has bound to if you tell it to bind to port 0.

dabeaz commented 7 years ago

tcp_server() currently runs forever so returning a result is tricky. Open to ideas.

jkbbwr commented 7 years ago

could tcp_server make the tcp_server then return a run_tcp_server coro and maybe metadata

dabeaz commented 7 years ago

Maybe I could split it into two functions. A tcp_server_socket() function that would make a TCP socket. And a run_server() function that would run the server. So, you'd do this:

 sock = tcp_server_socket(address, ...)
 # Look at sock metadata. Set additional options
 ...
 await run_server(sock, handler)

I'd keep tcp_server() the same as it is now (but make it combine these two steps).

jkbbwr commented 7 years ago

The main drive for this was to allow parallel unit tests in the main project by having every test bind to port 0.

dabeaz commented 7 years ago

Have modified Curio basically do the above. To get the socket address do this:

 from curio.network import tcp_server_socket, run_server

 async def main():
         sock = tcp_server_socket('localhost', 0)
         address = sock.getsockname()
         await run_server(sock, client_handler)
njsmith commented 7 years ago

Sounds like this is sorted and I'm not sure how appropriate this suggestion would be in this context anyway, but for reference... in my code I've been handling this kind of situation by the convention that instead of writing code like

task = await spawn(tcp_server(...))

I have code like

task, address = await start_tcp_server(...)

where start_* is a convention meaning "this does setup work, then spawns a task, and only returns once the task is ready". This is sorta-inspired by how erlang spawns tasks. (Actually the full convention is that the first argument to a start_* function is a task supervisor object that we spawn "into", but curio doesn't have any concept like that so it definitely doesn't make much sense for tcp_server.)

dabeaz commented 7 years ago

Interesting. I'd consider something like this as a possibility for Curio.

dabeaz commented 7 years ago

Closing for now.