From 34a8310f6f85a5de8de57bc2f1251ff4a87d9cff Mon Sep 17 00:00:00 2001 From: Michael Pilosov Date: Sun, 19 Mar 2023 02:52:36 -0600 Subject: [PATCH] retry logic for when host server is offline during startup of host block --- example_block/eden-server/announce.py | 35 +++++++++------------------ 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/example_block/eden-server/announce.py b/example_block/eden-server/announce.py index 2a34c05..f4afbac 100644 --- a/example_block/eden-server/announce.py +++ b/example_block/eden-server/announce.py @@ -28,9 +28,20 @@ async def announce_server(): @sio.event async def connect(): await sio.emit('register', {'name': SERVER_NAME, 'ip': SERVER_IP, 'port': SERVER_PORT}) + print("Announced server to host") async def main(): - await sio.connect(f'http://{HOST_SERVER_IP}:{HOST_SERVER_PORT}') + # retry until we connect to the host + while True: + try: + await sio.connect(f'http://{HOST_SERVER_IP}:{HOST_SERVER_PORT}') + break + except Exception as e: + print(e) + print("Failed to connect to host, retrying in 5 seconds") + await asyncio.sleep(5) + # await sio.connect(f'http://{HOST_SERVER_IP}:{HOST_SERVER_PORT}') + print("Connected to host") @sio.on("heartbeat") async def on_heartbeat(): @@ -42,24 +53,6 @@ async def announce_server(): await main() -# def announce_server_decorator(host_block_function): -# @wraps(host_block_function) -# def wrapper(*args, **kwargs): -# loop = asyncio.get_event_loop() - -# # Start the server announcement task -# announce_task = loop.create_task(announce_server()) - -# # Run the original host_block function -# result = host_block_function(*args, **kwargs) - -# # Cancel the announcement task after the host_block function is done -# announce_task.cancel() - -# return result - -# return wrapper - def announce_server_decorator(host_block_function): @wraps(host_block_function) def wrapper(*args, **kwargs): @@ -69,14 +62,10 @@ def announce_server_decorator(host_block_function): # Announce the server to the host await announce_server() - # announce_task = loop.create_task(announce_server()) - # run announcement task infinitely in background but allow host_block to run - # await asyncio.gather(announce_task, host_block_thread) # Wait for host_block to finish await host_block_thread - # announce_task.cancel() return asyncio.run(main()) return wrapper