From 47f0b529bfb830d21fbbf37f51cb3923f46aa89d Mon Sep 17 00:00:00 2001 From: n9k Date: Sun, 24 Jul 2022 05:35:10 +0000 Subject: [PATCH] Minor: rename background task fluff --- anonstream/__init__.py | 10 ++++++---- anonstream/events.py | 4 ++-- anonstream/tasks.py | 9 ++++----- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/anonstream/__init__.py b/anonstream/__init__.py index b2260e6..28e3060 100644 --- a/anonstream/__init__.py +++ b/anonstream/__init__.py @@ -60,16 +60,18 @@ def create_app(toml_config): app.stream_viewership = None app.last_info_task = None - # Background tasks' asyncio.sleep tasks, cancelled on shutdown - app.background_sleep = set() + # asyncio tasks to be cancelled on shutdown + app.tasks = set() # Queues for event socket clients app.event_queues = set() @app.after_serving async def shutdown(): - # Force all background tasks to finish - for task in app.background_sleep: + # Cancel started asyncio tasks that would otherwise block shutdown + # The asyncio tasks we create are: + # * quart background tasks awaiting asyncio.sleep() + for task in app.tasks: task.cancel() @app.before_serving diff --git a/anonstream/events.py b/anonstream/events.py index eb19fd6..51081df 100644 --- a/anonstream/events.py +++ b/anonstream/events.py @@ -6,8 +6,8 @@ import json from quart import current_app -async def start_event_server_at(address): - return await asyncio.start_unix_server(serve_event_client, address) +def start_event_server_at(address): + return asyncio.start_unix_server(serve_event_client, address) async def serve_event_client(reader, writer): reader.feed_eof() diff --git a/anonstream/tasks.py b/anonstream/tasks.py index 4902f92..7c6d8aa 100644 --- a/anonstream/tasks.py +++ b/anonstream/tasks.py @@ -19,14 +19,13 @@ USERS = current_app.users CAPTCHAS = current_app.captchas CAPTCHA_SIGNER = current_app.captcha_signer -async def sleep_and_collect_task(delay): - coro = asyncio.sleep(delay) +async def cancel_on_shutdown(coro): task = asyncio.create_task(coro) - current_app.background_sleep.add(task) + current_app.tasks.add(task) try: await task finally: - current_app.background_sleep.remove(task) + current_app.tasks.remove(task) def with_period(period): def periodically(f): @@ -35,7 +34,7 @@ def with_period(period): for iteration in itertools.count(): await f(iteration, *args, **kwargs) try: - await sleep_and_collect_task(period) + await cancel_on_shutdown(asyncio.sleep(period)) except asyncio.CancelledError: break