From 99bf72f75767d866bd5b22464f657abc4554724f Mon Sep 17 00:00:00 2001 From: sacOO7 Date: Sat, 30 Sep 2023 03:04:27 +0530 Subject: [PATCH] Added eventloop close decorator --- ably/decorator/sync.py | 25 +++++++++++++++++++++++++ ably/rest/rest.py | 10 +++------- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/ably/decorator/sync.py b/ably/decorator/sync.py index 16095585..f3577072 100644 --- a/ably/decorator/sync.py +++ b/ably/decorator/sync.py @@ -37,3 +37,28 @@ def wrapper(*args, **kwargs): return res return wrapper + + +def close_app_eventloop(fn): + import asyncio + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + + caller_eventloop = None + try: + caller_eventloop: events = asyncio.get_running_loop() + except Exception: + pass + + app_eventloop: events = AppEventLoop.current() + if caller_eventloop is not None: + app_eventloop.close() + return caller_eventloop.create_task(fn(*args, **kwargs)) + else: + future = asyncio.run_coroutine_threadsafe(fn(*args, **kwargs), app_eventloop.loop) + result = future.result() + app_eventloop.close() + return result + + return wrapper diff --git a/ably/rest/rest.py b/ably/rest/rest.py index 3c8cb984..1c636147 100644 --- a/ably/rest/rest.py +++ b/ably/rest/rest.py @@ -2,7 +2,7 @@ from typing import Optional from urllib.parse import urlencode -from ably.decorator.sync import optional_sync +from ably.decorator.sync import optional_sync, close_app_eventloop from ably.executer.eventloop import AppEventLoop from ably.http.http import Http from ably.http.paginatedresult import PaginatedResult, HttpPaginatedResponse @@ -152,12 +152,8 @@ async def __aexit__(self, *excinfo): await self.close() def __exit__(self, *excinfo): - self.close_sync() + self.close() + @close_app_eventloop async def close(self): await self.http.close() - AppEventLoop.current().close() - - def close_sync(self): - self.http.close() - AppEventLoop.current().close()