Skip to content
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

Change Client, Document actor to class #187

Merged
merged 2 commits into from
Jul 17, 2024
Merged

Change Client, Document actor to class #187

merged 2 commits into from
Jul 17, 2024

Conversation

humdrum
Copy link
Contributor

@humdrum humdrum commented Jul 17, 2024

What this PR does / why we need it:

  • Change Client and Document from actor to class
  • Refactor for loop to for-in to speed

The client and document generated by the factor should be called asynchronously.
In this case, it cannot be used for a structure that must be handled synchronously by the main thread.

Which issue(s) this PR fixes:

Fixes #

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • Refactor

    • Transitioned Client struct to a class and improved initialization and sync handling.
    • Converted Document from an actor to a class with enhanced property and method structures.
    • Refactored CRDTTree for better readability and performance.
    • Updated IndexTree to use more expressive constructs for iterations.
  • Tests

    • Simplified logic in DocumentTests by removing unnecessary nested Task blocks.

@humdrum humdrum self-assigned this Jul 17, 2024
Copy link
Contributor

coderabbitai bot commented Jul 17, 2024

Walkthrough

The recent updates primarily involve transitioning core structures from actors to classes, refining initialization processes, and enhancing method handling. These changes aim to improve performance, readability, and synchronization logic in document management. Additionally, various methods were modified to remove asynchronous behavior, aligning with the new design approach.

Changes

Files Change Summary
Sources/Core/Client.swift Modified Client from struct to class, adjusted initializations, removed asynchronous keywords, and updated synchronization logic.
Sources/Document/CRDT/CRDTTree.swift Refactored loops to use more concise constructs for better readability and potential performance enhancements.
Sources/Document/Document.swift Converted Document to class with @MainActor, adjusted properties and methods, and introduced new initializers.
Sources/Util/IndexTree.swift Refactored loops using more concise constructs like prefix(upTo:) and path.dropLast() for better readability and performance.
Tests/Unit/Document/DocumentTests.swift Simplified test logic by removing nested Task block, directly asserting values in a path query.

Poem

In the land of code, a change so grand,
From structs to classes, a new stand.
Async no more, sync we adore,
With loops refined, we explore.
Document and Client, now aligned,
Our code shines bright, so well-defined.
Cheers to the team, a job well-done,
A rabbit's hop, the race is won! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @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.

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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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 17, 2024

Codecov Report

Attention: Patch coverage is 37.50000% with 40 lines in your changes missing coverage. Please review.

Project coverage is 45.11%. Comparing base (62bd08f) to head (228921a).

Files Patch % Lines
Sources/Core/Client.swift 0.00% 39 Missing ⚠️
Sources/Document/Document.swift 93.75% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #187      +/-   ##
==========================================
- Coverage   45.13%   45.11%   -0.03%     
==========================================
  Files         105      105              
  Lines       19333    19320      -13     
==========================================
- Hits         8726     8716      -10     
+ Misses      10607    10604       -3     

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

Copy link
Contributor

@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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 62bd08f and 228921a.

Files selected for processing (5)
  • Sources/Core/Client.swift (16 hunks)
  • Sources/Document/CRDT/CRDTTree.swift (2 hunks)
  • Sources/Document/Document.swift (5 hunks)
  • Sources/Util/IndexTree.swift (3 hunks)
  • Tests/Unit/Document/DocumentTests.swift (1 hunks)
Additional comments not posted (23)
Sources/Document/Document.swift (9)

73-74: Change from actor to class is approved.

The transition from actor to @MainActor class is correctly implemented, ensuring that instances of Document are still confined to the main actor's context, which is crucial for UI-related operations in iOS.


75-75: Change in SubscribeCallback type.

The change from using isolated Document to Document in the SubscribeCallback type is consistent with the actor-to-class transition. This modification ensures that the callback can still be executed on the main actor without requiring isolation, which is necessary due to the class not supporting isolation like actors.


78-89: Initialization of properties inline.

Initializing properties inline (e.g., status, changeID, checkpoint, localChanges, root, subscribeCallbacks, presenceSubscribeCallback) is a good practice as it ensures that all instances start with a known state, reducing the potential for bugs related to uninitialized properties.


96-96: Initialization of onlineClients.

The change to initialize onlineClients inline ensures that the property is never nil, which simplifies the usage of this property throughout the class by removing the need to check for nil before use.


101-101: Refactor of initializers.

Changing public init(key: String) to public convenience nonisolated init(key: String) and adjusting the call to another initializer within the same class is a good practice. It simplifies the initialization process by centralizing common initialization steps in one initializer, reducing code duplication.


107-109: Use of nonisolated in initializers.

Marking the initializer as nonisolated allows it to be called from any context, not just the main actor, which increases the flexibility of how instances of Document can be created.


Line range hint 115-136: Refactor of update method to synchronous.

Removing async from the update method and its internal logic is consistent with the PR's goal to make Document operations synchronous. This change should ensure that updates to the document are immediate and predictable, which is often required when dealing with UI elements that should update synchronously with user interactions.


245-245: Refactor of applyChangePack method to synchronous.

The change from async throws to throws in the applyChangePack method aligns with the overall goal of making document operations synchronous. This adjustment should help in scenarios where immediate feedback or state update is necessary after applying changes.


367-367: Optimization in garbageCollect method.

The addition of a condition to check disableGC before performing garbage collection is a good optimization. It avoids unnecessary processing when garbage collection is disabled, which can improve performance.

Tests/Unit/Document/DocumentTests.swift (1)

741-743: Simplify test structure by removing nested Task blocks.

The changes made remove unnecessary complexity, aligning with the PR's objectives to simplify and enhance synchronization logic.

Sources/Document/CRDT/CRDTTree.swift (2)

624-624: Refactor of loop using suffix(from:) and for-in loop approved.

The refactoring of the loop to use suffix(from:) and a for-in loop improves readability and potentially enhances performance by leveraging Swift's built-in functions.

Verify side effects of loop refactoring.
Ensure that the refactoring does not introduce any side effects, especially in edge cases where the loop might behave differently.

Verification successful

Refactor of loop using suffix(from:) and for-in loop approved.

The refactoring of the loop to use suffix(from:) and a for-in loop improves readability and potentially enhances performance by leveraging Swift's built-in functions.

  • The existing test functions in JSONTextTest.swift indirectly verify the behavior of the findNodesAndSplitText method through various operations on JSONText objects.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the loop behavior by checking the unit tests related to this method.

# Test: Search for the unit tests related to `findNodesAndSplitText`.
rg --type swift -A 10 $'func findNodesAndSplitText'

Length of output: 1062


Script:

#!/bin/bash
# Description: Search for unit tests related to `findNodesAndSplitText` in the entire codebase.

# Test: Search for the term `findNodesAndSplitText` in test files.
rg --type swift -g '*Test.swift' 'findNodesAndSplitText'

Length of output: 56


Script:

#!/bin/bash
# Description: Search for test functions in the test files and analyze their content to identify any indirect tests for `findNodesAndSplitText`.

# Test: Search for test functions in Swift test files.
rg --type swift -g '*Test.swift' 'func test'

Length of output: 1072


Script:

#!/bin/bash
# Description: Extract the content of identified test functions and check for any references to `findNodesAndSplitText`.

# Extract the content of the test functions.
rg --type swift -g 'JSONTextTest.swift' -A 20 'func test_should_handle'

Length of output: 15737


1143-1143: Refactor of loop using enumerated() approved.

The use of enumerated() in the loop simplifies the access to both the index and the value, enhancing readability and maintainability.

Verify side effects of loop refactoring using enumerated().
Ensure that the use of enumerated() does not introduce any unintended side effects, especially in edge cases.

Sources/Core/Client.swift (8)

130-130: Change from actor to class noted.

The change from actor to class for Client aligns with the PR's description to handle synchronous operations on the main thread.


131-131: Initialization of properties within the class.

Inline initialization of properties like attachmentMap and various timing configurations ensures that all instances of Client start with a defined state, which is crucial for classes to avoid uninitialized state issues.


145-145: Initialization of status property.

Initializing the status property inline is a good practice as it ensures that every instance of Client has a predictable initial state.


170-170: Use of convenience initializer.

Changing to a convenience initializer that calls another initializer is a standard practice in Swift for providing multiple pathways to initialize an object. This change is well-implemented.


241-241: Handling document attachment logic.

The changes in document attachment logic, specifically the checks and status updates, are crucial for ensuring that documents are managed correctly in the new synchronous context.

Also applies to: 269-269, 273-273


315-315: Handling document detachment logic.

The logic for detaching documents, including status checks and exception handling, appears correctly implemented to ensure that documents are detached properly.

Also applies to: 322-322, 333-333, 336-336


536-536: Watch loop adjustments.

The modifications to the watch loop management, specifically the handling of document watching and event responses, are crucial for maintaining the integrity of document synchronization.

Also applies to: 586-586


696-696: Push-pull synchronization adjustments.

The changes to how documents are synchronized with the server, including error handling and status updates, are well-implemented. It's important to ensure that these changes work seamlessly with the rest of the system to maintain data consistency.

Also applies to: 720-720, 726-726, 733-733

Sources/Util/IndexTree.swift (3)

96-96: Refactoring of loop in addSizeOfLeftSiblings.

Using prefix(upTo:) to iterate over left siblings is a more efficient approach than the previous method, likely improving performance by avoiding unnecessary iterations.


751-751: Refactoring of loop in findTextPos.

Iterating directly over node.children simplifies the logic and potentially improves the readability and performance of the function.


858-858: Refactoring of path iteration in pathToTreePos.

Using dropLast() to iterate over path elements is a cleaner and potentially more efficient approach than manually managing indices. This change likely improves both performance and readability.


/**
* @param rpcAddr - the address of the RPC server.
* @param opts - the options of the client.
*/
public init(_ urlString: String, _ options: ClientOptions = ClientOptions()) {
public nonisolated init(_ urlString: String, _ options: ClientOptions = ClientOptions()) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Marking initializer as nonisolated.

Since Client is no longer an actor, marking the initializer as nonisolated allows it to be called from any thread context, which is necessary for synchronous operations but requires careful management to avoid race conditions.

Consider ensuring that all accesses to mutable state within Client are thread-safe, possibly using synchronization mechanisms like locks or serial queues.

@@ -400,7 +398,7 @@ public actor Client {
* `changeSyncMode` changes the synchronization mode of the given document.
*/
@discardableResult
public func changeSyncMode(_ doc: Document, _ syncMode: SyncMode) async throws -> Document {
public func changeSyncMode(_ doc: Document, _ syncMode: SyncMode) throws -> Document {
Copy link
Contributor

Choose a reason for hiding this comment

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

Modification of synchronization mode handling.

The removal of asynchronous handling in changeSyncMode and adjustments to the synchronization logic are significant. It's essential to ensure that these changes do not introduce any unintended behaviors or race conditions, especially since synchronization settings are critical for the correct operation of the client.

Verify that the new synchronization logic correctly handles all edge cases and that there are no race conditions introduced by these changes.

Also applies to: 431-431

@humdrum humdrum merged commit 6860357 into main Jul 17, 2024
3 checks passed
@humdrum humdrum deleted the main_actor branch July 17, 2024 08:46
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