Skip to content

chore(llc): cancel call operations on leave #1022

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 16, 2025

Conversation

Brazol
Copy link
Contributor

@Brazol Brazol commented Jul 10, 2025

resolves FLU-203

We want to make sure all ongoing operations (joining/reconnecting) are canceled when call.leave() is called. Also extracted a common internal method for get() and getOrCreate().

Summary by CodeRabbit

  • Bug Fixes

    • Improved call reliability by canceling ongoing or pending operations when a call is left, preventing unexpected behavior after leaving a call.
    • Enhanced error handling during call session start by detecting and responding to error events promptly.
  • Refactor

    • Streamlined internal logic for handling call operations, resulting in more consistent and stable call management.
    • Standardized and improved logging output formatting across call lifecycle events for clearer diagnostics.
    • Consolidated common call operation logic into reusable methods for better maintainability.
    • Enhanced logging system with conditional logging capabilities for more flexible and efficient log management.

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

coderabbitai bot commented Jul 10, 2025

Walkthrough

A private lifecycle completer was added to the Call class to signal when a call has ended. Multiple async methods now check this completer to abort if the call lifecycle is over. A new helper method consolidates coordinator "get" operations, and related methods were refactored to use it. The CallSession start method was updated to handle error events alongside join responses. Logging in the StateLifecycleMixin was refactored for consistency using a helper. Logger classes gained conditional logging capabilities, and minor cleanup was done in API extensions.

Changes

File(s) Change Summary
packages/stream_video/lib/src/call/call.dart Added _callLifecycleCompleter to manage call lifecycle; updated async methods to check lifecycle; refactored "get" logic into _performGetOperation.
packages/stream_video/lib/src/call/session/call_session.dart Modified start to await either join response or error event, handling errors explicitly.
packages/stream_video/lib/src/call/state/mixins/state_lifecycle_mixin.dart Refactored logging to use a private helper _logWithState for consistent message formatting and log levels.
packages/stream_video/lib/src/logger/impl/tagged_logger.dart Added logConditional method to support conditional logging based on priority.
packages/stream_video/lib/src/logger/stream_log.dart Added priority field; fixed log condition to use actual priority; added logConditional method for priority-aware logging.
packages/stream_video/lib/src/coordinator/open_api/open_api_extensions.dart Removed commented TODO and logging statement from toCallSettings() without changing logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Call
    participant Coordinator

    User->>Call: join()
    Call->>Call: check _callLifecycleCompleter
    alt Lifecycle active
        Call->>Coordinator: perform join
        Coordinator-->>Call: join result
    else Lifecycle ended
        Call-->>User: abort with error
    end

    User->>Call: leave()
    Call->>Call: _callLifecycleCompleter.complete()
    Note right of Call: All pending operations abort
Loading
sequenceDiagram
    participant CallSession
    participant SFU_WebSocket

    CallSession->>SFU_WebSocket: await SfuJoinResponseEvent or SfuErrorEvent (timeout)
    alt SfuErrorEvent received
        CallSession->>CallSession: log error
        CallSession-->>Caller: return failure result
    else SfuJoinResponseEvent received
        CallSession->>CallSession: proceed with join response processing
        CallSession-->>Caller: return success result
    end
Loading

Possibly related PRs

  • fix(llc): Leave call when failing to join #1005: Both PRs modify the internal join and leave logic of the Call class to improve handling of call lifecycle termination, with the main PR adding a lifecycle cancellation mechanism and the retrieved PR ensuring the call is left on join failure; thus, they are related.

  • chore(llc): improved sfu error handling in call flow #1004: Both PRs enhance the Call class lifecycle and error handling by managing leave state and improving SFU error handling; they share overlapping changes to join and leave logic.

Poem

A call begins, a call may end,
Now lifecycle rules we must defend.
With a completer’s gentle nudge,
No stray tasks left to begrudge.
Refactored "get", less code to sprawl—
Hopping forward, that’s one tidy call!
🐇✨


📜 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 c42c744 and f26db07.

📒 Files selected for processing (1)
  • packages/stream_video/lib/src/call/call.dart (16 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: stream_video_flutter
  • GitHub Check: analyze_legacy_version
  • GitHub Check: stream_video_noise_cancellation
  • GitHub Check: stream_video_push_notification
  • GitHub Check: stream_video
  • GitHub Check: stream_video_screen_sharing
  • GitHub Check: build
  • GitHub Check: analyze
🔇 Additional comments (17)
packages/stream_video/lib/src/call/call.dart (17)

289-291: LGTM: Lifecycle completer properly declared

The _callLifecycleCompleter is correctly declared as a final field and will be used to signal when the call lifecycle ends.


733-737: LGTM: Lifecycle check added in join flow

The check properly prevents joining if the call has already been left, with appropriate logging and error return.


759-763: LGTM: Lifecycle check added after coordinator join

The check correctly prevents session creation if the call was left during the joining process.


802-808: LGTM: Lifecycle check added after session creation

The check properly prevents session starting if the call was left during session creation.


941-945: LGTM: Lifecycle check added in join request

The check correctly prevents coordinator call execution if the call has been left.


1102-1106: LGTM: Lifecycle check added in session start

The check properly prevents session starting if the call was left during the process.


1255-1259: LGTM: Lifecycle check added in reconnect loop

The check correctly prevents reconnection attempts if the call has been left.


1279-1285: LGTM: Lifecycle check added during network wait

The check properly prevents reconnection if the call was left during network availability waiting.


1415-1439: LGTM: Improved network waiting with lifecycle cancellation

The refactored implementation correctly races the network future against the lifecycle completer, ensuring network waiting stops when the call is left. The use of Future.any properly handles early cancellation.


1469-1482: LGTM: Improved await logic with lifecycle cancellation

The refactored implementation correctly races the await future against the lifecycle completer, ensuring waiting operations stop when the call is left.


1493-1503: LGTM: Lifecycle completer completion on leave

The implementation correctly completes the lifecycle completer to signal cancellation of ongoing operations when leaving the call. The duplicate call protection is also appropriate.


1507-1510: LGTM: Logging adjustment in leave method

The logging level change from warning to debug is appropriate for this common scenario.


1533-1538: LGTM: Error handling added for stopAudioProcessing

The try-catch block properly handles exceptions during audio processing cleanup without failing the entire leave operation.


1555-1560: LGTM: Error handling added for session dispose

The try-catch block properly handles exceptions during session disposal without failing the entire cleanup operation.


1936-1964: LGTM: Well-designed helper method for coordinator operations

The _performGetOperation helper method effectively consolidates common logic between get and getOrCreate methods. The generic implementation handles event observation, coordinator calls, and call settings application consistently.


1974-2002: LGTM: Refactored get method using helper

The refactored get method properly uses the new _performGetOperation helper, reducing code duplication and improving maintainability.


2074-2102: LGTM: Refactored getOrCreate method using helper

The refactored getOrCreate method properly uses the new _performGetOperation helper, maintaining consistency with the get method implementation.


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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/stream_video/lib/src/call/call.dart (1)

733-737: Consider using more descriptive error messages for better debugging.

The error messages could be more specific to help with debugging when operations are cancelled at different stages.

   if (_callLifecycleCompleter.isCompleted) {
     _logger.w(() => '[join] rejected (call was left)');
-    return Result.error('call was left');
+    return Result.error('call was left before join could start');
   }

And for the second check:

   if (_callLifecycleCompleter.isCompleted) {
     _logger.w(() => '[join] rejected (call was left during joining)');
-    return Result.error('call was left');
+    return Result.error('call was left during join operation');
   }

Also applies to: 759-763

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 650befb and 5bfadf1.

📒 Files selected for processing (1)
  • packages/stream_video/lib/src/call/call.dart (14 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: build
  • GitHub Check: analyze
  • GitHub Check: stream_video_noise_cancellation
  • GitHub Check: stream_video_screen_sharing
  • GitHub Check: stream_video
  • GitHub Check: stream_video_flutter
  • GitHub Check: stream_video_push_notification
  • GitHub Check: analyze_legacy_version
🔇 Additional comments (6)
packages/stream_video/lib/src/call/call.dart (6)

289-291: LGTM! Good use of Completer for lifecycle management.

The _callLifecycleCompleter provides a clean way to signal and check for call termination across async operations.


1415-1440: Excellent implementation of cancellable network wait.

The use of Future.any to race the network status against the call lifecycle is a clean solution that prevents hanging operations when the call is terminated.


1927-1955: Well-designed helper method for consolidating coordinator operations.

The _performGetOperation method effectively eliminates code duplication between get() and getOrCreate() while maintaining flexibility through generics and callbacks.


1970-1994: Clean refactoring of the get method.

The method now properly leverages the _performGetOperation helper, improving code maintainability while preserving functionality.


2065-2092: Consistent refactoring of the getOrCreate method.

The method properly uses the _performGetOperation helper while maintaining all original functionality, including the outgoing call state management.


1498-1502: Confirm one-time use of Call instances after leave()

I ran a codebase search for any .join(), .get(), or .getOrCreate() calls following leave(), as well as tests reusing a Call after leave(), and found no occurrences. This indicates that Call instances are currently designed for one-time use.

• No .join()/.get() calls appear after leave()
• No tests reuse a Call instance post-leave

Please verify this matches the intended usage pattern. If reusability is required, consider exposing a way to reset or recreate the _callLifecycleCompleter before rejoining.

Copy link

codecov bot commented Jul 10, 2025

Codecov Report

Attention: Patch coverage is 37.38318% with 67 lines in your changes missing coverage. Please review.

Project coverage is 4.29%. Comparing base (650befb) to head (f26db07).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/stream_video/lib/src/call/call.dart 37.31% 42 Missing ⚠️
...b/src/call/state/mixins/state_lifecycle_mixin.dart 45.45% 12 Missing ⚠️
...tream_video/lib/src/call/session/call_session.dart 0.00% 8 Missing ⚠️
...ckages/stream_video/lib/src/logger/stream_log.dart 37.50% 5 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##            main   #1022      +/-   ##
========================================
+ Coverage   4.24%   4.29%   +0.05%     
========================================
  Files        574     574              
  Lines      38526   38577      +51     
========================================
+ Hits        1634    1658      +24     
- Misses     36892   36919      +27     

☔ 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 973a6db into main Jul 16, 2025
17 checks passed
@Brazol Brazol deleted the chore/cancel-call-operations-on-leave branch July 16, 2025 13:48
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