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

feat: add session replay for mixpanel #1899

Merged
merged 8 commits into from
Oct 25, 2024

Conversation

shrouti1507
Copy link
Contributor

@shrouti1507 shrouti1507 commented Oct 22, 2024

PR Description

Adding session replay feature for mixpanel.
Ref: https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript#session-replay

Linear task (optional)

Linear task link

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

  • New Features

    • Introduced a sessionReplayPercentage property to enhance session replay capabilities in the Mixpanel integration.
    • Added a new function, getDestinationOptions, for improved retrieval of destination-specific options, ensuring backward compatibility.
  • Tests

    • Expanded test suite with new cases for validating session replay configuration and error handling, ensuring robust coverage for various scenarios.

@shrouti1507 shrouti1507 requested review from a team and ItsSudip October 22, 2024 04:45
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Warning

Rate limit exceeded

@shrouti1507 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 28 minutes and 55 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

Files that changed from the base of the PR and between 71defdb and c23e83a.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request enhance the Mixpanel integration within the analytics-js library. A new property, sessionReplayPercentage, is introduced in the Mixpanel class, allowing for session replay configuration. The init method is updated to incorporate a new configuration object, mixpanelIntgConfig, which facilitates session replay settings. Additionally, a new utility function, getDestinationOptions, is added to retrieve integration options, ensuring backward compatibility. These modifications aim to improve session replay capabilities without changing the existing public interface or overall functionality.

Changes

File Change Summary
packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js Added sessionReplayPercentage property to Mixpanel class; updated init method to include mixpanelIntgConfig and session replay configuration. Changed options declaration from const to let.
packages/analytics-js-integrations/src/integrations/Mixpanel/util.js Added getDestinationOptions function for retrieving destination-specific options; updated exports to include this new function.
packages/analytics-js-integrations/tests/integrations/Mixpanel/browser.test.js Added new test cases for session replay configuration, including validation of parameters and error handling for invalid session replay percentage.

Possibly related PRs

  • fix: auto session tracking #1856: The changes in this PR enhance session tracking logic, which is directly related to the modifications made in the main PR regarding session replay capabilities in the Mixpanel integration. Both PRs focus on improving session management and tracking functionalities.

Suggested reviewers

  • saikumarrs

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

🧹 Outside diff range and nitpick comments (4)
packages/analytics-js-integrations/src/integrations/Mixpanel/util.js (1)

276-285: LGTM: Well-implemented getDestinationOptions function with clear documentation.

The new getDestinationOptions function is well-implemented and documented. It provides a clean way to retrieve destination-specific options with backward compatibility.

Consider adding null safety to the return statement for extra robustness:

-const getDestinationOptions = integrationsOptions =>
-  integrationsOptions && (integrationsOptions[DISPLAY_NAME] || integrationsOptions[NAME]);
+const getDestinationOptions = integrationsOptions =>
+  integrationsOptions ? (integrationsOptions[DISPLAY_NAME] || integrationsOptions[NAME]) : undefined;

This change ensures that undefined is explicitly returned when integrationsOptions is falsy, maintaining consistent behavior across all scenarios.

packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (3)

70-70: LGTM: New property for session replay configuration.

The sessionReplayPercentage property is correctly added to support the new session replay feature. Consider adding a default value or type checking for robustness.

Consider adding a default value or type checking:

-    this.sessionReplayPercentage = config.sessionReplayPercentage;
+    this.sessionReplayPercentage = config.sessionReplayPercentage || 0; // Default to 0% if not specified

Line range hint 77-114: LGTM with suggestions: Session replay configuration added.

The changes correctly implement the session replay configuration. However, consider the following improvements:

  1. Instead of changing options to let, consider creating a separate object for session replay config and then merging it with options.
  2. The sessionReplayConfig object could be moved to a separate method for better readability.
  3. Consider adding null checks for mixpanelIntgConfig properties.

Here's a suggested refactoring:

init() {
  // ... existing code ...

  const options = {
    cross_subdomain_cookie: this.crossSubdomainCookie || false,
    secure_cookie: this.secureCookie || false,
    // ... other existing options ...
  };

  const mixpanelIntgConfig = getDestinationOptions(this.analytics.loadOnlyIntegrations);
  if (mixpanelIntgConfig) {
    const sessionReplayConfig = this.getSessionReplayConfig(mixpanelIntgConfig);
    Object.assign(options, removeUndefinedAndNullValues(sessionReplayConfig));
  }

  // ... rest of the method ...
}

getSessionReplayConfig(mixpanelIntgConfig) {
  return {
    record_sessions_percent: this.sessionReplayPercentage,
    record_block_class: mixpanelIntgConfig?.recordBlockClass,
    record_collect_fonts: mixpanelIntgConfig?.recordCollectFonts,
    record_idle_timeout_ms: mixpanelIntgConfig?.recordIdleTimeout,
    record_mask_text_class: mixpanelIntgConfig?.recordMaskTextClass,
    record_mask_text_selector: mixpanelIntgConfig?.recordMaskTextSelector,
    record_max_ms: mixpanelIntgConfig?.recordMaxMs,
    record_min_ms: mixpanelIntgConfig?.recordMinMs
  };
}

This refactoring improves readability and maintainability of the code.


Line range hint 1-424: Suggestion: Add tests and documentation for session replay feature.

While the implementation looks correct, it's important to ensure that the new session replay functionality is properly tested and documented. Consider the following suggestions:

  1. Add unit tests for the new getSessionReplayConfig method (if implemented as suggested in the previous comment).
  2. Update existing tests for the init method to cover the new session replay configuration.
  3. Add documentation comments explaining the purpose and usage of the new sessionReplayPercentage property and how it affects the Mixpanel integration.
  4. Consider adding a section in the class-level documentation about the session replay feature and how to configure it.

Would you like assistance in drafting test cases or documentation for the new session replay feature?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2365e1c and 3cae53b.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (3 hunks)
  • packages/analytics-js-integrations/src/integrations/Mixpanel/util.js (3 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/analytics-js-integrations/src/integrations/Mixpanel/util.js (3)

5-5: LGTM: Import statement updated correctly.

The addition of the NAME constant to the import statement is consistent with its usage in the new getDestinationOptions function. This change maintains good module organization.


300-300: LGTM: Export statement updated correctly.

The addition of getDestinationOptions to the export statement is appropriate, making the new utility function available for use in other parts of the application.


Line range hint 1-301: Overall assessment: Well-implemented changes enhancing Mixpanel integration options retrieval.

The changes to this file are well-structured and purposeful. They introduce a new utility function getDestinationOptions that enhances the flexibility of retrieving Mixpanel integration options. The implementation is backward-compatible and well-documented. The minor suggestion for null safety in the getDestinationOptions function is the only point for potential improvement.

To ensure the changes don't introduce any unintended side effects, please run the following verification script:

This script will help identify any areas in the codebase that might need to be updated to use the new getDestinationOptions function, as well as any existing error handling that might need to be adjusted.

packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (1)

19-19: LGTM: New import for session replay functionality.

The addition of getDestinationOptions import is consistent with the new session replay feature being implemented.

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

codecov bot commented Oct 22, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 57.37%. Comparing base (5590af7) to head (c23e83a).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1899      +/-   ##
===========================================
+ Coverage    57.34%   57.37%   +0.03%     
===========================================
  Files          482      482              
  Lines        16417    16430      +13     
  Branches      3294     3274      -20     
===========================================
+ Hits          9414     9427      +13     
- Misses        5725     5767      +42     
+ Partials      1278     1236      -42     

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

Copy link

github-actions bot commented Oct 22, 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.56 KB 15.56 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.22 KB 16.22 KB (0%) 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 758 B 758 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.28 KB 30.28 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.52 KB 30.52 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.31 KB 30.31 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.79 KB 29.79 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 30.06 KB 30.06 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.91 KB 29.91 KB (0%) 30 KB
Core - Legacy - CDN 48.34 KB 48.34 KB (0%) 48.5 KB
Core - Modern - CDN 24.79 KB 24.79 KB (0%) 25 KB
Core - Legacy - NPM (ESM) 48.24 KB 48.24 KB (0%) 48.5 KB
Core - Legacy - NPM (CJS) 48.49 KB 48.49 KB (0%) 48.5 KB
Core - Legacy - NPM (UMD) 48.2 KB 48.2 KB (0%) 48.5 KB
Core - Modern - NPM (ESM) 24.53 KB 24.53 KB (0%) 25 KB
Core - Modern - NPM (CJS) 24.72 KB 24.72 KB (0%) 25 KB
Core - Modern - NPM (UMD) 24.53 KB 24.53 KB (0%) 25 KB
Core (Bundled) - Legacy - NPM (ESM) 48.24 KB 48.24 KB (0%) 48.5 KB
Core (Bundled) - Legacy - NPM (CJS) 48.44 KB 48.44 KB (0%) 48.5 KB
Core (Bundled) - Legacy - NPM (UMD) 48.2 KB 48.2 KB (0%) 48.5 KB
Core (Bundled) - Modern - NPM (ESM) 39.34 KB 39.34 KB (0%) 39.5 KB
Core (Bundled) - Modern - NPM (CJS) 39.67 KB 39.67 KB (0%) 40 KB
Core (Bundled) - Modern - NPM (UMD) 39.39 KB 39.39 KB (0%) 39.5 KB
Core (Content Script) - Legacy - NPM (ESM) 47.69 KB 47.69 KB (0%) 48 KB
Core (Content Script) - Legacy - NPM (CJS) 47.91 KB 47.91 KB (0%) 48 KB
Core (Content Script) - Legacy - NPM (UMD) 47.68 KB 47.68 KB (0%) 48 KB
Core (Content Script) - Modern - NPM (ESM) 38.81 KB 38.81 KB (0%) 39 KB
Core (Content Script) - Modern - NPM (CJS) 39.07 KB 39.07 KB (0%) 40 KB
Core (Content Script) - Modern - NPM (UMD) 38.72 KB 38.72 KB (0%) 39 KB
Service Worker - Legacy - NPM (ESM) 30.6 KB 30.6 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.91 KB 30.91 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.64 KB 30.64 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.75 KB 25.75 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 26 KB 26 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.79 KB 25.79 KB (0%) 26 KB
All Integrations - Legacy - CDN 94.15 KB 94.48 KB (+0.35% ▲) 95.3 KB
All Integrations - Modern - CDN 89.35 KB 89.68 KB (+0.38% ▲) 91 KB

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

🧹 Outside diff range and nitpick comments (3)
packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (2)

75-75: LGTM: New sessionReplayPercentage property added.

The sessionReplayPercentage property is correctly initialized from the config object. Consider adding a comment or updating the class documentation to explain the purpose and expected values of this new property.


Line range hint 82-129: LGTM: Session replay configuration added with proper validation.

The implementation of session replay configuration is well-structured and includes appropriate validation for the sessionReplayPercentage. The use of removeUndefinedAndNullValues ensures clean configuration objects.

Consider extracting the session replay configuration logic into a separate method for improved readability and maintainability.

packages/analytics-js-integrations/__tests__/integrations/Mixpanel/browser.test.js (1)

182-215: Ensure consoleSpy is properly restored even if the test fails

Currently, consoleSpy.mockRestore() is called at the end of the test. If an assertion fails before this call, the mock may not be restored, potentially affecting other tests. To prevent this, wrap the test code in a try...finally block to ensure consoleSpy is restored regardless of test outcomes.

Apply this diff to adjust the test:

      test('Session replay configuration with invalid percentage', () => {
        const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+       try {
          // Existing test code...
          mixpanel.init();

          expect(window.mixpanel._i[0][1]).toEqual({
            cross_subdomain_cookie: false,
            secure_cookie: false,
            persistence: 'localStorage',
            persistence_name: 'test',
            loaded: expect.any(Function),
          });

          expect(consoleSpy).toHaveBeenCalledWith(
            '%c RS SDK - Mixpanel %c Invalid sessionReplayPercentage: 101. It should be a string matching the pattern "^(100|[1-9]?[0-9])$"',
            'font-weight: bold; background: black; color: white;',
            'font-weight: normal;',
          );
        }
+       finally {
          consoleSpy.mockRestore();
        }
      });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3cae53b and 274007d.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/tests/integrations/Mixpanel/browser.test.js (1 hunks)
  • packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (4 hunks)
🧰 Additional context used
🔇 Additional comments (5)
packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js (2)

8-13: LGTM: New utility imports added.

The additional imports from commonUtils are appropriate for the new functionality being implemented.


Line range hint 1-424: Overall: Well-implemented session replay functionality.

The changes to add session replay for Mixpanel are well-structured and properly integrated into the existing Mixpanel class. The implementation includes appropriate configuration handling and validation.

To ensure the reliability of these changes:

  1. Add unit tests for the new session replay configuration logic.
  2. Perform integration tests to verify the correct interaction with the Mixpanel SDK.
  3. Conduct cross-browser testing as mentioned in the PR objectives.

Run the following script to check for existing tests related to the new functionality:

packages/analytics-js-integrations/__tests__/integrations/Mixpanel/browser.test.js (3)

80-122: Tests for session replay configuration are comprehensive and well-structured

The added test thoroughly covers the session replay configuration with all options provided, ensuring that the integration behaves as expected.


124-154: Partial session replay options are correctly validated

The test accurately checks the behavior when only partial session replay options are provided, confirming that defaults and optional parameters are handled appropriately.


156-181: Handling of missing loadOnlyIntegrations is properly tested

This test ensures that the integration correctly processes the session replay configuration even when loadOnlyIntegrations is not specified, enhancing the robustness of the code.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 22, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 22, 2024
ItsSudip
ItsSudip previously approved these changes Oct 24, 2024
Copy link

@shrouti1507 shrouti1507 merged commit bfa9d0a into develop Oct 25, 2024
12 checks passed
@shrouti1507 shrouti1507 deleted the feat.mixpanel-session-replay branch October 25, 2024 04:15
@coderabbitai coderabbitai bot mentioned this pull request Jan 6, 2025
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants