client: Fix the gracefull shutdown of a client.

This commit is contained in:
Damir Jelić 2019-04-11 14:20:09 +02:00
parent 5001f2fc12
commit 5151095740
2 changed files with 35 additions and 30 deletions

View File

@ -25,7 +25,7 @@ class PantaClient(AsyncClient):
super().__init__(homeserver, user, device_id, store_path, config, super().__init__(homeserver, user, device_id, store_path, config,
ssl, proxy) ssl, proxy)
self.loop_running = False self.task = None
self.loop_stopped = asyncio.Event() self.loop_stopped = asyncio.Event()
self.synced = asyncio.Event() self.synced = asyncio.Event()
@ -40,17 +40,24 @@ class PantaClient(AsyncClient):
"user {}".format(device.id, user_id)) "user {}".format(device.id, user_id))
self.verify_device(device) self.verify_device(device)
async def loop(self): def start_loop(self):
"""Start a loop that runs forever and keeps on syncing with the server. """Start a loop that runs forever and keeps on syncing with the server.
The loop can be stopped with the stop_loop() method. The loop can be stopped with the stop_loop() method.
""" """
loop = asyncio.get_event_loop()
task = loop.create_task(self.loop())
self.task = task
return task
async def loop(self):
self.loop_running = True self.loop_running = True
self.loop_stopped.clear() self.loop_stopped.clear()
logger.info(f"Starting sync loop for {self.user_id}") logger.info(f"Starting sync loop for {self.user_id}")
while self.loop_running: try:
while True:
if not self.logged_in: if not self.logged_in:
# TODO login # TODO login
pass pass
@ -73,18 +80,17 @@ class PantaClient(AsyncClient):
self.synced.set() self.synced.set()
self.synced.clear() self.synced.clear()
except asyncio.CancelledError:
logger.info("Stopping the sync loop") logger.info("Stopping the sync loop")
self.loop_running = False
self.loop_stopped.set() self.loop_stopped.set()
async def loop_stop(self): async def loop_stop(self):
"""Stop the client loop. """Stop the client loop."""
if not self.task:
return
Raises LocalProtocolError if the loop isn't running. self.task.cancel()
"""
if not self.loop_running:
raise LocalProtocolError("Loop is not running")
self.loop_running = False
await self.loop_stopped.wait() await self.loop_stopped.wait()
async def encrypt(self, room_id, msgtype, content): async def encrypt(self, room_id, msgtype, content):

View File

@ -152,8 +152,7 @@ class ProxyDaemon:
self.panta_clients[user_id] = panta_client self.panta_clients[user_id] = panta_client
loop = asyncio.get_event_loop() panta_client.start_loop()
loop.create_task(panta_client.loop())
async def login(self, request): async def login(self, request):
try: try: