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(internal-plugin-metrics): allow caller to specify metadata of business metric events #4000

Open
wants to merge 1 commit into
base: next
Choose a base branch
from

Conversation

lialang-cisco
Copy link
Contributor

@lialang-cisco lialang-cisco commented Nov 21, 2024

COMPLETES #CX-17090

This pull request addresses CX-17090

by making the following changes, we allow consumers of the SDK to specify the metadata of business metric events that they send to Pinot.

This can be used to set the appType and indexHint for example.

Change Type

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Tooling change
  • Internal code refactor

The following scenarios were tested

Sent a metric event from the wxcc_desktop client using this new code path, and observed it in Pinot in the desired table. Added unit test.

I certified that

  • I have read and followed contributing guidelines

  • I discussed changes with code owners prior to submitting this pull request

  • I have not skipped any automated checks

  • All existing and new tests passed

  • I have updated the documentation accordingly


Make sure to have followed the contributing guidelines before submitting.

Summary by CodeRabbit

  • New Features

    • Enhanced event submission process with the introduction of an optional metadata parameter for improved flexibility in the submitBusinessEvent method.
  • Bug Fixes

    • Updated tests to ensure correct handling and submission of events with the new metadata parameter, enhancing error handling and logging mechanisms.
  • Tests

    • Expanded test coverage for the NewMetrics class to validate functionality and error handling scenarios related to event submissions.

@lialang-cisco lialang-cisco requested review from a team as code owners November 21, 2024 12:07
Copy link

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes in this pull request focus on enhancing the BusinessMetrics class by consolidating event submission methods. Several private methods were removed and replaced with a new private method called buildEvent, which constructs event objects with optional metadata. The submitBusinessEvent method was updated to include this new metadata parameter. Corresponding updates were made to the Metrics class and its tests, ensuring that the new functionality is thoroughly covered and validated.

Changes

File Change Summary
packages/@webex/internal-plugin-metrics/src/business-metrics.ts Removed private methods and added buildEvent method; updated submitBusinessEvent to include optional metadata parameter.
packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts Updated tests for submitBusinessEvent to include metadata in the payload for business_metrics.
packages/@webex/internal-plugin-metrics/src/new-metrics.ts Updated submitBusinessEvent method to include metadata parameter; adjusted implementation accordingly.
packages/@webex/internal-plugin-metrics/test/unit/spec/new-metrics.ts Modified tests for NewMetrics class to include metadata in submitBusinessEvent method calls; enhanced error handling tests.

Possibly related PRs

Suggested labels

validated

Suggested reviewers

  • Shreyas281299
  • adhmenon

Poem

🐇 In the meadow where metrics play,
Events are built in a brand new way.
With metadata now in tow,
Business insights start to glow!
Hopping through code, we celebrate,
A streamlined path, oh how great! 🌼

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.

warning [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/[email protected]: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/[email protected]: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > [email protected]: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning eslint-import-resolver-typescript > [email protected]: Glob versions prior to v9 are no longer supported
warning [email protected]: Glob versions prior to v9 are no longer supported
warning intern > [email protected]: Glob versions prior to v9 are no longer supported
warning intern > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning jasmine > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-config > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-runtime > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/reporters > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/transform > babel-plugin-istanbul > test-exclude > [email protected]: Glob versions prior to v9 are no longer supported
warning mocha > [email protected]: Glob versions prior to v9 are no longer supported
warning mocha > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning [email protected]: 16.1.1
warning wd > [email protected]: You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.

(For a CapTP with native promises, see @endo/eventual-send and @endo/captp)
warning wd > archiver > [email protected]: Glob versions prior to v9 are no longer supported
warning wd > [email protected]: request has been deprecated, see request/request#3142
warning wd > archiver > archiver-utils > [email protected]: Glob versions prior to v9 are no longer supported
warning wd > request > [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
warning wd > request > [email protected]: this library is no longer supported
warning @babel/cli > [email protected]: Glob versions prior to v9 are no longer supported
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-async-generator-functions instead.
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-export-namespace-from instead.
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.
warning @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning @babel/[email protected]: 🚨 This package has been deprecated in favor of separate inclusion of a polyfill and regenerator-runtime (when needed). See the @babel/polyfill docs (https://babeljs.io/docs/en/babel-polyfill) for more information.
warning @babel/polyfill > [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
warning @babel/runtime-corejs2 > [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
warning babel-plugin-lodash > [email protected]: Glob versions prior to v9 are no longer supported
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > [email protected]: Glob versions prior to v9 are no longer supported
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > [email protected]: 16.1.1
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-async-generator-functions instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-export-namespace-from instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning workspace-aggregator-d1dcb369-ab94-4cbc-a904-a13f5761b72e > @babel/[email protected]: 🚨 This package has been deprecated in favor of separate inclusion of a polyfill and regenerator-runtime (when needed). See the @babel/polyfill docs (https://babeljs.io/docs/en/babel-polyfill) for more information.
error [email protected]: The engine "node" is incompatible with this module. Expected version "^14 || ^16 || ^17 || ^18 || ^19". Got "22.9.0"
error Found incompatible module.


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

This pull request is automatically being deployed by Amplify Hosting (learn more).

Access this pull request here: https://pr-4000.d3m3l2kee0btzx.amplifyapp.com

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

🧹 Outside diff range and nitpick comments (3)
packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2)

65-71: Fix typo in documentation

The JSDoc comment contains a typo in the word "buisness".

-   * Submit a buisness metric to our metrics endpoint
+   * Submit a business metric to our metrics endpoint

72-89: Consider refactoring to reduce code duplication

The event construction logic is very similar across all submit methods. Consider extracting the common event construction logic into a shared private method.

Example refactor:

private createBaseEvent(name: string, payload: EventPayload, appType: string, options?: {indexHint?: string}) {
  return {
    type: ['business'],
    eventPayload: {
      key: name,
      client_timestamp: new Date().toISOString(),
      appType,
      ...(options?.indexHint && {indexHint: options.indexHint}),
      value: {
        ...this.getContext(),
        ...this.getBrowserDetails(),
        ...payload,
      },
    },
  };
}

private submitWxccDesktopEvent({name, payload}: {name: string; payload: EventPayload}) {
  const event = this.createBaseEvent(name, payload, 'WxCC Desktop', {indexHint: 'wxccdesktop'});
  return this.submitEvent({
    kind: 'business-events:business_metrics_wxcc_desktop -> ',
    name,
    event,
  });
}
packages/@webex/internal-plugin-metrics/src/metrics.types.ts (1)

172-177: LGTM! Consider adding documentation.

The addition of 'business_metrics_wxcc_desktop' to the Table type is well-structured and aligns with the FedRAMP compliance requirements. The change is non-breaking and follows the existing naming patterns.

Consider adding a JSDoc comment above the Table type to document the purpose of each table, particularly the new business_metrics_wxcc_desktop table. This would improve maintainability and help other developers understand when to use each table type.

+/**
+ * Defines the available metric table destinations
+ * @property business_metrics_wxcc_desktop - Table for FedRAMP compliance metrics from wxcc desktop client
+ * ... document other table types ...
+ */
 export type Table =
   | 'wbxapp_callend_metrics'
   | 'business_metrics'
   | 'business_ucf'
   | 'business_metrics_wxcc_desktop'
   | 'default';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8d6d1bc and ea3c708.

📒 Files selected for processing (3)
  • packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2 hunks)
  • packages/@webex/internal-plugin-metrics/src/metrics.types.ts (1 hunks)
  • packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts

[error] 208-208: This property value named locale is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named locale

(lint/suspicious/noDuplicateObjectKeys)

🔇 Additional comments (5)
packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2)

141-142: LGTM!

The switch case addition is clean and follows the established pattern.


Line range hint 65-142: Verify test coverage for the new functionality

The PR objectives mention that unit tests were added, but they're not visible in the provided files. Please ensure that:

  1. Test cases cover the new submitWxccDesktopEvent method
  2. Test cases verify the correct event structure including the indexHint and appType fields
  3. Test cases validate the new table option in submitBusinessEvent
✅ Verification successful

Let me check the test file content to verify the test coverage.


Test coverage is complete and accurate

The test file includes comprehensive coverage for the new functionality:

  • Test case verifies submitWxccDesktopEvent through the business_metrics_wxcc_desktop table option
  • Validates correct event structure including indexHint: 'wxccdesktop' and appType: 'WxCC Desktop'
  • Asserts the proper payload structure and timestamp handling
  • Confirms the integration with the table routing in submitBusinessEvent
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related test files and their coverage of the new functionality
fd -e test.ts -e spec.ts . | xargs rg -l "business_metrics_wxcc_desktop"

# Look for existing test patterns that should be followed
rg -A 5 "describe.*BusinessMetrics" 

Length of output: 754


Script:

#!/bin/bash
# Check the content of the test file
cat "packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts"

Length of output: 8712

packages/@webex/internal-plugin-metrics/src/metrics.types.ts (1)

172-177: Verify handling of the new table type.

Let's ensure the new table type is properly handled throughout the codebase.

✅ Verification successful

Let me generate another script to check for switch statements handling the table type more specifically:


The new table type is properly handled throughout the codebase

The verification shows that:

  1. The new table type is properly handled in the switch statement with a dedicated case that maps to submitWxccDesktopEvent
  2. The type is properly defined in metrics.types.ts
  3. The implementation includes proper documentation for the new table type
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify proper handling of the new table type

# Check for switch/case statements that handle table types
echo "Checking for switch statements handling table types..."
rg -A 5 "switch.*\(.*[tT]able.*\)" 

# Check for hardcoded table type strings
echo "Checking for hardcoded table type strings..."
rg -i "business_metrics_wxcc_desktop"

# Check for type imports
echo "Checking for Table type imports..."
rg "import.*\{.*Table.*\}.*from.*metrics\.types"

Length of output: 132172


Script:

#!/bin/bash
# Check for switch statements handling table types in business-metrics.ts
echo "Checking switch statement handling of table types..."
rg -A 10 "switch.*\(.*table.*\)" packages/@webex/internal-plugin-metrics/src/business-metrics.ts

# Check for any other references to the table type
echo "Checking for other table type references..."
rg -A 2 "business_metrics_wxcc_desktop" packages/@webex/internal-plugin-metrics/src/

Length of output: 1793

packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts (2)

185-219: LGTM! Test structure follows established patterns.

The new test case is well-organized and follows the existing test structure, maintaining consistency with other table-specific tests.

🧰 Tools
🪛 Biome

[error] 208-208: This property value named locale is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named locale

(lint/suspicious/noDuplicateObjectKeys)


185-219: Verify FedRAMP compliance requirements coverage.

While the test covers the basic functionality, please verify if there are any additional FedRAMP-specific requirements that need to be validated in the test case, such as:

  • Required fields for compliance
  • Data format validations
  • Security-related assertions

Let me help verify the FedRAMP requirements:

🧰 Tools
🪛 Biome

[error] 208-208: This property value named locale is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named locale

(lint/suspicious/noDuplicateObjectKeys)

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

🧹 Outside diff range and nitpick comments (5)
packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2)

11-27: Improve type safety and documentation of buildEvent method.

The method implementation looks good, but could benefit from stronger typing and better documentation:

/**
+ * @private
 * Build the metric event to submit.
 * @param {string} name of the metric
 * @param {EventPayload} payload user payload of the metric
 * @param {EventPayload} metadata to include outside of eventPayload.value
- * @returns {object}
+ * @returns {MetricEvent} The constructed metric event
 */
private buildEvent({name, payload, metadata}: {
  name: string;
- payload: object;
- metadata: object;
+ payload: EventPayload;
+ metadata: EventPayload;
}): MetricEvent {

Consider adding a MetricEvent interface to define the return type structure.


Update the Table type to include the new FedRAMP table

The Table type in metrics.types.ts needs to be updated to include the new business_metrics_wxcc_desktop table for FedRAMP compliance. Also, there's a typo in the JSDoc comment where "buisness" should be "business".

  • In packages/@webex/internal-plugin-metrics/src/metrics.types.ts:
    export type Table = 'wbxapp_callend_metrics' | 'business_metrics' | 'business_ucf' | 'business_metrics_wxcc_desktop' | 'default';
  • In packages/@webex/internal-plugin-metrics/src/business-metrics.ts:
    /**
     * Submit a business metric to our metrics endpoint.
     */
🔗 Analysis chain

Line range hint 28-49: Fix documentation issues and update Table type.

  1. There's a typo in "buisness" in the JSDoc.
  2. The Table type needs to be updated to include the new business_metrics_wxcc_desktop table mentioned in the PR objectives.
/**
- * Submit a buisness metric to our metrics endpoint.
+ * Submit a business metric to our metrics endpoint.
 */

Let's verify if the Table type has been updated:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if Table type includes the new table
rg -A 10 "export type Table =" packages/@webex/internal-plugin-metrics/src/metrics.types.ts

Length of output: 583

🧰 Tools
🪛 Biome (1.9.4)

[error] 93-93: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)


[error] 94-94: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

packages/@webex/internal-plugin-metrics/test/unit/spec/new-metrics.ts (1)

96-103: Enhance test coverage for metadata parameter

While the basic metadata functionality is tested, consider adding the following test cases for more comprehensive coverage:

  1. Test with actual FedRAMP-related metadata fields
  2. Test with missing/undefined metadata (optional parameter)
  3. Test with the specific business_metrics_wxcc_desktop table mentioned in PR objectives

Example test case structure:

it('handles business_metrics_wxcc_desktop table with FedRAMP metadata', () => {
  webex.internal.newMetrics.submitBusinessEvent({
    name: 'fedRampMetric',
    payload: {},
    table: 'business_metrics_wxcc_desktop',
    metadata: {
      complianceFramework: 'FedRAMP',
      securityLevel: 'moderate',
      // Add other relevant FedRAMP fields
    },
  });
  
  // Assert the call
});

it('handles missing metadata parameter', () => {
  webex.internal.newMetrics.submitBusinessEvent({
    name: 'metricWithoutMeta',
    payload: {},
    table: 'business_metrics_wxcc_desktop'
  });
  
  // Assert the call
});
packages/@webex/internal-plugin-metrics/src/new-metrics.ts (2)

210-216: Add JSDoc documentation for the metadata parameter

The implementation looks good, but please add documentation for the new metadata parameter to maintain consistency with the existing JSDoc comments.

Apply this diff to add the documentation:

   /**
    * Buisness event
    * @param args
+   * @param {EventPayload} [args.metadata] - Optional metadata for the business event
    */

Line range hint 210-228: Consider adding metadata validation

The implementation correctly handles the new metadata parameter, but consider adding validation to ensure the metadata meets any FedRAMP compliance requirements before passing it to the business metrics table.

Example validation approach:

   submitBusinessEvent({
     name,
     payload,
     table,
     metadata,
   }: {
     name: string;
     payload: EventPayload;
     table?: Table;
     metadata?: EventPayload;
   }) {
     if (!this.isReady) {
       // @ts-ignore
       this.webex.logger.log(
         `NewMetrics: @submitBusinessEvent. Attempted to submit before webex.ready: ${name}`
       );
 
       return Promise.resolve();
     }
 
     this.lazyBuildBusinessMetrics();
 
+    // Validate metadata if present
+    if (metadata) {
+      // Add validation logic specific to FedRAMP requirements
+      // Example: Check for required fields, data types, or sensitive information
+      if (!this.isValidMetadata(metadata)) {
+        return Promise.reject(new Error('Invalid metadata format for FedRAMP compliance'));
+      }
+    }
+
     return this.businessMetrics.submitBusinessEvent({name, payload, table, metadata});
   }
+
+  /**
+   * Validates metadata for FedRAMP compliance
+   * @private
+   */
+  private isValidMetadata(metadata: EventPayload): boolean {
+    // Add validation rules based on FedRAMP requirements
+    return true;
+  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ea3c708 and 7a919a2.

📒 Files selected for processing (4)
  • packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2 hunks)
  • packages/@webex/internal-plugin-metrics/src/new-metrics.ts (2 hunks)
  • packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts (1 hunks)
  • packages/@webex/internal-plugin-metrics/test/unit/spec/new-metrics.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/@webex/internal-plugin-metrics/test/unit/spec/business/business-metrics.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/@webex/internal-plugin-metrics/src/business-metrics.ts

[error] 93-93: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)


[error] 94-94: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

🔇 Additional comments (3)
packages/@webex/internal-plugin-metrics/src/business-metrics.ts (2)

60-91: ⚠️ Potential issue

Fix typo in event kind parameter.

There's a typo in the event kind parameter:

-          kind: 'buisness-events:wbxapp_callend_metrics -> ',
+          kind: 'business-events:wbxapp_callend_metrics -> ',
-          kind: 'buisness-events:business_metrics -> ',
+          kind: 'business-events:business_metrics -> ',

53-58: Review default appType for wxcc_desktop metrics.

The default appType is set to 'Web Client', which might not be appropriate for metrics being sent to the business_metrics_wxcc_desktop table. Consider making this configurable or setting it based on the target table.

Let's check for other appType usages:

packages/@webex/internal-plugin-metrics/src/new-metrics.ts (1)

228-228: Verify metadata handling in BusinessMetrics class

Let's verify how the metadata is handled in the BusinessMetrics class implementation.

✅ Verification successful

Metadata is properly handled in BusinessMetrics implementation

The BusinessMetrics class correctly implements metadata handling:

  • The submitBusinessEvent method accepts metadata as an optional parameter
  • Metadata is properly initialized to an empty object if not provided
  • The buildEvent method correctly incorporates metadata into the eventPayload structure
  • Different table cases (wbxapp_callend_metrics, business_metrics, business_ucf/default) all properly handle the metadata parameter
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of metadata handling in BusinessMetrics class

# Look for the submitBusinessEvent method in BusinessMetrics class
ast-grep --pattern 'class BusinessMetrics {
  $$$
  submitBusinessEvent($_) {
    $$$
  }
  $$$
}'

# Search for any existing metadata handling
rg -l "metadata.*EventPayload" --type ts

Length of output: 266


Script:

#!/bin/bash
# Let's check the implementation of submitBusinessEvent in business-metrics.ts
rg -A 10 "submitBusinessEvent" packages/@webex/internal-plugin-metrics/src/business-metrics.ts

# Also check the type definition for metadata
rg "interface.*EventPayload" -A 5 packages/@webex/internal-plugin-metrics/src/business-metrics.ts

Length of output: 395


Script:

#!/bin/bash
# Let's get more context around the submitBusinessEvent implementation
rg -B 5 -A 15 "submitBusinessEvent" packages/@webex/internal-plugin-metrics/src/business-metrics.ts

# Also check the full file content to understand the metadata handling
cat packages/@webex/internal-plugin-metrics/src/business-metrics.ts

Length of output: 4276

@lialang-cisco lialang-cisco changed the title feat(internal-plugin-metrics): add business_metrics_wxcc_desktop feat(internal-plugin-metrics): allow caller to specify metadata of business metric events Nov 27, 2024
assert.equal(requestCalls.length, 1)
assert.deepEqual(requestCalls[0], {
eventPayload: {
key: 'foobar',
asdf: 'hjkl',

Choose a reason for hiding this comment

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

So, if the given metadata field already exists in the request, then this input will override it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yep, that's right

@@ -173,7 +174,6 @@ describe('internal-plugin-metrics', () => {
os: getOSNameInternal(),
app: {version: 'webex-version'},
device: {id: 'deviceId'},
locale: 'language',
Copy link
Contributor Author

Choose a reason for hiding this comment

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

duplicate, locale is already included a few lines above

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