feat(ws): per-instance event loop, graceful stop, and recv timeout - #144
Open
hotwater9 wants to merge 1 commit into
Open
feat(ws): per-instance event loop, graceful stop, and recv timeout#144hotwater9 wants to merge 1 commit into
hotwater9 wants to merge 1 commit into
Conversation
hotwater9
force-pushed
the
feat/per-instance-event-loop
branch
from
July 22, 2026 02:33
dd82e46 to
d1c279a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The
ws.Clientuses a module-levelloopvariable that is shared acrossall instances. In multi-bot deployments (multiple
Clientobjects in separatethreads), each thread overwrites the same global, causing:
RuntimeError: Task got Future attached to a different loopon reconnect (ws.Client: module-level loop variable prevents multiple instances (multi-bot race condition) #119)_receive_message_loopcrashes but_select()keeps sleeping,making the client appear alive while receiving nothing
Solution
self._loopper instance; eachstart()creates its own loopasyncio.wait_for(conn.recv(), timeout=300)_receive_message_loopsetsstop_eventon unrecoverable failurestop()→call_soon_threadsafe(stop_event.set)start_async()usesget_running_loop()asyncio.sleep()→wait_for(stop_event.wait(), timeout=...)Breaking Changes
None.
start()signature is unchanged.stop()andstart_async()are additive.Module-level
loopis retained (set to the last started instance's loop) forbackward compatibility.
Related
Testing
test_multi_instance.py: independent loops, stop() terminates start(),stop() interrupts reconnect, start_async() reuses caller loop, backward compat
test_websockets_compat.pyfor per-instance loop