fix(android): MM-68210 guard WebSocket methods against missing client NPE - #170
fix(android): MM-68210 guard WebSocket methods against missing client NPE#170pavelzeman wants to merge 3 commits into
Conversation
Replace non-null assertion operators (!!) with safe access patterns across all WebSocket client methods to prevent NullPointerException when a client doesn't exist for a given URI. - invalidateClientFor: use ?.let for safe access, resolve even if client doesn't exist (desired state is already achieved) - connectFor, disconnectFor, sendDataFor: explicit null check with promise rejection instead of relying on NPE caught by try/catch - ensureClientFor: use ?.let instead of containsKey + !! Fixes Sentry #7153287556 (1,568 events / 1,074 affected users) Co-authored-by: Claude <claude@anthropic.com>
📝 WalkthroughWalkthrough
ChangesNull-safe client handling
Estimated code review effort🎯 2 (Simple) | ⏱️ ~15 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt`:
- Around line 149-151: The websocket send flow in WebSocketClientModuleImpl.send
is resolving the promise even when client.webSocket?.send(data) returns null or
false, so dropped frames are treated as successful sends. Update the send logic
to inspect the return value from client.webSocket?.send(data) and reject the
promise whenever the socket is missing or OkHttp declines the frame, keeping
promise.resolve(null) only for a confirmed send.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f9fe4df1-ad82-4557-8d6e-7839c8355646
📒 Files selected for processing (1)
android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt
Check the return value of webSocket.send() — returns false when OkHttp declines the frame (e.g. socket closing) and null when the socket is missing. Only resolve the promise on a confirmed send. Addresses CodeRabbit review feedback on PR #170. Co-authored-by: Claude <claude@anthropic.com>
jgheithcock
left a comment
There was a problem hiding this comment.
This was actually caught by Sentry and the ticket created back on April 6. Interestingly, the user count then fell off under the >100 users/week on May 17 (though it still reports).
While this file looks good, the https://github.com/mattermost/react-native-network-client also has two instances where we have the unsafe clients[url]!! pattern:
ApiClientModuleImpl.kt: download and upload. Just FYI, not for this PR.
Replaced unsafe `clients[url]!!` pattern with null-safe checks across: - getClientHeadersFor - addClientHeadersFor - importClientP12For - invalidateClientFor - download - upload All methods now reject promise with clear error when client doesn't exist for the given URL, matching the pattern already established in WebSocket methods. Sentry issue: MATTERMOST-ANDROID-TEST-2E / MM-68210 Co-authored-by: Claude <claude@anthropic.com>
977ee5b to
f86a8b4
Compare
|
Expanded scope: Added null guards for 6 additional methods in
All now follow the same safe pattern as the WebSocket methods: check for null client and reject promise with clear error message if missing. This force-push invalidates the previous approval — please re-review. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt (1)
165-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse a regular exception type for missing-client rejections.
These branches model an expected runtime miss, so
Error(...)is the wrong throwable shape here. If this ever gets propagated or handled outsidePromise.reject, it will not be caught bycatch (Exception)blocks and reads like an unrecoverable JVM failure. PreferIllegalStateExceptionor a stable RN error code/message instead.Proposed change
- return promise.reject(Error("Client not found for baseUrl: $url")) + return promise.reject(IllegalStateException("Client not found for baseUrl: $url"))Also applies to: 185-185, 206-206, 227-227, 279-279, 343-343
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt` at line 165, The missing-client rejection branches in ApiClientModuleImpl should not use Error(...) because these are expected runtime failures; update the Promise.reject calls in the client lookup paths (for example the logic around getClient and related baseUrl checks) to use a regular exception such as IllegalStateException, or a stable React Native error code/message shape. Keep the existing rejection behavior, but make sure the throwable type is catchable by normal Exception handlers and clearly represents a recoverable missing-client condition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt`:
- Line 165: The missing-client rejection branches in ApiClientModuleImpl should
not use Error(...) because these are expected runtime failures; update the
Promise.reject calls in the client lookup paths (for example the logic around
getClient and related baseUrl checks) to use a regular exception such as
IllegalStateException, or a stable React Native error code/message shape. Keep
the existing rejection behavior, but make sure the throwable type is catchable
by normal Exception handlers and clearly represents a recoverable missing-client
condition.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d48fd336-88df-4c20-adc1-d6f800313a80
📒 Files selected for processing (2)
android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.ktandroid/src/test/java/com/mattermost/networkclient/WebSocketClientNullSafetyTest.kt
✅ Files skipped from review due to trivial changes (1)
- android/src/test/java/com/mattermost/networkclient/WebSocketClientNullSafetyTest.kt
|
Sorry about the force-push, that was unintentional. The 1 additional change was fixing all remaining outstanding similar code paths where a similar NPE could theoretically happen - JG, thanks for pointing that out. |
Summary
Fixes a
NullPointerExceptioncrash inWebSocketClientModuleImplaffecting 1,074 users (1,568 events) tracked in Sentry #7153287556.Root Cause
invalidateClientFor()used Kotlin's force-unwrap operator (!!) on a map lookup:When JS calls
invalidateClientForfor a URL that was never created or was already invalidated,clients[wsUri]returnsnulland!!throwsNullPointerException. This crashes the app because the call is not wrapped in try/catch.The same
!!pattern existed inconnectFor,disconnectFor,sendDataFor, andensureClientFor— those were wrapped in try/catch so they rejected the promise instead of crashing, but they still used unsafe patterns.Fix
invalidateClientFor: Safe access with?.let. Resolves the promise even if the client doesn't exist (idempotent — the desired end state is "no client", which is already true).connectFor,disconnectFor,sendDataFor: Explicit null checks with descriptive error messages viapromise.reject().ensureClientFor: ReplacedcontainsKey+!!with?.letpattern.All 5
!!non-null assertions onclients[wsUri]have been removed.Ticket Link
This was logged by Sentry on April 6, 2026:
https://mattermost.atlassian.net/browse/MM-68210
Release Note