Skip to content

Commit

Permalink
feat(port=0): Add infrastructure to handle dynamically assigned port
Browse files Browse the repository at this point in the history
  • Loading branch information
jourdain committed Dec 6, 2021
1 parent e856180 commit eca3e23
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
13 changes: 10 additions & 3 deletions python/src/wslink/backends/aiohttp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ def get_config(self):
def set_config(self, config):
self.config = config

async def start(self):
def get_port(self):
return self.app["state"]["runner"].addresses[0][1]

async def start(self, port_callback=None):
app = self.app
server_config = self.config
host = self.config["host"]
Expand All @@ -103,6 +106,9 @@ async def start(self):
logging.info("awaiting site startup")
await my_site.start()

if port_callback is not None:
port_callback(self.get_port())

logging.info("awaiting running future")
await running

Expand Down Expand Up @@ -418,7 +424,7 @@ async def sendWrappedMessage(self, rpcid, content, method="", client_id=None):
return

websockets = (
[self.connections[client_id]]
[self.connections.get(client_id)]
if client_id
else [self.connections[c] for c in self.connections]
)
Expand Down Expand Up @@ -458,7 +464,8 @@ async def sendWrappedMessage(self, rpcid, content, method="", client_id=None):
pub.publishManager.unregisterAttachment(key)

for ws in websockets:
await ws.send_str(encMsg)
if ws is not None:
await ws.send_str(encMsg)

loop = asyncio.get_running_loop()
loop.call_soon(pub.publishManager.freeAttachments, found_keys)
Expand Down
17 changes: 15 additions & 2 deletions python/src/wslink/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,16 @@ def start(argv=None, protocol=wsl.ServerProtocol, description="wslink web-server
# =============================================================================
def stop_webserver():
if ws_server:
ws_server.stop()
loop = asyncio.get_event_loop()
return loop.create_task(ws_server.stop())

# =============================================================================
# Get webserver port (useful when 0 is provided and a dynamic one was picked)
# =============================================================================
def get_port():
if ws_server:
return ws_server.get_port()
return -1


# =============================================================================
Expand Down Expand Up @@ -218,8 +227,12 @@ def start_webserver(
# Until then, we can start the server this way
loop = asyncio.get_event_loop()

port_callback = None
if hasattr(wslinkServer, "port_callback"):
port_callback = wslinkServer.port_callback

try:
loop.run_until_complete(ws_server.start())
loop.run_until_complete(ws_server.start(port_callback))
finally:
loop.close()

Expand Down

0 comments on commit eca3e23

Please sign in to comment.