From 26e1ce4db66d3cdd55071f80fe52186eebc7a5f7 Mon Sep 17 00:00:00 2001 From: Quinten Stokkink Date: Mon, 16 Sep 2024 11:25:20 +0200 Subject: [PATCH] Fixed InvalidStateError on shutdown --- src/tribler/core/restapi/events_endpoint.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/tribler/core/restapi/events_endpoint.py b/src/tribler/core/restapi/events_endpoint.py index 675a7136a4..bee86db43f 100644 --- a/src/tribler/core/restapi/events_endpoint.py +++ b/src/tribler/core/restapi/events_endpoint.py @@ -2,7 +2,7 @@ import json import time -from asyncio import CancelledError, Event, Queue +from asyncio import CancelledError, Event, Future, Queue from contextlib import suppress from traceback import format_exception from typing import TYPE_CHECKING, TypedDict @@ -251,6 +251,12 @@ async def get_events(self, request: Request) -> web.StreamResponse: else: self._logger.info("Event stream was closed due to shutdown") + # A ``shutdown()`` on our parent may have cancelled ``_handler_waiter`` before this method returns. + # If we leave this be, an error will be raised if the ``Future`` result is set after this method returns. + # See: https://github.com/Tribler/tribler/issues/8156 + if request.protocol._handler_waiter and request.protocol._handler_waiter.cancelled(): # noqa: SLF001 + request.protocol._handler_waiter = Future() # noqa: SLF001 + # See: https://github.com/Tribler/tribler/pull/7906 with suppress(ValueError): self.events_responses.remove(response)