Skip to content

chore(llc): improved sfu error handling in call flow #1004

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 2, 2025

Conversation

Brazol
Copy link
Contributor

@Brazol Brazol commented Jul 2, 2025

Summary by CodeRabbit

  • New Features

    • Added the ability to control video mirroring for participants.
    • Improved tracking of disconnect reasons, enabling the disconnected call state to more accurately reflect the original cause.
  • Bug Fixes

    • Enhanced error handling during call flows, especially for SFU-related errors, to prevent unintended reconnections and provide clearer disconnect reasons.
  • Documentation

    • Updated changelogs to reflect new features and improvements.
  • Refactor

    • Centralized and streamlined disconnection logic for improved maintainability.
    • Adjusted logging levels for unexpected event types to reduce noise.
    • Improved handling of unknown enum values by returning safe defaults instead of throwing errors.

@Brazol Brazol requested a review from a team as a code owner July 2, 2025 13:44
Copy link

coderabbitai bot commented Jul 2, 2025

Walkthrough

The changes introduce improved SFU error handling and more precise disconnect reason tracking in the call flow. A new DisconnectReason.sfuError type is added, and the code now avoids reconnection attempts during intentional call leaves. Enum mapping extensions now return safe defaults instead of throwing errors, and disconnection logic is centralized.

Changes

File(s) Change Summary
packages/stream_video/CHANGELOG.md, packages/stream_video_flutter/CHANGELOG.md Updated changelogs to document SFU error handling improvements and new disconnect reason logic.
packages/stream_video/lib/src/call/call.dart Added _leaveCallTriggered flag, improved leave/join logic, explicit disconnect reasons, and SFU error handling.
packages/stream_video/lib/src/call/session/call_session.dart Added SDP presence check before calling setRemoteAnswer in renegotiation logic.
packages/stream_video/lib/src/call/state/mixins/state_lifecycle_mixin.dart Centralized disconnection logic, added guard for repeated disconnects, refactored timeout and failure handling.
packages/stream_video/lib/src/coordinator/open_api/event/open_api_event.dart Changed log level for unknown event types from error to debug.
packages/stream_video/lib/src/models/disconnect_reason.dart Added DisconnectReason.sfuError and corresponding class for SFU error disconnect reasons.
packages/stream_video/lib/src/sfu/data/events/sfu_event_mapper_extensions.dart Enum mapping extensions now return unspecified instead of throwing on unknown values.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Call
    participant SFU
    participant Logger

    User->>Call: join()
    alt Join fails
        Call->>Call: leave(reason: DisconnectReason.failure)
    end

    SFU-->>Call: SfuParticipantLeftEvent
    alt Last participant left & dropIfAlone
        Call->>Call: leave(reason: DisconnectReason.lastParticipantLeft)
    end

    SFU-->>Call: SfuSocketDisconnected
    alt _leaveCallTriggered is true
        Call->>Logger: Debug log (no reconnection)
    else _leaveCallTriggered is false
        Call->>Call: Attempt reconnection
    end

    SFU-->>Call: SfuErrorEvent (disconnect strategy)
    Call->>Call: leave(reason: DisconnectReason.sfuError)
Loading

Suggested reviewers

  • renefloor

Poem

In the warren where video calls hop,
SFU errors now cause fewer a flop.
Disconnections are clear, with reasons that show,
No more wild reconnections when it’s time to go.
Enum maps are gentle—no more surprise,
Just unspecified carrots for rabbitly wise! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f6e0f47 and 87d486e.

📒 Files selected for processing (8)
  • packages/stream_video/CHANGELOG.md (1 hunks)
  • packages/stream_video/lib/src/call/call.dart (6 hunks)
  • packages/stream_video/lib/src/call/session/call_session.dart (1 hunks)
  • packages/stream_video/lib/src/call/state/mixins/state_lifecycle_mixin.dart (2 hunks)
  • packages/stream_video/lib/src/coordinator/open_api/event/open_api_event.dart (1 hunks)
  • packages/stream_video/lib/src/models/disconnect_reason.dart (3 hunks)
  • packages/stream_video/lib/src/sfu/data/events/sfu_event_mapper_extensions.dart (4 hunks)
  • packages/stream_video_flutter/CHANGELOG.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
packages/stream_video_flutter/CHANGELOG.md

[duplication] ~17-~17: Possible typo: you repeated a word.
Context: ...alState. * Deprecated old callbacks ✅ Added * Added setMirrorVideomethod toCall` class...

(ENGLISH_WORD_REPEAT_RULE)

⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: analyze_legacy_version
  • GitHub Check: analyze
  • GitHub Check: build
  • GitHub Check: stream_video_screen_sharing
  • GitHub Check: stream_video_noise_cancellation
  • GitHub Check: stream_video_push_notification
  • GitHub Check: stream_video
  • GitHub Check: stream_video_flutter
🔇 Additional comments (21)
packages/stream_video/lib/src/coordinator/open_api/event/open_api_event.dart (1)

212-212: LGTM! Appropriate log level reduction for unknown events.

Changing from error to debug level is appropriate here. Unknown event types aren't necessarily errors - they could be new event types that this SDK version doesn't recognize yet. This reduces log noise while maintaining debug visibility.

packages/stream_video/CHANGELOG.md (1)

7-9: Well-documented bug fix entry.

The changelog entry clearly describes the SFU error handling improvements and provides valuable context about the disconnected call state accuracy improvements.

packages/stream_video_flutter/CHANGELOG.md (2)

17-19: Clear documentation for new feature.

The setMirrorVideo method addition is well-documented with a clear description of its functionality.


20-22: Consistent bug fix documentation.

The SFU error handling improvement is consistently documented across both packages, providing users with clear information about the enhanced disconnect reason handling.

packages/stream_video/lib/src/call/session/call_session.dart (1)

859-864: Excellent defensive programming improvement!

The conditional SDP check prevents potential runtime errors when pubResult.data doesn't contain SDP data. This aligns well with the improved SFU error handling objective and follows good defensive programming practices.

packages/stream_video/lib/src/sfu/data/events/sfu_event_mapper_extensions.dart (4)

253-253: Excellent improvement in error handling resilience!

Replacing StateError throws with safe fallback returns makes the enum mapping more robust against unexpected SFU responses. This prevents crashes and allows the application to gracefully handle unknown enum values.


268-268: Consistent safe fallback pattern applied.

Good consistency with the other enum extensions - returning unspecified instead of throwing errors.


287-287: Safe fallback handling maintained across all enum types.

Consistent application of the safe fallback pattern for call ended reasons.


306-306: Completes the consistent error handling pattern.

Final enum extension properly handles unknown values with safe fallback to unspecified.

packages/stream_video/lib/src/models/disconnect_reason.dart (3)

6-6: Appropriate import added for the new functionality.

The SfuError import is correctly placed and necessary for the new DisconnectReasonSfuError class.


18-20: Well-designed factory constructor follows existing patterns.

The sfuError factory constructor maintains consistency with other disconnect reason factory constructors and provides a clean API for creating SFU error disconnections.


76-88: Complete and well-implemented DisconnectReasonSfuError class.

The implementation properly:

  • Follows the same pattern as other DisconnectReason subtypes
  • Correctly implements props for Equatable comparison
  • Provides meaningful toString output
  • Uses const constructor for immutability
packages/stream_video/lib/src/call/state/mixins/state_lifecycle_mixin.dart (3)

169-174: Excellent guard clause prevents redundant state updates.

The early return with warning log prevents unnecessary state mutations when the call is already disconnected. This defensive approach improves robustness and provides helpful debugging information.


197-197: Good refactoring to centralize disconnection logic.

Delegating to lifecycleCallDisconnected with the specific timeout reason eliminates code duplication and ensures consistent disconnection handling.


200-205: Consistent centralization pattern applied.

The refactoring maintains the same beneficial pattern - delegating to the centralized disconnection method with appropriate error context while eliminating code duplication.

packages/stream_video/lib/src/call/call.dart (6)

286-286: LGTM! Clean state tracking addition.

The new _leaveCallTriggered field follows proper naming conventions and provides clear intent for tracking the leave call process.


677-681: Excellent improvement to error handling.

The enhanced error handling now properly captures and propagates the failure reason when leaving after a failed join operation, providing better debugging context and disconnect reason tracking.


1143-1143: Good addition of specific disconnect reason.

Adding the DisconnectReason.lastParticipantLeft() provides clear context for why the call was left in this scenario, improving the overall disconnect reason tracking.


1158-1169: Excellent prevention of unwanted reconnections.

The addition of the _leaveCallTriggered check prevents reconnection attempts during intentional call leaves, avoiding potential race conditions. The debug logging and logical flow are well-structured.


1193-1193: Great addition of SFU error context.

Passing the DisconnectReason.sfuError(sfuEvent.error) provides specific error details for debugging and improves the overall disconnect reason tracking consistency.


1422-1446: Excellent flag management with proper exception safety.

The nested try-finally structure ensures the _leaveCallTriggered flag is properly reset even if exceptions occur during the leave process. This prevents the flag from getting stuck in a true state, which could cause issues with future reconnection attempts.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jul 2, 2025

Codecov Report

Attention: Patch coverage is 0% with 39 lines in your changes missing coverage. Please review.

Project coverage is 4.16%. Comparing base (f6e0f47) to head (87d486e).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/stream_video/lib/src/call/call.dart 0.00% 21 Missing ⚠️
...b/src/call/state/mixins/state_lifecycle_mixin.dart 0.00% 7 Missing ⚠️
...stream_video/lib/src/models/disconnect_reason.dart 0.00% 5 Missing ⚠️
...tream_video/lib/src/call/session/call_session.dart 0.00% 4 Missing ⚠️
...src/coordinator/open_api/event/open_api_event.dart 0.00% 1 Missing ⚠️
...c/sfu/data/events/sfu_event_mapper_extensions.dart 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##            main   #1004      +/-   ##
========================================
- Coverage   4.16%   4.16%   -0.01%     
========================================
  Files        573     573              
  Lines      38508   38513       +5     
========================================
  Hits        1604    1604              
- Misses     36904   36909       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Brazol Brazol merged commit f26cefa into main Jul 2, 2025
14 of 15 checks passed
@Brazol Brazol deleted the chore/better-sfu-error-handling branch July 2, 2025 14:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants