Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve gracefully_cancel logic #720

Merged
merged 5 commits into from
Sep 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/afraid-dolls-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-agents": patch
---

improve gracefully_cancel logic
27 changes: 22 additions & 5 deletions livekit-agents/livekit/agents/utils/aio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
import contextlib
import functools

from . import debug, duplex_unix, itertools
from .channel import Chan, ChanClosed, ChanReceiver, ChanSender
Expand All @@ -9,11 +9,28 @@


async def gracefully_cancel(*futures: asyncio.Future):
for f in futures:
f.cancel()
loop = asyncio.get_running_loop()
waiters = []

with contextlib.suppress(asyncio.CancelledError):
await asyncio.gather(*futures)
for fut in futures:
waiter = loop.create_future()
cb = functools.partial(_release_waiter, waiter)
waiters.append((waiter, cb))
fut.add_done_callback(cb)
fut.cancel()

try:
for waiter in waiters:
await waiter
finally:
for i, fut in enumerate(futures):
_, cb = waiters[i]
fut.remove_done_callback(cb)


def _release_waiter(waiter, *args):
if not waiter.done():
waiter.set_result(None)


__all__ = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import asyncio
import dataclasses
import os
from dataclasses import dataclass
from typing import AsyncIterable, List, Union

Expand Down Expand Up @@ -121,6 +120,7 @@ def _recognizer(self) -> str:
project_id = self._ensure_client().transport._credentials.project_id # type: ignore
except AttributeError:
from google.auth import default as ga_default

_, project_id = ga_default()
return f"projects/{project_id}/locations/global/recognizers/_"

Expand Down
Loading