Skip to content

[PUB-1094] Infer key name of the LiveMap in its direct subscription update object#1995

Merged
VeskeR merged 1 commit intointegration/liveobjectsfrom
PUB-1094/infer-key-in-map-update
Apr 10, 2025
Merged

[PUB-1094] Infer key name of the LiveMap in its direct subscription update object#1995
VeskeR merged 1 commit intointegration/liveobjectsfrom
PUB-1094/infer-key-in-map-update

Conversation

@VeskeR
Copy link
Contributor

@VeskeR VeskeR commented Apr 9, 2025

Resolves PUB-1094

Summary by CodeRabbit

  • Refactor

    • Enhanced the real-time map update processing for a more robust, consistent experience. Live updates now follow a refined logic ensuring that changes are validated accurately.
  • Bug Fixes

    • Improved update notification handling by addressing edge-case scenarios, resulting in smoother and more reliable data transitions in live map views.

@coderabbitai
Copy link

coderabbitai bot commented Apr 9, 2025

Walkthrough

This change set refines the type definitions for the LiveMap and LiveMapUpdate interfaces and their implementations. A generic type parameter T is introduced in both declarations and method signatures to ensure that updates are strictly typed. Additionally, the subscription callback in one test file now uses a new variable to determine the update key with an added case for undefined. These modifications improve consistency and type safety across the components.

Changes

File(s) Change Summary
ably.d.ts, src/plugins/objects/livemap.ts Updated LiveMap and LiveMapUpdate interfaces and related method signatures to include a generic type parameter T, refining mapped types for update keys and enhancing type safety.
test/package/browser/template/src/index-objects.ts Modified subscription callback logic by replacing update.someKey with typedKeyOnMap and adding an explicit case for undefined in the switch-case.

Sequence Diagram(s)

sequenceDiagram
    participant LM as LiveMap
    participant CB as Callback Handler
    participant SW as Switch-Case Evaluator

    LM->>CB: Emit update event (with update object)
    CB->>CB: Extract key -> assign to typedKeyOnMap
    CB->>SW: Pass typedKeyOnMap for evaluation
    SW-->>CB: Return matched case (e.g., 'undefined' or default)
    CB->>LM: Process update based on matched case
Loading

Possibly related PRs

Suggested reviewers

  • mschristensen
  • zknill
  • kaschula

Poem

I'm a rabbit coding under the moonlight glow,
Hopping through generics where strict types grow.
LiveMap now sings with parameters so neat,
Update keys mapped and dancing to the beat.
With typed updates, our code shall never stray—
Hoppy, safe, and bright in every way!
🐰🚀

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • PUB-1094: Cannot read properties of undefined (reading 'displayName')

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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 plan to trigger planning for file edits and PR creation.
  • @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: 0

🧹 Nitpick comments (2)
src/plugins/objects/livemap.ts (2)

50-51: Consider distinguishing “added” vs “updated” keys
Currently, the LiveMapUpdate<T> interface provides only 'updated' and 'removed' states in update. This may conflate genuinely new entries with modified ones, complicating downstream logic. Consider introducing a separate 'added' state to better highlight new entries.

-  update: { [keyName in keyof T & string]?: 'updated' | 'removed' };
+  update: { [keyName in keyof T & string]?: 'added' | 'updated' | 'removed' };

654-709: _applyMapSet always marks updates as “updated”
The method treats both genuinely new and modified keys as 'updated', which can be acceptable in LWW. However, if you need to differentiate a brand-new key from a modified key, consider adding an 'added' status. Also note that the method does not deep-compare the new vs. old data, so identical values will still emit 'updated'. If that is desired, no further changes are necessary.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 84c1643 and 5f9da2c.

📒 Files selected for processing (3)
  • ably.d.ts (2 hunks)
  • src/plugins/objects/livemap.ts (10 hunks)
  • test/package/browser/template/src/index-objects.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • 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)
  • GitHub Check: test-npm-package
🔇 Additional comments (13)
test/package/browser/template/src/index-objects.ts (3)

45-47: The update object now infers keys from the map type correctly

The change from directly using update.someKey to first assigning update.stringKey to a variable typedKeyOnMap aligns with the improved typing in the LiveMapUpdate interface. This change correctly leverages the inference of keys from the map type, making the code more type-safe.


50-50: Added necessary handling for undefined case

Adding the undefined case is important as it properly handles situations where a key might not be present in the update object, which can happen in real-world scenarios. This makes the switch statement more robust.


54-54: Updated exhaustiveness check to use the new variable

The exhaustiveness check has been properly updated to use the new typedKeyOnMap variable, ensuring that the TypeScript compiler will still enforce that all possible types are handled in the switch statement.

ably.d.ts (3)

2302-2302: Enhanced type safety with generic parameter in LiveMap interface

The LiveMap interface has been updated to extend LiveObject<LiveMapUpdate<T>> instead of LiveObject<LiveMapUpdate>, ensuring that the LiveMapUpdate is parameterized with the same type T as the LiveMap. This change improves type safety by creating a stronger relationship between the map and its updates.


2362-2362: Added generic type parameter to LiveMapUpdate interface

Making the LiveMapUpdate interface accept a type parameter T that extends LiveMapType is a good improvement for type safety. This allows the update interface to be aware of the specific structure of the LiveMap it's associated with.


2368-2368: Implemented mapped type for more precise update property typing

The update property in LiveMapUpdate has been changed from a simple object with string keys to a mapped type that uses keyof T & string as keys. This is an excellent improvement as it ensures that only keys that exist in the LiveMap type can be used in the update object, along with their associated update statuses ('updated' or 'removed').

src/plugins/objects/livemap.ts (7)

54-54: Great use of generics for improved type safety
Leveraging LiveMapUpdate<T> in the class signature elegantly enforces type constraints. No issues found here.


394-394: Variable declaration for combined update looks correct
Storing the combined LiveMapUpdate<T> or LiveObjectUpdateNoop in a local variable ensures clarity when logic differentiates between a no-op and an actual update.


438-438: Method override for object state is well-typed
Accepting ObjectState and returning LiveMapUpdate<T> or LiveObjectUpdateNoop follows the new generic approach consistently.


529-583: _updateFromDataDiff logic is consistent with LWW semantics
This method scans differences between prevDataRef and newDataRef, marking keys as 'updated' or 'removed'. The approach is clear and matches last-writer-wins (LWW) semantics. If you want to separately track newly added vs. modified keys, consider refining 'updated' into multiple states. Otherwise, the current logic is perfectly valid for LWW.


585-619: Successively merging MAP_CREATE operations
Merging initial create operations into an aggregated update object is an elegant approach. It provides consolidated reporting of changes without spamming numerous discrete operations.


629-652: _applyMapCreate method properly checks second create attempts
By guarding with _createOperationIsMerged, the code ensures only one MAP_CREATE operation is applied. This helps avoid duplicate initializations. No changes required.


711-744: _applyMapRemove is straightforward and consistent
Removing a key sets its tombstone state and correctly emits a 'removed' update. This is aligned with the new generic type approach.

@VeskeR VeskeR requested a review from mschristensen April 9, 2025 08:40
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 291a2a4 into integration/liveobjects Apr 10, 2025
8 of 14 checks passed
@VeskeR VeskeR deleted the PUB-1094/infer-key-in-map-update branch April 10, 2025 08:30
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.

2 participants