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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use asyncio.Event to stop stream in heartbeat route #7932

Merged
merged 11 commits into from Apr 5, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tiny-friends-stick.md
@@ -0,0 +1,5 @@
---
"gradio": patch
---

feat:Use asyncio.Event to stop stream in heartbeat route
1 change: 1 addition & 0 deletions gradio/blocks.py
Expand Up @@ -2480,6 +2480,7 @@ def close(self, verbose: bool = True) -> None:
self._queue.close()
# set this before closing server to shut down heartbeats
self.is_running = False
self.app.stop_event.set()
if self.server:
self.server.close()
# So that the startup events (starting the queue)
Expand Down
6 changes: 6 additions & 0 deletions gradio/route_utils.py
Expand Up @@ -8,6 +8,7 @@
import os
import re
import shutil
import sys
from collections import deque
from contextlib import AsyncExitStack, asynccontextmanager
from dataclasses import dataclass as python_dataclass
Expand Down Expand Up @@ -792,6 +793,11 @@ async def _delete_state(app: App):
@asynccontextmanager
async def _delete_state_handler(app: App):
"""When the server launches, regularly delete expired state."""
# The stop event needs to get the current event loop for python 3.8
# but the loop parameter is deprecated for 3.8+
if sys.version_info < (3, 9):
loop = asyncio.get_running_loop()
app.stop_event = asyncio.Event(loop=loop)
asyncio.create_task(_delete_state(app))
yield

Expand Down
4 changes: 2 additions & 2 deletions gradio/routes.py
Expand Up @@ -156,6 +156,7 @@ def __init__(
self.iterators: dict[str, AsyncIterator] = {}
self.iterators_to_reset: set[str] = set()
self.lock = utils.safe_get_lock()
self.stop_event = utils.safe_get_stop_event()
self.cookie_id = secrets.token_urlsafe(32)
self.queue_token = secrets.token_urlsafe(32)
self.startup_events_triggered = False
Expand Down Expand Up @@ -606,8 +607,7 @@ async def wait():
return "wait"

async def stop_stream():
while app.get_blocks().is_running:
await asyncio.sleep(0.25)
await app.stop_event.wait()
return "stop"

async def iterator():
Expand Down
8 changes: 8 additions & 0 deletions gradio/utils.py
Expand Up @@ -89,6 +89,14 @@ def safe_get_lock() -> asyncio.Lock:
return None # type: ignore


def safe_get_stop_event() -> asyncio.Event:
try:
asyncio.get_event_loop()
return asyncio.Event()
except RuntimeError:
return None # type: ignore


class BaseReloader(ABC):
@property
@abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion js/app/test/unload_event_test.spec.ts
Expand Up @@ -29,6 +29,6 @@ test("when a user closes the page, the unload event should be triggered", async
expect(data).toContain("incremented 1");
expect(data).toContain("incremented 2");
expect(data).toContain("incremented 3");
expect(data).toContain("deleted 4");
expect(data).toContain("unloading");
expect(data).toContain("deleted 4");
});