| # Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| import asyncio | |
| import logging | |
| from typing import Any | |
| async def await_shielded_cleanup( | |
| cleanup_task: asyncio.Task[Any], | |
| logger: logging.Logger, | |
| failure_context: str, | |
| ) -> None: | |
| """Waits for a cleanup task to finish, deferring cancellation until done. | |
| Repeated cancellations while waiting are absorbed and the most recent | |
| `CancelledError` is re-raised after `cleanup_task` completes. Any non-cancel | |
| exception raised by `cleanup_task` is logged at warning level on `logger`. | |
| If `cleanup_task` itself is cancelled externally without the caller being | |
| cancelled, this function returns cleanly without logging or raising. | |
| """ | |
| deferred_cancel: asyncio.CancelledError | None = None | |
| while not cleanup_task.done(): | |
| try: | |
| await asyncio.shield(cleanup_task) | |
| except asyncio.CancelledError as exc: | |
| current_task = asyncio.current_task() | |
| if not cleanup_task.cancelled() or ( | |
| current_task is not None and current_task.cancelling() > 0 | |
| ): | |
| deferred_cancel = exc | |
| except Exception: | |
| pass | |
| if ( | |
| not cleanup_task.cancelled() | |
| and (cleanup_exc := cleanup_task.exception()) is not None | |
| ): | |
| logger.warning("%s: %s", failure_context, cleanup_exc) | |
| if deferred_cancel is not None: | |
| raise deferred_cancel |