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/fraud 3.1 #2681

Merged
merged 6 commits into from
Nov 15, 2024
Merged

Feat/fraud 3.1 #2681

merged 6 commits into from
Nov 15, 2024

Conversation

P3rceval
Copy link
Collaborator

@P3rceval P3rceval commented Nov 7, 2024

A merger avec le refactor sur la couche HttpTransport

Summary by CodeRabbit

  • New Features

    • Introduced API versioning support across various services and repositories, enhancing fraud detection and status handling based on the API version used.
    • Added new labels for anomalies and terms in testing, improving the specificity of test cases.
  • Bug Fixes

    • Updated logic in fraud detection methods to return appropriate labels based on API version.
  • Documentation

    • Enhanced method signatures to include context and API version parameters for better clarity and functionality.
  • Tests

    • Restructured and expanded test cases to accommodate new labels and API versioning, ensuring accurate validation of functionalities.

Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on the CarpoolStatusService and related classes. The findByOperatorJourneyId method in CarpoolStatusService now accepts an api_version parameter, which is utilized in the fraud detection logic. Corresponding changes are made in the CarpoolLabelRepository to accommodate this new parameter. Additionally, the integration tests have been updated to use more specific labels and reflect the new API versioning. Other files, such as StatusJourneyAction and status.contract.ts, have also been modified to support the new API versioning requirements.

Changes

File Change Summary
api/src/pdc/providers/carpool/providers/CarpoolStatusService.ts Updated findByOperatorJourneyId method to include api_version: string parameter; passed this parameter to findFraudByOperatorJourneyId method.
api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.ts Modified findFraudByOperatorJourneyId method to accept api_version and added conditional logic based on semantic versioning; included semver import.
api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.integration.spec.ts Introduced new label constants for anomalies, terms, and frauds; updated test cases to use these new labels and reflect API versioning.
api/src/pdc/services/acquisition/actions/StatusJourneyAction.ts Updated handle method to accept context: ContextType parameter and provided a default for context.call?.api_version_range.
api/src/shared/acquisition/status.contract.ts Added `api_version: "v3"
api/src/pdc/proxy/HttpTransport.ts Changed rpcAnswerOnSuccess property for POST method of /journeys route from false to true, indicating successful responses will now return a positive acknowledgment.

Possibly related PRs

Suggested reviewers

  • nmrgt
  • jonathanfallon

Poem

🐰 In the code where journeys flow,
New parameters help us know,
With labels bright, and tests so clear,
API versions bring us cheer!
A hop, a skip, through logic's maze,
We celebrate these code-filled days! 🌟


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.

@P3rceval P3rceval marked this pull request as ready for review November 15, 2024 11:15
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: 5

🧹 Outside diff range and nitpick comments (7)
api/src/pdc/services/acquisition/actions/StatusJourneyAction.ts (1)

Line range hint 26-45: Consider enhancing error monitoring for fraud detection

Given this is part of a fraud detection system, consider adding structured logging or monitoring for:

  • API version usage patterns
  • Fraud detection rates
  • Common error patterns

This would help track the effectiveness of different API versions and fraud detection rules.

api/src/pdc/providers/carpool/providers/CarpoolStatusService.ts (1)

Line range hint 1-71: Consider documenting API versioning strategy

The introduction of API versioning for fraud detection suggests a need for a clear versioning strategy. Consider:

  1. Documenting the differences between v3 and v3.1 fraud detection
  2. Adding migration guides for clients
  3. Planning for future version deprecation
api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.ts (1)

Line range hint 36-40: Consider improving parameter placement and type safety

  1. The api_version parameter would be more conventional as the last parameter.
  2. Consider using a more specific type or enum for api_version to prevent invalid version strings.
 async findFraudByOperatorJourneyId(
-  api_version: string,
   operator_id: number,
   operator_journey_id: string,
-  client?: PoolClient,
+  client?: PoolClient,
+  api_version: ApiVersion, // Consider creating an enum or type
 ): Promise<Array<CarpoolLabel>>
api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.integration.spec.ts (4)

14-24: LGTM! Consider grouping constants into objects for better maintainability.

The label constants are well-organized by type. To improve maintainability, consider grouping them into objects by category.

- const anomaly_label_1 = "temporal_overlap_anomaly";
- const terms_label_1 = "distance_too_short";
- const fraud_label_1_V3 = "interoperator_fraud";
- const fraud_label_1_V3_1 = "interoperator_overlap_trip";
- const fraud_label_2_V3_1 = "interoperator_too_many_trips_by_day";

+ const ANOMALY_LABELS = {
+   TEMPORAL_OVERLAP: "temporal_overlap_anomaly",
+ };
+ const TERMS_LABELS = {
+   DISTANCE_TOO_SHORT: "distance_too_short",
+ };
+ const FRAUD_LABELS = {
+   V3: {
+     INTEROPERATOR: "interoperator_fraud",
+   },
+   V3_1: {
+     OVERLAP_TRIP: "interoperator_overlap_trip",
+     TOO_MANY_TRIPS: "interoperator_too_many_trips_by_day",
+   },
+ };

28-55: Add error handling to database operations.

The helper functions are well-structured, but they should include error handling for database operations to make debugging test failures easier.

 const insertTermLabels = async (carpool_id: number) => {
+  try {
     await db.connection.getClient().query(
       sql`INSERT INTO ${raw(labelRepository.termsTable)} (carpool_id, labels) VALUES (${carpool_id}, ${[
         terms_label_1,
       ]})`,
     );
+  } catch (error) {
+    console.error(`Failed to insert terms label for carpool_id ${carpool_id}:`, error);
+    throw error;
+  }
 };

Line range hint 98-111: Remove duplicate test case for empty fraud labels.

There are two nearly identical test cases checking for empty fraud labels. Consider combining them using test parameters for different versions.

- it("Should read carpool fraud label and returns empty array if none for api v3", async () => {
-   // Arrange
-   await repository.register({ ...insertableCarpool, operator_journey_id: "operator_journey_id-4" });
-   // Act
-   const result = await labelRepository.findFraudByOperatorJourneyId(
-     "v3",
-     insertableCarpool.operator_id,
-     "operator_journey_id-4",
-   );
-   // Assert
-   assertEquals(result, []);
- });

- it("Should read carpool fraud label and returns empty array if none for api v3", async () => {
-   // Arrange
-   await repository.register({ ...insertableCarpool, operator_journey_id: "operator_journey_id-4" });
-   // Act
-   const result = await labelRepository.findFraudByOperatorJourneyId(
-     "v3.1",
-     insertableCarpool.operator_id,
-     "operator_journey_id-4",
-   );
-   // Assert
-   assertEquals(result, []);
- });

+ const versions = ["v3", "v3.1"];
+ for (const version of versions) {
+   it(`Should return empty array for non-existent fraud labels (${version})`, async () => {
+     // Arrange
+     await repository.register({ ...insertableCarpool, operator_journey_id: "operator_journey_id-4" });
+     // Act
+     const result = await labelRepository.findFraudByOperatorJourneyId(
+       version,
+       insertableCarpool.operator_id,
+       "operator_journey_id-4",
+     );
+     // Assert
+     assertEquals(result, []);
+   });
+ }

Also applies to: 137-150


114-122: Standardize API version format.

The test uses "v3.0" while other tests use "v3". Standardize the version format across all tests.

   const result = await labelRepository.findFraudByOperatorJourneyId(
-    "v3.0",
+    "v3",
     insertableCarpool.operator_id,
     insertableCarpool.operator_journey_id,
   );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1b91214 and 6159ea9.

📒 Files selected for processing (5)
  • api/src/pdc/providers/carpool/providers/CarpoolStatusService.ts (2 hunks)
  • api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.integration.spec.ts (2 hunks)
  • api/src/pdc/providers/carpool/repositories/CarpoolLabelRepository.ts (3 hunks)
  • api/src/pdc/services/acquisition/actions/StatusJourneyAction.ts (2 hunks)
  • api/src/shared/acquisition/status.contract.ts (2 hunks)
🔇 Additional comments (5)
api/src/shared/acquisition/status.contract.ts (2)

42-42: LGTM: Simple formatting improvement

The formatting change to the signature constant declaration improves readability while maintaining functionality.


4-4: Verify handling of breaking change in API contracts

The addition of a required api_version property is a breaking change that will affect all consumers of this interface. While the typing is correctly constrained to specific versions, we should ensure proper migration paths exist.

Let's verify the impact:

Consider:

  1. Adding migration documentation
  2. Implementing runtime validation to provide helpful error messages
  3. Consider making this optional with a default value to ease migration
api/src/pdc/services/acquisition/actions/StatusJourneyAction.ts (2)

1-1: LGTM: Import changes are consistent with new requirements

The addition of ContextType and updated contract imports properly support the new context-aware handler implementation.

Also applies to: 7-7


26-26: Verify handler usage across the codebase

The addition of the context parameter is a breaking change that could affect existing callers.

api/src/pdc/providers/carpool/providers/CarpoolStatusService.ts (1)

41-44: Verify integration with CarpoolLabelRepository

The api_version parameter is now used in fraud detection. Please ensure:

  1. All callers of this method are updated to provide the version
  2. The fraud detection logic in CarpoolLabelRepository correctly handles all version cases
✅ Verification successful

Let me gather more specific information about the fraud detection integration.


Based on the results, I can now provide a final response:

Integration with CarpoolLabelRepository is properly implemented

The api_version parameter is correctly integrated:

  • The method is properly implemented in CarpoolLabelRepository with version support
  • Integration tests demonstrate handling of different API versions (v3, v3.0, v3.1)
  • The fraud detection is properly scoped to the specific journey through operator_id and operator_journey_id parameters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all calls to findByOperatorJourneyId to ensure they're updated
ast-grep --pattern 'findByOperatorJourneyId($$$)'

# Verify the implementation in CarpoolLabelRepository
ast-grep --pattern 'findFraudByOperatorJourneyId(api_version: $_, $$$)'

Length of output: 5120


Script:

#!/bin/bash
# Search for the implementation and usage of findFraudByOperatorJourneyId
rg "findFraudByOperatorJourneyId" -A 5

# Find all references to CarpoolLabelRepository
rg "CarpoolLabelRepository" -A 3

# Look for status service implementations that might call this method
ast-grep --pattern 'class $_ implements CarpoolStatusInterface {
  $$$
}'

Length of output: 6864

const { operator_journey_id, operator_id } = params;
const result = await this.statusService.findByOperatorJourneyId(
operator_id,
operator_journey_id,
context.call?.api_version_range || "3.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider centralizing API version configuration

The hardcoded version string "3.1" should be moved to a central configuration. This would make version management more maintainable and reduce the risk of inconsistencies.

Consider creating a shared constants file:

// src/shared/constants/api.ts
export const API_VERSIONS = {
  DEFAULT: '3.1',
  V3: 'v3',
  V3_1: 'v3.1',
} as const;

Then update the code:

- context.call?.api_version_range || "3.1",
+ context.call?.api_version_range || API_VERSIONS.DEFAULT,

Comment on lines +124 to +135
// fraud V3.1
it("Should read carpool fraud label and returns 2 labels for api v3.1", async () => {
const result = await labelRepository.findFraudByOperatorJourneyId(
"v3.1",
insertableCarpool.operator_id,
insertableCarpool.operator_journey_id,
);
assertEquals(result, [
{ label: fraud_label_1_V3_1 },
{ label: fraud_label_2_V3_1 },
]);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add test cases for edge cases in version handling.

The tests cover happy paths but are missing important edge cases for version handling.

Consider adding test cases for:

  1. Invalid version formats
  2. Unsupported versions
  3. Case sensitivity in version strings

Example:

it("Should handle invalid version format gracefully", async () => {
  await assertRejects(
    () => labelRepository.findFraudByOperatorJourneyId(
      "invalid_version",
      insertableCarpool.operator_id,
      insertableCarpool.operator_journey_id,
    ),
    Error,
    "Invalid version format",
  );
});

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)
api/src/pdc/proxy/HttpTransport.ts (1)

Line range hint 553-556: Review rate limit configuration for security.

The current rate limit of 20,000 requests per minute for the journey creation endpoint seems high, especially for a fraud-sensitive endpoint. Consider:

  1. Reducing the limit to a more conservative value
  2. Implementing additional fraud prevention measures like IP-based rate limiting
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6159ea9 and 552535f.

📒 Files selected for processing (1)
  • api/src/pdc/proxy/HttpTransport.ts (1 hunks)
🔇 Additional comments (1)
api/src/pdc/proxy/HttpTransport.ts (1)

557-557: Verify client compatibility with the updated response format.

The change to rpcAnswerOnSuccess: true aligns with other routes in the acquisition group and improves consistency. However, this change will affect how successful responses are formatted, which may impact existing clients.

Let's verify the consistency of this change with other acquisition routes:

✅ Verification successful

Change is consistent with other acquisition routes

The verification confirms that the rpcAnswerOnSuccess: true setting is consistent with other acquisition routes in the codebase. Specifically:

  • The /journeys/:operator_journey_id/cancel POST route uses rpcAnswerOnSuccess: true
  • The /journeys POST route (the one being modified) now matches this pattern

This standardization of response formats within the acquisition routes group is a positive change that maintains API consistency.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check response format configuration across acquisition routes
# Expected: Most acquisition routes should use rpcAnswerOnSuccess: true

# Search for all acquisition route configurations
rg -B 5 -A 5 'acquisition:[a-z]+.+method: .POST.' 

Length of output: 51


Script:

#!/bin/bash
# Let's try a different approach to find acquisition-related routes
# Search for registerAcquisitionRoutes method and its context
rg -B 10 -A 20 "registerAcquisitionRoutes"

Length of output: 3953


Script:

#!/bin/bash
# Let's search for all route registrations in the HttpTransport class
# specifically looking for POST methods and their rpcAnswerOnSuccess configuration
rg -B 5 -A 10 'method: "POST",' api/src/pdc/proxy/HttpTransport.ts

Length of output: 3810

@P3rceval P3rceval merged commit dc6c226 into main Nov 15, 2024
8 checks passed
@P3rceval P3rceval deleted the feat/fraud_3.1 branch November 15, 2024 11:35
P3rceval added a commit that referenced this pull request Nov 15, 2024
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.

1 participant