Repository navigation
fix(realtime): prevent null check crash in connect() during rapid lifecycle transitions - #1321
Conversation
…ecycle transitions Capture the WebSocketChannel in a local variable before awaiting ready, then add a staleness guard (conn != localConn) after the await to bail out if disconnect() ran concurrently. This prevents the TypeError when conn is nullified between the await and the stream.listen() call. Also replace the conn!.sink.done access in onResumed() with a stored _disconnectFuture to eliminate a second NPE risk during lifecycle flapping. Fixes supabase#1320
There was a problem hiding this comment.
Pull request overview
This PR addresses a race condition during rapid app lifecycle transitions that could trigger null-check crashes when disconnect() interleaves with connect() in the realtime client, and adjusts Supabase lifecycle reconnect logic to avoid dereferencing a nullified connection.
Changes:
- Update
RealtimeClient.connect()to capture the createdWebSocketChannelin a local variable and add a post-await readystaleness guard before listening to the stream. - Update
Supabase.onResumed()to wait on a stored disconnect future instead of accessingrealtime.conn!.sink.done. - Add unit tests in
socket_test.dartcovering connect/disconnect race scenarios.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| packages/supabase_flutter/lib/src/supabase.dart | Track disconnect completion via _disconnectFuture and use it to sequence reconnect on resume without conn! access. |
| packages/realtime_client/lib/src/realtime_client.dart | Prevent null-check crash by using a local socket reference across await ready and guarding against staleness. |
| packages/realtime_client/test/socket_test.dart | Add regression tests for rapid connect/disconnect interleavings. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
… in post-await guard Address review feedback: - Add conn != localConn guard inside the catch block to avoid firing error handlers for a stale connection attempt. - Strengthen the post-await guard to also check connState == connecting, preventing connect() from proceeding if disconnect() has already set connState to disconnecting but hasn't yet nulled conn.
…ad of eagerly Address review feedback from icnahom: if a second resumed event fires while disconnect is still in progress (e.g. paused → resumed → inactive → resumed), the eagerly-nulled _disconnectFuture causes the second resumed to fall into the else branch where connect() no-ops because conn is still non-null. Move _disconnectFuture = null into the .then() callback with a guard to avoid overwriting a newer future set by a subsequent paused event.
Add transport field to RealtimeClientOptions (non-breaking, additive) so tests can inject a mock WebSocket transport. Add two lifecycle tests: - paused → resumed reconnects after disconnect completes - paused → resumed → inactive → resumed still reconnects (validates _disconnectFuture is not eagerly cleared)
There was a problem hiding this comment.
Although I have my reservations about introducing a second source of truth (_disconnectFuture), the PR effectively resolves the primary issue.
A follow up PR could be created to further improve the app lifecycle based connection management logic.
For example, double resumed call will forceRejoin channels. But instead of putting another band aid, we could rewrite the logic to better handle edge cases.
Pseudo-code:
// 1. Event Queue ensures operations never overlap
// Dart Future Chaining or external Package like `synchronized` or `pool`
TaskQueue taskQueue
// Track the absolute most recent state
AppState latestState
onLifecycleChange(newState):
// Update synchronously before queuing
latestState = newState
// Append to queue instead of tracking 'in-flight' futures
taskQueue.enqueue(() => processLifecycle(newState))
processLifecycle(targetState):
// 2. Built-in Cancellation: Did the app switch states while we
// were waiting in the queue? If so, abort this outdated task.
if targetState != latestState:
return
// 3. Single Source of Truth (SSOT): Ask the socket itself
bool isConnectionActive = RealtimeClient.isConnected OR RealtimeClient.isConnecting
if targetState == RESUMED:
// 4. Idempotency: If already connected, do nothing.
// This safely handles "double resumed" naturally.
if isConnectionActive:
return
RealtimeClient.connect()
if targetState == PAUSED:
// Idempotency: If already disconnected, do nothing.
if not isConnectionActive:
return
RealtimeClient.disconnect()|
Hi @icnahom. Much thanks for reviewing the PR, and I agree with your suggestion. Would it make sense to merge this PR, and work together on a more structural follow up PR, as you suggested? I can take it, but this would require deeper testing and review. |
|
@grdsdev Could you please merge this when you have a moment? |
grdsdev
left a comment
There was a problem hiding this comment.
Thanks @brunovsiqueira for the fix.
As @icnahom suggested, we need to refactor this.
I'm approving this PR, but feel free to open another one improving this implementation.
Summary
connect()inrealtime_client.dart: CaptureWebSocketChannelin a local variable beforeawait ready, then checkconn != localConnafterward as a staleness guard. This prevents theTypeError: Null check operator used on a null valuecrash atconn!.stream.listen(...)whendisconnect()nullifiesconnduring the await.onResumed()insupabase.dart: Replacerealtime.conn!.sink.donewith a stored_disconnectFuturefield, eliminating a second NPE risk whenconnis nullified between the null check and the access during rapid lifecycle transitions.Fixes #1320
Test plan
dart testpasses inpackages/realtime_client(29 tests, including 3 new race condition tests)flutter testpasses inpackages/supabase_flutter(36 tests)Manual testing
adb shell am memory-factor critical, then immediately resume