Skip to content

Conversation

@VeskeR
Copy link
Contributor

@VeskeR VeskeR commented Mar 4, 2025

Adds javascript Map's equivalents .keys(), .values(), .entries() to LiveMap and BatchContextLiveMap.

Resolves PUB-1235

Summary by CodeRabbit

  • New Features

    • Added iteration support for LiveMap objects, enabling retrieval of entries, keys, and values.
    • Enhanced batch context operations for more consistent access to map data.
  • Documentation

    • Updated examples in the documentation to show how to iterate over LiveMap collections, improving user guidance and clarity.

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2025

Walkthrough

This update enhances the LiveMap functionality by adding new iteration methods. The changes include code examples in the documentation and the introduction of three iterable methods—entries(), keys(), and values()—across multiple components including the LiveMap interface, BatchContextLiveMap class, and LiveMap class. Additionally, the test suite is expanded to verify enumeration and error handling for closed batch contexts.

Changes

Files Change Summary
README.md, ably.d.ts Updated documentation and interface definitions by adding three new iteration methods (entries(), keys(), values()) to demonstrate and enable traversal of LiveMap contents.
src/.../batchcontextlivemap.ts, src/.../livemap.ts Implemented new generator methods (entries, keys, values) in BatchContextLiveMap and refactored LiveMap’s data retrieval. Added private helpers (_getResolvedValueFromStateData and _isMapEntryTombstoned) to streamline value resolution and tombstoned entry filtering in iteration logic.
test/realtime/live_objects.test.js Enhanced test scenarios to cover the new enumeration methods and improved error handling functions (expectAccessBatchApiToThrow, expectWriteBatchApiToThrow) for verifying behavior when batch contexts have been closed and tombstoned entries are skipped in the count.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant B as BatchContextLiveMap
    participant M as Internal Map
    U->>B: Call entries()
    B->>B: throwIfInvalidAccessApiConfiguration()
    B->>B: throwIfClosed()
    B->>M: Iterate over entries
    M-->>B: Yield [key, value]
    B-->>U: Return each key-value pair
Loading
sequenceDiagram
    participant U as User
    participant L as LiveMap
    participant R as _getResolvedValueFromStateData
    U->>L: Call get(key)
    L->>R: Resolve state data for key
    R-->>L: Return value (primitive or LiveObject)
    L-->>U: Return the resolved value
Loading

Possibly related PRs

Suggested reviewers

  • mschristensen
  • zknill
  • kaschula

Poem

In my techy warren, I hop with delight,
New loops and methods shine so bright.
Keys and values, like carrots in a row,
Iterating magic as the warm breezes blow.
Code blooms anew, a joyful sight! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ast-grep (0.31.1)
test/realtime/live_objects.test.js
✨ Finishing Touches
  • 📝 Generate Docstrings

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>, please review it.
    • 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 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 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 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 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.

@VeskeR VeskeR requested a review from mschristensen March 4, 2025 08:00
@github-actions github-actions bot temporarily deployed to staging/pull/1981/bundle-report March 4, 2025 08:01 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1981/typedoc March 4, 2025 08:01 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1981/features March 4, 2025 08:01 Inactive
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: 0

🧹 Nitpick comments (3)
README.md (1)

675-684: Clear and Concise Enumeration Examples

The newly added examples for iterating over the map using .entries(), .keys(), and .values() are well aligned with the standard JavaScript Map API. The use of placeholder comments (/**/) keeps the examples succinct, although you might consider briefly commenting on the expected behavior or output for added clarity to users unfamiliar with these methods.

ably.d.ts (1)

2317-2330: Interface enhancement for improved LiveMap iteration.

The addition of the standard Map iteration methods (entries(), keys(), and values()) to the LiveMap interface is well-implemented, with proper TypeScript typing that ensures type safety during iteration.

Consider adding JSDoc comments to these methods to document the iteration behavior with filtered elements, especially if the implementation excludes tombstoned entries or other special cases. Example:

/**
 * Returns an iterable of key/value pairs for every entry in the map.
 * Note: Tombstoned entries or deleted LiveObjects will not be included in the iteration.
 */
entries<TKey extends keyof T & string>(): IterableIterator<[TKey, T[TKey]]>;
src/plugins/liveobjects/livemap.ts (1)

289-303: Consider caching size for performance.
This method correctly counts only non-tombstoned entries but runs in O(n). If the map can grow large or size() is frequently called, caching and invalidating the size upon mutations could improve performance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between efdce88 and 24aba84.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • ably.d.ts (1 hunks)
  • src/plugins/liveobjects/batchcontextlivemap.ts (1 hunks)
  • src/plugins/liveobjects/livemap.ts (2 hunks)
  • test/realtime/live_objects.test.js (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test-browser (webkit)
  • GitHub Check: test-node (20.x)
  • GitHub Check: test-browser (firefox)
  • GitHub Check: test-node (18.x)
  • GitHub Check: test-browser (chromium)
  • GitHub Check: test-node (16.x)
🔇 Additional comments (16)
src/plugins/liveobjects/batchcontextlivemap.ts (3)

31-35: Implementation of entries() method for LiveMap batch context.

The implementation uses correct generator syntax and proper validation checks before iteration.


37-41: Implementation of keys() method for LiveMap batch context.

The implementation uses correct generator syntax and proper validation checks before iteration.


43-47:

Details

❓ Verification inconclusive

Implementation of values() method for LiveMap batch context.

The implementation uses correct generator syntax and proper validation checks before iteration.

One minor observation: The get() method has special handling for LiveObject instances by wrapping them via getWrappedObject(), but the values() method directly yields the map's values without similar wrapping. Is this intentional? Depending on the use case, it might be worth checking if LiveObjects should be wrapped consistently across both methods.


🏁 Script executed:

#!/bin/bash
# Check for LiveObject wrapping in the implementation of LiveMap's values method

# First, find the LiveMap class implementation to see how the values() method is implemented
echo "Searching for LiveMap.values() implementation..."
grep -A 15 "values.*IterableIterator" --include="*.ts" -r src/plugins/liveobjects/

# Also check for references to wrapping LiveObjects in iteration methods
echo "Searching for LiveObject wrapping in iteration methods..."
grep -A 5 -B 5 "getWrappedObject" --include="*.ts" -r src/plugins/liveobjects/ | grep -E "entries|keys|values"

Length of output: 3201


Attention: Confirm Consistency in LiveObject Wrapping

  • File: src/plugins/liveobjects/batchcontextlivemap.ts (Lines: 43-47)
  • Observation: The values() method correctly performs its validation checks and yields values directly from the map. In contrast, the get() method applies a special wrapping for LiveObject instances via getWrappedObject(). The current implementation of values() does not include such wrapping.
  • Action: Please verify whether the absence of wrapping in the values() method is intentional. If ensuring a consistent behavior between get() and values() methods is desired, consider incorporating wrapping for the yielded LiveObjects.
src/plugins/liveobjects/livemap.ts (6)

286-287: Non-null assertion is justified given prior tombstone and data existence checks.
This usage of the ! operator is safe here, as the logic guarantees element.data is defined for non-tombstoned entries.


305-318: Generator-based entries() method is well-structured.
Skipping tombstoned entries and using _getResolvedValueFromStateData aligns with the intended semantics. This approach cleanly mimics JavaScript’s native Map.


320-324: keys() method correctly reuses entries.
Yielding keys from entries() is consistent with typical Map semantics and ensures consistent tombstone filtering.


326-330: values() method correctly reuses entries.
This approach ensures values reflect the same tombstone and resolved data handling.


793-816: _getResolvedValueFromStateData logic is solid.
Returning undefined for tombstoned or missing references is consistent with the user-facing contract. It neatly separates primitive vs. object reference handling.


817-834: _isMapEntryTombstoned centralizes tombstone checks.
Including a check for tombstoned referenced objects ensures the map’s external API won’t expose dead objects.

test/realtime/live_objects.test.js (7)

3202-3213: Thorough testing of the new enumeration methods

Good addition of tests for the new LiveMap enumeration methods (.entries(), .keys(), and .values()). The tests verify both functionality and synchronous behavior in batch context.


3340-3342: Complete verification of enumeration methods in error cases

Properly testing that enumeration methods throw the correct errors when the batch is closed.


3388-3399: Good refactoring of batch API error testing

Great refactoring of batch API error testing logic into reusable utility functions. This improves maintainability and readability of the tests.


3453-3577: Comprehensive testing of LiveMap and BatchContextLiveMap enumeration

The test scenarios thoroughly verify that:

  1. Enumeration methods work properly for both LiveMap and BatchContextLiveMap
  2. Tombstoned entries are correctly excluded from enumeration results
  3. The methods return the expected types and values

This provides good coverage for the new API methods that implement JavaScript Map-equivalent behavior.


3496-3510: Validation of tombstone handling in enumeration methods

Good test coverage of tombstone handling in enumeration methods. The test confirms that:

  1. size() doesn't count tombstoned entries
  2. entries() doesn't include tombstoned entries
  3. keys() and values() don't include keys or values from tombstoned entries

This is important for ensuring consistent behavior with JavaScript Map.


4304-4306: Complete coverage of access API error testing

The extended access API error testing now includes verification for the new enumeration methods, ensuring they throw appropriate errors in expected failure cases.


4340-4342: Complete coverage of batch API error testing

Proper testing of all batch context enumeration methods in error scenarios ensures they throw appropriate errors when the batch is closed.

Copy link
Contributor

@mschristensen mschristensen left a comment

Choose a reason for hiding this comment

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

Nice, LGTM

@VeskeR VeskeR merged commit b7e3887 into integration/liveobjects Mar 5, 2025
8 of 14 checks passed
@VeskeR VeskeR deleted the PUB-1235/enumerate-map-keys branch March 5, 2025 09:38
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