Skip to content

Commit

Permalink
Cancel tasks on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
RB387 committed Sep 23, 2024
1 parent a5c3a50 commit db80feb
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/magic_di/healthcheck.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
from asyncio import Future
from contextlib import suppress
from dataclasses import dataclass
from typing import Any, Protocol

Expand Down Expand Up @@ -38,11 +39,21 @@ async def ping_dependencies(self, max_concurrency: int = 1) -> None:
"""
tasks: set[Future[Any]] = set()

for dependency in self.injector.get_dependencies_by_interface(PingableProtocol):
tasks.add(asyncio.ensure_future(dependency.__ping__()))
try:
for dependency in self.injector.get_dependencies_by_interface(PingableProtocol):
tasks.add(asyncio.ensure_future(dependency.__ping__()))

if len(tasks) >= max_concurrency:
tasks, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
if len(tasks) >= max_concurrency:
tasks, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)

if tasks:
await asyncio.gather(*tasks)
if tasks:
await asyncio.gather(*tasks)
tasks = set()

finally:
for task in tasks:
task.cancel()

if tasks:
with suppress(asyncio.CancelledError):
await asyncio.gather(*tasks)

0 comments on commit db80feb

Please sign in to comment.