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: onboard plugin integration service #2832

Closed
wants to merge 13 commits into from

Conversation

utsabc
Copy link
Member

@utsabc utsabc commented Nov 16, 2023

Onboarding Plugin Integration Service

This PR introduces onboarding of plugin integration framework to transformer, we take the approach of onboarding a new service aligning to the predefined interface to dictate the service structure

Major Piece of event order orchestration for transformer <> server contract lie in pluginAdapter.ts which after passing the events to integration plugin and handles the consistent structuring for responding back to outer layer

The pluginAdapter uses integration-store to get integration-plugin to do either processor/router transformer

Further we updated type definitions referencing from integrations-lib which acts as a common library

Resolves
INT-837

Description here

Type of change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

Related issues

Fix #1

Checklists

Development

  • Lint rules pass locally
  • The code changed/added as part of this pull request has been covered with tests
  • All tests related to the changed code pass in development

Code review

  • This pull request has a descriptive title and information useful to a reviewer. There may be a screenshot or screencast attached
  • "Ready for review" label attached to the PR and reviewers mentioned in a comment
  • Changes have been reviewed by at least one other engineer
  • Issue from task tracker has a link to this pull request

Summary by CodeRabbit

  • New Features

    • Introduced a new PluginAdapter for data transformation at processor and router levels.
    • Added a new PluginIntegrationService to handle plugin destinations.
    • Implemented a new constant PLUGIN_DEST for integration services.
  • Bug Fixes

    • Fixed a syntax error in the CHANNELS object definition.
  • Documentation

    • Updated inline comments for ESLint rule exceptions.
  • Refactor

    • Enhanced the ServiceSelector class to support plugin destinations.
    • Modified the getTestThreshold function for better property access.
    • Streamlined the handling of batchedRequest in DestinationPostTransformationService.
    • Adjusted imports for Metadata to use the @rudderstack/integrations-lib package.
  • Tests

    • Expanded test cases to include the IsProcessorEnabled property.
    • Updated integration tests to support plugin destinations and mock Axios adapters.
  • Chores

    • Updated type imports and renamed Metadata to TransformedOutput in type definitions.

@utsabc utsabc requested review from a team and sivashanmukh as code owners November 16, 2023 13:18
Copy link

codecov bot commented Nov 16, 2023

Codecov Report

Attention: Patch coverage is 91.32948% with 15 lines in your changes are missing coverage. Please review.

Project coverage is 87.20%. Comparing base (f6652b5) to head (66ecdd6).
Report is 211 commits behind head on develop.

Files Patch % Lines
src/services/destination/pluginIntegration.ts 57.57% 14 Missing ⚠️
src/helpers/serviceSelector.ts 90.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2832      +/-   ##
===========================================
+ Coverage    87.18%   87.20%   +0.02%     
===========================================
  Files          529      531       +2     
  Lines        28659    28824     +165     
  Branches      6824     6837      +13     
===========================================
+ Hits         24985    25135     +150     
- Misses        3340     3355      +15     
  Partials       334      334              

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

Copy link
Contributor

coderabbitai bot commented Nov 28, 2023

Important

Auto Review Skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository.

To trigger a single review, invoke the @coderabbitai review command.

Walkthrough

The codebase has been updated with a focus on enhancing plugin integration capabilities. A new PluginAdapter class has been introduced to handle data transformations at different levels, and the ServiceSelector has been updated to include plugin destinations. Changes to constants and types reflect the integration of plugins and adjustments to transformation responses. The PluginIntegrationService has been expanded with new methods, although some functionalities remain unimplemented. Adjustments to existing services and tests align with these new features and the broader integration strategy.

Changes

File Path Change Summary
src/helpers/pluginAdapter.ts
src/services/destination/pluginIntegration.ts
Introduced PluginAdapter and PluginIntegrationService for handling plugin-related transformations and integrations.
src/helpers/serviceSelector.ts
src/routes/utils/constants.js
Added logic and constants for handling plugin destinations.
src/services/comparator.ts
src/services/misc.ts
src/types/index.ts
Updated imports and types to align with the new plugin integration system.
src/services/destination/postTransformation.ts
src/services/userTransform.ts
Modified transformation logic and types to support the updated system.
test/controllerUtility/ctrl-utility.test.ts
test/integrations/component.test.ts
test/integrations/destinations/webhook/router/data.ts
Updated tests to reflect changes in the codebase, including new plugin destination handling and data structure modifications.

Assessment against linked issues

Objective Addressed Explanation
Checking in latest GATransform artifacts under dipanjan branch of rudder-transformer repository (#1) The summary does not explicitly mention GATransform artifacts, so it's unclear if these specific changes are included.

Poem

In the code where logic weaves, 🐇💻
A rabbit hops with brand new leaves. 🍃
Plugins here and adapters there,
Transforming data with utmost care. 🌟

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>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 7

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9eda50e and c331a8e.
Files ignored due to filter (4)
  • package-lock.json
  • package.json
  • src/cdk/v2/destinations/webhook/rtWorkflow.yaml
  • test/tests/data/webhook_router_output.json
Files selected for processing (12)
  • src/helpers/pluginAdapter.ts (1 hunks)
  • src/helpers/serviceSelector.ts (4 hunks)
  • src/routes/utils/constants.js (1 hunks)
  • src/services/comparator.ts (2 hunks)
  • src/services/destination/pluginIntegration.ts (1 hunks)
  • src/services/destination/postTransformation.ts (2 hunks)
  • src/services/misc.ts (1 hunks)
  • src/services/userTransform.ts (1 hunks)
  • src/types/index.ts (7 hunks)
  • test/controllerUtility/ctrl-utility.test.ts (22 hunks)
  • test/integrations/component.test.ts (5 hunks)
  • test/integrations/destinations/webhook/router/data.ts (5 hunks)
Additional comments: 31
src/helpers/pluginAdapter.ts (1)
  • 26-251: Overall, the PluginAdapter class is well-structured and follows good practices for asynchronous operations, error handling, and data transformation. The methods transformAtProcessor and transformAtRouter are designed to handle plugin integrations effectively. Ensure that the TODO regarding dynamic integration config is addressed in the future.
src/helpers/serviceSelector.ts (5)
  • 8-11: The import of PluginIntegrationService and the addition of PLUGIN_DEST in the ServiceSelector class align with the summary and the pull request's intent to introduce a new plugin integration service.

  • 33-35: The new method isPluginDestination correctly checks for the plugin destination using the destinationDefinitionConfig object. Ensure that the isPlugin property is always present in the destinationDefinitionConfig object for plugin destinations.

  • 78-80: The logic to handle plugin destinations in getPrimaryDestinationService is correctly implemented, ensuring that the PluginIntegrationService is returned when the destination is a plugin.

  • 74-85: The getPrimaryDestinationService method has been updated to handle the new plugin destination type. Ensure that the rest of the service selection logic remains compatible with this change.

  • 74-85: The getSourceService method is not implemented and currently contains a placeholder comment. Verify if this is intentional and if there are plans to implement this method in the future.

src/routes/utils/constants.js (2)
  • 9-9: The addition of PLUGIN_DEST to the INTEGRATION_SERVICE object aligns with the pull request's intent to introduce a new plugin integration framework.

  • 10-13: The correction of the syntax error in the CHANNELS object by adding the missing closing brace ensures the integrity of the object definition.

src/services/comparator.ts (1)
  • 2-2: The import of Destination is correctly added and used in the getTestThreshold function.
src/services/destination/pluginIntegration.ts (3)
  • 20-20: Verify if the init method is intentionally left empty or if initialization logic is missing.

  • 115-138: Ensure that the placeholder methods doBatchTransformation, deliver, and processUserDeletion are implemented before the service goes into production.

  • 122-122: Verify the error messages in TransformationError for consistency and correct references. 'CDKV1' and 'CDV1' might be typos or incorrect version references.

Also applies to: 130-130, 137-137

src/services/destination/postTransformation.ts (1)
  • 73-80: The logic to convert userId to a string for both single and array instances of batchedRequest is correctly implemented.
src/services/misc.ts (1)
  • 5-5: The import of Metadata from @rudderstack/integrations-lib should be verified to ensure that the properties accessed in getMetaTags are present and compatible with the new Metadata type.
src/types/index.ts (5)
  • 1-4: The changes to the import statements align with the summary provided, and the renaming of Metadata to TransformedOutput is reflected in the code.

  • 20-26: The usage of Metadata type in ProcessorTransformationOutput and MessageIdMetadataMap is consistent with the import changes and renaming.

  • 61-74: The optional fields error and statTags in ProcessorTransformationResponse and RouterTransformationResponse types are correctly updated as per the summary.

  • 82-87: The SourceTransformationResponse type has been correctly updated to make outputToSource and statTags fields optional.

  • 228-229: The export of the TransformedOutput type is present and correct as per the summary.

test/controllerUtility/ctrl-utility.test.ts (1)
  • 71-74: The addition of the IsProcessorEnabled property to the destination object in the test cases is consistent with the changes described in the summary. Ensure that the corresponding code that processes these test cases is updated to handle this new property correctly.

Also applies to: 136-139, 205-208, 270-273, 339-342, 404-407, 475-478, 538-541, 601-604, 664-667, 731-734, 794-797, 857-860, 920-923, 992-995, 1055-1058, 1121-1124, 1187-1190, 1255-1258, 1318-1321, 1384-1387, 1450-1453

test/integrations/component.test.ts (5)
  • 24-25: The import set from @rudderstack/integrations-lib is not directly used in the provided code. If it's not used elsewhere in the file, consider removing it to keep the code clean.

  • 55-55: The pluginDestinations array is used to determine if a destination is a plugin. Ensure that this array is kept up-to-date as new plugin destinations are added.

  • 84-90: The registerAxiosMocks function has been correctly updated to accept an additional mockAxiosAdapter parameter and is used to register mocks for both axios instances.

  • 108-122: The updateTCDataForPluginDests function is correctly implemented to update the test case data for plugin destinations. Ensure that the path used in the set function matches the structure of the event objects.

  • 160-164: The destinationTestHandler function correctly checks if the destination is a plugin and updates the test case data accordingly. This is a good use of conditional logic to handle different types of destinations.

test/integrations/destinations/webhook/router/data.ts (6)
  • 107-107: The webhookUrl has been changed to use HTTP. Verify that this change does not introduce security vulnerabilities, especially if sensitive data is being transmitted.

  • 117-117: The headers array includes additional key-value pairs. Ensure that these new headers are expected and properly documented.

  • 254-254: The batchedRequest field has been transformed from an object to an array of objects. Confirm that all consuming code has been updated to handle this new structure.

  • 369-369: The batched field has been updated to true. This change should be consistent with the updated batchedRequest structure.

  • 370-370: The statusCode field has been updated to 200. Ensure that this status code is appropriate for all responses expected from the webhook.

  • 120-122: A new DestinationDefinition object with a cdkV2Enabled property set to true has been added. Verify that this new configuration is supported and properly handled in the destination's implementation.

@@ -47,7 +47,7 @@ export class UserTransformService {
}
const responses = await Promise.all<FixMe>(
Object.entries(groupedEvents).map(async ([, destEvents]) => {
const eventsToProcess = destEvents as ProcessorTransformationRequest[];
const eventsToProcess = destEvents as any[];
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 28, 2023

Choose a reason for hiding this comment

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

The type assertion for eventsToProcess has been changed to any[], which removes the type safety provided by ProcessorTransformationRequest[]. Consider reverting this change or implementing a type guard to ensure the elements of eventsToProcess conform to the expected structure at runtime.

- const eventsToProcess = destEvents as any[];
+ const eventsToProcess = destEvents as ProcessorTransformationRequest[];

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.

Suggested change
const eventsToProcess = destEvents as any[];
const eventsToProcess = destEvents as ProcessorTransformationRequest[];

Copy link
Member Author

Choose a reason for hiding this comment

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

Ignore it

Copy link
Contributor

Choose a reason for hiding this comment

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

@utsabc Understood, I'll make a note of this. If you encounter any issues related to this in the future or decide to enforce type safety, please feel free to revisit it.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines +71 to 81
const resultantPayloads: RouterTransformationResponse[] = transformedPayloads;
resultantPayloads.forEach((resultantPayload) => {
if (resultantPayload.batchedRequest && resultantPayload.batchedRequest.userId) {
if (Array.isArray(resultantPayload.batchedRequest)) {
resultantPayload.batchedRequest.forEach((batchedRequest) => {
if (batchedRequest.userId) {
batchedRequest.userId = `${batchedRequest.userId}`;
}
});
} else if (resultantPayload.batchedRequest && resultantPayload.batchedRequest.userId) {
resultantPayload.batchedRequest.userId = `${resultantPayload.batchedRequest.userId}`;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The change from using cloneDeep to direct assignment in handleRouterTransformSuccessEvents could lead to potential mutability issues if the original transformedPayloads object is expected to remain unchanged. Verify if this change in behavior is intentional and ensure that no side effects will occur due to this modification.

Comment on lines 63 to 66
const config = destination.DestinationDefinition?.Config as {
camparisonTestThreshold?: number;
};
return config?.camparisonTestThreshold || 0;
Copy link
Contributor

Choose a reason for hiding this comment

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

There is a typo in the property name camparisonTestThreshold. It should be corrected to comparisonTestThreshold.

-      camparisonTestThreshold?: number;
+      comparisonTestThreshold?: number;

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.

Suggested change
const config = destination.DestinationDefinition?.Config as {
camparisonTestThreshold?: number;
};
return config?.camparisonTestThreshold || 0;
const config = destination.DestinationDefinition?.Config as {
comparisonTestThreshold?: number;
};
return config?.comparisonTestThreshold || 0;

src/services/destination/pluginIntegration.ts Show resolved Hide resolved
Comment on lines +46 to +82
public async doProcessorTransformation(
events: ProcessorTransformationRequest[],
destinationType: string,
_version: string,
_requestMetadata: unknown,
): Promise<ProcessorTransformationResponse[]> {
const results = await PluginAdapter.transformAtProcessor(events, destinationType);
const respList: ProcessorTransformationResponse[] = [];
results.allSuccessList.forEach((successResponse) => {
respList.push({
output: successResponse.payload,
metadata: successResponse.metadata,
statusCode: 200,
});
});

results.allErrorList.forEach(
(errorResponse: {
metadata: Metadata;
response: {
// need to build type def here
message: string;
status: number;
destinationResponse?: any;
statTags?: { [x: string]: string };
};
}) => {
respList.push({
metadata: errorResponse.metadata,
statusCode: errorResponse.response.status,
error: errorResponse.response.message,
statTags: errorResponse.response.statTags,
});
},
);
return respList;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider refactoring the doProcessorTransformation and doRouterTransformation methods to reduce code duplication, if the logic remains similar.

src/helpers/pluginAdapter.ts Show resolved Hide resolved
Comment on lines 37 to 43
// TODO: default integration config need to make it dynamic by making some sort of config call or get it from config file
// const integrationConfig: IntegrationConfig = {
// name: integrationName,
// saveResponse: true,
// eventOrdering: true,
// plugins: ['preprocessor', 'multiplexer'],
// };
Copy link
Contributor

Choose a reason for hiding this comment

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

There is a TODO comment regarding making the integration config dynamic. This should be prioritized to ensure that the integration configuration can be retrieved from a configuration file or service, rather than being hardcoded or left as a placeholder.

@koladilip
Copy link
Contributor

can you split this into multiple PRs for easy review

@utsabc utsabc requested a review from a team as a code owner January 16, 2024 17:12
Copy link

Quality Gate Passed Quality Gate passed

Kudos, no new issues were introduced!

0 New issues
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

@devops-github-rudderstack
Copy link
Contributor

This PR is considered to be stale. It has been open for 20 days with no further activity thus it is going to be closed in 7 days. To avoid such a case please consider removing the stale label manually or add a comment to the PR.

@devops-github-rudderstack
Copy link
Contributor

This PR is considered to be stale. It has been open for 20 days with no further activity thus it is going to be closed in 7 days. To avoid such a case please consider removing the stale label manually or add a comment to the PR.

@devops-github-rudderstack
Copy link
Contributor

This PR is considered to be stale. It has been open for 20 days with no further activity thus it is going to be closed in 7 days. To avoid such a case please consider removing the stale label manually or add a comment to the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants