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

refactor: reduce conginitive complexity of the function #1891

Merged
merged 4 commits into from
Oct 17, 2024

Conversation

saikumarrs
Copy link
Member

@saikumarrs saikumarrs commented Oct 17, 2024

PR Description

Refactored an internal function to reduce its cognitive complexity as pointed out in the SonarCloud analysis.

Linear task (optional)

https://linear.app/rudderstack/issue/SDK-2159/fix-sonar-detected-issues

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

  • Improvements
    • Enhanced management of server-side cookies and data service URLs for better performance and reliability.
    • Streamlined logic for handling cookie options, ensuring correct attributes are set based on request conditions.
    • Introduced a new helper function to improve modularity and clarity in cookie management processes.
    • Added support for a sameDomainCookiesOnly property to better control cookie handling based on domain requirements.
    • Updated default load options to include a new cookie property for improved state management.
    • Adjusted size limit configuration for better resource allocation.

@saikumarrs saikumarrs self-assigned this Oct 17, 2024
@saikumarrs saikumarrs requested a review from a team as a code owner October 17, 2024 11:24
Copy link

codecov bot commented Oct 17, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 57.01%. Comparing base (7d4959b) to head (d340774).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1891      +/-   ##
===========================================
+ Coverage    56.99%   57.01%   +0.01%     
===========================================
  Files          476      476              
  Lines        16253    16260       +7     
  Branches      3237     3248      +11     
===========================================
+ Hits          9264     9271       +7     
+ Misses        5753     5744       -9     
- Partials      1236     1245       +9     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve significant updates to the commonUtil.ts, loadOptions.ts, and loadOptions.ts files. A new helper function, getServerSideCookiesStateData, has been introduced to manage server-side cookies and data service URL handling. The updateStorageStateFromLoadOptions function has been modified to utilize this new helper. Additionally, the normalizeLoadOptions function now includes a sameDomainCookiesOnly property, and the defaultLoadOptions object has been updated to include a new cookie property. These changes enhance the modularity and clarity of the code.

Changes

File Path Change Summary
packages/analytics-js/src/components/configManager/util/commonUtil.ts Added getServerSideCookiesStateData function; modified updateStorageStateFromLoadOptions to use the new function; updated handling of server-side cookies and data service URL logic.
packages/analytics-js/src/components/utilities/loadOptions.ts Added sameDomainCookiesOnly property to normalizedLoadOpts in normalizeLoadOptions function.
packages/analytics-js/src/state/slices/loadOptions.ts Added cookie property to the storage object in defaultLoadOptions.
packages/analytics-js/.size-limit.mjs Updated size limit for "Core (Content Script) - Modern - NPM (CJS)" from '38.5 KiB' to '40 KiB'.

Possibly related PRs

  • feat: set server side cookies #1649: This PR introduces a new load option for setting server-side cookies, which is directly related to the changes made in the commonUtil.ts file regarding server-side cookie management and the new helper function getServerSideCookiesStateData.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8bc43f4 and d340774.

📒 Files selected for processing (1)
  • packages/analytics-js/.size-limit.mjs (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/analytics-js/.size-limit.mjs (1)

116-116: Clarification needed on size limit increase

The size limit for "Core (Content Script) - Modern - NPM (CJS)" has been increased from 38.5 KiB to 40 KiB. While this change allows for a slightly larger bundle size, it raises some concerns:

  1. The PR objective mentions reducing cognitive complexity, but increasing the size limit seems counterintuitive to this goal. Can you explain how this change relates to the refactoring efforts?

  2. The comment at the top of the file explicitly states: "DO NOT EDIT the size limits configured in this file. Should you update them, please contact CODEOWNERS." Has this change been approved by the CODEOWNERS?

  3. What is the reason for this specific increase? Is it due to necessary additional code, or is it to accommodate the refactored code?

  4. Have you considered the impact on performance, especially for users with slower internet connections?

To better understand the context of this change, let's check the current size of the affected file:

This will help us determine if the size increase was necessary based on the current file size.


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

github-actions bot commented Oct 17, 2024

size-limit report 📦

Name Size (Base) Size (Current) Size Limit Status
Plugins Module Federation Mapping - Legacy - CDN 332 B 332 B (0%) 512 B
Plugins - Legacy - CDN 15.48 KB 15.48 KB (0%) 16 KB
Plugins Module Federation Mapping - Modern - CDN 331 B 331 B (0%) 512 B
Plugins - Modern - CDN 7.2 KB 7.2 KB (0%) 7.5 KB
Common - No bundling 16.11 KB 16.15 KB (+0.24% ▲) 16.5 KB
Cookies Utils - Legacy - NPM (ESM) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (CJS) 1.75 KB 1.75 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (UMD) 1.53 KB 1.53 KB (0%) 2 KB
Cookies Utils - Modern - NPM (ESM) 1.17 KB 1.17 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (CJS) 1.4 KB 1.4 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (UMD) 1.16 KB 1.16 KB (0%) 1.5 KB
Load Snippet 757 B 757 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.25 KB 30.25 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.48 KB 30.48 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.29 KB 30.29 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.8 KB 29.8 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 30.1 KB 30.1 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.87 KB 29.87 KB (0%) 30 KB
Core - Legacy - CDN 47.35 KB 47.43 KB (+0.19% ▲) 48 KB
Core - Modern - CDN 24.24 KB 24.28 KB (+0.16% ▲) 24.5 KB
Core - Legacy - NPM (ESM) 47.22 KB 47.28 KB (+0.14% ▲) 48 KB
Core - Legacy - NPM (CJS) 47.47 KB 47.53 KB (+0.14% ▲) 48 KB
Core - Legacy - NPM (UMD) 47.23 KB 47.34 KB (+0.25% ▲) 48 KB
Core - Modern - NPM (ESM) 23.99 KB 24.03 KB (+0.18% ▲) 24.5 KB
Core - Modern - NPM (CJS) 24.19 KB 24.22 KB (+0.12% ▲) 24.5 KB
Core - Modern - NPM (UMD) 24.03 KB 24.05 KB (+0.08% ▲) 24.5 KB
Core (Bundled) - Legacy - NPM (ESM) 47.22 KB 47.28 KB (+0.14% ▲) 48 KB
Core (Bundled) - Legacy - NPM (CJS) 47.56 KB 47.57 KB (+0.02% ▲) 48 KB
Core (Bundled) - Legacy - NPM (UMD) 47.23 KB 47.34 KB (+0.25% ▲) 48 KB
Core (Bundled) - Modern - NPM (ESM) 38.63 KB 38.69 KB (+0.16% ▲) 39 KB
Core (Bundled) - Modern - NPM (CJS) 38.93 KB 38.95 KB (+0.06% ▲) 39.5 KB
Core (Bundled) - Modern - NPM (UMD) 38.68 KB 38.72 KB (+0.09% ▲) 39 KB
Core (Content Script) - Legacy - NPM (ESM) 46.76 KB 46.8 KB (+0.08% ▲) 48 KB
Core (Content Script) - Legacy - NPM (CJS) 47.01 KB 47.03 KB (+0.05% ▲) 47.5 KB
Core (Content Script) - Legacy - NPM (UMD) 46.73 KB 46.8 KB (+0.15% ▲) 47.5 KB
Core (Content Script) - Modern - NPM (ESM) 38.15 KB 38.13 KB (-0.06% ▼) 38.5 KB
Core (Content Script) - Modern - NPM (CJS) 38.37 KB 38.53 KB (+0.41% ▲) 40 KB
Core (Content Script) - Modern - NPM (UMD) 38.12 KB 38.13 KB (+0.03% ▲) 38.5 KB
Service Worker - Legacy - NPM (ESM) 30.61 KB 30.61 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.85 KB 30.85 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.63 KB 30.63 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.74 KB 25.74 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 26.02 KB 26.02 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.79 KB 25.79 KB (0%) 26 KB
All Integrations - Legacy - CDN 94.26 KB 94.26 KB (0%) 95.3 KB
All Integrations - Modern - CDN 89.4 KB 89.4 KB (0%) 91 KB

MoumitaM
MoumitaM previously approved these changes Oct 17, 2024
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 (1)
packages/analytics-js/src/components/configManager/util/commonUtil.ts (1)

161-163: Refactor cookie options manipulation logic into a single location

There's a TODO comment indicating that the cookie options manipulation logic should be refactored into one place. Consolidating this logic will improve maintainability and reduce potential inconsistencies.

Would you like assistance in refactoring this code? I can help by suggesting how to modularize the cookie options manipulation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7d4959b and 226320a.

📒 Files selected for processing (1)
  • packages/analytics-js/src/components/configManager/util/commonUtil.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/analytics-js/src/components/configManager/util/commonUtil.ts (1)

132-202: Refactored function improves code maintainability

The updateStorageStateFromLoadOptions function has been successfully refactored to reduce cognitive complexity. The restructuring of logic related to server-side cookies and data service URL handling enhances readability and maintainability.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 17, 2024
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 (1)
packages/analytics-js/src/components/configManager/util/commonUtil.ts (1)

121-121: Address the TODO: Centralize cookie options manipulation

The TODO comment indicates a need to refactor the cookie options manipulation logic into a single location. Consolidating this logic will improve maintainability and reduce potential errors due to code duplication.

Would you like assistance in refactoring this logic? I can help propose a solution or open a GitHub issue to track this task.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 226320a and 2798c4f.

📒 Files selected for processing (1)
  • packages/analytics-js/src/components/configManager/util/commonUtil.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/analytics-js/src/components/configManager/util/commonUtil.ts (2)

81-158: Refactoring server-side cookies logic improves modularity

The extraction of server-side cookies and data service URL handling into the getServerSideCookiesStateData helper function enhances code modularity and reduces cognitive complexity in updateStorageStateFromLoadOptions.


205-206: Enhanced readability by integrating helper function

Updating updateStorageStateFromLoadOptions to utilize getServerSideCookiesStateData simplifies the function, making it more readable and maintainable.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 17, 2024
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/analytics-js/src/components/utilities/loadOptions.ts (1)

35-36: LGTM! Consider adding a comment for clarity.

The addition of the sameDomainCookiesOnly property normalization is implemented correctly and consistently with other boolean properties in the function. This change contributes to the PR's objective of reducing cognitive complexity.

For improved clarity, consider adding a brief comment explaining the purpose of this property:

+  // Normalize sameDomainCookiesOnly to restrict cookies to the same domain if set to true
   normalizedLoadOpts.sameDomainCookiesOnly = normalizedLoadOpts.sameDomainCookiesOnly === true;
packages/analytics-js/src/components/configManager/util/commonUtil.ts (1)

84-161: LGTM with suggestions: New helper function added

The new getServerSideCookiesStateData function effectively centralizes the logic for managing server-side cookies and data service URL handling. It properly handles various scenarios and edge cases, which is commendable.

However, consider the following suggestions to improve maintainability and readability:

  1. Break down the function into smaller, more focused helper functions. For example, you could create separate functions for determining the use of exact domain, handling cross-site requests, and validating the data service URL.

  2. Add more inline comments or JSDoc to explain the complex logic, especially around the conditions for enabling/disabling server-side cookies.

  3. Consider using early returns to reduce nesting and improve readability.

Would you like assistance in refactoring this function into smaller, more focused helper functions?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2798c4f and 8bc43f4.

📒 Files selected for processing (3)
  • packages/analytics-js/src/components/configManager/util/commonUtil.ts (3 hunks)
  • packages/analytics-js/src/components/utilities/loadOptions.ts (1 hunks)
  • packages/analytics-js/src/state/slices/loadOptions.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/analytics-js/src/state/slices/loadOptions.ts (1)

40-40: LGTM. Please provide more context on the cookie property.

The addition of the cookie property to the storage object in defaultLoadOptions is structurally sound and follows the existing code patterns.

However, to better understand the purpose and future usage of this property:

  1. Could you elaborate on the intended use of this cookie property?
  2. Are there plans to add specific cookie configuration options in the future?
  3. How does this change relate to the PR's objective of reducing cognitive complexity?

To ensure this change doesn't introduce unintended side effects, let's verify its usage:

✅ Verification successful

Verified the cookie property usage.

The addition of the cookie property has been successfully verified across the codebase. No unintended side effects were found, and the implementation aligns with existing usage patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any existing uses of the new cookie property

# Test 1: Search for direct access to storage.cookie
echo "Checking for direct access to storage.cookie:"
rg --type typescript "storage\.cookie" --glob '!**/loadOptions.ts'

# Test 2: Search for spread operator usage with storage, which might inadvertently include the new cookie property
echo "Checking for spread operator usage with storage:"
rg --type typescript "\.\.\.storage" --glob '!**/loadOptions.ts'

Length of output: 413


Script:

#!/bin/bash
# Description: Check for any existing uses of the new cookie property

# Test 1: Search for direct access to storage.cookie
echo "Checking for direct access to storage.cookie:"
rg "storage\.cookie" --glob '*.ts' --glob '*.tsx' --glob '!**/loadOptions.ts'

# Test 2: Search for spread operator usage with storage
echo "Checking for spread operator usage with storage:"
rg "\.\.\.storage" --glob '*.ts' --glob '*.tsx' --glob '!**/loadOptions.ts'

Length of output: 2929

packages/analytics-js/src/components/utilities/loadOptions.ts (1)

Line range hint 16-131: Consider refactoring for improved maintainability and type safety

While the changes made are good, there are a few suggestions to further improve the code:

  1. The normalizeLoadOptions function is quite long and handles many different properties. Consider splitting it into smaller, more focused functions for each group of related properties. This would improve readability and maintainability, further reducing cognitive complexity.

  2. There's a TODO comment at the beginning of the function suggesting the addition of warnings for invalid values. Consider implementing this to improve error handling and debugging.

  3. Some properties are using type assertions. Try to improve type safety by using type guards or refactoring to avoid the need for assertions.

Here's an example of how you might start refactoring:

const normalizeCookieOptions = (opts: Partial<LoadOptions>): Partial<LoadOptions> => {
  const normalized = { ...opts };
  
  if (!isString(normalized.setCookieDomain)) {
    delete normalized.setCookieDomain;
  }

  const cookieSameSiteValues = ['Strict', 'Lax', 'None'];
  if (!cookieSameSiteValues.includes(normalized.sameSiteCookie as CookieSameSite)) {
    delete normalized.sameSiteCookie;
  }

  normalized.secureCookie = normalized.secureCookie === true;
  normalized.sameDomainCookiesOnly = normalized.sameDomainCookiesOnly === true;

  return normalized;
}

// Use in main function
const normalizeLoadOptions = (
  loadOptionsFromState: LoadOptions,
  loadOptions: Partial<LoadOptions>,
): LoadOptions => {
  let normalizedLoadOpts = clone(loadOptions);
  
  normalizedLoadOpts = normalizeCookieOptions(normalizedLoadOpts);
  
  // ... other normalizations
}

To check for other potential SonarCloud issues, you can run the following command:

This will help identify long functions, type assertions, and TODO comments across the TypeScript files in the project.

🧰 Tools
🪛 Biome

[error] 39-39: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

packages/analytics-js/src/components/configManager/util/commonUtil.ts (2)

6-9: LGTM: Import statement updated correctly

The addition of the CookieOptions import from the Storage types is appropriate for the new functionality introduced in this file.


Line range hint 163-217: LGTM: Effective integration of new helper function

The changes to the updateStorageStateFromLoadOptions function successfully integrate the new getServerSideCookiesStateData helper function. The batch update at the end of the function has been appropriately modified to include the new state updates for server-side cookies and data service URL.

These changes improve the modularity of the code and make it easier to manage server-side cookie related state updates.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 17, 2024
Copy link

sonarcloud bot commented Oct 17, 2024

@saikumarrs saikumarrs merged commit df144f4 into develop Oct 17, 2024
13 checks passed
@saikumarrs saikumarrs deleted the refactor.for-sonar-issue-sdk-2159 branch October 17, 2024 14:23
@coderabbitai coderabbitai bot mentioned this pull request Oct 17, 2024
5 tasks
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.

2 participants