Skip to content

Conversation

@lawrence-forooghian
Copy link
Collaborator

@lawrence-forooghian lawrence-forooghian commented Jul 8, 2025

Note: This PR is based on top of #22; please review that one first.

Implements the behaviours specified in ably/specification#343, except for buffering during a sync, which we have a separate task for. See commit messages for more details.

Summary by CodeRabbit

  • New Features

    • Improved handling and application of object protocol messages, including structured and logged processing of map and counter operations.
    • Enhanced thread safety for object message processing.
    • Unified and centralized mutable state management for live objects.
    • Added detailed logging throughout object creation and operation application.
  • Bug Fixes

    • Ensured consistent logging capability during object creation and operation handling.
  • Tests

    • Expanded and refactored test coverage for map and counter operations, including initial value merging, operation application, and edge cases.
    • Added comprehensive tests for protocol message handling and operation applicability logic.
    • Introduced new test factories for streamlined creation of test objects and operations.
  • Chores

    • Updated all test cases to use explicit logger parameters for improved traceability.

This is based on the values stated in RTOL3 of [1] at 29276a5. (We'll
formalise the fact that these are common LiveObject properties in an
upcoming commit.)

[1] ably/specification#343
All done by Cursor at my instruction.
Based on [1] at 29276a5. Development approach as described in cb427d8.

[1] ably/specification#343
This applies the changes from [1] at 29276a5. Development approach as
described in cb427d8.

[1] ably/specification#343
@github-actions github-actions bot temporarily deployed to staging/pull/23/AblyLiveObjects July 8, 2025 21:34 Inactive
Based on [1] at 29276a5. I wrote the implementation, and for the tests
followed the development approach described in cb427d8.

We have a separate issue for applying RTO8a's buffering during a sync,
so I haven't done that here.

[1] ably/specification#343
@umair-ably
Copy link
Collaborator

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Jul 24, 2025

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link

coderabbitai bot commented Jul 24, 2025

Walkthrough

This change set introduces robust, thread-safe, and logged handling of OBJECT protocol messages and object operations in AblyLiveObjects. It centralizes mutable state management for live objects, refactors creation and application logic for maps and counters, and propagates logging throughout. Extensive new and updated tests provide comprehensive coverage of operation application, state transitions, and protocol compliance.

Changes

File(s) Change Summary
Sources/AblyLiveObjects/DefaultRealtimeObjects.swift Enhanced OBJECT protocol message handling, mutex protection, delegated processing, and detailed logging.
Sources/AblyLiveObjects/Internal/DefaultLiveCounter.swift Refactored state to use LiveObjectMutableState, added logger, implemented operation application logic, and test-only helpers.
Sources/AblyLiveObjects/Internal/DefaultLiveMap.swift Refactored state to LiveObjectMutableState, added logger, structured create/merge/apply logic, and improved operation handling.
Sources/AblyLiveObjects/Internal/LiveObjectMutableState.swift Introduced new struct for live object mutable state, with RTLO4a-compliant operation applicability logic.
Sources/AblyLiveObjects/Internal/ObjectsPool.swift Added logger propagation, standardized zero-value object creation, and unified operation application interface for pool entries.
Tests/AblyLiveObjectsTests/DefaultLiveCounterTests.swift Major test expansion: operation application, merge logic, flags, and state transitions for counters.
Tests/AblyLiveObjectsTests/DefaultLiveMapTests.swift Major test expansion: operation application, merge logic, flags, and state transitions for maps; logging integrated in all tests.
Tests/AblyLiveObjectsTests/DefaultRealtimeObjectsTests.swift Added new tests for OBJECT protocol message handling and operation application, covering RTO8/RTO9.
Tests/AblyLiveObjectsTests/Helpers/TestFactories.swift Added factory methods for specific inbound object operation messages to support new tests.
Tests/AblyLiveObjectsTests/LiveObjectMutableStateTests.swift New tests for LiveObjectMutableState operation applicability logic (RTLO4).
Tests/AblyLiveObjectsTests/ObjectsPoolTests.swift Updated all tests to use logger and explicit object IDs; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DefaultRealtimeObjects
    participant Mutex
    participant MutableState
    participant ObjectsPool
    participant Logger

    Client->>DefaultRealtimeObjects: Receive OBJECT protocol message
    DefaultRealtimeObjects->>Mutex: Lock
    Mutex-->>DefaultRealtimeObjects: Locked
    DefaultRealtimeObjects->>MutableState: handleObjectProtocolMessage(messages)
    MutableState->>Logger: Log receipt
    MutableState->>ObjectsPool: For each message, apply operation
    ObjectsPool->>Logger: Log object creation/warnings
    ObjectsPool->>ObjectsPool: Create or fetch object as needed
    ObjectsPool->>ObjectsPool: Apply operation to object (map/counter)
    MutableState->>Logger: Log operation results
    DefaultRealtimeObjects->>Mutex: Unlock
    Mutex-->>DefaultRealtimeObjects: Unlocked
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇✨
In the warren of objects, a message arrives,
With mutex and logger, the logic survives.
Maps and counters now merge with care,
Each operation applied with a rabbit’s flair.
Tests multiply, coverage grows,
In burrows of code, the confidence shows!
— CodeRabbit

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ECO-5333-apply-OBJECT

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 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.

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 (2)
Sources/AblyLiveObjects/Internal/DefaultLiveMap.swift (2)

247-271: Test methods properly implemented with thread safety.

The test-only methods correctly delegate to mutableState while maintaining thread safety. Consider whether these could be tested through public APIs instead of exposing internal methods.


579-603: MAP_CREATE operation handler correctly prevents duplicates.

The implementation properly checks for already-merged CREATE operations and logs appropriately. Note the TODO for semantics comparison (RTLM16c) that needs to be addressed.

Would you like me to open an issue to track the TODO for implementing the semantics comparison?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d881e2 and 6430358.

📒 Files selected for processing (11)
  • Sources/AblyLiveObjects/DefaultRealtimeObjects.swift (5 hunks)
  • Sources/AblyLiveObjects/Internal/DefaultLiveCounter.swift (3 hunks)
  • Sources/AblyLiveObjects/Internal/DefaultLiveMap.swift (11 hunks)
  • Sources/AblyLiveObjects/Internal/LiveObjectMutableState.swift (1 hunks)
  • Sources/AblyLiveObjects/Internal/ObjectsPool.swift (5 hunks)
  • Tests/AblyLiveObjectsTests/DefaultLiveCounterTests.swift (5 hunks)
  • Tests/AblyLiveObjectsTests/DefaultLiveMapTests.swift (23 hunks)
  • Tests/AblyLiveObjectsTests/DefaultRealtimeObjectsTests.swift (1 hunks)
  • Tests/AblyLiveObjectsTests/Helpers/TestFactories.swift (2 hunks)
  • Tests/AblyLiveObjectsTests/LiveObjectMutableStateTests.swift (1 hunks)
  • Tests/AblyLiveObjectsTests/ObjectsPoolTests.swift (11 hunks)
🔇 Additional comments (41)
Tests/AblyLiveObjectsTests/ObjectsPoolTests.swift (3)

11-11: LGTM: Consistent logger integration in tests

The addition of TestLogger() instances throughout the test methods properly supports the enhanced logging capabilities introduced in the production code. The changes are mechanical and maintain test integrity.

Also applies to: 25-25, 45-45, 63-63, 75-75


14-15: LGTM: Proper parameter passing for updated constructors

The tests correctly pass the required logger parameter to the updated constructors and factory methods. The changes maintain compatibility with the enhanced production code signatures.

Also applies to: 28-28, 48-48, 66-66, 78-78


17-17: LGTM: Consistent method signature updates

All method calls are updated to include the new logger parameter, ensuring comprehensive test coverage of the logging functionality introduced across the codebase.

Also applies to: 30-30, 50-50, 68-68, 80-80

Tests/AblyLiveObjectsTests/LiveObjectMutableStateTests.swift (1)

1-117: Excellent comprehensive test coverage for LiveObjectMutableState

This test suite provides thorough coverage of the canApplyOperation method with well-structured parameterized tests. The test cases cover all the RTLO4 specification points including:

  • Invalid serial/siteCode validation (RTLO4a3-4)
  • Missing/empty siteSerial handling (RTLO4a5)
  • Lexicographical comparison logic (RTLO4a6)

The use of a TestCase struct with descriptive names makes the tests highly maintainable and clear about what each scenario validates.

Sources/AblyLiveObjects/Internal/LiveObjectMutableState.swift (3)

6-13: Well-structured mutable state container

The LiveObjectMutableState struct effectively centralizes the common mutable state properties (objectID, siteTimeserials, createOperationIsMerged) that are shared across live object implementations. The properties correctly map to the RTLO3 specification points.


17-20: Good design choice for ApplicableOperation

The ApplicableOperation struct is a clean way to return both the decision (can apply) and the validated parameters (non-nil serial and siteCode) needed for subsequent operation processing. This avoids duplicate validation logic downstream.


25-49: Solid implementation of operation applicability logic

The canApplyOperation method correctly implements the RTLO4a specification with:

  • Proper validation of serial and siteCode (RTLO4a3)
  • Appropriate warning logging for invalid inputs
  • Correct handling of missing/empty siteSerial (RTLO4a5)
  • Accurate lexicographical comparison (RTLO4a6)

The guard clauses make the logic clear and prevent invalid operations from proceeding.

Tests/AblyLiveObjectsTests/DefaultRealtimeObjectsTests.swift (1)

668-926: Comprehensive test coverage for OBJECT protocol message handling

The new HandleObjectProtocolMessageTests suite provides excellent coverage of the RTO8 and RTO9 specification points:

Strengths:

  • Well-organized nested structure separating different test concerns
  • Realistic test setup using sync messages to establish initial state
  • Proper verification of side effects (updated values, site timeserials, merge flags)
  • Coverage of all major operation types (MAP_CREATE, MAP_SET, MAP_REMOVE, COUNTER_CREATE, COUNTER_INC)
  • Clear test naming and documentation with spec references

Good testing practices:

  • Tests verify both object creation (RTO9a2a1) and operation application (RTO9a2a3)
  • Each test establishes known initial state before applying operations
  • Side effects are checked to ensure operations are properly applied
  • Proper use of test factories for creating consistent test data

The test structure effectively validates the new operation application logic introduced in the pull request.

Sources/AblyLiveObjects/Internal/ObjectsPool.swift (4)

32-55: Well-designed operation delegation method

The new apply method in the Entry enum provides clean delegation to the underlying live object types. The method signature properly passes through all necessary parameters including the mutable ObjectsPool reference, enabling objects to modify the pool state during operation application.


72-73: Consistent logger parameter integration

The logger parameter is properly threaded through all constructors and factory methods, enabling comprehensive logging throughout the object pool operations. The consistent parameter passing maintains API coherence.

Also applies to: 78-79, 86-87, 91-91


118-120: Proper logger propagation in object creation

The createZeroValueObject method correctly passes the logger parameter to the zero-value constructors of both DefaultLiveMap and DefaultLiveCounter, ensuring logging capabilities are available during object creation.

Also applies to: 138-141


160-162: Effective logging integration for debugging

The logging statements provide valuable debugging information at appropriate levels:

  • Debug level for normal operations (object counts, creation, updates)
  • Warning level for unsupported operations
  • Clear, informative messages that aid in troubleshooting

This will be helpful for debugging synchronization and operation application issues.

Also applies to: 172-173, 183-184, 203-204, 218-219, 224-224

Tests/AblyLiveObjectsTests/Helpers/TestFactories.swift (2)

389-392: LGTM! Well-structured test utility

The counterOp helper method follows the existing factory pattern and provides a clean way to create counter operations for testing.


524-617: Well-implemented operation message factories

The new factory methods for creating operation messages (MAP_SET, MAP_REMOVE, MAP_CREATE, COUNTER_CREATE, COUNTER_INC) are well-structured and follow the existing patterns. They provide comprehensive test data creation utilities that align with the broader operation handling enhancements.

Sources/AblyLiveObjects/DefaultRealtimeObjects.swift (4)

76-76: Logger parameter properly integrated

Good addition of the logger parameter to the ObjectsPool initialization, ensuring consistent logging throughout the object lifecycle.


169-180: Well-structured OBJECT protocol message handling

The implementation properly delegates to the mutable state with mutex protection and passes all necessary parameters including the logger. This follows the RTO8 specification requirements.


333-406: Comprehensive implementation of OBJECT handling (RTO8/RTO9)

The implementation correctly:

  • Yields messages to the continuation stream
  • Applies each object message individually
  • Creates zero-value objects when needed (RTO9a2a2)
  • Handles all specified operation types
  • Logs warnings for unsupported operations (RTO9a2b)

The thread-safe design and detailed logging make this a robust implementation.


283-287: Review Sync Cursor Parsing Error Handling

The code in Sources/AblyLiveObjects/DefaultRealtimeObjects.swift (lines 283–287) currently catches and logs any SyncCursor parsing error, then returns early—silently dropping the message. Please confirm whether, per the RTO5a specification, a parsing failure should instead
• be propagated (e.g., throw up to the caller or surface via a client callback)
• or if aborting without propagation is the intended behavior.

Points to review:

  • File: Sources/AblyLiveObjects/DefaultRealtimeObjects.swift
  • Lines: 283–287
Tests/AblyLiveObjectsTests/DefaultLiveMapTests.swift (3)

12-13: Consistent logger usage across tests

Good practice to consistently use TestLogger throughout all tests, enabling better debugging capabilities during test execution.


816-890: Comprehensive coverage of merge initial value functionality (RTLM17)

Excellent test coverage for the merge initial value functionality, including:

  • MAP_SET operations from create operations
  • MAP_REMOVE operations with proper timeserial ordering
  • Verification of the createOperationIsMerged flag

The tests effectively verify the specification requirements.


942-1084: Thorough testing of apply operation method (RTLM15)

The ApplyOperationTests struct provides excellent coverage of the apply method, including:

  • Operations that cannot be applied due to timeserial ordering
  • All operation types (MAP_CREATE, MAP_SET, MAP_REMOVE)
  • Site timeserial updates
  • Proper mutex protection verification

The tests are well-structured and cover both positive and negative cases.

Tests/AblyLiveObjectsTests/DefaultLiveCounterTests.swift (3)

12-13: Consistent test setup with logger and objectID

Good consistency in using TestLogger and explicit objectID throughout all tests, aligning with the refactored DefaultLiveCounter implementation.


126-177: Well-structured merge initial value tests (RTLC10)

Excellent coverage of the merge initial value functionality with clear test cases for:

  • Adding counter count to existing data
  • Handling missing count values
  • Setting the createOperationIsMerged flag

The tests effectively verify all aspects of RTLC10.


244-335: Comprehensive apply operation tests (RTLC7)

The ApplyOperationTests provide thorough coverage including:

  • Operations that cannot be applied due to timeserial constraints
  • Both COUNTER_CREATE and COUNTER_INC operations
  • Site timeserial updates
  • Proper verification of side effects

The parameterized approach for testing different scenarios is well-implemented.

Sources/AblyLiveObjects/Internal/DefaultLiveCounter.swift (5)

2-2: Proper integration of logger dependency

Good addition of the AblyPlugin import and logger property, enabling comprehensive logging throughout the counter implementation.

Also applies to: 31-31


12-28: Clean abstraction of mutable state properties

The test-only properties now properly delegate to the centralized LiveObjectMutableState, providing a clean interface while maintaining encapsulation.


185-189: Consider extracting common merge logic

The merge initial value logic is duplicated between replaceData and mergeInitialValue. Consider calling mergeInitialValue(from: createOp) directly here to reduce duplication.

-            // RTLC6d: If ObjectState.createOp is present, merge the initial value into the LiveCounter as described in RTLC10
-            if let createOp = state.createOp {
-                mergeInitialValue(from: createOp)
-            }
+            // RTLC6d: If ObjectState.createOp is present, merge the initial value into the LiveCounter as described in RTLC10
+            if let createOp = state.createOp {
+                mergeInitialValue(from: createOp)
+            }

Actually, the code is already doing this correctly. My apologies for the confusion.


147-232: Well-structured operation application with proper validation

The apply method implementation is excellent:

  • Proper validation using canApplyOperation (RTLC7b)
  • Site timeserial updates (RTLC7c)
  • Correct dispatching to operation-specific handlers
  • Comprehensive logging for debugging
  • Thread-safe implementation

234-257: Robust implementation of counter operations

Both COUNTER_CREATE and COUNTER_INC operations are implemented correctly:

  • Proper check for duplicate create operations (RTLC8b)
  • Clean increment logic with nil handling
  • Appropriate warning logs for error conditions
Sources/AblyLiveObjects/Internal/DefaultLiveMap.swift (12)

2-2: LGTM! Appropriate import for logging support.

The internal visibility modifier correctly restricts the import scope.


23-45: Good refactoring to centralize mutable state management.

The migration of properties to LiveObjectMutableState improves code organization and maintains thread safety through consistent mutex usage.


54-55: LGTM! Logger property follows dependency injection pattern.

The logger is correctly declared as an immutable private property.


58-88: Initialization properly updated for new state structure and logging.

The logger parameter is correctly threaded through both initializers, and the new LiveObjectMutableState is properly initialized.


93-110: Factory method correctly updated with required parameters.

The createZeroValued factory method properly accepts and passes through the new objectID and logger parameters.


235-246: LGTM! Logging support added to replaceData.

The logger is correctly passed through while maintaining thread safety.


273-291: Well-structured method for applying operations.

The apply method properly handles thread safety and follows the established delegation pattern.


310-310: LGTM! Logger parameter added consistently.


330-339: Excellent refactoring to consolidate common state.

Moving shared mutable state into LiveObjectMutableState improves code organization and promotes reusability across LiveObject implementations.


343-369: Proper implementation of create operation handling.

The method now correctly handles createOp by delegating to mergeInitialValue, following the RTLM6d specification.


371-406: Well-implemented merge logic following RTLM17 specification.

The method correctly handles both tombstoned and non-tombstoned entries, with clear spec references and proper delegation to operation handlers.


474-510: Logger parameter properly integrated into MAP_SET operation.

The logger is correctly passed through to enable logging during zero-value object creation.

Base automatically changed from ECO-5330-LiveMap-access-API to main July 24, 2025 16:27
Copy link
Collaborator

@umair-ably umair-ably left a comment

Choose a reason for hiding this comment

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

didn't look at the tests but impl looks good

@lawrence-forooghian lawrence-forooghian merged commit 2d11ea0 into main Jul 24, 2025
33 checks passed
@lawrence-forooghian lawrence-forooghian deleted the ECO-5333-apply-OBJECT branch July 24, 2025 17:16
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.

3 participants