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

fix: make SimpleMessageQueue server cancellable #394

Merged
merged 1 commit into from
Nov 30, 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
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import asyncio

import pytest

from llama_deploy import SimpleMessageQueue


@pytest.mark.e2e
@pytest.mark.asyncio
async def test_cancel_launch_server():
mq = SimpleMessageQueue()
t = asyncio.create_task(mq.launch_server())

# Make sure the queue starts
await asyncio.sleep(1)

# Cancel
t.cancel()
await t
20 changes: 9 additions & 11 deletions llama_deploy/message_queues/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
import asyncio
import random
from collections import deque
from contextlib import asynccontextmanager
from logging import getLogger
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Sequence
from typing import Any, Dict, List, Literal, Optional, Sequence
from urllib.parse import urljoin

import httpx
Expand Down Expand Up @@ -197,7 +196,7 @@ def __init__(
internal_port=internal_port,
)

self._app = FastAPI(lifespan=self.lifespan)
self._app = FastAPI()

self._app.add_api_route(
"/", self.home, methods=["GET"], tags=["Message Queue State"]
Expand Down Expand Up @@ -392,13 +391,6 @@ async def processing_loop(self) -> None:
) # TODO dedicated ack
await asyncio.sleep(0.1)

@asynccontextmanager
async def lifespan(self, app: FastAPI) -> AsyncGenerator[None, None]:
"""Starts the processing loop when the fastapi app starts."""
asyncio.create_task(self.processing_loop())
yield
self.running = False

async def launch_local(self) -> asyncio.Task:
"""Launch the message queue locally, in-process."""
logger.info("Launching message queue locally")
Expand All @@ -417,7 +409,13 @@ def install_signal_handlers(self) -> None:

cfg = uvicorn.Config(self._app, host=host, port=port)
server = CustomServer(cfg)
await server.serve()
pl_task = asyncio.create_task(self.processing_loop())

try:
await server.serve()
except asyncio.CancelledError:
self.running = False
await asyncio.gather(server.shutdown(), pl_task, return_exceptions=True)

async def home(self) -> Dict[str, str]:
return {
Expand Down
Loading