|
| 1 | +# Copyright (c) 2023 Tulir Asokan |
| 2 | +# |
| 3 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | +# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from typing import Coroutine |
| 9 | +import asyncio |
| 10 | +import logging |
| 11 | + |
| 12 | +_tasks = set() |
| 13 | +log = logging.getLogger("mau.background_task") |
| 14 | + |
| 15 | + |
| 16 | +async def catch(coro: Coroutine, caller: str) -> None: |
| 17 | + try: |
| 18 | + await coro |
| 19 | + except Exception: |
| 20 | + log.exception(f"Uncaught error in background task (created in {caller})") |
| 21 | + |
| 22 | + |
| 23 | +# Logger.findCaller finds the 3rd stack frame, so add an intermediate function |
| 24 | +# to get the caller of create(). |
| 25 | +def _find_caller() -> tuple[str, int, str, None]: |
| 26 | + return log.findCaller() |
| 27 | + |
| 28 | + |
| 29 | +def create(coro: Coroutine, *, name: str | None = None, catch_errors: bool = True) -> asyncio.Task: |
| 30 | + """ |
| 31 | + Create a background asyncio task safely, ensuring a reference is kept until the task completes. |
| 32 | + It also catches and logs uncaught errors (unless disabled via the parameter). |
| 33 | +
|
| 34 | + Args: |
| 35 | + coro: The coroutine to wrap in a task and execute. |
| 36 | + name: An optional name for the created task. |
| 37 | + catch_errors: Should the task be wrapped in a try-except block to log any uncaught errors? |
| 38 | +
|
| 39 | + Returns: |
| 40 | + An asyncio Task object wrapping the given coroutine. |
| 41 | + """ |
| 42 | + if catch_errors: |
| 43 | + try: |
| 44 | + file_name, line_number, function_name, _ = _find_caller() |
| 45 | + caller = f"{function_name} at {file_name}:{line_number}" |
| 46 | + except ValueError: |
| 47 | + caller = "unknown function" |
| 48 | + task = asyncio.create_task(catch(coro, caller), name=name) |
| 49 | + else: |
| 50 | + task = asyncio.create_task(coro, name=name) |
| 51 | + _tasks.add(task) |
| 52 | + task.add_done_callback(_tasks.discard) |
| 53 | + return task |
0 commit comments