Skip to content

[ECO-5225] Subscribe without attach fix - #258

Closed
umair-ably wants to merge 2 commits into
mainfrom
ECO-5225-subscribeonattachfix
Closed

[ECO-5225] Subscribe without attach fix#258
umair-ably wants to merge 2 commits into
mainfrom
ECO-5225-subscribeonattachfix

Conversation

@umair-ably

@umair-ably umair-ably commented Apr 3, 2025

Copy link
Copy Markdown
Contributor

Fixes an issue in which a Message subscription would not return if the underlying channel was not already attached.

@maratal - this is the fix that seemed to have helped with failing/flaky tests

Summary by CodeRabbit

  • New Features

    • Enhanced message subscription handling now operates asynchronously, improving update and removal processes during messaging sessions.
  • Refactor

    • Overhauled the underlying subscription management logic to provide a more robust, thread-safe experience during channel interactions and termination.

…e underlying channel was not already attached
@umair-ably
umair-ably requested a review from maratal April 3, 2025 15:16
@coderabbitai

coderabbitai Bot commented Apr 3, 2025

Copy link
Copy Markdown

Walkthrough

This change refactors the subscription management in the default messages module. It replaces a dictionary holding MessageSubscriptionWrapper instances with a new actor, SubscriptionStore, to manage subscriptions asynchronously and in a thread-safe manner. Key methods and properties in the subscription flow, including resolveSubscriptionStart and subscribe, have been updated to integrate the new store. The modifications also adjust the handling of subscription serial values and update the removal logic during termination and channel attachment.

Changes

File Change Summary
Sources/AblyChat/.../DefaultMessages.swift (SubscriptionStore and Wrapper) Replaced the private dictionary subscriptionPoints with an actor-based SubscriptionStore. Updated the MessageSubscriptionWrapper struct with an optional serial property. Added asynchronous methods: addSubscription(uuid:subscription:), setSerial(uuid:serial:), removeSubscription(uuid:), and getSubscription(uuid:).
Sources/AblyChat/.../DefaultMessages.swift (Implementation) Updated method signature of resolveSubscriptionStart to accept a UUID and removed its string return. Integrated the new subscriptionStore instance into subscription logic within methods like subscribe, and modified termination and reset handling to use the actor asynchronously.

Sequence Diagram(s)

sequenceDiagram
    participant Impl as Implementation
    participant Store as SubscriptionStore

    Impl->>Store: addSubscription(uuid, subscription)
    Impl->>Store: resolveSubscriptionStart(for: uuid)
    Store->>Store: setSerial(uuid, newSerial)
    Note over Impl,Store: Subscription updates occur asynchronously.
    Impl->>Store: removeSubscription(uuid) [on termination/channel re-attach]
Loading

Assessment against linked issues

Objective Addressed Explanation
room.messages.subscribe() returns immediately when channel is not attached ECO-5225

Suggested reviewers

  • umair-ably
  • lawrence-forooghian

Poem

In the code garden where data hops free,
I, a little rabbit, dance with glee.
The subscriptions now skip with graceful ease,
Managed by an actor, designed to please.
A whisker-twitch cheer for changes so bright,
Hopping along in the realm of async light!
🐇✨


📜 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 3e9ab65 and 28dfd17.

📒 Files selected for processing (1)
  • Sources/AblyChat/DefaultMessages.swift (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Sources/AblyChat/DefaultMessages.swift
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: check-documentation
  • GitHub Check: generate-matrices
  • GitHub Check: spec-coverage
  • GitHub Check: Generate code coverage
  • GitHub Check: lint
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch ECO-5225-subscribeonattachfix
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests for 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.

@github-actions
github-actions Bot temporarily deployed to staging/pull/258/AblyChat April 3, 2025 15:17 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
Sources/AblyChat/DefaultMessages.swift (1)

83-84: Ensure robust error handling during subscription start
By adding the subscription first (addSubscription) and then attempting to start it (resolveSubscriptionStart), the workflow is logical. However, if resolveSubscriptionStart fails, consider removing or cleaning up the partially added subscription to avoid inconsistent states.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 94d96d7 and 3e9ab65.

📒 Files selected for processing (1)
  • Sources/AblyChat/DefaultMessages.swift (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Generate code coverage (Xcode 16.2)
  • GitHub Check: Example app, tvOS (Xcode 16.2)
  • GitHub Check: Example app, iOS (Xcode 16.2)
  • GitHub Check: Example app, macOS (Xcode 16.2)
  • GitHub Check: Xcode, tvOS (Xcode 16.2)
  • GitHub Check: Xcode, release configuration, tvOS (Xcode 16.2)
  • GitHub Check: Xcode, iOS (Xcode 16.2)
  • GitHub Check: SPM (Xcode 16.2)
  • GitHub Check: Xcode, release configuration, iOS (Xcode 16.2)
  • GitHub Check: Xcode, macOS (Xcode 16.2)
  • GitHub Check: Xcode, release configuration, macOS (Xcode 16.2)
  • GitHub Check: SPM, release configuration (Xcode 16.2)
🔇 Additional comments (8)
Sources/AblyChat/DefaultMessages.swift (8)

57-57: Good introduction of a shared subscription store
Storing a shared SubscriptionStore at the implementation level is a clear, modular approach to centralizing subscription logic. This actor-based design also helps ensure thread safety.


156-158: Proper resource cleanup on termination
Placing the subscription removal in a Task block ensures it runs asynchronously without blocking the termination handler. This is a good pattern. Consider logging or handling errors if future store operations become fallible.


207-207: Graceful handling of nonexistent subscriptions
The guard let statement ensures that attempting to fetch history for an unregistered subscription results in an error. This is a clear and defensive approach that prevents further complications.


260-262: Bulk reset on channel attach
Looping through all subscriptions to reset their serials is correct for handling non-resumed attaches. The actor-based store is consistently accessed via await, ensuring safe concurrency.


270-270: Expanded method signature clarifies usage
Renaming the method to resolveSubscriptionStart(for:) is more descriptive and clearly indicates it operates on a specific subscription.


276-277: Immediate return after setting serial
Once the serial is successfully set, returning early prevents unnecessary code execution. This clean control flow is a good practice for improved readability.


368-372: Well-defined wrapper for subscription and serial
Encapsulating both the MessageSubscription and its potentially nil serial in one struct nicely centralizes state. This keeps the code flexible for handling subscriptions that do not yet have an attach serial.


374-395: Actor-based subscription storage
Introducing an actor for subscription storage is a robust solution. It ensures all modifications to the subscriptions dictionary are thread-safe. Additional logs when adding/removing subscriptions could provide useful debugging context but are optional.

Comment on lines +287 to +288
try await subscriptionStore.setSerial(uuid: uuid, serial: serialOnChannelAttach())
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle potential errors from serialOnChannelAttach()
Spawning a separate Task to set the serial is fine, but the thrown errors inside this Task block are not caught. Without additional error handling or logging, failures may be silently ignored and hamper troubleshooting.

 Task {
-    try await subscriptionStore.setSerial(uuid: uuid, serial: serialOnChannelAttach())
+    do {
+        let attachSerial = try await serialOnChannelAttach()
+        await subscriptionStore.setSerial(uuid: uuid, serial: attachSerial)
+    } catch {
+        logger.log(message: "Failed to set serial: \(error)", level: .error)
+    }
 }

Committable suggestion skipped: line range outside the PR's diff.

@lawrence-forooghian
lawrence-forooghian self-requested a review April 3, 2025 17:24
Comment thread Sources/AblyChat/DefaultMessages.swift

@maratal maratal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Those two still fail because getPreviousMessages doesn't pickup attachSerial since it doesn't wait until handleChannelEvents resolves it.

@maratal

maratal commented Apr 10, 2025

Copy link
Copy Markdown
Contributor

@umair-ably ^^

@maratal

maratal commented Apr 11, 2025

Copy link
Copy Markdown
Contributor

See #249 (comment)

@maratal

maratal commented May 12, 2025

Copy link
Copy Markdown
Contributor

@umair-ably couldn't you resolve conflicts?

@maratal maratal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Left a question

Comment thread Sources/AblyChat/DefaultMessages.swift
@umair-ably

Copy link
Copy Markdown
Contributor Author

@umair-ably couldn't you resolve conflicts?

sure thing, i'll just wrap up the docs needed for the single channel release

@maratal
maratal self-requested a review May 13, 2025 21:53

@maratal maratal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@lawrence-forooghian

Copy link
Copy Markdown
Contributor

@maratal if you're happy with this please can you resolve conflicts and merge?

…ttachfix

# Conflicts:
#	Sources/AblyChat/DefaultMessages.swift
@maratal

maratal commented Jun 13, 2025

Copy link
Copy Markdown
Contributor

Check / SPM (Xcode 16.1) (pull_request) hanged, so I think it should be merged after #295 resolved @lawrence-forooghian

@maratal

maratal commented Jul 7, 2025

Copy link
Copy Markdown
Contributor

Fixed in #318

@maratal maratal closed this Jul 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

room.messages.subscribe() doesn't return until channel becomes attached

4 participants