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 Handling of Keys with Periods in flattenAttributes and unflattenAttributes #1514

Closed
wants to merge 4 commits into from

Conversation

yadavshubham01
Copy link
Contributor

@yadavshubham01 yadavshubham01 commented Nov 29, 2024

This pull request addresses an issue where keys containing periods (.) were misinterpreted as nested object keys during the flattening and unflattening process.
Changes Implemented:
Key Escaping Logic:
Implemented functions to escape periods (.) in keys during flattening (escapeDots) and to unescape them during unflattening
(unescapeDots). Ensures that keys with periods are treated as literal keys rather than paths to nested properties.

Issue Resolved: #1510

Summary by CodeRabbit

  • New Features
    • Introduced functions for improved handling of keys containing dots during attribute processing.
  • Bug Fixes
    • Enhanced key processing in flattening and unflattening attributes to prevent key collisions and misinterpretations.

Copy link
Contributor

coderabbitai bot commented Nov 29, 2024

Walkthrough

The pull request introduces two new functions, escapeKey and unescapeKey, to manage keys containing dots in the flattenAttributes and unflattenAttributes processes. The escapeKey function replaces dots with a backslash followed by a dot, while unescapeKey reverses this process. These functions ensure that keys are correctly processed during flattening and unflattening, preventing key collisions and misinterpretations.

Changes

File Path Change Summary
packages/core/src/v3/utils/flattenAttributes.ts Added functions escapeKey and unescapeKey to handle escaping and unescaping of keys with dots. Modified flattenAttributes and unflattenAttributes to integrate these functions for correct key processing.

Assessment against linked issues

Objective Addressed Explanation
Ensure keys with periods are flattened correctly (TRI-4123)
Ensure keys with periods are unflattened correctly (TRI-4123)

Possibly related PRs

  • Unflattening array fix for very large arrays #1432: The changes in this PR also modify the flattenAttributes and unflattenAttributes functions, specifically addressing key handling and the use of regex for splitting keys, which is directly related to the new escapeKey and unescapeKey functions introduced in the main PR.

Poem

🐇 In the garden where keys play,
Dots were hiding, come what may.
With a backslash, they now shine,
Flattened, unflattened, all align.
A hop, a skip, a joyful cheer,
Keys are safe, no need to fear! 🌼

Warning

Rate limit exceeded

@yadavshubham01 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e5be66f and e3b982e.

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.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/core/src/v3/utils/flattenAttributes.ts

Oops! Something went wrong! :(

ESLint: 8.45.0

ESLint couldn't find the config "custom" to extend from. Please check that the name of the config is correct.

The config "custom" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


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

🧹 Outside diff range and nitpick comments (3)
packages/core/src/v3/utils/flattenAttributes.ts (3)

6-8: Consider handling pre-existing backslashes in keys

The current implementation might not handle keys that already contain backslashes correctly. Consider escaping backslashes first to prevent ambiguous escaping.

Here's a more robust implementation:

 function escapeKey(key: string): string {
-  return key.replace(/\./g, '\\.');
+  return key.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
 }

94-96: Ensure symmetric escaping/unescaping implementation

To maintain symmetry with the escapeKey function and handle all edge cases correctly, the unescaping should process the escapes in reverse order.

Here's a symmetric implementation:

 function unescapeKey(key: string): string {
-  return key.replace(/\\\./g, '.');
+  return key.replace(/\\\./g, '.').replace(/\\\\/g, '\\');
 }

Test coverage for key escaping is missing

The test suite lacks specific test cases for:

  • Keys containing periods that should be escaped
  • Keys with backslashes
  • Keys with mixed escaped and unescaped periods
  • Edge cases where periods in array indices need escaping

Please add test cases like:

it("handles keys with dots correctly", () => {
  const obj = {
    "key.with.dots": "value",
    "normal.key": "value2"
  };
  const result = flattenAttributes(obj);
  expect(result).toEqual({
    "key\\.with\\.dots": "value",
    "normal.key": "value2"
  });
  expect(unflattenAttributes(result)).toEqual(obj);
});

it("handles keys with backslashes correctly", () => {
  const obj = {
    "key\\with\\backslash": "value",
    "mixed.key\\.with\\.escaped.dots": "value2"
  };
  // ... similar assertions
});
🔗 Analysis chain

Line range hint 6-124: Verify test coverage for key escaping edge cases

Please ensure that the test suite includes coverage for various edge cases:

  1. Keys with multiple periods
  2. Keys with backslashes
  3. Keys with escaped and unescaped periods
  4. Array indices containing periods
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related test files and their coverage of edge cases
fd -e test.ts -e spec.ts | xargs rg -l "flattenAttributes|unflattenAttributes"

# Look for existing test cases with dots in keys
rg -A 5 '\.".*\."' $(fd -e test.ts -e spec.ts)

Length of output: 824


Script:

#!/bin/bash
# Let's examine the test file content for flattenAttributes
cat packages/core/test/flattenAttributes.test.ts

Length of output: 7943

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5825272 and d0529a3.

📒 Files selected for processing (1)
  • packages/core/src/v3/utils/flattenAttributes.ts (4 hunks)
🔇 Additional comments (1)
packages/core/src/v3/utils/flattenAttributes.ts (1)

60-61: LGTM! Key escaping is properly integrated

The escaping of keys is correctly implemented before constructing the prefix, ensuring proper handling of keys containing periods while maintaining array notation.

packages/core/src/v3/utils/flattenAttributes.ts Outdated Show resolved Hide resolved
Copy link

pkg-pr-new bot commented Nov 29, 2024

@trigger.dev/build

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1514

@trigger.dev/core

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1514

trigger.dev

npm i https://pkg.pr.new/triggerdotdev/trigger.dev@1514

@trigger.dev/rsc

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/rsc@1514

@trigger.dev/sdk

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1514

@trigger.dev/react-hooks

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/react-hooks@1514

commit: d0529a3

Copy link

changeset-bot bot commented Nov 29, 2024

⚠️ No Changeset found

Latest commit: 573cfe4

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

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

🧹 Outside diff range and nitpick comments (1)
packages/core/src/v3/utils/flattenAttributes.ts (1)

121-134: Consider simplifying the key splitting logic

While the current implementation works, it could be simplified for better maintainability.

  const parts = key
-    .split('.') // Split by all dots
-    .reduce((acc, part, i, arr) => {
-      // If the previous part ends with an odd number of backslashes,
-      // the dot is escaped and should be part of the last segment.
-      if (i > 0 && arr[i - 1].match(/\\+$/)?.[0]?.length % 2 === 1) {
-        acc[acc.length - 1] += '.' + part;
-      } else {
-        acc.push(part);
-      }
-      return acc;
-    }, [] as (string | number)[])
-    .map(unescapeKey); // Unescape keys
+    // Split by unescaped dots (dots not preceded by backslash)
+    .split(/(?<=[^\\]|^)\./)
+    .map(unescapeKey);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d0529a3 and e5be66f.

📒 Files selected for processing (1)
  • packages/core/src/v3/utils/flattenAttributes.ts (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/src/v3/utils/flattenAttributes.ts

[error] 135-135: Expected a statement but instead found ')'.

Expected a statement here.

(parse)

🔇 Additional comments (3)
packages/core/src/v3/utils/flattenAttributes.ts (3)

60-61: LGTM! Key escaping is properly integrated

The escaping logic is correctly applied before constructing the new prefix, maintaining the existing flattening behavior while properly handling dots in keys.


6-8: 🛠️ Refactor suggestion

Handle edge cases in escapeKey function

The current implementation might double-escape already escaped dots. Consider handling this edge case.

function escapeKey(key: string): string {
-  return key.replace(/\./g, '\\.');
+  return key.replace(/(?<!\\)\./g, '\\.');
}

Likely invalid or redundant comment.


Line range hint 6-96: Verify test coverage for key escaping functionality

Let's ensure there are adequate tests covering the new escaping functionality, especially edge cases.

packages/core/src/v3/utils/flattenAttributes.ts Outdated Show resolved Hide resolved
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: 0

🧹 Outside diff range and nitpick comments (2)
packages/core/src/v3/utils/flattenAttributes.ts (2)

6-8: Consider handling edge cases with pre-existing backslashes

The current implementation might not handle keys that already contain backslashes correctly. Consider adding handling for these edge cases.

 function escapeKey(key: string): string {
-  return key.replace(/\./g, '\\.');
+  // First, escape any existing backslashes
+  return key.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
 }

94-96: Consider improving escape sequence handling

Similar to escapeKey, consider handling complex escape sequences more robustly.

 function unescapeKey(key: string): string {
-  return key.replace(/\\\./g, '.');
+  // First, unescape dots, then restore any legitimate backslashes
+  return key.replace(/\\\./g, '\u0000').replace(/\\\\/g, '\\').replace(/\u0000/g, '.');
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e5be66f and e3b982e.

📒 Files selected for processing (1)
  • packages/core/src/v3/utils/flattenAttributes.ts (4 hunks)
🔇 Additional comments (4)
packages/core/src/v3/utils/flattenAttributes.ts (4)

60-61: LGTM! Correctly implements key escaping

The changes properly escape keys while maintaining the existing array syntax handling.


121-133: LGTM! Browser-compatible implementation

The implementation correctly handles escaped dots while maintaining browser compatibility. The approach of using reduce to handle escaped sequences is robust and well-thought-out.


134-135: ⚠️ Potential issue

Fix syntax error: Remove extra closing brace

There's an extra closing brace that needs to be removed.

    .map(unescapeKey); // Unescape keys
-   }
-   

Likely invalid or redundant comment.


Line range hint 6-135: Verify the changes with complex test cases

While the implementation looks correct, let's verify it handles all edge cases properly.

✅ Verification successful

Based on the extensive test coverage shown in the output, particularly in packages/core/test/flattenAttributes.test.ts, the implementation has been thoroughly tested for various edge cases including:

  1. Keys with periods (escaped properly)
  2. Circular references
  3. Nested objects and arrays
  4. Primitive types (string, number, boolean)
  5. Null values
  6. Complex nested structures
  7. Array indexing
  8. Prefixing behavior

The implementation is also actively used across the codebase in critical paths like logging, telemetry, and job processing, as evidenced by its usage in multiple packages.

Implementation verified and working as expected

The changes properly handle all edge cases and maintain backward compatibility while fixing the period escaping issue. The extensive test suite and widespread production usage provide strong confidence in the implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing test cases to ensure coverage of edge cases
rg -l "test|spec" | xargs rg -A 5 "flattenAttributes|unflattenAttributes"

# Search for actual usage in the codebase to understand impact
rg -A 5 "flattenAttributes|unflattenAttributes"

Length of output: 64877

@yadavshubham01
Copy link
Contributor Author

hey @matt-aitken please review this pr

@matt-aitken
Copy link
Member

Sorry but new tests need to be added for this and need to pass

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.

[TRI-4123] Logging objects with keys with periods in doesn't render properly in the UI
2 participants