Create a comprehensive implementation guide for adding the routing rule evaluation endpoint that calls the decision engine with API key authentication. The guide should include:
The exact changes needed to be made to the codebase
The specific file paths and functions to modify
The expected behavior and request/response format
How the API authentication works with ApiKeyAuth
How to properly call the decision engine functions
This is for a developer to implement the feature described in the task.
Assistant
I'll create a comprehensive implementation guide for adding the routing rule evaluation endpoint that calls the decision engine with API key authentication. Let me first explore the codebase to understand the current structure and identify the files we need to modify.
Assistant
Let me search for routing/routing related files and decision engine implementations:
Assistant
Now let's look for decision engine related files:
Assistant
Let me search more broadly for decision related code:
Assistant
Let me look for authentication and API key related files:
Assistant
Let me check the API keys implementation:
Assistant
Let me check the authentication module:
Assistant
(no content)
Assistant
Let me check the routing module:
Assistant
Let me look at the routing core functionality to understand how routing decisions are made:
Assistant
Let me check the routing types to understand the API structure:
Assistant
Let me also check how authentication and API keys work in the router by examining the authentication service:
Assistant
Let me check how the decision engine integration works by searching for references to it:
Assistant
Let me check how routing rule evaluation is typically handled in payments:
Assistant
Let me search for the specific functions for calling the decision engine:
Assistant
Let me check the utility file for routing functions:
Assistant
Now I need to understand how API authentication works. Let me check for the API keys implementation and the routing API routes:
Assistant
(no content)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This document provides a comprehensive guide for implementing a routing rule evaluation endpoint that integrates with the decision engine using API key authentication. The endpoint will allow external systems to submit routing rules and receive evaluated connector recommendations based on the decision engine's logic.
Key Components and Architecture
1. Endpoint Design
The implementation will create a new endpoint that:
Accepts routing evaluation requests
Authenticates using API keys
Calls the decision engine to evaluate routing rules
Returns appropriate responses with evaluated connectors
2. API Key Authentication System
The system uses API keys for authentication with the following components:
Authentication Flow:
API keys are stored in the database with associated merchant accounts
Each API key has permissions tied to specific merchant contexts
Requests include the API key in the header (typically api-key or Authorization header)
The authentication middleware validates the key against the database
Key Files Involved:
crates/router/src/core/api_keys.rs - API key management
Implement the core routing evaluation function in the routing module:
rust
// crates/router/src/core/routing.rs
use crate::{
core::errors::RouterResult,
routes::SessionState,
types::domain,
services::api as service_api,
};
pub async fn evaluate_routing_rule(
state: SessionState,
merchant_context: domain::MerchantContext,
request: api_models::routing::RoutingRuleEvaluationRequest,
) -> RouterResult<api_models::routing::RoutingRuleEvaluationResponse> {
// Validate request parameters if needed
// Get merchant ID from context
let merchant_id = merchant_context.get_merchant_account().get_id();
// Convert request to decision engine format
let de_request = convert_routing_request_to_decision_engine_format(request)?;
// Call decision engine for evaluation
let events_wrapper = create_routing_events_wrapper(
&state,
merchant_context.get_merchant_account().get_id(),
&merchant_context.get_merchant_key_store().get_id(),
"routing_rule_evaluation".to_string(),
)?;
let response = perform_decision_euclid_routing(
&state,
de_request,
events_wrapper,
vec![], // fallback_output - you might want to provide a default
).await?;
// Convert back to API response format
let api_response = convert_decision_engine_response_to_api_format(response)?;
Ok(api_response)
}
// Helper function to create events wrapper for routing operations
async fn create_routing_events_wrapper(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
key_store: &common_utils::id_type::KeyId,
flow: String,
) -> RouterResult<utils::RoutingEventsWrapper<RoutingEvaluateRequest>> {
let request_id = state.request_id.clone();
let payment_id = "routing-eval".to_string(); // Or generate from context
let profile_id = common_utils::id_type::ProfileId::from("default-profile"); // Or derive from context
Ok(utils::RoutingEventsWrapper::new(
key_store.get_tenant_id().clone(),
request_id,
payment_id,
profile_id,
merchant_id.clone(),
flow,
None::<RoutingEvaluateRequest>,
true,
true,
))
}
The implementation uses ApiKeyAuth as specified in the requirements:
rust
// In the authentication layer
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
)
Key Features of Authentication:
API Key Validation: Checks if the provided API key exists and is valid
Merchant Context Association: Links API key to merchant account for proper access control
Permission Checking: Ensures the key has appropriate permissions for the operation
Header-Based Authentication: Expects API key in HTTP headers
How API Keys Work:
API keys are stored in the database with associated merchant IDs
When a request comes in, the authentication middleware extracts the API key from headers
It verifies the key against stored keys in the database
It checks if the key belongs to the merchant account requesting the resource
Permissions are checked to ensure the merchant has appropriate access rights
How to Properly Call the Decision Engine Functions
1. Using Existing Utility Functions
The implementation leverages existing utilities for decision engine communication:
rust
// In the routing core module
let events_wrapper = create_routing_events_wrapper(&state, merchant_id, key_store, "routing_rule_evaluation".to_string())?;
let response = perform_decision_euclid_routing(
&state,
de_request,
events_wrapper,
vec![], // fallback_output
).await?;
2. Integration Points
The decision engine integration includes:
REST API Calls: Through the EuclidApiClient trait
GRPC Client: Direct communication for specific decision engine operations
Event Logging: Captures API interactions for debugging and monitoring
Error Handling: Graceful handling of timeouts and engine errors
3. Data Transformation
The system handles transformations between:
Internal Hyperswitch routing data types
Decision engine compatible data formats
API response formats
4. Security Considerations
All communications with the decision engine are authenticated
Rate limiting should be applied to prevent abuse
Logging of sensitive parameters should be restricted
Proper error responses without exposing internal information
Testing and Validation
Unit Tests Required:
API key authentication validation
Decision engine request construction
Response parsing and transformation
Error handling for various scenarios
Fallback mechanism when decision engine is unavailable
Integration Tests:
End-to-end routing rule evaluation flow
API key-based access control
Decision engine connectivity verification
Response format compliance
Deployment Considerations
Configuration Parameters:
Decision engine endpoint URL in configuration
API key validation timeout settings
Circuit breaker thresholds for decision engine failures
Event logging verbosity levels
Monitoring and Observability:
Metrics for routing evaluation success rates
Latency measurements for decision engine calls
Error rate tracking for authentication and engine failures
Resource usage monitoring for high-volume scenarios
This implementation follows the existing codebase patterns and integrates seamlessly with the current authentication and routing infrastructure. The API key authentication ensures secure access to the routing rule evaluation functionality while the decision engine integration provides sophisticated routing logic based on business rules and historical data.