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

[WEB-2001] feat: Fix local cache issues v2 #5712

Merged
merged 4 commits into from
Sep 27, 2024
Merged

Conversation

SatishGandham
Copy link
Contributor

@SatishGandham SatishGandham commented Sep 27, 2024

  • Fix issue description removed from local store
  • Fix the load workspace queries to handle single quotes
  • Change secondary order to sequence id

Summary by CodeRabbit

  • New Features

    • Enhanced indexing capabilities with the addition of the "sequence_id" field for improved query efficiency.
    • Improved SQL query logic for sorting and filtering, allowing for more flexible data retrieval.
  • Bug Fixes

    • Fixed potential SQL injection vulnerabilities by properly escaping single quotes in string and object values.
  • Refactor

    • Updated the updatePersistentLayer function to handle issue IDs asynchronously, improving data processing efficiency.

Copy link
Contributor

coderabbitai bot commented Sep 27, 2024

Walkthrough

The pull request introduces several changes across multiple files in the codebase. Key modifications include the addition of a new index field, "sequence_id", in the createIssueIndexes function to enhance indexing capabilities. The handling of single quotes in SQL queries has been improved to prevent injection vulnerabilities. Updates to SQL query construction logic include changes in ordering and filtering conditions. Additionally, the updatePersistentLayer function has been modified to process issue IDs asynchronously, improving the efficiency of data updates.

Changes

File Path Change Summary
web/core/local-db/utils/indexes.ts Added "sequence_id" to the index fields in createIssueIndexes function.
web/core/local-db/utils/load-workspace.ts Enhanced single quote handling in stageInserts function to prevent SQL injection by replacing single quotes with two single quotes.
web/core/local-db/utils/query.utils.ts Modified SQL query logic in getOrderByFragment to use sequence_id for ordering; updated getFilteredRowsForGrouping to include sequence_id in CTE selection; added handling for empty filter values in singleFilterConstructor.
web/core/local-db/utils/utils.ts Changed updatePersistentLayer to process issueIds asynchronously and expanded properties included in the issuePartial object.

Possibly related PRs

  • [WEB-2001] fix: Issue local cache fixes #5703: The changes in this PR include escaping single quotes in dynamic queries, which is directly related to the modifications made in the stageIssueInserts function in the main PR, where single quotes are also handled to prevent SQL injection issues.

Suggested labels

🐛bug, ⚡performance

Suggested reviewers

  • rahulramesha
  • sriramveeraghanta

🐰 In the code so bright and new,
A sequence added, just for you!
With quotes that dance and never harm,
Our queries now have extra charm.
Async updates, swift and neat,
A hopping change, oh what a treat! 🐇✨


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.

@SatishGandham SatishGandham changed the title Fix local cache issues v2 [WEB-2001] feat: Fix local cache issues v2 Sep 27, 2024
@SatishGandham SatishGandham marked this pull request as ready for review September 27, 2024 07:26
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 (6)
web/core/local-db/utils/indexes.ts (1)

Line range hint 1-71: Consider addressing TODOs and improving error handling

While reviewing the entire file, I noticed a few areas for potential improvement:

  1. There's a commented out line for the "priority" index. Consider either removing this comment or implementing the index if it's needed.
  2. There's a TODO for "Estimate Points". It might be worth addressing this in a future update.
  3. The error handling in the createIndexes function could be more robust. Currently, it only logs the error message.

Consider updating the error handling in the createIndexes function:

 try {
   await Promise.all(promises);
 } catch (e) {
-  console.log((e as Error).message);
+  console.error("Error creating indexes:", (e as Error).message);
+  // Consider adding more specific error handling or rethrowing the error if needed
 }

Also, consider addressing the TODO and the commented out "priority" index in future updates to improve the completeness of the indexing strategy.

web/core/local-db/utils/utils.ts (2)

19-25: Approved: Improved async handling and data merging

The changes to the updatePersistentLayer function are well-implemented:

  1. The use of an async forEach loop allows for proper handling of asynchronous operations within the loop.
  2. Retrieving dbIssue from persistence before merging ensures that the latest data from the persistent layer is considered.
  3. Using the spread operator for merging is a clean and efficient way to combine the objects.

These improvements align well with the PR objectives of fixing local cache issues.

Consider using Promise.all for potential performance improvement:

await Promise.all(issueIds.map(async (issueId) => {
  // ... rest of the function body
}));

This change would allow for parallel processing of all issues, potentially speeding up the operation for multiple issues.


No existing tests found for updatePersistentLayer

It appears that there are no test files related to the updatePersistentLayer function. To ensure comprehensive coverage and prevent potential regressions, please consider adding unit and integration tests for this function.

  • Files referencing updatePersistentLayer:
    • web/core/store/issue/helpers/base-issues.store.ts
    • web/core/store/issue/issue.store.ts
    • web/core/store/issue/issue-details/sub_issues.store.ts
    • web/local-db/utils/utils.ts
🔗 Analysis chain

Line range hint 16-56: Summary: Improved local cache handling

The changes to the updatePersistentLayer function effectively address the PR objectives:

  1. The issue description is now properly stored in the local cache.
  2. The function now handles asynchronous operations more efficiently.
  3. The merging of data ensures that the most up-to-date information is stored.

These improvements will enhance the reliability and performance of the local caching mechanism.

To ensure the changes are fully effective and don't introduce any regressions:

  1. Please update any existing unit tests for this function to cover the new async behavior and the addition of 'description_html'.
  2. Consider adding integration tests that verify the correct storage and retrieval of issue data, including the description.

Run the following script to check for existing tests that may need updating:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test files related to updatePersistentLayer
rg --type typescript -g '*test*' -g '*spec*' 'updatePersistentLayer'

Length of output: 103


Script:

#!/bin/bash
# Search for test files related to updatePersistentLayer using the correct type
rg --type ts -g '*test*' -g '*spec*' 'updatePersistentLayer'

Length of output: 60


Script:

#!/bin/bash
# Find test files related to updatePersistentLayer using fd and rg
fd -e ts -e tsx -e js -e jsx -g '*test*' -g '*spec*' | xargs rg 'updatePersistentLayer'

Length of output: 1097

web/core/local-db/utils/load-workspace.ts (3)

Line range hint 44-58: Consider adding error handling to data loading functions

The data loading functions (e.g., loadLabels, loadModules, etc.) currently don't have explicit error handling. Consider wrapping the main logic of these functions in try-catch blocks to handle potential errors gracefully. This will prevent silent failures and improve the robustness of the application.

Example implementation:

export const loadLabels = async (workspaceSlug: string, batchSize = 500) => {
  try {
    const issueLabelService = new IssueLabelService();
    const objects = await issueLabelService.getWorkspaceIssueLabels(workspaceSlug);
    // ... rest of the function
  } catch (error) {
    console.error("Error loading labels:", error);
    // Consider adding more sophisticated error handling or reporting
  }
};

Apply similar error handling to all data loading functions.

Also applies to: 62-76, 80-94, 98-112, 116-134, 138-152


Line range hint 44-58: Refactor batch insertion logic to reduce code duplication

The batch insertion logic is repeated across multiple functions (loadLabels, loadModules, etc.). Consider abstracting this common pattern into a reusable function to improve code maintainability and reduce duplication.

Example implementation:

const batchInsert = async (
  objects: any[],
  table: string,
  schema: Schema,
  batchSize: number
) => {
  for (let i = 0; i < objects.length; i += batchSize) {
    const batch = objects.slice(i, i + batchSize);
    persistence.db.exec("BEGIN TRANSACTION;");
    batch.forEach((item: any) => {
      stageInserts(table, schema, item);
    });
    await persistence.db.exec("COMMIT;");
  }
};

export const loadLabels = async (workspaceSlug: string, batchSize = 500) => {
  const issueLabelService = new IssueLabelService();
  const objects = await issueLabelService.getWorkspaceIssueLabels(workspaceSlug);
  await batchInsert(objects, "labels", labelSchema, batchSize);
};

// Apply similar refactoring to other loading functions

This refactoring will make the code more DRY and easier to maintain.

Also applies to: 62-76, 80-94, 98-112, 116-134, 138-152


Line range hint 116-134: Optimize loadEstimatePoints function for performance

The loadEstimatePoints function currently fetches all estimates and then processes them to extract points. This approach might be inefficient, especially if there are many estimates or if the points data is large.

Consider optimizing this function by:

  1. Fetching only the necessary data (points) from the API if possible.
  2. If the API doesn't support fetching only points, process the estimates in batches instead of loading all of them into memory at once.

Example optimization:

export const loadEstimatePoints = async (workspaceSlug: string, batchSize = 500) => {
  const estimateService = new EstimateService();
  const estimates = await estimateService.fetchWorkspaceEstimates(workspaceSlug);
  
  for (const estimate of estimates) {
    if (estimate?.points) {
      await batchInsert(estimate.points, "estimate_points", estimatePointSchema, batchSize);
    }
  }
};

This approach processes estimates one at a time, reducing memory usage and potentially improving performance for large datasets.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ade03e9 and 5cece0f.

📒 Files selected for processing (4)
  • web/core/local-db/utils/indexes.ts (1 hunks)
  • web/core/local-db/utils/load-workspace.ts (1 hunks)
  • web/core/local-db/utils/query.utils.ts (4 hunks)
  • web/core/local-db/utils/utils.ts (3 hunks)
🔇 Additional comments (8)
web/core/local-db/utils/indexes.ts (1)

13-13: LGTM! Addition of "sequence_id" index improves query performance.

The addition of "sequence_id" to the indexed columns aligns with the PR objective of changing the secondary order. This will likely enhance query performance for operations involving this field.

To ensure consistency, let's verify if there are any related changes in query patterns:

✅ Verification successful

Verification Successful!

All query patterns involving "sequence_id" have been appropriately updated, consistent with the new index. No issues found.

  • web/core/local-db/utils/query.utils.ts
  • web/core/store/inbox/project-inbox.store.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for changes in query patterns related to sequence_id

# Search for SQL queries using sequence_id
rg --type typescript 'SELECT.*sequence_id|ORDER BY.*sequence_id' --glob '!**/indexes.ts'

# Search for TypeScript code referencing sequence_id in queries or sorting
rg --type typescript 'sequence_id.*sort|sort.*sequence_id' --glob '!**/indexes.ts'

Length of output: 245


Script:

#!/bin/bash
# Description: Check for changes in query patterns related to sequence_id

# Search for SQL queries using sequence_id in TypeScript files
rg 'SELECT.*sequence_id|ORDER BY.*sequence_id' --glob '!**/indexes.ts' -g '*.ts' -g '*.tsx'

# Search for TypeScript code referencing sequence_id in queries or sorting
rg 'sequence_id.*sort|sort.*sequence_id' --glob '!**/indexes.ts' -g '*.ts' -g '*.tsx'

Length of output: 951

web/core/local-db/utils/utils.ts (2)

4-4: LGTM: Import of persistence object

The addition of the persistence import from "../storage.sqlite" is appropriate for the changes made in this file, particularly for the updatePersistentLayer function. This aligns with the PR objectives of addressing local cache issues.


53-53: LGTM: Addition of 'description_html' to picked properties

The inclusion of 'description_html' in the list of picked properties is a positive change. This ensures that the HTML description of the issue is included when updating the persistent layer, directly addressing the PR objective of fixing the issue where the issue description was removed from the local store.

web/core/local-db/utils/load-workspace.ts (2)

30-33: Excellent security improvement for SQL query construction!

These changes effectively address the issue of handling single quotes in both object and string values, which was mentioned in the PR objectives. By escaping single quotes, you've significantly reduced the risk of SQL injection vulnerabilities. This is a crucial security improvement that aligns well with best practices for constructing SQL queries.

Some key points:

  1. For objects (line 30), single quotes are now properly escaped in the JSON stringified representation.
  2. For strings (line 33), single quotes are directly escaped.

These modifications ensure that data containing single quotes is correctly inserted into the database without breaking the SQL syntax or introducing security vulnerabilities.


Line range hint 1-158: Summary of review findings

The changes made in this PR successfully address the issue of handling single quotes in SQL queries, which was one of the main objectives. These modifications significantly improve the security of the application by preventing SQL injection vulnerabilities.

While the immediate changes are beneficial, I've identified several areas for potential improvement:

  1. Error handling: Adding try-catch blocks to the data loading functions would improve robustness.
  2. Code duplication: Abstracting the batch insertion logic into a reusable function would enhance maintainability.
  3. Performance optimization: Refactoring the loadEstimatePoints function could improve efficiency, especially for large datasets.

These suggestions, if implemented, would further enhance the overall quality, maintainability, and performance of the code. Consider addressing these in future iterations or as part of ongoing refactoring efforts.

web/core/local-db/utils/query.utils.ts (3)

50-52: LGTM: Improved result ordering with sequence_id

The addition of ${table}sequence_id DESC as a secondary sorting criterion is a good improvement. This change ensures a consistent and deterministic ordering of results, even when there are ties in the primary sorting field. By using DESC order for sequence_id, newer items will appear first within each group of the primary sort, which is usually the desired behavior.


133-133: LGTM: Including sequence_id in the result set

The addition of i.sequence_id to the SELECT statement is necessary to support the new ordering logic implemented in the getOrderByFragment function. This change ensures that the sequence_id is available for sorting in the final result set, maintaining consistency with the updated ordering mechanism.


156-156: LGTM: Consistent inclusion of sequence_id

The addition of i.sequence_id to the SELECT statement in this part of the function maintains consistency with the previous change. This ensures that the sequence_id is included in the result set regardless of whether joins are required or not, providing a uniform data structure for further processing and sorting.

Comment on lines +241 to +244
if (!value) {
sql += ` AND ${key} IS NULL`;
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential issue with null value handling

The addition of null value handling is a good improvement. However, the current implementation might lead to incorrect SQL generation for array fields. The condition if (!value) will be true for both empty strings and empty arrays, which could cause issues for array fields checked later in the function.

Consider refining the condition to specifically check for empty strings:

- if (!value) {
+ if (value === '') {
    sql += ` AND ${key} IS NULL`;
    return;
  }

This change ensures that only empty string values are treated as NULL in the SQL query, while empty arrays are handled correctly by the existing logic for array fields.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!value) {
sql += ` AND ${key} IS NULL`;
return;
}
if (value === '') {
sql += ` AND ${key} IS NULL`;
return;
}

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.

3 participants