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

Fix: ToJsonEncoder keeps order fields during encoding map #7237

Merged
merged 5 commits into from
Nov 26, 2024

Conversation

lciolecki
Copy link
Contributor

@lciolecki lciolecki commented Nov 26, 2024

Describe your changes

Checklist before merge

  • Related issue ID is placed at the beginning of PR title in [brackets] (can be GH issue or Nu Jira issue)
  • Code is cleaned from temporary changes and commented out lines
  • Parts of the code that are not easy to understand are documented in the code
  • Changes are covered by automated tests
  • Showcase in dev-application.conf added to demonstrate the feature
  • Documentation added or updated
  • Added entry in Changelog.md describing the change from the perspective of a public distribution user
  • Added MigrationGuide.md entry in the appropriate subcategory if introducing a breaking change
  • Verify that PR will be squashed during merge

Summary by CodeRabbit

  • New Features

    • Enhanced JSON encoding to maintain the order of keys when converting maps.
  • Tests

    • Added a test case to verify that maps are encoded to JSON while preserving the order of keys.
  • Documentation

    • Updated changelog to include new features, improvements, and fixes, including the ToJsonEncoder enhancement and other version updates.

Copy link

coderabbitai bot commented Nov 26, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the ToJsonEncoder object located in the ToJsonEncoder.scala file, specifically enhancing the encode method to handle scala.collection.immutable.ListMap. A new private method, encodeListMap, has been introduced to specifically encode ListMap instances by converting their entries into a list of key-value pairs. The existing handling of scala.collection.Map and java.util.Map remains, but the encodeMap method has been updated to encode the values of the map entries instead of simply returning them. Additionally, some import statements have been removed, while the overall structure of the ToJsonEncoder class remains intact, with enhancements focused on the encoding of specific map types.

In the test file ToJsonEncoderSpec.scala, a new test case has been added to verify that a ListMap is correctly encoded to JSON while preserving the order of its keys. This test ensures that the output JSON accurately reflects the key order and values of a nested map structure. The existing functionality and error handling in the encoder remain unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ToJsonEncoder
    participant ListMap

    User->>ToJsonEncoder: Request to encode map
    ToJsonEncoder->>ListMap: Create ListMap from input map
    ListMap-->>ToJsonEncoder: Return ListMap
    ToJsonEncoder->>ToJsonEncoder: Apply encoding to values
    ToJsonEncoder-->>User: Return encoded JSON
Loading

Suggested labels

client

Suggested reviewers

  • Dzuming
  • JulianWielga

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1943c73 and a0ecd85.

📒 Files selected for processing (1)
  • utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala

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 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: 0

🧹 Outside diff range and nitpick comments (1)
utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala (1)

105-121: LGTM: Well-structured test case with comprehensive coverage

The test case effectively verifies the order preservation requirement with a good mix of data types and realistic field names.

Consider adding these additional test cases to strengthen the coverage:

  1. A comparison test with regular Map to demonstrate the difference
  2. A test with nested ordered maps to verify order preservation at multiple levels

Example:

it("should preserve order in nested maps") {
  val nestedMap = ListMap(
    "first" -> ListMap(
      "a" -> 1,
      "b" -> 2
    ),
    "second" -> ListMap(
      "x" -> 3,
      "y" -> 4
    )
  )
  
  encoder.encode(nestedMap) shouldBe Json.obj(
    "first" -> Json.obj(
      "a" -> fromInt(1),
      "b" -> fromInt(2)
    ),
    "second" -> Json.obj(
      "x" -> fromInt(3),
      "y" -> fromInt(4)
    )
  )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a306cab and 1a5337c.

📒 Files selected for processing (2)
  • utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (2 hunks)
  • utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala (2 hunks)
🔇 Additional comments (5)
utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (3)

14-14: LGTM! Appropriate choice for ordered map implementation.

The addition of SeqMap import is well-placed and aligns perfectly with the PR's objective of maintaining field order during JSON encoding.


91-96: Excellent implementation with performance optimization!

The changes effectively maintain field order while also improving performance through:

  1. Using SeqMap.from to preserve insertion order
  2. Switching to mapValuesNow for eager evaluation instead of the lazy mapValues

91-96: Verify behavior with nested maps and special characters in keys

While the implementation looks correct, please ensure it handles these edge cases:

  1. Nested maps (maps containing maps)
  2. Maps with special characters in keys
  3. Maps with null keys or values

Let's verify the test coverage:

✅ Verification successful

Let me gather more specific information about the test coverage by examining the actual test implementations.


Let me check the actual implementation of ToJsonEncoder to see how it handles the edge cases mentioned in the review.


Based on the implementation and test coverage analysis, I can now provide the final response:

Implementation handles all mentioned edge cases correctly

The implementation safely handles all the edge cases mentioned in the review:

  1. Nested maps: The encode method recursively processes map values through mapValuesNow(encode), ensuring proper handling of nested maps
  2. Special characters in keys: Keys are converted to strings using toString, which preserves special characters
  3. Null handling: Both keys and values are properly handled through:
    • Null values via the safeJson wrapper and explicit null case in encode
    • The Option handling in the main encode method
    • The toString conversion for keys which safely handles null keys

The test suite includes verification of:

  • Various data types and collections
  • Nested structures through the custom encoder tests
  • Map key ordering preservation
  • Null values and Options
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for relevant test cases in the codebase
rg -l "ToJsonEncoderSpec" | while read -r file; do
  echo "=== $file ==="
  rg "test|\"map|\"nested|special.*character|null.*key" "$file"
done

Length of output: 540


Script:

#!/bin/bash
# Get the content of the test file to examine the test cases
cat utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala

Length of output: 5664


Script:

#!/bin/bash
# Get the implementation of ToJsonEncoder
cat utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala

Length of output: 4506

utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala (2)

12-12: LGTM: Import addition is appropriate

The addition of SeqMap import aligns with the PR's objective of maintaining field order during JSON encoding.


105-121: Verify consistency between test and implementation

The test uses ListMap while the implementation (according to the AI summary) uses SeqMap. While both preserve order, we should ensure this difference doesn't cause any issues.

✅ Verification successful

Implementation and test are consistent in handling ordered maps

Both the implementation and test are using order-preserving map types from the Scala collections:

  • The implementation uses SeqMap from scala.collection
  • The test uses ListMap from scala.collection.immutable

Both types preserve insertion order, and ListMap is actually an immutable implementation of an ordered map, making it a suitable choice for testing. The implementation correctly maintains the contract being tested.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Map-related type declarations in ToJsonEncoder
ast-grep --pattern 'Map[$_]' utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala

# Search for specific map conversion methods
rg -A 5 'def.*Map' utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala

Length of output: 380


Script:

#!/bin/bash
# Let's check imports to understand the SeqMap type
rg "SeqMap" utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala -B 5

# Also check if ListMap is imported in the test file
rg "ListMap" utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala -B 5

Length of output: 1103

@lciolecki lciolecki changed the base branch from staging to release/1.18 November 26, 2024 08:37
@lciolecki lciolecki force-pushed the fix/to-json-encoder-list-map branch from 1a5337c to d048e74 Compare November 26, 2024 08:42
@github-actions github-actions bot added the docs label Nov 26, 2024
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

🧹 Outside diff range and nitpick comments (3)
utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (3)

14-15: Remove unused import scala.collection.SeqMap

The SeqMap import appears to be unused in the code. Consider removing it to keep the imports clean.

-import scala.collection.SeqMap
import scala.collection.immutable.ListMap

90-96: Consider adding null checks and improving key handling

While the implementation correctly preserves order, there are a few potential improvements:

  1. Add null checking similar to other encode methods
  2. Consider handling non-string keys more explicitly, as toString might lose important type information

Consider this safer implementation:

 private def encodeListMap(value: scala.collection.immutable.ListMap[_, _]): Json = {
+  if (value == null) return Null
   val mapWithStringKeys = value.toList.map { case (k, v) =>
-    k.toString -> encode(v)
+    Option(k).map(_.toString).getOrElse("null") -> encode(v)
   }
   fromFields(mapWithStringKeys)
 }

Line range hint 1-105: Document the order preservation behavior

Since this change introduces order preservation for maps, it should be properly documented:

  1. Add ScalaDoc to explain the ordering guarantee
  2. Consider adding an entry to the migration guide if any clients might depend on the previous behavior

Consider adding documentation like this at the class level:

/**
 * Encodes values to JSON format.
 * Note: As of version 1.18.1, the encoder preserves the order of fields when encoding ListMap instances.
 * For other map types, the order is not guaranteed.
 */
case class ToJsonEncoder(...)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6eb15cb and 0dc7f3d.

📒 Files selected for processing (2)
  • utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (3 hunks)
  • utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • utils/utils/src/test/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoderSpec.scala
🔇 Additional comments (2)
utils/utils/src/main/scala/pl/touk/nussknacker/engine/util/json/ToJsonEncoder.scala (2)

72-74: LGTM! Correct pattern matching order

The ListMap case is correctly positioned before the general Map cases, ensuring proper type-based pattern matching precedence.


101-105: Verify view optimization impact and consider consistent key handling

The changes look good with the view optimization for large maps. However:

  1. The key handling should be consistent with the ListMap implementation
  2. The view optimization's impact should be verified with performance tests

Let's verify the usage patterns to ensure the optimization is beneficial:

@lciolecki lciolecki force-pushed the fix/to-json-encoder-list-map branch from 0dc7f3d to 8328cfe Compare November 26, 2024 10:43
@lciolecki lciolecki force-pushed the fix/to-json-encoder-list-map branch from 8328cfe to 1943c73 Compare November 26, 2024 10:51
Copy link
Contributor

created: #7239
⚠️ Be careful! Snapshot changes are not necessarily the cause of the error. Check the logs.

@lciolecki lciolecki merged commit 9d4f381 into release/1.18 Nov 26, 2024
17 of 18 checks passed
@lciolecki lciolecki deleted the fix/to-json-encoder-list-map branch November 26, 2024 15:15
@coderabbitai coderabbitai bot mentioned this pull request Dec 3, 2024
9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants