fix: guard completer against race condition in web connect#87
Open
jin123456bat wants to merge 1 commit into
Open
fix: guard completer against race condition in web connect#87jin123456bat wants to merge 1 commit into
jin123456bat wants to merge 1 commit into
Conversation
When a WebSocket opens successfully but later encounters an error, both onOpen and onError fire on the same connect() call. The second handler attempts to complete an already-completed Completer, causing a StateError: Bad state: Future already completed. Add isCompleted guards to both handlers to prevent the race. Fixes the scenario where a WebSocket connection succeeds (onOpen fires first, completing the completer) and then disconnects (onError fires, trying to completeError an already-completed completer).
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
When a WebSocket opens successfully but later encounters an error (e.g., network drops), both
onOpenandonErrorfire on the sameconnect()call. The second handler attempts to complete an already-completedCompleter, causing aStateError: Bad state: Future already completed.This is commonly seen in Flutter web apps using
web_socket_clientviapusher_client_socket, where the WebSocket connection is used for real-time communication.Root Cause
The
connect()function listens to bothonOpen.firstandonError.firstwithunawaitedfutures. On the web, a WebSocket can fire both events sequentially (open then error on disconnect), and the second event will crash because theCompleterwas already resolved by the first.Fix
Add
if (!completer.isCompleted)guards to bothonOpenandonErrorhandlers so that whichever event fires second is silently dropped instead of throwingStateError.Before
After
Impact
StateError: Bad state: Future already completednoise in production error tracking